4 # Prior copyright probably rmurray, troup, joey, jgg -- weasel 2008
5 # Copyright (c) 2008 Peter Palfrader <peter@palfrader.org>
7 import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, os;
9 from userdir_gpg import *;
10 from userdir_ldap import *;
12 # Error codes from /usr/include/sysexits.h
13 ReplyTo = ConfModule.replyto;
14 PingFrom = ConfModule.pingfrom;
15 ChPassFrom = ConfModule.chpassfrom;
16 ChangeFrom = ConfModule.changefrom;
17 ReplayCacheFile = ConfModule.replaycachefile;
20 EX_PERMFAIL = 65; # EX_DATAERR
21 Error = 'Message Error';
30 ArbChanges = {"c": "..",
32 "facsimileTelephoneNumber": ".*",
33 "telephoneNumber": ".*",
34 "postalAddress": ".*",
37 "emailForward": "^([^<>@]+@.+)?$",
38 "jabberJID": "^([^<>@]+@.+)?$",
43 "birthDate": "^([0-9]{4})([01][0-9])([0-3][0-9])$",
44 "mailDisableMessage": ".*",
45 "mailGreylisting": "^(TRUE|FALSE)$",
46 "mailCallout": "^(TRUE|FALSE)$",
50 DelItems = {"c": None,
52 "facsimileTelephoneNumber": None,
53 "telephoneNumber": None,
54 "postalAddress": None,
66 "sshRSAAuthKey": None,
67 "sshDSAAuthKey": None,
69 "mailGreylisting": None,
73 "mailWhitelist": None,
74 "mailDisableMessage": None,
78 # Decode a GPS location from some common forms
79 def LocDecode(Str,Dir):
80 # Check for Decimal degrees, DGM, or DGMS
81 if re.match("^[+-]?[\d.]+$",Str) != None:
84 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
86 # Check for DDDxMM.MMMM where x = [nsew]
87 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
90 Deg = G[0]; Min = G[2]; Dr = G[1];
93 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
96 Deg = G[0]; Dr = G[1];
98 # Check for DD:MM.MM x
99 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
102 Deg = G[0]; Min = G[1]; Dr = G[2];
104 # Check for DD:MM:SS.SS x
105 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
108 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
112 raise "Failed","Bad degrees";
113 if Min != None and float(Min) > 60:
114 raise "Failed","Bad minutes";
115 if Sec != None and float(Sec) > 60:
116 raise "Failed","Bad seconds";
118 # Pad on an extra leading 0 to disambiguate small numbers
119 if len(Deg) <= 1 or Deg[1] == '.':
121 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
123 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
126 # Construct a DGM/DGMS type value from the components.
137 # Handle changing a set of arbitary fields
139 def DoArbChange(Str,Attrs):
140 Match = re.match("^([^ :]+): (.*)$",Str);
145 attrName = G[0].lower();
146 for i in ArbChanges.keys():
147 if i.lower() == attrName:
150 if ArbChanges.has_key(attrName) == 0:
153 if re.match(ArbChanges[attrName],G[1]) == None:
154 raise Error, "Item does not match the required format"+ArbChanges[attrName];
156 # if attrName == 'birthDate':
157 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
158 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
159 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
161 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
163 # } elsif ($bd_day <= 28) {
166 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
167 # if ($bd_day <= 30) {
171 # if ($bd_day <= 31) {
176 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
179 Attrs.append((ldap.MOD_REPLACE,attrName,G[1]));
180 return "Changed entry %s to %s"%(attrName,G[1]);
182 # Handle changing a set of arbitary fields
184 def DoDel(Str,Attrs):
185 Match = re.match("^del (.*)$",Str);
190 attrName = G[0].lower();
191 for i in DelItems.keys():
192 if i.lower() == attrName:
195 if DelItems.has_key(attrName) == 0:
196 return "Cannot erase entry %s"%(attrName);
198 Attrs.append((ldap.MOD_DELETE,attrName,None));
199 return "Removed entry %s"%(attrName);
201 # Handle a position change message, the line format is:
202 # Lat: -12412.23 Long: +12341.2342
203 def DoPosition(Str,Attrs):
204 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
210 sLat = LocDecode(G[0],"ns");
211 sLong = LocDecode(G[1],"ew");
212 Lat = DecDegree(sLat,1);
213 Long = DecDegree(sLong,1);
215 raise Error, "Positions were found, but they are not correctly formed";
217 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
218 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
219 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
221 # Handle an SSH authentication key, the line format is:
222 # [options] 1024 35 13188913666680[..] [comment]
223 def DoSSH(Str,Attrs):
224 Match = SSH2AuthSplit.match(Str);
226 Match = re.compile('^1024 (\d+) ').match(Str)
227 if Match is not None:
228 return "SSH1 keys not supported anymore"
233 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
234 return "SSH Key added "+FormatSSHAuth(Str);
236 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
238 return "SSH Keys replaced with "+FormatSSHAuth(Str);
240 # Handle changing a dns entry
241 # host IN A 12.12.12.12
242 # host IN AAAA 1234::5678
243 # host IN CNAME foo.bar. <- Trailing dot is required
244 # host IN MX foo.bar. <- Trailing dot is required
245 def DoDNS(Str,Attrs,DnRecord):
246 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
247 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
248 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
249 #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)
250 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
252 if cnamerecord == None and\
254 mxrecord == None and\
258 # Check if the name is already taken
259 G = re.match('^([-\w+]+)\s',Str)
261 raise Error, "Hostname not found although we already passed record syntax checks"
262 hostname = G.group(1)
264 # Check for collisions
266 # [JT 20070409 - search for both tab and space suffixed hostnames
267 # since we accept either. It'd probably be better to parse the
268 # incoming string in order to construct what we feed LDAP rather
269 # than just passing it through as is.]
270 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
271 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
273 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
274 return "DNS entry is already owned by " + GetAttr(x,"uid")
280 if DNS.has_key(hostname):
281 return "CNAME and other RR types not allowed: "+Str
285 if DNS.has_key(hostname) and DNS[hostname] == 2:
286 return "CNAME and other RR types not allowed: "+Str
290 if cnamerecord != None:
291 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
292 elif arecord != None:
293 ipaddress = arecord.group(1)
294 for quad in ipaddress.split('.'):
295 if not (int(quad) >=0 and int(quad) <= 255):
296 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
297 sanitized = "%s IN A %s"% (hostname, ipaddress)
298 elif mxrecord != None:
299 priority = mxrecord.group(1)
300 mx = mxrecord.group(2)
301 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
302 elif aaaarecord != None:
303 ipv6address = aaaarecord.group(1)
304 parts = ipv6address.split(':')
306 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
308 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
313 seenEmptypart = False
316 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
319 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
321 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
323 raise Error, "None of the types I recognize was it. I shouldn't be here. confused."
326 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
327 return "DNS Entry added "+sanitized;
329 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
331 return "DNS Entry replaced with "+sanitized;
333 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
334 def DoRBL(Str,Attrs):
335 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
339 if Match.group(1) == "rbl":
341 if Match.group(1) == "rhsbl":
343 if Match.group(1) == "whitelist":
344 Key = "mailWhitelist"
345 Host = Match.group(2)
348 if SeenList.has_key(Key):
349 Attrs.append((ldap.MOD_ADD,Key,Host))
350 return "%s added %s" % (Key,Host)
352 Attrs.append((ldap.MOD_REPLACE,Key,Host))
354 return "%s replaced with %s" % (Key,Host)
356 # Handle an [almost] arbitary change
357 def HandleChange(Reply,DnRecord,Key):
359 Lines = re.split("\n *\r?",PlainText);
369 # Try to process a command line
370 Result = Result + "> "+Line+"\n";
376 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
377 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
378 DoDel(Line,Attrs) or DoRBL(Line,Attrs);
381 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
383 # Fail, if someone tries to send someone elses signed email to the
384 # daemon then we want to abort ASAP.
386 Result = Result + "Command is not understood. Halted\n";
388 Result = Result + Res + "\n";
390 # Connect to the ldap server
391 l = ldap.open(LDAPServer);
392 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
393 AccessPass = F.readline().strip().split(" ")
397 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
398 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
399 if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
400 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
401 raise Error, "This account is locked";
402 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
403 l.modify_s(Dn,Attrs);
407 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
409 raise Error, "User not found"
410 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
413 Subst["__FROM__"] = ChangeFrom;
414 Subst["__EMAIL__"] = EmailAddress(DnRecord);
415 Subst["__ADMIN__"] = ReplyTo;
416 Subst["__RESULT__"] = Result;
417 Subst["__ATTR__"] = Attribs;
419 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
421 # Handle ping handles an email sent to the 'ping' address (ie this program
422 # called with a ping argument) It replies with a dump of the public records.
423 def HandlePing(Reply,DnRecord,Key):
425 Subst["__FROM__"] = PingFrom;
426 Subst["__EMAIL__"] = EmailAddress(DnRecord);
427 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
428 Subst["__ADMIN__"] = ReplyTo;
430 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
432 # Handle a change password email sent to the change password address
433 # (this program called with the chpass argument)
434 def HandleChPass(Reply,DnRecord,Key):
435 # Generate a random password
436 Password = GenPass();
437 Pass = HashPass(Password);
439 # Use GPG to encrypt it
440 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
445 raise Error, "Unable to generate the encrypted reply, gpg failed.";
448 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
450 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
451 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
454 Subst["__FROM__"] = ChPassFrom;
455 Subst["__EMAIL__"] = EmailAddress(DnRecord);
456 Subst["__CRYPTTYPE__"] = Type;
457 Subst["__PASSWORD__"] = Message;
458 Subst["__ADMIN__"] = ReplyTo;
459 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
461 # Connect to the ldap server
462 l = ldap.open(LDAPServer);
463 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
464 AccessPass = F.readline().strip().split(" ")
466 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
468 # Check for a locked account
469 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
470 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
471 or GetAttr(Attrs[0],"userPassword").startswith("!"):
472 raise Error, "This account is locked";
474 # Modify the password
475 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
476 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
481 # Start of main program
483 # Drop messages from a mailer daemon.
484 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
487 ErrMsg = "Indeterminate Error";
488 ErrType = EX_TEMPFAIL;
490 # Startup the replay cache
491 ErrType = EX_TEMPFAIL;
492 ErrMsg = "Failed to initialize the replay cache:";
493 RC = ReplayCache(ReplayCacheFile);
497 ErrType = EX_PERMFAIL;
498 ErrMsg = "Failed to understand the email or find a signature:";
499 Email = mimetools.Message(sys.stdin,0);
500 Msg = GetClearSig(Email);
502 ErrMsg = "Message is not PGP signed:"
503 if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
504 Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
505 raise Error, "No PGP signature";
507 # Check the signature
508 ErrMsg = "Unable to check the signature or the signature was invalid:";
509 Res = GPGCheckSig(Msg[0]);
515 raise Error, "Null signature text";
517 # Extract the plain message text in the event of mime encoding
519 ErrMsg = "Problem stripping MIME headers from the decoded message"
522 Index = Res[3].index("\n\n") + 2;
524 Index = Res[3].index("\n\r\n") + 3;
525 PlainText = Res[3][Index:];
529 # Check the signature against the replay cache
530 ErrMsg = "The replay cache rejected your message. Check your clock!";
531 Rply = RC.Check(Res[1]);
535 # Connect to the ldap server
536 ErrType = EX_TEMPFAIL;
537 ErrMsg = "An error occured while performing the LDAP lookup";
539 l = ldap.open(LDAPServer);
540 l.simple_bind_s("","");
542 # Search for the matching key fingerprint
543 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
545 ErrType = EX_PERMFAIL;
547 raise Error, "Key not found"
549 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
553 # Determine the sender address
554 ErrMsg = "A problem occured while trying to formulate the reply";
555 Sender = Email.getheader("Reply-To");
557 Sender = Email.getheader("From");
559 raise Error, "Unable to determine the sender's address";
562 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
563 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
566 if sys.argv[1] == "ping":
567 Reply = HandlePing(Reply,Attrs[0],Res[2]);
568 elif sys.argv[1] == "chpass":
569 if PlainText.strip().find("Please change my Debian password") != 0:
570 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
571 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
572 elif sys.argv[1] == "change":
573 Reply = HandleChange(Reply,Attrs[0],Res[2]);
576 raise Error, "Incorrect Invokation";
578 # Send the message through sendmail
579 ErrMsg = "A problem occured while trying to send the reply";
580 Child = os.popen("/usr/sbin/sendmail -t","w");
581 # Child = os.popen("cat","w");
583 if Child.close() != None:
584 raise Error, "Sendmail gave a non-zero return code";
588 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
589 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
593 Subst["__ERROR__"] = ErrMsg;
594 Subst["__ADMIN__"] = ReplyTo;
596 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
597 List = traceback.extract_tb(sys.exc_traceback);
599 Trace = Trace + "Python Stack Trace:\n";
601 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
603 Subst["__TRACE__"] = Trace;
605 # Try to send the bounce
607 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
609 Child = os.popen("/usr/sbin/sendmail -t","w");
610 Child.write(ErrReplyHead);
611 Child.write(ErrReply);
612 if Child.close() != None:
613 raise Error, "Sendmail gave a non-zero return code";
615 sys.exit(EX_TEMPFAIL);
617 if ErrType != EX_PERMFAIL: