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>
8 # Copyright (c) 2010 Helmut Grohne <helmut@subdivi.de>
10 import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, os, commands
13 from userdir_gpg import *
14 from userdir_ldap import *
15 from userdir_exceptions import *
17 # Error codes from /usr/include/sysexits.h
18 ReplyTo = ConfModule.replyto;
19 PingFrom = ConfModule.pingfrom;
20 ChPassFrom = ConfModule.chpassfrom;
21 ChangeFrom = ConfModule.changefrom;
22 ReplayCacheFile = ConfModule.replaycachefile;
23 SSHFingerprintFile = ConfModule.fingerprintfile
25 UUID_FORMAT = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
28 EX_PERMFAIL = 65; # EX_DATAERR
29 Error = 'Message Error';
39 SSHFingerprint = re.compile('^(\d+) ([0-9a-f\:]{47}) (.+)$')
40 SSHRSA1Match = re.compile('^^(.* )?\d+ \d+ \d+')
42 GenderTable = {"male": 1,
50 ArbChanges = {"c": "..",
52 "facsimileTelephoneNumber": ".*",
53 "telephoneNumber": ".*",
54 "postalAddress": ".*",
58 "emailForward": "^([^<>@]+@.+)?$",
59 "jabberJID": "^([^<>@]+@.+)?$",
64 "birthDate": "^([0-9]{4})([01][0-9])([0-3][0-9])$",
65 "mailDisableMessage": ".*",
66 "mailGreylisting": "^(TRUE|FALSE)$",
67 "mailCallout": "^(TRUE|FALSE)$",
68 "mailDefaultOptions": "^(TRUE|FALSE)$",
70 "gender": "^(1|2|9|male|female|unspecified)$",
71 "mailContentInspectionAction": "^(reject|blackhole|markup)$",
74 DelItems = {"c": None,
76 "facsimileTelephoneNumber": None,
77 "telephoneNumber": None,
78 "postalAddress": None,
91 "sshRSAAuthKey": None,
93 "mailGreylisting": None,
97 "mailWhitelist": None,
98 "mailDisableMessage": None,
99 "mailDefaultOptions": None,
101 "mailContentInspectionAction": None,
105 # Decode a GPS location from some common forms
106 def LocDecode(Str,Dir):
107 # Check for Decimal degrees, DGM, or DGMS
108 if re.match("^[+-]?[\d.]+$",Str) != None:
111 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
113 # Check for DDDxMM.MMMM where x = [nsew]
114 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
117 Deg = G[0]; Min = G[2]; Dr = G[1];
120 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
123 Deg = G[0]; Dr = G[1];
125 # Check for DD:MM.MM x
126 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
129 Deg = G[0]; Min = G[1]; Dr = G[2];
131 # Check for DD:MM:SS.SS x
132 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
135 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
139 raise UDFormatError, "Bad degrees";
140 if Min != None and float(Min) > 60:
141 raise UDFormatError, "Bad minutes";
142 if Sec != None and float(Sec) > 60:
143 raise UDFormatError, "Bad seconds";
145 # Pad on an extra leading 0 to disambiguate small numbers
146 if len(Deg) <= 1 or Deg[1] == '.':
148 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
150 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
153 # Construct a DGM/DGMS type value from the components.
164 # Handle changing a set of arbitary fields
166 def DoArbChange(Str,Attrs):
167 Match = re.match("^([^ :]+): (.*)$",Str);
172 attrName = G[0].lower();
173 for i in ArbChanges.keys():
174 if i.lower() == attrName:
177 if ArbChanges.has_key(attrName) == 0:
180 if re.match(ArbChanges[attrName],G[1]) == None:
181 raise UDFormatError, "Item does not match the required format"+ArbChanges[attrName];
184 if attrName == 'gender':
185 if G[1] not in GenderTable:
186 raise UDFormatError, "Gender not found in table"
187 value = GenderTable[G[1]]
189 # if attrName == 'birthDate':
190 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
191 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
192 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
194 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
196 # } elsif ($bd_day <= 28) {
199 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
200 # if ($bd_day <= 30) {
204 # if ($bd_day <= 31) {
209 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
212 Attrs.append((ldap.MOD_REPLACE,attrName,value));
213 return "Changed entry %s to %s"%(attrName,value);
215 # Handle changing a set of arbitary fields
217 def DoDel(Str,Attrs):
218 Match = re.match("^del (.*)$",Str);
223 attrName = G[0].lower();
224 for i in DelItems.keys():
225 if i.lower() == attrName:
228 if DelItems.has_key(attrName) == 0:
229 return "Cannot erase entry %s"%(attrName);
231 Attrs.append((ldap.MOD_DELETE,attrName,None));
232 return "Removed entry %s"%(attrName);
234 # Handle a position change message, the line format is:
235 # Lat: -12412.23 Long: +12341.2342
236 def DoPosition(Str,Attrs):
237 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
243 sLat = LocDecode(G[0],"ns");
244 sLong = LocDecode(G[1],"ew");
245 Lat = DecDegree(sLat,1);
246 Long = DecDegree(sLong,1);
248 raise UDFormatError, "Positions were found, but they are not correctly formed";
250 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
251 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
252 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
254 # Load bad ssh fingerprints
256 f = open(SSHFingerprintFile, "r")
258 FingerprintLine = re.compile('^([0-9a-f\:]{47}).*$')
259 for line in f.readlines():
260 Match = FingerprintLine.match(line)
261 if Match is not None:
266 # Handle an SSH authentication key, the line format is:
267 # [options] 1024 35 13188913666680[..] [comment]
268 # maybe it really should be:
269 # [allowed_hosts=machine1,machine2 ][options ]ssh-rsa keybytes [comment]
270 machine_regex = re.compile("^[0-9a-zA-Z.-]+$")
271 def DoSSH(Str, Attrs, badkeys, uid):
272 Match = SSH2AuthSplit.match(Str);
278 Match = SSHRSA1Match.match(Str)
279 if Match is not None:
280 return "RSA1 keys not supported anymore"
283 # lines can now be prepended with "allowed_hosts=machine1,machine2 "
284 if Str.startswith("allowed_hosts="):
285 Str = Str.split("=", 1)[1]
287 return "invalid ssh key syntax with machine specification"
288 machines, Str = Str.split(' ', 1)
289 machines = machines.split(",")
292 return "empty machine specification for ssh key"
293 if not machine_regex.match(m):
294 return "machine specification for ssh key contains invalid characters"
296 (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
298 f.write("%s\n" % (Str))
300 cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
301 (result, output) = commands.getstatusoutput(cmd)
304 raise UDExecuteError, "ssh-keygen -l invocation failed!\n%s\n" % (output)
308 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
309 ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
311 Subst["__ADMIN__"] = ReplyTo
312 Subst["__USER__"] = uid
314 Match = SSHFingerprint.match(output)
320 Subst["__ERROR__"] = "SSH keysize %s is below limit 1024" % (g[0])
321 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
323 Child = os.popen("/usr/sbin/sendmail -t","w")
324 Child.write(ErrReplyHead)
325 Child.write(ErrReply)
326 if Child.close() != None:
327 raise UDExecuteError, "Sendmail gave a non-zero return code"
329 sys.exit(EX_TEMPFAIL)
331 # And now break and stop processing input, which sends a reply to the user.
332 raise UDFormatError, "SSH keys must have at least 1024 bits, processing halted, NOTHING MODIFIED AT ALL"
333 elif g[1] in badkeys:
336 Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
337 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
339 Child = os.popen("/usr/sbin/sendmail -t","w")
340 Child.write(ErrReplyHead)
341 Child.write(ErrReply)
342 if Child.close() != None:
343 raise UDExecuteError, "Sendmail gave a non-zero return code"
345 sys.exit(EX_TEMPFAIL)
347 # And now break and stop processing input, which sends a reply to the user.
348 raise UDFormatError, "Submitted SSH Key known to be bad and insecure, processing halted, NOTHING MODIFIED AT ALL"
350 if (typekey == "dss"):
351 return "DSA keys not accepted anymore"
355 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
356 return "SSH Key added "+FormatSSHAuth(Str);
358 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
360 return "SSH Keys replaced with "+FormatSSHAuth(Str);
362 # Handle changing a dns entry
363 # host IN A 12.12.12.12
364 # host IN AAAA 1234::5678
365 # host IN CNAME foo.bar. <- Trailing dot is required
366 # host IN MX foo.bar. <- Trailing dot is required
367 def DoDNS(Str,Attrs,DnRecord):
368 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
369 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
370 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
371 #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)
372 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
374 if cnamerecord == None and\
376 mxrecord == None and\
380 # Check if the name is already taken
381 G = re.match('^([-\w+]+)\s',Str)
383 raise UDFormatError, "Hostname not found although we already passed record syntax checks"
384 hostname = G.group(1)
386 # Check for collisions
388 # [JT 20070409 - search for both tab and space suffixed hostnames
389 # since we accept either. It'd probably be better to parse the
390 # incoming string in order to construct what we feed LDAP rather
391 # than just passing it through as is.]
392 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
393 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
395 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
396 return "DNS entry is already owned by " + GetAttr(x,"uid")
402 if DNS.has_key(hostname):
403 return "CNAME and other RR types not allowed: "+Str
407 if DNS.has_key(hostname) and DNS[hostname] == 2:
408 return "CNAME and other RR types not allowed: "+Str
412 if cnamerecord != None:
413 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
414 elif arecord != None:
415 ipaddress = arecord.group(1)
416 for quad in ipaddress.split('.'):
417 if not (int(quad) >=0 and int(quad) <= 255):
418 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
419 sanitized = "%s IN A %s"% (hostname, ipaddress)
420 elif mxrecord != None:
421 priority = mxrecord.group(1)
422 mx = mxrecord.group(2)
423 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
424 elif aaaarecord != None:
425 ipv6address = aaaarecord.group(1)
426 parts = ipv6address.split(':')
428 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
430 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
435 seenEmptypart = False
438 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
441 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
443 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
445 raise UDFormatError, "None of the types I recognize was it. I shouldn't be here. confused."
448 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
449 return "DNS Entry added "+sanitized;
451 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
453 return "DNS Entry replaced with "+sanitized;
455 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
456 def DoRBL(Str,Attrs):
457 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
461 if Match.group(1) == "rbl":
463 if Match.group(1) == "rhsbl":
465 if Match.group(1) == "whitelist":
466 Key = "mailWhitelist"
467 Host = Match.group(2)
470 if SeenList.has_key(Key):
471 Attrs.append((ldap.MOD_ADD,Key,Host))
472 return "%s added %s" % (Key,Host)
474 Attrs.append((ldap.MOD_REPLACE,Key,Host))
476 return "%s replaced with %s" % (Key,Host)
478 # Handle a ConfirmSudoPassword request
479 def DoConfirmSudopassword(Str):
480 Match = re.compile('^confirm sudopassword ('+UUID_FORMAT+') ([a-z0-9.,*]+) ([0-9a-f]{40})$').match(Str)
484 uuid = Match.group(1)
485 hosts = Match.group(2)
486 hmac = Match.group(3)
489 SudoPasswd[uuid] = (hosts, hmac)
490 return "got confirm for sudo password %s on host(s) %s, auth code %s" % (uuid,hosts, hmac)
492 def FinishConfirmSudopassword(l, uid, Attrs):
496 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+uid, ['sudoPassword']);
498 raise UDFormatError, "Not exactly one hit when searching for user"
499 if res[0][1].has_key('sudoPassword'):
500 inldap = res[0][1]['sudoPassword']
506 Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*]+) ([^ ]+)$').match(entry)
508 raise UDFormatError, "Could not parse existing sudopasswd entry"
509 uuid = Match.group(1)
510 status = Match.group(2)
511 hosts = Match.group(3)
512 cryptedpass = Match.group(4)
514 if SudoPasswd.has_key(uuid):
515 confirmedHosts = SudoPasswd[uuid][0]
516 confirmedHmac = SudoPasswd[uuid][1]
517 if status.startswith('confirmed:'):
518 if status == 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass):
519 result = result + "Entry %s for sudo password on hosts %s already confirmed.\n"%(uuid, hosts)
521 result = result + "Entry %s for sudo password on hosts %s is listed as confirmed, but HMAC does not verify.\n"%(uuid, hosts)
522 elif confirmedHosts != hosts:
523 result = result + "Entry %s hostlist mismatch (%s vs. %s).\n"%(uuid, hosts, confirmedHosts)
524 elif make_passwd_hmac('confirm-new-password', 'sudo', uid, uuid, hosts, cryptedpass) == confirmedHmac:
525 result = result + "Entry %s for sudo password on hosts %s now confirmed.\n"%(uuid, hosts)
526 status = 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass)
528 result = result + "Entry %s for sudo password on hosts %s HMAC verify failed.\n"%(uuid, hosts)
531 newentry = " ".join([uuid, status, hosts, cryptedpass])
532 if len(newldap) == 0:
533 newldap.append((ldap.MOD_REPLACE,"sudoPassword",newentry))
535 newldap.append((ldap.MOD_ADD,"sudoPassword",newentry))
537 for entry in SudoPasswd:
538 result = result + "Entry %s that you confirm is not listed in ldap."%(entry)
540 for entry in newldap:
545 # Handle an [almost] arbitary change
546 def HandleChange(Reply,DnRecord,Key):
548 Lines = re.split("\n *\r?",PlainText);
559 # Try to process a command line
560 Result = Result + "> "+Line+"\n";
566 badkeys = LoadBadSSH()
567 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
568 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
569 DoDel(Line,Attrs) or DoRBL(Line,Attrs) or DoConfirmSudopassword(Line)
572 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
574 # Fail, if someone tries to send someone elses signed email to the
575 # daemon then we want to abort ASAP.
578 Result = Result + "Command is not understood. Halted - no changes committed\n";
580 Result = Result + Res + "\n";
582 # Connect to the ldap server
584 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
585 AccessPass = F.readline().strip().split(" ")
588 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
589 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
590 if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
591 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
592 raise UDNotAllowedError, "This account is locked";
594 if CommitChanges == 1: # only if we are still good to go
596 Res = FinishConfirmSudopassword(l, GetAttr(DnRecord,"uid"), Attrs)
597 Result = Result + Res + "\n";
600 Result = Result + "FinishConfirmSudopassword raised an error (%s) - no changes committed\n"%(e);
603 if CommitChanges == 1:
604 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
605 l.modify_s(Dn,Attrs);
609 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
611 raise UDNotAllowedError, "User not found"
612 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
615 Subst["__FROM__"] = ChangeFrom;
616 Subst["__EMAIL__"] = EmailAddress(DnRecord);
617 Subst["__ADMIN__"] = ReplyTo;
618 Subst["__RESULT__"] = Result;
619 Subst["__ATTR__"] = Attribs;
621 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
623 # Handle ping handles an email sent to the 'ping' address (ie this program
624 # called with a ping argument) It replies with a dump of the public records.
625 def HandlePing(Reply,DnRecord,Key):
627 Subst["__FROM__"] = PingFrom;
628 Subst["__EMAIL__"] = EmailAddress(DnRecord);
629 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
630 Subst["__ADMIN__"] = ReplyTo;
632 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
634 # Handle a change password email sent to the change password address
635 # (this program called with the chpass argument)
636 def HandleChPass(Reply,DnRecord,Key):
637 # Generate a random password
638 Password = GenPass();
639 Pass = HashPass(Password);
641 # Use GPG to encrypt it
642 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
647 raise UDFormatError, "Unable to generate the encrypted reply, gpg failed.";
650 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
652 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
653 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
656 Subst["__FROM__"] = ChPassFrom;
657 Subst["__EMAIL__"] = EmailAddress(DnRecord);
658 Subst["__CRYPTTYPE__"] = Type;
659 Subst["__PASSWORD__"] = Message;
660 Subst["__ADMIN__"] = ReplyTo;
661 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
663 # Connect to the ldap server
665 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
666 AccessPass = F.readline().strip().split(" ")
668 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
670 # Check for a locked account
671 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
672 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
673 or GetAttr(Attrs[0],"userPassword").startswith("!"):
674 raise UDNotAllowedError, "This account is locked";
676 # Modify the password
677 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass),
678 (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60)))];
679 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
684 # Start of main program
686 # Drop messages from a mailer daemon.
687 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
690 ErrMsg = "Indeterminate Error";
691 ErrType = EX_TEMPFAIL;
693 # Startup the replay cache
694 ErrType = EX_TEMPFAIL;
695 ErrMsg = "Failed to initialize the replay cache:";
698 ErrType = EX_PERMFAIL;
699 ErrMsg = "Failed to understand the email or find a signature:";
700 Email = mimetools.Message(sys.stdin,0);
701 Msg = GetClearSig(Email);
703 ErrMsg = "Message is not PGP signed:"
704 if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
705 Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
706 raise UDFormatError, "No PGP signature";
708 # Check the signature
709 ErrMsg = "Unable to check the signature or the signature was invalid:";
710 Res = GPGCheckSig(Msg[0]);
713 raise UDFormatError, Res[0];
716 raise UDFormatError, "Null signature text";
718 # Extract the plain message text in the event of mime encoding
720 ErrMsg = "Problem stripping MIME headers from the decoded message"
723 Index = Res[3].index("\n\n") + 2;
725 Index = Res[3].index("\n\r\n") + 3;
726 PlainText = Res[3][Index:];
730 # Connect to the ldap server
731 ErrType = EX_TEMPFAIL;
732 ErrMsg = "An error occured while performing the LDAP lookup";
735 l.simple_bind_s("","");
737 # Search for the matching key fingerprint
738 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
740 ErrType = EX_PERMFAIL;
742 raise UDFormatError, "Key not found"
744 raise UDFormatError, "Oddly your key fingerprint is assigned to more than one account.."
747 # Check the signature against the replay cache
748 RC = ReplayCache(ReplayCacheFile);
750 ErrMsg = "The replay cache rejected your message. Check your clock!";
751 Rply = RC.Check(Res[1]);
754 raise UDNotAllowedError, Rply;
758 # Determine the sender address
759 ErrMsg = "A problem occured while trying to formulate the reply";
760 Sender = Email.getheader("Reply-To");
762 Sender = Email.getheader("From");
764 raise UDFormatError, "Unable to determine the sender's address";
767 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
768 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
771 if sys.argv[1] == "ping":
772 Reply = HandlePing(Reply,Attrs[0],Res[2]);
773 elif sys.argv[1] == "chpass":
774 if PlainText.strip().find("Please change my Debian password") != 0:
775 raise UDFormatError,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
776 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
777 elif sys.argv[1] == "change":
778 Reply = HandleChange(Reply,Attrs[0],Res[2]);
781 raise UDFormatError, "Incorrect Invokation";
783 # Send the message through sendmail
784 ErrMsg = "A problem occured while trying to send the reply";
785 Child = os.popen("/usr/sbin/sendmail -t","w");
786 # Child = os.popen("cat","w");
788 if Child.close() != None:
789 raise UDExecuteError, "Sendmail gave a non-zero return code";
793 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
794 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
798 Subst["__ERROR__"] = ErrMsg;
799 Subst["__ADMIN__"] = ReplyTo;
801 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
802 List = traceback.extract_tb(sys.exc_traceback);
804 Trace = Trace + "Python Stack Trace:\n";
806 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
808 Subst["__TRACE__"] = Trace;
810 # Try to send the bounce
812 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
814 Child = os.popen("/usr/sbin/sendmail -t -oi -f ''","w");
815 Child.write(ErrReplyHead);
816 Child.write(ErrReply);
817 if Child.close() != None:
818 raise UDExecuteError, "Sendmail gave a non-zero return code";
820 sys.exit(EX_TEMPFAIL);
822 if ErrType != EX_PERMFAIL:
828 # vim:set shiftwidth=3: