4 # Prior copyright probably rmurray, troup, joey, jgg -- weasel 2008
5 # Copyright (c) 2008 Peter Palfrader <peter@palfrader.org>
6 # Copyright (c) 2008 Joerg Jaspert <joerg@debian.org>
8 import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, os, commands
11 from userdir_gpg import *
12 from userdir_ldap import *
14 # Error codes from /usr/include/sysexits.h
15 ReplyTo = ConfModule.replyto;
16 PingFrom = ConfModule.pingfrom;
17 ChPassFrom = ConfModule.chpassfrom;
18 ChangeFrom = ConfModule.changefrom;
19 ReplayCacheFile = ConfModule.replaycachefile;
20 SSHFingerprintFile = ConfModule.fingerprintfile
22 UUID_FORMAT = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
25 EX_PERMFAIL = 65; # EX_DATAERR
26 Error = 'Message Error';
36 SSHFingerprint = re.compile('^(\d+) ([0-9a-f\:]{47}) (.+)$')
37 SSHRSA1Match = re.compile('^^(.* )?\d+ \d+ \d+')
39 GenderTable = {"male": 1,
47 ArbChanges = {"c": "..",
49 "facsimileTelephoneNumber": ".*",
50 "telephoneNumber": ".*",
51 "postalAddress": ".*",
54 "emailForward": "^([^<>@]+@.+)?$",
55 "jabberJID": "^([^<>@]+@.+)?$",
60 "birthDate": "^([0-9]{4})([01][0-9])([0-3][0-9])$",
61 "mailDisableMessage": ".*",
62 "mailGreylisting": "^(TRUE|FALSE)$",
63 "mailCallout": "^(TRUE|FALSE)$",
65 "gender": "^(1|2|9|male|female|unspecified)$",
68 DelItems = {"c": None,
70 "facsimileTelephoneNumber": None,
71 "telephoneNumber": None,
72 "postalAddress": None,
84 "sshRSAAuthKey": None,
86 "mailGreylisting": None,
90 "mailWhitelist": None,
91 "mailDisableMessage": None,
96 # Decode a GPS location from some common forms
97 def LocDecode(Str,Dir):
98 # Check for Decimal degrees, DGM, or DGMS
99 if re.match("^[+-]?[\d.]+$",Str) != None:
102 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
104 # Check for DDDxMM.MMMM where x = [nsew]
105 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
108 Deg = G[0]; Min = G[2]; Dr = G[1];
111 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
114 Deg = G[0]; Dr = G[1];
116 # Check for DD:MM.MM x
117 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
120 Deg = G[0]; Min = G[1]; Dr = G[2];
122 # Check for DD:MM:SS.SS x
123 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
126 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
130 raise "Failed","Bad degrees";
131 if Min != None and float(Min) > 60:
132 raise "Failed","Bad minutes";
133 if Sec != None and float(Sec) > 60:
134 raise "Failed","Bad seconds";
136 # Pad on an extra leading 0 to disambiguate small numbers
137 if len(Deg) <= 1 or Deg[1] == '.':
139 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
141 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
144 # Construct a DGM/DGMS type value from the components.
155 # Handle changing a set of arbitary fields
157 def DoArbChange(Str,Attrs):
158 Match = re.match("^([^ :]+): (.*)$",Str);
163 attrName = G[0].lower();
164 for i in ArbChanges.keys():
165 if i.lower() == attrName:
168 if ArbChanges.has_key(attrName) == 0:
171 if re.match(ArbChanges[attrName],G[1]) == None:
172 raise Error, "Item does not match the required format"+ArbChanges[attrName];
175 if attrName == 'gender':
176 if G[1] not in GenderTable:
177 raise Error, "Gender not found in table"
178 value = GenderTable[G[1]]
180 # if attrName == 'birthDate':
181 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
182 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
183 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
185 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
187 # } elsif ($bd_day <= 28) {
190 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
191 # if ($bd_day <= 30) {
195 # if ($bd_day <= 31) {
200 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
203 Attrs.append((ldap.MOD_REPLACE,attrName,value));
204 return "Changed entry %s to %s"%(attrName,value);
206 # Handle changing a set of arbitary fields
208 def DoDel(Str,Attrs):
209 Match = re.match("^del (.*)$",Str);
214 attrName = G[0].lower();
215 for i in DelItems.keys():
216 if i.lower() == attrName:
219 if DelItems.has_key(attrName) == 0:
220 return "Cannot erase entry %s"%(attrName);
222 Attrs.append((ldap.MOD_DELETE,attrName,None));
223 return "Removed entry %s"%(attrName);
225 # Handle a position change message, the line format is:
226 # Lat: -12412.23 Long: +12341.2342
227 def DoPosition(Str,Attrs):
228 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
234 sLat = LocDecode(G[0],"ns");
235 sLong = LocDecode(G[1],"ew");
236 Lat = DecDegree(sLat,1);
237 Long = DecDegree(sLong,1);
239 raise Error, "Positions were found, but they are not correctly formed";
241 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
242 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
243 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
245 # Load bad ssh fingerprints
247 f = open(SSHFingerprintFile, "r")
249 FingerprintLine = re.compile('^([0-9a-f\:]{47}).*$')
250 for line in f.readlines():
251 Match = FingerprintLine.match(line)
252 if Match is not None:
257 # Handle an SSH authentication key, the line format is:
258 # [options] 1024 35 13188913666680[..] [comment]
259 def DoSSH(Str, Attrs, badkeys, uid):
260 Match = SSH2AuthSplit.match(Str);
266 Match = SSHRSA1Match.match(Str)
267 if Match is not None:
268 return "RSA1 keys not supported anymore"
271 (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
273 f.write("%s\n" % (Str))
275 cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
276 (result, output) = commands.getstatusoutput(cmd)
279 raise Error, "ssh-keygen -l invocation failed!\n%s\n" % (output)
283 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
284 ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
286 Subst["__ADMIN__"] = ReplyTo
287 Subst["__USER__"] = uid
289 Match = SSHFingerprint.match(output)
295 Subst["__ERROR__"] = "SSH keysize %s is below limit 1024" % (g[0])
296 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
298 Child = os.popen("/usr/sbin/sendmail -t","w")
299 Child.write(ErrReplyHead)
300 Child.write(ErrReply)
301 if Child.close() != None:
302 raise Error, "Sendmail gave a non-zero return code"
304 sys.exit(EX_TEMPFAIL)
306 # And now break and stop processing input, which sends a reply to the user.
307 raise Error, "SSH keys must have at least 1024 bits, processing halted, NOTHING MODIFIED AT ALL"
308 elif g[1] in badkeys:
311 Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
312 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
314 Child = os.popen("/usr/sbin/sendmail -t","w")
315 Child.write(ErrReplyHead)
316 Child.write(ErrReply)
317 if Child.close() != None:
318 raise Error, "Sendmail gave a non-zero return code"
320 sys.exit(EX_TEMPFAIL)
322 # And now break and stop processing input, which sends a reply to the user.
323 raise Error, "Submitted SSH Key known to be bad and insecure, processing halted, NOTHING MODIFIED AT ALL"
325 if (typekey == "dss"):
326 return "DSA keys not accepted anymore"
330 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
331 return "SSH Key added "+FormatSSHAuth(Str);
333 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
335 return "SSH Keys replaced with "+FormatSSHAuth(Str);
337 # Handle changing a dns entry
338 # host IN A 12.12.12.12
339 # host IN AAAA 1234::5678
340 # host IN CNAME foo.bar. <- Trailing dot is required
341 # host IN MX foo.bar. <- Trailing dot is required
342 def DoDNS(Str,Attrs,DnRecord):
343 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
344 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
345 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
346 #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)
347 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
349 if cnamerecord == None and\
351 mxrecord == None and\
355 # Check if the name is already taken
356 G = re.match('^([-\w+]+)\s',Str)
358 raise Error, "Hostname not found although we already passed record syntax checks"
359 hostname = G.group(1)
361 # Check for collisions
363 # [JT 20070409 - search for both tab and space suffixed hostnames
364 # since we accept either. It'd probably be better to parse the
365 # incoming string in order to construct what we feed LDAP rather
366 # than just passing it through as is.]
367 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
368 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
370 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
371 return "DNS entry is already owned by " + GetAttr(x,"uid")
377 if DNS.has_key(hostname):
378 return "CNAME and other RR types not allowed: "+Str
382 if DNS.has_key(hostname) and DNS[hostname] == 2:
383 return "CNAME and other RR types not allowed: "+Str
387 if cnamerecord != None:
388 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
389 elif arecord != None:
390 ipaddress = arecord.group(1)
391 for quad in ipaddress.split('.'):
392 if not (int(quad) >=0 and int(quad) <= 255):
393 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
394 sanitized = "%s IN A %s"% (hostname, ipaddress)
395 elif mxrecord != None:
396 priority = mxrecord.group(1)
397 mx = mxrecord.group(2)
398 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
399 elif aaaarecord != None:
400 ipv6address = aaaarecord.group(1)
401 parts = ipv6address.split(':')
403 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
405 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
410 seenEmptypart = False
413 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
416 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
418 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
420 raise Error, "None of the types I recognize was it. I shouldn't be here. confused."
423 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
424 return "DNS Entry added "+sanitized;
426 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
428 return "DNS Entry replaced with "+sanitized;
430 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
431 def DoRBL(Str,Attrs):
432 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
436 if Match.group(1) == "rbl":
438 if Match.group(1) == "rhsbl":
440 if Match.group(1) == "whitelist":
441 Key = "mailWhitelist"
442 Host = Match.group(2)
445 if SeenList.has_key(Key):
446 Attrs.append((ldap.MOD_ADD,Key,Host))
447 return "%s added %s" % (Key,Host)
449 Attrs.append((ldap.MOD_REPLACE,Key,Host))
451 return "%s replaced with %s" % (Key,Host)
453 # Handle a ConfirmSudoPassword request
454 def DoConfirmSudopassword(Str):
455 Match = re.compile('^confirm sudopassword ('+UUID_FORMAT+') ([a-z0-9.,*]+) ([0-9a-f]{40})$').match(Str)
459 uuid = Match.group(1)
460 hosts = Match.group(2)
461 hmac = Match.group(3)
464 SudoPasswd[uuid] = (hosts, hmac)
465 return "got confirm for sudo password %s on host(s) %s, auth code %s" % (uuid,hosts, hmac)
467 def FinishConfirmSudopassword(l, uid, Attrs):
471 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+uid, ['sudoPassword']);
473 raise Error, "Not exactly one hit when searching for user"
474 if res[0][1].has_key('sudoPassword'):
475 inldap = res[0][1]['sudoPassword']
481 Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*]+) ([^ ]+)$').match(entry)
483 raise Error, "Could not parse existing sudopasswd entry"
484 uuid = Match.group(1)
485 status = Match.group(2)
486 hosts = Match.group(3)
487 cryptedpass = Match.group(4)
489 if SudoPasswd.has_key(uuid):
490 confirmedHosts = SudoPasswd[uuid][0]
491 confirmedHmac = SudoPasswd[uuid][1]
492 if status.startswith('confirmed:'):
493 if status == 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass):
494 result = result + "Entry %s for sudo password on hosts %s already confirmed.\n"%(uuid, hosts)
496 result = result + "Entry %s for sudo password on hosts %s is listed as confirmed, but HMAC does not verify.\n"%(uuid, hosts)
497 elif confirmedHosts != hosts:
498 result = result + "Entry %s hostlist mismatch (%s vs. %s).\n"%(uuid, hosts, confirmedHosts)
499 elif make_passwd_hmac('confirm-new-password', 'sudo', uid, uuid, hosts, cryptedpass) == confirmedHmac:
500 result = result + "Entry %s for sudo password on hosts %s now confirmed.\n"%(uuid, hosts)
501 status = 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass)
503 result = result + "Entry %s for sudo password on hosts %s HMAC verify failed.\n"%(uuid, hosts)
506 newentry = " ".join([uuid, status, hosts, cryptedpass])
507 if len(newldap) == 0:
508 newldap.append((ldap.MOD_REPLACE,"sudoPassword",newentry))
510 newldap.append((ldap.MOD_ADD,"sudoPassword",newentry))
512 for entry in SudoPasswd:
513 result = result + "Entry %s that you confirm is not listed in ldap."%(entry)
515 for entry in newldap:
520 # Handle an [almost] arbitary change
521 def HandleChange(Reply,DnRecord,Key):
523 Lines = re.split("\n *\r?",PlainText);
534 # Try to process a command line
535 Result = Result + "> "+Line+"\n";
541 badkeys = LoadBadSSH()
542 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
543 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
544 DoDel(Line,Attrs) or DoRBL(Line,Attrs) or DoConfirmSudopassword(Line)
547 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
549 # Fail, if someone tries to send someone elses signed email to the
550 # daemon then we want to abort ASAP.
553 Result = Result + "Command is not understood. Halted - no changes committed\n";
555 Result = Result + Res + "\n";
557 # Connect to the ldap server
559 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
560 AccessPass = F.readline().strip().split(" ")
563 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
564 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
565 if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
566 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
567 raise Error, "This account is locked";
569 if CommitChanges == 1: # only if we are still good to go
571 Res = FinishConfirmSudopassword(l, GetAttr(DnRecord,"uid"), Attrs)
572 Result = Result + Res + "\n";
575 Result = Result + "FinishConfirmSudopassword raised an error (%s) - no changes committed\n"%(e);
578 if CommitChanges == 1:
579 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
580 l.modify_s(Dn,Attrs);
584 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
586 raise Error, "User not found"
587 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
590 Subst["__FROM__"] = ChangeFrom;
591 Subst["__EMAIL__"] = EmailAddress(DnRecord);
592 Subst["__ADMIN__"] = ReplyTo;
593 Subst["__RESULT__"] = Result;
594 Subst["__ATTR__"] = Attribs;
596 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
598 # Handle ping handles an email sent to the 'ping' address (ie this program
599 # called with a ping argument) It replies with a dump of the public records.
600 def HandlePing(Reply,DnRecord,Key):
602 Subst["__FROM__"] = PingFrom;
603 Subst["__EMAIL__"] = EmailAddress(DnRecord);
604 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
605 Subst["__ADMIN__"] = ReplyTo;
607 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
609 # Handle a change password email sent to the change password address
610 # (this program called with the chpass argument)
611 def HandleChPass(Reply,DnRecord,Key):
612 # Generate a random password
613 Password = GenPass();
614 Pass = HashPass(Password);
616 # Use GPG to encrypt it
617 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
622 raise Error, "Unable to generate the encrypted reply, gpg failed.";
625 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
627 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
628 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
631 Subst["__FROM__"] = ChPassFrom;
632 Subst["__EMAIL__"] = EmailAddress(DnRecord);
633 Subst["__CRYPTTYPE__"] = Type;
634 Subst["__PASSWORD__"] = Message;
635 Subst["__ADMIN__"] = ReplyTo;
636 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
638 # Connect to the ldap server
640 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
641 AccessPass = F.readline().strip().split(" ")
643 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
645 # Check for a locked account
646 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
647 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
648 or GetAttr(Attrs[0],"userPassword").startswith("!"):
649 raise Error, "This account is locked";
651 # Modify the password
652 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass),
653 (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60)))];
654 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
659 # Start of main program
661 # Drop messages from a mailer daemon.
662 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
665 ErrMsg = "Indeterminate Error";
666 ErrType = EX_TEMPFAIL;
668 # Startup the replay cache
669 ErrType = EX_TEMPFAIL;
670 ErrMsg = "Failed to initialize the replay cache:";
671 RC = ReplayCache(ReplayCacheFile);
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 Error, "No PGP signature";
685 # Check the signature
686 ErrMsg = "Unable to check the signature or the signature was invalid:";
687 Res = GPGCheckSig(Msg[0]);
693 raise Error, "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 # Check the signature against the replay cache
708 ErrMsg = "The replay cache rejected your message. Check your clock!";
709 Rply = RC.Check(Res[1]);
713 # Connect to the ldap server
714 ErrType = EX_TEMPFAIL;
715 ErrMsg = "An error occured while performing the LDAP lookup";
718 l.simple_bind_s("","");
720 # Search for the matching key fingerprint
721 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
723 ErrType = EX_PERMFAIL;
725 raise Error, "Key not found"
727 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
731 # Determine the sender address
732 ErrMsg = "A problem occured while trying to formulate the reply";
733 Sender = Email.getheader("Reply-To");
735 Sender = Email.getheader("From");
737 raise Error, "Unable to determine the sender's address";
740 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
741 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
744 if sys.argv[1] == "ping":
745 Reply = HandlePing(Reply,Attrs[0],Res[2]);
746 elif sys.argv[1] == "chpass":
747 if PlainText.strip().find("Please change my Debian password") != 0:
748 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
749 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
750 elif sys.argv[1] == "change":
751 Reply = HandleChange(Reply,Attrs[0],Res[2]);
754 raise Error, "Incorrect Invokation";
756 # Send the message through sendmail
757 ErrMsg = "A problem occured while trying to send the reply";
758 Child = os.popen("/usr/sbin/sendmail -t","w");
759 # Child = os.popen("cat","w");
761 if Child.close() != None:
762 raise Error, "Sendmail gave a non-zero return code";
766 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
767 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
771 Subst["__ERROR__"] = ErrMsg;
772 Subst["__ADMIN__"] = ReplyTo;
774 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
775 List = traceback.extract_tb(sys.exc_traceback);
777 Trace = Trace + "Python Stack Trace:\n";
779 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
781 Subst["__TRACE__"] = Trace;
783 # Try to send the bounce
785 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
787 Child = os.popen("/usr/sbin/sendmail -t","w");
788 Child.write(ErrReplyHead);
789 Child.write(ErrReply);
790 if Child.close() != None:
791 raise Error, "Sendmail gave a non-zero return code";
793 sys.exit(EX_TEMPFAIL);
795 if ErrType != EX_PERMFAIL:
801 # vim:set shiftwidth=3: