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,
85 "sshDSAAuthKey": None,
87 "mailGreylisting": None,
91 "mailWhitelist": None,
92 "mailDisableMessage": None,
97 # Decode a GPS location from some common forms
98 def LocDecode(Str,Dir):
99 # Check for Decimal degrees, DGM, or DGMS
100 if re.match("^[+-]?[\d.]+$",Str) != None:
103 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
105 # Check for DDDxMM.MMMM where x = [nsew]
106 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
109 Deg = G[0]; Min = G[2]; Dr = G[1];
112 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
115 Deg = G[0]; Dr = G[1];
117 # Check for DD:MM.MM x
118 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
121 Deg = G[0]; Min = G[1]; Dr = G[2];
123 # Check for DD:MM:SS.SS x
124 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
127 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
131 raise "Failed","Bad degrees";
132 if Min != None and float(Min) > 60:
133 raise "Failed","Bad minutes";
134 if Sec != None and float(Sec) > 60:
135 raise "Failed","Bad seconds";
137 # Pad on an extra leading 0 to disambiguate small numbers
138 if len(Deg) <= 1 or Deg[1] == '.':
140 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
142 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
145 # Construct a DGM/DGMS type value from the components.
156 # Handle changing a set of arbitary fields
158 def DoArbChange(Str,Attrs):
159 Match = re.match("^([^ :]+): (.*)$",Str);
164 attrName = G[0].lower();
165 for i in ArbChanges.keys():
166 if i.lower() == attrName:
169 if ArbChanges.has_key(attrName) == 0:
172 if re.match(ArbChanges[attrName],G[1]) == None:
173 raise Error, "Item does not match the required format"+ArbChanges[attrName];
176 if attrName == 'gender':
177 if G[1] not in GenderTable:
178 raise Error, "Gender not found in table"
179 value = GenderTable[G[1]]
181 # if attrName == 'birthDate':
182 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
183 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
184 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
186 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
188 # } elsif ($bd_day <= 28) {
191 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
192 # if ($bd_day <= 30) {
196 # if ($bd_day <= 31) {
201 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
204 Attrs.append((ldap.MOD_REPLACE,attrName,value));
205 return "Changed entry %s to %s"%(attrName,value);
207 # Handle changing a set of arbitary fields
209 def DoDel(Str,Attrs):
210 Match = re.match("^del (.*)$",Str);
215 attrName = G[0].lower();
216 for i in DelItems.keys():
217 if i.lower() == attrName:
220 if DelItems.has_key(attrName) == 0:
221 return "Cannot erase entry %s"%(attrName);
223 Attrs.append((ldap.MOD_DELETE,attrName,None));
224 return "Removed entry %s"%(attrName);
226 # Handle a position change message, the line format is:
227 # Lat: -12412.23 Long: +12341.2342
228 def DoPosition(Str,Attrs):
229 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
235 sLat = LocDecode(G[0],"ns");
236 sLong = LocDecode(G[1],"ew");
237 Lat = DecDegree(sLat,1);
238 Long = DecDegree(sLong,1);
240 raise Error, "Positions were found, but they are not correctly formed";
242 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
243 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
244 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
246 # Load bad ssh fingerprints
248 f = open(SSHFingerprintFile, "r")
250 FingerprintLine = re.compile('^([0-9a-f\:]{47}).*$')
251 for line in f.readlines():
252 Match = FingerprintLine.match(line)
253 if Match is not None:
258 # Handle an SSH authentication key, the line format is:
259 # [options] 1024 35 13188913666680[..] [comment]
260 def DoSSH(Str, Attrs, badkeys, uid):
261 Match = SSH2AuthSplit.match(Str);
267 Match = SSHRSA1Match.match(Str)
268 if Match is not None:
269 return "RSA1 keys not supported anymore"
272 (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
274 f.write("%s\n" % (Str))
276 cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
277 (result, output) = commands.getstatusoutput(cmd)
280 raise Error, "ssh-keygen -l invocation failed!\n%s\n" % (output)
284 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
285 ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
287 Subst["__ADMIN__"] = ReplyTo
288 Subst["__USER__"] = uid
290 Match = SSHFingerprint.match(output)
296 Subst["__ERROR__"] = "SSH keysize %s is below limit 1024" % (g[0])
297 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
299 Child = os.popen("/usr/sbin/sendmail -t","w")
300 Child.write(ErrReplyHead)
301 Child.write(ErrReply)
302 if Child.close() != None:
303 raise Error, "Sendmail gave a non-zero return code"
305 sys.exit(EX_TEMPFAIL)
307 # And now break and stop processing input, which sends a reply to the user.
308 raise Error, "SSH keys must have at least 1024 bits, processing halted, NOTHING MODIFIED AT ALL"
309 elif g[1] in badkeys:
312 Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
313 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
315 Child = os.popen("/usr/sbin/sendmail -t","w")
316 Child.write(ErrReplyHead)
317 Child.write(ErrReply)
318 if Child.close() != None:
319 raise Error, "Sendmail gave a non-zero return code"
321 sys.exit(EX_TEMPFAIL)
323 # And now break and stop processing input, which sends a reply to the user.
324 raise Error, "Submitted SSH Key known to be bad and insecure, processing halted, NOTHING MODIFIED AT ALL"
326 if (typekey == "dss"):
327 return "DSA keys not accepted anymore"
331 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
332 return "SSH Key added "+FormatSSHAuth(Str);
334 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
336 return "SSH Keys replaced with "+FormatSSHAuth(Str);
338 # Handle changing a dns entry
339 # host IN A 12.12.12.12
340 # host IN AAAA 1234::5678
341 # host IN CNAME foo.bar. <- Trailing dot is required
342 # host IN MX foo.bar. <- Trailing dot is required
343 def DoDNS(Str,Attrs,DnRecord):
344 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
345 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
346 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
347 #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)
348 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
350 if cnamerecord == None and\
352 mxrecord == None and\
356 # Check if the name is already taken
357 G = re.match('^([-\w+]+)\s',Str)
359 raise Error, "Hostname not found although we already passed record syntax checks"
360 hostname = G.group(1)
362 # Check for collisions
364 # [JT 20070409 - search for both tab and space suffixed hostnames
365 # since we accept either. It'd probably be better to parse the
366 # incoming string in order to construct what we feed LDAP rather
367 # than just passing it through as is.]
368 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
369 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
371 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
372 return "DNS entry is already owned by " + GetAttr(x,"uid")
378 if DNS.has_key(hostname):
379 return "CNAME and other RR types not allowed: "+Str
383 if DNS.has_key(hostname) and DNS[hostname] == 2:
384 return "CNAME and other RR types not allowed: "+Str
388 if cnamerecord != None:
389 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
390 elif arecord != None:
391 ipaddress = arecord.group(1)
392 for quad in ipaddress.split('.'):
393 if not (int(quad) >=0 and int(quad) <= 255):
394 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
395 sanitized = "%s IN A %s"% (hostname, ipaddress)
396 elif mxrecord != None:
397 priority = mxrecord.group(1)
398 mx = mxrecord.group(2)
399 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
400 elif aaaarecord != None:
401 ipv6address = aaaarecord.group(1)
402 parts = ipv6address.split(':')
404 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
406 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
411 seenEmptypart = False
414 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
417 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
419 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
421 raise Error, "None of the types I recognize was it. I shouldn't be here. confused."
424 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
425 return "DNS Entry added "+sanitized;
427 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
429 return "DNS Entry replaced with "+sanitized;
431 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
432 def DoRBL(Str,Attrs):
433 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
437 if Match.group(1) == "rbl":
439 if Match.group(1) == "rhsbl":
441 if Match.group(1) == "whitelist":
442 Key = "mailWhitelist"
443 Host = Match.group(2)
446 if SeenList.has_key(Key):
447 Attrs.append((ldap.MOD_ADD,Key,Host))
448 return "%s added %s" % (Key,Host)
450 Attrs.append((ldap.MOD_REPLACE,Key,Host))
452 return "%s replaced with %s" % (Key,Host)
454 # Handle a ConfirmSudoPassword request
455 def DoConfirmSudopassword(Str):
456 Match = re.compile('^confirm sudopassword ('+UUID_FORMAT+') ([a-z0-9.,*]+) ([0-9a-f]{40})$').match(Str)
460 uuid = Match.group(1)
461 hosts = Match.group(2)
462 hmac = Match.group(3)
465 SudoPasswd[uuid] = (hosts, hmac)
466 return "got confirm for sudo password %s on host(s) %s, auth code %s" % (uuid,hosts, hmac)
468 def FinishConfirmSudopassword(l, uid, Attrs):
472 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+uid, ['sudoPassword']);
474 raise Error, "Not exactly one hit when searching for user"
475 if res[0][1].has_key('sudoPassword'):
476 inldap = res[0][1]['sudoPassword']
482 Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*]+) ([^ ]+)$').match(entry)
484 raise Error, "Could not parse existing sudopasswd entry"
485 uuid = Match.group(1)
486 status = Match.group(2)
487 hosts = Match.group(3)
488 cryptedpass = Match.group(4)
490 if SudoPasswd.has_key(uuid):
491 confirmedHosts = SudoPasswd[uuid][0]
492 confirmedHmac = SudoPasswd[uuid][1]
493 if status.startswith('confirmed:'):
494 if status == 'confirmed:'+make_sudopasswd_hmac('password-is-confirmed', uuid, hosts, cryptedpass):
495 result = result + "Entry %s for sudo password on hosts %s already confirmed.\n"%(uuid, hosts)
497 result = result + "Entry %s for sudo password on hosts %s is listed as confirmed, but HMAC does not verify.\n"%(uuid, hosts)
498 elif confirmedHosts != hosts:
499 result = result + "Entry %s hostlist mismatch (%s vs. %s).\n"%(uuid, hosts, confirmedHosts)
500 elif make_sudopasswd_hmac('confirm-new-password', uuid, hosts, cryptedpass) == confirmedHmac:
501 result = result + "Entry %s for sudo password on hosts %s now confirmed.\n"%(uuid, hosts)
502 status = 'confirmed:'+make_sudopasswd_hmac('password-is-confirmed', uuid, hosts, cryptedpass)
504 result = result + "Entry %s for sudo password on hosts %s HMAC verify failed.\n"%(uuid, hosts)
507 newentry = " ".join([uuid, status, hosts, cryptedpass])
508 if len(newldap) == 0:
509 newldap.append((ldap.MOD_REPLACE,"sudoPassword",newentry))
511 newldap.append((ldap.MOD_ADD,"sudoPassword",newentry))
513 for entry in SudoPasswd:
514 result = result + "Entry %s that you confirm is not listed in ldap."%(entry)
516 for entry in newldap:
521 # Handle an [almost] arbitary change
522 def HandleChange(Reply,DnRecord,Key):
524 Lines = re.split("\n *\r?",PlainText);
535 # Try to process a command line
536 Result = Result + "> "+Line+"\n";
542 badkeys = LoadBadSSH()
543 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
544 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
545 DoDel(Line,Attrs) or DoRBL(Line,Attrs) or DoConfirmSudopassword(Line)
548 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
550 # Fail, if someone tries to send someone elses signed email to the
551 # daemon then we want to abort ASAP.
554 Result = Result + "Command is not understood. Halted - no changes committed\n";
556 Result = Result + Res + "\n";
558 # Connect to the ldap server
560 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
561 AccessPass = F.readline().strip().split(" ")
564 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
565 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
566 if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
567 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
568 raise Error, "This account is locked";
570 Res = FinishConfirmSudopassword(l, GetAttr(DnRecord,"uid"), Attrs)
571 Result = Result + Res + "\n";
574 Result = Result + "FinishConfirmSudopassword raised an error (%s) - no changes committed\n"%(e);
576 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
577 if CommitChanges == 1:
578 l.modify_s(Dn,Attrs);
582 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
584 raise Error, "User not found"
585 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
588 Subst["__FROM__"] = ChangeFrom;
589 Subst["__EMAIL__"] = EmailAddress(DnRecord);
590 Subst["__ADMIN__"] = ReplyTo;
591 Subst["__RESULT__"] = Result;
592 Subst["__ATTR__"] = Attribs;
594 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
596 # Handle ping handles an email sent to the 'ping' address (ie this program
597 # called with a ping argument) It replies with a dump of the public records.
598 def HandlePing(Reply,DnRecord,Key):
600 Subst["__FROM__"] = PingFrom;
601 Subst["__EMAIL__"] = EmailAddress(DnRecord);
602 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
603 Subst["__ADMIN__"] = ReplyTo;
605 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
607 # Handle a change password email sent to the change password address
608 # (this program called with the chpass argument)
609 def HandleChPass(Reply,DnRecord,Key):
610 # Generate a random password
611 Password = GenPass();
612 Pass = HashPass(Password);
614 # Use GPG to encrypt it
615 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
620 raise Error, "Unable to generate the encrypted reply, gpg failed.";
623 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
625 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
626 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
629 Subst["__FROM__"] = ChPassFrom;
630 Subst["__EMAIL__"] = EmailAddress(DnRecord);
631 Subst["__CRYPTTYPE__"] = Type;
632 Subst["__PASSWORD__"] = Message;
633 Subst["__ADMIN__"] = ReplyTo;
634 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
636 # Connect to the ldap server
638 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
639 AccessPass = F.readline().strip().split(" ")
641 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
643 # Check for a locked account
644 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
645 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
646 or GetAttr(Attrs[0],"userPassword").startswith("!"):
647 raise Error, "This account is locked";
649 # Modify the password
650 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass),
651 (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60)))];
652 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
657 # Start of main program
659 # Drop messages from a mailer daemon.
660 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
663 ErrMsg = "Indeterminate Error";
664 ErrType = EX_TEMPFAIL;
666 # Startup the replay cache
667 ErrType = EX_TEMPFAIL;
668 ErrMsg = "Failed to initialize the replay cache:";
669 RC = ReplayCache(ReplayCacheFile);
673 ErrType = EX_PERMFAIL;
674 ErrMsg = "Failed to understand the email or find a signature:";
675 Email = mimetools.Message(sys.stdin,0);
676 Msg = GetClearSig(Email);
678 ErrMsg = "Message is not PGP signed:"
679 if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
680 Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
681 raise Error, "No PGP signature";
683 # Check the signature
684 ErrMsg = "Unable to check the signature or the signature was invalid:";
685 Res = GPGCheckSig(Msg[0]);
691 raise Error, "Null signature text";
693 # Extract the plain message text in the event of mime encoding
695 ErrMsg = "Problem stripping MIME headers from the decoded message"
698 Index = Res[3].index("\n\n") + 2;
700 Index = Res[3].index("\n\r\n") + 3;
701 PlainText = Res[3][Index:];
705 # Check the signature against the replay cache
706 ErrMsg = "The replay cache rejected your message. Check your clock!";
707 Rply = RC.Check(Res[1]);
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 Error, "Key not found"
725 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
729 # Determine the sender address
730 ErrMsg = "A problem occured while trying to formulate the reply";
731 Sender = Email.getheader("Reply-To");
733 Sender = Email.getheader("From");
735 raise Error, "Unable to determine the sender's address";
738 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
739 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
742 if sys.argv[1] == "ping":
743 Reply = HandlePing(Reply,Attrs[0],Res[2]);
744 elif sys.argv[1] == "chpass":
745 if PlainText.strip().find("Please change my Debian password") != 0:
746 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
747 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
748 elif sys.argv[1] == "change":
749 Reply = HandleChange(Reply,Attrs[0],Res[2]);
752 raise Error, "Incorrect Invokation";
754 # Send the message through sendmail
755 ErrMsg = "A problem occured while trying to send the reply";
756 Child = os.popen("/usr/sbin/sendmail -t","w");
757 # Child = os.popen("cat","w");
759 if Child.close() != None:
760 raise Error, "Sendmail gave a non-zero return code";
764 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
765 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
769 Subst["__ERROR__"] = ErrMsg;
770 Subst["__ADMIN__"] = ReplyTo;
772 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
773 List = traceback.extract_tb(sys.exc_traceback);
775 Trace = Trace + "Python Stack Trace:\n";
777 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
779 Subst["__TRACE__"] = Trace;
781 # Try to send the bounce
783 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
785 Child = os.popen("/usr/sbin/sendmail -t","w");
786 Child.write(ErrReplyHead);
787 Child.write(ErrReply);
788 if Child.close() != None:
789 raise Error, "Sendmail gave a non-zero return code";
791 sys.exit(EX_TEMPFAIL);
793 if ErrType != EX_PERMFAIL: