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
10 from userdir_gpg import *
11 from userdir_ldap import *
13 # Error codes from /usr/include/sysexits.h
14 ReplyTo = ConfModule.replyto;
15 PingFrom = ConfModule.pingfrom;
16 ChPassFrom = ConfModule.chpassfrom;
17 ChangeFrom = ConfModule.changefrom;
18 ReplayCacheFile = ConfModule.replaycachefile;
19 SSHFingerprintFile = ConfModule.fingerprintfile
22 EX_PERMFAIL = 65; # EX_DATAERR
23 Error = 'Message Error';
32 SSHFingerprint = re.compile('^(\d+) ([0-9a-f\:]{47}) (.+)$')
33 SSHRSA1Match = re.compile('^^(.* )?\d+ \d+ \d+')
35 ArbChanges = {"c": "..",
37 "facsimileTelephoneNumber": ".*",
38 "telephoneNumber": ".*",
39 "postalAddress": ".*",
42 "emailForward": "^([^<>@]+@.+)?$",
43 "jabberJID": "^([^<>@]+@.+)?$",
48 "birthDate": "^([0-9]{4})([01][0-9])([0-3][0-9])$",
49 "mailDisableMessage": ".*",
50 "mailGreylisting": "^(TRUE|FALSE)$",
51 "mailCallout": "^(TRUE|FALSE)$",
55 DelItems = {"c": None,
57 "facsimileTelephoneNumber": None,
58 "telephoneNumber": None,
59 "postalAddress": None,
71 "sshRSAAuthKey": None,
72 "sshDSAAuthKey": None,
74 "mailGreylisting": None,
78 "mailWhitelist": None,
79 "mailDisableMessage": None,
83 # Decode a GPS location from some common forms
84 def LocDecode(Str,Dir):
85 # Check for Decimal degrees, DGM, or DGMS
86 if re.match("^[+-]?[\d.]+$",Str) != None:
89 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
91 # Check for DDDxMM.MMMM where x = [nsew]
92 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
95 Deg = G[0]; Min = G[2]; Dr = G[1];
98 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
101 Deg = G[0]; Dr = G[1];
103 # Check for DD:MM.MM x
104 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
107 Deg = G[0]; Min = G[1]; Dr = G[2];
109 # Check for DD:MM:SS.SS x
110 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
113 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
117 raise "Failed","Bad degrees";
118 if Min != None and float(Min) > 60:
119 raise "Failed","Bad minutes";
120 if Sec != None and float(Sec) > 60:
121 raise "Failed","Bad seconds";
123 # Pad on an extra leading 0 to disambiguate small numbers
124 if len(Deg) <= 1 or Deg[1] == '.':
126 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
128 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
131 # Construct a DGM/DGMS type value from the components.
142 # Handle changing a set of arbitary fields
144 def DoArbChange(Str,Attrs):
145 Match = re.match("^([^ :]+): (.*)$",Str);
150 attrName = G[0].lower();
151 for i in ArbChanges.keys():
152 if i.lower() == attrName:
155 if ArbChanges.has_key(attrName) == 0:
158 if re.match(ArbChanges[attrName],G[1]) == None:
159 raise Error, "Item does not match the required format"+ArbChanges[attrName];
161 # if attrName == 'birthDate':
162 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
163 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
164 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
166 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
168 # } elsif ($bd_day <= 28) {
171 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
172 # if ($bd_day <= 30) {
176 # if ($bd_day <= 31) {
181 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
184 Attrs.append((ldap.MOD_REPLACE,attrName,G[1]));
185 return "Changed entry %s to %s"%(attrName,G[1]);
187 # Handle changing a set of arbitary fields
189 def DoDel(Str,Attrs):
190 Match = re.match("^del (.*)$",Str);
195 attrName = G[0].lower();
196 for i in DelItems.keys():
197 if i.lower() == attrName:
200 if DelItems.has_key(attrName) == 0:
201 return "Cannot erase entry %s"%(attrName);
203 Attrs.append((ldap.MOD_DELETE,attrName,None));
204 return "Removed entry %s"%(attrName);
206 # Handle a position change message, the line format is:
207 # Lat: -12412.23 Long: +12341.2342
208 def DoPosition(Str,Attrs):
209 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
215 sLat = LocDecode(G[0],"ns");
216 sLong = LocDecode(G[1],"ew");
217 Lat = DecDegree(sLat,1);
218 Long = DecDegree(sLong,1);
220 raise Error, "Positions were found, but they are not correctly formed";
222 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
223 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
224 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
226 # Load bad ssh fingerprints
228 f = open(SSHFingerprintFile, "r")
230 FingerprintLine = re.compile('^([0-9a-f\:]{47}).*$')
231 for line in f.readlines():
232 Match = FingerprintLine.match(line)
233 if Match is not None:
238 # Handle an SSH authentication key, the line format is:
239 # [options] 1024 35 13188913666680[..] [comment]
240 def DoSSH(Str, Attrs, badkeys, uid):
241 Match = SSH2AuthSplit.match(Str);
245 Match = SSHRSA1Match.match(Str)
246 if Match is not None:
247 return "RSA1 keys not supported anymore"
250 (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
252 f.write("%s\n" % (Str))
254 cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
255 (result, output) = commands.getstatusoutput(cmd)
258 raise Error, "ssh-keygen -l invocation failed!\n%s\n" % (output)
262 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
263 ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
265 Subst["__ADMIN__"] = ReplyTo
266 Subst["__USER__"] = uid
268 Match = SSHFingerprint.match(output)
274 Subst["__ERROR__"] = "SSH keysize %s is below limit 1024" % (g[0])
275 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
277 Child = os.popen("/usr/sbin/sendmail -t","w")
278 Child.write(ErrReplyHead)
279 Child.write(ErrReply)
280 if Child.close() != None:
281 raise Error, "Sendmail gave a non-zero return code"
283 sys.exit(EX_TEMPFAIL)
285 # And now break and stop processing input, which sends a reply to the user.
286 raise Error, "SSH keys must have at least 1024 bits, processing halted, NOTHING MODIFIED AT ALL"
287 elif g[1] in badkeys:
290 Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
291 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
293 Child = os.popen("/usr/sbin/sendmail -t","w")
294 Child.write(ErrReplyHead)
295 Child.write(ErrReply)
296 if Child.close() != None:
297 raise Error, "Sendmail gave a non-zero return code"
299 sys.exit(EX_TEMPFAIL)
301 # And now break and stop processing input, which sends a reply to the user.
302 raise Error, "Submitted SSH Key known to be bad and insecure, processing halted, NOTHING MODIFIED AT ALL"
304 if (typekey == "dss"):
305 return "DSA keys not accepted anymore"
309 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
310 return "SSH Key added "+FormatSSHAuth(Str);
312 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
314 return "SSH Keys replaced with "+FormatSSHAuth(Str);
316 # Handle changing a dns entry
317 # host IN A 12.12.12.12
318 # host IN AAAA 1234::5678
319 # host IN CNAME foo.bar. <- Trailing dot is required
320 # host IN MX foo.bar. <- Trailing dot is required
321 def DoDNS(Str,Attrs,DnRecord):
322 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
323 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
324 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
325 #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)
326 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
328 if cnamerecord == None and\
330 mxrecord == None and\
334 # Check if the name is already taken
335 G = re.match('^([-\w+]+)\s',Str)
337 raise Error, "Hostname not found although we already passed record syntax checks"
338 hostname = G.group(1)
340 # Check for collisions
342 # [JT 20070409 - search for both tab and space suffixed hostnames
343 # since we accept either. It'd probably be better to parse the
344 # incoming string in order to construct what we feed LDAP rather
345 # than just passing it through as is.]
346 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
347 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
349 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
350 return "DNS entry is already owned by " + GetAttr(x,"uid")
356 if DNS.has_key(hostname):
357 return "CNAME and other RR types not allowed: "+Str
361 if DNS.has_key(hostname) and DNS[hostname] == 2:
362 return "CNAME and other RR types not allowed: "+Str
366 if cnamerecord != None:
367 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
368 elif arecord != None:
369 ipaddress = arecord.group(1)
370 for quad in ipaddress.split('.'):
371 if not (int(quad) >=0 and int(quad) <= 255):
372 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
373 sanitized = "%s IN A %s"% (hostname, ipaddress)
374 elif mxrecord != None:
375 priority = mxrecord.group(1)
376 mx = mxrecord.group(2)
377 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
378 elif aaaarecord != None:
379 ipv6address = aaaarecord.group(1)
380 parts = ipv6address.split(':')
382 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
384 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
389 seenEmptypart = False
392 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
395 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
397 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
399 raise Error, "None of the types I recognize was it. I shouldn't be here. confused."
402 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
403 return "DNS Entry added "+sanitized;
405 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
407 return "DNS Entry replaced with "+sanitized;
409 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
410 def DoRBL(Str,Attrs):
411 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
415 if Match.group(1) == "rbl":
417 if Match.group(1) == "rhsbl":
419 if Match.group(1) == "whitelist":
420 Key = "mailWhitelist"
421 Host = Match.group(2)
424 if SeenList.has_key(Key):
425 Attrs.append((ldap.MOD_ADD,Key,Host))
426 return "%s added %s" % (Key,Host)
428 Attrs.append((ldap.MOD_REPLACE,Key,Host))
430 return "%s replaced with %s" % (Key,Host)
432 # Handle an [almost] arbitary change
433 def HandleChange(Reply,DnRecord,Key):
435 Lines = re.split("\n *\r?",PlainText);
445 # Try to process a command line
446 Result = Result + "> "+Line+"\n";
452 badkeys = LoadBadSSH()
453 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
454 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
455 DoDel(Line,Attrs) or DoRBL(Line,Attrs)
458 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
460 # Fail, if someone tries to send someone elses signed email to the
461 # daemon then we want to abort ASAP.
463 Result = Result + "Command is not understood. Halted\n";
465 Result = Result + Res + "\n";
467 # Connect to the ldap server
468 l = ldap.open(LDAPServer);
469 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
470 AccessPass = F.readline().strip().split(" ")
474 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
475 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
476 if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
477 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
478 raise Error, "This account is locked";
479 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
480 l.modify_s(Dn,Attrs);
484 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
486 raise Error, "User not found"
487 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
490 Subst["__FROM__"] = ChangeFrom;
491 Subst["__EMAIL__"] = EmailAddress(DnRecord);
492 Subst["__ADMIN__"] = ReplyTo;
493 Subst["__RESULT__"] = Result;
494 Subst["__ATTR__"] = Attribs;
496 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
498 # Handle ping handles an email sent to the 'ping' address (ie this program
499 # called with a ping argument) It replies with a dump of the public records.
500 def HandlePing(Reply,DnRecord,Key):
502 Subst["__FROM__"] = PingFrom;
503 Subst["__EMAIL__"] = EmailAddress(DnRecord);
504 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
505 Subst["__ADMIN__"] = ReplyTo;
507 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
509 # Handle a change password email sent to the change password address
510 # (this program called with the chpass argument)
511 def HandleChPass(Reply,DnRecord,Key):
512 # Generate a random password
513 Password = GenPass();
514 Pass = HashPass(Password);
516 # Use GPG to encrypt it
517 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
522 raise Error, "Unable to generate the encrypted reply, gpg failed.";
525 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
527 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
528 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
531 Subst["__FROM__"] = ChPassFrom;
532 Subst["__EMAIL__"] = EmailAddress(DnRecord);
533 Subst["__CRYPTTYPE__"] = Type;
534 Subst["__PASSWORD__"] = Message;
535 Subst["__ADMIN__"] = ReplyTo;
536 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
538 # Connect to the ldap server
539 l = ldap.open(LDAPServer);
540 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
541 AccessPass = F.readline().strip().split(" ")
543 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
545 # Check for a locked account
546 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
547 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
548 or GetAttr(Attrs[0],"userPassword").startswith("!"):
549 raise Error, "This account is locked";
551 # Modify the password
552 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
553 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
558 # Start of main program
560 # Drop messages from a mailer daemon.
561 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
564 ErrMsg = "Indeterminate Error";
565 ErrType = EX_TEMPFAIL;
567 # Startup the replay cache
568 ErrType = EX_TEMPFAIL;
569 ErrMsg = "Failed to initialize the replay cache:";
570 RC = ReplayCache(ReplayCacheFile);
574 ErrType = EX_PERMFAIL;
575 ErrMsg = "Failed to understand the email or find a signature:";
576 Email = mimetools.Message(sys.stdin,0);
577 Msg = GetClearSig(Email);
579 ErrMsg = "Message is not PGP signed:"
580 if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
581 Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
582 raise Error, "No PGP signature";
584 # Check the signature
585 ErrMsg = "Unable to check the signature or the signature was invalid:";
586 Res = GPGCheckSig(Msg[0]);
592 raise Error, "Null signature text";
594 # Extract the plain message text in the event of mime encoding
596 ErrMsg = "Problem stripping MIME headers from the decoded message"
599 Index = Res[3].index("\n\n") + 2;
601 Index = Res[3].index("\n\r\n") + 3;
602 PlainText = Res[3][Index:];
606 # Check the signature against the replay cache
607 ErrMsg = "The replay cache rejected your message. Check your clock!";
608 Rply = RC.Check(Res[1]);
612 # Connect to the ldap server
613 ErrType = EX_TEMPFAIL;
614 ErrMsg = "An error occured while performing the LDAP lookup";
616 l = ldap.open(LDAPServer);
617 l.simple_bind_s("","");
619 # Search for the matching key fingerprint
620 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
622 ErrType = EX_PERMFAIL;
624 raise Error, "Key not found"
626 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
630 # Determine the sender address
631 ErrMsg = "A problem occured while trying to formulate the reply";
632 Sender = Email.getheader("Reply-To");
634 Sender = Email.getheader("From");
636 raise Error, "Unable to determine the sender's address";
639 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
640 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
643 if sys.argv[1] == "ping":
644 Reply = HandlePing(Reply,Attrs[0],Res[2]);
645 elif sys.argv[1] == "chpass":
646 if PlainText.strip().find("Please change my Debian password") != 0:
647 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
648 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
649 elif sys.argv[1] == "change":
650 Reply = HandleChange(Reply,Attrs[0],Res[2]);
653 raise Error, "Incorrect Invokation";
655 # Send the message through sendmail
656 ErrMsg = "A problem occured while trying to send the reply";
657 Child = os.popen("/usr/sbin/sendmail -t","w");
658 # Child = os.popen("cat","w");
660 if Child.close() != None:
661 raise Error, "Sendmail gave a non-zero return code";
665 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
666 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
670 Subst["__ERROR__"] = ErrMsg;
671 Subst["__ADMIN__"] = ReplyTo;
673 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
674 List = traceback.extract_tb(sys.exc_traceback);
676 Trace = Trace + "Python Stack Trace:\n";
678 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
680 Subst["__TRACE__"] = Trace;
682 # Try to send the bounce
684 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
686 Child = os.popen("/usr/sbin/sendmail -t","w");
687 Child.write(ErrReplyHead);
688 Child.write(ErrReply);
689 if Child.close() != None:
690 raise Error, "Sendmail gave a non-zero return code";
692 sys.exit(EX_TEMPFAIL);
694 if ErrType != EX_PERMFAIL: