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
15 from userdir_gpg import *
16 from userdir_ldap import *
17 from userdir_exceptions import *
19 # Error codes from /usr/include/sysexits.h
20 ReplyTo = ConfModule.replyto;
21 PingFrom = ConfModule.pingfrom;
22 ChPassFrom = ConfModule.chpassfrom;
23 ChangeFrom = ConfModule.changefrom;
24 ReplayCacheFile = ConfModule.replaycachefile;
25 SSHFingerprintFile = ConfModule.fingerprintfile
27 UUID_FORMAT = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
30 EX_PERMFAIL = 65; # EX_DATAERR
31 Error = 'Message Error';
39 ValidHostNames = [] # will be initialized in later
41 SSHFingerprint = re.compile('^(\d+) ([0-9a-f\:]{47}) (.+)$')
42 SSHRSA1Match = re.compile('^^(.* )?\d+ \d+ \d+')
44 GenderTable = {"male": '1',
52 ArbChanges = {"c": "..",
54 "facsimileTelephoneNumber": ".*",
55 "telephoneNumber": ".*",
56 "postalAddress": ".*",
60 "emailForward": "^([^<>@]+@.+)?$",
61 "jabberJID": "^([^<>@]+@.+)?$",
66 "birthDate": "^([0-9]{4})([01][0-9])([0-3][0-9])$",
67 "mailDisableMessage": ".*",
68 "mailGreylisting": "^(TRUE|FALSE)$",
69 "mailCallout": "^(TRUE|FALSE)$",
70 "mailDefaultOptions": "^(TRUE|FALSE)$",
72 "gender": "^(1|2|9|male|female|unspecified)$",
73 "mailContentInspectionAction": "^(reject|blackhole|markup)$",
76 DelItems = {"c": None,
78 "facsimileTelephoneNumber": None,
79 "telephoneNumber": None,
80 "postalAddress": None,
93 "sshRSAAuthKey": None,
95 "mailGreylisting": None,
99 "mailWhitelist": None,
100 "mailDisableMessage": None,
101 "mailDefaultOptions": None,
103 "mailContentInspectionAction": None,
107 # Decode a GPS location from some common forms
108 def LocDecode(Str,Dir):
109 # Check for Decimal degrees, DGM, or DGMS
110 if re.match("^[+-]?[\d.]+$",Str) != None:
113 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
115 # Check for DDDxMM.MMMM where x = [nsew]
116 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
119 Deg = G[0]; Min = G[2]; Dr = G[1];
122 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
125 Deg = G[0]; Dr = G[1];
127 # Check for DD:MM.MM x
128 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
131 Deg = G[0]; Min = G[1]; Dr = G[2];
133 # Check for DD:MM:SS.SS x
134 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
137 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
141 raise UDFormatError, "Bad degrees";
142 if Min != None and float(Min) > 60:
143 raise UDFormatError, "Bad minutes";
144 if Sec != None and float(Sec) > 60:
145 raise UDFormatError, "Bad seconds";
147 # Pad on an extra leading 0 to disambiguate small numbers
148 if len(Deg) <= 1 or Deg[1] == '.':
150 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
152 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
155 # Construct a DGM/DGMS type value from the components.
166 # Handle changing a set of arbitary fields
168 def DoArbChange(Str,Attrs):
169 Match = re.match("^([^ :]+): (.*)$",Str);
174 attrName = G[0].lower();
175 for i in ArbChanges.keys():
176 if i.lower() == attrName:
179 if ArbChanges.has_key(attrName) == 0:
182 if re.match(ArbChanges[attrName],G[1]) == None:
183 raise UDFormatError, "Item does not match the required format"+ArbChanges[attrName];
186 if attrName == 'gender':
187 if G[1] not in GenderTable:
188 raise UDFormatError, "Gender not found in table"
189 value = GenderTable[G[1]]
191 # if attrName == 'birthDate':
192 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
193 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
194 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
196 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
198 # } elsif ($bd_day <= 28) {
201 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
202 # if ($bd_day <= 30) {
206 # if ($bd_day <= 31) {
211 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
214 Attrs.append((ldap.MOD_REPLACE,attrName,value));
215 return "Changed entry %s to %s"%(attrName,value);
217 # Handle changing a set of arbitary fields
219 def DoDel(Str,Attrs):
220 Match = re.match("^del (.*)$",Str);
225 attrName = G[0].lower();
226 for i in DelItems.keys():
227 if i.lower() == attrName:
230 if DelItems.has_key(attrName) == 0:
231 return "Cannot erase entry %s"%(attrName);
233 Attrs.append((ldap.MOD_DELETE,attrName,None));
234 return "Removed entry %s"%(attrName);
236 # Handle a position change message, the line format is:
237 # Lat: -12412.23 Long: +12341.2342
238 def DoPosition(Str,Attrs):
239 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
245 sLat = LocDecode(G[0],"ns");
246 sLong = LocDecode(G[1],"ew");
247 Lat = DecDegree(sLat,1);
248 Long = DecDegree(sLong,1);
250 raise UDFormatError, "Positions were found, but they are not correctly formed";
252 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
253 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
254 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
256 # Load bad ssh fingerprints
258 f = open(SSHFingerprintFile, "r")
260 FingerprintLine = re.compile('^([0-9a-f\:]{47}).*$')
261 for line in f.readlines():
262 Match = FingerprintLine.match(line)
263 if Match is not None:
268 # Handle an SSH authentication key, the line format is:
269 # [options] 1024 35 13188913666680[..] [comment]
270 # maybe it really should be:
271 # [allowed_hosts=machine1,machine2 ][options ]ssh-rsa keybytes [comment]
272 machine_regex = re.compile("^[0-9a-zA-Z.-]+$")
273 def DoSSH(Str, Attrs, badkeys, uid):
274 Match = SSH2AuthSplit.match(Str);
280 Match = SSHRSA1Match.match(Str)
281 if Match is not None:
282 return "RSA1 keys not supported anymore"
285 # lines can now be prepended with "allowed_hosts=machine1,machine2 "
287 if Str.startswith("allowed_hosts="):
288 Str = Str.split("=", 1)[1]
290 return "invalid ssh key syntax with machine specification"
291 machines, Str = Str.split(' ', 1)
292 machines = machines.split(",")
295 return "empty machine specification for ssh key"
296 if not machine_regex.match(m):
297 return "machine specification for ssh key contains invalid characters"
298 if m not in ValidHostNames:
299 return "unknown machine used in allowed_hosts stanza for ssh keys"
301 (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
303 f.write("%s\n" % (Str))
305 cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
306 (result, output) = commands.getstatusoutput(cmd)
309 raise UDExecuteError, "ssh-keygen -l invocation failed!\n%s\n" % (output)
311 # format the string again for ldap:
313 Str = "allowed_hosts=%s %s" % (",".join(machines), Str)
317 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
318 ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
320 Subst["__ADMIN__"] = ReplyTo
321 Subst["__USER__"] = uid
323 Match = SSHFingerprint.match(output)
326 if typekey == "ssh-rsa":
327 key_size_ok = (g[0]) >= 2048)
328 elif typekey == "ed25519":
336 Subst["__ERROR__"] = "SSH key fails formal criteria. We only accept RSA keys (>= 2048 bits) or ed25519 keys." % (g[0])
337 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
339 Child = os.popen("/usr/sbin/sendmail -t","w")
340 Child.write(ErrReplyHead)
341 Child.write(ErrReply)
342 if Child.close() != None:
343 raise UDExecuteError, "Sendmail gave a non-zero return code"
345 sys.exit(EX_TEMPFAIL)
347 # And now break and stop processing input, which sends a reply to the user.
348 raise UDFormatError, "SSH key fails formal criteria, NOTHING MODIFIED AT ALL"
349 elif g[1] in badkeys:
352 Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
353 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
355 Child = os.popen("/usr/sbin/sendmail -t","w")
356 Child.write(ErrReplyHead)
357 Child.write(ErrReply)
358 if Child.close() != None:
359 raise UDExecuteError, "Sendmail gave a non-zero return code"
361 sys.exit(EX_TEMPFAIL)
363 # And now break and stop processing input, which sends a reply to the user.
364 raise UDFormatError, "Submitted SSH Key known to be bad and insecure, processing halted, NOTHING MODIFIED AT ALL"
368 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
369 return "SSH Key added "+FormatSSHAuth(Str);
371 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
373 return "SSH Keys replaced with "+FormatSSHAuth(Str);
375 # Handle changing a dns entry
376 # host IN A 12.12.12.12
377 # host IN AAAA 1234::5678
378 # host IN CNAME foo.bar. <- Trailing dot is required
379 # host IN MX foo.bar. <- Trailing dot is required
380 def DoDNS(Str,Attrs,DnRecord):
381 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
382 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
383 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
384 txtrecord = re.match("^[-\w]+\s+IN\s+TXT\s+([-\d. a-z\t<>@]+)", Str, re.IGNORECASE)
385 #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)
386 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
388 if cnamerecord is None and\
390 mxrecord is None and\
391 txtrecord is None and\
395 # Check if the name is already taken
396 G = re.match('^([-\w+]+)\s',Str)
398 raise UDFormatError, "Hostname not found although we already passed record syntax checks"
399 hostname = G.group(1)
401 # Check for collisions
403 # [JT 20070409 - search for both tab and space suffixed hostnames
404 # since we accept either. It'd probably be better to parse the
405 # incoming string in order to construct what we feed LDAP rather
406 # than just passing it through as is.]
407 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
408 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
410 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
411 return "DNS entry is already owned by " + GetAttr(x,"uid")
417 if DNS.has_key(hostname):
418 return "CNAME and other RR types not allowed: "+Str
422 if DNS.has_key(hostname) and DNS[hostname] == 2:
423 return "CNAME and other RR types not allowed: "+Str
427 if cnamerecord is not None:
428 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
429 elif txtrecord is not None:
430 sanitized = "%s IN TXT %s" % (hostname, txtrecord.group(1))
431 elif arecord is not None:
432 ipaddress = arecord.group(1)
433 for quad in ipaddress.split('.'):
434 if not (int(quad) >=0 and int(quad) <= 255):
435 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
436 sanitized = "%s IN A %s"% (hostname, ipaddress)
437 elif mxrecord is not None:
438 priority = mxrecord.group(1)
439 mx = mxrecord.group(2)
440 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
441 elif aaaarecord is not None:
442 ipv6address = aaaarecord.group(1)
443 parts = ipv6address.split(':')
445 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
447 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
452 seenEmptypart = False
455 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
458 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
460 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
462 raise UDFormatError, "None of the types I recognize was it. I shouldn't be here. confused."
465 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
466 return "DNS Entry added "+sanitized;
468 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
470 return "DNS Entry replaced with "+sanitized;
472 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
473 def DoRBL(Str,Attrs):
474 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
478 if Match.group(1) == "rbl":
480 if Match.group(1) == "rhsbl":
482 if Match.group(1) == "whitelist":
483 Key = "mailWhitelist"
484 Host = Match.group(2)
487 if SeenList.has_key(Key):
488 Attrs.append((ldap.MOD_ADD,Key,Host))
489 return "%s added %s" % (Key,Host)
491 Attrs.append((ldap.MOD_REPLACE,Key,Host))
493 return "%s replaced with %s" % (Key,Host)
495 # Handle a ConfirmSudoPassword request
496 def DoConfirmSudopassword(Str, SudoPasswd):
497 Match = re.compile('^confirm sudopassword ('+UUID_FORMAT+') ([a-z0-9.,*-]+) ([0-9a-f]{40})$').match(Str)
501 uuid = Match.group(1)
502 hosts = Match.group(2)
503 hmac = Match.group(3)
505 SudoPasswd[uuid] = (hosts, hmac)
506 return "got confirm for sudo password %s on host(s) %s, auth code %s" % (uuid,hosts, hmac)
508 def FinishConfirmSudopassword(l, uid, Attrs, SudoPasswd):
511 if len(SudoPasswd) == 0:
514 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+uid, ['sudoPassword']);
516 raise UDFormatError, "Not exactly one hit when searching for user"
517 if res[0][1].has_key('sudoPassword'):
518 inldap = res[0][1]['sudoPassword']
524 Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*-]+) ([^ ]+)$').match(entry)
526 raise UDFormatError, "Could not parse existing sudopasswd entry"
527 uuid = Match.group(1)
528 status = Match.group(2)
529 hosts = Match.group(3)
530 cryptedpass = Match.group(4)
532 if SudoPasswd.has_key(uuid):
533 confirmedHosts = SudoPasswd[uuid][0]
534 confirmedHmac = SudoPasswd[uuid][1]
535 if status.startswith('confirmed:'):
536 if status == 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass):
537 result = result + "Entry %s for sudo password on hosts %s already confirmed.\n"%(uuid, hosts)
539 result = result + "Entry %s for sudo password on hosts %s is listed as confirmed, but HMAC does not verify.\n"%(uuid, hosts)
540 elif confirmedHosts != hosts:
541 result = result + "Entry %s hostlist mismatch (%s vs. %s).\n"%(uuid, hosts, confirmedHosts)
542 elif make_passwd_hmac('confirm-new-password', 'sudo', uid, uuid, hosts, cryptedpass) == confirmedHmac:
543 result = result + "Entry %s for sudo password on hosts %s now confirmed.\n"%(uuid, hosts)
544 status = 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass)
546 result = result + "Entry %s for sudo password on hosts %s HMAC verify failed.\n"%(uuid, hosts)
549 newentry = " ".join([uuid, status, hosts, cryptedpass])
550 if len(newldap) == 0:
551 newldap.append((ldap.MOD_REPLACE,"sudoPassword",newentry))
553 newldap.append((ldap.MOD_ADD,"sudoPassword",newentry))
555 for entry in SudoPasswd:
556 result = result + "Entry %s that you confirm is not listed in ldap."%(entry)
558 for entry in newldap:
563 def connect_to_ldap_and_check_if_locked(DnRecord):
564 # Connect to the ldap server
566 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
567 AccessPass = F.readline().strip().split(" ")
569 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
571 # Check for a locked account
572 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
573 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
574 or GetAttr(Attrs[0],"userPassword").startswith("!"):
575 raise UDNotAllowedError, "This account is locked";
579 # Handle an [almost] arbitary change
580 def HandleChange(Reply,DnRecord,Key):
582 Lines = re.split("\n *\r?",PlainText);
594 # Try to process a command line
595 Result = Result + "> "+Line+"\n";
601 badkeys = LoadBadSSH()
602 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
603 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
604 DoDel(Line,Attrs) or DoRBL(Line,Attrs) or DoConfirmSudopassword(Line, SudoPasswd)
607 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
609 # Fail, if someone tries to send someone elses signed email to the
610 # daemon then we want to abort ASAP.
613 Result = Result + "Command is not understood. Halted - no changes committed\n";
615 Result = Result + Res + "\n";
617 # Connect to the ldap server
618 l = connect_to_ldap_and_check_if_locked(DnRecord)
620 if CommitChanges == 1 and len(SudoPasswd) > 0: # only if we are still good to go
622 Res = FinishConfirmSudopassword(l, GetAttr(DnRecord,"uid"), Attrs, SudoPasswd)
624 Result = Result + Res + "\n";
627 Result = Result + "FinishConfirmSudopassword raised an error (%s) - no changes committed\n"%(e);
629 if CommitChanges == 1 and len(Attrs) > 0:
630 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
631 l.modify_s(Dn,Attrs);
635 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
637 raise UDNotAllowedError, "User not found"
638 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
641 Subst["__FROM__"] = ChangeFrom;
642 Subst["__EMAIL__"] = EmailAddress(DnRecord);
643 Subst["__ADMIN__"] = ReplyTo;
644 Subst["__RESULT__"] = Result;
645 Subst["__ATTR__"] = Attribs;
647 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
649 # Handle ping handles an email sent to the 'ping' address (ie this program
650 # called with a ping argument) It replies with a dump of the public records.
651 def HandlePing(Reply,DnRecord,Key):
653 Subst["__FROM__"] = PingFrom;
654 Subst["__EMAIL__"] = EmailAddress(DnRecord);
655 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
656 Subst["__ADMIN__"] = ReplyTo;
658 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
662 def get_crypttype_preamble(key):
664 type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
666 type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
667 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
670 # Handle a change password email sent to the change password address
671 # (this program called with the chpass argument)
672 def HandleChPass(Reply,DnRecord,Key):
673 # Generate a random password
674 Password = GenPass();
675 Pass = HashPass(Password);
677 # Use GPG to encrypt it
678 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
683 raise UDFormatError, "Unable to generate the encrypted reply, gpg failed.";
686 Subst["__FROM__"] = ChPassFrom;
687 Subst["__EMAIL__"] = EmailAddress(DnRecord);
688 Subst["__CRYPTTYPE__"] = get_crypttype_preamble(Key)
689 Subst["__PASSWORD__"] = Message;
690 Subst["__ADMIN__"] = ReplyTo;
691 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
693 l = connect_to_ldap_and_check_if_locked(DnRecord)
694 # Modify the password
695 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass),
696 (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60)))];
697 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
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)
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()
711 exitcode = krb_proc.returncode
713 # Use GPG to encrypt it
714 m = "Tried to reset your kerberos principal's password.\n"
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."
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."
724 m += "\n"+''.join( map(lambda x: "| "+x, out) )
726 Message = GPGEncrypt(m, "0x"+Key[1],Key[4]);
728 raise UDFormatError, "Unable to generate the encrypted reply, gpg failed.";
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());
740 # Start of main program
742 # Drop messages from a mailer daemon.
743 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
746 ErrMsg = "Indeterminate Error";
747 ErrType = EX_TEMPFAIL;
749 # Startup the replay cache
750 ErrType = EX_TEMPFAIL;
751 ErrMsg = "Failed to initialize the replay cache:";
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);
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";
764 # Check the signature
765 ErrMsg = "Unable to check the signature or the signature was invalid:";
766 pgp = GPGCheckSig2(Msg[0])
769 raise UDFormatError, pgp.why
772 raise UDFormatError, "Null signature text"
774 # Extract the plain message text in the event of mime encoding
776 ErrMsg = "Problem stripping MIME headers from the decoded message"
778 e = email.parser.Parser().parsestr(pgp.text)
779 PlainText = e.get_payload(decode=True)
783 # Connect to the ldap server
784 ErrType = EX_TEMPFAIL;
785 ErrMsg = "An error occured while performing the LDAP lookup";
788 l.simple_bind_s("","");
790 # Search for the matching key fingerprint
791 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + pgp.key_fpr)
793 ErrType = EX_PERMFAIL;
795 raise UDFormatError, "Key not found"
797 raise UDFormatError, "Oddly your key fingerprint is assigned to more than one account.."
800 # Check the signature against the replay cache
801 RC = ReplayCache(ReplayCacheFile);
802 RC.process(pgp.sig_info)
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";
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);
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], [])
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);
830 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.";
831 elif sys.argv[1] == "change":
832 Reply = HandleChange(Reply,Attrs[0],pgp.key_info);
835 raise UDFormatError, "Incorrect Invokation";
837 # Send the message through sendmail
838 ErrMsg = "A problem occured while trying to send the reply";
839 Child = os.popen("/usr/sbin/sendmail -t","w");
840 # Child = os.popen("cat","w");
842 if Child.close() != None:
843 raise UDExecuteError, "Sendmail gave a non-zero return code";
847 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
848 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
852 Subst["__ERROR__"] = ErrMsg;
853 Subst["__ADMIN__"] = ReplyTo;
855 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
856 List = traceback.extract_tb(sys.exc_traceback);
858 Trace = Trace + "Python Stack Trace:\n";
860 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
862 Subst["__TRACE__"] = Trace;
864 # Try to send the bounce
866 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
868 Child = os.popen("/usr/sbin/sendmail -t -oi -f ''","w");
869 Child.write(ErrReplyHead);
870 Child.write(ErrReply);
871 if Child.close() != None:
872 raise UDExecuteError, "Sendmail gave a non-zero return code";
874 sys.exit(EX_TEMPFAIL);
876 if ErrType != EX_PERMFAIL:
882 # vim:set shiftwidth=3: