4 # Prior copyright probably rmurray, troup, joey, jgg -- weasel 2008
5 # Copyright (c) 2009 Stephen Gran <steve@lobefin.net>
6 # Copyright (c) 2008 Peter Palfrader <peter@palfrader.org>
7 # Copyright (c) 2008 Joerg Jaspert <joerg@debian.org>
9 import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, os, commands
12 from userdir_gpg import *
13 from userdir_ldap import *
14 from userdir_exceptions import *
16 # Error codes from /usr/include/sysexits.h
17 ReplyTo = ConfModule.replyto;
18 PingFrom = ConfModule.pingfrom;
19 ChPassFrom = ConfModule.chpassfrom;
20 ChangeFrom = ConfModule.changefrom;
21 ReplayCacheFile = ConfModule.replaycachefile;
22 SSHFingerprintFile = ConfModule.fingerprintfile
24 UUID_FORMAT = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
27 EX_PERMFAIL = 65; # EX_DATAERR
28 Error = 'Message Error';
38 SSHFingerprint = re.compile('^(\d+) ([0-9a-f\:]{47}) (.+)$')
39 SSHRSA1Match = re.compile('^^(.* )?\d+ \d+ \d+')
41 GenderTable = {"male": 1,
49 ArbChanges = {"c": "..",
51 "facsimileTelephoneNumber": ".*",
52 "telephoneNumber": ".*",
53 "postalAddress": ".*",
57 "emailForward": "^([^<>@]+@.+)?$",
58 "jabberJID": "^([^<>@]+@.+)?$",
63 "birthDate": "^([0-9]{4})([01][0-9])([0-3][0-9])$",
64 "mailDisableMessage": ".*",
65 "mailGreylisting": "^(TRUE|FALSE)$",
66 "mailCallout": "^(TRUE|FALSE)$",
68 "gender": "^(1|2|9|male|female|unspecified)$",
69 "mailContentInspectionAction": "^(reject|blackhole|markup)$",
72 DelItems = {"c": None,
74 "facsimileTelephoneNumber": None,
75 "telephoneNumber": None,
76 "postalAddress": None,
89 "sshRSAAuthKey": None,
91 "mailGreylisting": None,
95 "mailWhitelist": None,
96 "mailDisableMessage": None,
98 "mailContentInspectionAction": None,
102 # Decode a GPS location from some common forms
103 def LocDecode(Str,Dir):
104 # Check for Decimal degrees, DGM, or DGMS
105 if re.match("^[+-]?[\d.]+$",Str) != None:
108 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
110 # Check for DDDxMM.MMMM where x = [nsew]
111 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
114 Deg = G[0]; Min = G[2]; Dr = G[1];
117 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
120 Deg = G[0]; Dr = G[1];
122 # Check for DD:MM.MM x
123 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
126 Deg = G[0]; Min = G[1]; Dr = G[2];
128 # Check for DD:MM:SS.SS x
129 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
132 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
136 raise UDFormatError, "Bad degrees";
137 if Min != None and float(Min) > 60:
138 raise UDFormatError, "Bad minutes";
139 if Sec != None and float(Sec) > 60:
140 raise UDFormatError, "Bad seconds";
142 # Pad on an extra leading 0 to disambiguate small numbers
143 if len(Deg) <= 1 or Deg[1] == '.':
145 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
147 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
150 # Construct a DGM/DGMS type value from the components.
161 # Handle changing a set of arbitary fields
163 def DoArbChange(Str,Attrs):
164 Match = re.match("^([^ :]+): (.*)$",Str);
169 attrName = G[0].lower();
170 for i in ArbChanges.keys():
171 if i.lower() == attrName:
174 if ArbChanges.has_key(attrName) == 0:
177 if re.match(ArbChanges[attrName],G[1]) == None:
178 raise UDFormatError, "Item does not match the required format"+ArbChanges[attrName];
181 if attrName == 'gender':
182 if G[1] not in GenderTable:
183 raise UDFormatError, "Gender not found in table"
184 value = GenderTable[G[1]]
186 # if attrName == 'birthDate':
187 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
188 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
189 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
191 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
193 # } elsif ($bd_day <= 28) {
196 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
197 # if ($bd_day <= 30) {
201 # if ($bd_day <= 31) {
206 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
209 Attrs.append((ldap.MOD_REPLACE,attrName,value));
210 return "Changed entry %s to %s"%(attrName,value);
212 # Handle changing a set of arbitary fields
214 def DoDel(Str,Attrs):
215 Match = re.match("^del (.*)$",Str);
220 attrName = G[0].lower();
221 for i in DelItems.keys():
222 if i.lower() == attrName:
225 if DelItems.has_key(attrName) == 0:
226 return "Cannot erase entry %s"%(attrName);
228 Attrs.append((ldap.MOD_DELETE,attrName,None));
229 return "Removed entry %s"%(attrName);
231 # Handle a position change message, the line format is:
232 # Lat: -12412.23 Long: +12341.2342
233 def DoPosition(Str,Attrs):
234 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
240 sLat = LocDecode(G[0],"ns");
241 sLong = LocDecode(G[1],"ew");
242 Lat = DecDegree(sLat,1);
243 Long = DecDegree(sLong,1);
245 raise UDFormatError, "Positions were found, but they are not correctly formed";
247 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
248 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
249 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
251 # Load bad ssh fingerprints
253 f = open(SSHFingerprintFile, "r")
255 FingerprintLine = re.compile('^([0-9a-f\:]{47}).*$')
256 for line in f.readlines():
257 Match = FingerprintLine.match(line)
258 if Match is not None:
263 # Handle an SSH authentication key, the line format is:
264 # [options] 1024 35 13188913666680[..] [comment]
265 def DoSSH(Str, Attrs, badkeys, uid):
266 Match = SSH2AuthSplit.match(Str);
272 Match = SSHRSA1Match.match(Str)
273 if Match is not None:
274 return "RSA1 keys not supported anymore"
277 (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
279 f.write("%s\n" % (Str))
281 cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
282 (result, output) = commands.getstatusoutput(cmd)
285 raise UDExecuteError, "ssh-keygen -l invocation failed!\n%s\n" % (output)
289 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
290 ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
292 Subst["__ADMIN__"] = ReplyTo
293 Subst["__USER__"] = uid
295 Match = SSHFingerprint.match(output)
301 Subst["__ERROR__"] = "SSH keysize %s is below limit 1024" % (g[0])
302 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
304 Child = os.popen("/usr/sbin/sendmail -t","w")
305 Child.write(ErrReplyHead)
306 Child.write(ErrReply)
307 if Child.close() != None:
308 raise UDExecuteError, "Sendmail gave a non-zero return code"
310 sys.exit(EX_TEMPFAIL)
312 # And now break and stop processing input, which sends a reply to the user.
313 raise UDFormatError, "SSH keys must have at least 1024 bits, processing halted, NOTHING MODIFIED AT ALL"
314 elif g[1] in badkeys:
317 Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
318 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
320 Child = os.popen("/usr/sbin/sendmail -t","w")
321 Child.write(ErrReplyHead)
322 Child.write(ErrReply)
323 if Child.close() != None:
324 raise UDExecuteError, "Sendmail gave a non-zero return code"
326 sys.exit(EX_TEMPFAIL)
328 # And now break and stop processing input, which sends a reply to the user.
329 raise UDFormatError, "Submitted SSH Key known to be bad and insecure, processing halted, NOTHING MODIFIED AT ALL"
331 if (typekey == "dss"):
332 return "DSA keys not accepted anymore"
336 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
337 return "SSH Key added "+FormatSSHAuth(Str);
339 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
341 return "SSH Keys replaced with "+FormatSSHAuth(Str);
343 # Handle changing a dns entry
344 # host IN A 12.12.12.12
345 # host IN AAAA 1234::5678
346 # host IN CNAME foo.bar. <- Trailing dot is required
347 # host IN MX foo.bar. <- Trailing dot is required
348 def DoDNS(Str,Attrs,DnRecord):
349 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
350 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
351 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
352 #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)
353 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
355 if cnamerecord == None and\
357 mxrecord == None and\
361 # Check if the name is already taken
362 G = re.match('^([-\w+]+)\s',Str)
364 raise UDFormatError, "Hostname not found although we already passed record syntax checks"
365 hostname = G.group(1)
367 # Check for collisions
369 # [JT 20070409 - search for both tab and space suffixed hostnames
370 # since we accept either. It'd probably be better to parse the
371 # incoming string in order to construct what we feed LDAP rather
372 # than just passing it through as is.]
373 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
374 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
376 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
377 return "DNS entry is already owned by " + GetAttr(x,"uid")
383 if DNS.has_key(hostname):
384 return "CNAME and other RR types not allowed: "+Str
388 if DNS.has_key(hostname) and DNS[hostname] == 2:
389 return "CNAME and other RR types not allowed: "+Str
393 if cnamerecord != None:
394 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
395 elif arecord != None:
396 ipaddress = arecord.group(1)
397 for quad in ipaddress.split('.'):
398 if not (int(quad) >=0 and int(quad) <= 255):
399 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
400 sanitized = "%s IN A %s"% (hostname, ipaddress)
401 elif mxrecord != None:
402 priority = mxrecord.group(1)
403 mx = mxrecord.group(2)
404 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
405 elif aaaarecord != None:
406 ipv6address = aaaarecord.group(1)
407 parts = ipv6address.split(':')
409 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
411 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
416 seenEmptypart = False
419 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
422 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
424 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
426 raise UDFormatError, "None of the types I recognize was it. I shouldn't be here. confused."
429 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
430 return "DNS Entry added "+sanitized;
432 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
434 return "DNS Entry replaced with "+sanitized;
436 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
437 def DoRBL(Str,Attrs):
438 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
442 if Match.group(1) == "rbl":
444 if Match.group(1) == "rhsbl":
446 if Match.group(1) == "whitelist":
447 Key = "mailWhitelist"
448 Host = Match.group(2)
451 if SeenList.has_key(Key):
452 Attrs.append((ldap.MOD_ADD,Key,Host))
453 return "%s added %s" % (Key,Host)
455 Attrs.append((ldap.MOD_REPLACE,Key,Host))
457 return "%s replaced with %s" % (Key,Host)
459 # Handle a ConfirmSudoPassword request
460 def DoConfirmSudopassword(Str):
461 Match = re.compile('^confirm sudopassword ('+UUID_FORMAT+') ([a-z0-9.,*]+) ([0-9a-f]{40})$').match(Str)
465 uuid = Match.group(1)
466 hosts = Match.group(2)
467 hmac = Match.group(3)
470 SudoPasswd[uuid] = (hosts, hmac)
471 return "got confirm for sudo password %s on host(s) %s, auth code %s" % (uuid,hosts, hmac)
473 def FinishConfirmSudopassword(l, uid, Attrs):
477 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+uid, ['sudoPassword']);
479 raise UDFormatError, "Not exactly one hit when searching for user"
480 if res[0][1].has_key('sudoPassword'):
481 inldap = res[0][1]['sudoPassword']
487 Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*]+) ([^ ]+)$').match(entry)
489 raise UDFormatError, "Could not parse existing sudopasswd entry"
490 uuid = Match.group(1)
491 status = Match.group(2)
492 hosts = Match.group(3)
493 cryptedpass = Match.group(4)
495 if SudoPasswd.has_key(uuid):
496 confirmedHosts = SudoPasswd[uuid][0]
497 confirmedHmac = SudoPasswd[uuid][1]
498 if status.startswith('confirmed:'):
499 if status == 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass):
500 result = result + "Entry %s for sudo password on hosts %s already confirmed.\n"%(uuid, hosts)
502 result = result + "Entry %s for sudo password on hosts %s is listed as confirmed, but HMAC does not verify.\n"%(uuid, hosts)
503 elif confirmedHosts != hosts:
504 result = result + "Entry %s hostlist mismatch (%s vs. %s).\n"%(uuid, hosts, confirmedHosts)
505 elif make_passwd_hmac('confirm-new-password', 'sudo', uid, uuid, hosts, cryptedpass) == confirmedHmac:
506 result = result + "Entry %s for sudo password on hosts %s now confirmed.\n"%(uuid, hosts)
507 status = 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass)
509 result = result + "Entry %s for sudo password on hosts %s HMAC verify failed.\n"%(uuid, hosts)
512 newentry = " ".join([uuid, status, hosts, cryptedpass])
513 if len(newldap) == 0:
514 newldap.append((ldap.MOD_REPLACE,"sudoPassword",newentry))
516 newldap.append((ldap.MOD_ADD,"sudoPassword",newentry))
518 for entry in SudoPasswd:
519 result = result + "Entry %s that you confirm is not listed in ldap."%(entry)
521 for entry in newldap:
526 # Handle an [almost] arbitary change
527 def HandleChange(Reply,DnRecord,Key):
529 Lines = re.split("\n *\r?",PlainText);
540 # Try to process a command line
541 Result = Result + "> "+Line+"\n";
547 badkeys = LoadBadSSH()
548 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
549 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
550 DoDel(Line,Attrs) or DoRBL(Line,Attrs) or DoConfirmSudopassword(Line)
553 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
555 # Fail, if someone tries to send someone elses signed email to the
556 # daemon then we want to abort ASAP.
559 Result = Result + "Command is not understood. Halted - no changes committed\n";
561 Result = Result + Res + "\n";
563 # Connect to the ldap server
565 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
566 AccessPass = F.readline().strip().split(" ")
569 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
570 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
571 if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
572 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
573 raise UDNotAllowedError, "This account is locked";
575 if CommitChanges == 1: # only if we are still good to go
577 Res = FinishConfirmSudopassword(l, GetAttr(DnRecord,"uid"), Attrs)
578 Result = Result + Res + "\n";
581 Result = Result + "FinishConfirmSudopassword raised an error (%s) - no changes committed\n"%(e);
584 if CommitChanges == 1:
585 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
586 l.modify_s(Dn,Attrs);
590 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
592 raise UDNotAllowedError, "User not found"
593 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
596 Subst["__FROM__"] = ChangeFrom;
597 Subst["__EMAIL__"] = EmailAddress(DnRecord);
598 Subst["__ADMIN__"] = ReplyTo;
599 Subst["__RESULT__"] = Result;
600 Subst["__ATTR__"] = Attribs;
602 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
604 # Handle ping handles an email sent to the 'ping' address (ie this program
605 # called with a ping argument) It replies with a dump of the public records.
606 def HandlePing(Reply,DnRecord,Key):
608 Subst["__FROM__"] = PingFrom;
609 Subst["__EMAIL__"] = EmailAddress(DnRecord);
610 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
611 Subst["__ADMIN__"] = ReplyTo;
613 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
615 # Handle a change password email sent to the change password address
616 # (this program called with the chpass argument)
617 def HandleChPass(Reply,DnRecord,Key):
618 # Generate a random password
619 Password = GenPass();
620 Pass = HashPass(Password);
622 # Use GPG to encrypt it
623 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
628 raise UDFormatError, "Unable to generate the encrypted reply, gpg failed.";
631 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
633 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
634 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
637 Subst["__FROM__"] = ChPassFrom;
638 Subst["__EMAIL__"] = EmailAddress(DnRecord);
639 Subst["__CRYPTTYPE__"] = Type;
640 Subst["__PASSWORD__"] = Message;
641 Subst["__ADMIN__"] = ReplyTo;
642 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
644 # Connect to the ldap server
646 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
647 AccessPass = F.readline().strip().split(" ")
649 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
651 # Check for a locked account
652 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
653 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
654 or GetAttr(Attrs[0],"userPassword").startswith("!"):
655 raise UDNotAllowedError, "This account is locked";
657 # Modify the password
658 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass),
659 (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60)))];
660 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
665 # Start of main program
667 # Drop messages from a mailer daemon.
668 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
671 ErrMsg = "Indeterminate Error";
672 ErrType = EX_TEMPFAIL;
674 # Startup the replay cache
675 ErrType = EX_TEMPFAIL;
676 ErrMsg = "Failed to initialize the replay cache:";
679 ErrType = EX_PERMFAIL;
680 ErrMsg = "Failed to understand the email or find a signature:";
681 Email = mimetools.Message(sys.stdin,0);
682 Msg = GetClearSig(Email);
684 ErrMsg = "Message is not PGP signed:"
685 if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
686 Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
687 raise UDFormatError, "No PGP signature";
689 # Check the signature
690 ErrMsg = "Unable to check the signature or the signature was invalid:";
691 Res = GPGCheckSig(Msg[0]);
694 raise UDFormatError, Res[0];
697 raise UDFormatError, "Null signature text";
699 # Extract the plain message text in the event of mime encoding
701 ErrMsg = "Problem stripping MIME headers from the decoded message"
704 Index = Res[3].index("\n\n") + 2;
706 Index = Res[3].index("\n\r\n") + 3;
707 PlainText = Res[3][Index:];
711 # Connect to the ldap server
712 ErrType = EX_TEMPFAIL;
713 ErrMsg = "An error occured while performing the LDAP lookup";
716 l.simple_bind_s("","");
718 # Search for the matching key fingerprint
719 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
721 ErrType = EX_PERMFAIL;
723 raise UDFormatError, "Key not found"
725 raise UDFormatError, "Oddly your key fingerprint is assigned to more than one account.."
728 # Check the signature against the replay cache
729 RC = ReplayCache(ReplayCacheFile);
731 ErrMsg = "The replay cache rejected your message. Check your clock!";
732 Rply = RC.Check(Res[1]);
735 raise UDNotAllowedError, Rply;
739 # Determine the sender address
740 ErrMsg = "A problem occured while trying to formulate the reply";
741 Sender = Email.getheader("Reply-To");
743 Sender = Email.getheader("From");
745 raise UDFormatError, "Unable to determine the sender's address";
748 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
749 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
752 if sys.argv[1] == "ping":
753 Reply = HandlePing(Reply,Attrs[0],Res[2]);
754 elif sys.argv[1] == "chpass":
755 if PlainText.strip().find("Please change my Debian password") != 0:
756 raise UDFormatError,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
757 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
758 elif sys.argv[1] == "change":
759 Reply = HandleChange(Reply,Attrs[0],Res[2]);
762 raise UDFormatError, "Incorrect Invokation";
764 # Send the message through sendmail
765 ErrMsg = "A problem occured while trying to send the reply";
766 Child = os.popen("/usr/sbin/sendmail -t","w");
767 # Child = os.popen("cat","w");
769 if Child.close() != None:
770 raise UDExecuteError, "Sendmail gave a non-zero return code";
774 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
775 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
779 Subst["__ERROR__"] = ErrMsg;
780 Subst["__ADMIN__"] = ReplyTo;
782 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
783 List = traceback.extract_tb(sys.exc_traceback);
785 Trace = Trace + "Python Stack Trace:\n";
787 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
789 Subst["__TRACE__"] = Trace;
791 # Try to send the bounce
793 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
795 Child = os.popen("/usr/sbin/sendmail -t -oi -f ''","w");
796 Child.write(ErrReplyHead);
797 Child.write(ErrReply);
798 if Child.close() != None:
799 raise UDExecuteError, "Sendmail gave a non-zero return code";
801 sys.exit(EX_TEMPFAIL);
803 if ErrType != EX_PERMFAIL:
809 # vim:set shiftwidth=3: