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";
87 # Semi-evil hack to get the proper hash type inserted in the message
88 if Msg.getparam('micalg') != None:
89 Output = Output + "Hash: %s\r\n"%(string.upper(Msg.getparam('micalg')[4:]));
90 Output = Output + "\r\n";
91 Output = Output + Signed.getvalue() + Signature;
94 # Just return the message body
95 return (string.joinfields(Msg.fp.readlines(),''),0);
97 # This opens GPG in 'write filter' mode. It takes Message and sends it
98 # to GPGs standard input, pipes the standard output to a temp file along
99 # with the status FD. The two tempfiles are passed to GPG by fd and are
100 # accessible from the filesystem for only a short period. Message may be
101 # None in which case GPGs stdin is closed directly after forking. This
102 # is best used for sig checking and encryption.
103 # The return result is a tuple (Exit,StatusFD,OutputFD), both fds are
104 # fully rewound and readable.
105 def GPGWriteFilter(Program,Options,Message):
106 # Make sure the tmp files we open are unreadable, there is a short race
107 # between when the temp file is opened and unlinked that some one else
108 # could open it or hard link it. This is not important however as no
109 # Secure data is fed through the temp files.
110 OldMask = os.umask(0777);
112 Output = tempfile.TemporaryFile("w+b");
113 GPGText = tempfile.TemporaryFile("w+b");
115 InPipe = [InPipe[0],InPipe[1]];
120 # Fork off GPG in a horrible way, we redirect most of its FDs
121 # Input comes from a pipe and its two outputs are spooled to unlinked
122 # temp files (ie private)
126 os.dup2(InPipe[0],0);
128 os.dup2(Output.fileno(),1);
129 os.dup2(os.open("/dev/null",os.O_WRONLY),2);
130 os.dup2(GPGText.fileno(),3);
132 Args = [Program,"--status-fd","3"] + GPGBasicOptions + GPGKeyRings + Options
133 os.execvp(Program,Args);
137 # Get rid of the other end of the pipe
144 os.write(InPipe[1],Message);
150 # Wait for GPG to finish
151 Exit = os.waitpid(Child,0);
153 # Create the result including the new readable file descriptors
154 Result = (Exit,os.fdopen(os.dup(GPGText.fileno()),"r"), \
155 os.fdopen(os.dup(Output.fileno()),"r"));
170 # This takes a text passage, a destination and a flag indicating the
171 # compatibility to use and returns an encrypted message to the recipient.
172 # It is best if the recipient is specified using the hex key fingerprint
173 # of the target, ie 0x64BE1319CCF6D393BF87FF9358A6D4EE
174 def GPGEncrypt(Message,To,PGP2):
175 # Encrypt using the PGP5 block encoding and with the PGP5 option set.
176 # This will handle either RSA or DSA/DH asymetric keys.
177 # In PGP2 compatible mode IDEA and rfc1991 encoding are used so that
178 # PGP2 can read the result. RSA keys do not need PGP2 to be set, as GPG
179 # can read a message encrypted with blowfish and RSA.
183 Res = GPGWriteFilter(GPGPath,["-r",To]+GPGEncryptOptions,Message);
186 Text = Res[2].read();
193 # We have to call gpg with a filename or it will create a packet that
194 # PGP2 cannot understand.
195 TmpName = tempfile.mktemp();
198 MsgFile = open(TmpName,"wc");
199 MsgFile.write(Message);
201 Res = GPGWriteFilter(GPGPath,["-r",To]+GPGEncryptPGP2Options+[TmpName],None);
204 Text = Res[2].read();
215 # Checks the signature of a standard PGP message, like that returned by
216 # GetClearSig. It returns a large tuple of the form:
217 # (Why,(SigId,Date,KeyFinger),(KeyID,KeyFinger,Owner,Length,PGP2),Text);
219 # Why = None if checking was OK otherwise an error string.
220 # SigID+Date represent something suitable for use in a replay cache. The
221 # date is returned as the number of seconds since the UTC epoch.
222 # The keyID is also in this tuple for easy use of the replay
224 # KeyID, KeyFinger and Owner represent the Key used to sign this message
225 # PGP2 indicates if the message was created using PGP 2.x
226 # Text is the full byte-for-byte signed text in a string
227 def GPGCheckSig(Message):
230 Res = GPGWriteFilter(GPGPath,GPGSigOptions,Message);
233 # Parse the GPG answer
244 # Grab and split up line
245 Line = Strm.readline();
248 Split = re.split("[ \n]",Line);
249 if Split[0] != "[GNUPG:]":
252 # We only process the first occurance of any tag.
253 if TagMap.has_key(Split[1]):
255 TagMap[Split[1]] = None;
257 # Good signature response
258 if Split[1] == "GOODSIG":
259 # Just in case GPG returned a bad signal before this (bug?)
263 Owner = string.join(Split[3:],' ');
265 # Bad signature response
266 if Split[1] == "BADSIG":
269 Why = "Verification of signature failed";
271 # Bad signature response
272 if Split[1] == "ERRSIG":
276 Why = "GPG error, ERRSIG status tag is invalid";
277 elif Split[7] == '9':
278 Why = "Unable to verify signature, signing key missing.";
279 elif Split[7] == '4':
280 Why = "Unable to verify signature, unknown packet format/key type";
282 Why = "Unable to verify signature, unknown reason";
284 if Split[1] == "NO_PUBKEY":
286 Why = "Unable to verify signature, signing key missing.";
289 if Split[1] == "SIGEXPIRED":
291 Why = "Signature has expired";
294 if Split[1] == "KEYREVOKED":
296 Why = "Signing key has been revoked";
299 if Split[1] == "NODATA" or Split[1] == "BADARMOR":
301 Why = "The packet was corrupted or contained no data";
304 if Split[1] == "SIG_ID":
306 Date = long(Split[4]);
308 # ValidSig has the key finger print
309 if Split[1] == "VALIDSIG":
310 KeyFinger = Split[2];
312 # Reopen the stream as a readable stream
313 Text = Res[2].read();
315 # A gpg failure is an automatic bad signature
316 if Exit[1] != 0 and Why == None:
318 Why = "GPG execution failed " + str(Exit[0]);
320 if GoodSig == 0 and (Why == None or len(Why) == 0):
321 Why = "Checking Failed";
323 # Try to decide if this message was sent using PGP2
325 if (re.search("-----[\n\r][\n\r]?Version: 2\\.",Message) != None):
328 return (Why,(SigId,Date,KeyFinger),(KeyID,KeyFinger,Owner,0,PGP2Message),Text);
334 # Search for keys given a search pattern. The pattern is passed directly
335 # to GPG for processing. The result is a list of tuples of the form:
336 # (KeyID,KeyFinger,Owner,Length)
337 # Which is similar to the key identification tuple output by GPGChecksig
338 def GPGKeySearch(SearchCriteria):
339 Args = [GPGPath] + GPGBasicOptions + GPGKeyRings + GPGSearchOptions + \
340 [SearchCriteria," 2> /dev/null"]
346 Strm = os.popen(string.join(Args," "),"r");
349 # Grab and split up line
350 Line = Strm.readline();
353 Split = string.split(Line,":");
355 # Store some of the key fields
356 if Split[0] == 'pub':
359 Length = int(Split[2]);
362 if Split[0] == 'fpr':
363 Result.append( (KeyID,Split[9],Owner,Length) );
369 # Print the available key information in a format similar to GPG's output
370 # We do not know the values of all the feilds so they are just replaced
372 def GPGPrintKeyInfo(Ident):
373 print "pub %u?/%s ??-??-?? %s" % (Ident[3],Ident[0][-8:],Ident[2]);
374 print " key fingerprint = 0x%s" % (Ident[1]);
376 # Perform a substition of template
377 def TemplateSubst(Map,Template):
379 Template = string.replace(Template,x,Map[x]);
382 # The replay class uses a python DB (BSD db if avail) to implement
383 # protection against replay. Replay is an attacker capturing the
384 # plain text signed message and sending it back to the victim at some
385 # later date. Each signature has a unique signature ID (and signing
386 # Key Fingerprint) as well as a timestamp. The first stage of replay
387 # protection is to ensure that the timestamp is reasonable, in particular
388 # not to far ahead or too far behind the current system time. The next
389 # step is to look up the signature + key fingerprint in the replay database
390 # and determine if it has been recived. The database is cleaned out
391 # periodically and old signatures are discarded. By using a timestamp the
392 # database size is bounded to being within the range of the allowed times
393 # plus a little fuzz. The cache is serialized with a flocked lock file
395 def __init__(self,Database):
396 self.Lock = open(Database + ".lock","w",0600);
397 fcntl.flock(self.Lock.fileno(),FCNTL.LOCK_EX);
398 self.DB = anydbm.open(Database,"c",0600);
399 self.CleanCutOff = CleanCutOff;
400 self.AgeCutOff = AgeCutOff;
401 self.FutureCutOff = FutureCutOff;
403 # Close the cache and lock
410 # Clean out any old signatures
412 CutOff = time.time() - self.CleanCutOff;
413 for x in self.DB.keys():
414 if int(self.DB[x]) <= CutOff:
417 # Check a signature. 'sig' is a 3 tuple that has the sigId, date and
420 if Sig[0] == None or Sig[1] == None or Sig[2] == None:
421 return "Invalid signature";
422 if int(Sig[1]) > time.time() + self.FutureCutOff:
423 return "Signature has a time too far in the future";
424 if self.DB.has_key(Sig[0] + '-' + Sig[2]):
425 return "Signature has already been received";
426 if int(Sig[1]) < time.time() - self.AgeCutOff:
427 return "Signature has passed the age cut off ";
428 # + str(int(Sig[1])) + ',' + str(time.time()) + "," + str(Sig);
431 # Add a signature, the sig is the same as is given to Check
433 if Sig[0] == None or Sig[1] == None:
434 raise RuntimeError,"Invalid signature";
435 if Sig[1] < time.time() - self.CleanCutOff:
437 Key = Sig[0] + '-' + Sig[2]
438 if self.DB.has_key(Key):
439 if int(self.DB[Key]) < Sig[1]:
440 self.DB[Key] = str(int(Sig[1]));
442 self.DB[Key] = str(int(Sig[1]));