4 # Prior copyright probably rmurray, troup, joey, jgg -- weasel 2008
5 # Copyright (c) 2009 Stephen Gran <steve@lobefin.net>
6 # Copyright (c) 2008,2009,2010 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 txtrecord = re.match("^[-\w]+\s+IN\s+TXT\s+([-\d. a-z\t<>@]+)", Str, re.IGNORECASE)
380 #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)
381 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
383 if cnamerecord is None and\
385 mxrecord is None and\
386 txtrecord is None and\
390 # Check if the name is already taken
391 G = re.match('^([-\w+]+)\s',Str)
393 raise UDFormatError, "Hostname not found although we already passed record syntax checks"
394 hostname = G.group(1)
396 # Check for collisions
398 # [JT 20070409 - search for both tab and space suffixed hostnames
399 # since we accept either. It'd probably be better to parse the
400 # incoming string in order to construct what we feed LDAP rather
401 # than just passing it through as is.]
402 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
403 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
405 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
406 return "DNS entry is already owned by " + GetAttr(x,"uid")
412 if DNS.has_key(hostname):
413 return "CNAME and other RR types not allowed: "+Str
417 if DNS.has_key(hostname) and DNS[hostname] == 2:
418 return "CNAME and other RR types not allowed: "+Str
422 if cnamerecord is not None:
423 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
424 elif txtrecord is not None:
425 sanitized = "%s IN TXT %s" % (hostname, txtrecord.group(1))
426 elif arecord is not None:
427 ipaddress = arecord.group(1)
428 for quad in ipaddress.split('.'):
429 if not (int(quad) >=0 and int(quad) <= 255):
430 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
431 sanitized = "%s IN A %s"% (hostname, ipaddress)
432 elif mxrecord is not None:
433 priority = mxrecord.group(1)
434 mx = mxrecord.group(2)
435 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
436 elif aaaarecord is not None:
437 ipv6address = aaaarecord.group(1)
438 parts = ipv6address.split(':')
440 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
442 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
447 seenEmptypart = False
450 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
453 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
455 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
457 raise UDFormatError, "None of the types I recognize was it. I shouldn't be here. confused."
460 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
461 return "DNS Entry added "+sanitized;
463 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
465 return "DNS Entry replaced with "+sanitized;
467 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
468 def DoRBL(Str,Attrs):
469 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
473 if Match.group(1) == "rbl":
475 if Match.group(1) == "rhsbl":
477 if Match.group(1) == "whitelist":
478 Key = "mailWhitelist"
479 Host = Match.group(2)
482 if SeenList.has_key(Key):
483 Attrs.append((ldap.MOD_ADD,Key,Host))
484 return "%s added %s" % (Key,Host)
486 Attrs.append((ldap.MOD_REPLACE,Key,Host))
488 return "%s replaced with %s" % (Key,Host)
490 # Handle a ConfirmSudoPassword request
491 def DoConfirmSudopassword(Str):
492 Match = re.compile('^confirm sudopassword ('+UUID_FORMAT+') ([a-z0-9.,*]+) ([0-9a-f]{40})$').match(Str)
496 uuid = Match.group(1)
497 hosts = Match.group(2)
498 hmac = Match.group(3)
501 SudoPasswd[uuid] = (hosts, hmac)
502 return "got confirm for sudo password %s on host(s) %s, auth code %s" % (uuid,hosts, hmac)
504 def FinishConfirmSudopassword(l, uid, Attrs):
508 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+uid, ['sudoPassword']);
510 raise UDFormatError, "Not exactly one hit when searching for user"
511 if res[0][1].has_key('sudoPassword'):
512 inldap = res[0][1]['sudoPassword']
518 Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*]+) ([^ ]+)$').match(entry)
520 raise UDFormatError, "Could not parse existing sudopasswd entry"
521 uuid = Match.group(1)
522 status = Match.group(2)
523 hosts = Match.group(3)
524 cryptedpass = Match.group(4)
526 if SudoPasswd.has_key(uuid):
527 confirmedHosts = SudoPasswd[uuid][0]
528 confirmedHmac = SudoPasswd[uuid][1]
529 if status.startswith('confirmed:'):
530 if status == 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass):
531 result = result + "Entry %s for sudo password on hosts %s already confirmed.\n"%(uuid, hosts)
533 result = result + "Entry %s for sudo password on hosts %s is listed as confirmed, but HMAC does not verify.\n"%(uuid, hosts)
534 elif confirmedHosts != hosts:
535 result = result + "Entry %s hostlist mismatch (%s vs. %s).\n"%(uuid, hosts, confirmedHosts)
536 elif make_passwd_hmac('confirm-new-password', 'sudo', uid, uuid, hosts, cryptedpass) == confirmedHmac:
537 result = result + "Entry %s for sudo password on hosts %s now confirmed.\n"%(uuid, hosts)
538 status = 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', uid, uuid, hosts, cryptedpass)
540 result = result + "Entry %s for sudo password on hosts %s HMAC verify failed.\n"%(uuid, hosts)
543 newentry = " ".join([uuid, status, hosts, cryptedpass])
544 if len(newldap) == 0:
545 newldap.append((ldap.MOD_REPLACE,"sudoPassword",newentry))
547 newldap.append((ldap.MOD_ADD,"sudoPassword",newentry))
549 for entry in SudoPasswd:
550 result = result + "Entry %s that you confirm is not listed in ldap."%(entry)
552 for entry in newldap:
557 # Handle an [almost] arbitary change
558 def HandleChange(Reply,DnRecord,Key):
560 Lines = re.split("\n *\r?",PlainText);
571 # Try to process a command line
572 Result = Result + "> "+Line+"\n";
578 badkeys = LoadBadSSH()
579 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
580 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
581 DoDel(Line,Attrs) or DoRBL(Line,Attrs) or DoConfirmSudopassword(Line)
584 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
586 # Fail, if someone tries to send someone elses signed email to the
587 # daemon then we want to abort ASAP.
590 Result = Result + "Command is not understood. Halted - no changes committed\n";
592 Result = Result + Res + "\n";
594 # Connect to the ldap server
596 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
597 AccessPass = F.readline().strip().split(" ")
600 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
601 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
602 if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
603 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
604 raise UDNotAllowedError, "This account is locked";
606 if CommitChanges == 1: # only if we are still good to go
608 Res = FinishConfirmSudopassword(l, GetAttr(DnRecord,"uid"), Attrs)
609 Result = Result + Res + "\n";
612 Result = Result + "FinishConfirmSudopassword raised an error (%s) - no changes committed\n"%(e);
615 if CommitChanges == 1:
616 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
617 l.modify_s(Dn,Attrs);
621 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
623 raise UDNotAllowedError, "User not found"
624 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
627 Subst["__FROM__"] = ChangeFrom;
628 Subst["__EMAIL__"] = EmailAddress(DnRecord);
629 Subst["__ADMIN__"] = ReplyTo;
630 Subst["__RESULT__"] = Result;
631 Subst["__ATTR__"] = Attribs;
633 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
635 # Handle ping handles an email sent to the 'ping' address (ie this program
636 # called with a ping argument) It replies with a dump of the public records.
637 def HandlePing(Reply,DnRecord,Key):
639 Subst["__FROM__"] = PingFrom;
640 Subst["__EMAIL__"] = EmailAddress(DnRecord);
641 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
642 Subst["__ADMIN__"] = ReplyTo;
644 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
646 # Handle a change password email sent to the change password address
647 # (this program called with the chpass argument)
648 def HandleChPass(Reply,DnRecord,Key):
649 # Generate a random password
650 Password = GenPass();
651 Pass = HashPass(Password);
653 # Use GPG to encrypt it
654 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
659 raise UDFormatError, "Unable to generate the encrypted reply, gpg failed.";
662 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
664 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
665 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
668 Subst["__FROM__"] = ChPassFrom;
669 Subst["__EMAIL__"] = EmailAddress(DnRecord);
670 Subst["__CRYPTTYPE__"] = Type;
671 Subst["__PASSWORD__"] = Message;
672 Subst["__ADMIN__"] = ReplyTo;
673 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
675 # Connect to the ldap server
677 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
678 AccessPass = F.readline().strip().split(" ")
680 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
682 # Check for a locked account
683 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
684 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
685 or GetAttr(Attrs[0],"userPassword").startswith("!"):
686 raise UDNotAllowedError, "This account is locked";
688 # Modify the password
689 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass),
690 (ldap.MOD_REPLACE,"shadowLastChange",str(int(time.time()/24/60/60)))];
691 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
696 # Start of main program
698 # Drop messages from a mailer daemon.
699 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
702 ErrMsg = "Indeterminate Error";
703 ErrType = EX_TEMPFAIL;
705 # Startup the replay cache
706 ErrType = EX_TEMPFAIL;
707 ErrMsg = "Failed to initialize the replay cache:";
710 ErrType = EX_PERMFAIL;
711 ErrMsg = "Failed to understand the email or find a signature:";
712 Email = mimetools.Message(sys.stdin,0);
713 Msg = GetClearSig(Email);
715 ErrMsg = "Message is not PGP signed:"
716 if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
717 Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
718 raise UDFormatError, "No PGP signature";
720 # Check the signature
721 ErrMsg = "Unable to check the signature or the signature was invalid:";
722 pgp = GPGCheckSig2(Msg[0])
725 raise UDFormatError, pgp.why
728 raise UDFormatError, "Null signature text"
730 # Extract the plain message text in the event of mime encoding
732 ErrMsg = "Problem stripping MIME headers from the decoded message"
735 Index = pgp.text.index("\n\n") + 2
737 Index = pgp.text.index("\n\r\n") + 3
738 PlainText = pgp.text[Index:]
742 # Connect to the ldap server
743 ErrType = EX_TEMPFAIL;
744 ErrMsg = "An error occured while performing the LDAP lookup";
747 l.simple_bind_s("","");
749 # Search for the matching key fingerprint
750 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + pgp.key_fpr)
752 ErrType = EX_PERMFAIL;
754 raise UDFormatError, "Key not found"
756 raise UDFormatError, "Oddly your key fingerprint is assigned to more than one account.."
759 # Check the signature against the replay cache
760 RC = ReplayCache(ReplayCacheFile);
762 ErrMsg = "The replay cache rejected your message. Check your clock!";
763 Rply = RC.Check(pgp.sig_info);
766 raise UDNotAllowedError, Rply;
767 RC.Add(pgp.sig_info);
770 # Determine the sender address
771 ErrMsg = "A problem occured while trying to formulate the reply";
772 Sender = Email.getheader("Reply-To");
774 Sender = Email.getheader("From");
776 raise UDFormatError, "Unable to determine the sender's address";
779 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
780 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
782 Res = l.search_s(HostBaseDn, ldap.SCOPE_SUBTREE, '(objectClass=debianServer)', ['hostname'] )
783 # Res is a list of tuples.
784 # The tuples contain a dn (str) and a dictionary.
785 # The dictionaries map the key "hostname" to a list.
786 # These lists contain a single hostname (str).
787 ValidHostNames = reduce(lambda a,b: a+b, [value.get("hostname", []) for (dn, value) in Res], [])
790 if sys.argv[1] == "ping":
791 Reply = HandlePing(Reply,Attrs[0],pgp.key_info);
792 elif sys.argv[1] == "chpass":
793 if PlainText.strip().find("Please change my Debian password") != 0:
794 raise UDFormatError,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
795 Reply = HandleChPass(Reply,Attrs[0],pgp.key_info);
796 elif sys.argv[1] == "change":
797 Reply = HandleChange(Reply,Attrs[0],pgp.key_info);
800 raise UDFormatError, "Incorrect Invokation";
802 # Send the message through sendmail
803 ErrMsg = "A problem occured while trying to send the reply";
804 Child = os.popen("/usr/sbin/sendmail -t","w");
805 # Child = os.popen("cat","w");
807 if Child.close() != None:
808 raise UDExecuteError, "Sendmail gave a non-zero return code";
812 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
813 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
817 Subst["__ERROR__"] = ErrMsg;
818 Subst["__ADMIN__"] = ReplyTo;
820 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
821 List = traceback.extract_tb(sys.exc_traceback);
823 Trace = Trace + "Python Stack Trace:\n";
825 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
827 Subst["__TRACE__"] = Trace;
829 # Try to send the bounce
831 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
833 Child = os.popen("/usr/sbin/sendmail -t -oi -f ''","w");
834 Child.write(ErrReplyHead);
835 Child.write(ErrReply);
836 if Child.close() != None:
837 raise UDExecuteError, "Sendmail gave a non-zero return code";
839 sys.exit(EX_TEMPFAIL);
841 if ErrType != EX_PERMFAIL:
847 # vim:set shiftwidth=3: