3 import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, os;
5 from userdir_gpg import *;
6 from userdir_ldap import *;
8 # Error codes from /usr/include/sysexits.h
9 ReplyTo = ConfModule.replyto;
10 PingFrom = ConfModule.pingfrom;
11 ChPassFrom = ConfModule.chpassfrom;
12 ChangeFrom = ConfModule.changefrom;
13 ReplayCacheFile = ConfModule.replaycachefile;
16 EX_PERMFAIL = 65; # EX_DATAERR
17 Error = 'Message Error';
26 ArbChanges = {"c": "..",
28 "facsimileTelephoneNumber": ".*",
29 "telephoneNumber": ".*",
30 "postalAddress": ".*",
33 "emailForward": "^([^<>@]+@.+)?$",
34 "jabberJID": "^([^<>@]+@.+)?$",
39 "birthDate": "^([0-9]{4})([01][0-9])([0-3][0-9])$",
40 "mailDisableMessage": ".*",
41 "mailGreylisting": "^(TRUE|FALSE)$",
42 "mailCallout": "^(TRUE|FALSE)$",
45 DelItems = {"c": None,
47 "facsimileTelephoneNumber": None,
48 "telephoneNumber": None,
49 "postalAddress": None,
61 "sshRSAAuthKey": None,
62 "sshDSAAuthKey": None,
64 "mailGreylisting": None,
68 "mailWhitelist": None,
69 "mailDisableMessage": None,
72 # Decode a GPS location from some common forms
73 def LocDecode(Str,Dir):
74 # Check for Decimal degrees, DGM, or DGMS
75 if re.match("^[+-]?[\d.]+$",Str) != None:
78 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
80 # Check for DDDxMM.MMMM where x = [nsew]
81 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
84 Deg = G[0]; Min = G[2]; Dr = G[1];
87 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
90 Deg = G[0]; Dr = G[1];
92 # Check for DD:MM.MM x
93 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
96 Deg = G[0]; Min = G[1]; Dr = G[2];
98 # Check for DD:MM:SS.SS x
99 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
102 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
106 raise "Failed","Bad degrees";
107 if Min != None and float(Min) > 60:
108 raise "Failed","Bad minutes";
109 if Sec != None and float(Sec) > 60:
110 raise "Failed","Bad seconds";
112 # Pad on an extra leading 0 to disambiguate small numbers
113 if len(Deg) <= 1 or Deg[1] == '.':
115 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
117 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
120 # Construct a DGM/DGMS type value from the components.
131 # Handle changing a set of arbitary fields
133 def DoArbChange(Str,Attrs):
134 Match = re.match("^([^ :]+): (.*)$",Str);
139 attrName = G[0].lower();
140 for i in ArbChanges.keys():
141 if i.lower() == attrName:
144 if ArbChanges.has_key(attrName) == 0:
147 if re.match(ArbChanges[attrName],G[1]) == None:
148 raise Error, "Item does not match the required format"+ArbChanges[attrName];
150 # if attrName == 'birthDate':
151 # (re.match("^([0-9]{4})([01][0-9])([0-3][0-9])$",G[1]) {
152 # $bd_yr = $1; $bd_mo = $2; $bd_day = $3;
153 # if ($bd_mo > 0 and $bd_mo <= 12 and $bd_day > 0) {
155 # if ($bd_day == 29 and ($bd_yr == 0 or ($bd_yr % 4 == 0 && ($bd_yr % 100 != 0 || $bd_yr % 400 == 0)))) {
157 # } elsif ($bd_day <= 28) {
160 # } elsif ($bd_mo == 4 or $bd_mo == 6 or $bd_mo == 9 or $bd_mo == 11) {
161 # if ($bd_day <= 30) {
165 # if ($bd_day <= 31) {
170 # } elsif (not defined($query->param('birthdate')) or $query->param('birthdate') =~ /^\s*$/) {
173 Attrs.append((ldap.MOD_REPLACE,attrName,G[1]));
174 return "Changed entry %s to %s"%(attrName,G[1]);
176 # Handle changing a set of arbitary fields
178 def DoDel(Str,Attrs):
179 Match = re.match("^del (.*)$",Str);
184 attrName = G[0].lower();
185 for i in DelItems.keys():
186 if i.lower() == attrName:
189 if DelItems.has_key(attrName) == 0:
190 return "Cannot erase entry %s"%(attrName);
192 Attrs.append((ldap.MOD_DELETE,attrName,None));
193 return "Removed entry %s"%(attrName);
195 # Handle a position change message, the line format is:
196 # Lat: -12412.23 Long: +12341.2342
197 def DoPosition(Str,Attrs):
198 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$", Str.lower())
204 sLat = LocDecode(G[0],"ns");
205 sLong = LocDecode(G[1],"ew");
206 Lat = DecDegree(sLat,1);
207 Long = DecDegree(sLong,1);
209 raise Error, "Positions were found, but they are not correctly formed";
211 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
212 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
213 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
215 # Handle an SSH authentication key, the line format is:
216 # [options] 1024 35 13188913666680[..] [comment]
217 def DoSSH(Str,Attrs):
218 Match = SSH2AuthSplit.match(Str);
220 Match = re.compile('^1024 (\d+) ').match(Str)
221 if Match is not None:
222 return "SSH1 keys not supported anymore"
227 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
228 return "SSH Key added "+FormatSSHAuth(Str);
230 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
232 return "SSH Keys replaced with "+FormatSSHAuth(Str);
234 # Handle changing a dns entry
235 # host IN A 12.12.12.12
236 # host IN AAAA 1234::5678
237 # host IN CNAME foo.bar. <- Trailing dot is required
238 # host IN MX foo.bar. <- Trailing dot is required
239 def DoDNS(Str,Attrs,DnRecord):
240 cnamerecord = re.match("^[-\w]+\s+IN\s+CNAME\s+([-\w.]+\.)$",Str,re.IGNORECASE)
241 arecord = re.match('^[-\w]+\s+IN\s+A\s+(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$',Str,re.IGNORECASE)
242 mxrecord = re.match("^[-\w]+\s+IN\s+MX\s+(\d{1,3})\s+([-\w.]+\.)$",Str,re.IGNORECASE)
243 #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)
244 aaaarecord = re.match('^[-\w]+\s+IN\s+AAAA\s+([A-F0-9:]{2,39})$',Str,re.IGNORECASE)
246 if cnamerecord == None and\
248 mxrecord == None and\
252 # Check if the name is already taken
253 G = re.match('^([-\w+]+)\s',Str)
255 raise Error, "Hostname not found although we already passed record syntax checks"
256 hostname = G.group(1)
258 # Check for collisions
260 # [JT 20070409 - search for both tab and space suffixed hostnames
261 # since we accept either. It'd probably be better to parse the
262 # incoming string in order to construct what we feed LDAP rather
263 # than just passing it through as is.]
264 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (hostname, hostname)
265 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
267 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
268 return "DNS entry is already owned by " + GetAttr(x,"uid")
274 if DNS.has_key(hostname):
275 return "CNAME and other RR types not allowed: "+Str
279 if DNS.has_key(hostname) and DNS[hostname] == 2:
280 return "CNAME and other RR types not allowed: "+Str
284 if cnamerecord != None:
285 sanitized = "%s IN CNAME %s" % (hostname, cnamerecord.group(1))
286 elif arecord != None:
287 ipaddress = arecord.group(1)
288 for quad in ipaddress.split('.'):
289 if not (int(quad) >=0 and int(quad) <= 255):
290 return "Invalid quad %s in IP address %s in line %s" %(quad, ipaddress, Str)
291 sanitized = "%s IN A %s"% (hostname, ipaddress)
292 elif mxrecord != None:
293 priority = mxrecord.group(1)
294 mx = mxrecord.group(2)
295 sanitized = "%s IN MX %s %s" % (hostname, priority, mx)
296 elif aaaarecord != None:
297 ipv6address = aaaarecord.group(1)
298 parts = ipv6address.split(':')
300 return "Invalid IPv6 address (%s): too many parts"%(ipv6address)
302 return "Invalid IPv6 address (%s): too few parts"%(ipv6address)
307 seenEmptypart = False
310 return "Invalid IPv6 address (%s): part %s is longer than 4 characters"%(ipv6address, p)
313 return "Invalid IPv6 address (%s): more than one :: (nothing in between colons) is not allowed"%(ipv6address)
315 sanitized = "%s IN AAAA %s" % (hostname, ipv6address)
317 raise Error, "None of the types I recognize was it. I shouldn't be here. confused."
320 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",sanitized));
321 return "DNS Entry added "+sanitized;
323 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",sanitized));
325 return "DNS Entry replaced with "+sanitized;
327 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
328 def DoRBL(Str,Attrs):
329 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(Str.lower())
333 if Match.group(1) == "rbl":
335 if Match.group(1) == "rhsbl":
337 if Match.group(1) == "whitelist":
338 Key = "mailWhitelist"
339 Host = Match.group(2)
342 if SeenList.has_key(Key):
343 Attrs.append((ldap.MOD_ADD,Key,Host))
344 return "%s added %s" % (Key,Host)
346 Attrs.append((ldap.MOD_REPLACE,Key,Host))
348 return "%s replaced with %s" % (Key,Host)
350 # Handle an [almost] arbitary change
351 def HandleChange(Reply,DnRecord,Key):
353 Lines = re.split("\n *\r?",PlainText);
363 # Try to process a command line
364 Result = Result + "> "+Line+"\n";
370 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
371 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
372 DoDel(Line,Attrs) or DoRBL(Line,Attrs);
375 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
377 # Fail, if someone tries to send someone elses signed email to the
378 # daemon then we want to abort ASAP.
380 Result = Result + "Command is not understood. Halted\n";
382 Result = Result + Res + "\n";
384 # Connect to the ldap server
385 l = ldap.open(LDAPServer);
386 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
387 AccessPass = F.readline().strip().split(" ")
391 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
392 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
393 if ((GetAttr(oldAttrs[0],"userPassword").find("*LK*") != -1)
394 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
395 raise Error, "This account is locked";
396 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
397 l.modify_s(Dn,Attrs);
401 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
403 raise Error, "User not found"
404 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
407 Subst["__FROM__"] = ChangeFrom;
408 Subst["__EMAIL__"] = EmailAddress(DnRecord);
409 Subst["__ADMIN__"] = ReplyTo;
410 Subst["__RESULT__"] = Result;
411 Subst["__ATTR__"] = Attribs;
413 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
415 # Handle ping handles an email sent to the 'ping' address (ie this program
416 # called with a ping argument) It replies with a dump of the public records.
417 def HandlePing(Reply,DnRecord,Key):
419 Subst["__FROM__"] = PingFrom;
420 Subst["__EMAIL__"] = EmailAddress(DnRecord);
421 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
422 Subst["__ADMIN__"] = ReplyTo;
424 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
426 # Handle a change password email sent to the change password address
427 # (this program called with the chpass argument)
428 def HandleChPass(Reply,DnRecord,Key):
429 # Generate a random password
430 Password = GenPass();
431 Pass = HashPass(Password);
433 # Use GPG to encrypt it
434 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
439 raise Error, "Unable to generate the encrypted reply, gpg failed.";
442 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
444 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
445 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
448 Subst["__FROM__"] = ChPassFrom;
449 Subst["__EMAIL__"] = EmailAddress(DnRecord);
450 Subst["__CRYPTTYPE__"] = Type;
451 Subst["__PASSWORD__"] = Message;
452 Subst["__ADMIN__"] = ReplyTo;
453 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
455 # Connect to the ldap server
456 l = ldap.open(LDAPServer);
457 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
458 AccessPass = F.readline().strip().split(" ")
460 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
462 # Check for a locked account
463 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
464 if (GetAttr(Attrs[0],"userPassword").find("*LK*") != -1) \
465 or GetAttr(Attrs[0],"userPassword").startswith("!"):
466 raise Error, "This account is locked";
468 # Modify the password
469 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
470 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
475 # Start of main program
477 # Drop messages from a mailer daemon.
478 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
481 ErrMsg = "Indeterminate Error";
482 ErrType = EX_TEMPFAIL;
484 # Startup the replay cache
485 ErrType = EX_TEMPFAIL;
486 ErrMsg = "Failed to initialize the replay cache:";
487 RC = ReplayCache(ReplayCacheFile);
491 ErrType = EX_PERMFAIL;
492 ErrMsg = "Failed to understand the email or find a signature:";
493 Email = mimetools.Message(sys.stdin,0);
494 Msg = GetClearSig(Email);
496 ErrMsg = "Message is not PGP signed:"
497 if Msg[0].find("-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
498 Msg[0].find("-----BEGIN PGP MESSAGE-----") == -1:
499 raise Error, "No PGP signature";
501 # Check the signature
502 ErrMsg = "Unable to check the signature or the signature was invalid:";
503 Res = GPGCheckSig(Msg[0]);
509 raise Error, "Null signature text";
511 # Extract the plain message text in the event of mime encoding
513 ErrMsg = "Problem stripping MIME headers from the decoded message"
516 Index = Res[3].index("\n\n") + 2;
518 Index = Res[3].index("\n\r\n") + 3;
519 PlainText = Res[3][Index:];
523 # Check the signature against the replay cache
524 ErrMsg = "The replay cache rejected your message. Check your clock!";
525 Rply = RC.Check(Res[1]);
529 # Connect to the ldap server
530 ErrType = EX_TEMPFAIL;
531 ErrMsg = "An error occured while performing the LDAP lookup";
533 l = ldap.open(LDAPServer);
534 l.simple_bind_s("","");
536 # Search for the matching key fingerprint
537 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
539 ErrType = EX_PERMFAIL;
541 raise Error, "Key not found"
543 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
547 # Determine the sender address
548 ErrMsg = "A problem occured while trying to formulate the reply";
549 Sender = Email.getheader("Reply-To");
551 Sender = Email.getheader("From");
553 raise Error, "Unable to determine the sender's address";
556 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
557 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
560 if sys.argv[1] == "ping":
561 Reply = HandlePing(Reply,Attrs[0],Res[2]);
562 elif sys.argv[1] == "chpass":
563 if PlainText.strip().find("Please change my Debian password") != 0:
564 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
565 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
566 elif sys.argv[1] == "change":
567 Reply = HandleChange(Reply,Attrs[0],Res[2]);
570 raise Error, "Incorrect Invokation";
572 # Send the message through sendmail
573 ErrMsg = "A problem occured while trying to send the reply";
574 Child = os.popen("/usr/sbin/sendmail -t","w");
575 # Child = os.popen("cat","w");
577 if Child.close() != None:
578 raise Error, "Sendmail gave a non-zero return code";
582 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
583 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
587 Subst["__ERROR__"] = ErrMsg;
588 Subst["__ADMIN__"] = ReplyTo;
590 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
591 List = traceback.extract_tb(sys.exc_traceback);
593 Trace = Trace + "Python Stack Trace:\n";
595 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
597 Subst["__TRACE__"] = Trace;
599 # Try to send the bounce
601 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
603 Child = os.popen("/usr/sbin/sendmail -t","w");
604 Child.write(ErrReplyHead);
605 Child.write(ErrReply);
606 if Child.close() != None:
607 raise Error, "Sendmail gave a non-zero return code";
609 sys.exit(EX_TEMPFAIL);
611 if ErrType != EX_PERMFAIL: