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