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