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