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