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