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 "mailDisableMessage": ".*",
40 "mailGreylisting": "^(TRUE|FALSE)$",
41 "mailCallout": "^(TRUE|FALSE)$",
44 DelItems = {"c": None,
46 "facsimileTelephoneNumber": None,
47 "telephoneNumber": None,
48 "postalAddress": None,
60 "sshRSAAuthKey": None,
61 "sshDSAAuthKey": None,
63 "mailGreylisting": None,
67 "mailWhitelist": None,
68 "mailDisableMessage": None,
71 # Decode a GPS location from some common forms
72 def LocDecode(Str,Dir):
73 # Check for Decimal degrees, DGM, or DGMS
74 if re.match("^[+-]?[\d.]+$",Str) != None:
77 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
79 # Check for DDDxMM.MMMM where x = [nsew]
80 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
83 Deg = G[0]; Min = G[2]; Dr = G[1];
86 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
89 Deg = G[0]; Dr = G[1];
91 # Check for DD:MM.MM x
92 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
95 Deg = G[0]; Min = G[1]; Dr = G[2];
97 # Check for DD:MM:SS.SS x
98 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
101 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
105 raise "Failed","Bad degrees";
106 if Min != None and float(Min) > 60:
107 raise "Failed","Bad minutes";
108 if Sec != None and float(Sec) > 60:
109 raise "Failed","Bad seconds";
111 # Pad on an extra leading 0 to disambiguate small numbers
112 if len(Deg) <= 1 or Deg[1] == '.':
114 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
116 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
119 # Construct a DGM/DGMS type value from the components.
130 # Handle changing a set of arbitary fields
132 def DoArbChange(Str,Attrs):
133 Match = re.match("^([^ :]+): (.*)$",Str);
138 attrName = G[0].lower();
139 for i in ArbChanges.keys():
140 if i.lower() == attrName:
143 if ArbChanges.has_key(attrName) == 0:
146 if re.match(ArbChanges[attrName],G[1]) == None:
147 raise Error, "Item does not match the required format"+ArbChanges[attrName];
149 Attrs.append((ldap.MOD_REPLACE,attrName,G[1]));
150 return "Changed entry %s to %s"%(attrName,G[1]);
152 # Handle changing a set of arbitary fields
154 def DoDel(Str,Attrs):
155 Match = re.match("^del (.*)$",Str);
160 attrName = G[0].lower();
161 for i in DelItems.keys():
162 if i.lower() == attrName:
165 if DelItems.has_key(attrName) == 0:
166 return "Cannot erase entry %s"%(attrName);
168 Attrs.append((ldap.MOD_DELETE,attrName,None));
169 return "Removed entry %s"%(attrName);
171 # Handle a position change message, the line format is:
172 # Lat: -12412.23 Long: +12341.2342
173 def DoPosition(Str,Attrs):
174 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$",string.lower(Str));
180 sLat = LocDecode(G[0],"ns");
181 sLong = LocDecode(G[1],"ew");
182 Lat = DecDegree(sLat,1);
183 Long = DecDegree(sLong,1);
185 raise Error, "Positions were found, but they are not correctly formed";
187 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
188 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
189 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
191 # Handle an SSH authentication key, the line format is:
192 # [options] 1024 35 13188913666680[..] [comment]
193 def DoSSH(Str,Attrs):
194 Match = SSH2AuthSplit.match(Str);
196 Match = re.compile('^1024 (\d+) ').match(Str)
197 if Match is not None:
198 return "SSH1 keys not supported anymore"
203 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
204 return "SSH Key added "+FormatSSHAuth(Str);
206 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
208 return "SSH Keys replaced with "+FormatSSHAuth(Str);
210 # Handle changing a dns entry
211 # host in a 12.12.12.12
212 # host in cname foo.bar. <- Trailing dot is required
213 def DoDNS(Str,Attrs,DnRecord):
214 cname = re.match("^[-\w]+\s+in\s+cname\s+[-\w.]+\.$",Str,re.IGNORECASE);
215 if re.match('^[-\w]+\s+in\s+a\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',\
216 Str,re.IGNORECASE) == None and cname == None and \
217 re.match("^[-\w]+\s+in\s+mx\s+\d{1,3}\s+[-\w.]+\.$",Str,re.IGNORECASE) == None:
220 # Check if the name is already taken
221 G = re.match('^([-\w+]+)\s',Str).groups();
223 # Check for collisions
225 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"dnsZoneEntry="+G[0]+" *",["uid"]);
227 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
228 return "DNS entry is already owned by " + GetAttr(x,"uid")
234 if DNS.has_key(G[0]):
235 return "CNAME and other RR types not allowed: "+Str
239 if DNS.has_key(G[0]) and DNS[G[0]] == 2:
240 return "CNAME and other RR types not allowed: "+Str
245 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",Str));
246 return "DNS Entry added "+Str;
248 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",Str));
250 return "DNS Entry replaced with "+Str;
252 # Handle an RBL list (mailRBL, mailRHSBL, mailWhitelist)
253 def DoRBL(Str,Attrs):
254 Match = re.compile('^mail(rbl|rhsbl|whitelist) ([-a-z0-9.]+)$').match(string.lower(Str))
258 if Match.group(1) == "rbl":
260 if Match.group(1) == "rhsbl":
262 if Match.group(1) == "whitelist":
263 Key = "mailWhitelist"
264 Host = Match.group(2)
267 if SeenList.has_key(Key):
268 Attrs.append((ldap.MOD_ADD,Key,Host))
269 return "%s added %s" % (Key,Host)
271 Attrs.append((ldap.MOD_REPLACE,Key,Host))
273 return "%s replaced with %s" % (Key,Host)
275 # Handle an [almost] arbitary change
276 def HandleChange(Reply,DnRecord,Key):
278 Lines = re.split("\n *\r?",PlainText);
284 Line = string.strip(Line);
288 # Try to process a command line
289 Result = Result + "> "+Line+"\n";
295 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
296 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
297 DoDel(Line,Attrs) or DoRBL(Line,Attrs);
300 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
302 # Fail, if someone tries to send someone elses signed email to the
303 # daemon then we want to abort ASAP.
305 Result = Result + "Command is not understood. Halted\n";
307 Result = Result + Res + "\n";
309 # Connect to the ldap server
310 l = ldap.open(LDAPServer);
311 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
312 AccessPass = string.split(string.strip(F.readline())," ");
316 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
317 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
318 if (string.find(GetAttr(oldAttrs[0],"userPassword"),"*LK*") != -1):
319 raise Error, "This account is locked";
320 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
321 l.modify_s(Dn,Attrs);
325 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
327 raise Error, "User not found"
328 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
331 Subst["__FROM__"] = ChangeFrom;
332 Subst["__EMAIL__"] = EmailAddress(DnRecord);
333 Subst["__ADMIN__"] = ReplyTo;
334 Subst["__RESULT__"] = Result;
335 Subst["__ATTR__"] = Attribs;
337 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
339 # Handle ping handles an email sent to the 'ping' address (ie this program
340 # called with a ping argument) It replies with a dump of the public records.
341 def HandlePing(Reply,DnRecord,Key):
343 Subst["__FROM__"] = PingFrom;
344 Subst["__EMAIL__"] = EmailAddress(DnRecord);
345 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
346 Subst["__ADMIN__"] = ReplyTo;
348 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
350 # Handle a change password email sent to the change password address
351 # (this program called with the chpass argument)
352 def HandleChPass(Reply,DnRecord,Key):
353 # Generate a random password
354 Password = GenPass();
355 Pass = HashPass(Password);
357 # Use GPG to encrypt it
358 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
363 raise Error, "Unable to generate the encrypted reply, gpg failed.";
366 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
368 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
369 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
372 Subst["__FROM__"] = ChPassFrom;
373 Subst["__EMAIL__"] = EmailAddress(DnRecord);
374 Subst["__CRYPTTYPE__"] = Type;
375 Subst["__PASSWORD__"] = Message;
376 Subst["__ADMIN__"] = ReplyTo;
377 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
379 # Connect to the ldap server
380 l = ldap.open(LDAPServer);
381 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
382 AccessPass = string.split(string.strip(F.readline())," ");
384 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
386 # Check for a locked account
387 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
388 if (string.find(GetAttr(Attrs[0],"userPassword"),"*LK*") != -1):
389 raise Error, "This account is locked";
391 # Modify the password
392 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
393 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
398 # Start of main program
400 # Drop messages from a mailer daemon.
401 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
404 ErrMsg = "Indeterminate Error";
405 ErrType = EX_TEMPFAIL;
407 # Startup the replay cache
408 ErrType = EX_TEMPFAIL;
409 ErrMsg = "Failed to initialize the replay cache:";
410 RC = ReplayCache(ReplayCacheFile);
414 ErrType = EX_PERMFAIL;
415 ErrMsg = "Failed to understand the email or find a signature:";
416 Email = mimetools.Message(sys.stdin,0);
417 Msg = GetClearSig(Email);
419 ErrMsg = "Message is not PGP signed:"
420 if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
421 string.find(Msg[0],"-----BEGIN PGP MESSAGE-----") == -1:
422 raise Error, "No PGP signature";
424 # Check the signature
425 ErrMsg = "Unable to check the signature or the signature was invalid:";
426 Res = GPGCheckSig(Msg[0]);
432 raise Error, "Null signature text";
434 # Extract the plain message text in the event of mime encoding
436 ErrMsg = "Problem stripping MIME headers from the decoded message"
439 Index = string.index(Res[3],"\n\n") + 2;
441 Index = string.index(Res[3],"\n\r\n") + 3;
442 PlainText = Res[3][Index:];
446 # Check the signature against the replay cache
447 ErrMsg = "The replay cache rejected your message. Check your clock!";
448 Rply = RC.Check(Res[1]);
452 # Connect to the ldap server
453 ErrType = EX_TEMPFAIL;
454 ErrMsg = "An error occured while performing the LDAP lookup";
456 l = ldap.open(LDAPServer);
457 l.simple_bind_s("","");
459 # Search for the matching key fingerprint
460 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
462 ErrType = EX_PERMFAIL;
464 raise Error, "Key not found"
466 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
470 # Determine the sender address
471 ErrMsg = "A problem occured while trying to formulate the reply";
472 Sender = Email.getheader("Reply-To");
474 Sender = Email.getheader("From");
476 raise Error, "Unable to determine the sender's address";
479 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
480 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
483 if sys.argv[1] == "ping":
484 Reply = HandlePing(Reply,Attrs[0],Res[2]);
485 elif sys.argv[1] == "chpass":
486 if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
487 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
488 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
489 elif sys.argv[1] == "change":
490 Reply = HandleChange(Reply,Attrs[0],Res[2]);
493 raise Error, "Incorrect Invokation";
495 # Send the message through sendmail
496 ErrMsg = "A problem occured while trying to send the reply";
497 Child = os.popen("/usr/sbin/sendmail -t","w");
498 # Child = os.popen("cat","w");
500 if Child.close() != None:
501 raise Error, "Sendmail gave a non-zero return code";
505 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
506 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
510 Subst["__ERROR__"] = ErrMsg;
511 Subst["__ADMIN__"] = ReplyTo;
513 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
514 List = traceback.extract_tb(sys.exc_traceback);
516 Trace = Trace + "Python Stack Trace:\n";
518 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
520 Subst["__TRACE__"] = Trace;
522 # Try to send the bounce
524 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
526 Child = os.popen("/usr/sbin/sendmail -t","w");
527 Child.write(ErrReplyHead);
528 Child.write(ErrReply);
529 if Child.close() != None:
530 raise Error, "Sendmail gave a non-zero return code";
532 sys.exit(EX_TEMPFAIL);
534 if ErrType != EX_PERMFAIL: