e0f3feb8d99828b68d7d074e3683015b75992e38
[mirror/userdir-ldap.git] / userdir_gpg.py
1  #!/usr/bin/env python
2 # -*- mode: python -*-
3
4 # GPG issues - 
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
10 #    good too.
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.
14
15 import string, mimetools, multifile, sys, StringIO, os, tempfile, re;
16 import rfc822, time, fcntl, FCNTL, anydbm
17
18 # General GPG options
19 GPGPath = "gpg"
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;
31
32 # Replay cutoff times in seconds
33 CleanCutOff = 7*24*60*60;
34 AgeCutOff = 4*24*60*60;
35 FutureCutOff = 3*24*60*60;
36
37 # GetClearSig takes an un-seekable email message stream (mimetools.Message) 
38 # and returns a standard PGP '---BEGIN PGP SIGNED MESSAGE---' bounded 
39 # clear signed text.
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.
47 def GetClearSig(Msg):
48    Error = 'MIME Error';
49    # See if this is a MIME encoded multipart signed message
50    if Msg.gettype() == "multipart/signed":
51       Boundary = Msg.getparam("boundary");
52       if not Boundary:
53          raise Error, "multipart/* without a boundary parameter";
54
55       # Create the multipart handler. Regrettably their implementation 
56       # Needs seeking..
57       SkMessage = StringIO.StringIO();
58       SkMessage.write(Msg.fp.read());
59       SkMessage.seek(0);
60       mf = multifile.MultiFile(SkMessage)
61       mf.push(Msg.getparam("boundary"));
62
63       # Get the first part of the multipart message
64       if not mf.next():
65          raise Error, "Invalid pgp/mime encoding [no section]";
66
67       # Get the part as a safe seekable stream
68       Signed = StringIO.StringIO();
69       Signed.write(mf.read());
70       InnerMsg = mimetools.Message(Signed);
71
72       # Make sure it is the right type
73       if InnerMsg.gettype() != "text/plain":
74          raise Error, "Invalid pgp/mime encoding [wrong plaintext type]";
75    
76       # Get the next part of the multipart message
77       if not mf.next():
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(),'');
83
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 +  string.replace(Signed.getvalue(),"\n---","\n- ---") + Signature;
92       return (Output,1);
93    else:
94       # Just return the message body
95       return (string.joinfields(Msg.fp.readlines(),''),0);
96
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);
111    try:
112       Output = tempfile.TemporaryFile("w+b");
113       GPGText = tempfile.TemporaryFile("w+b");
114       InPipe = os.pipe();
115       InPipe = [InPipe[0],InPipe[1]];
116    finally:
117       os.umask(OldMask);
118       
119    try:
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)
123       Child = os.fork();
124       if Child == 0:
125          try:
126             os.dup2(InPipe[0],0);
127             os.close(InPipe[1]);
128             os.dup2(Output.fileno(),1);
129             os.dup2(os.open("/dev/null",os.O_WRONLY),2);
130             os.dup2(GPGText.fileno(),3);
131             
132             Args = [Program,"--status-fd","3"] + GPGBasicOptions + GPGKeyRings + Options
133             os.execvp(Program,Args);
134          finally:
135             os._exit(100);
136       
137       # Get rid of the other end of the pipe
138       os.close(InPipe[0])
139       InPipe[0] = -1;
140
141       # Send the message
142       if Message != None:
143          try:
144             os.write(InPipe[1],Message);
145          except:
146            pass;
147       os.close(InPipe[1]);
148       InPipe[1] = -1;
149
150       # Wait for GPG to finish
151       Exit = os.waitpid(Child,0);
152
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"));
156       Result[1].seek(0);
157       Result[2].seek(0);
158
159       Output.close();
160       GPGText.close();
161       return Result;
162    finally:
163       if InPipe[0] != -1:
164          os.close(InPipe[0]);
165       if InPipe[1] != -1:
166          os.close(InPipe[1]);
167       Output.close();
168       GPGText.close();
169
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.
180    if PGP2 == 0:
181       try:
182          Res = None;
183          Res = GPGWriteFilter(GPGPath,["-r",To]+GPGEncryptOptions,Message);
184          if Res[0][1] != 0:
185             return None;
186          Text = Res[2].read();
187          return Text;
188       finally:
189          if Res != None:
190             Res[1].close();
191             Res[2].close();
192    else:
193       # We have to call gpg with a filename or it will create a packet that
194       # PGP2 cannot understand.
195       TmpName = tempfile.mktemp();
196       try:
197          Res = None;
198          MsgFile = open(TmpName,"wc");
199          MsgFile.write(Message);
200          MsgFile.close();
201          Res = GPGWriteFilter(GPGPath,["-r",To]+GPGEncryptPGP2Options+[TmpName],None);
202          if Res[0][1] != 0:
203             return None;
204          Text = Res[2].read();
205          return Text;
206       finally:
207          try:
208             os.unlink(TmpName);
209          except:
210             pass;
211          if Res != None:
212             Res[1].close();
213             Res[2].close();
214
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);
218 # Where,
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 
223 #             cache
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):
228    Res = None;
229    try:
230       Res = GPGWriteFilter(GPGPath,GPGSigOptions,Message);
231       Exit = Res[0];
232
233       # Parse the GPG answer
234       Strm = Res[1];
235       GoodSig = 0;
236       SigId = None;
237       KeyFinger = None;
238       KeyID = None;
239       Owner = None;
240       Date = None;
241       Why = None;
242       TagMap = {};
243       while(1):
244          # Grab and split up line
245          Line = Strm.readline();
246          if Line == "":
247             break;
248          Split = re.split("[ \n]",Line);
249          if Split[0] != "[GNUPG:]":
250             continue;
251
252          # We only process the first occurance of any tag.
253          if TagMap.has_key(Split[1]):
254             continue;
255          TagMap[Split[1]] = None;
256
257          # Good signature response
258          if Split[1] == "GOODSIG":
259             # Just in case GPG returned a bad signal before this (bug?)
260             if Why == None:
261                GoodSig = 1;
262             KeyID = Split[2];
263             Owner = string.join(Split[3:],' ');
264             
265          # Bad signature response
266          if Split[1] == "BADSIG":
267             GoodSig = 0;
268             KeyID = Split[2];
269             Why = "Verification of signature failed";
270
271          # Bad signature response
272          if Split[1] == "ERRSIG":
273             GoodSig = 0;
274             KeyID = Split[2];
275             if len(Split) <= 7:
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";
281             else:   
282                Why = "Unable to verify signature, unknown reason";
283
284          if Split[1] == "NO_PUBKEY":
285             GoodSig = 0;
286             Why = "Unable to verify signature, signing key missing.";
287
288          # Expired signature
289          if Split[1] == "SIGEXPIRED":
290             GoodSig = 0;
291             Why = "Signature has expired";
292             
293          # Revoked key
294          if Split[1] == "KEYREVOKED":
295             GoodSig = 0;
296             Why = "Signing key has been revoked";
297
298          # Corrupted packet
299          if Split[1] == "NODATA" or Split[1] == "BADARMOR":
300             GoodSig = 0;
301             Why = "The packet was corrupted or contained no data";
302             
303          # Signature ID
304          if Split[1] == "SIG_ID":
305             SigId = Split[2];
306             Date = long(Split[4]);
307
308          # ValidSig has the key finger print
309          if Split[1] == "VALIDSIG":
310             KeyFinger = Split[2];
311
312       # Reopen the stream as a readable stream
313       Text = Res[2].read();
314
315       # A gpg failure is an automatic bad signature
316       if Exit[1] != 0 and Why == None:
317          GoodSig = 0;
318          Why = "GPG execution failed " + str(Exit[0]);
319
320       if GoodSig == 0 and (Why == None or len(Why) == 0):
321          Why = "Checking Failed";
322
323       # Try to decide if this message was sent using PGP2
324       PGP2Message = 0;
325       if (re.search("-----[\n\r][\n\r]?Version: 2\\.",Message) != None):
326          PGP2Message = 1;
327
328       return (Why,(SigId,Date,KeyFinger),(KeyID,KeyFinger,Owner,0,PGP2Message),Text);
329    finally:
330       if Res != None:
331          Res[1].close();
332          Res[2].close();
333
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"]
341    Strm = None;
342    Result = [];
343    Owner = "";
344    KeyID = "";
345    Hits = {};
346    try:
347       Strm = os.popen(string.join(Args," "),"r");
348       
349       while(1):
350          # Grab and split up line
351          Line = Strm.readline();
352          if Line == "":
353             break;
354          Split = string.split(Line,":");
355          
356          # Store some of the key fields
357          if Split[0] == 'pub':
358             KeyID = Split[4];
359             Owner = Split[9];
360             Length = int(Split[2]);
361
362          # Output the key
363          if Split[0] == 'fpr':
364             if Hits.has_key(Split[9]):
365                continue;
366             Hits[Split[9]] = None;
367             Result.append( (KeyID,Split[9],Owner,Length) );
368    finally:
369       if Strm != None:
370          Strm.close();
371    return Result;
372
373 # Print the available key information in a format similar to GPG's output
374 # We do not know the values of all the feilds so they are just replaced
375 # with ?'s
376 def GPGPrintKeyInfo(Ident):
377    print "pub  %u?/%s ??-??-?? %s" % (Ident[3],Ident[0][-8:],Ident[2]);
378    print "     key fingerprint = 0x%s" % (Ident[1]);
379
380 # Perform a substition of template 
381 def TemplateSubst(Map,Template):
382    for x in Map.keys():
383       Template = string.replace(Template,x,Map[x]);
384    return Template;
385
386 # The replay class uses a python DB (BSD db if avail) to implement
387 # protection against replay. Replay is an attacker capturing the
388 # plain text signed message and sending it back to the victim at some
389 # later date. Each signature has a unique signature ID (and signing 
390 # Key Fingerprint) as well as a timestamp. The first stage of replay
391 # protection is to ensure that the timestamp is reasonable, in particular
392 # not to far ahead or too far behind the current system time. The next
393 # step is to look up the signature + key fingerprint in the replay database
394 # and determine if it has been recived. The database is cleaned out 
395 # periodically and old signatures are discarded. By using a timestamp the
396 # database size is bounded to being within the range of the allowed times
397 # plus a little fuzz. The cache is serialized with a flocked lock file
398 class ReplayCache:
399    def __init__(self,Database):
400       self.Lock = open(Database + ".lock","w",0600);
401       fcntl.flock(self.Lock.fileno(),FCNTL.LOCK_EX);
402       self.DB = anydbm.open(Database,"c",0600);
403       self.CleanCutOff = CleanCutOff;
404       self.AgeCutOff = AgeCutOff;
405       self.FutureCutOff = FutureCutOff;
406       
407    # Close the cache and lock
408    def __del__(self):
409       self.close();
410    def close(self):
411       self.DB.close();
412       self.Lock.close();
413       
414    # Clean out any old signatures
415    def Clean(self):
416       CutOff = time.time() - self.CleanCutOff;
417       for x in self.DB.keys():
418          if int(self.DB[x]) <= CutOff:
419             del self.DB[x];
420     
421    # Check a signature. 'sig' is a 3 tuple that has the sigId, date and
422    # key ID
423    def Check(self,Sig):
424       if Sig[0] == None or Sig[1] == None or Sig[2] == None:
425          return "Invalid signature";
426       if int(Sig[1]) > time.time() + self.FutureCutOff:
427          return "Signature has a time too far in the future";
428       if self.DB.has_key(Sig[0] + '-' + Sig[2]):
429          return "Signature has already been received";
430       if int(Sig[1]) < time.time() - self.AgeCutOff:
431          return "Signature has passed the age cut off ";
432       # + str(int(Sig[1])) + ',' + str(time.time()) + "," + str(Sig);
433       return None;
434            
435    # Add a signature, the sig is the same as is given to Check
436    def Add(self,Sig):
437       if Sig[0] == None or Sig[1] == None:
438          raise RuntimeError,"Invalid signature";
439       if Sig[1] < time.time() - self.CleanCutOff:
440          return;
441       Key = Sig[0] + '-' + Sig[2]
442       if self.DB.has_key(Key):
443          if int(self.DB[Key]) < Sig[1]:
444             self.DB[Key] = str(int(Sig[1]));
445       else:
446          self.DB[Key] = str(int(Sig[1]));
447