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
14 import sha as sha1_module
16 from userdir_gpg import *
17 from userdir_ldap 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';
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": ".*",
59 "emailForward": "^([^<>@]+@.+)?$",
60 "jabberJID": "^([^<>@]+@.+)?$",
65 "birthDate": "^([0-9]{4})([01][0-9])([0-3][0-9])$",
66 "mailDisableMessage": ".*",
67 "mailGreylisting": "^(TRUE|FALSE)$",
68 "mailCallout": "^(TRUE|FALSE)$",
70 "gender": "^(1|2|9|male|female|unspecified)$",
73 DelItems = {"c": None,
75 "facsimileTelephoneNumber": None,
76 "telephoneNumber": None,
77 "postalAddress": None,
89 "sshRSAAuthKey": None,
90 "sshDSAAuthKey": None,
92 "mailGreylisting": None,
96 "mailWhitelist": None,
97 "mailDisableMessage": None,
102 F = open(PassDir+"/key-hmac","r");
103 key = F.readline().strip()
106 return hmac.new(key, str, sha1_module).hexdigest
110 # Decode a GPS location from some common forms
111 def LocDecode(Str,Dir):
112 # Check for Decimal degrees, DGM, or DGMS
113 if re.match("^[+-]?[\d.]+$",Str) != None:
116 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
118 # Check for DDDxMM.MMMM where x = [nsew]
119 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
122 Deg = G[0]; Min = G[2]; Dr = G[1];
125 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
128 Deg = G[0]; Dr = G[1];
130 # Check for DD:MM.MM x
131 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
134 Deg = G[0]; Min = G[1]; Dr = G[2];
136 # Check for DD:MM:SS.SS x
137 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
140 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
144 raise "Failed","Bad degrees";
145 if Min != None and float(Min) > 60:
146 raise "Failed","Bad minutes";
147 if Sec != None and float(Sec) > 60:
148 raise "Failed","Bad seconds";
150 # Pad on an extra leading 0 to disambiguate small numbers
151 if len(Deg) <= 1 or Deg[1] == '.':
153 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
155 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
158 # Construct a DGM/DGMS type value from the components.
169 # Handle changing a set of arbitary fields
171 def DoArbChange(Str,Attrs):
172 Match = re.match("^([^ :]+): (.*)$",Str);
177 attrName = G[0].lower();
178 for i in ArbChanges.keys():
179 if i.lower() == attrName:
182 if ArbChanges.has_key(attrName) == 0:
185 if re.match(ArbChanges[attrName],G[1]) == None:
186 raise Error, "Item does not match the required format"+ArbChanges[attrName];
189 if attrName == 'gender':
190 if G[1] not in GenderTable:
191 raise Error, "Gender not found in table"
192 value = GenderTable[G[1]]
194 # if attrName == 'birthDate':
195 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
196 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
197 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
199 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
201 # } elsif ($bd_day <= 28) {
204 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
205 # if ($bd_day <= 30) {
209 # if ($bd_day <= 31) {
214 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
217 Attrs.append((ldap.MOD_REPLACE,attrName,value));
218 return "Changed entry %s to %s"%(attrName,value);
220 # Handle changing a set of arbitary fields
222 def DoDel(Str,Attrs):
223 Match = re.match("^del (.*)$",Str);
228 attrName = G[0].lower();
229 for i in DelItems.keys():
230 if i.lower() == attrName:
233 if DelItems.has_key(attrName) == 0:
234 return "Cannot erase entry %s"%(attrName);
236 Attrs.append((ldap.MOD_DELETE,attrName,None));
237 return "Removed entry %s"%(attrName);
239 # Handle a position change message, the line format is:
240 # Lat: -12412.23 Long: +12341.2342
241 def DoPosition(Str,Attrs):
242 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
248 sLat = LocDecode(G[0],"ns");
249 sLong = LocDecode(G[1],"ew");
250 Lat = DecDegree(sLat,1);
251 Long = DecDegree(sLong,1);
253 raise Error, "Positions were found, but they are not correctly formed";
255 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
256 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
257 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
259 # Load bad ssh fingerprints
261 f = open(SSHFingerprintFile, "r")
263 FingerprintLine = re.compile('^([0-9a-f\:]{47}).*$')
264 for line in f.readlines():
265 Match = FingerprintLine.match(line)
266 if Match is not None:
271 # Handle an SSH authentication key, the line format is:
272 # [options] 1024 35 13188913666680[..] [comment]
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 (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
287 f.write("%s\n" % (Str))
289 cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
290 (result, output) = commands.getstatusoutput(cmd)
293 raise Error, "ssh-keygen -l invocation failed!\n%s\n" % (output)
297 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
298 ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
300 Subst["__ADMIN__"] = ReplyTo
301 Subst["__USER__"] = uid
303 Match = SSHFingerprint.match(output)
309 Subst["__ERROR__"] = "SSH keysize %s is below limit 1024" % (g[0])
310 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
312 Child = os.popen("/usr/sbin/sendmail -t","w")
313 Child.write(ErrReplyHead)
314 Child.write(ErrReply)
315 if Child.close() != None:
316 raise Error, "Sendmail gave a non-zero return code"
318 sys.exit(EX_TEMPFAIL)
320 # And now break and stop processing input, which sends a reply to the user.
321 raise Error, "SSH keys must have at least 1024 bits, processing halted, NOTHING MODIFIED AT ALL"
322 elif g[1] in badkeys:
325 Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
326 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
328 Child = os.popen("/usr/sbin/sendmail -t","w")
329 Child.write(ErrReplyHead)
330 Child.write(ErrReply)
331 if Child.close() != None:
332 raise Error, "Sendmail gave a non-zero return code"
334 sys.exit(EX_TEMPFAIL)
336 # And now break and stop processing input, which sends a reply to the user.
337 raise Error, "Submitted SSH Key known to be bad and insecure, processing halted, NOTHING MODIFIED AT ALL"
339 if (typekey == "dss"):
340 return "DSA keys not accepted anymore"
344 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
345 return "SSH Key added "+FormatSSHAuth(Str);
347 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
349 return "SSH Keys replaced with "+FormatSSHAuth(Str);
351 # Handle changing a dns entry
352 # host IN A 12.12.12.12
353 # host IN AAAA 1234::5678
354 # host IN CNAME foo.bar. <- Trailing dot is required
355 # host IN MX foo.bar. <- Trailing dot is required
356 def DoDNS(Str,Attrs,DnRecord):
357 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
358 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
359 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
360 #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)
361 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
363 if cnamerecord == None and\
365 mxrecord == None and\
369 # Check if the name is already taken
370 G = re.match('^([-\w+]+)\s',Str)
372 raise Error, "Hostname not found although we already passed record syntax checks"
373 hostname = G.group(1)
375 # Check for collisions
377 # [JT 20070409 - search for both tab and space suffixed hostnames
378 # since we accept either. It'd probably be better to parse the
379 # incoming string in order to construct what we feed LDAP rather
380 # than just passing it through as is.]
381 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
382 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
384 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
385 return "DNS entry is already owned by " + GetAttr(x,"uid")
391 if DNS.has_key(hostname):
392 return "CNAME and other RR types not allowed: "+Str
396 if DNS.has_key(hostname) and DNS[hostname] == 2:
397 return "CNAME and other RR types not allowed: "+Str
401 if cnamerecord != None:
402 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
403 elif arecord != None:
404 ipaddress = arecord.group(1)
405 for quad in ipaddress.split('.'):
406 if not (int(quad) >=0 and int(quad) <= 255):
407 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
408 sanitized = "%s IN A %s"% (hostname, ipaddress)
409 elif mxrecord != None:
410 priority = mxrecord.group(1)
411 mx = mxrecord.group(2)
412 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
413 elif aaaarecord != None:
414 ipv6address = aaaarecord.group(1)
415 parts = ipv6address.split(':')
417 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
419 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
424 seenEmptypart = False
427 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
430 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
432 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
434 raise Error, "None of the types I recognize was it. I shouldn't be here. confused."
437 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
438 return "DNS Entry added "+sanitized;
440 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
442 return "DNS Entry replaced with "+sanitized;
444 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
445 def DoRBL(Str,Attrs):
446 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
450 if Match.group(1) == "rbl":
452 if Match.group(1) == "rhsbl":
454 if Match.group(1) == "whitelist":
455 Key = "mailWhitelist"
456 Host = Match.group(2)
459 if SeenList.has_key(Key):
460 Attrs.append((ldap.MOD_ADD,Key,Host))
461 return "%s added %s" % (Key,Host)
463 Attrs.append((ldap.MOD_REPLACE,Key,Host))
465 return "%s replaced with %s" % (Key,Host)
467 # Handle a ConfirmSudoPassword request
468 def DoConfirmSudopassword(Str):
469 Match = re.compile('^confirm sudopassword ('+UUID_FORMAT+') ([a-z0-9,*]+) ([0-9a-f]{40})$').match(Str.lower())
473 uuid = Match.group(1)
474 hosts = Match.group(2)
475 hmac = Match.group(3)
478 SudoPasswd[uuid] = (hosts, hmac)
479 return "got confirm for sudo password %s on host(s) %s, auth code %s" % (uuid,hosts, hmac)
481 def FinishConfirmSudopassword(l, uid, Attrs):
485 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+uid, ['sudoPassword']);
487 raise Error, "Not exactly one hit when searching for user"
489 if Attrs.has_key('sudoPassword'):
490 inldap = Attrs['sudoPassword']
496 Match = re.compile('^('+UUID_FORMAT+') (confirmed|unconfirmed) ([a-z0-9,*]+) ([^ ]+)$'),match(entry.lower())
498 raise Error, "Could not parse existing sudopasswd entry"
499 uuid = Match.group(1)
500 status = Match.group(2)
501 hosts = Match.group(3)
502 cryptedpass = Match.group(4)
504 if SudoPasswd.has_key(uuid):
505 confirmedHosts = SudoPasswd[uuid][0]
506 confirmedHmac = SudoPasswd[uuid][1]
507 if status == "confirmed":
508 result = result + "Entry %s for sudo password on hosts %s already confirmed.\n"%(uuid, hosts)
509 elif confirmedHosts != hosts:
510 result = result + "Entry %s hostlist mismatch (%s vs. %s).\n"%(uuid, hosts, confirmedHosts)
511 elif make_hmac(':'.join([uuid, hosts, cryptedpass])) == confirmedHmac:
512 result = result + "Entry %s for sudo password on hosts %s now confirmed.\n"%(uuid, hosts)
515 result = result + "Entry %s for sudo password on hosts %s HMAC verify failed.\n"%(uuid, hosts)
518 newentry = " ".join([uuid, status, hosts, cryptedpass])
519 if len(newldap) == 0:
520 newldap.append((ldap.MOD_ADD,"sudoPassword",newentry))
522 newldap.append((ldap.MOD_REPLACE,"sudoPassword",newentry))
524 for entry in SudoPasswd:
525 result = result + "Entry %s that you confirm is not listed in ldap."%(entry)
527 for entry in newldap:
532 # Handle an [almost] arbitary change
533 def HandleChange(Reply,DnRecord,Key):
535 Lines = re.split("\n *\r?",PlainText);
546 # Try to process a command line
547 Result = Result + "> "+Line+"\n";
553 badkeys = LoadBadSSH()
554 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
555 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
556 DoDel(Line,Attrs) or DoRBL(Line,Attrs) or DoConfirmSudopassword(Line)
559 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
561 # Fail, if someone tries to send someone elses signed email to the
562 # daemon then we want to abort ASAP.
565 Result = Result + "Command is not understood. Halted - no changes committed\n";
567 Result = Result + Res + "\n";
569 # Connect to the ldap server
571 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
572 AccessPass = F.readline().strip().split(" ")
575 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
576 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
577 if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
578 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
579 raise Error, "This account is locked";
581 Res = FinishConfirmSudopassword(l, GetAttr(DnRecord,"uid"), Attrs)
582 Result = Result + Res + "\n";
585 Result = Result + "FinishConfirmSudopassword raised an error (%s) - no changes committed\n"%(e);
587 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
588 if CommitChanges == 1:
589 l.modify_s(Dn,Attrs);
593 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
595 raise Error, "User not found"
596 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
599 Subst["__FROM__"] = ChangeFrom;
600 Subst["__EMAIL__"] = EmailAddress(DnRecord);
601 Subst["__ADMIN__"] = ReplyTo;
602 Subst["__RESULT__"] = Result;
603 Subst["__ATTR__"] = Attribs;
605 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
607 # Handle ping handles an email sent to the 'ping' address (ie this program
608 # called with a ping argument) It replies with a dump of the public records.
609 def HandlePing(Reply,DnRecord,Key):
611 Subst["__FROM__"] = PingFrom;
612 Subst["__EMAIL__"] = EmailAddress(DnRecord);
613 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
614 Subst["__ADMIN__"] = ReplyTo;
616 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
618 # Handle a change password email sent to the change password address
619 # (this program called with the chpass argument)
620 def HandleChPass(Reply,DnRecord,Key):
621 # Generate a random password
622 Password = GenPass();
623 Pass = HashPass(Password);
625 # Use GPG to encrypt it
626 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
631 raise Error, "Unable to generate the encrypted reply, gpg failed.";
634 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
636 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
637 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
640 Subst["__FROM__"] = ChPassFrom;
641 Subst["__EMAIL__"] = EmailAddress(DnRecord);
642 Subst["__CRYPTTYPE__"] = Type;
643 Subst["__PASSWORD__"] = Message;
644 Subst["__ADMIN__"] = ReplyTo;
645 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
647 # Connect to the ldap server
649 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
650 AccessPass = F.readline().strip().split(" ")
652 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
654 # Check for a locked account
655 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
656 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
657 or GetAttr(Attrs[0],"userPassword").startswith("!"):
658 raise Error, "This account is locked";
660 # Modify the password
661 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass),
662 (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60)))];
663 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
668 # Start of main program
670 # Drop messages from a mailer daemon.
671 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
674 ErrMsg = "Indeterminate Error";
675 ErrType = EX_TEMPFAIL;
677 # Startup the replay cache
678 ErrType = EX_TEMPFAIL;
679 ErrMsg = "Failed to initialize the replay cache:";
680 RC = ReplayCache(ReplayCacheFile);
684 ErrType = EX_PERMFAIL;
685 ErrMsg = "Failed to understand the email or find a signature:";
686 Email = mimetools.Message(sys.stdin,0);
687 Msg = GetClearSig(Email);
689 ErrMsg = "Message is not PGP signed:"
690 if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
691 Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
692 raise Error, "No PGP signature";
694 # Check the signature
695 ErrMsg = "Unable to check the signature or the signature was invalid:";
696 Res = GPGCheckSig(Msg[0]);
702 raise Error, "Null signature text";
704 # Extract the plain message text in the event of mime encoding
706 ErrMsg = "Problem stripping MIME headers from the decoded message"
709 Index = Res[3].index("\n\n") + 2;
711 Index = Res[3].index("\n\r\n") + 3;
712 PlainText = Res[3][Index:];
716 # Check the signature against the replay cache
717 ErrMsg = "The replay cache rejected your message. Check your clock!";
718 Rply = RC.Check(Res[1]);
722 # Connect to the ldap server
723 ErrType = EX_TEMPFAIL;
724 ErrMsg = "An error occured while performing the LDAP lookup";
727 l.simple_bind_s("","");
729 # Search for the matching key fingerprint
730 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
732 ErrType = EX_PERMFAIL;
734 raise Error, "Key not found"
736 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
740 # Determine the sender address
741 ErrMsg = "A problem occured while trying to formulate the reply";
742 Sender = Email.getheader("Reply-To");
744 Sender = Email.getheader("From");
746 raise Error, "Unable to determine the sender's address";
749 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
750 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
753 if sys.argv[1] == "ping":
754 Reply = HandlePing(Reply,Attrs[0],Res[2]);
755 elif sys.argv[1] == "chpass":
756 if PlainText.strip().find("Please change my Debian password") != 0:
757 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
758 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
759 elif sys.argv[1] == "change":
760 Reply = HandleChange(Reply,Attrs[0],Res[2]);
763 raise Error, "Incorrect Invokation";
765 # Send the message through sendmail
766 ErrMsg = "A problem occured while trying to send the reply";
767 Child = os.popen("/usr/sbin/sendmail -t","w");
768 # Child = os.popen("cat","w");
770 if Child.close() != None:
771 raise Error, "Sendmail gave a non-zero return code";
775 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
776 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
780 Subst["__ERROR__"] = ErrMsg;
781 Subst["__ADMIN__"] = ReplyTo;
783 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
784 List = traceback.extract_tb(sys.exc_traceback);
786 Trace = Trace + "Python Stack Trace:\n";
788 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
790 Subst["__TRACE__"] = Trace;
792 # Try to send the bounce
794 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
796 Child = os.popen("/usr/sbin/sendmail -t","w");
797 Child.write(ErrReplyHead);
798 Child.write(ErrReply);
799 if Child.close() != None:
800 raise Error, "Sendmail gave a non-zero return code";
802 sys.exit(EX_TEMPFAIL);
804 if ErrType != EX_PERMFAIL: