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>
10 import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, os, commands
13 import email, email.parser
16 from userdir_gpg import *
17 from userdir_ldap import *
18 from userdir_exceptions import *
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
28 UUID_FORMAT = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
31 EX_PERMFAIL = 65; # EX_DATAERR
32 Error = 'Message Error';
40 ValidHostNames = [] # will be initialized in later
42 SSHFingerprint = re.compile('^(\d+) ([0-9a-f\:]{47}) (.+)$')
43 SSHRSA1Match = re.compile('^^(.* )?\d+ \d+ \d+')
45 GenderTable = {"male": '1',
53 ArbChanges = {"c": "..",
55 "facsimileTelephoneNumber": ".*",
56 "telephoneNumber": ".*",
57 "postalAddress": ".*",
61 "emailForward": "^([^<>@]+@.+)?$",
62 "jabberJID": "^([^<>@]+@.+)?$",
67 "birthDate": "^([0-9]{4})([01][0-9])([0-3][0-9])$",
68 "mailDisableMessage": ".*",
69 "mailGreylisting": "^(TRUE|FALSE)$",
70 "mailCallout": "^(TRUE|FALSE)$",
71 "mailDefaultOptions": "^(TRUE|FALSE)$",
73 "gender": "^(1|2|9|male|female|unspecified)$",
74 "mailContentInspectionAction": "^(reject|blackhole|markup)$",
77 DelItems = {"c": None,
79 "facsimileTelephoneNumber": None,
80 "telephoneNumber": None,
81 "postalAddress": None,
94 "sshRSAAuthKey": None,
96 "mailGreylisting": None,
100 "mailWhitelist": None,
101 "mailDisableMessage": None,
102 "mailDefaultOptions": None,
104 "mailContentInspectionAction": None,
108 # Decode a GPS location from some common forms
109 def LocDecode(Str,Dir):
110 # Check for Decimal degrees, DGM, or DGMS
111 if re.match("^[+-]?[\d.]+$",Str) != None:
114 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
116 # Check for DDDxMM.MMMM where x = [nsew]
117 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
120 Deg = G[0]; Min = G[2]; Dr = G[1];
123 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
126 Deg = G[0]; Dr = G[1];
128 # Check for DD:MM.MM x
129 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
132 Deg = G[0]; Min = G[1]; Dr = G[2];
134 # Check for DD:MM:SS.SS x
135 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
138 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
142 raise UDFormatError, "Bad degrees";
143 if Min != None and float(Min) > 60:
144 raise UDFormatError, "Bad minutes";
145 if Sec != None and float(Sec) > 60:
146 raise UDFormatError, "Bad seconds";
148 # Pad on an extra leading 0 to disambiguate small numbers
149 if len(Deg) <= 1 or Deg[1] == '.':
151 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
153 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
156 # Construct a DGM/DGMS type value from the components.
167 # Handle changing a set of arbitary fields
169 def DoArbChange(Str,Attrs):
170 Match = re.match("^([^ :]+): (.*)$",Str);
175 attrName = G[0].lower();
176 for i in ArbChanges.keys():
177 if i.lower() == attrName:
180 if ArbChanges.has_key(attrName) == 0:
183 if re.match(ArbChanges[attrName],G[1]) == None:
184 raise UDFormatError, "Item does not match the required format"+ArbChanges[attrName];
187 if attrName == 'gender':
188 if G[1] not in GenderTable:
189 raise UDFormatError, "Gender not found in table"
190 value = GenderTable[G[1]]
192 # if attrName == 'birthDate':
193 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
194 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
195 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
197 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
199 # } elsif ($bd_day <= 28) {
202 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
203 # if ($bd_day <= 30) {
207 # if ($bd_day <= 31) {
212 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
215 Attrs.append((ldap.MOD_REPLACE,attrName,value));
216 return "Changed entry %s to %s"%(attrName,value);
218 # Handle changing a set of arbitary fields
220 def DoDel(Str,Attrs):
221 Match = re.match("^del (.*)$",Str);
226 attrName = G[0].lower();
227 for i in DelItems.keys():
228 if i.lower() == attrName:
231 if DelItems.has_key(attrName) == 0:
232 return "Cannot erase entry %s"%(attrName);
234 Attrs.append((ldap.MOD_DELETE,attrName,None));
235 return "Removed entry %s"%(attrName);
237 # Handle a position change message, the line format is:
238 # Lat: -12412.23 Long: +12341.2342
239 def DoPosition(Str,Attrs):
240 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
246 sLat = LocDecode(G[0],"ns");
247 sLong = LocDecode(G[1],"ew");
248 Lat = DecDegree(sLat,1);
249 Long = DecDegree(sLong,1);
251 raise UDFormatError, "Positions were found, but they are not correctly formed";
253 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
254 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
255 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
257 # Load bad ssh fingerprints
259 f = open(SSHFingerprintFile, "r")
261 FingerprintLine = re.compile('^([0-9a-f\:]{47}).*$')
262 for line in f.readlines():
263 Match = FingerprintLine.match(line)
264 if Match is not None:
269 # Handle an SSH authentication key, the line format is:
270 # [options] 1024 35 13188913666680[..] [comment]
271 # maybe it really should be:
272 # [allowed_hosts=machine1,machine2 ][options ]ssh-rsa keybytes [comment]
273 machine_regex = re.compile("^[0-9a-zA-Z.-]+$")
274 def DoSSH(Str, Attrs, badkeys, uid):
275 Match = SSH2AuthSplit.match(Str);
281 Match = SSHRSA1Match.match(Str)
282 if Match is not None:
283 return "RSA1 keys not supported anymore"
286 # lines can now be prepended with "allowed_hosts=machine1,machine2 "
288 if Str.startswith("allowed_hosts="):
289 Str = Str.split("=", 1)[1]
291 return "invalid ssh key syntax with machine specification"
292 machines, Str = Str.split(' ', 1)
293 machines = machines.split(",")
296 return "empty machine specification for ssh key"
297 if not machine_regex.match(m):
298 return "machine specification for ssh key contains invalid characters"
299 if m not in ValidHostNames:
300 return "unknown machine used in allowed_hosts stanza for ssh keys"
302 (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
304 f.write("%s\n" % (Str))
306 cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
307 (result, output) = commands.getstatusoutput(cmd)
310 raise UDExecuteError, "ssh-keygen -l invocation failed!\n%s\n" % (output)
312 # format the string again for ldap:
314 Str = "allowed_hosts=%s %s" % (",".join(machines), Str)
318 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
319 ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
321 Subst["__ADMIN__"] = ReplyTo
322 Subst["__USER__"] = uid
324 Match = SSHFingerprint.match(output)
330 key_size_ok = (int(key_size) >= 2048)
331 elif typekey == "ed25519":
337 return "SSH key fails formal criteria, not added. We only accept RSA keys (>= 2048 bits) or ed25519 keys."
338 elif fingerprint in badkeys:
341 Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
342 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
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"
350 sys.exit(EX_TEMPFAIL)
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"
357 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
358 return "SSH Key added: %s %s [%s]"%(key_size, fingerprint, FormatSSHAuth(Str))
360 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
362 return "SSH Keys replaced with: %s %s [%s]"%(key_size, fingerprint, FormatSSHAuth(Str))
364 # Handle changing a dns entry
365 # host IN A 12.12.12.12
366 # host IN AAAA 1234::5678
367 # host IN CNAME foo.bar. <- Trailing dot is required
368 # host IN MX foo.bar. <- Trailing dot is required
369 def DoDNS(Str,Attrs,DnRecord):
370 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
371 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
372 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
373 txtrecord = re.match("^[-\w]+\s+IN\s+TXT\s+([-\d. a-z\t<>@]+)", Str, re.IGNORECASE)
374 #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)
375 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
377 if cnamerecord is None and\
379 mxrecord is None and\
380 txtrecord is None and\
384 # Check if the name is already taken
385 G = re.match('^([-\w+]+)\s',Str)
387 raise UDFormatError, "Hostname not found although we already passed record syntax checks"
388 hostname = G.group(1)
390 # Check for collisions
392 # [JT 20070409 - search for both tab and space suffixed hostnames
393 # since we accept either. It'd probably be better to parse the
394 # incoming string in order to construct what we feed LDAP rather
395 # than just passing it through as is.]
396 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
397 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
399 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
400 return "DNS entry is already owned by " + GetAttr(x,"uid")
406 if DNS.has_key(hostname):
407 return "CNAME and other RR types not allowed: "+Str
411 if DNS.has_key(hostname) and DNS[hostname] == 2:
412 return "CNAME and other RR types not allowed: "+Str
416 if cnamerecord is not None:
417 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
418 elif txtrecord is not None:
419 sanitized = "%s IN TXT %s" % (hostname, txtrecord.group(1))
420 elif arecord is not None:
421 ipaddress = arecord.group(1)
422 for quad in ipaddress.split('.'):
423 if not (int(quad) >=0 and int(quad) <= 255):
424 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
425 sanitized = "%s IN A %s"% (hostname, ipaddress)
426 elif mxrecord is not None:
427 priority = mxrecord.group(1)
428 mx = mxrecord.group(2)
429 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
430 elif aaaarecord is not None:
431 ipv6address = aaaarecord.group(1)
432 parts = ipv6address.split(':')
434 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
436 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
441 seenEmptypart = False
444 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
447 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
449 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
451 raise UDFormatError, "None of the types I recognize was it. I shouldn't be here. confused."
454 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
455 return "DNS Entry added "+sanitized;
457 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
459 return "DNS Entry replaced with "+sanitized;
461 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
462 def DoRBL(Str,Attrs):
463 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
467 if Match.group(1) == "rbl":
469 if Match.group(1) == "rhsbl":
471 if Match.group(1) == "whitelist":
472 Key = "mailWhitelist"
473 Host = Match.group(2)
476 if SeenList.has_key(Key):
477 Attrs.append((ldap.MOD_ADD,Key,Host))
478 return "%s added %s" % (Key,Host)
480 Attrs.append((ldap.MOD_REPLACE,Key,Host))
482 return "%s replaced with %s" % (Key,Host)
484 # Handle a ConfirmSudoPassword request
485 def DoConfirmSudopassword(Str, SudoPasswd):
486 Match = re.compile('^confirm sudopassword ('+UUID_FORMAT+') ([a-z0-9.,*-]+) ([0-9a-f]{40})$').match(Str)
490 uuid = Match.group(1)
491 hosts = Match.group(2)
492 hmac = Match.group(3)
494 SudoPasswd[uuid] = (hosts, hmac)
495 return "got confirm for sudo password %s on host(s) %s, auth code %s" % (uuid,hosts, hmac)
497 def FinishConfirmSudopassword(l, uid, Attrs, SudoPasswd):
500 if len(SudoPasswd) == 0:
503 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+uid, ['sudoPassword']);
505 raise UDFormatError, "Not exactly one hit when searching for user"
506 if res[0][1].has_key('sudoPassword'):
507 inldap = res[0][1]['sudoPassword']
513 Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*-]+) ([^ ]+)$').match(entry)
515 raise UDFormatError, "Could not parse existing sudopasswd entry"
516 uuid = Match.group(1)
517 status = Match.group(2)
518 hosts = Match.group(3)
519 cryptedpass = Match.group(4)
521 if SudoPasswd.has_key(uuid):
522 confirmedHosts = SudoPasswd[uuid][0]
523 confirmedHmac = SudoPasswd[uuid][1]
524 if status.startswith('confirmed:'):
525 if status == 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass):
526 result = result + "Entry %s for sudo password on hosts %s already confirmed.\n"%(uuid, hosts)
528 result = result + "Entry %s for sudo password on hosts %s is listed as confirmed, but HMAC does not verify.\n"%(uuid, hosts)
529 elif confirmedHosts != hosts:
530 result = result + "Entry %s hostlist mismatch (%s vs. %s).\n"%(uuid, hosts, confirmedHosts)
531 elif make_passwd_hmac('confirm-new-password', 'sudo', uid, uuid, hosts, cryptedpass) == confirmedHmac:
532 result = result + "Entry %s for sudo password on hosts %s now confirmed.\n"%(uuid, hosts)
533 status = 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass)
535 result = result + "Entry %s for sudo password on hosts %s HMAC verify failed.\n"%(uuid, hosts)
538 newentry = " ".join([uuid, status, hosts, cryptedpass])
539 if len(newldap) == 0:
540 newldap.append((ldap.MOD_REPLACE,"sudoPassword",newentry))
542 newldap.append((ldap.MOD_ADD,"sudoPassword",newentry))
544 for entry in SudoPasswd:
545 result = result + "Entry %s that you confirm is not listed in ldap."%(entry)
547 for entry in newldap:
552 def connect_to_ldap_and_check_if_locked(DnRecord):
553 # Connect to the ldap server
555 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
556 AccessPass = F.readline().strip().split(" ")
558 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
560 # Check for a locked account
561 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
562 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
563 or GetAttr(Attrs[0],"userPassword").startswith("!"):
564 raise UDNotAllowedError, "This account is locked";
568 # Handle an [almost] arbitary change
569 def HandleChange(Reply,DnRecord,Key):
571 Lines = re.split("\n *\r?",PlainText);
583 # Try to process a command line
584 Result = Result + "> "+Line+"\n";
590 badkeys = LoadBadSSH()
591 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
592 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
593 DoDel(Line,Attrs) or DoRBL(Line,Attrs) or DoConfirmSudopassword(Line, SudoPasswd)
596 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
598 # Fail, if someone tries to send someone elses signed email to the
599 # daemon then we want to abort ASAP.
602 Result = Result + "Command is not understood. Halted - no changes committed\n";
604 Result = Result + Res + "\n";
606 # Connect to the ldap server
607 l = connect_to_ldap_and_check_if_locked(DnRecord)
609 if CommitChanges == 1 and len(SudoPasswd) > 0: # only if we are still good to go
611 Res = FinishConfirmSudopassword(l, GetAttr(DnRecord,"uid"), Attrs, SudoPasswd)
613 Result = Result + Res + "\n";
616 Result = Result + "FinishConfirmSudopassword raised an error (%s) - no changes committed\n"%(e);
618 if CommitChanges == 1 and len(Attrs) > 0:
619 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
620 l.modify_s(Dn,Attrs);
624 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
626 raise UDNotAllowedError, "User not found"
627 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
630 Subst["__FROM__"] = ChangeFrom;
631 Subst["__EMAIL__"] = EmailAddress(DnRecord);
632 Subst["__ADMIN__"] = ReplyTo;
633 Subst["__RESULT__"] = Result;
634 Subst["__ATTR__"] = Attribs;
636 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
638 # Handle ping handles an email sent to the 'ping' address (ie this program
639 # called with a ping argument) It replies with a dump of the public records.
640 def HandlePing(Reply,DnRecord,Key):
642 Subst["__FROM__"] = PingFrom;
643 Subst["__EMAIL__"] = EmailAddress(DnRecord);
644 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
645 Subst["__ADMIN__"] = ReplyTo;
647 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
651 def get_crypttype_preamble(key):
653 type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
655 type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
656 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
659 # Handle a change password email sent to the change password address
660 # (this program called with the chpass argument)
661 def HandleChPass(Reply,DnRecord,Key):
662 # Generate a random password
663 Password = GenPass();
664 Pass = HashPass(Password);
666 # Use GPG to encrypt it
667 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
672 raise UDFormatError, "Unable to generate the encrypted reply, gpg failed.";
675 Subst["__FROM__"] = ChPassFrom;
676 Subst["__EMAIL__"] = EmailAddress(DnRecord);
677 Subst["__CRYPTTYPE__"] = get_crypttype_preamble(Key)
678 Subst["__PASSWORD__"] = Message;
679 Subst["__ADMIN__"] = ReplyTo;
680 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
682 l = connect_to_ldap_and_check_if_locked(DnRecord)
683 # Modify the password
684 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass),
685 (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60)))];
686 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
691 def HandleChTOTPSeed(Reply, DnRecord, Key):
692 # Generate a random seed
693 seed = binascii.hexlify(open("/dev/urandom", "r").read(32))
694 msg = GPGEncrypt("Your new TOTP seed is '%s'\n" % (seed,), "0x"+Key[1],Key[4]);
697 raise UDFormatError, "Unable to generate the encrypted reply, gpg failed.";
700 Subst["__FROM__"] = ChPassFrom
701 Subst["__EMAIL__"] = EmailAddress(DnRecord)
702 Subst["__PASSWORD__"] = msg
703 Subst["__ADMIN__"] = ReplyTo
704 Reply = Reply + TemplateSubst(Subst, open(TemplatesDir+"totp-seed-changed", "r").read())
706 l = connect_to_ldap_and_check_if_locked(DnRecord)
707 # Modify the password
708 Rec = [(ldap.MOD_REPLACE, "totpSeed", seed)]
709 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn
713 def HandleChKrbPass(Reply,DnRecord,Key):
714 # Connect to the ldap server, will throw an exception if account locked.
715 l = connect_to_ldap_and_check_if_locked(DnRecord)
717 user = GetAttr(DnRecord,"uid")
718 krb_proc = subprocess.Popen( ('ud-krb-reset', user), stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
719 krb_proc.stdin.close()
720 out = krb_proc.stdout.readlines()
722 exitcode = krb_proc.returncode
724 # Use GPG to encrypt it
725 m = "Tried to reset your kerberos principal's password.\n"
727 m += "The exitcode of the reset script was zero, indicating that everything\n"
728 m += "worked. However, this being software who knows. Script's output below."
730 m += "The exitcode of the reset script was %d, indicating that something\n"%(exitcode)
731 m += "went terribly, terribly wrong. Please consult the script's output below\n"
732 m += "for more information. Contact the admins if you have any questions or\n"
733 m += "require assitance."
735 m += "\n"+''.join( map(lambda x: "| "+x, out) )
737 Message = GPGEncrypt(m, "0x"+Key[1],Key[4]);
739 raise UDFormatError, "Unable to generate the encrypted reply, gpg failed.";
742 Subst["__FROM__"] = ChPassFrom;
743 Subst["__EMAIL__"] = EmailAddress(DnRecord);
744 Subst["__CRYPTTYPE__"] = get_crypttype_preamble(Key)
745 Subst["__PASSWORD__"] = Message;
746 Subst["__ADMIN__"] = ReplyTo;
747 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
751 # Start of main program
753 # Drop messages from a mailer daemon.
754 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
757 ErrMsg = "Indeterminate Error";
758 ErrType = EX_TEMPFAIL;
760 # Startup the replay cache
761 ErrType = EX_TEMPFAIL;
762 ErrMsg = "Failed to initialize the replay cache:";
765 ErrType = EX_PERMFAIL;
766 ErrMsg = "Failed to understand the email or find a signature:";
767 mail = email.parser.Parser().parse(sys.stdin);
768 Msg = GetClearSig(mail);
770 ErrMsg = "Message is not PGP signed:"
771 if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
772 Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
773 raise UDFormatError, "No PGP signature";
775 # Check the signature
776 ErrMsg = "Unable to check the signature or the signature was invalid:";
777 pgp = GPGCheckSig2(Msg[0])
780 raise UDFormatError, pgp.why
783 raise UDFormatError, "Null signature text"
785 # Extract the plain message text in the event of mime encoding
787 ErrMsg = "Problem stripping MIME headers from the decoded message"
789 e = email.parser.Parser().parsestr(pgp.text)
790 PlainText = e.get_payload(decode=True)
794 # Connect to the ldap server
795 ErrType = EX_TEMPFAIL;
796 ErrMsg = "An error occured while performing the LDAP lookup";
799 l.simple_bind_s("","");
801 # Search for the matching key fingerprint
802 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + pgp.key_fpr)
804 ErrType = EX_PERMFAIL;
806 raise UDFormatError, "Key not found"
808 raise UDFormatError, "Oddly your key fingerprint is assigned to more than one account.."
811 # Check the signature against the replay cache
812 RC = ReplayCache(ReplayCacheFile);
813 RC.process(pgp.sig_info)
815 # Determine the sender address
816 ErrMsg = "A problem occured while trying to formulate the reply";
817 Sender = mail['Reply-To']
818 if not Sender: Sender = mail['From']
819 if not Sender: raise UDFormatError, "Unable to determine the sender's address";
822 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
823 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
825 Res = l.search_s(HostBaseDn, ldap.SCOPE_SUBTREE, '(objectClass=debianServer)', ['hostname'] )
826 # Res is a list of tuples.
827 # The tuples contain a dn (str) and a dictionary.
828 # The dictionaries map the key "hostname" to a list.
829 # These lists contain a single hostname (str).
830 ValidHostNames = reduce(lambda a,b: a+b, [value.get("hostname", []) for (dn, value) in Res], [])
833 if sys.argv[1] == "ping":
834 Reply = HandlePing(Reply,Attrs[0],pgp.key_info);
835 elif sys.argv[1] == "chpass":
836 if PlainText.strip().find("Please change my Debian password") >= 0:
837 Reply = HandleChPass(Reply,Attrs[0],pgp.key_info);
838 elif PlainText.strip().find("Please change my Kerberos password") >= 0:
839 Reply = HandleChKrbPass(Reply,Attrs[0],pgp.key_info);
840 elif PlainText.strip().find("Please change my TOTP seed") >= 0:
841 Reply = HandleChTOTPSeed(Reply, Attrs[0], pgp.key_info)
843 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.";
844 elif sys.argv[1] == "change":
845 Reply = HandleChange(Reply,Attrs[0],pgp.key_info);
848 raise UDFormatError, "Incorrect Invokation";
850 # Send the message through sendmail
851 ErrMsg = "A problem occured while trying to send the reply";
852 Child = os.popen("/usr/sbin/sendmail -t","w");
853 # Child = os.popen("cat","w");
855 if Child.close() != None:
856 raise UDExecuteError, "Sendmail gave a non-zero return code";
860 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
861 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
865 Subst["__ERROR__"] = ErrMsg;
866 Subst["__ADMIN__"] = ReplyTo;
868 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
869 List = traceback.extract_tb(sys.exc_traceback);
871 Trace = Trace + "Python Stack Trace:\n";
873 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
875 Subst["__TRACE__"] = Trace;
877 # Try to send the bounce
879 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
881 Child = os.popen("/usr/sbin/sendmail -t -oi -f ''","w");
882 Child.write(ErrReplyHead);
883 Child.write(ErrReply);
884 if Child.close() != None:
885 raise UDExecuteError, "Sendmail gave a non-zero return code";
887 sys.exit(EX_TEMPFAIL);
889 if ErrType != EX_PERMFAIL:
895 # vim:set shiftwidth=3: