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": ".*",
56 "emailForward": "^([^<>@]+@.+)?$",
57 "jabberJID": "^([^<>@]+@.+)?$",
62 "birthDate": "^([0-9]{4})([01][0-9])([0-3][0-9])$",
63 "mailDisableMessage": ".*",
64 "mailGreylisting": "^(TRUE|FALSE)$",
65 "mailCallout": "^(TRUE|FALSE)$",
67 "gender": "^(1|2|9|male|female|unspecified)$",
68 "mailContentInspectionAction": "^(reject|blackhole|markup)$",
71 DelItems = {"c": None,
73 "facsimileTelephoneNumber": None,
74 "telephoneNumber": None,
75 "postalAddress": None,
87 "sshRSAAuthKey": None,
89 "mailGreylisting": None,
93 "mailWhitelist": None,
94 "mailDisableMessage": None,
96 "mailContentInspectionAction": None,
100 # Decode a GPS location from some common forms
101 def LocDecode(Str,Dir):
102 # Check for Decimal degrees, DGM, or DGMS
103 if re.match("^[+-]?[\d.]+$",Str) != None:
106 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
108 # Check for DDDxMM.MMMM where x = [nsew]
109 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
112 Deg = G[0]; Min = G[2]; Dr = G[1];
115 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
118 Deg = G[0]; Dr = G[1];
120 # Check for DD:MM.MM x
121 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
124 Deg = G[0]; Min = G[1]; Dr = G[2];
126 # Check for DD:MM:SS.SS x
127 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
130 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
134 raise UDFormatError, "Bad degrees";
135 if Min != None and float(Min) > 60:
136 raise UDFormatError, "Bad minutes";
137 if Sec != None and float(Sec) > 60:
138 raise UDFormatError, "Bad seconds";
140 # Pad on an extra leading 0 to disambiguate small numbers
141 if len(Deg) <= 1 or Deg[1] == '.':
143 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
145 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
148 # Construct a DGM/DGMS type value from the components.
159 # Handle changing a set of arbitary fields
161 def DoArbChange(Str,Attrs):
162 Match = re.match("^([^ :]+): (.*)$",Str);
167 attrName = G[0].lower();
168 for i in ArbChanges.keys():
169 if i.lower() == attrName:
172 if ArbChanges.has_key(attrName) == 0:
175 if re.match(ArbChanges[attrName],G[1]) == None:
176 raise UDFormatError, "Item does not match the required format"+ArbChanges[attrName];
179 if attrName == 'gender':
180 if G[1] not in GenderTable:
181 raise UDFormatError, "Gender not found in table"
182 value = GenderTable[G[1]]
184 # if attrName == 'birthDate':
185 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
186 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
187 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
189 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
191 # } elsif ($bd_day <= 28) {
194 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
195 # if ($bd_day <= 30) {
199 # if ($bd_day <= 31) {
204 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
207 Attrs.append((ldap.MOD_REPLACE,attrName,value));
208 return "Changed entry %s to %s"%(attrName,value);
210 # Handle changing a set of arbitary fields
212 def DoDel(Str,Attrs):
213 Match = re.match("^del (.*)$",Str);
218 attrName = G[0].lower();
219 for i in DelItems.keys():
220 if i.lower() == attrName:
223 if DelItems.has_key(attrName) == 0:
224 return "Cannot erase entry %s"%(attrName);
226 Attrs.append((ldap.MOD_DELETE,attrName,None));
227 return "Removed entry %s"%(attrName);
229 # Handle a position change message, the line format is:
230 # Lat: -12412.23 Long: +12341.2342
231 def DoPosition(Str,Attrs):
232 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
238 sLat = LocDecode(G[0],"ns");
239 sLong = LocDecode(G[1],"ew");
240 Lat = DecDegree(sLat,1);
241 Long = DecDegree(sLong,1);
243 raise UDFormatError, "Positions were found, but they are not correctly formed";
245 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
246 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
247 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
249 # Load bad ssh fingerprints
251 f = open(SSHFingerprintFile, "r")
253 FingerprintLine = re.compile('^([0-9a-f\:]{47}).*$')
254 for line in f.readlines():
255 Match = FingerprintLine.match(line)
256 if Match is not None:
261 # Handle an SSH authentication key, the line format is:
262 # [options] 1024 35 13188913666680[..] [comment]
263 def DoSSH(Str, Attrs, badkeys, uid):
264 Match = SSH2AuthSplit.match(Str);
270 Match = SSHRSA1Match.match(Str)
271 if Match is not None:
272 return "RSA1 keys not supported anymore"
275 (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
277 f.write("%s\n" % (Str))
279 cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
280 (result, output) = commands.getstatusoutput(cmd)
283 raise UDExecuteError, "ssh-keygen -l invocation failed!\n%s\n" % (output)
287 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
288 ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
290 Subst["__ADMIN__"] = ReplyTo
291 Subst["__USER__"] = uid
293 Match = SSHFingerprint.match(output)
299 Subst["__ERROR__"] = "SSH keysize %s is below limit 1024" % (g[0])
300 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
302 Child = os.popen("/usr/sbin/sendmail -t","w")
303 Child.write(ErrReplyHead)
304 Child.write(ErrReply)
305 if Child.close() != None:
306 raise UDExecuteError, "Sendmail gave a non-zero return code"
308 sys.exit(EX_TEMPFAIL)
310 # And now break and stop processing input, which sends a reply to the user.
311 raise UDFormatError, "SSH keys must have at least 1024 bits, processing halted, NOTHING MODIFIED AT ALL"
312 elif g[1] in badkeys:
315 Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
316 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
318 Child = os.popen("/usr/sbin/sendmail -t","w")
319 Child.write(ErrReplyHead)
320 Child.write(ErrReply)
321 if Child.close() != None:
322 raise UDExecuteError, "Sendmail gave a non-zero return code"
324 sys.exit(EX_TEMPFAIL)
326 # And now break and stop processing input, which sends a reply to the user.
327 raise UDFormatError, "Submitted SSH Key known to be bad and insecure, processing halted, NOTHING MODIFIED AT ALL"
329 if (typekey == "dss"):
330 return "DSA keys not accepted anymore"
334 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
335 return "SSH Key added "+FormatSSHAuth(Str);
337 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
339 return "SSH Keys replaced with "+FormatSSHAuth(Str);
341 # Handle changing a dns entry
342 # host IN A 12.12.12.12
343 # host IN AAAA 1234::5678
344 # host IN CNAME foo.bar. <- Trailing dot is required
345 # host IN MX foo.bar. <- Trailing dot is required
346 def DoDNS(Str,Attrs,DnRecord):
347 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
348 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
349 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
350 #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)
351 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
353 if cnamerecord == None and\
355 mxrecord == None and\
359 # Check if the name is already taken
360 G = re.match('^([-\w+]+)\s',Str)
362 raise UDFormatError, "Hostname not found although we already passed record syntax checks"
363 hostname = G.group(1)
365 # Check for collisions
367 # [JT 20070409 - search for both tab and space suffixed hostnames
368 # since we accept either. It'd probably be better to parse the
369 # incoming string in order to construct what we feed LDAP rather
370 # than just passing it through as is.]
371 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
372 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
374 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
375 return "DNS entry is already owned by " + GetAttr(x,"uid")
381 if DNS.has_key(hostname):
382 return "CNAME and other RR types not allowed: "+Str
386 if DNS.has_key(hostname) and DNS[hostname] == 2:
387 return "CNAME and other RR types not allowed: "+Str
391 if cnamerecord != None:
392 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
393 elif arecord != None:
394 ipaddress = arecord.group(1)
395 for quad in ipaddress.split('.'):
396 if not (int(quad) >=0 and int(quad) <= 255):
397 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
398 sanitized = "%s IN A %s"% (hostname, ipaddress)
399 elif mxrecord != None:
400 priority = mxrecord.group(1)
401 mx = mxrecord.group(2)
402 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
403 elif aaaarecord != None:
404 ipv6address = aaaarecord.group(1)
405 parts = ipv6address.split(':')
407 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
409 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
414 seenEmptypart = False
417 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
420 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
422 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
424 raise UDFormatError, "None of the types I recognize was it. I shouldn't be here. confused."
427 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
428 return "DNS Entry added "+sanitized;
430 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
432 return "DNS Entry replaced with "+sanitized;
434 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
435 def DoRBL(Str,Attrs):
436 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
440 if Match.group(1) == "rbl":
442 if Match.group(1) == "rhsbl":
444 if Match.group(1) == "whitelist":
445 Key = "mailWhitelist"
446 Host = Match.group(2)
449 if SeenList.has_key(Key):
450 Attrs.append((ldap.MOD_ADD,Key,Host))
451 return "%s added %s" % (Key,Host)
453 Attrs.append((ldap.MOD_REPLACE,Key,Host))
455 return "%s replaced with %s" % (Key,Host)
457 # Handle a ConfirmSudoPassword request
458 def DoConfirmSudopassword(Str):
459 Match = re.compile('^confirm sudopassword ('+UUID_FORMAT+') ([a-z0-9.,*]+) ([0-9a-f]{40})$').match(Str)
463 uuid = Match.group(1)
464 hosts = Match.group(2)
465 hmac = Match.group(3)
468 SudoPasswd[uuid] = (hosts, hmac)
469 return "got confirm for sudo password %s on host(s) %s, auth code %s" % (uuid,hosts, hmac)
471 def FinishConfirmSudopassword(l, uid, Attrs):
475 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+uid, ['sudoPassword']);
477 raise UDFormatError, "Not exactly one hit when searching for user"
478 if res[0][1].has_key('sudoPassword'):
479 inldap = res[0][1]['sudoPassword']
485 Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*]+) ([^ ]+)$').match(entry)
487 raise UDFormatError, "Could not parse existing sudopasswd entry"
488 uuid = Match.group(1)
489 status = Match.group(2)
490 hosts = Match.group(3)
491 cryptedpass = Match.group(4)
493 if SudoPasswd.has_key(uuid):
494 confirmedHosts = SudoPasswd[uuid][0]
495 confirmedHmac = SudoPasswd[uuid][1]
496 if status.startswith('confirmed:'):
497 if status == 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass):
498 result = result + "Entry %s for sudo password on hosts %s already confirmed.\n"%(uuid, hosts)
500 result = result + "Entry %s for sudo password on hosts %s is listed as confirmed, but HMAC does not verify.\n"%(uuid, hosts)
501 elif confirmedHosts != hosts:
502 result = result + "Entry %s hostlist mismatch (%s vs. %s).\n"%(uuid, hosts, confirmedHosts)
503 elif make_passwd_hmac('confirm-new-password', 'sudo', uid, uuid, hosts, cryptedpass) == confirmedHmac:
504 result = result + "Entry %s for sudo password on hosts %s now confirmed.\n"%(uuid, hosts)
505 status = 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass)
507 result = result + "Entry %s for sudo password on hosts %s HMAC verify failed.\n"%(uuid, hosts)
510 newentry = " ".join([uuid, status, hosts, cryptedpass])
511 if len(newldap) == 0:
512 newldap.append((ldap.MOD_REPLACE,"sudoPassword",newentry))
514 newldap.append((ldap.MOD_ADD,"sudoPassword",newentry))
516 for entry in SudoPasswd:
517 result = result + "Entry %s that you confirm is not listed in ldap."%(entry)
519 for entry in newldap:
524 # Handle an [almost] arbitary change
525 def HandleChange(Reply,DnRecord,Key):
527 Lines = re.split("\n *\r?",PlainText);
538 # Try to process a command line
539 Result = Result + "> "+Line+"\n";
545 badkeys = LoadBadSSH()
546 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
547 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
548 DoDel(Line,Attrs) or DoRBL(Line,Attrs) or DoConfirmSudopassword(Line)
551 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
553 # Fail, if someone tries to send someone elses signed email to the
554 # daemon then we want to abort ASAP.
557 Result = Result + "Command is not understood. Halted - no changes committed\n";
559 Result = Result + Res + "\n";
561 # Connect to the ldap server
563 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
564 AccessPass = F.readline().strip().split(" ")
567 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
568 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
569 if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
570 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
571 raise UDNotAllowedError, "This account is locked";
573 if CommitChanges == 1: # only if we are still good to go
575 Res = FinishConfirmSudopassword(l, GetAttr(DnRecord,"uid"), Attrs)
576 Result = Result + Res + "\n";
579 Result = Result + "FinishConfirmSudopassword raised an error (%s) - no changes committed\n"%(e);
582 if CommitChanges == 1:
583 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
584 l.modify_s(Dn,Attrs);
588 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
590 raise UDNotAllowedError, "User not found"
591 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
594 Subst["__FROM__"] = ChangeFrom;
595 Subst["__EMAIL__"] = EmailAddress(DnRecord);
596 Subst["__ADMIN__"] = ReplyTo;
597 Subst["__RESULT__"] = Result;
598 Subst["__ATTR__"] = Attribs;
600 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
602 # Handle ping handles an email sent to the 'ping' address (ie this program
603 # called with a ping argument) It replies with a dump of the public records.
604 def HandlePing(Reply,DnRecord,Key):
606 Subst["__FROM__"] = PingFrom;
607 Subst["__EMAIL__"] = EmailAddress(DnRecord);
608 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
609 Subst["__ADMIN__"] = ReplyTo;
611 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
613 # Handle a change password email sent to the change password address
614 # (this program called with the chpass argument)
615 def HandleChPass(Reply,DnRecord,Key):
616 # Generate a random password
617 Password = GenPass();
618 Pass = HashPass(Password);
620 # Use GPG to encrypt it
621 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
626 raise UDFormatError, "Unable to generate the encrypted reply, gpg failed.";
629 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
631 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
632 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
635 Subst["__FROM__"] = ChPassFrom;
636 Subst["__EMAIL__"] = EmailAddress(DnRecord);
637 Subst["__CRYPTTYPE__"] = Type;
638 Subst["__PASSWORD__"] = Message;
639 Subst["__ADMIN__"] = ReplyTo;
640 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
642 # Connect to the ldap server
644 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
645 AccessPass = F.readline().strip().split(" ")
647 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
649 # Check for a locked account
650 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
651 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
652 or GetAttr(Attrs[0],"userPassword").startswith("!"):
653 raise UDNotAllowedError, "This account is locked";
655 # Modify the password
656 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass),
657 (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60)))];
658 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
663 # Start of main program
665 # Drop messages from a mailer daemon.
666 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
669 ErrMsg = "Indeterminate Error";
670 ErrType = EX_TEMPFAIL;
672 # Startup the replay cache
673 ErrType = EX_TEMPFAIL;
674 ErrMsg = "Failed to initialize the replay cache:";
677 ErrType = EX_PERMFAIL;
678 ErrMsg = "Failed to understand the email or find a signature:";
679 Email = mimetools.Message(sys.stdin,0);
680 Msg = GetClearSig(Email);
682 ErrMsg = "Message is not PGP signed:"
683 if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
684 Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
685 raise UDFormatError, "No PGP signature";
687 # Check the signature
688 ErrMsg = "Unable to check the signature or the signature was invalid:";
689 Res = GPGCheckSig(Msg[0]);
692 raise UDFormatError, Res[0];
695 raise UDFormatError, "Null signature text";
697 # Extract the plain message text in the event of mime encoding
699 ErrMsg = "Problem stripping MIME headers from the decoded message"
702 Index = Res[3].index("\n\n") + 2;
704 Index = Res[3].index("\n\r\n") + 3;
705 PlainText = Res[3][Index:];
709 # Connect to the ldap server
710 ErrType = EX_TEMPFAIL;
711 ErrMsg = "An error occured while performing the LDAP lookup";
714 l.simple_bind_s("","");
716 # Search for the matching key fingerprint
717 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
719 ErrType = EX_PERMFAIL;
721 raise UDFormatError, "Key not found"
723 raise UDFormatError, "Oddly your key fingerprint is assigned to more than one account.."
726 # Check the signature against the replay cache
727 RC = ReplayCache(ReplayCacheFile);
729 ErrMsg = "The replay cache rejected your message. Check your clock!";
730 Rply = RC.Check(Res[1]);
733 raise UDNotAllowedError, Rply;
737 # Determine the sender address
738 ErrMsg = "A problem occured while trying to formulate the reply";
739 Sender = Email.getheader("Reply-To");
741 Sender = Email.getheader("From");
743 raise UDFormatError, "Unable to determine the sender's address";
746 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
747 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
750 if sys.argv[1] == "ping":
751 Reply = HandlePing(Reply,Attrs[0],Res[2]);
752 elif sys.argv[1] == "chpass":
753 if PlainText.strip().find("Please change my Debian password") != 0:
754 raise UDFormatError,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
755 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
756 elif sys.argv[1] == "change":
757 Reply = HandleChange(Reply,Attrs[0],Res[2]);
760 raise UDFormatError, "Incorrect Invokation";
762 # Send the message through sendmail
763 ErrMsg = "A problem occured while trying to send the reply";
764 Child = os.popen("/usr/sbin/sendmail -t","w");
765 # Child = os.popen("cat","w");
767 if Child.close() != None:
768 raise UDExecuteError, "Sendmail gave a non-zero return code";
772 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
773 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
777 Subst["__ERROR__"] = ErrMsg;
778 Subst["__ADMIN__"] = ReplyTo;
780 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
781 List = traceback.extract_tb(sys.exc_traceback);
783 Trace = Trace + "Python Stack Trace:\n";
785 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
787 Subst["__TRACE__"] = Trace;
789 # Try to send the bounce
791 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
793 Child = os.popen("/usr/sbin/sendmail -t -oi -f ''","w");
794 Child.write(ErrReplyHead);
795 Child.write(ErrReply);
796 if Child.close() != None:
797 raise UDExecuteError, "Sendmail gave a non-zero return code";
799 sys.exit(EX_TEMPFAIL);
801 if ErrType != EX_PERMFAIL:
807 # vim:set shiftwidth=3: