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)$",
49 DelItems = {"c": None,
51 "facsimileTelephoneNumber": None,
52 "telephoneNumber": None,
53 "postalAddress": None,
65 "sshRSAAuthKey": None,
66 "sshDSAAuthKey": None,
68 "mailGreylisting": None,
72 "mailWhitelist": None,
73 "mailDisableMessage": None,
76 # Decode a GPS location from some common forms
77 def LocDecode(Str,Dir):
78 # Check for Decimal degrees, DGM, or DGMS
79 if re.match("^[+-]?[\d.]+$",Str) != None:
82 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
84 # Check for DDDxMM.MMMM where x = [nsew]
85 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
88 Deg = G[0]; Min = G[2]; Dr = G[1];
91 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
94 Deg = G[0]; Dr = G[1];
96 # Check for DD:MM.MM x
97 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
100 Deg = G[0]; Min = G[1]; Dr = G[2];
102 # Check for DD:MM:SS.SS x
103 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
106 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
110 raise "Failed","Bad degrees";
111 if Min != None and float(Min) > 60:
112 raise "Failed","Bad minutes";
113 if Sec != None and float(Sec) > 60:
114 raise "Failed","Bad seconds";
116 # Pad on an extra leading 0 to disambiguate small numbers
117 if len(Deg) <= 1 or Deg[1] == '.':
119 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
121 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
124 # Construct a DGM/DGMS type value from the components.
135 # Handle changing a set of arbitary fields
137 def DoArbChange(Str,Attrs):
138 Match = re.match("^([^ :]+): (.*)$",Str);
143 attrName = G[0].lower();
144 for i in ArbChanges.keys():
145 if i.lower() == attrName:
148 if ArbChanges.has_key(attrName) == 0:
151 if re.match(ArbChanges[attrName],G[1]) == None:
152 raise Error, "Item does not match the required format"+ArbChanges[attrName];
154 # if attrName == 'birthDate':
155 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
156 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
157 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
159 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
161 # } elsif ($bd_day <= 28) {
164 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
165 # if ($bd_day <= 30) {
169 # if ($bd_day <= 31) {
174 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
177 Attrs.append((ldap.MOD_REPLACE,attrName,G[1]));
178 return "Changed entry %s to %s"%(attrName,G[1]);
180 # Handle changing a set of arbitary fields
182 def DoDel(Str,Attrs):
183 Match = re.match("^del (.*)$",Str);
188 attrName = G[0].lower();
189 for i in DelItems.keys():
190 if i.lower() == attrName:
193 if DelItems.has_key(attrName) == 0:
194 return "Cannot erase entry %s"%(attrName);
196 Attrs.append((ldap.MOD_DELETE,attrName,None));
197 return "Removed entry %s"%(attrName);
199 # Handle a position change message, the line format is:
200 # Lat: -12412.23 Long: +12341.2342
201 def DoPosition(Str,Attrs):
202 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
208 sLat = LocDecode(G[0],"ns");
209 sLong = LocDecode(G[1],"ew");
210 Lat = DecDegree(sLat,1);
211 Long = DecDegree(sLong,1);
213 raise Error, "Positions were found, but they are not correctly formed";
215 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
216 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
217 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
219 # Handle an SSH authentication key, the line format is:
220 # [options] 1024 35 13188913666680[..] [comment]
221 def DoSSH(Str,Attrs):
222 Match = SSH2AuthSplit.match(Str);
224 Match = re.compile('^1024 (\d+) ').match(Str)
225 if Match is not None:
226 return "SSH1 keys not supported anymore"
231 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
232 return "SSH Key added "+FormatSSHAuth(Str);
234 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
236 return "SSH Keys replaced with "+FormatSSHAuth(Str);
238 # Handle changing a dns entry
239 # host IN A 12.12.12.12
240 # host IN AAAA 1234::5678
241 # host IN CNAME foo.bar. <- Trailing dot is required
242 # host IN MX foo.bar. <- Trailing dot is required
243 def DoDNS(Str,Attrs,DnRecord):
244 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
245 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
246 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
247 #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)
248 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
250 if cnamerecord == None and\
252 mxrecord == None and\
256 # Check if the name is already taken
257 G = re.match('^([-\w+]+)\s',Str)
259 raise Error, "Hostname not found although we already passed record syntax checks"
260 hostname = G.group(1)
262 # Check for collisions
264 # [JT 20070409 - search for both tab and space suffixed hostnames
265 # since we accept either. It'd probably be better to parse the
266 # incoming string in order to construct what we feed LDAP rather
267 # than just passing it through as is.]
268 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
269 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
271 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
272 return "DNS entry is already owned by " + GetAttr(x,"uid")
278 if DNS.has_key(hostname):
279 return "CNAME and other RR types not allowed: "+Str
283 if DNS.has_key(hostname) and DNS[hostname] == 2:
284 return "CNAME and other RR types not allowed: "+Str
288 if cnamerecord != None:
289 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
290 elif arecord != None:
291 ipaddress = arecord.group(1)
292 for quad in ipaddress.split('.'):
293 if not (int(quad) >=0 and int(quad) <= 255):
294 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
295 sanitized = "%s IN A %s"% (hostname, ipaddress)
296 elif mxrecord != None:
297 priority = mxrecord.group(1)
298 mx = mxrecord.group(2)
299 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
300 elif aaaarecord != None:
301 ipv6address = aaaarecord.group(1)
302 parts = ipv6address.split(':')
304 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
306 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
311 seenEmptypart = False
314 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
317 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
319 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
321 raise Error, "None of the types I recognize was it. I shouldn't be here. confused."
324 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
325 return "DNS Entry added "+sanitized;
327 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
329 return "DNS Entry replaced with "+sanitized;
331 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
332 def DoRBL(Str,Attrs):
333 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
337 if Match.group(1) == "rbl":
339 if Match.group(1) == "rhsbl":
341 if Match.group(1) == "whitelist":
342 Key = "mailWhitelist"
343 Host = Match.group(2)
346 if SeenList.has_key(Key):
347 Attrs.append((ldap.MOD_ADD,Key,Host))
348 return "%s added %s" % (Key,Host)
350 Attrs.append((ldap.MOD_REPLACE,Key,Host))
352 return "%s replaced with %s" % (Key,Host)
354 # Handle an [almost] arbitary change
355 def HandleChange(Reply,DnRecord,Key):
357 Lines = re.split("\n *\r?",PlainText);
367 # Try to process a command line
368 Result = Result + "> "+Line+"\n";
374 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
375 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
376 DoDel(Line,Attrs) or DoRBL(Line,Attrs);
379 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
381 # Fail, if someone tries to send someone elses signed email to the
382 # daemon then we want to abort ASAP.
384 Result = Result + "Command is not understood. Halted\n";
386 Result = Result + Res + "\n";
388 # Connect to the ldap server
389 l = ldap.open(LDAPServer);
390 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
391 AccessPass = F.readline().strip().split(" ")
395 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
396 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
397 if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
398 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
399 raise Error, "This account is locked";
400 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
401 l.modify_s(Dn,Attrs);
405 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
407 raise Error, "User not found"
408 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
411 Subst["__FROM__"] = ChangeFrom;
412 Subst["__EMAIL__"] = EmailAddress(DnRecord);
413 Subst["__ADMIN__"] = ReplyTo;
414 Subst["__RESULT__"] = Result;
415 Subst["__ATTR__"] = Attribs;
417 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
419 # Handle ping handles an email sent to the 'ping' address (ie this program
420 # called with a ping argument) It replies with a dump of the public records.
421 def HandlePing(Reply,DnRecord,Key):
423 Subst["__FROM__"] = PingFrom;
424 Subst["__EMAIL__"] = EmailAddress(DnRecord);
425 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
426 Subst["__ADMIN__"] = ReplyTo;
428 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
430 # Handle a change password email sent to the change password address
431 # (this program called with the chpass argument)
432 def HandleChPass(Reply,DnRecord,Key):
433 # Generate a random password
434 Password = GenPass();
435 Pass = HashPass(Password);
437 # Use GPG to encrypt it
438 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
443 raise Error, "Unable to generate the encrypted reply, gpg failed.";
446 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
448 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
449 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
452 Subst["__FROM__"] = ChPassFrom;
453 Subst["__EMAIL__"] = EmailAddress(DnRecord);
454 Subst["__CRYPTTYPE__"] = Type;
455 Subst["__PASSWORD__"] = Message;
456 Subst["__ADMIN__"] = ReplyTo;
457 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
459 # Connect to the ldap server
460 l = ldap.open(LDAPServer);
461 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
462 AccessPass = F.readline().strip().split(" ")
464 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
466 # Check for a locked account
467 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
468 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
469 or GetAttr(Attrs[0],"userPassword").startswith("!"):
470 raise Error, "This account is locked";
472 # Modify the password
473 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
474 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
479 # Start of main program
481 # Drop messages from a mailer daemon.
482 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
485 ErrMsg = "Indeterminate Error";
486 ErrType = EX_TEMPFAIL;
488 # Startup the replay cache
489 ErrType = EX_TEMPFAIL;
490 ErrMsg = "Failed to initialize the replay cache:";
491 RC = ReplayCache(ReplayCacheFile);
495 ErrType = EX_PERMFAIL;
496 ErrMsg = "Failed to understand the email or find a signature:";
497 Email = mimetools.Message(sys.stdin,0);
498 Msg = GetClearSig(Email);
500 ErrMsg = "Message is not PGP signed:"
501 if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
502 Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
503 raise Error, "No PGP signature";
505 # Check the signature
506 ErrMsg = "Unable to check the signature or the signature was invalid:";
507 Res = GPGCheckSig(Msg[0]);
513 raise Error, "Null signature text";
515 # Extract the plain message text in the event of mime encoding
517 ErrMsg = "Problem stripping MIME headers from the decoded message"
520 Index = Res[3].index("\n\n") + 2;
522 Index = Res[3].index("\n\r\n") + 3;
523 PlainText = Res[3][Index:];
527 # Check the signature against the replay cache
528 ErrMsg = "The replay cache rejected your message. Check your clock!";
529 Rply = RC.Check(Res[1]);
533 # Connect to the ldap server
534 ErrType = EX_TEMPFAIL;
535 ErrMsg = "An error occured while performing the LDAP lookup";
537 l = ldap.open(LDAPServer);
538 l.simple_bind_s("","");
540 # Search for the matching key fingerprint
541 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
543 ErrType = EX_PERMFAIL;
545 raise Error, "Key not found"
547 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
551 # Determine the sender address
552 ErrMsg = "A problem occured while trying to formulate the reply";
553 Sender = Email.getheader("Reply-To");
555 Sender = Email.getheader("From");
557 raise Error, "Unable to determine the sender's address";
560 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
561 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
564 if sys.argv[1] == "ping":
565 Reply = HandlePing(Reply,Attrs[0],Res[2]);
566 elif sys.argv[1] == "chpass":
567 if PlainText.strip().find("Please change my Debian password") != 0:
568 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
569 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
570 elif sys.argv[1] == "change":
571 Reply = HandleChange(Reply,Attrs[0],Res[2]);
574 raise Error, "Incorrect Invokation";
576 # Send the message through sendmail
577 ErrMsg = "A problem occured while trying to send the reply";
578 Child = os.popen("/usr/sbin/sendmail -t","w");
579 # Child = os.popen("cat","w");
581 if Child.close() != None:
582 raise Error, "Sendmail gave a non-zero return code";
586 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
587 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
591 Subst["__ERROR__"] = ErrMsg;
592 Subst["__ADMIN__"] = ReplyTo;
594 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
595 List = traceback.extract_tb(sys.exc_traceback);
597 Trace = Trace + "Python Stack Trace:\n";
599 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
601 Subst["__TRACE__"] = Trace;
603 # Try to send the bounce
605 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
607 Child = os.popen("/usr/sbin/sendmail -t","w");
608 Child.write(ErrReplyHead);
609 Child.write(ErrReply);
610 if Child.close() != None:
611 raise Error, "Sendmail gave a non-zero return code";
613 sys.exit(EX_TEMPFAIL);
615 if ErrType != EX_PERMFAIL: