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