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