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';
22 ArbChanges = {"c": "..",
24 "facsimileTelephoneNumber": ".*",
25 "telephoneNumber": ".*",
26 "postalAddress": ".*",
29 "emailForward": "^([^<>@]+@.+)?$",
35 DelItems = {"c": None,
37 "facsimileTelephoneNumber": None,
38 "telephoneNumber": None,
39 "postalAddress": None,
49 "sshRSAAuthKey": None,
50 "sshDSAAuthKey": None};
52 # Decode a GPS location from some common forms
53 def LocDecode(Str,Dir):
54 # Check for Decimal degrees, DGM, or DGMS
55 if re.match("^[+-]?[\d.]+$",Str) != None:
58 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
60 # Check for DDDxMM.MMMM where x = [nsew]
61 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
64 Deg = G[0]; Min = G[2]; Dr = G[1];
67 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
70 Deg = G[0]; Dr = G[1];
72 # Check for DD:MM.MM x
73 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
76 Deg = G[0]; Min = G[1]; Dr = G[2];
78 # Check for DD:MM:SS.SS x
79 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
82 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
86 raise "Failed","Bad degrees";
87 if Min != None and float(Min) > 60:
88 raise "Failed","Bad minutes";
89 if Sec != None and float(Sec) > 60:
90 raise "Failed","Bad seconds";
92 # Pad on an extra leading 0 to disambiguate small numbers
93 if len(Deg) <= 1 or Deg[1] == '.':
95 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
97 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
100 # Construct a DGM/DGMS type value from the components.
111 # Handle changing a set of arbitary fields
113 def DoArbChange(Str,Attrs):
114 Match = re.match("^([^ :]+): (.*)$",Str);
119 attrName = G[0].lower();
120 for i in ArbChanges.keys():
121 if i.lower() == attrName:
124 if ArbChanges.has_key(attrName) == 0:
127 if re.match(ArbChanges[attrName],G[1]) == None:
128 raise Error, "Item does not match the required format"+ArbChanges[attrName];
130 Attrs.append((ldap.MOD_REPLACE,attrName,G[1]));
131 return "Changed entry %s to %s"%(attrName,G[1]);
133 # Handle changing a set of arbitary fields
135 def DoDel(Str,Attrs):
136 Match = re.match("^del (.*)$",Str);
141 attrName = G[0].lower();
142 for i in DelItems.keys():
143 if i.lower() == attrName:
146 if DelItems.has_key(attrName) == 0:
147 return "Cannot erase entry %s"%(attrName);
149 Attrs.append((ldap.MOD_DELETE,attrName,None));
150 return "Removed entry %s"%(attrName);
152 # Handle a position change message, the line format is:
153 # Lat: -12412.23 Long: +12341.2342
154 def DoPosition(Str,Attrs):
155 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$",string.lower(Str));
161 sLat = LocDecode(G[0],"ns");
162 sLong = LocDecode(G[1],"ew");
163 Lat = DecDegree(sLat,1);
164 Long = DecDegree(sLong,1);
166 raise Error, "Positions were found, but they are not correctly formed";
168 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
169 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
170 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
172 # Handle an SSH authentication key, the line format is:
173 # [options] 1024 35 13188913666680[..] [comment]
174 def DoSSH(Str,Attrs):
175 Match = SSH2AuthSplit.match(Str);
181 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
182 return "SSH Key added "+FormatSSHAuth(Str);
184 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
186 return "SSH Keys replaced with "+FormatSSHAuth(Str);
188 # Handle changing a dns entry
189 # host in a 12.12.12.12
190 # host in cname foo.bar. <- Trailing dot is required
191 def DoDNS(Str,Attrs,DnRecord):
192 cname = re.match("^[-\w]+\s+in\s+cname\s+[-\w.]+\.$",Str,re.IGNORECASE);
193 if re.match('^[-\w]+\s+in\s+a\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',\
194 Str,re.IGNORECASE) == None and cname == None and \
195 re.match("^[-\w]+\s+in\s+mx\s+\d{1,3}\s+[-\w.]+\.$",Str,re.IGNORECASE) == None:
198 # Check if the name is already taken
199 G = re.match('^([-\w+]+)\s',Str).groups();
201 # Check for collisions
203 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"dnsZoneEntry="+G[0]+" *",["uid"]);
205 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
206 return "DNS entry is already owned by " + GetAttr(x,"uid")
212 if DNS.has_key(G[0]):
213 return "CNAME and other RR types not allowed: "+Str
217 if DNS.has_key(G[0]) and DNS[G[0]] == 2:
218 return "CNAME and other RR types not allowed: "+Str
223 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",Str));
224 return "DNS Entry added "+Str;
226 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",Str));
228 return "DNS Entry replaced with "+Str;
230 # Handle an [almost] arbitary change
231 def HandleChange(Reply,DnRecord,Key):
233 Lines = re.split("\n *\r?",PlainText);
239 Line = string.strip(Line);
243 # Try to process a command line
244 Result = Result + "> "+Line+"\n";
250 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
251 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
255 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
257 # Fail, if someone tries to send someone elses signed email to the
258 # daemon then we want to abort ASAP.
260 Result = Result + "Command is not understood. Halted\n";
262 Result = Result + Res + "\n";
264 # Connect to the ldap server
265 l = ldap.open(LDAPServer);
266 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
267 AccessPass = string.split(string.strip(F.readline())," ");
271 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
272 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
273 if (string.find(GetAttr(oldAttrs[0],"userPassword"),"*LK*") != -1):
274 raise Error, "This account is locked";
275 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
276 l.modify_s(Dn,Attrs);
280 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
282 raise Error, "User not found"
283 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
286 Subst["__FROM__"] = ChangeFrom;
287 Subst["__EMAIL__"] = EmailAddress(DnRecord);
288 Subst["__ADMIN__"] = ReplyTo;
289 Subst["__RESULT__"] = Result;
290 Subst["__ATTR__"] = Attribs;
292 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
294 # Handle ping handles an email sent to the 'ping' address (ie this program
295 # called with a ping argument) It replies with a dump of the public records.
296 def HandlePing(Reply,DnRecord,Key):
298 Subst["__FROM__"] = PingFrom;
299 Subst["__EMAIL__"] = EmailAddress(DnRecord);
300 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
301 Subst["__ADMIN__"] = ReplyTo;
303 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
305 # Handle a change password email sent to the change password address
306 # (this program called with the chpass argument)
307 def HandleChPass(Reply,DnRecord,Key):
308 # Generate a random password
309 Password = GenPass();
310 Pass = HashPass(Password);
312 # Use GPG to encrypt it
313 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
318 raise Error, "Unable to generate the encrypted reply, gpg failed.";
321 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
323 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
324 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
327 Subst["__FROM__"] = ChPassFrom;
328 Subst["__EMAIL__"] = EmailAddress(DnRecord);
329 Subst["__CRYPTTYPE__"] = Type;
330 Subst["__PASSWORD__"] = Message;
331 Subst["__ADMIN__"] = ReplyTo;
332 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
334 # Connect to the ldap server
335 l = ldap.open(LDAPServer);
336 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
337 AccessPass = string.split(string.strip(F.readline())," ");
339 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
341 # Check for a locked account
342 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
343 if (string.find(GetAttr(Attrs[0],"userPassword"),"*LK*") != -1):
344 raise Error, "This account is locked";
346 # Modify the password
347 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
348 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
353 # Start of main program
355 # Drop messages from a mailer daemon.
356 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
359 ErrMsg = "Indeterminate Error";
360 ErrType = EX_TEMPFAIL;
362 # Startup the replay cache
363 ErrType = EX_TEMPFAIL;
364 ErrMsg = "Failed to initialize the replay cache:";
365 RC = ReplayCache(ReplayCacheFile);
369 ErrType = EX_PERMFAIL;
370 ErrMsg = "Failed to understand the email or find a signature:";
371 Email = mimetools.Message(sys.stdin,0);
372 Msg = GetClearSig(Email);
374 ErrMsg = "Message is not PGP signed:"
375 if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
376 string.find(Msg[0],"-----BEGIN PGP MESSAGE-----") == -1:
377 raise Error, "No PGP signature";
379 # Check the signature
380 ErrMsg = "Unable to check the signature or the signature was invalid:";
381 Res = GPGCheckSig(Msg[0]);
387 raise Error, "Null signature text";
389 # Extract the plain message text in the event of mime encoding
391 ErrMsg = "Problem stripping MIME headers from the decoded message"
394 Index = string.index(Res[3],"\n\n") + 2;
396 Index = string.index(Res[3],"\n\r\n") + 3;
397 PlainText = Res[3][Index:];
401 # Check the signature against the replay cache
402 ErrMsg = "The replay cache rejected your message. Check your clock!";
403 Rply = RC.Check(Res[1]);
407 # Connect to the ldap server
408 ErrType = EX_TEMPFAIL;
409 ErrMsg = "An error occured while performing the LDAP lookup";
411 l = ldap.open(LDAPServer);
412 l.simple_bind_s("","");
414 # Search for the matching key fingerprint
415 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
417 ErrType = EX_PERMFAIL;
419 raise Error, "Key not found"
421 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
425 # Determine the sender address
426 ErrMsg = "A problem occured while trying to formulate the reply";
427 Sender = Email.getheader("Reply-To");
429 Sender = Email.getheader("From");
431 raise Error, "Unable to determine the sender's address";
434 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
435 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
438 if sys.argv[1] == "ping":
439 Reply = HandlePing(Reply,Attrs[0],Res[2]);
440 elif sys.argv[1] == "chpass":
441 if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
442 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
443 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
444 elif sys.argv[1] == "change":
445 Reply = HandleChange(Reply,Attrs[0],Res[2]);
448 raise Error, "Incorrect Invokation";
450 # Send the message through sendmail
451 ErrMsg = "A problem occured while trying to send the reply";
452 Child = os.popen("/usr/sbin/sendmail -t","w");
453 # Child = os.popen("cat","w");
455 if Child.close() != None:
456 raise Error, "Sendmail gave a non-zero return code";
460 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
461 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
465 Subst["__ERROR__"] = ErrMsg;
466 Subst["__ADMIN__"] = ReplyTo;
468 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
469 List = traceback.extract_tb(sys.exc_traceback);
471 Trace = Trace + "Python Stack Trace:\n";
473 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
475 Subst["__TRACE__"] = Trace;
477 # Try to send the bounce
479 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
481 Child = os.popen("/usr/sbin/sendmail -t","w");
482 Child.write(ErrReplyHead);
483 Child.write(ErrReply);
484 if Child.close() != None:
485 raise Error, "Sendmail gave a non-zero return code";
487 sys.exit(EX_TEMPFAIL);
489 if ErrType != EX_PERMFAIL: