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