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