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