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