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}) (.+)$')
34 ArbChanges = {"c": "..",
36 "facsimileTelephoneNumber": ".*",
37 "telephoneNumber": ".*",
38 "postalAddress": ".*",
41 "emailForward": "^([^<>@]+@.+)?$",
42 "jabberJID": "^([^<>@]+@.+)?$",
47 "birthDate": "^([0-9]{4})([01][0-9])([0-3][0-9])$",
48 "mailDisableMessage": ".*",
49 "mailGreylisting": "^(TRUE|FALSE)$",
50 "mailCallout": "^(TRUE|FALSE)$",
54 DelItems = {"c": None,
56 "facsimileTelephoneNumber": None,
57 "telephoneNumber": None,
58 "postalAddress": None,
70 "sshRSAAuthKey": None,
71 "sshDSAAuthKey": None,
73 "mailGreylisting": None,
77 "mailWhitelist": None,
78 "mailDisableMessage": None,
82 # Decode a GPS location from some common forms
83 def LocDecode(Str,Dir):
84 # Check for Decimal degrees, DGM, or DGMS
85 if re.match("^[+-]?[\d.]+$",Str) != None:
88 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
90 # Check for DDDxMM.MMMM where x = [nsew]
91 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
94 Deg = G[0]; Min = G[2]; Dr = G[1];
97 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
100 Deg = G[0]; Dr = G[1];
102 # Check for DD:MM.MM x
103 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
106 Deg = G[0]; Min = G[1]; Dr = G[2];
108 # Check for DD:MM:SS.SS x
109 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
112 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
116 raise "Failed","Bad degrees";
117 if Min != None and float(Min) > 60:
118 raise "Failed","Bad minutes";
119 if Sec != None and float(Sec) > 60:
120 raise "Failed","Bad seconds";
122 # Pad on an extra leading 0 to disambiguate small numbers
123 if len(Deg) <= 1 or Deg[1] == '.':
125 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
127 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
130 # Construct a DGM/DGMS type value from the components.
141 # Handle changing a set of arbitary fields
143 def DoArbChange(Str,Attrs):
144 Match = re.match("^([^ :]+): (.*)$",Str);
149 attrName = G[0].lower();
150 for i in ArbChanges.keys():
151 if i.lower() == attrName:
154 if ArbChanges.has_key(attrName) == 0:
157 if re.match(ArbChanges[attrName],G[1]) == None:
158 raise Error, "Item does not match the required format"+ArbChanges[attrName];
160 # if attrName == 'birthDate':
161 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
162 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
163 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
165 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
167 # } elsif ($bd_day <= 28) {
170 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
171 # if ($bd_day <= 30) {
175 # if ($bd_day <= 31) {
180 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
183 Attrs.append((ldap.MOD_REPLACE,attrName,G[1]));
184 return "Changed entry %s to %s"%(attrName,G[1]);
186 # Handle changing a set of arbitary fields
188 def DoDel(Str,Attrs):
189 Match = re.match("^del (.*)$",Str);
194 attrName = G[0].lower();
195 for i in DelItems.keys():
196 if i.lower() == attrName:
199 if DelItems.has_key(attrName) == 0:
200 return "Cannot erase entry %s"%(attrName);
202 Attrs.append((ldap.MOD_DELETE,attrName,None));
203 return "Removed entry %s"%(attrName);
205 # Handle a position change message, the line format is:
206 # Lat: -12412.23 Long: +12341.2342
207 def DoPosition(Str,Attrs):
208 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
214 sLat = LocDecode(G[0],"ns");
215 sLong = LocDecode(G[1],"ew");
216 Lat = DecDegree(sLat,1);
217 Long = DecDegree(sLong,1);
219 raise Error, "Positions were found, but they are not correctly formed";
221 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
222 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
223 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
225 # Load bad ssh fingerprints
227 f = open(SSHFingerprintFile, "r")
229 FingerprintLine = re.compile('^([0-9a-f\:]{47}).*$')
230 for line in f.readlines():
231 Match = FingerprintLine.match(line)
232 if Match is not None:
237 # Handle an SSH authentication key, the line format is:
238 # [options] 1024 35 13188913666680[..] [comment]
239 def DoSSH(Str, Attrs, badkeys, uid):
240 Match = SSH2AuthSplit.match(Str);
244 Match = re.compile('^1024 (\d+) ').match(Str)
245 if Match is not None:
246 return "SSH1 keys not supported anymore"
249 (fd, path) = tempfile.mkstemp(".pub", "sshkeytry", "/tmp")
251 f.write("%s\n" % (Str))
253 cmd = "/usr/bin/ssh-keygen -l -f %s < /dev/null" % (path)
254 (result, output) = commands.getstatusoutput(cmd)
257 raise Error, "ssh-keygen -l invocation failed!\n%s\n" % (output)
261 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()))
262 ErrReplyHead = "From: %s\nCc: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],os.environ['SENDER'],ReplyTo,Date)
264 Subst["__ADMIN__"] = ReplyTo
265 Subst["__USER__"] = uid
267 Match = SSHFingerprint.match(output)
273 Subst["__ERROR__"] = "SSH keysize %s is below limit 1024" % (g[0])
274 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
276 Child = os.popen("/usr/sbin/sendmail -t","w")
277 Child.write(ErrReplyHead)
278 Child.write(ErrReply)
279 if Child.close() != None:
280 raise Error, "Sendmail gave a non-zero return code"
282 sys.exit(EX_TEMPFAIL)
284 # And now break and stop processing input, which sends a reply to the user.
285 raise Error, "SSH keys must have at least 1024 bits, processing halted, NOTHING MODIFIED AT ALL"
286 elif g[1] in badkeys:
289 Subst["__ERROR__"] = "SSH key with fingerprint %s known as bad key" % (g[1])
290 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"admin-info","r").read())
292 Child = os.popen("/usr/sbin/sendmail -t","w")
293 Child.write(ErrReplyHead)
294 Child.write(ErrReply)
295 if Child.close() != None:
296 raise Error, "Sendmail gave a non-zero return code"
298 sys.exit(EX_TEMPFAIL)
300 # And now break and stop processing input, which sends a reply to the user.
301 raise Error, "Submitted SSH Key known to be bad and insecure, processing halted, NOTHING MODIFIED AT ALL"
303 if (typekey == "dss"):
304 return "DSA keys not accepted anymore"
308 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
309 return "SSH Key added "+FormatSSHAuth(Str);
311 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
313 return "SSH Keys replaced with "+FormatSSHAuth(Str);
315 # Handle changing a dns entry
316 # host IN A 12.12.12.12
317 # host IN AAAA 1234::5678
318 # host IN CNAME foo.bar. <- Trailing dot is required
319 # host IN MX foo.bar. <- Trailing dot is required
320 def DoDNS(Str,Attrs,DnRecord):
321 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
322 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
323 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
324 #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)
325 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
327 if cnamerecord == None and\
329 mxrecord == None and\
333 # Check if the name is already taken
334 G = re.match('^([-\w+]+)\s',Str)
336 raise Error, "Hostname not found although we already passed record syntax checks"
337 hostname = G.group(1)
339 # Check for collisions
341 # [JT 20070409 - search for both tab and space suffixed hostnames
342 # since we accept either. It'd probably be better to parse the
343 # incoming string in order to construct what we feed LDAP rather
344 # than just passing it through as is.]
345 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
346 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
348 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
349 return "DNS entry is already owned by " + GetAttr(x,"uid")
355 if DNS.has_key(hostname):
356 return "CNAME and other RR types not allowed: "+Str
360 if DNS.has_key(hostname) and DNS[hostname] == 2:
361 return "CNAME and other RR types not allowed: "+Str
365 if cnamerecord != None:
366 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
367 elif arecord != None:
368 ipaddress = arecord.group(1)
369 for quad in ipaddress.split('.'):
370 if not (int(quad) >=0 and int(quad) <= 255):
371 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
372 sanitized = "%s IN A %s"% (hostname, ipaddress)
373 elif mxrecord != None:
374 priority = mxrecord.group(1)
375 mx = mxrecord.group(2)
376 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
377 elif aaaarecord != None:
378 ipv6address = aaaarecord.group(1)
379 parts = ipv6address.split(':')
381 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
383 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
388 seenEmptypart = False
391 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
394 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
396 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
398 raise Error, "None of the types I recognize was it. I shouldn't be here. confused."
401 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
402 return "DNS Entry added "+sanitized;
404 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
406 return "DNS Entry replaced with "+sanitized;
408 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
409 def DoRBL(Str,Attrs):
410 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
414 if Match.group(1) == "rbl":
416 if Match.group(1) == "rhsbl":
418 if Match.group(1) == "whitelist":
419 Key = "mailWhitelist"
420 Host = Match.group(2)
423 if SeenList.has_key(Key):
424 Attrs.append((ldap.MOD_ADD,Key,Host))
425 return "%s added %s" % (Key,Host)
427 Attrs.append((ldap.MOD_REPLACE,Key,Host))
429 return "%s replaced with %s" % (Key,Host)
431 # Handle an [almost] arbitary change
432 def HandleChange(Reply,DnRecord,Key):
434 Lines = re.split("\n *\r?",PlainText);
444 # Try to process a command line
445 Result = Result + "> "+Line+"\n";
451 badkeys = LoadBadSSH()
452 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
453 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs,badkeys,GetAttr(DnRecord,"uid")) or \
454 DoDel(Line,Attrs) or DoRBL(Line,Attrs)
457 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
459 # Fail, if someone tries to send someone elses signed email to the
460 # daemon then we want to abort ASAP.
462 Result = Result + "Command is not understood. Halted\n";
464 Result = Result + Res + "\n";
466 # Connect to the ldap server
467 l = ldap.open(LDAPServer);
468 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
469 AccessPass = F.readline().strip().split(" ")
473 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
474 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
475 if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
476 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
477 raise Error, "This account is locked";
478 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
479 l.modify_s(Dn,Attrs);
483 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
485 raise Error, "User not found"
486 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
489 Subst["__FROM__"] = ChangeFrom;
490 Subst["__EMAIL__"] = EmailAddress(DnRecord);
491 Subst["__ADMIN__"] = ReplyTo;
492 Subst["__RESULT__"] = Result;
493 Subst["__ATTR__"] = Attribs;
495 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
497 # Handle ping handles an email sent to the 'ping' address (ie this program
498 # called with a ping argument) It replies with a dump of the public records.
499 def HandlePing(Reply,DnRecord,Key):
501 Subst["__FROM__"] = PingFrom;
502 Subst["__EMAIL__"] = EmailAddress(DnRecord);
503 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
504 Subst["__ADMIN__"] = ReplyTo;
506 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
508 # Handle a change password email sent to the change password address
509 # (this program called with the chpass argument)
510 def HandleChPass(Reply,DnRecord,Key):
511 # Generate a random password
512 Password = GenPass();
513 Pass = HashPass(Password);
515 # Use GPG to encrypt it
516 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
521 raise Error, "Unable to generate the encrypted reply, gpg failed.";
524 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
526 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
527 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
530 Subst["__FROM__"] = ChPassFrom;
531 Subst["__EMAIL__"] = EmailAddress(DnRecord);
532 Subst["__CRYPTTYPE__"] = Type;
533 Subst["__PASSWORD__"] = Message;
534 Subst["__ADMIN__"] = ReplyTo;
535 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
537 # Connect to the ldap server
538 l = ldap.open(LDAPServer);
539 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
540 AccessPass = F.readline().strip().split(" ")
542 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
544 # Check for a locked account
545 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
546 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
547 or GetAttr(Attrs[0],"userPassword").startswith("!"):
548 raise Error, "This account is locked";
550 # Modify the password
551 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
552 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
557 # Start of main program
559 # Drop messages from a mailer daemon.
560 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
563 ErrMsg = "Indeterminate Error";
564 ErrType = EX_TEMPFAIL;
566 # Startup the replay cache
567 ErrType = EX_TEMPFAIL;
568 ErrMsg = "Failed to initialize the replay cache:";
569 RC = ReplayCache(ReplayCacheFile);
573 ErrType = EX_PERMFAIL;
574 ErrMsg = "Failed to understand the email or find a signature:";
575 Email = mimetools.Message(sys.stdin,0);
576 Msg = GetClearSig(Email);
578 ErrMsg = "Message is not PGP signed:"
579 if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
580 Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
581 raise Error, "No PGP signature";
583 # Check the signature
584 ErrMsg = "Unable to check the signature or the signature was invalid:";
585 Res = GPGCheckSig(Msg[0]);
591 raise Error, "Null signature text";
593 # Extract the plain message text in the event of mime encoding
595 ErrMsg = "Problem stripping MIME headers from the decoded message"
598 Index = Res[3].index("\n\n") + 2;
600 Index = Res[3].index("\n\r\n") + 3;
601 PlainText = Res[3][Index:];
605 # Check the signature against the replay cache
606 ErrMsg = "The replay cache rejected your message. Check your clock!";
607 Rply = RC.Check(Res[1]);
611 # Connect to the ldap server
612 ErrType = EX_TEMPFAIL;
613 ErrMsg = "An error occured while performing the LDAP lookup";
615 l = ldap.open(LDAPServer);
616 l.simple_bind_s("","");
618 # Search for the matching key fingerprint
619 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
621 ErrType = EX_PERMFAIL;
623 raise Error, "Key not found"
625 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
629 # Determine the sender address
630 ErrMsg = "A problem occured while trying to formulate the reply";
631 Sender = Email.getheader("Reply-To");
633 Sender = Email.getheader("From");
635 raise Error, "Unable to determine the sender's address";
638 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
639 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
642 if sys.argv[1] == "ping":
643 Reply = HandlePing(Reply,Attrs[0],Res[2]);
644 elif sys.argv[1] == "chpass":
645 if PlainText.strip().find("Please change my Debian password") != 0:
646 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
647 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
648 elif sys.argv[1] == "change":
649 Reply = HandleChange(Reply,Attrs[0],Res[2]);
652 raise Error, "Incorrect Invokation";
654 # Send the message through sendmail
655 ErrMsg = "A problem occured while trying to send the reply";
656 Child = os.popen("/usr/sbin/sendmail -t","w");
657 # Child = os.popen("cat","w");
659 if Child.close() != None:
660 raise Error, "Sendmail gave a non-zero return code";
664 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
665 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
669 Subst["__ERROR__"] = ErrMsg;
670 Subst["__ADMIN__"] = ReplyTo;
672 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
673 List = traceback.extract_tb(sys.exc_traceback);
675 Trace = Trace + "Python Stack Trace:\n";
677 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
679 Subst["__TRACE__"] = Trace;
681 # Try to send the bounce
683 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
685 Child = os.popen("/usr/sbin/sendmail -t","w");
686 Child.write(ErrReplyHead);
687 Child.write(ErrReply);
688 if Child.close() != None:
689 raise Error, "Sendmail gave a non-zero return code";
691 sys.exit(EX_TEMPFAIL);
693 if ErrType != EX_PERMFAIL: