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