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