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"];
22 GPGKeyRings = ["--keyring","/usr/share/keyrings/debian-keyring.pgp",\
23 "--keyring","/usr/share/keyrings/debian-keyring.gpg"];
24 GPGSigOptions = ["--output","-"];
25 GPGSearchOptions = ["--dry-run","--with-colons","--fingerprint"];
26 GPGEncryptOptions = ["--output","-","--quiet","--always-trust",\
27 "--armor","--encrypt"];
28 GPGEncryptPGP2Options = ["--set-filename","","--rfc1991",\
29 "--load-extension","idea",\
30 "--cipher-algo","idea"] + GPGEncryptOptions;
32 # Replay cutoff times in seconds
33 CleanCutOff = 7*24*60*60;
34 AgeCutOff = 4*24*60*60;
35 FutureCutOff = 3*24*60*60;
37 # GetClearSig takes an un-seekable email message stream (mimetools.Message)
38 # and returns a standard PGP '---BEGIN PGP SIGNED MESSAGE---' bounded
40 # If this is fed to gpg/pgp it will verify the signature and spit out the
41 # signed text component. Email headers and PGP mime (RFC 2015) is understood
42 # but no effort is made to cull any information outside the PGP boundaries
43 # Please note that in the event of a mime decode the mime headers will be
44 # present in the signature text! The return result is a tuple, the first
45 # element is the text itself the second is a mime flag indicating if the
46 # result should be mime processed after sig checking.
49 # See if this is a MIME encoded multipart signed message
50 if Msg.gettype() == "multipart/signed":
51 Boundary = Msg.getparam("boundary");
53 raise Error, "multipart/* without a boundary parameter";
55 # Create the multipart handler. Regrettably their implementation
57 SkMessage = StringIO.StringIO();
58 SkMessage.write(Msg.fp.read());
60 mf = multifile.MultiFile(SkMessage)
61 mf.push(Msg.getparam("boundary"));
63 # Get the first part of the multipart message
65 raise Error, "Invalid pgp/mime encoding [no section]";
67 # Get the part as a safe seekable stream
68 Signed = StringIO.StringIO();
69 Signed.write(mf.read());
70 InnerMsg = mimetools.Message(Signed);
72 # Make sure it is the right type
73 if InnerMsg.gettype() != "text/plain":
74 raise Error, "Invalid pgp/mime encoding [wrong plaintext type]";
76 # Get the next part of the multipart message
78 raise Error, "Invalid pgp/mime encoding [no section]";
79 InnerMsg = mimetools.Message(mf);
80 if InnerMsg.gettype() != "application/pgp-signature":
81 raise Error, "Invalid pgp/mime encoding [wrong signature type]";
82 Signature = string.joinfields(mf.readlines(),'');
84 # Append the PGP boundary header and the signature text to re-form the
85 # original signed block [needs to convert to \r\n]
86 Output = "-----BEGIN PGP SIGNED MESSAGE-----\r\n\r\n" + Signed.getvalue() + Signature;
89 # Just return the message body
90 return (string.joinfields(Msg.fp.readlines(),''),0);
92 # This opens GPG in 'write filter' mode. It takes Message and sends it
93 # to GPGs standard input, pipes the standard output to a temp file along
94 # with the status FD. The two tempfiles are passed to GPG by fd and are
95 # accessible from the filesystem for only a short period. Message may be
96 # None in which case GPGs stdin is closed directly after forking. This
97 # is best used for sig checking and encryption.
98 # The return result is a tuple (Exit,StatusFD,OutputFD), both fds are
99 # fully rewound and readable.
100 def GPGWriteFilter(Program,Options,Message):
101 # Make sure the tmp files we open are unreadable, there is a short race
102 # between when the temp file is opened and unlinked that some one else
103 # could open it or hard link it. This is not important however as no
104 # Secure data is fed through the temp files.
105 OldMask = os.umask(0777);
107 Output = tempfile.TemporaryFile("w+b");
108 GPGText = tempfile.TemporaryFile("w+b");
110 InPipe = [InPipe[0],InPipe[1]];
115 # Fork off GPG in a horrible way, we redirect most of its FDs
116 # Input comes from a pipe and its two outputs are spooled to unlinked
117 # temp files (ie private)
121 os.dup2(InPipe[0],0);
123 os.dup2(Output.fileno(),1);
124 os.dup2(os.open("/dev/null",os.O_WRONLY),2);
125 os.dup2(GPGText.fileno(),3);
127 Args = [Program,"--status-fd","3"] + GPGBasicOptions + GPGKeyRings + Options
128 os.execvp(Program,Args);
132 # Get rid of the other end of the pipe
139 os.write(InPipe[1],Message);
145 # Wait for GPG to finish
146 Exit = os.waitpid(Child,0);
148 # Create the result including the new readable file descriptors
149 Result = (Exit,os.fdopen(os.dup(GPGText.fileno()),"r"), \
150 os.fdopen(os.dup(Output.fileno()),"r"));
165 # This takes a text passage, a destination and a flag indicating the
166 # compatibility to use and returns an encrypted message to the recipient.
167 # It is best if the recipient is specified using the hex key fingerprint
168 # of the target, ie 0x64BE1319CCF6D393BF87FF9358A6D4EE
169 def GPGEncrypt(Message,To,PGP2):
170 # Encrypt using the PGP5 block encoding and with the PGP5 option set.
171 # This will handle either RSA or DSA/DH asymetric keys.
172 # In PGP2 compatible mode IDEA and rfc1991 encoding are used so that
173 # PGP2 can read the result. RSA keys do not need PGP2 to be set, as GPG
174 # can read a message encrypted with blowfish and RSA.
178 Res = GPGWriteFilter(GPGPath,["-r",To]+GPGEncryptOptions,Message);
181 Text = Res[2].read();
188 # We have to call gpg with a filename or it will create a packet that
189 # PGP2 cannot understand.
190 TmpName = tempfile.mktemp();
193 MsgFile = open(TmpName,"wc");
194 MsgFile.write(Message);
196 Res = GPGWriteFilter(GPGPath,["-r",To]+GPGEncryptPGP2Options+[TmpName],None);
199 Text = Res[2].read();
210 # Checks the signature of a standard PGP message, like that returned by
211 # GetClearSig. It returns a large tuple of the form:
212 # (Why,(SigId,Date,KeyFinger),(KeyID,KeyFinger,Owner,Length,PGP2),Text);
214 # Why = None if checking was OK otherwise an error string.
215 # SigID+Date represent something suitable for use in a replay cache. The
216 # date is returned as the number of seconds since the UTC epoch.
217 # The keyID is also in this tuple for easy use of the replay
219 # KeyID, KeyFinger and Owner represent the Key used to sign this message
220 # PGP2 indicates if the message was created using PGP 2.x
221 # Text is the full byte-for-byte signed text in a string
222 def GPGCheckSig(Message):
225 Res = GPGWriteFilter(GPGPath,GPGSigOptions,Message);
228 # Parse the GPG answer
239 # Grab and split up line
240 Line = Strm.readline();
243 Split = re.split("[ \n]",Line);
244 if Split[0] != "[GNUPG:]":
247 # We only process the first occurance of any tag.
248 if TagMap.has_key(Split[1]):
250 TagMap[Split[1]] = None;
252 # Good signature response
253 if Split[1] == "GOODSIG":
254 # Just in case GPG returned a bad signal before this (bug?)
258 Owner = string.join(Split[3:],' ');
260 # Bad signature response
261 if Split[1] == "BADSIG":
264 Why = "Verification of signature failed";
266 # Bad signature response
267 if Split[1] == "ERRSIG":
271 Why = "GPG error, ERRSIG status tag is invalid";
272 elif Split[7] == '9':
273 Why = "Unable to verify signature, signing key missing.";
274 elif Split[7] == '4':
275 Why = "Unable to verify signature, unknown packet format/key type";
277 Why = "Unable to verify signature, unknown reason";
279 if Split[1] == "NO_PUBKEY":
281 Why = "Unable to verify signature, signing key missing.";
284 if Split[1] == "SIGEXPIRED":
286 Why = "Signature has expired";
289 if Split[1] == "KEYREVOKED":
291 Why = "Signing key has been revoked";
294 if Split[1] == "NODATA" or Split[1] == "BADARMOR":
296 Why = "The packet was corrupted or contained no data";
299 if Split[1] == "SIG_ID":
301 Date = long(Split[4]);
303 # ValidSig has the key finger print
304 if Split[1] == "VALIDSIG":
305 KeyFinger = Split[2];
307 # Reopen the stream as a readable stream
308 Text = Res[2].read();
310 # A gpg failure is an automatic bad signature
311 if Exit[1] != 0 and Why == None:
313 Why = "GPG execution failed " + str(Exit[0]);
315 if GoodSig == 0 and (Why == None or len(Why) == 0):
316 Why = "Checking Failed";
318 # Try to decide if this message was sent using PGP2
320 if (re.search("-----[\n\r][\n\r]?Version: 2\\.",Message) != None):
323 return (Why,(SigId,Date,KeyFinger),(KeyID,KeyFinger,Owner,0,PGP2Message),Text);
329 # Search for keys given a search pattern. The pattern is passed directly
330 # to GPG for processing. The result is a list of tuples of the form:
331 # (KeyID,KeyFinger,Owner,Length)
332 # Which is similar to the key identification tuple output by GPGChecksig
333 def GPGKeySearch(SearchCriteria):
334 Args = [GPGPath] + GPGBasicOptions + GPGKeyRings + GPGSearchOptions + \
335 [SearchCriteria," 2> /dev/null"]
341 Strm = os.popen(string.join(Args," "),"r");
344 # Grab and split up line
345 Line = Strm.readline();
348 Split = string.split(Line,":");
350 # Store some of the key fields
351 if Split[0] == 'pub':
354 Length = int(Split[2]);
357 if Split[0] == 'fpr':
358 Result.append( (KeyID,Split[9],Owner,Length) );
364 # Print the available key information in a format similar to GPG's output
365 # We do not know the values of all the feilds so they are just replaced
367 def GPGPrintKeyInfo(Ident):
368 print "pub %u?/%s ??-??-?? %s" % (Ident[3],Ident[0][-8:],Ident[2]);
369 print " key fingerprint = 0x%s" % (Ident[1]);
371 # Perform a substition of template
372 def TemplateSubst(Map,Template):
374 Template = string.replace(Template,x,Map[x]);
377 # The replay class uses a python DB (BSD db if avail) to implement
378 # protection against replay. Replay is an attacker capturing the
379 # plain text signed message and sending it back to the victim at some
380 # later date. Each signature has a unique signature ID (and signing
381 # Key Fingerprint) as well as a timestamp. The first stage of replay
382 # protection is to ensure that the timestamp is reasonable, in particular
383 # not to far ahead or too far behind the current system time. The next
384 # step is to look up the signature + key fingerprint in the replay database
385 # and determine if it has been recived. The database is cleaned out
386 # periodically and old signatures are discarded. By using a timestamp the
387 # database size is bounded to being within the range of the allowed times
388 # plus a little fuzz. The cache is serialized with a flocked lock file
390 def __init__(self,Database):
391 self.Lock = open(Database + ".lock","w",0600);
392 fcntl.flock(self.Lock.fileno(),FCNTL.LOCK_EX);
393 self.DB = anydbm.open(Database,"c",0600);
394 self.CleanCutOff = CleanCutOff;
395 self.AgeCutOff = AgeCutOff;
396 self.FutureCutOff = FutureCutOff;
398 # Close the cache and lock
405 # Clean out any old signatures
407 CutOff = time.time() - self.CleanCutOff;
408 for x in self.DB.keys():
409 if int(self.DB[x]) <= CutOff:
412 # Check a signature. 'sig' is a 3 tuple that has the sigId, date and
415 if Sig[0] == None or Sig[1] == None or Sig[2] == None:
416 return "Invalid signature";
417 if int(Sig[1]) > time.time() + self.FutureCutOff:
418 return "Signature has a time too far in the future";
419 if self.DB.has_key(Sig[0] + '-' + Sig[2]):
420 return "Signature has already been received";
421 if int(Sig[1]) < time.time() - self.AgeCutOff:
422 return "Signature has passed the age cut off ";
423 # + str(int(Sig[1])) + ',' + str(time.time()) + "," + str(Sig);
426 # Add a signature, the sig is the same as is given to Check
428 if Sig[0] == None or Sig[1] == None:
429 raise RuntimeError,"Invalid signature";
430 if Sig[1] < time.time() - self.CleanCutOff:
432 Key = Sig[0] + '-' + Sig[2]
433 if self.DB.has_key(Key):
434 if int(self.DB[Key]) < Sig[1]:
435 self.DB[Key] = str(int(Sig[1]));
437 self.DB[Key] = str(int(Sig[1]));