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)$",
70 DelItems = {"c": None,
72 "facsimileTelephoneNumber": None,
73 "telephoneNumber": None,
74 "postalAddress": None,
86 "sshRSAAuthKey": None,
88 "mailGreylisting": None,
92 "mailWhitelist": None,
93 "mailDisableMessage": None,
98 # Decode a GPS location from some common forms
99 def LocDecode(Str,Dir):
100 # Check for Decimal degrees, DGM, or DGMS
101 if re.match("^[+-]?[\d.]+$",Str) != None:
104 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
106 # Check for DDDxMM.MMMM where x = [nsew]
107 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
110 Deg = G[0]; Min = G[2]; Dr = G[1];
113 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
116 Deg = G[0]; Dr = G[1];
118 # Check for DD:MM.MM x
119 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
122 Deg = G[0]; Min = G[1]; Dr = G[2];
124 # Check for DD:MM:SS.SS x
125 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
128 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
132 raise UDFormatError, "Bad degrees";
133 if Min != None and float(Min) > 60:
134 raise UDFormatError, "Bad minutes";
135 if Sec != None and float(Sec) > 60:
136 raise UDFormatError, "Bad seconds";
138 # Pad on an extra leading 0 to disambiguate small numbers
139 if len(Deg) <= 1 or Deg[1] == '.':
141 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
143 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
146 # Construct a DGM/DGMS type value from the components.
157 # Handle changing a set of arbitary fields
159 def DoArbChange(Str,Attrs):
160 Match = re.match("^([^ :]+): (.*)$",Str);
165 attrName = G[0].lower();
166 for i in ArbChanges.keys():
167 if i.lower() == attrName:
170 if ArbChanges.has_key(attrName) == 0:
173 if re.match(ArbChanges[attrName],G[1]) == None:
174 raise UDFormatError, "Item does not match the required format"+ArbChanges[attrName];
177 if attrName == 'gender':
178 if G[1] not in GenderTable:
179 raise UDFormatError, "Gender not found in table"
180 value = GenderTable[G[1]]
182 # if attrName == 'birthDate':
183 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
184 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
185 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
187 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
189 # } elsif ($bd_day <= 28) {
192 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
193 # if ($bd_day <= 30) {
197 # if ($bd_day <= 31) {
202 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
205 Attrs.append((ldap.MOD_REPLACE,attrName,value));
206 return "Changed entry %s to %s"%(attrName,value);
208 # Handle changing a set of arbitary fields
210 def DoDel(Str,Attrs):
211 Match = re.match("^del (.*)$",Str);
216 attrName = G[0].lower();
217 for i in DelItems.keys():
218 if i.lower() == attrName:
221 if DelItems.has_key(attrName) == 0:
222 return "Cannot erase entry %s"%(attrName);
224 Attrs.append((ldap.MOD_DELETE,attrName,None));
225 return "Removed entry %s"%(attrName);
227 # Handle a position change message, the line format is:
228 # Lat: -12412.23 Long: +12341.2342
229 def DoPosition(Str,Attrs):
230 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
236 sLat = LocDecode(G[0],"ns");
237 sLong = LocDecode(G[1],"ew");
238 Lat = DecDegree(sLat,1);
239 Long = DecDegree(sLong,1);
241 raise UDFormatError, "Positions were found, but they are not correctly formed";
243 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
244 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
245 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
247 # Load bad ssh fingerprints
249 f = open(SSHFingerprintFile, "r")
251 FingerprintLine = re.compile('^([0-9a-f\:]{47}).*$')
252 for line in f.readlines():
253 Match = FingerprintLine.match(line)
254 if Match is not None:
259 # Handle an SSH authentication key, the line format is:
260 # [options] 1024 35 13188913666680[..] [comment]
261 def DoSSH(Str, Attrs, badkeys, uid):
262 Match = SSH2AuthSplit.match(Str);
268 Match = SSHRSA1Match.match(Str)
269 if Match is not None:
270 return "RSA1 keys not supported anymore"
273 (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
275 f.write("%s\n" % (Str))
277 cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
278 (result, output) = commands.getstatusoutput(cmd)
281 raise UDExecuteError, "ssh-keygen -l invocation failed!\n%s\n" % (output)
285 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
286 ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
288 Subst["__ADMIN__"] = ReplyTo
289 Subst["__USER__"] = uid
291 Match = SSHFingerprint.match(output)
297 Subst["__ERROR__"] = "SSH keysize %s is below limit 1024" % (g[0])
298 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
300 Child = os.popen("/usr/sbin/sendmail -t","w")
301 Child.write(ErrReplyHead)
302 Child.write(ErrReply)
303 if Child.close() != None:
304 raise UDExecuteError, "Sendmail gave a non-zero return code"
306 sys.exit(EX_TEMPFAIL)
308 # And now break and stop processing input, which sends a reply to the user.
309 raise UDFormatError, "SSH keys must have at least 1024 bits, processing halted, NOTHING MODIFIED AT ALL"
310 elif g[1] in badkeys:
313 Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
314 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
316 Child = os.popen("/usr/sbin/sendmail -t","w")
317 Child.write(ErrReplyHead)
318 Child.write(ErrReply)
319 if Child.close() != None:
320 raise UDExecuteError, "Sendmail gave a non-zero return code"
322 sys.exit(EX_TEMPFAIL)
324 # And now break and stop processing input, which sends a reply to the user.
325 raise UDFormatError, "Submitted SSH Key known to be bad and insecure, processing halted, NOTHING MODIFIED AT ALL"
327 if (typekey == "dss"):
328 return "DSA keys not accepted anymore"
332 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
333 return "SSH Key added "+FormatSSHAuth(Str);
335 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
337 return "SSH Keys replaced with "+FormatSSHAuth(Str);
339 # Handle changing a dns entry
340 # host IN A 12.12.12.12
341 # host IN AAAA 1234::5678
342 # host IN CNAME foo.bar. <- Trailing dot is required
343 # host IN MX foo.bar. <- Trailing dot is required
344 def DoDNS(Str,Attrs,DnRecord):
345 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
346 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
347 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
348 #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)
349 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
351 if cnamerecord == None and\
353 mxrecord == None and\
357 # Check if the name is already taken
358 G = re.match('^([-\w+]+)\s',Str)
360 raise UDFormatError, "Hostname not found although we already passed record syntax checks"
361 hostname = G.group(1)
363 # Check for collisions
365 # [JT 20070409 - search for both tab and space suffixed hostnames
366 # since we accept either. It'd probably be better to parse the
367 # incoming string in order to construct what we feed LDAP rather
368 # than just passing it through as is.]
369 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
370 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
372 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
373 return "DNS entry is already owned by " + GetAttr(x,"uid")
379 if DNS.has_key(hostname):
380 return "CNAME and other RR types not allowed: "+Str
384 if DNS.has_key(hostname) and DNS[hostname] == 2:
385 return "CNAME and other RR types not allowed: "+Str
389 if cnamerecord != None:
390 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
391 elif arecord != None:
392 ipaddress = arecord.group(1)
393 for quad in ipaddress.split('.'):
394 if not (int(quad) >=0 and int(quad) <= 255):
395 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
396 sanitized = "%s IN A %s"% (hostname, ipaddress)
397 elif mxrecord != None:
398 priority = mxrecord.group(1)
399 mx = mxrecord.group(2)
400 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
401 elif aaaarecord != None:
402 ipv6address = aaaarecord.group(1)
403 parts = ipv6address.split(':')
405 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
407 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
412 seenEmptypart = False
415 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
418 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
420 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
422 raise UDFormatError, "None of the types I recognize was it. I shouldn't be here. confused."
425 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
426 return "DNS Entry added "+sanitized;
428 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
430 return "DNS Entry replaced with "+sanitized;
432 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
433 def DoRBL(Str,Attrs):
434 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
438 if Match.group(1) == "rbl":
440 if Match.group(1) == "rhsbl":
442 if Match.group(1) == "whitelist":
443 Key = "mailWhitelist"
444 Host = Match.group(2)
447 if SeenList.has_key(Key):
448 Attrs.append((ldap.MOD_ADD,Key,Host))
449 return "%s added %s" % (Key,Host)
451 Attrs.append((ldap.MOD_REPLACE,Key,Host))
453 return "%s replaced with %s" % (Key,Host)
455 # Handle a ConfirmSudoPassword request
456 def DoConfirmSudopassword(Str):
457 Match = re.compile('^confirm sudopassword ('+UUID_FORMAT+') ([a-z0-9.,*]+) ([0-9a-f]{40})$').match(Str)
461 uuid = Match.group(1)
462 hosts = Match.group(2)
463 hmac = Match.group(3)
466 SudoPasswd[uuid] = (hosts, hmac)
467 return "got confirm for sudo password %s on host(s) %s, auth code %s" % (uuid,hosts, hmac)
469 def FinishConfirmSudopassword(l, uid, Attrs):
473 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+uid, ['sudoPassword']);
475 raise UDFormatError, "Not exactly one hit when searching for user"
476 if res[0][1].has_key('sudoPassword'):
477 inldap = res[0][1]['sudoPassword']
483 Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*]+) ([^ ]+)$').match(entry)
485 raise UDFormatError, "Could not parse existing sudopasswd entry"
486 uuid = Match.group(1)
487 status = Match.group(2)
488 hosts = Match.group(3)
489 cryptedpass = Match.group(4)
491 if SudoPasswd.has_key(uuid):
492 confirmedHosts = SudoPasswd[uuid][0]
493 confirmedHmac = SudoPasswd[uuid][1]
494 if status.startswith('confirmed:'):
495 if status == 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass):
496 result = result + "Entry %s for sudo password on hosts %s already confirmed.\n"%(uuid, hosts)
498 result = result + "Entry %s for sudo password on hosts %s is listed as confirmed, but HMAC does not verify.\n"%(uuid, hosts)
499 elif confirmedHosts != hosts:
500 result = result + "Entry %s hostlist mismatch (%s vs. %s).\n"%(uuid, hosts, confirmedHosts)
501 elif make_passwd_hmac('confirm-new-password', 'sudo', uid, uuid, hosts, cryptedpass) == confirmedHmac:
502 result = result + "Entry %s for sudo password on hosts %s now confirmed.\n"%(uuid, hosts)
503 status = 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass)
505 result = result + "Entry %s for sudo password on hosts %s HMAC verify failed.\n"%(uuid, hosts)
508 newentry = " ".join([uuid, status, hosts, cryptedpass])
509 if len(newldap) == 0:
510 newldap.append((ldap.MOD_REPLACE,"sudoPassword",newentry))
512 newldap.append((ldap.MOD_ADD,"sudoPassword",newentry))
514 for entry in SudoPasswd:
515 result = result + "Entry %s that you confirm is not listed in ldap."%(entry)
517 for entry in newldap:
522 # Handle an [almost] arbitary change
523 def HandleChange(Reply,DnRecord,Key):
525 Lines = re.split("\n *\r?",PlainText);
536 # Try to process a command line
537 Result = Result + "> "+Line+"\n";
543 badkeys = LoadBadSSH()
544 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
545 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
546 DoDel(Line,Attrs) or DoRBL(Line,Attrs) or DoConfirmSudopassword(Line)
549 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
551 # Fail, if someone tries to send someone elses signed email to the
552 # daemon then we want to abort ASAP.
555 Result = Result + "Command is not understood. Halted - no changes committed\n";
557 Result = Result + Res + "\n";
559 # Connect to the ldap server
561 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
562 AccessPass = F.readline().strip().split(" ")
565 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
566 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
567 if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
568 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
569 raise UDNotAllowedError, "This account is locked";
571 if CommitChanges == 1: # only if we are still good to go
573 Res = FinishConfirmSudopassword(l, GetAttr(DnRecord,"uid"), Attrs)
574 Result = Result + Res + "\n";
577 Result = Result + "FinishConfirmSudopassword raised an error (%s) - no changes committed\n"%(e);
580 if CommitChanges == 1:
581 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
582 l.modify_s(Dn,Attrs);
586 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
588 raise UDNotAllowedError, "User not found"
589 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
592 Subst["__FROM__"] = ChangeFrom;
593 Subst["__EMAIL__"] = EmailAddress(DnRecord);
594 Subst["__ADMIN__"] = ReplyTo;
595 Subst["__RESULT__"] = Result;
596 Subst["__ATTR__"] = Attribs;
598 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
600 # Handle ping handles an email sent to the 'ping' address (ie this program
601 # called with a ping argument) It replies with a dump of the public records.
602 def HandlePing(Reply,DnRecord,Key):
604 Subst["__FROM__"] = PingFrom;
605 Subst["__EMAIL__"] = EmailAddress(DnRecord);
606 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
607 Subst["__ADMIN__"] = ReplyTo;
609 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
611 # Handle a change password email sent to the change password address
612 # (this program called with the chpass argument)
613 def HandleChPass(Reply,DnRecord,Key):
614 # Generate a random password
615 Password = GenPass();
616 Pass = HashPass(Password);
618 # Use GPG to encrypt it
619 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
624 raise UDFormatError, "Unable to generate the encrypted reply, gpg failed.";
627 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
629 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
630 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
633 Subst["__FROM__"] = ChPassFrom;
634 Subst["__EMAIL__"] = EmailAddress(DnRecord);
635 Subst["__CRYPTTYPE__"] = Type;
636 Subst["__PASSWORD__"] = Message;
637 Subst["__ADMIN__"] = ReplyTo;
638 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
640 # Connect to the ldap server
642 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
643 AccessPass = F.readline().strip().split(" ")
645 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
647 # Check for a locked account
648 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
649 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
650 or GetAttr(Attrs[0],"userPassword").startswith("!"):
651 raise UDNotAllowedError, "This account is locked";
653 # Modify the password
654 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass),
655 (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60)))];
656 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
661 # Start of main program
663 # Drop messages from a mailer daemon.
664 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
667 ErrMsg = "Indeterminate Error";
668 ErrType = EX_TEMPFAIL;
670 # Startup the replay cache
671 ErrType = EX_TEMPFAIL;
672 ErrMsg = "Failed to initialize the replay cache:";
675 ErrType = EX_PERMFAIL;
676 ErrMsg = "Failed to understand the email or find a signature:";
677 Email = mimetools.Message(sys.stdin,0);
678 Msg = GetClearSig(Email);
680 ErrMsg = "Message is not PGP signed:"
681 if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
682 Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
683 raise UDFormatError, "No PGP signature";
685 # Check the signature
686 ErrMsg = "Unable to check the signature or the signature was invalid:";
687 Res = GPGCheckSig(Msg[0]);
690 raise UDFormatError, Res[0];
693 raise UDFormatError, "Null signature text";
695 # Extract the plain message text in the event of mime encoding
697 ErrMsg = "Problem stripping MIME headers from the decoded message"
700 Index = Res[3].index("\n\n") + 2;
702 Index = Res[3].index("\n\r\n") + 3;
703 PlainText = Res[3][Index:];
707 # Connect to the ldap server
708 ErrType = EX_TEMPFAIL;
709 ErrMsg = "An error occured while performing the LDAP lookup";
712 l.simple_bind_s("","");
714 # Search for the matching key fingerprint
715 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
717 ErrType = EX_PERMFAIL;
719 raise UDFormatError, "Key not found"
721 raise UDFormatError, "Oddly your key fingerprint is assigned to more than one account.."
724 # Check the signature against the replay cache
725 RC = ReplayCache(ReplayCacheFile);
727 ErrMsg = "The replay cache rejected your message. Check your clock!";
728 Rply = RC.Check(Res[1]);
731 raise UDNotAllowedError, Rply;
735 # Determine the sender address
736 ErrMsg = "A problem occured while trying to formulate the reply";
737 Sender = Email.getheader("Reply-To");
739 Sender = Email.getheader("From");
741 raise UDFormatError, "Unable to determine the sender's address";
744 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
745 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
748 if sys.argv[1] == "ping":
749 Reply = HandlePing(Reply,Attrs[0],Res[2]);
750 elif sys.argv[1] == "chpass":
751 if PlainText.strip().find("Please change my Debian password") != 0:
752 raise UDFormatError,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
753 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
754 elif sys.argv[1] == "change":
755 Reply = HandleChange(Reply,Attrs[0],Res[2]);
758 raise UDFormatError, "Incorrect Invokation";
760 # Send the message through sendmail
761 ErrMsg = "A problem occured while trying to send the reply";
762 Child = os.popen("/usr/sbin/sendmail -t","w");
763 # Child = os.popen("cat","w");
765 if Child.close() != None:
766 raise UDExecuteError, "Sendmail gave a non-zero return code";
770 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
771 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
775 Subst["__ERROR__"] = ErrMsg;
776 Subst["__ADMIN__"] = ReplyTo;
778 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
779 List = traceback.extract_tb(sys.exc_traceback);
781 Trace = Trace + "Python Stack Trace:\n";
783 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
785 Subst["__TRACE__"] = Trace;
787 # Try to send the bounce
789 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
791 Child = os.popen("/usr/sbin/sendmail -t -oi -f ''","w");
792 Child.write(ErrReplyHead);
793 Child.write(ErrReply);
794 if Child.close() != None:
795 raise UDExecuteError, "Sendmail gave a non-zero return code";
797 sys.exit(EX_TEMPFAIL);
799 if ErrType != EX_PERMFAIL:
805 # vim:set shiftwidth=3: