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';
38 ValidHostNames = [] # will be initialized in later
40 SSHFingerprint = re.compile('^(\d+) ([0-9a-f\:]{47}) (.+)$')
41 SSHRSA1Match = re.compile('^^(.* )?\d+ \d+ \d+')
43 GenderTable = {"male": 1,
51 ArbChanges = {"c": "..",
53 "facsimileTelephoneNumber": ".*",
54 "telephoneNumber": ".*",
55 "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)$",
69 "mailDefaultOptions": "^(TRUE|FALSE)$",
71 "gender": "^(1|2|9|male|female|unspecified)$",
72 "mailContentInspectionAction": "^(reject|blackhole|markup)$",
75 DelItems = {"c": None,
77 "facsimileTelephoneNumber": None,
78 "telephoneNumber": None,
79 "postalAddress": None,
92 "sshRSAAuthKey": None,
94 "mailGreylisting": None,
98 "mailWhitelist": None,
99 "mailDisableMessage": None,
100 "mailDefaultOptions": None,
102 "mailContentInspectionAction": None,
106 # Decode a GPS location from some common forms
107 def LocDecode(Str,Dir):
108 # Check for Decimal degrees, DGM, or DGMS
109 if re.match("^[+-]?[\d.]+$",Str) != None:
112 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
114 # Check for DDDxMM.MMMM where x = [nsew]
115 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
118 Deg = G[0]; Min = G[2]; Dr = G[1];
121 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
124 Deg = G[0]; Dr = G[1];
126 # Check for DD:MM.MM x
127 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
130 Deg = G[0]; Min = G[1]; Dr = G[2];
132 # Check for DD:MM:SS.SS x
133 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
136 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
140 raise UDFormatError, "Bad degrees";
141 if Min != None and float(Min) > 60:
142 raise UDFormatError, "Bad minutes";
143 if Sec != None and float(Sec) > 60:
144 raise UDFormatError, "Bad seconds";
146 # Pad on an extra leading 0 to disambiguate small numbers
147 if len(Deg) <= 1 or Deg[1] == '.':
149 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
151 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
154 # Construct a DGM/DGMS type value from the components.
165 # Handle changing a set of arbitary fields
167 def DoArbChange(Str,Attrs):
168 Match = re.match("^([^ :]+): (.*)$",Str);
173 attrName = G[0].lower();
174 for i in ArbChanges.keys():
175 if i.lower() == attrName:
178 if ArbChanges.has_key(attrName) == 0:
181 if re.match(ArbChanges[attrName],G[1]) == None:
182 raise UDFormatError, "Item does not match the required format"+ArbChanges[attrName];
185 if attrName == 'gender':
186 if G[1] not in GenderTable:
187 raise UDFormatError, "Gender not found in table"
188 value = GenderTable[G[1]]
190 # if attrName == 'birthDate':
191 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
192 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
193 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
195 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
197 # } elsif ($bd_day <= 28) {
200 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
201 # if ($bd_day <= 30) {
205 # if ($bd_day <= 31) {
210 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
213 Attrs.append((ldap.MOD_REPLACE,attrName,value));
214 return "Changed entry %s to %s"%(attrName,value);
216 # Handle changing a set of arbitary fields
218 def DoDel(Str,Attrs):
219 Match = re.match("^del (.*)$",Str);
224 attrName = G[0].lower();
225 for i in DelItems.keys():
226 if i.lower() == attrName:
229 if DelItems.has_key(attrName) == 0:
230 return "Cannot erase entry %s"%(attrName);
232 Attrs.append((ldap.MOD_DELETE,attrName,None));
233 return "Removed entry %s"%(attrName);
235 # Handle a position change message, the line format is:
236 # Lat: -12412.23 Long: +12341.2342
237 def DoPosition(Str,Attrs):
238 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
244 sLat = LocDecode(G[0],"ns");
245 sLong = LocDecode(G[1],"ew");
246 Lat = DecDegree(sLat,1);
247 Long = DecDegree(sLong,1);
249 raise UDFormatError, "Positions were found, but they are not correctly formed";
251 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
252 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
253 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
255 # Load bad ssh fingerprints
257 f = open(SSHFingerprintFile, "r")
259 FingerprintLine = re.compile('^([0-9a-f\:]{47}).*$')
260 for line in f.readlines():
261 Match = FingerprintLine.match(line)
262 if Match is not None:
267 # Handle an SSH authentication key, the line format is:
268 # [options] 1024 35 13188913666680[..] [comment]
269 # maybe it really should be:
270 # [allowed_hosts=machine1,machine2 ][options ]ssh-rsa keybytes [comment]
271 machine_regex = re.compile("^[0-9a-zA-Z.-]+$")
272 def DoSSH(Str, Attrs, badkeys, uid):
273 Match = SSH2AuthSplit.match(Str);
279 Match = SSHRSA1Match.match(Str)
280 if Match is not None:
281 return "RSA1 keys not supported anymore"
284 # lines can now be prepended with "allowed_hosts=machine1,machine2 "
286 if Str.startswith("allowed_hosts="):
287 Str = Str.split("=", 1)[1]
289 return "invalid ssh key syntax with machine specification"
290 machines, Str = Str.split(' ', 1)
291 machines = machines.split(",")
294 return "empty machine specification for ssh key"
295 if not machine_regex.match(m):
296 return "machine specification for ssh key contains invalid characters"
297 if m not in ValidHostNames:
298 return "unknown machine used in allowed_hosts stanza for ssh keys"
300 (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
302 f.write("%s\n" % (Str))
304 cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
305 (result, output) = commands.getstatusoutput(cmd)
308 raise UDExecuteError, "ssh-keygen -l invocation failed!\n%s\n" % (output)
310 # format the string again for ldap:
312 Str = "allowed_hosts=%s %s" % (",".join(machines), Str)
316 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
317 ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
319 Subst["__ADMIN__"] = ReplyTo
320 Subst["__USER__"] = uid
322 Match = SSHFingerprint.match(output)
328 Subst["__ERROR__"] = "SSH keysize %s is below limit 1024" % (g[0])
329 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
331 Child = os.popen("/usr/sbin/sendmail -t","w")
332 Child.write(ErrReplyHead)
333 Child.write(ErrReply)
334 if Child.close() != None:
335 raise UDExecuteError, "Sendmail gave a non-zero return code"
337 sys.exit(EX_TEMPFAIL)
339 # And now break and stop processing input, which sends a reply to the user.
340 raise UDFormatError, "SSH keys must have at least 1024 bits, processing halted, NOTHING MODIFIED AT ALL"
341 elif g[1] in badkeys:
344 Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
345 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
347 Child = os.popen("/usr/sbin/sendmail -t","w")
348 Child.write(ErrReplyHead)
349 Child.write(ErrReply)
350 if Child.close() != None:
351 raise UDExecuteError, "Sendmail gave a non-zero return code"
353 sys.exit(EX_TEMPFAIL)
355 # And now break and stop processing input, which sends a reply to the user.
356 raise UDFormatError, "Submitted SSH Key known to be bad and insecure, processing halted, NOTHING MODIFIED AT ALL"
358 if (typekey == "dss"):
359 return "DSA keys not accepted anymore"
363 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
364 return "SSH Key added "+FormatSSHAuth(Str);
366 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
368 return "SSH Keys replaced with "+FormatSSHAuth(Str);
370 # Handle changing a dns entry
371 # host IN A 12.12.12.12
372 # host IN AAAA 1234::5678
373 # host IN CNAME foo.bar. <- Trailing dot is required
374 # host IN MX foo.bar. <- Trailing dot is required
375 def DoDNS(Str,Attrs,DnRecord):
376 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
377 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
378 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
379 #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)
380 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
382 if cnamerecord == None and\
384 mxrecord == None and\
388 # Check if the name is already taken
389 G = re.match('^([-\w+]+)\s',Str)
391 raise UDFormatError, "Hostname not found although we already passed record syntax checks"
392 hostname = G.group(1)
394 # Check for collisions
396 # [JT 20070409 - search for both tab and space suffixed hostnames
397 # since we accept either. It'd probably be better to parse the
398 # incoming string in order to construct what we feed LDAP rather
399 # than just passing it through as is.]
400 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
401 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
403 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
404 return "DNS entry is already owned by " + GetAttr(x,"uid")
410 if DNS.has_key(hostname):
411 return "CNAME and other RR types not allowed: "+Str
415 if DNS.has_key(hostname) and DNS[hostname] == 2:
416 return "CNAME and other RR types not allowed: "+Str
420 if cnamerecord != None:
421 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
422 elif arecord != None:
423 ipaddress = arecord.group(1)
424 for quad in ipaddress.split('.'):
425 if not (int(quad) >=0 and int(quad) <= 255):
426 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
427 sanitized = "%s IN A %s"% (hostname, ipaddress)
428 elif mxrecord != None:
429 priority = mxrecord.group(1)
430 mx = mxrecord.group(2)
431 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
432 elif aaaarecord != None:
433 ipv6address = aaaarecord.group(1)
434 parts = ipv6address.split(':')
436 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
438 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
443 seenEmptypart = False
446 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
449 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
451 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
453 raise UDFormatError, "None of the types I recognize was it. I shouldn't be here. confused."
456 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
457 return "DNS Entry added "+sanitized;
459 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
461 return "DNS Entry replaced with "+sanitized;
463 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
464 def DoRBL(Str,Attrs):
465 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
469 if Match.group(1) == "rbl":
471 if Match.group(1) == "rhsbl":
473 if Match.group(1) == "whitelist":
474 Key = "mailWhitelist"
475 Host = Match.group(2)
478 if SeenList.has_key(Key):
479 Attrs.append((ldap.MOD_ADD,Key,Host))
480 return "%s added %s" % (Key,Host)
482 Attrs.append((ldap.MOD_REPLACE,Key,Host))
484 return "%s replaced with %s" % (Key,Host)
486 # Handle a ConfirmSudoPassword request
487 def DoConfirmSudopassword(Str):
488 Match = re.compile('^confirm sudopassword ('+UUID_FORMAT+') ([a-z0-9.,*]+) ([0-9a-f]{40})$').match(Str)
492 uuid = Match.group(1)
493 hosts = Match.group(2)
494 hmac = Match.group(3)
497 SudoPasswd[uuid] = (hosts, hmac)
498 return "got confirm for sudo password %s on host(s) %s, auth code %s" % (uuid,hosts, hmac)
500 def FinishConfirmSudopassword(l, uid, Attrs):
504 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+uid, ['sudoPassword']);
506 raise UDFormatError, "Not exactly one hit when searching for user"
507 if res[0][1].has_key('sudoPassword'):
508 inldap = res[0][1]['sudoPassword']
514 Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*]+) ([^ ]+)$').match(entry)
516 raise UDFormatError, "Could not parse existing sudopasswd entry"
517 uuid = Match.group(1)
518 status = Match.group(2)
519 hosts = Match.group(3)
520 cryptedpass = Match.group(4)
522 if SudoPasswd.has_key(uuid):
523 confirmedHosts = SudoPasswd[uuid][0]
524 confirmedHmac = SudoPasswd[uuid][1]
525 if status.startswith('confirmed:'):
526 if status == 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass):
527 result = result + "Entry %s for sudo password on hosts %s already confirmed.\n"%(uuid, hosts)
529 result = result + "Entry %s for sudo password on hosts %s is listed as confirmed, but HMAC does not verify.\n"%(uuid, hosts)
530 elif confirmedHosts != hosts:
531 result = result + "Entry %s hostlist mismatch (%s vs. %s).\n"%(uuid, hosts, confirmedHosts)
532 elif make_passwd_hmac('confirm-new-password', 'sudo', uid, uuid, hosts, cryptedpass) == confirmedHmac:
533 result = result + "Entry %s for sudo password on hosts %s now confirmed.\n"%(uuid, hosts)
534 status = 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass)
536 result = result + "Entry %s for sudo password on hosts %s HMAC verify failed.\n"%(uuid, hosts)
539 newentry = " ".join([uuid, status, hosts, cryptedpass])
540 if len(newldap) == 0:
541 newldap.append((ldap.MOD_REPLACE,"sudoPassword",newentry))
543 newldap.append((ldap.MOD_ADD,"sudoPassword",newentry))
545 for entry in SudoPasswd:
546 result = result + "Entry %s that you confirm is not listed in ldap."%(entry)
548 for entry in newldap:
553 # Handle an [almost] arbitary change
554 def HandleChange(Reply,DnRecord,Key):
556 Lines = re.split("\n *\r?",PlainText);
567 # Try to process a command line
568 Result = Result + "> "+Line+"\n";
574 badkeys = LoadBadSSH()
575 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
576 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
577 DoDel(Line,Attrs) or DoRBL(Line,Attrs) or DoConfirmSudopassword(Line)
580 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
582 # Fail, if someone tries to send someone elses signed email to the
583 # daemon then we want to abort ASAP.
586 Result = Result + "Command is not understood. Halted - no changes committed\n";
588 Result = Result + Res + "\n";
590 # Connect to the ldap server
592 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
593 AccessPass = F.readline().strip().split(" ")
596 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
597 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
598 if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
599 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
600 raise UDNotAllowedError, "This account is locked";
602 if CommitChanges == 1: # only if we are still good to go
604 Res = FinishConfirmSudopassword(l, GetAttr(DnRecord,"uid"), Attrs)
605 Result = Result + Res + "\n";
608 Result = Result + "FinishConfirmSudopassword raised an error (%s) - no changes committed\n"%(e);
611 if CommitChanges == 1:
612 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
613 l.modify_s(Dn,Attrs);
617 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
619 raise UDNotAllowedError, "User not found"
620 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
623 Subst["__FROM__"] = ChangeFrom;
624 Subst["__EMAIL__"] = EmailAddress(DnRecord);
625 Subst["__ADMIN__"] = ReplyTo;
626 Subst["__RESULT__"] = Result;
627 Subst["__ATTR__"] = Attribs;
629 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
631 # Handle ping handles an email sent to the 'ping' address (ie this program
632 # called with a ping argument) It replies with a dump of the public records.
633 def HandlePing(Reply,DnRecord,Key):
635 Subst["__FROM__"] = PingFrom;
636 Subst["__EMAIL__"] = EmailAddress(DnRecord);
637 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
638 Subst["__ADMIN__"] = ReplyTo;
640 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
642 # Handle a change password email sent to the change password address
643 # (this program called with the chpass argument)
644 def HandleChPass(Reply,DnRecord,Key):
645 # Generate a random password
646 Password = GenPass();
647 Pass = HashPass(Password);
649 # Use GPG to encrypt it
650 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
655 raise UDFormatError, "Unable to generate the encrypted reply, gpg failed.";
658 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
660 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
661 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
664 Subst["__FROM__"] = ChPassFrom;
665 Subst["__EMAIL__"] = EmailAddress(DnRecord);
666 Subst["__CRYPTTYPE__"] = Type;
667 Subst["__PASSWORD__"] = Message;
668 Subst["__ADMIN__"] = ReplyTo;
669 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
671 # Connect to the ldap server
673 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
674 AccessPass = F.readline().strip().split(" ")
676 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
678 # Check for a locked account
679 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
680 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
681 or GetAttr(Attrs[0],"userPassword").startswith("!"):
682 raise UDNotAllowedError, "This account is locked";
684 # Modify the password
685 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass),
686 (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60)))];
687 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
692 # Start of main program
694 # Drop messages from a mailer daemon.
695 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
698 ErrMsg = "Indeterminate Error";
699 ErrType = EX_TEMPFAIL;
701 # Startup the replay cache
702 ErrType = EX_TEMPFAIL;
703 ErrMsg = "Failed to initialize the replay cache:";
706 ErrType = EX_PERMFAIL;
707 ErrMsg = "Failed to understand the email or find a signature:";
708 Email = mimetools.Message(sys.stdin,0);
709 Msg = GetClearSig(Email);
711 ErrMsg = "Message is not PGP signed:"
712 if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
713 Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
714 raise UDFormatError, "No PGP signature";
716 # Check the signature
717 ErrMsg = "Unable to check the signature or the signature was invalid:";
718 Res = GPGCheckSig(Msg[0]);
721 raise UDFormatError, Res[0];
724 raise UDFormatError, "Null signature text";
726 # Extract the plain message text in the event of mime encoding
728 ErrMsg = "Problem stripping MIME headers from the decoded message"
731 Index = Res[3].index("\n\n") + 2;
733 Index = Res[3].index("\n\r\n") + 3;
734 PlainText = Res[3][Index:];
738 # Connect to the ldap server
739 ErrType = EX_TEMPFAIL;
740 ErrMsg = "An error occured while performing the LDAP lookup";
743 l.simple_bind_s("","");
745 # Search for the matching key fingerprint
746 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
748 ErrType = EX_PERMFAIL;
750 raise UDFormatError, "Key not found"
752 raise UDFormatError, "Oddly your key fingerprint is assigned to more than one account.."
755 # Check the signature against the replay cache
756 RC = ReplayCache(ReplayCacheFile);
758 ErrMsg = "The replay cache rejected your message. Check your clock!";
759 Rply = RC.Check(Res[1]);
762 raise UDNotAllowedError, Rply;
766 # Determine the sender address
767 ErrMsg = "A problem occured while trying to formulate the reply";
768 Sender = Email.getheader("Reply-To");
770 Sender = Email.getheader("From");
772 raise UDFormatError, "Unable to determine the sender's address";
775 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
776 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
778 global ValidHostNames
779 Res = l.search_s(HostBaseDn, ldap.SCOPE_SUBTREE, '(objectClass=debianServer)', ['hostname'] )
780 # Res is a list of tuples.
781 # The tuples contain a dn (str) and a dictionary.
782 # The dictionaries map the key "hostname" to a list.
783 # These lists contain a single hostname (str).
784 ValidHostNames = reduce(lambda a,b: a+b, [value.get("hostname", []) for (dn, value) in Res], [])
787 if sys.argv[1] == "ping":
788 Reply = HandlePing(Reply,Attrs[0],Res[2]);
789 elif sys.argv[1] == "chpass":
790 if PlainText.strip().find("Please change my Debian password") != 0:
791 raise UDFormatError,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
792 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
793 elif sys.argv[1] == "change":
794 Reply = HandleChange(Reply,Attrs[0],Res[2]);
797 raise UDFormatError, "Incorrect Invokation";
799 # Send the message through sendmail
800 ErrMsg = "A problem occured while trying to send the reply";
801 Child = os.popen("/usr/sbin/sendmail -t","w");
802 # Child = os.popen("cat","w");
804 if Child.close() != None:
805 raise UDExecuteError, "Sendmail gave a non-zero return code";
809 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
810 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
814 Subst["__ERROR__"] = ErrMsg;
815 Subst["__ADMIN__"] = ReplyTo;
817 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
818 List = traceback.extract_tb(sys.exc_traceback);
820 Trace = Trace + "Python Stack Trace:\n";
822 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
824 Subst["__TRACE__"] = Trace;
826 # Try to send the bounce
828 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
830 Child = os.popen("/usr/sbin/sendmail -t -oi -f ''","w");
831 Child.write(ErrReplyHead);
832 Child.write(ErrReply);
833 if Child.close() != None:
834 raise UDExecuteError, "Sendmail gave a non-zero return code";
836 sys.exit(EX_TEMPFAIL);
838 if ErrType != EX_PERMFAIL:
844 # vim:set shiftwidth=3: