ud-mailgate: minor refactoring
[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 is None and\
384       arecord is None and\
385       mxrecord is None and\
386       txtrecord is None and\
387       aaaarecord is None:
388      return None;
389
390    # Check if the name is already taken
391    G = re.match('^([-\w+]+)\s',Str)
392    if G is 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 is not None:
423      sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
424    elif txtrecord is not None:
425       sanitized = "%s IN TXT %s" % (hostname, txtrecord.group(1))
426    elif arecord is not 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 is not None:
433      priority = mxrecord.group(1)
434      mx = mxrecord.group(2)
435      sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
436    elif aaaarecord is not 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 def connect_to_ldap_and_check_if_locked(DnRecord):
558    # Connect to the ldap server
559    l = connectLDAP()
560    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
561    AccessPass = F.readline().strip().split(" ")
562    F.close();
563    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
564
565    # Check for a locked account
566    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
567    if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
568              or GetAttr(Attrs[0],"userPassword").startswith("!"):
569       raise UDNotAllowedError, "This account is locked";
570
571 # Handle an [almost] arbitary change
572 def HandleChange(Reply,DnRecord,Key):
573    global PlainText;
574    Lines = re.split("\n *\r?",PlainText);
575
576    Result = "";
577    Attrs = [];
578    Show = 0;
579    CommitChanges = 1
580    for Line in Lines: 
581       Line = Line.strip()
582       if Line == "":
583          continue;
584
585       # Try to process a command line
586       Result = Result + "> "+Line+"\n";
587       try:
588          if Line == "show":
589             Show = 1;
590             Res = "OK";
591          else:
592             badkeys = LoadBadSSH()
593             Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
594                   DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
595                   DoDel(Line,Attrs) or DoRBL(Line,Attrs) or DoConfirmSudopassword(Line)
596       except:
597          Res = None;
598          Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
599
600       # Fail, if someone tries to send someone elses signed email to the
601       # daemon then we want to abort ASAP.
602       if Res == None:
603          CommitChanges = 0
604          Result = Result + "Command is not understood. Halted - no changes committed\n";
605          break;
606       Result = Result + Res + "\n";
607
608    # Connect to the ldap server
609    l = connect_to_ldap_and_check_if_locked(DnRecord)
610
611    if CommitChanges == 1: # only if we are still good to go
612       try:
613          Res = FinishConfirmSudopassword(l, GetAttr(DnRecord,"uid"), Attrs)
614          Result = Result + Res + "\n";
615       except Error, e:
616          CommitChanges = 0
617          Result = Result + "FinishConfirmSudopassword raised an error (%s) - no changes committed\n"%(e);
618
619    # Modify the record
620    if CommitChanges == 1:
621       Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
622       l.modify_s(Dn,Attrs);
623
624    Attribs = "";
625    if Show == 1:
626       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
627       if len(Attrs) == 0:
628          raise UDNotAllowedError, "User not found"
629       Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
630
631    Subst = {};
632    Subst["__FROM__"] = ChangeFrom;
633    Subst["__EMAIL__"] = EmailAddress(DnRecord);
634    Subst["__ADMIN__"] = ReplyTo;
635    Subst["__RESULT__"] = Result;
636    Subst["__ATTR__"] = Attribs;
637
638    return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
639    
640 # Handle ping handles an email sent to the 'ping' address (ie this program
641 # called with a ping argument) It replies with a dump of the public records.
642 def HandlePing(Reply,DnRecord,Key):
643    Subst = {};
644    Subst["__FROM__"] = PingFrom;
645    Subst["__EMAIL__"] = EmailAddress(DnRecord);
646    Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
647    Subst["__ADMIN__"] = ReplyTo;
648
649    return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
650
651
652
653 def get_crypttype_preamble(key):
654    if (key[4] == 1):
655       type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
656    else:
657       type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
658              "mode, without IDEA. This message cannot be decoded using PGP 2.x";
659    return type
660
661 # Handle a change password email sent to the change password address
662 # (this program called with the chpass argument)
663 def HandleChPass(Reply,DnRecord,Key):
664    # Generate a random password
665    Password = GenPass();
666    Pass = HashPass(Password);
667
668    # Use GPG to encrypt it      
669    Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
670                         "0x"+Key[1],Key[4]);
671    Password = None;
672
673    if Message == None:
674       raise UDFormatError, "Unable to generate the encrypted reply, gpg failed.";
675
676    Subst = {};
677    Subst["__FROM__"] = ChPassFrom;
678    Subst["__EMAIL__"] = EmailAddress(DnRecord);
679    Subst["__CRYPTTYPE__"] = get_crypttype_preamble(Key)
680    Subst["__PASSWORD__"] = Message;
681    Subst["__ADMIN__"] = ReplyTo;
682    Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
683
684    l = connect_to_ldap_and_check_if_locked(DnRecord)
685    # Modify the password
686    Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass),
687           (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60)))];
688    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
689    l.modify_s(Dn,Rec);
690
691    return Reply;
692
693 # Start of main program
694
695 # Drop messages from a mailer daemon.
696 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
697    sys.exit(0);
698
699 ErrMsg = "Indeterminate Error";
700 ErrType = EX_TEMPFAIL;
701 try:
702    # Startup the replay cache
703    ErrType = EX_TEMPFAIL;
704    ErrMsg = "Failed to initialize the replay cache:";
705
706    # Get the email 
707    ErrType = EX_PERMFAIL;
708    ErrMsg = "Failed to understand the email or find a signature:";
709    Email = mimetools.Message(sys.stdin,0);
710    Msg = GetClearSig(Email);
711
712    ErrMsg = "Message is not PGP signed:"
713    if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
714       Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
715       raise UDFormatError, "No PGP signature";
716    
717    # Check the signature
718    ErrMsg = "Unable to check the signature or the signature was invalid:";
719    pgp = GPGCheckSig2(Msg[0])
720
721    if not pgp.ok:
722       raise UDFormatError, pgp.why
723       
724    if pgp.text is None:
725       raise UDFormatError, "Null signature text"
726
727    # Extract the plain message text in the event of mime encoding
728    global PlainText;
729    ErrMsg = "Problem stripping MIME headers from the decoded message"
730    if Msg[1] == 1:
731       try:
732          Index = pgp.text.index("\n\n") + 2
733       except ValueError:
734          Index = pgp.text.index("\n\r\n") + 3
735       PlainText = pgp.text[Index:]
736    else:
737       PlainText = pgp.text
738
739    # Connect to the ldap server
740    ErrType = EX_TEMPFAIL;
741    ErrMsg = "An error occured while performing the LDAP lookup";
742    global l;
743    l = connectLDAP()
744    l.simple_bind_s("","");
745
746    # Search for the matching key fingerprint
747    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + pgp.key_fpr)
748
749    ErrType = EX_PERMFAIL;
750    if len(Attrs) == 0:
751       raise UDFormatError, "Key not found"
752    if len(Attrs) != 1:
753       raise UDFormatError, "Oddly your key fingerprint is assigned to more than one account.."
754
755
756    # Check the signature against the replay cache
757    RC = ReplayCache(ReplayCacheFile);
758    RC.Clean();
759    ErrMsg = "The replay cache rejected your message. Check your clock!";
760    Rply = RC.Check(pgp.sig_info);
761    if Rply != None:
762       RC.close()
763       raise UDNotAllowedError, Rply;
764    RC.Add(pgp.sig_info);
765    RC.close()
766
767    # Determine the sender address
768    ErrMsg = "A problem occured while trying to formulate the reply";
769    Sender = Email.getheader("Reply-To");
770    if Sender == None:
771       Sender = Email.getheader("From");
772    if Sender == None:
773       raise UDFormatError, "Unable to determine the sender's address";
774
775    # Formulate a reply
776    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
777    Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
778
779    Res = l.search_s(HostBaseDn, ldap.SCOPE_SUBTREE, '(objectClass=debianServer)', ['hostname'] )
780    # Res is a list of tuples.
781    # The tuples contain a dn (str) and a dictionary.
782    # The dictionaries map the key "hostname" to a list.
783    # These lists contain a single hostname (str).
784    ValidHostNames = reduce(lambda a,b: a+b, [value.get("hostname", []) for (dn, value) in Res], [])
785
786    # Dispatch
787    if sys.argv[1] == "ping":
788       Reply = HandlePing(Reply,Attrs[0],pgp.key_info);
789    elif sys.argv[1] == "chpass":
790       if PlainText.strip().find("Please change my Debian password"):
791          Reply = HandleChPass(Reply,Attrs[0],pgp.key_info);
792       else:
793          raise UDFormatError,"Please send a signed message where the first line of text is the string 'Please change my Debian password' or some other string we accept here.";
794    elif sys.argv[1] == "change":
795       Reply = HandleChange(Reply,Attrs[0],pgp.key_info);
796    else:
797       print sys.argv;
798       raise UDFormatError, "Incorrect Invokation";
799
800    # Send the message through sendmail      
801    ErrMsg = "A problem occured while trying to send the reply";
802    Child = os.popen("/usr/sbin/sendmail -t","w");
803 #   Child = os.popen("cat","w");
804    Child.write(Reply);
805    if Child.close() != None:
806       raise UDExecuteError, "Sendmail gave a non-zero return code";
807
808 except:
809    # Error Reply Header
810    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
811    ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
812
813    # Error Body
814    Subst = {};
815    Subst["__ERROR__"] = ErrMsg;
816    Subst["__ADMIN__"] = ReplyTo;
817
818    Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
819    List = traceback.extract_tb(sys.exc_traceback);
820    if len(List) > 1:
821       Trace = Trace + "Python Stack Trace:\n";
822       for x in List:
823          Trace = Trace +  "   %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
824
825    Subst["__TRACE__"] = Trace;
826
827    # Try to send the bounce
828    try:
829       ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
830
831       Child = os.popen("/usr/sbin/sendmail -t -oi -f ''","w");
832       Child.write(ErrReplyHead);
833       Child.write(ErrReply);
834       if Child.close() != None:
835          raise UDExecuteError, "Sendmail gave a non-zero return code";
836    except:
837       sys.exit(EX_TEMPFAIL);
838       
839    if ErrType != EX_PERMFAIL:
840       sys.exit(ErrType);
841    sys.exit(0);
842
843 # vim:set et:
844 # vim:set ts=3:
845 # vim:set shiftwidth=3: