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])?)$",string.lower(Str));
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 cname foo.bar. <- Trailing dot is required
237 def DoDNS(Str,Attrs,DnRecord):
238 cname = re.match("^[-\w]+\s+in\s+cname\s+[-\w.]+\.$",Str,re.IGNORECASE);
239 if re.match('^[-\w]+\s+in\s+a\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',\
240 Str,re.IGNORECASE) == None and cname == None and \
241 re.match("^[-\w]+\s+in\s+mx\s+\d{1,3}\s+[-\w.]+\.$",Str,re.IGNORECASE) == None:
244 # Check if the name is already taken
245 G = re.match('^([-\w+]+)\s',Str).groups();
247 # Check for collisions
249 # [JT 20070409 - search for both tab and space suffixed hostnames
250 # since we accept either. It'd probably be better to parse the
251 # incoming string in order to construct what we feed LDAP rather
252 # than just passing it through as is.]
253 filter = "(|(dnsZoneEntry=%s *)(dnsZoneEntry=%s *))" % (G[0], G[0])
254 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["uid"]);
256 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
257 return "DNS entry is already owned by " + GetAttr(x,"uid")
263 if DNS.has_key(G[0]):
264 return "CNAME and other RR types not allowed: "+Str
268 if DNS.has_key(G[0]) and DNS[G[0]] == 2:
269 return "CNAME and other RR types not allowed: "+Str
274 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",Str));
275 return "DNS Entry added "+Str;
277 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",Str));
279 return "DNS Entry replaced with "+Str;
281 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
282 def DoRBL(Str,Attrs):
283 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(string.lower(Str))
287 if Match.group(1) == "rbl":
289 if Match.group(1) == "rhsbl":
291 if Match.group(1) == "whitelist":
292 Key = "mailWhitelist"
293 Host = Match.group(2)
296 if SeenList.has_key(Key):
297 Attrs.append((ldap.MOD_ADD,Key,Host))
298 return "%s added %s" % (Key,Host)
300 Attrs.append((ldap.MOD_REPLACE,Key,Host))
302 return "%s replaced with %s" % (Key,Host)
304 # Handle an [almost] arbitary change
305 def HandleChange(Reply,DnRecord,Key):
307 Lines = re.split("\n *\r?",PlainText);
313 Line = string.strip(Line);
317 # Try to process a command line
318 Result = Result + "> "+Line+"\n";
324 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
325 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
326 DoDel(Line,Attrs) or DoRBL(Line,Attrs);
329 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
331 # Fail, if someone tries to send someone elses signed email to the
332 # daemon then we want to abort ASAP.
334 Result = Result + "Command is not understood. Halted\n";
336 Result = Result + Res + "\n";
338 # Connect to the ldap server
339 l = ldap.open(LDAPServer);
340 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
341 AccessPass = string.split(string.strip(F.readline())," ");
345 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
346 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
347 if ((string.find(GetAttr(oldAttrs[0],"userPassword"),"*LK*") != -1)
348 or GetAttr(oldAttrs[0],"userPassword").startswith("!")):
349 raise Error, "This account is locked";
350 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
351 l.modify_s(Dn,Attrs);
355 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
357 raise Error, "User not found"
358 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
361 Subst["__FROM__"] = ChangeFrom;
362 Subst["__EMAIL__"] = EmailAddress(DnRecord);
363 Subst["__ADMIN__"] = ReplyTo;
364 Subst["__RESULT__"] = Result;
365 Subst["__ATTR__"] = Attribs;
367 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
369 # Handle ping handles an email sent to the 'ping' address (ie this program
370 # called with a ping argument) It replies with a dump of the public records.
371 def HandlePing(Reply,DnRecord,Key):
373 Subst["__FROM__"] = PingFrom;
374 Subst["__EMAIL__"] = EmailAddress(DnRecord);
375 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
376 Subst["__ADMIN__"] = ReplyTo;
378 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
380 # Handle a change password email sent to the change password address
381 # (this program called with the chpass argument)
382 def HandleChPass(Reply,DnRecord,Key):
383 # Generate a random password
384 Password = GenPass();
385 Pass = HashPass(Password);
387 # Use GPG to encrypt it
388 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
393 raise Error, "Unable to generate the encrypted reply, gpg failed.";
396 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
398 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
399 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
402 Subst["__FROM__"] = ChPassFrom;
403 Subst["__EMAIL__"] = EmailAddress(DnRecord);
404 Subst["__CRYPTTYPE__"] = Type;
405 Subst["__PASSWORD__"] = Message;
406 Subst["__ADMIN__"] = ReplyTo;
407 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
409 # Connect to the ldap server
410 l = ldap.open(LDAPServer);
411 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
412 AccessPass = string.split(string.strip(F.readline())," ");
414 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
416 # Check for a locked account
417 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
418 if (string.find(GetAttr(Attrs[0],"userPassword"),"*LK*") != -1) \
419 or GetAttr(Attrs[0],"userPassword").startswith("!"):
420 raise Error, "This account is locked";
422 # Modify the password
423 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
424 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
429 # Start of main program
431 # Drop messages from a mailer daemon.
432 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
435 ErrMsg = "Indeterminate Error";
436 ErrType = EX_TEMPFAIL;
438 # Startup the replay cache
439 ErrType = EX_TEMPFAIL;
440 ErrMsg = "Failed to initialize the replay cache:";
441 RC = ReplayCache(ReplayCacheFile);
445 ErrType = EX_PERMFAIL;
446 ErrMsg = "Failed to understand the email or find a signature:";
447 Email = mimetools.Message(sys.stdin,0);
448 Msg = GetClearSig(Email);
450 ErrMsg = "Message is not PGP signed:"
451 if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
452 string.find(Msg[0],"-----BEGIN PGP MESSAGE-----") == -1:
453 raise Error, "No PGP signature";
455 # Check the signature
456 ErrMsg = "Unable to check the signature or the signature was invalid:";
457 Res = GPGCheckSig(Msg[0]);
463 raise Error, "Null signature text";
465 # Extract the plain message text in the event of mime encoding
467 ErrMsg = "Problem stripping MIME headers from the decoded message"
470 Index = string.index(Res[3],"\n\n") + 2;
472 Index = string.index(Res[3],"\n\r\n") + 3;
473 PlainText = Res[3][Index:];
477 # Check the signature against the replay cache
478 ErrMsg = "The replay cache rejected your message. Check your clock!";
479 Rply = RC.Check(Res[1]);
483 # Connect to the ldap server
484 ErrType = EX_TEMPFAIL;
485 ErrMsg = "An error occured while performing the LDAP lookup";
487 l = ldap.open(LDAPServer);
488 l.simple_bind_s("","");
490 # Search for the matching key fingerprint
491 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
493 ErrType = EX_PERMFAIL;
495 raise Error, "Key not found"
497 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
501 # Determine the sender address
502 ErrMsg = "A problem occured while trying to formulate the reply";
503 Sender = Email.getheader("Reply-To");
505 Sender = Email.getheader("From");
507 raise Error, "Unable to determine the sender's address";
510 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
511 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
514 if sys.argv[1] == "ping":
515 Reply = HandlePing(Reply,Attrs[0],Res[2]);
516 elif sys.argv[1] == "chpass":
517 if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
518 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
519 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
520 elif sys.argv[1] == "change":
521 Reply = HandleChange(Reply,Attrs[0],Res[2]);
524 raise Error, "Incorrect Invokation";
526 # Send the message through sendmail
527 ErrMsg = "A problem occured while trying to send the reply";
528 Child = os.popen("/usr/sbin/sendmail -t","w");
529 # Child = os.popen("cat","w");
531 if Child.close() != None:
532 raise Error, "Sendmail gave a non-zero return code";
536 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
537 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
541 Subst["__ERROR__"] = ErrMsg;
542 Subst["__ADMIN__"] = ReplyTo;
544 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
545 List = traceback.extract_tb(sys.exc_traceback);
547 Trace = Trace + "Python Stack Trace:\n";
549 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
551 Subst["__TRACE__"] = Trace;
553 # Try to send the bounce
555 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
557 Child = os.popen("/usr/sbin/sendmail -t","w");
558 Child.write(ErrReplyHead);
559 Child.write(ErrReply);
560 if Child.close() != None:
561 raise Error, "Sendmail gave a non-zero return code";
563 sys.exit(EX_TEMPFAIL);
565 if ErrType != EX_PERMFAIL: