Get rid of semicolons
[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'
106    Min = None
107    Sec = None
108    Dr = Dir[0]
109    
110    # Check for DDDxMM.MMMM where x = [nsew]
111    Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str)
112    if Match != None:
113       G = Match.groups()
114       Deg = G[0]
115       Min = G[2]
116       Dr = G[1]
117
118    # Check for DD.DD x 
119    Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str)
120    if Match != None:
121       G = Match.groups()
122       Deg = G[0]
123       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]
130       Min = G[1]
131       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]
138       Min = G[1]
139       Sec = G[2]
140       Dr = G[3]
141       
142    # Some simple checks
143    if float(Deg) > 180:
144       raise UDFormatError, "Bad degrees"
145    if Min != None and float(Min) > 60:
146       raise UDFormatError, "Bad minutes"
147    if Sec != None and float(Sec) > 60:
148       raise UDFormatError, "Bad seconds"
149       
150    # Pad on an extra leading 0 to disambiguate small numbers
151    if len(Deg) <= 1 or Deg[1] == '.':
152       Deg = '0' + Deg
153    if Min != None and (len(Min) <= 1 or Min[1] == '.'):
154       Min = '0' + Min
155    if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
156       Sec = '0' + Sec
157    
158    # Construct a DGM/DGMS type value from the components.
159    Res = "+"
160    if Dr == Dir[1]:
161       Res = "-"
162    Res = Res + Deg
163    if Min != None:
164       Res = Res + Min
165    if Sec != None:
166       Res = Res + Sec
167    return Res
168               
169 # Handle changing a set of arbitary fields
170 #  <field>: value
171 def DoArbChange(Str,Attrs):
172    Match = re.match("^([^ :]+): (.*)$",Str)
173    if Match == None:
174       return None
175    G = Match.groups()
176
177    attrName = G[0].lower()
178    for i in ArbChanges.keys():
179       if i.lower() == attrName:
180          attrName = i
181          break
182    if ArbChanges.has_key(attrName) == 0:
183       return None
184
185    if re.match(ArbChanges[attrName],G[1]) == None:
186       raise UDFormatError, "Item does not match the required format"+ArbChanges[attrName]
187
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          if m not in ValidHostNames:
297             return "unknown machine {} used in allowed_hosts stanza for ssh keys".format(m)
298
299    (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
300    f = open(path, "w")
301    f.write("%s\n" % (Str))
302    f.close()
303    cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
304    (result, output) = commands.getstatusoutput(cmd)
305    os.remove(path)
306    if (result != 0):
307       raise UDExecuteError, "ssh-keygen -l invocation failed!\n%s\n" % (output)
308
309    # format the string again for ldap:
310    if machines:
311       Str = "allowed_hosts=%s %s" % (",".join(machines), Str)
312
313
314    # Head
315    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
316    ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
317    Subst = {}
318    Subst["__ADMIN__"] = ReplyTo
319    Subst["__USER__"] = uid
320
321    Match = SSHFingerprint.match(output)
322    if Match is None:
323       return "Failed to match SSH fingerprint, has the output of ssh-keygen changed?"
324    g = Match.groups()
325    key_size = g[0]
326    fingerprint = g[1]
327
328    if typekey == "rsa":
329       key_size_ok = (int(key_size) >= 2048)
330    elif typekey == "ed25519":
331      key_size_ok = True
332    else:
333      key_size_ok = False
334
335    if not key_size_ok:
336       return "SSH key fails formal criteria, not added.  We only accept RSA keys (>= 2048 bits) or ed25519 keys."
337    elif fingerprint in badkeys:
338       try:
339          # Body
340          Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
341          ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
342
343          Child = os.popen("/usr/sbin/sendmail -t","w")
344          Child.write(ErrReplyHead)
345          Child.write(ErrReply)
346          if Child.close() != None:
347             raise UDExecuteError, "Sendmail gave a non-zero return code"
348       except:
349          sys.exit(EX_TEMPFAIL)
350
351       # And now break and stop processing input, which sends a reply to the user.
352       raise UDFormatError, "Submitted SSH Key known to be bad and insecure, processing halted, NOTHING MODIFIED AT ALL"
353
354    global SeenKey
355    if SeenKey:
356      Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str))
357      return "SSH Key added: %s %s [%s]"%(key_size, fingerprint, FormatSSHAuth(Str))
358
359    Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str))
360    SeenKey = 1
361    return "SSH Keys replaced with: %s %s [%s]"%(key_size, fingerprint, FormatSSHAuth(Str))
362
363 # Handle changing a dns entry
364 #  host IN A     12.12.12.12
365 #  host IN AAAA  1234::5678
366 #  host IN CNAME foo.bar.    <- Trailing dot is required
367 #  host IN MX    foo.bar.    <- Trailing dot is required
368 def DoDNS(Str,Attrs,DnRecord):
369    cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
370    arecord     = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
371    mxrecord    = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
372    txtrecord   = re.match("^[-\w]+\s+IN\s+TXT\s+([-\d. a-z\t<>@:]+)", Str, re.IGNORECASE)
373    #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)
374    aaaarecord  = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
375
376    if cnamerecord is None and\
377       arecord is None and\
378       mxrecord is None and\
379       txtrecord is None and\
380       aaaarecord is None:
381      return None
382
383    # Check if the name is already taken
384    G = re.match('^([-\w+]+)\s',Str)
385    if G is None:
386      raise UDFormatError, "Hostname not found although we already passed record syntax checks"
387    hostname = G.group(1)
388
389    # Check for collisions
390    global l
391    # [JT 20070409 - search for both tab and space suffixed hostnames
392    #  since we accept either.  It'd probably be better to parse the
393    #  incoming string in order to construct what we feed LDAP rather
394    #  than just passing it through as is.]
395    filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
396    Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"])
397    for x in Rec:
398       if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
399          return "DNS entry is already owned by " + GetAttr(x,"uid")
400
401    global SeenDNS
402    global DNS
403
404    if cnamerecord:
405      if DNS.has_key(hostname):
406        return "CNAME and other RR types not allowed: "+Str
407      else:
408        DNS[hostname] = 2
409    else:
410      if DNS.has_key(hostname) and DNS[hostname] == 2:
411        return "CNAME and other RR types not allowed: "+Str
412      else:
413        DNS[hostname] = 1
414
415    if cnamerecord is not None:
416      sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
417    elif txtrecord is not None:
418       sanitized = "%s IN TXT %s" % (hostname, txtrecord.group(1))
419    elif arecord is not 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 is not None:
426      priority = mxrecord.group(1)
427      mx = mxrecord.group(2)
428      sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
429    elif aaaarecord is not 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, SudoPasswd):
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    SudoPasswd[uuid] = (hosts, hmac)
494    return "got confirm for sudo password %s on host(s) %s, auth code %s" % (uuid,hosts, hmac)
495
496 def FinishConfirmSudopassword(l, uid, Attrs, SudoPasswd):
497    result = "\n"
498
499    if len(SudoPasswd) == 0:
500        return None
501
502    res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+uid, ['sudoPassword'])
503    if len(res) != 1:
504       raise UDFormatError, "Not exactly one hit when searching for user"
505    if res[0][1].has_key('sudoPassword'):
506       inldap = res[0][1]['sudoPassword']
507    else:
508       inldap = []
509
510    newldap = []
511    for entry in inldap:
512       Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*-]+) ([^ ]+)$').match(entry)
513       if Match == None:
514          raise UDFormatError, "Could not parse existing sudopasswd entry"
515       uuid = Match.group(1)
516       status = Match.group(2)
517       hosts = Match.group(3)
518       cryptedpass = Match.group(4)
519
520       if SudoPasswd.has_key(uuid):
521          confirmedHosts = SudoPasswd[uuid][0]
522          confirmedHmac = SudoPasswd[uuid][1]
523          if status.startswith('confirmed:'):
524             if status == 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass):
525                result = result + "Entry %s for sudo password on hosts %s already confirmed.\n"%(uuid, hosts)
526             else:
527                result = result + "Entry %s for sudo password on hosts %s is listed as confirmed, but HMAC does not verify.\n"%(uuid, hosts)
528          elif confirmedHosts != hosts:
529             result = result + "Entry %s hostlist mismatch (%s vs. %s).\n"%(uuid, hosts, confirmedHosts)
530          elif make_passwd_hmac('confirm-new-password', 'sudo', uid, uuid, hosts, cryptedpass) == confirmedHmac:
531             result = result + "Entry %s for sudo password on hosts %s now confirmed.\n"%(uuid, hosts)
532             status = 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass)
533          else:
534             result = result + "Entry %s for sudo password on hosts %s HMAC verify failed.\n"%(uuid, hosts)
535          del SudoPasswd[uuid]
536
537       newentry = " ".join([uuid, status, hosts, cryptedpass])
538       if len(newldap) == 0:
539          newldap.append((ldap.MOD_REPLACE,"sudoPassword",newentry))
540       else:
541          newldap.append((ldap.MOD_ADD,"sudoPassword",newentry))
542
543    for entry in SudoPasswd:
544       result = result + "Entry %s that you confirm is not listed in ldap."%(entry)
545
546    for entry in newldap:
547       Attrs.append(entry)
548
549    return result
550
551 def connect_to_ldap_and_check_if_locked(DnRecord):
552    # Connect to the ldap server
553    l = connectLDAP()
554    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r")
555    AccessPass = F.readline().strip().split(" ")
556    F.close()
557    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1])
558
559    # Check for a locked account
560    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"))
561    if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
562              or GetAttr(Attrs[0],"userPassword").startswith("!"):
563       raise UDNotAllowedError, "This account is locked"
564
565    return l
566
567 # Handle an [almost] arbitary change
568 def HandleChange(Reply,DnRecord,Key):
569    global PlainText
570    Lines = re.split("\n *\r?",PlainText)
571
572    Result = ""
573    Attrs = []
574    SudoPasswd = {}
575    Show = 0
576    CommitChanges = 1
577    for Line in Lines: 
578       Line = Line.strip()
579       if Line == "":
580          continue
581
582       # Try to process a command line
583       Result = Result + "> "+Line+"\n"
584       try:
585          if Line == "show":
586             Show = 1
587             Res = "OK"
588          else:
589             badkeys = LoadBadSSH()
590             Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
591                   DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
592                   DoDel(Line,Attrs) or DoRBL(Line,Attrs) or DoConfirmSudopassword(Line, SudoPasswd)
593       except:
594          Res = None
595          Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value)
596
597       # Fail, if someone tries to send someone elses signed email to the
598       # daemon then we want to abort ASAP.
599       if Res == None:
600          CommitChanges = 0
601          Result = Result + "Command is not understood. Halted - no changes committed\n"
602          break
603       Result += Res + "\n"
604
605    # Connect to the ldap server
606    l = connect_to_ldap_and_check_if_locked(DnRecord)
607
608    if CommitChanges == 1 and len(SudoPasswd) > 0: # only if we are still good to go
609       try:
610          Res = FinishConfirmSudopassword(l, GetAttr(DnRecord,"uid"), Attrs, SudoPasswd)
611          if Res is not None:
612             Result = Result + Res + "\n"
613       except Error, e:
614          CommitChanges = 0
615          Result = Result + "FinishConfirmSudopassword raised an error (%s) - no changes committed\n"%(e)
616
617    if CommitChanges == 1 and len(Attrs) > 0:
618       Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn
619       l.modify_s(Dn,Attrs)
620
621    Attribs = ""
622    if Show == 1:
623       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"))
624       if len(Attrs) == 0:
625          raise UDNotAllowedError, "User not found"
626       Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4])
627
628    Subst = {}
629    Subst["__FROM__"] = ChangeFrom
630    Subst["__EMAIL__"] = EmailAddress(DnRecord)
631    Subst["__ADMIN__"] = ReplyTo
632    Subst["__RESULT__"] = Result
633    Subst["__ATTR__"] = Attribs
634
635    return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read())
636    
637 # Handle ping handles an email sent to the 'ping' address (ie this program
638 # called with a ping argument) It replies with a dump of the public records.
639 def HandlePing(Reply,DnRecord,Key):
640    Subst = {}
641    Subst["__FROM__"] = PingFrom
642    Subst["__EMAIL__"] = EmailAddress(DnRecord)
643    Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord)
644    Subst["__ADMIN__"] = ReplyTo
645
646    return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read())
647
648
649
650 def get_crypttype_preamble(key):
651    if (key[4] == 1):
652       type = "Your message was encrypted using PGP 2.x\ncompatibility mode."
653    else:
654       type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
655              "mode, without IDEA. This message cannot be decoded using PGP 2.x"
656    return type
657
658 # Handle a change password email sent to the change password address
659 # (this program called with the chpass argument)
660 def HandleChPass(Reply,DnRecord,Key):
661    # Generate a random password
662    Password = GenPass()
663    Pass = HashPass(Password)
664
665    # Use GPG to encrypt it      
666    Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
667                         "0x"+Key[1],Key[4])
668    Password = None
669
670    if Message == None:
671       raise UDFormatError, "Unable to generate the encrypted reply, gpg failed."
672
673    Subst = {}
674    Subst["__FROM__"] = ChPassFrom
675    Subst["__EMAIL__"] = EmailAddress(DnRecord)
676    Subst["__CRYPTTYPE__"] = get_crypttype_preamble(Key)
677    Subst["__PASSWORD__"] = Message
678    Subst["__ADMIN__"] = ReplyTo
679    Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read())
680
681    l = connect_to_ldap_and_check_if_locked(DnRecord)
682    # Modify the password
683    Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass),
684           (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60)))]
685    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn
686    l.modify_s(Dn,Rec)
687
688    return Reply
689
690 def HandleChTOTPSeed(Reply, DnRecord, Key):
691    # Generate a random seed
692    seed = binascii.hexlify(open("/dev/urandom", "r").read(32))
693    msg = GPGEncrypt("Your new TOTP seed is '%s'\n" % (seed,), "0x"+Key[1],Key[4])
694
695    if msg is None:
696       raise UDFormatError, "Unable to generate the encrypted reply, gpg failed."
697
698    Subst = {}
699    Subst["__FROM__"] = ChPassFrom
700    Subst["__EMAIL__"] = EmailAddress(DnRecord)
701    Subst["__PASSWORD__"] = msg
702    Subst["__ADMIN__"] = ReplyTo
703    Reply = Reply + TemplateSubst(Subst, open(TemplatesDir+"totp-seed-changed", "r").read())
704
705    l = connect_to_ldap_and_check_if_locked(DnRecord)
706    # Modify the password
707    Rec = [(ldap.MOD_REPLACE, "totpSeed", seed)]
708    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn
709    l.modify_s(Dn,Rec)
710    return Reply
711
712 def HandleChKrbPass(Reply,DnRecord,Key):
713    # Connect to the ldap server, will throw an exception if account locked.
714    l = connect_to_ldap_and_check_if_locked(DnRecord)
715
716    user = GetAttr(DnRecord,"uid")
717    krb_proc = subprocess.Popen( ('ud-krb-reset', user), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
718    krb_proc.stdin.close()
719    out = krb_proc.stdout.readlines()
720    krb_proc.wait()
721    exitcode = krb_proc.returncode
722
723    # Use GPG to encrypt it
724    m = "Tried to reset your kerberos principal's password.\n"
725    if exitcode == 0:
726       m += "The exitcode of the reset script was zero, indicating that everything\n"
727       m += "worked.  However, this being software who knows.  Script's output below."
728    else:
729       m += "The exitcode of the reset script was %d, indicating that something\n"%(exitcode)
730       m += "went terribly, terribly wrong.  Please consult the script's output below\n"
731       m += "for more information.  Contact the admins if you have any questions or\n"
732       m += "require assitance."
733
734    m += "\n"+''.join( map(lambda x: "| "+x, out)  )
735
736    Message = GPGEncrypt(m, "0x"+Key[1],Key[4])
737    if Message == None:
738       raise UDFormatError, "Unable to generate the encrypted reply, gpg failed."
739
740    Subst = {}
741    Subst["__FROM__"] = ChPassFrom
742    Subst["__EMAIL__"] = EmailAddress(DnRecord)
743    Subst["__CRYPTTYPE__"] = get_crypttype_preamble(Key)
744    Subst["__PASSWORD__"] = Message
745    Subst["__ADMIN__"] = ReplyTo
746    Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read())
747
748    return Reply
749
750 # Start of main program
751
752 # Drop messages from a mailer daemon.
753 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
754    sys.exit(0)
755
756 ErrMsg = "Indeterminate Error"
757 ErrType = EX_TEMPFAIL
758 try:
759    # Startup the replay cache
760    ErrType = EX_TEMPFAIL
761    ErrMsg = "Failed to initialize the replay cache:"
762
763    # Get the email 
764    ErrType = EX_PERMFAIL
765    ErrMsg = "Failed to understand the email or find a signature:"
766    mail = email.parser.Parser().parse(sys.stdin)
767    Msg = GetClearSig(mail)
768
769    ErrMsg = "Message is not PGP signed:"
770    if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
771       Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
772       raise UDFormatError, "No PGP signature"
773    
774    # Check the signature
775    ErrMsg = "Unable to check the signature or the signature was invalid:"
776    pgp = GPGCheckSig2(Msg[0])
777
778    if not pgp.ok:
779       raise UDFormatError, pgp.why
780       
781    if pgp.text is None:
782       raise UDFormatError, "Null signature text"
783
784    # Extract the plain message text in the event of mime encoding
785    global PlainText
786    ErrMsg = "Problem stripping MIME headers from the decoded message"
787    if Msg[1] == 1:
788       e = email.parser.Parser().parsestr(pgp.text)
789       PlainText = e.get_payload(decode=True)
790    else:
791       PlainText = pgp.text
792
793    # Connect to the ldap server
794    ErrType = EX_TEMPFAIL
795    ErrMsg = "An error occured while performing the LDAP lookup"
796    global l
797    l = connectLDAP()
798    l.simple_bind_s("","")
799
800    # Search for the matching key fingerprint
801    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + pgp.key_fpr)
802
803    ErrType = EX_PERMFAIL
804    if len(Attrs) == 0:
805       raise UDFormatError, "Key not found"
806    if len(Attrs) != 1:
807       raise UDFormatError, "Oddly your key fingerprint is assigned to more than one account.."
808
809
810    # Check the signature against the replay cache
811    RC = ReplayCache(ReplayCacheFile)
812    RC.process(pgp.sig_info)
813
814    # Determine the sender address
815    ErrMsg = "A problem occured while trying to formulate the reply"
816    Sender = mail['Reply-To']
817    if not Sender: Sender = mail['From']
818    if not Sender: 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       elif PlainText.strip().find("Please change my TOTP seed") >= 0:
840          Reply = HandleChTOTPSeed(Reply, Attrs[0], pgp.key_info)
841       else:
842          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."
843    elif sys.argv[1] == "change":
844       Reply = HandleChange(Reply,Attrs[0],pgp.key_info)
845    else:
846       print sys.argv
847       raise UDFormatError, "Incorrect Invokation"
848
849    # Send the message through sendmail      
850    ErrMsg = "A problem occured while trying to send the reply"
851    Child = os.popen("/usr/sbin/sendmail -t","w")
852 #   Child = os.popen("cat","w")
853    Child.write(Reply)
854    if Child.close() != None:
855       raise UDExecuteError, "Sendmail gave a non-zero return code"
856
857 except:
858    # Error Reply Header
859    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
860    ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date)
861
862    # Error Body
863    Subst = {}
864    Subst["__ERROR__"] = ErrMsg
865    Subst["__ADMIN__"] = ReplyTo
866
867    Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value)
868    List = traceback.extract_tb(sys.exc_traceback)
869    if len(List) > 1:
870       Trace = Trace + "Python Stack Trace:\n"
871       for x in List:
872          Trace = Trace +  "   %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3])
873
874    Subst["__TRACE__"] = Trace
875
876    # Try to send the bounce
877    try:
878       ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read())
879
880       Child = os.popen("/usr/sbin/sendmail -t -oi -f ''","w")
881       Child.write(ErrReplyHead)
882       Child.write(ErrReply)
883       if Child.close() != None:
884          raise UDExecuteError, "Sendmail gave a non-zero return code"
885    except:
886       sys.exit(EX_TEMPFAIL)
887       
888    if ErrType != EX_PERMFAIL:
889       sys.exit(ErrType)
890    sys.exit(0)
891
892 # vim:set et:
893 # vim:set ts=3:
894 # vim:set shiftwidth=3: