Do SSL when connecting to the ldap server.
[mirror/userdir-ldap.git] / ud-mailgate
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3
4 #   Prior copyright probably rmurray, troup, joey, jgg -- weasel 2008
5 #   Copyright (c) 2008 Peter Palfrader <peter@palfrader.org>
6 #   Copyright (c) 2008 Joerg Jaspert <joerg@debian.org>
7
8 import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, os, commands
9 import pwd, tempfile
10 from userdir_gpg import *
11 from userdir_ldap import *
12
13 # Error codes from /usr/include/sysexits.h
14 ReplyTo = ConfModule.replyto;
15 PingFrom = ConfModule.pingfrom;
16 ChPassFrom = ConfModule.chpassfrom;
17 ChangeFrom = ConfModule.changefrom;
18 ReplayCacheFile = ConfModule.replaycachefile;
19 SSHFingerprintFile = ConfModule.fingerprintfile
20
21 EX_TEMPFAIL = 75;
22 EX_PERMFAIL = 65;      # EX_DATAERR
23 Error = 'Message Error';
24 SeenKey = 0;
25 SeenDNS = 0;
26 mailRBL = {}
27 mailRHSBL = {}
28 mailWhitelist = {}
29 SeenList = {}
30 DNS = {}
31
32 SSHFingerprint = re.compile('^(\d+) ([0-9a-f\:]{47}) (.+)$')
33 SSHRSA1Match = re.compile('^^(.* )?\d+ \d+ \d+')
34
35 ArbChanges = {"c": "..",
36               "l": ".*",
37               "facsimileTelephoneNumber": ".*",
38               "telephoneNumber": ".*",
39               "postalAddress": ".*",
40               "postalCode": ".*",
41               "loginShell": ".*",
42               "emailForward": "^([^<>@]+@.+)?$",
43               "jabberJID": "^([^<>@]+@.+)?$",
44               "ircNick": ".*",
45               "icqUin": "^[0-9]*$",
46               "onVacation": ".*",
47               "labeledURI": ".*",
48               "birthDate": "^([0-9]{4})([01][0-9])([0-3][0-9])$",
49               "mailDisableMessage": ".*",
50               "mailGreylisting": "^(TRUE|FALSE)$",
51               "mailCallout": "^(TRUE|FALSE)$",
52               "VoIP": ".*",
53 };
54
55 DelItems = {"c": None,
56             "l": None,
57             "facsimileTelephoneNumber": None,
58             "telephoneNumber": None,
59             "postalAddress": None,
60             "postalCode": None,
61             "emailForward": None,
62             "ircNick": None,
63             "onVacation": None,
64             "labeledURI": None,
65             "latitude": None,
66             "longitude": None,
67             "icqUin": None,
68             "jabberJID": None,
69             "jpegPhoto": None,
70             "dnsZoneEntry": None,
71             "sshRSAAuthKey": None,
72             "sshDSAAuthKey": None,
73             "birthDate" : None,
74             "mailGreylisting": None,
75             "mailCallout": None,
76             "mailRBL": None,
77             "mailRHSBL": None,
78             "mailWhitelist": None,
79             "mailDisableMessage": None,
80             "VoIP": None,
81             };
82
83 # Decode a GPS location from some common forms
84 def LocDecode(Str,Dir):
85    # Check for Decimal degrees, DGM, or DGMS
86    if re.match("^[+-]?[\d.]+$",Str) != None:
87       return Str;
88
89    Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
90    
91    # Check for DDDxMM.MMMM where x = [nsew]
92    Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
93    if Match != None:
94       G = Match.groups();
95       Deg = G[0]; Min = G[2]; Dr = G[1];
96
97    # Check for DD.DD x 
98    Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
99    if Match != None:
100       G = Match.groups();
101       Deg = G[0]; Dr = G[1];
102
103    # Check for DD:MM.MM x 
104    Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
105    if Match != None:
106       G = Match.groups();
107       Deg = G[0]; Min = G[1]; Dr = G[2];
108
109    # Check for DD:MM:SS.SS x
110    Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
111    if Match != None:
112       G = Match.groups();
113       Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
114       
115    # Some simple checks
116    if float(Deg) > 180:
117       raise "Failed","Bad degrees";
118    if Min != None and float(Min) > 60:
119       raise "Failed","Bad minutes";
120    if Sec != None and float(Sec) > 60:
121       raise "Failed","Bad seconds";
122       
123    # Pad on an extra leading 0 to disambiguate small numbers
124    if len(Deg) <= 1 or Deg[1] == '.':
125       Deg = '0' + Deg;
126    if Min != None and (len(Min) <= 1 or Min[1] == '.'):
127       Min = '0' + Min;
128    if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
129       Sec = '0' + Sec;
130    
131    # Construct a DGM/DGMS type value from the components.
132    Res = "+"
133    if Dr == Dir[1]:
134       Res = "-";
135    Res = Res + Deg;
136    if Min != None:
137       Res = Res + Min;
138    if Sec != None:
139       Res = Res + Sec;
140    return Res;
141               
142 # Handle changing a set of arbitary fields
143 #  <field>: value
144 def DoArbChange(Str,Attrs):
145    Match = re.match("^([^ :]+): (.*)$",Str);
146    if Match == None:
147       return None;
148    G = Match.groups();
149
150    attrName = G[0].lower();
151    for i in ArbChanges.keys():
152       if i.lower() == attrName:
153          attrName = i;
154          break;
155    if ArbChanges.has_key(attrName) == 0:
156       return None;
157
158    if re.match(ArbChanges[attrName],G[1]) == None:
159       raise Error, "Item does not match the required format"+ArbChanges[attrName];
160
161 #   if attrName == 'birthDate':
162 #      (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
163 #    $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
164 #    if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
165 #      if ($bd_mo == 2) {
166 #        if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
167 #          $bd_ok = 1;
168 #        } elsif ($bd_day <= 28) {
169 #          $bd_ok = 1;
170 #        }
171 #      } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
172 #       if ($bd_day <= 30) {
173 #         $bd_ok = 1;
174 #       }
175 #      } else {
176 #       if ($bd_day <= 31) {
177 #         $bd_ok = 1;
178 #       }
179 #      }
180 #    }
181 #  } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
182 #    $bd_ok = 1;
183 #  }
184    Attrs.append((ldap.MOD_REPLACE,attrName,G[1]));
185    return "Changed entry %s to %s"%(attrName,G[1]);
186
187 # Handle changing a set of arbitary fields
188 #  <field>: value
189 def DoDel(Str,Attrs):
190    Match = re.match("^del (.*)$",Str);
191    if Match == None:
192       return None;
193    G = Match.groups();
194
195    attrName = G[0].lower();
196    for i in DelItems.keys():
197       if i.lower() == attrName:
198          attrName = i;
199          break;
200    if DelItems.has_key(attrName) == 0:
201       return "Cannot erase entry %s"%(attrName);
202
203    Attrs.append((ldap.MOD_DELETE,attrName,None));
204    return "Removed entry %s"%(attrName);
205
206 # Handle a position change message, the line format is:
207 #  Lat: -12412.23 Long: +12341.2342
208 def DoPosition(Str,Attrs):
209    Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
210    if Match == None:
211       return None;
212
213    G = Match.groups();
214    try:
215       sLat = LocDecode(G[0],"ns");
216       sLong = LocDecode(G[1],"ew");
217       Lat = DecDegree(sLat,1);
218       Long = DecDegree(sLong,1);
219    except:
220       raise Error, "Positions were found, but they are not correctly formed";
221
222    Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
223    Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
224    return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
225
226 # Load bad ssh fingerprints
227 def LoadBadSSH():
228    f = open(SSHFingerprintFile, "r")
229    bad = []
230    FingerprintLine = re.compile('^([0-9a-f\:]{47}).*$')
231    for line in f.readlines():
232       Match = FingerprintLine.match(line)
233       if Match is not None:
234          g = Match.groups()
235          bad.append(g[0])
236    return bad
237
238 # Handle an SSH authentication key, the line format is:
239 #  [options] 1024 35 13188913666680[..] [comment]
240 def DoSSH(Str, Attrs, badkeys, uid):
241    Match = SSH2AuthSplit.match(Str);
242    if Match == None:
243       return None;
244    g = Match.groups()
245    typekey = g[1]
246    if Match == None:
247       Match = SSHRSA1Match.match(Str)
248       if Match is not None:
249          return "RSA1 keys not supported anymore"
250       return None;
251
252    (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
253    f = open(path, "w")
254    f.write("%s\n" % (Str))
255    f.close()
256    cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
257    (result, output) = commands.getstatusoutput(cmd)
258    os.remove(path)
259    if (result != 0):
260       raise Error, "ssh-keygen -l invocation failed!\n%s\n" % (output)
261
262
263    # Head
264    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
265    ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
266    Subst = {}
267    Subst["__ADMIN__"] = ReplyTo
268    Subst["__USER__"] = uid
269
270    Match = SSHFingerprint.match(output)
271    g = Match.groups()
272
273    if int(g[0]) < 1024:
274       try:
275          # Body
276          Subst["__ERROR__"] = "SSH keysize %s is below limit 1024" % (g[0])
277          ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
278
279          Child = os.popen("/usr/sbin/sendmail -t","w")
280          Child.write(ErrReplyHead)
281          Child.write(ErrReply)
282          if Child.close() != None:
283             raise Error, "Sendmail gave a non-zero return code"
284       except:
285          sys.exit(EX_TEMPFAIL)
286
287       # And now break and stop processing input, which sends a reply to the user.
288       raise Error, "SSH keys must have at least 1024 bits, processing halted, NOTHING MODIFIED AT ALL"
289    elif g[1] in badkeys:
290       try:
291          # Body
292          Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
293          ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
294
295          Child = os.popen("/usr/sbin/sendmail -t","w")
296          Child.write(ErrReplyHead)
297          Child.write(ErrReply)
298          if Child.close() != None:
299             raise Error, "Sendmail gave a non-zero return code"
300       except:
301          sys.exit(EX_TEMPFAIL)
302
303       # And now break and stop processing input, which sends a reply to the user.
304       raise Error, "Submitted SSH Key known to be bad and insecure, processing halted, NOTHING MODIFIED AT ALL"
305
306    if (typekey == "dss"):
307       return "DSA keys not accepted anymore"
308
309    global SeenKey;
310    if SeenKey:
311      Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
312      return "SSH Key added "+FormatSSHAuth(Str);
313       
314    Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
315    SeenKey = 1;
316    return "SSH Keys replaced with "+FormatSSHAuth(Str);
317
318 # Handle changing a dns entry
319 #  host IN A     12.12.12.12
320 #  host IN AAAA  1234::5678
321 #  host IN CNAME foo.bar.    <- Trailing dot is required
322 #  host IN MX    foo.bar.    <- Trailing dot is required
323 def DoDNS(Str,Attrs,DnRecord):
324    cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
325    arecord     = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
326    mxrecord    = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
327    #aaaarecord  = re.match('^[-\w]+\s+IN\s+AAAA\s+((?:[0-9a-f]{1,4})(?::[0-9a-f]{1,4})*(?::(?:(?::[0-9a-f]{1,4})*|:))?)$',Str,re.IGNORECASE)
328    aaaarecord  = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
329
330    if cnamerecord == None and\
331       arecord == None and\
332       mxrecord == None and\
333       aaaarecord == None:
334      return None;
335
336    # Check if the name is already taken
337    G = re.match('^([-\w+]+)\s',Str)
338    if G == None:
339      raise Error, "Hostname not found although we already passed record syntax checks"
340    hostname = G.group(1)
341
342    # Check for collisions
343    global l;
344    # [JT 20070409 - search for both tab and space suffixed hostnames
345    #  since we accept either.  It'd probably be better to parse the
346    #  incoming string in order to construct what we feed LDAP rather
347    #  than just passing it through as is.]
348    filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
349    Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
350    for x in Rec:
351       if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
352          return "DNS entry is already owned by " + GetAttr(x,"uid")
353
354    global SeenDNS;
355    global DNS;
356
357    if cnamerecord:
358      if DNS.has_key(hostname):
359        return "CNAME and other RR types not allowed: "+Str
360      else:
361        DNS[hostname] = 2
362    else:
363      if DNS.has_key(hostname) and DNS[hostname] == 2:
364        return "CNAME and other RR types not allowed: "+Str
365      else:
366        DNS[hostname] = 1
367
368    if cnamerecord != None:
369      sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
370    elif arecord != None:
371      ipaddress = arecord.group(1)
372      for quad in ipaddress.split('.'):
373        if not (int(quad) >=0 and int(quad) <= 255):
374          return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
375      sanitized = "%s IN A %s"% (hostname, ipaddress)
376    elif mxrecord != None:
377      priority = mxrecord.group(1)
378      mx = mxrecord.group(2)
379      sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
380    elif aaaarecord != None:
381      ipv6address = aaaarecord.group(1)
382      parts = ipv6address.split(':')
383      if len(parts) > 8:
384        return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
385      if len(parts) <= 2:
386        return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
387      if parts[0] == "":
388        parts.pop(0)
389      if parts[-1] == "":
390        parts.pop(-1)
391      seenEmptypart = False
392      for p in parts:
393        if len(p) > 4:
394          return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
395        if p == "":
396          if seenEmptypart:
397            return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
398          seenEmptypart = True
399      sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
400    else:
401      raise Error, "None of the types I recognize was it.  I shouldn't be here.  confused."
402
403    if SeenDNS:
404      Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
405      return "DNS Entry added "+sanitized;
406
407    Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
408    SeenDNS = 1;
409    return "DNS Entry replaced with "+sanitized;
410
411 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
412 def DoRBL(Str,Attrs):
413    Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
414    if Match == None:
415       return None
416    
417    if Match.group(1) == "rbl":
418       Key = "mailRBL"
419    if Match.group(1) == "rhsbl":
420       Key = "mailRHSBL"
421    if Match.group(1) == "whitelist":
422       Key = "mailWhitelist"
423    Host = Match.group(2)
424
425    global SeenList
426    if SeenList.has_key(Key):
427      Attrs.append((ldap.MOD_ADD,Key,Host))
428      return "%s added %s" % (Key,Host)
429       
430    Attrs.append((ldap.MOD_REPLACE,Key,Host))
431    SeenList[Key] = 1;
432    return "%s replaced with %s" % (Key,Host)
433
434 # Handle an [almost] arbitary change
435 def HandleChange(Reply,DnRecord,Key):
436    global PlainText;
437    Lines = re.split("\n *\r?",PlainText);
438
439    Result = "";
440    Attrs = [];
441    Show = 0;
442    for Line in Lines: 
443       Line = Line.strip()
444       if Line == "":
445          continue;
446
447       # Try to process a command line
448       Result = Result + "> "+Line+"\n";
449       try:
450          if Line == "show":
451             Show = 1;
452             Res = "OK";
453          else:
454             badkeys = LoadBadSSH()
455             Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
456                   DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
457                   DoDel(Line,Attrs) or DoRBL(Line,Attrs)
458       except:
459          Res = None;
460          Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
461          
462       # Fail, if someone tries to send someone elses signed email to the
463       # daemon then we want to abort ASAP.
464       if Res == None:
465          Result = Result + "Command is not understood. Halted\n";
466          break;
467       Result = Result + Res + "\n";
468
469    # Connect to the ldap server
470    l = connectLDAP()
471    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
472    AccessPass = F.readline().strip().split(" ")
473    F.close();
474
475    # Modify the record
476    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
477    oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
478    if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1) 
479        or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
480       raise Error, "This account is locked";
481    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
482    l.modify_s(Dn,Attrs);
483
484    Attribs = "";
485    if Show == 1:
486       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
487       if len(Attrs) == 0:
488          raise Error, "User not found"
489       Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
490       
491    Subst = {};
492    Subst["__FROM__"] = ChangeFrom;
493    Subst["__EMAIL__"] = EmailAddress(DnRecord);
494    Subst["__ADMIN__"] = ReplyTo;
495    Subst["__RESULT__"] = Result;
496    Subst["__ATTR__"] = Attribs;
497
498    return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
499    
500 # Handle ping handles an email sent to the 'ping' address (ie this program
501 # called with a ping argument) It replies with a dump of the public records.
502 def HandlePing(Reply,DnRecord,Key):
503    Subst = {};
504    Subst["__FROM__"] = PingFrom;
505    Subst["__EMAIL__"] = EmailAddress(DnRecord);
506    Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
507    Subst["__ADMIN__"] = ReplyTo;
508
509    return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
510
511 # Handle a change password email sent to the change password address
512 # (this program called with the chpass argument)
513 def HandleChPass(Reply,DnRecord,Key):
514    # Generate a random password
515    Password = GenPass();
516    Pass = HashPass(Password);
517       
518    # Use GPG to encrypt it      
519    Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
520                         "0x"+Key[1],Key[4]);
521    Password = None;
522
523    if Message == None:
524       raise Error, "Unable to generate the encrypted reply, gpg failed.";
525
526    if (Key[4] == 1):
527       Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
528    else:
529       Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
530              "mode, without IDEA. This message cannot be decoded using PGP 2.x";
531    
532    Subst = {};
533    Subst["__FROM__"] = ChPassFrom;
534    Subst["__EMAIL__"] = EmailAddress(DnRecord);
535    Subst["__CRYPTTYPE__"] = Type;
536    Subst["__PASSWORD__"] = Message;
537    Subst["__ADMIN__"] = ReplyTo;
538    Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
539    
540    # Connect to the ldap server
541    l = connectLDAP()
542    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
543    AccessPass = F.readline().strip().split(" ")
544    F.close();
545    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
546
547    # Check for a locked account
548    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
549    if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
550              or GetAttr(Attrs[0],"userPassword").startswith("!"):
551       raise Error, "This account is locked";
552
553    # Modify the password
554    Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass),
555           (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60)))];
556    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
557    l.modify_s(Dn,Rec);
558
559    return Reply;
560       
561 # Start of main program
562
563 # Drop messages from a mailer daemon.
564 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
565    sys.exit(0);
566
567 ErrMsg = "Indeterminate Error";
568 ErrType = EX_TEMPFAIL;
569 try:
570    # Startup the replay cache
571    ErrType = EX_TEMPFAIL;
572    ErrMsg = "Failed to initialize the replay cache:";
573    RC = ReplayCache(ReplayCacheFile);
574    RC.Clean();
575
576    # Get the email 
577    ErrType = EX_PERMFAIL;
578    ErrMsg = "Failed to understand the email or find a signature:";
579    Email = mimetools.Message(sys.stdin,0);
580    Msg = GetClearSig(Email);
581
582    ErrMsg = "Message is not PGP signed:"
583    if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
584       Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
585       raise Error, "No PGP signature";
586    
587    # Check the signature
588    ErrMsg = "Unable to check the signature or the signature was invalid:";
589    Res = GPGCheckSig(Msg[0]);
590
591    if Res[0] != None:
592       raise Error, Res[0];
593       
594    if Res[3] == None:
595       raise Error, "Null signature text";
596
597    # Extract the plain message text in the event of mime encoding
598    global PlainText;
599    ErrMsg = "Problem stripping MIME headers from the decoded message"
600    if Msg[1] == 1:
601       try:
602          Index = Res[3].index("\n\n") + 2;
603       except ValueError:
604          Index = Res[3].index("\n\r\n") + 3;
605       PlainText = Res[3][Index:];
606    else:
607       PlainText = Res[3];   
608
609    # Check the signature against the replay cache
610    ErrMsg = "The replay cache rejected your message. Check your clock!";
611    Rply = RC.Check(Res[1]);
612    if Rply != None:
613       raise Error, Rply;
614
615    # Connect to the ldap server
616    ErrType = EX_TEMPFAIL;
617    ErrMsg = "An error occured while performing the LDAP lookup";
618    global l;
619    l = connectLDAP()
620    l.simple_bind_s("","");
621
622    # Search for the matching key fingerprint
623    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
624
625    ErrType = EX_PERMFAIL;
626    if len(Attrs) == 0:
627       raise Error, "Key not found"
628    if len(Attrs) != 1:
629       raise Error, "Oddly your key fingerprint is assigned to more than one account.."
630
631    RC.Add(Res[1]);
632
633    # Determine the sender address
634    ErrMsg = "A problem occured while trying to formulate the reply";
635    Sender = Email.getheader("Reply-To");
636    if Sender == None:
637       Sender = Email.getheader("From");
638    if Sender == None:
639       raise Error, "Unable to determine the sender's address";
640
641    # Formulate a reply
642    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
643    Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
644
645    # Dispatch
646    if sys.argv[1] == "ping":
647       Reply = HandlePing(Reply,Attrs[0],Res[2]);
648    elif sys.argv[1] == "chpass":
649       if PlainText.strip().find("Please change my Debian password") != 0:
650          raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
651       Reply = HandleChPass(Reply,Attrs[0],Res[2]);
652    elif sys.argv[1] == "change":
653       Reply = HandleChange(Reply,Attrs[0],Res[2]);
654    else:
655       print sys.argv;
656       raise Error, "Incorrect Invokation";
657
658    # Send the message through sendmail      
659    ErrMsg = "A problem occured while trying to send the reply";
660    Child = os.popen("/usr/sbin/sendmail -t","w");
661 #   Child = os.popen("cat","w");
662    Child.write(Reply);
663    if Child.close() != None:
664       raise Error, "Sendmail gave a non-zero return code";
665
666 except:
667    # Error Reply Header
668    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
669    ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
670
671    # Error Body
672    Subst = {};
673    Subst["__ERROR__"] = ErrMsg;
674    Subst["__ADMIN__"] = ReplyTo;
675
676    Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
677    List = traceback.extract_tb(sys.exc_traceback);
678    if len(List) > 1:
679       Trace = Trace + "Python Stack Trace:\n";
680       for x in List:
681          Trace = Trace +  "   %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
682
683    Subst["__TRACE__"] = Trace;
684
685    # Try to send the bounce
686    try:
687       ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
688
689       Child = os.popen("/usr/sbin/sendmail -t","w");
690       Child.write(ErrReplyHead);
691       Child.write(ErrReply);
692       if Child.close() != None:
693          raise Error, "Sendmail gave a non-zero return code";
694    except:
695       sys.exit(EX_TEMPFAIL);
696       
697    if ErrType != EX_PERMFAIL:
698       sys.exit(ErrType);
699    sys.exit(0);
700