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