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