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