Try to make key acceptance logic clearer
[mirror/userdir-ldap.git] / userdir_gpg.py
1 #   Copyright (c) 1999-2001  Jason Gunthorpe <jgg@debian.org>
2 #   Copyright (c) 2005       Joey Schulze <joey@infodrom.org>
3 #
4 #   This program is free software; you can redistribute it and/or modify
5 #   it under the terms of the GNU General Public License as published by
6 #   the Free Software Foundation; either version 2 of the License, or
7 #   (at your option) any later version.
8 #
9 #   This program is distributed in the hope that it will be useful,
10 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
11 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 #   GNU General Public License for more details.
13 #
14 #   You should have received a copy of the GNU General Public License
15 #   along with this program; if not, write to the Free Software
16 #   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 # GPG issues -
19 #  - gpgm with a status FD being fed keymaterial and other interesting
20 #    things does nothing.. If it could ID the keys and stuff over the
21 #    status-fd I could decide what to do with them. I would also like it
22 #    to report which key it selected for encryption (also if there
23 #    were multi-matches..) Being able to detect a key-revoke cert would be
24 #    good too.
25 #  - I would like to be able to fetch the comment and version fields from the
26 #    packets so I can tell if a signature is made by pgp2 to enable the
27 #    pgp2 encrypting mode.
28
29 import sys, StringIO, os, tempfile, re;
30 import time, fcntl, anydbm
31 import email, email.message
32
33 from userdir_exceptions import *
34
35 # General GPG options
36 GPGPath = "gpg"
37 # "--load-extension","rsa",
38 GPGBasicOptions = [
39    "--no-options",
40    "--batch",
41    "--no-default-keyring",
42    "--secret-keyring", "/dev/null",
43    "--always-trust"];
44 GPGKeyRings = [];
45 GPGSigOptions = ["--output","-"];
46 GPGSearchOptions = ["--dry-run","--with-colons","--fingerprint"];
47 GPGEncryptOptions = ["--output","-","--quiet","--always-trust",\
48                      "--armor","--encrypt"];
49 GPGEncryptPGP2Options = ["--set-filename","","--rfc1991",\
50                          "--load-extension","idea",\
51                          "--cipher-algo","idea"] + GPGEncryptOptions;
52
53 # Replay cutoff times in seconds
54 CleanCutOff = 7*24*60*60;
55 AgeCutOff = 4*24*60*60;
56 FutureCutOff = 3*24*60*60;
57
58 def ClearKeyrings():
59    del GPGKeyRings[:]
60
61 # Set the keyrings, the input is a list of keyrings
62 def SetKeyrings(Rings):
63    for x in Rings:
64       GPGKeyRings.append("--keyring");
65       GPGKeyRings.append(x);
66
67 # GetClearSig takes an un-seekable email message stream (mimetools.Message)
68 # and returns a standard PGP '---BEGIN PGP SIGNED MESSAGE---' bounded
69 # clear signed text.
70 # If this is fed to gpg/pgp it will verify the signature and spit out the
71 # signed text component. Email headers and PGP mime (RFC 2015) is understood
72 # but no effort is made to cull any information outside the PGP boundaries
73 # Please note that in the event of a mime decode the mime headers will be
74 # present in the signature text! The return result is a tuple, the first
75 # element is the text itself the second is a mime flag indicating if the
76 # result should be mime processed after sig checking.
77 #
78 # Paranoid will check the message text to make sure that all the plaintext is
79 # in fact signed (bounded by a PGP packet)
80 #
81 # lax_multipart: treat multipart bodies other than multipart/signed
82 # as one big plain text body
83 def GetClearSig(Msg, Paranoid = 0, lax_multipart = False):
84    if not Msg.__class__ == email.message.Message:
85       raise RuntimeError, "GetClearSign() not called with a email.message.Message"
86
87    if Paranoid and lax_multipart:
88       raise RuntimeError, "Paranoid and lax_multipart don't mix well"
89
90    # See if this is a MIME encoded multipart signed message
91    if Msg.is_multipart():
92       if not Msg.get_content_type() == "multipart/signed":
93          if lax_multipart:
94             payloads = Msg.get_payload()
95             msg = "\n".join(map( lambda p: p.get_payload(decode=True), payloads))
96             return (msg, 0)
97          raise UDFormatError, "Cannot handle multipart messages not of type multipart/signed";
98
99       if Paranoid:
100          if Msg.preamble is not None and Msg.preamble.strip() != "":
101             raise UDFormatError,"Unsigned text in message (at start)";
102          if Msg.epilogue is not None and Msg.epilogue.strip() != "":
103             raise UDFormatError,"Unsigned text in message (at end)";
104
105       payloads = Msg.get_payload()
106       if len(payloads) != 2:
107          raise UDFormatError, "multipart/signed message with number of payloads != 2";
108
109       (Signed, Signature) = payloads
110
111       if Signed.get_content_type() != "text/plain" and not lax_multipart:
112          raise UDFormatError, "Invalid pgp/mime encoding for first part[wrong plaintext type]";
113       if Signature.get_content_type() != "application/pgp-signature":
114          raise UDFormatError, "Invalid pgp/mime encoding for second part [wrong signature type]";
115
116       # Append the PGP boundary header and the signature text to re-form the
117       # original signed block [needs to convert to \r\n]
118       Output = "-----BEGIN PGP SIGNED MESSAGE-----\r\n";
119       # Semi-evil hack to get the proper hash type inserted in the message
120       if Msg.get_param('micalg') != None:
121           Output = Output + "Hash: MD5,SHA1,%s\r\n"%(Msg.get_param('micalg')[4:].upper())
122       Output = Output + "\r\n";
123       Output = Output + Signed.as_string().replace("\n-","\n- -") + "\n" + Signature.get_payload(decode=True)
124       return (Output,1);
125    else:
126       if Paranoid == 0:
127          # Just return the message body
128          return (Msg.get_payload(decode=True), 0);
129
130       Body = [];
131       State = 1;
132       for x in Msg.get_payload(decode=True).split('\n'):
133           Body.append(x)
134
135           if x == "":
136              continue;
137
138           # Leading up to the signature
139           if State == 1:
140              if x == "-----BEGIN PGP SIGNED MESSAGE-----":
141                 State = 2;
142              else:
143                 raise UDFormatError,"Unsigned text in message (at start)";
144              continue;
145
146           # In the signature plain text
147           if State == 2:
148              if x == "-----BEGIN PGP SIGNATURE-----":
149                 State = 3;
150              continue;
151
152           # In the signature
153           if State == 3:
154              if x == "-----END PGP SIGNATURE-----":
155                 State = 4;
156              continue;
157
158           # Past the end
159           if State == 4:
160              raise UDFormatError,"Unsigned text in message (at end)";
161
162       return ("\n".join(Body), 0);
163
164 # This opens GPG in 'write filter' mode. It takes Message and sends it
165 # to GPGs standard input, pipes the standard output to a temp file along
166 # with the status FD. The two tempfiles are passed to GPG by fd and are
167 # accessible from the filesystem for only a short period. Message may be
168 # None in which case GPGs stdin is closed directly after forking. This
169 # is best used for sig checking and encryption.
170 # The return result is a tuple (Exit,StatusFD,OutputFD), both fds are
171 # fully rewound and readable.
172 def GPGWriteFilter(Program,Options,Message):
173    # Make sure the tmp files we open are unreadable, there is a short race
174    # between when the temp file is opened and unlinked that some one else
175    # could open it or hard link it. This is not important however as no
176    # Secure data is fed through the temp files.
177    OldMask = os.umask(0777);
178    try:
179       Output = tempfile.TemporaryFile("w+b");
180       GPGText = tempfile.TemporaryFile("w+b");
181       InPipe = os.pipe();
182       InPipe = [InPipe[0],InPipe[1]];
183    finally:
184       os.umask(OldMask);
185
186    try:
187       # Fork off GPG in a horrible way, we redirect most of its FDs
188       # Input comes from a pipe and its two outputs are spooled to unlinked
189       # temp files (ie private)
190       Child = os.fork();
191       if Child == 0:
192          try:
193             os.dup2(InPipe[0],0);
194             os.close(InPipe[1]);
195             os.dup2(Output.fileno(),1);
196             os.dup2(os.open("/dev/null",os.O_WRONLY),2);
197             os.dup2(GPGText.fileno(),3);
198
199             Args = [Program,"--status-fd","3"] + GPGBasicOptions + GPGKeyRings + Options
200             os.execvp(Program,Args);
201          finally:
202             os._exit(100);
203
204       # Get rid of the other end of the pipe
205       os.close(InPipe[0])
206       InPipe[0] = -1;
207
208       # Send the message
209       if Message != None:
210          try:
211             os.write(InPipe[1],Message);
212          except:
213            pass;
214       os.close(InPipe[1]);
215       InPipe[1] = -1;
216
217       # Wait for GPG to finish
218       Exit = os.waitpid(Child,0);
219
220       # Create the result including the new readable file descriptors
221       Result = (Exit,os.fdopen(os.dup(GPGText.fileno()),"r"), \
222                 os.fdopen(os.dup(Output.fileno()),"r"));
223       Result[1].seek(0);
224       Result[2].seek(0);
225
226       Output.close();
227       GPGText.close();
228       return Result;
229    finally:
230       if InPipe[0] != -1:
231          os.close(InPipe[0]);
232       if InPipe[1] != -1:
233          os.close(InPipe[1]);
234       Output.close();
235       GPGText.close();
236
237 # This takes a text passage, a destination and a flag indicating the
238 # compatibility to use and returns an encrypted message to the recipient.
239 # It is best if the recipient is specified using the hex key fingerprint
240 # of the target, ie 0x64BE1319CCF6D393BF87FF9358A6D4EE
241 def GPGEncrypt(Message,To,PGP2):
242    Error = "KeyringError"
243    # Encrypt using the PGP5 block encoding and with the PGP5 option set.
244    # This will handle either RSA or DSA/DH asymetric keys.
245    # In PGP2 compatible mode IDEA and rfc1991 encoding are used so that
246    # PGP2 can read the result. RSA keys do not need PGP2 to be set, as GPG
247    # can read a message encrypted with blowfish and RSA.
248    searchkey = GPGKeySearch(To);
249    if len(searchkey) == 0:
250       raise Error, "No key found matching %s"%(To);
251    elif len(searchkey) > 1:
252       raise Error, "Multiple keys found matching %s"%(To);
253    if searchkey[0][4].find("E") < 0:
254       raise Error, "Key %s has no encryption capability - are all encryption subkeys expired or revoked?  Are there any encryption subkeys?"%(To);
255
256    if PGP2 == 0:
257       try:
258          Res = None;
259          Res = GPGWriteFilter(GPGPath,["-r",To]+GPGEncryptOptions,Message);
260          if Res[0][1] != 0:
261             return None;
262          Text = Res[2].read();
263          return Text;
264       finally:
265          if Res != None:
266             Res[1].close();
267             Res[2].close();
268    else:
269       # We have to call gpg with a filename or it will create a packet that
270       # PGP2 cannot understand.
271       TmpName = tempfile.mktemp();
272       try:
273          Res = None;
274          MsgFile = open(TmpName,"wc");
275          MsgFile.write(Message);
276          MsgFile.close();
277          Res = GPGWriteFilter(GPGPath,["-r",To]+GPGEncryptPGP2Options+[TmpName],None);
278          if Res[0][1] != 0:
279             return None;
280          Text = Res[2].read();
281          return Text;
282       finally:
283          try:
284             os.unlink(TmpName);
285          except:
286             pass;
287          if Res != None:
288             Res[1].close();
289             Res[2].close();
290
291 # Checks the signature of a standard PGP message, like that returned by
292 # GetClearSig. It returns a large tuple of the form:
293 #   (Why,(SigId,Date,KeyFinger),(KeyID,KeyFinger,Owner,Length,PGP2),Text);
294 # Where,
295 #  Why = None if checking was OK otherwise an error string.
296 #  SigID+Date represent something suitable for use in a replay cache. The
297 #             date is returned as the number of seconds since the UTC epoch.
298 #             The keyID is also in this tuple for easy use of the replay
299 #             cache
300 #  KeyID, KeyFinger and Owner represent the Key used to sign this message
301 #         PGP2 indicates if the message was created using PGP 2.x
302 #  Text is the full byte-for-byte signed text in a string
303 def GPGCheckSig(Message):
304    Res = None;
305    try:
306       Res = GPGWriteFilter(GPGPath,GPGSigOptions,Message);
307       Exit = Res[0];
308
309       # Parse the GPG answer
310       Strm = Res[1];
311       GoodSig = 0;
312       SigId = None;
313       KeyFinger = None;
314       KeyID = None;
315       Owner = None;
316       Date = None;
317       Why = None;
318       TagMap = {};
319       while(1):
320          # Grab and split up line
321          Line = Strm.readline();
322          if Line == "":
323             break;
324          Split = re.split("[ \n]",Line);
325          if Split[0] != "[GNUPG:]":
326             continue;
327
328          # We only process the first occurance of any tag.
329          if TagMap.has_key(Split[1]):
330             continue;
331          TagMap[Split[1]] = None;
332
333          # Good signature response
334          if Split[1] == "GOODSIG":
335             # Just in case GPG returned a bad signal before this (bug?)
336             if Why == None:
337                GoodSig = 1;
338             KeyID = Split[2];
339             Owner = ' '.join(Split[3:])
340             # If this message is signed with a subkey which has not yet
341             # expired, GnuPG will say GOODSIG here, even if the primary
342             # key already has expired.  This came up in discussion of
343             # bug #489225.  GPGKeySearch only returns non-expired keys.
344             Verify = GPGKeySearch(KeyID);
345             if len(Verify) == 0:
346                GoodSig = 0
347                Why = "Key has expired (no unexpired key found in keyring matching %s)"%(KeyId);
348
349          # Bad signature response
350          if Split[1] == "BADSIG":
351             GoodSig = 0;
352             KeyID = Split[2];
353             Why = "Verification of signature failed";
354
355          # Bad signature response
356          if Split[1] == "ERRSIG":
357             GoodSig = 0;
358             KeyID = Split[2];
359             if len(Split) <= 7:
360                Why = "GPG error, ERRSIG status tag is invalid";
361             elif Split[7] == '9':
362                Why = "Unable to verify signature, signing key missing.";
363             elif Split[7] == '4':
364                Why = "Unable to verify signature, unknown packet format/key type";
365             else:
366                Why = "Unable to verify signature, unknown reason";
367
368          if Split[1] == "NO_PUBKEY":
369             GoodSig = 0;
370             Why = "Unable to verify signature, signing key missing.";
371
372          # Expired signature
373          if Split[1] == "EXPSIG":
374             GoodSig = 0;
375             Why = "Signature has expired";
376
377          # Expired signature
378          if Split[1] == "EXPKEYSIG":
379             GoodSig = 0;
380             Why = "Signing key (%s, %s) has expired"%(Split[2], Split[3]);
381
382          # Revoked key
383          if Split[1] == "KEYREVOKED" or Split[1] == "REVKEYSIG":
384             GoodSig = 0;
385             Why = "Signing key has been revoked";
386
387          # Corrupted packet
388          if Split[1] == "NODATA" or Split[1] == "BADARMOR":
389             GoodSig = 0;
390             Why = "The packet was corrupted or contained no data";
391
392          # Signature ID
393          if Split[1] == "SIG_ID":
394             SigId = Split[2];
395             Date = long(Split[4]);
396
397          # ValidSig has the key finger print
398          if Split[1] == "VALIDSIG":
399             # Use the fingerprint of the primary key when available
400             if len(Split) >= 12:
401                KeyFinger = Split[11];
402             else:
403                KeyFinger = Split[2];
404
405       # Reopen the stream as a readable stream
406       Text = Res[2].read();
407
408       # A gpg failure is an automatic bad signature
409       if Exit[1] != 0 and Why == None:
410          GoodSig = 0;
411          Why = "GPG execution returned non-zero exit status: " + str(Exit[1]);
412
413       if GoodSig == 0 and (Why == None or len(Why) == 0):
414          Why = "Checking Failed";
415
416       # Try to decide if this message was sent using PGP2
417       PGP2Message = 0;
418       if (re.search("-----[\n\r][\n\r]?Version: 2\\.",Message) != None):
419          PGP2Message = 1;
420
421       return (Why,(SigId,Date,KeyFinger),(KeyID,KeyFinger,Owner,0,PGP2Message),Text);
422    finally:
423       if Res != None:
424          Res[1].close();
425          Res[2].close();
426
427 class GPGCheckSig2:
428         def __init__(self, msg):
429                 res = GPGCheckSig(msg)
430                 self.why = res[0]
431                 self.sig_info = res[1]
432                 self.key_info = res[2]
433                 self.text = res[3]
434
435                 self.ok = self.why is None
436
437                 self.sig_id = self.sig_info[0]
438                 self.sig_date = self.sig_info[1]
439                 self.sig_fpr = self.sig_info[2]
440
441                 self.key_id = self.key_info[0]
442                 self.key_fpr = self.key_info[1]
443                 self.key_owner = self.key_info[2]
444
445                 self.is_pgp2 = self.key_info[4]
446
447 # Search for keys given a search pattern. The pattern is passed directly
448 # to GPG for processing. The result is a list of tuples of the form:
449 #   (KeyID,KeyFinger,Owner,Length)
450 # Which is similar to the key identification tuple output by GPGChecksig
451 #
452 # Do not return keys where the primary key has expired
453 def GPGKeySearch(SearchCriteria):
454    Args = [GPGPath] + GPGBasicOptions + GPGKeyRings + GPGSearchOptions + \
455           [SearchCriteria," 2> /dev/null"]
456    Strm = None;
457    Result = [];
458    Owner = "";
459    KeyID = "";
460    Capabilities = ""
461    Expired = None;
462    Hits = {};
463
464    dir = os.path.expanduser("~/.gnupg")
465    if not os.path.isdir(dir):
466       os.mkdir(dir, 0700)
467
468    try:
469       Strm = os.popen(" ".join(Args),"r")
470
471       while(1):
472          # Grab and split up line
473          Line = Strm.readline();
474          if Line == "":
475             break;
476          Split = Line.split(":")
477
478          # Store some of the key fields
479          if Split[0] == 'pub':
480             KeyID = Split[4];
481             Owner = Split[9];
482             Length = int(Split[2])
483             Capabilities = Split[11]
484             Expired = Split[1] == 'e'
485
486          # Output the key
487          if Split[0] == 'fpr':
488             if Hits.has_key(Split[9]):
489                continue;
490             Hits[Split[9]] = None;
491             if not Expired:
492                Result.append( (KeyID,Split[9],Owner,Length,Capabilities) );
493    finally:
494       if Strm != None:
495          Strm.close();
496    return Result;
497
498 # Print the available key information in a format similar to GPG's output
499 # We do not know the values of all the feilds so they are just replaced
500 # with ?'s
501 def GPGPrintKeyInfo(Ident):
502    print "pub  %u?/%s ??-??-?? %s" % (Ident[3],Ident[0][-8:],Ident[2]);
503    print "     key fingerprint = 0x%s" % (Ident[1]);
504
505 # Perform a substition of template
506 def TemplateSubst(Map,Template):
507    for x in Map.keys():
508       Template = Template.replace(x, Map[x])
509    return Template;
510
511 # The replay class uses a python DB (BSD db if avail) to implement
512 # protection against replay. Replay is an attacker capturing the
513 # plain text signed message and sending it back to the victim at some
514 # later date. Each signature has a unique signature ID (and signing
515 # Key Fingerprint) as well as a timestamp. The first stage of replay
516 # protection is to ensure that the timestamp is reasonable, in particular
517 # not to far ahead or too far behind the current system time. The next
518 # step is to look up the signature + key fingerprint in the replay database
519 # and determine if it has been recived. The database is cleaned out
520 # periodically and old signatures are discarded. By using a timestamp the
521 # database size is bounded to being within the range of the allowed times
522 # plus a little fuzz. The cache is serialized with a flocked lock file
523 class ReplayCache:
524    def __init__(self,Database):
525       self.Lock = open(Database + ".lock","w",0600);
526       fcntl.flock(self.Lock.fileno(),fcntl.LOCK_EX);
527       self.DB = anydbm.open(Database,"c",0600);
528       self.CleanCutOff = CleanCutOff;
529       self.AgeCutOff = AgeCutOff;
530       self.FutureCutOff = FutureCutOff;
531       self.Clean()
532
533    # Close the cache and lock
534    def __del__(self):
535       self.close();
536    def close(self):
537       self.DB.close();
538       self.Lock.close();
539
540    # Clean out any old signatures
541    def Clean(self):
542       CutOff = time.time() - self.CleanCutOff;
543       for x in self.DB.keys():
544          if int(self.DB[x]) <= CutOff:
545             del self.DB[x];
546
547    # Check a signature. 'sig' is a 3 tuple that has the sigId, date and
548    # key ID
549    def Check(self,Sig):
550       if Sig[0] == None or Sig[1] == None or Sig[2] == None:
551          return "Invalid signature";
552       if int(Sig[1]) > time.time() + self.FutureCutOff:
553          return "Signature has a time too far in the future";
554       if self.DB.has_key(Sig[0] + '-' + Sig[2]):
555          return "Signature has already been received";
556       if int(Sig[1]) < time.time() - self.AgeCutOff:
557          return "Signature has passed the age cut off ";
558       # + str(int(Sig[1])) + ',' + str(time.time()) + "," + str(Sig);
559       return None;
560
561    # Add a signature, the sig is the same as is given to Check
562    def Add(self,Sig):
563       if Sig[0] == None or Sig[1] == None:
564          raise RuntimeError,"Invalid signature";
565       if Sig[1] < time.time() - self.CleanCutOff:
566          return;
567       Key = Sig[0] + '-' + Sig[2]
568       if self.DB.has_key(Key):
569          if int(self.DB[Key]) < Sig[1]:
570             self.DB[Key] = str(int(Sig[1]));
571       else:
572          self.DB[Key] = str(int(Sig[1]));
573
574    def process(self, sig_info):
575       r = self.Check(sig_info);
576       if r != None:
577          raise RuntimeError, "The replay cache rejected your message: %s."%(r);
578       self.Add(sig_info);
579       self.close();
580
581 # vim:set et:
582 # vim:set ts=3:
583 # vim:set shiftwidth=3: