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