5 # - gpgm with a status FD being fed keymaterial and other interesting
6 # things does nothing.. If it could ID the keys and stuff over the
7 # status-fd I could decide what to do with them. I would also like it
8 # to report which key it selected for encryption (also if there
9 # were multi-matches..) Being able to detect a key-revoke cert would be
11 # - I would like to be able to fetch the comment and version fields from the
12 # packets so I can tell if a signature is made by pgp2 to enable the
13 # pgp2 encrypting mode.
15 import string, mimetools, multifile, sys, StringIO, os, tempfile, re;
16 import rfc822, time, fcntl, FCNTL, anydbm
20 GPGBasicOptions = ["--no-options","--batch","--load-extension","rsa",\
21 "--no-default-keyring","--always-trust"];
23 GPGSigOptions = ["--output","-"];
24 GPGSearchOptions = ["--dry-run","--with-colons","--fingerprint"];
25 GPGEncryptOptions = ["--output","-","--quiet","--always-trust",\
26 "--armor","--encrypt"];
27 GPGEncryptPGP2Options = ["--set-filename","","--rfc1991",\
28 "--load-extension","idea",\
29 "--cipher-algo","idea"] + GPGEncryptOptions;
31 # Replay cutoff times in seconds
32 CleanCutOff = 7*24*60*60;
33 AgeCutOff = 4*24*60*60;
34 FutureCutOff = 3*24*60*60;
36 # Set the keyrings, the input is a list of keyrings
37 def SetKeyrings(Rings):
39 GPGKeyRings.append("--keyring");
40 GPGKeyRings.append(x);
42 # GetClearSig takes an un-seekable email message stream (mimetools.Message)
43 # and returns a standard PGP '---BEGIN PGP SIGNED MESSAGE---' bounded
45 # If this is fed to gpg/pgp it will verify the signature and spit out the
46 # signed text component. Email headers and PGP mime (RFC 2015) is understood
47 # but no effort is made to cull any information outside the PGP boundaries
48 # Please note that in the event of a mime decode the mime headers will be
49 # present in the signature text! The return result is a tuple, the first
50 # element is the text itself the second is a mime flag indicating if the
51 # result should be mime processed after sig checking.
54 # See if this is a MIME encoded multipart signed message
55 if Msg.gettype() == "multipart/signed":
56 Boundary = Msg.getparam("boundary");
58 raise Error, "multipart/* without a boundary parameter";
60 # Create the multipart handler. Regrettably their implementation
62 SkMessage = StringIO.StringIO();
63 SkMessage.write(Msg.fp.read());
65 mf = multifile.MultiFile(SkMessage)
66 mf.push(Msg.getparam("boundary"));
68 # Get the first part of the multipart message
70 raise Error, "Invalid pgp/mime encoding [no section]";
72 # Get the part as a safe seekable stream
73 Signed = StringIO.StringIO();
74 Signed.write(mf.read());
75 InnerMsg = mimetools.Message(Signed);
77 # Make sure it is the right type
78 if InnerMsg.gettype() != "text/plain":
79 raise Error, "Invalid pgp/mime encoding [wrong plaintext type]";
81 # Get the next part of the multipart message
83 raise Error, "Invalid pgp/mime encoding [no section]";
84 InnerMsg = mimetools.Message(mf);
85 if InnerMsg.gettype() != "application/pgp-signature":
86 raise Error, "Invalid pgp/mime encoding [wrong signature type]";
87 Signature = string.joinfields(mf.readlines(),'');
89 # Append the PGP boundary header and the signature text to re-form the
90 # original signed block [needs to convert to \r\n]
91 Output = "-----BEGIN PGP SIGNED MESSAGE-----\r\n";
92 # Semi-evil hack to get the proper hash type inserted in the message
93 if Msg.getparam('micalg') != None:
94 Output = Output + "Hash: %s\r\n"%(string.upper(Msg.getparam('micalg')[4:]));
95 Output = Output + "\r\n";
96 Output = Output + string.replace(Signed.getvalue(),"\n---","\n- ---") + Signature;
99 # Just return the message body
100 return (string.joinfields(Msg.fp.readlines(),''),0);
102 # This opens GPG in 'write filter' mode. It takes Message and sends it
103 # to GPGs standard input, pipes the standard output to a temp file along
104 # with the status FD. The two tempfiles are passed to GPG by fd and are
105 # accessible from the filesystem for only a short period. Message may be
106 # None in which case GPGs stdin is closed directly after forking. This
107 # is best used for sig checking and encryption.
108 # The return result is a tuple (Exit,StatusFD,OutputFD), both fds are
109 # fully rewound and readable.
110 def GPGWriteFilter(Program,Options,Message):
111 # Make sure the tmp files we open are unreadable, there is a short race
112 # between when the temp file is opened and unlinked that some one else
113 # could open it or hard link it. This is not important however as no
114 # Secure data is fed through the temp files.
115 OldMask = os.umask(0777);
117 Output = tempfile.TemporaryFile("w+b");
118 GPGText = tempfile.TemporaryFile("w+b");
120 InPipe = [InPipe[0],InPipe[1]];
125 # Fork off GPG in a horrible way, we redirect most of its FDs
126 # Input comes from a pipe and its two outputs are spooled to unlinked
127 # temp files (ie private)
131 os.dup2(InPipe[0],0);
133 os.dup2(Output.fileno(),1);
134 os.dup2(os.open("/dev/null",os.O_WRONLY),2);
135 os.dup2(GPGText.fileno(),3);
137 Args = [Program,"--status-fd","3"] + GPGBasicOptions + GPGKeyRings + Options
138 os.execvp(Program,Args);
142 # Get rid of the other end of the pipe
149 os.write(InPipe[1],Message);
155 # Wait for GPG to finish
156 Exit = os.waitpid(Child,0);
158 # Create the result including the new readable file descriptors
159 Result = (Exit,os.fdopen(os.dup(GPGText.fileno()),"r"), \
160 os.fdopen(os.dup(Output.fileno()),"r"));
175 # This takes a text passage, a destination and a flag indicating the
176 # compatibility to use and returns an encrypted message to the recipient.
177 # It is best if the recipient is specified using the hex key fingerprint
178 # of the target, ie 0x64BE1319CCF6D393BF87FF9358A6D4EE
179 def GPGEncrypt(Message,To,PGP2):
180 # Encrypt using the PGP5 block encoding and with the PGP5 option set.
181 # This will handle either RSA or DSA/DH asymetric keys.
182 # In PGP2 compatible mode IDEA and rfc1991 encoding are used so that
183 # PGP2 can read the result. RSA keys do not need PGP2 to be set, as GPG
184 # can read a message encrypted with blowfish and RSA.
188 Res = GPGWriteFilter(GPGPath,["-r",To]+GPGEncryptOptions,Message);
191 Text = Res[2].read();
198 # We have to call gpg with a filename or it will create a packet that
199 # PGP2 cannot understand.
200 TmpName = tempfile.mktemp();
203 MsgFile = open(TmpName,"wc");
204 MsgFile.write(Message);
206 Res = GPGWriteFilter(GPGPath,["-r",To]+GPGEncryptPGP2Options+[TmpName],None);
209 Text = Res[2].read();
220 # Checks the signature of a standard PGP message, like that returned by
221 # GetClearSig. It returns a large tuple of the form:
222 # (Why,(SigId,Date,KeyFinger),(KeyID,KeyFinger,Owner,Length,PGP2),Text);
224 # Why = None if checking was OK otherwise an error string.
225 # SigID+Date represent something suitable for use in a replay cache. The
226 # date is returned as the number of seconds since the UTC epoch.
227 # The keyID is also in this tuple for easy use of the replay
229 # KeyID, KeyFinger and Owner represent the Key used to sign this message
230 # PGP2 indicates if the message was created using PGP 2.x
231 # Text is the full byte-for-byte signed text in a string
232 def GPGCheckSig(Message):
235 Res = GPGWriteFilter(GPGPath,GPGSigOptions,Message);
238 # Parse the GPG answer
249 # Grab and split up line
250 Line = Strm.readline();
253 Split = re.split("[ \n]",Line);
254 if Split[0] != "[GNUPG:]":
257 # We only process the first occurance of any tag.
258 if TagMap.has_key(Split[1]):
260 TagMap[Split[1]] = None;
262 # Good signature response
263 if Split[1] == "GOODSIG":
264 # Just in case GPG returned a bad signal before this (bug?)
268 Owner = string.join(Split[3:],' ');
270 # Bad signature response
271 if Split[1] == "BADSIG":
274 Why = "Verification of signature failed";
276 # Bad signature response
277 if Split[1] == "ERRSIG":
281 Why = "GPG error, ERRSIG status tag is invalid";
282 elif Split[7] == '9':
283 Why = "Unable to verify signature, signing key missing.";
284 elif Split[7] == '4':
285 Why = "Unable to verify signature, unknown packet format/key type";
287 Why = "Unable to verify signature, unknown reason";
289 if Split[1] == "NO_PUBKEY":
291 Why = "Unable to verify signature, signing key missing.";
294 if Split[1] == "SIGEXPIRED":
296 Why = "Signature has expired";
299 if Split[1] == "KEYREVOKED":
301 Why = "Signing key has been revoked";
304 if Split[1] == "NODATA" or Split[1] == "BADARMOR":
306 Why = "The packet was corrupted or contained no data";
309 if Split[1] == "SIG_ID":
311 Date = long(Split[4]);
313 # ValidSig has the key finger print
314 if Split[1] == "VALIDSIG":
315 KeyFinger = Split[2];
317 # Reopen the stream as a readable stream
318 Text = Res[2].read();
320 # A gpg failure is an automatic bad signature
321 if Exit[1] != 0 and Why == None:
323 Why = "GPG execution failed " + str(Exit[0]);
325 if GoodSig == 0 and (Why == None or len(Why) == 0):
326 Why = "Checking Failed";
328 # Try to decide if this message was sent using PGP2
330 if (re.search("-----[\n\r][\n\r]?Version: 2\\.",Message) != None):
333 return (Why,(SigId,Date,KeyFinger),(KeyID,KeyFinger,Owner,0,PGP2Message),Text);
339 # Search for keys given a search pattern. The pattern is passed directly
340 # to GPG for processing. The result is a list of tuples of the form:
341 # (KeyID,KeyFinger,Owner,Length)
342 # Which is similar to the key identification tuple output by GPGChecksig
343 def GPGKeySearch(SearchCriteria):
344 Args = [GPGPath] + GPGBasicOptions + GPGKeyRings + GPGSearchOptions + \
345 [SearchCriteria," 2> /dev/null"]
352 Strm = os.popen(string.join(Args," "),"r");
355 # Grab and split up line
356 Line = Strm.readline();
359 Split = string.split(Line,":");
361 # Store some of the key fields
362 if Split[0] == 'pub':
365 Length = int(Split[2]);
368 if Split[0] == 'fpr':
369 if Hits.has_key(Split[9]):
371 Hits[Split[9]] = None;
372 Result.append( (KeyID,Split[9],Owner,Length) );
378 # Print the available key information in a format similar to GPG's output
379 # We do not know the values of all the feilds so they are just replaced
381 def GPGPrintKeyInfo(Ident):
382 print "pub %u?/%s ??-??-?? %s" % (Ident[3],Ident[0][-8:],Ident[2]);
383 print " key fingerprint = 0x%s" % (Ident[1]);
385 # Perform a substition of template
386 def TemplateSubst(Map,Template):
388 Template = string.replace(Template,x,Map[x]);
391 # The replay class uses a python DB (BSD db if avail) to implement
392 # protection against replay. Replay is an attacker capturing the
393 # plain text signed message and sending it back to the victim at some
394 # later date. Each signature has a unique signature ID (and signing
395 # Key Fingerprint) as well as a timestamp. The first stage of replay
396 # protection is to ensure that the timestamp is reasonable, in particular
397 # not to far ahead or too far behind the current system time. The next
398 # step is to look up the signature + key fingerprint in the replay database
399 # and determine if it has been recived. The database is cleaned out
400 # periodically and old signatures are discarded. By using a timestamp the
401 # database size is bounded to being within the range of the allowed times
402 # plus a little fuzz. The cache is serialized with a flocked lock file
404 def __init__(self,Database):
405 self.Lock = open(Database + ".lock","w",0600);
406 fcntl.flock(self.Lock.fileno(),FCNTL.LOCK_EX);
407 self.DB = anydbm.open(Database,"c",0600);
408 self.CleanCutOff = CleanCutOff;
409 self.AgeCutOff = AgeCutOff;
410 self.FutureCutOff = FutureCutOff;
412 # Close the cache and lock
419 # Clean out any old signatures
421 CutOff = time.time() - self.CleanCutOff;
422 for x in self.DB.keys():
423 if int(self.DB[x]) <= CutOff:
426 # Check a signature. 'sig' is a 3 tuple that has the sigId, date and
429 if Sig[0] == None or Sig[1] == None or Sig[2] == None:
430 return "Invalid signature";
431 if int(Sig[1]) > time.time() + self.FutureCutOff:
432 return "Signature has a time too far in the future";
433 if self.DB.has_key(Sig[0] + '-' + Sig[2]):
434 return "Signature has already been received";
435 if int(Sig[1]) < time.time() - self.AgeCutOff:
436 return "Signature has passed the age cut off ";
437 # + str(int(Sig[1])) + ',' + str(time.time()) + "," + str(Sig);
440 # Add a signature, the sig is the same as is given to Check
442 if Sig[0] == None or Sig[1] == None:
443 raise RuntimeError,"Invalid signature";
444 if Sig[1] < time.time() - self.CleanCutOff:
446 Key = Sig[0] + '-' + Sig[2]
447 if self.DB.has_key(Key):
448 if int(self.DB[Key]) < Sig[1]:
449 self.DB[Key] = str(int(Sig[1]));
451 self.DB[Key] = str(int(Sig[1]));