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';
21 ArbChanges = {"c": "..",
23 "facsimiletelephonenumber": ".*",
24 "telephonenumber": ".*",
25 "postaladdress": ".*",
28 "emailforward": "^([^<>@]+@.+)?$",
34 DelItems = {"c": None,
36 "facsimiletelephonenumber": None,
37 "telephonenumber": None,
38 "postaladdress": None,
47 "sshrsaauthkey": None,
48 "sshdsaauthkey": None};
50 # Decode a GPS location from some common forms
51 def LocDecode(Str,Dir):
52 # Check for Decimal degrees, DGM, or DGMS
53 if re.match("^[+-]?[\d.]+$",Str) != None:
56 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
58 # Check for DDDxMM.MMMM where x = [nsew]
59 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
62 Deg = G[0]; Min = G[2]; Dr = G[1];
65 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
68 Deg = G[0]; Dr = G[1];
70 # Check for DD:MM.MM x
71 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
74 Deg = G[0]; Min = G[1]; Dr = G[2];
76 # Check for DD:MM:SS.SS x
77 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
80 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
84 raise "Failed","Bad degrees";
85 if Min != None and float(Min) > 60:
86 raise "Failed","Bad minutes";
87 if Sec != None and float(Sec) > 60:
88 raise "Failed","Bad seconds";
90 # Pad on an extra leading 0 to disambiguate small numbers
91 if len(Deg) <= 1 or Deg[1] == '.':
93 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
95 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
98 # Construct a DGM/DGMS type value from the components.
109 # Handle changing a set of arbitary fields
111 def DoArbChange(Str,Attrs):
112 Match = re.match("^([^ :]+): (.*)$",Str);
117 if ArbChanges.has_key(G[0]) == 0:
120 if re.match(ArbChanges[G[0]],G[1]) == None:
121 raise Error, "Item does not match the required format"+ArbChanges[G[0]];
123 Attrs.append((ldap.MOD_REPLACE,G[0],G[1]));
124 return "Changed entry %s to %s"%(G[0],G[1]);
126 # Handle changing a set of arbitary fields
128 def DoDel(Str,Attrs):
129 Match = re.match("^del (.*)$",Str);
134 if DelItems.has_key(G[0]) == 0:
135 return "Cannot erase entry %s"%(G[0]);
137 Attrs.append((ldap.MOD_DELETE,G[0],None));
138 return "Removed entry %s"%(G[0]);
140 # Handle a position change message, the line format is:
141 # Lat: -12412.23 Long: +12341.2342
142 def DoPosition(Str,Attrs):
143 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$",string.lower(Str));
149 sLat = LocDecode(G[0],"ns");
150 sLong = LocDecode(G[1],"ew");
151 Lat = DecDegree(sLat,1);
152 Long = DecDegree(sLong,1);
154 raise Error, "Positions were found, but they are not correctly formed";
156 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
157 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
158 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
160 # Handle an SSH authentication key, the line format is:
161 # [options] 1024 35 13188913666680[..] [comment]
162 def DoSSH(Str,Attrs):
163 Match = SSHAuthSplit.match(Str);
165 Match = SSH2AuthSplit.match(Str);
171 Attrs.append((ldap.MOD_ADD,"sshrsaauthkey",Str));
172 return "SSH Key added "+FormatSSHAuth(Str);
174 Attrs.append((ldap.MOD_REPLACE,"sshrsaauthkey",Str));
176 return "SSH Keys replaced with "+FormatSSHAuth(Str);
178 # Handle changing a dns entry
179 # host in a 12.12.12.12
180 # host in cname foo.bar. <- Trailing dot is required
181 def DoDNS(Str,Attrs,DnRecord):
182 if re.match('^[\w-]+\s+in\s+a\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',\
183 Str,re.IGNORECASE) == None and \
184 re.match("^[\w-]+\s+in\s+cname\s+[\w.\-]+\.$",Str,re.IGNORECASE) == None and \
185 re.match("^[\w-]+\s+in\s+mx\s+\d{1,3}\s+[\w.\-]+\.$",Str,re.IGNORECASE) == None:
188 # Check if the name is already taken
189 G = re.match('^([\w-+]+)\s',Str).groups();
191 # Check for collisions
193 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"dnszoneentry="+G[0]+" *",["uid"]);
195 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
196 return "DNS entry is already owned by " + GetAttr(x,"uid")
200 Attrs.append((ldap.MOD_ADD,"dnszoneentry",Str));
201 return "DNS Entry added "+Str;
203 Attrs.append((ldap.MOD_REPLACE,"dnszoneentry",Str));
205 return "DNS Entry replaced with "+Str;
207 # Handle an [almost] arbitary change
208 def HandleChange(Reply,DnRecord,Key):
210 Lines = re.split("\n *\r?",PlainText);
216 Line = string.strip(Line);
220 # Try to process a command line
221 Result = Result + "> "+Line+"\n";
227 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
228 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
232 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
234 # Fail, if someone tries to send someone elses signed email to the
235 # daemon then we want to abort ASAP.
237 Result = Result + "Command is not understood. Halted\n";
239 Result = Result + Res + "\n";
241 # Connect to the ldap server
242 l = ldap.open(LDAPServer);
243 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
244 AccessPass = string.split(string.strip(F.readline())," ");
248 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
249 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
250 l.modify_s(Dn,Attrs);
254 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
256 raise Error, "User not found"
257 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
260 Subst["__FROM__"] = ChangeFrom;
261 Subst["__EMAIL__"] = EmailAddress(DnRecord);
262 Subst["__ADMIN__"] = ReplyTo;
263 Subst["__RESULT__"] = Result;
264 Subst["__ATTR__"] = Attribs;
266 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
268 # Handle ping handles an email sent to the 'ping' address (ie this program
269 # called with a ping argument) It replies with a dump of the public records.
270 def HandlePing(Reply,DnRecord,Key):
272 Subst["__FROM__"] = PingFrom;
273 Subst["__EMAIL__"] = EmailAddress(DnRecord);
274 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
275 Subst["__ADMIN__"] = ReplyTo;
277 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
279 # Handle a change password email sent to the change password address
280 # (this program called with the chpass argument)
281 def HandleChPass(Reply,DnRecord,Key):
282 # Generate a random password
283 Password = GenPass();
284 Pass = HashPass(Password);
286 # Use GPG to encrypt it
287 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
292 raise Error, "Unable to generate the encrypted reply, gpg failed.";
295 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
297 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
298 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
301 Subst["__FROM__"] = ChPassFrom;
302 Subst["__EMAIL__"] = EmailAddress(DnRecord);
303 Subst["__CRYPTTYPE__"] = Type;
304 Subst["__PASSWORD__"] = Message;
305 Subst["__ADMIN__"] = ReplyTo;
306 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
308 # Connect to the ldap server
309 l = ldap.open(LDAPServer);
310 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
311 AccessPass = string.split(string.strip(F.readline())," ");
313 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
315 # Check for a locked account
316 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
317 if (string.find(GetAttr(Attrs[0],"userpassword"),"*LK*") != -1):
318 raise Error, "This account is locked";
320 # Modify the password
321 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
322 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
327 # Start of main program
329 # Drop messages from a mailer daemon.
330 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
333 ErrMsg = "Indeterminate Error";
334 ErrType = EX_TEMPFAIL;
336 # Startup the replay cache
337 ErrType = EX_TEMPFAIL;
338 ErrMsg = "Failed to initialize the replay cache:";
339 RC = ReplayCache(ReplayCacheFile);
343 ErrType = EX_PERMFAIL;
344 ErrMsg = "Failed to understand the email or find a signature:";
345 Email = mimetools.Message(sys.stdin,0);
346 Msg = GetClearSig(Email);
348 ErrMsg = "Message is not PGP signed:"
349 if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1:
350 raise Error, "No PGP signature";
352 # Check the signature
353 ErrMsg = "Unable to check the signature or the signature was invalid:";
354 Res = GPGCheckSig(Msg[0]);
360 raise Error, "Null signature text";
362 # Extract the plain message text in the event of mime encoding
364 ErrMsg = "Problem stripping MIME headers from the decoded message"
367 Index = string.index(Res[3],"\n\n") + 2;
369 Index = string.index(Res[3],"\n\r\n") + 3;
370 PlainText = Res[3][Index:];
374 # Check the signature against the replay cache
375 ErrMsg = "The replay cache rejected your message. Check your clock!";
376 Rply = RC.Check(Res[1]);
381 # Connect to the ldap server
382 ErrType = EX_TEMPFAIL;
383 ErrMsg = "An error occured while performing the LDAP lookup";
385 l = ldap.open(LDAPServer);
386 l.simple_bind_s("","");
388 # Search for the matching key fingerprint
389 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + Res[2][1]);
391 raise Error, "Key not found"
393 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
395 # Determine the sender address
396 ErrType = EX_PERMFAIL;
397 ErrMsg = "A problem occured while trying to formulate the reply";
398 Sender = Email.getheader("Reply-To");
400 Sender = Email.getheader("From");
402 raise Error, "Unable to determine the sender's address";
404 if (string.find(GetAttr(Attrs[0],"userpassword"),"*LK*") != -1):
405 raise Error, "This account is locked";
408 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
409 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
412 if sys.argv[1] == "ping":
413 Reply = HandlePing(Reply,Attrs[0],Res[2]);
414 elif sys.argv[1] == "chpass":
415 if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
416 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
417 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
418 elif sys.argv[1] == "change":
419 Reply = HandleChange(Reply,Attrs[0],Res[2]);
422 raise Error, "Incorrect Invokation";
424 # Send the message through sendmail
425 ErrMsg = "A problem occured while trying to send the reply";
426 Child = os.popen("/usr/sbin/sendmail -t","w");
427 # Child = os.popen("cat","w");
429 if Child.close() != None:
430 raise Error, "Sendmail gave a non-zero return code";
434 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
435 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
439 Subst["__ERROR__"] = ErrMsg;
440 Subst["__ADMIN__"] = ReplyTo;
442 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
443 List = traceback.extract_tb(sys.exc_traceback);
445 Trace = Trace + "Python Stack Trace:\n";
447 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
449 Subst["__TRACE__"] = Trace;
451 # Try to send the bounce
453 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
455 Child = os.popen("/usr/sbin/sendmail -t","w");
456 Child.write(ErrReplyHead);
457 Child.write(ErrReply);
458 if Child.close() != None:
459 raise Error, "Sendmail gave a non-zero return code";
461 sys.exit(EX_TEMPFAIL);
463 if ErrType != EX_PERMFAIL: