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