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};
49 # Decode a GPS location from some common forms
50 def LocDecode(Str,Dir):
51 # Check for Decimal degrees, DGM, or DGMS
52 if re.match("^[+-]?[\d.]+$",Str) != None:
55 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
57 # Check for DDDxMM.MMMM where x = [nsew]
58 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
61 Deg = G[0]; Min = G[2]; Dr = G[1];
64 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
67 Deg = G[0]; Dr = G[1];
69 # Check for DD:MM.MM x
70 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
73 Deg = G[0]; Min = G[1]; Dr = G[2];
75 # Check for DD:MM:SS.SS x
76 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
79 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
83 raise "Failed","Bad degrees";
84 if Min != None and float(Min) > 60:
85 raise "Failed","Bad minutes";
86 if Sec != None and float(Sec) > 60:
87 raise "Failed","Bad seconds";
89 # Pad on an extra leading 0 to disambiguate small numbers
90 if len(Deg) <= 1 or Deg[1] == '.':
92 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
94 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
97 # Construct a DGM/DGMS type value from the components.
108 # Handle changing a set of arbitary fields
110 def DoArbChange(Str,Attrs):
111 Match = re.match("^([^ :]+): (.*)$",Str);
116 if ArbChanges.has_key(G[0]) == 0:
119 if re.match(ArbChanges[G[0]],G[1]) == None:
120 raise Error, "Item does not match the required format"+ArbChanges[G[0]];
122 Attrs.append((ldap.MOD_REPLACE,G[0],G[1]));
123 return "Changed entry %s to %s"%(G[0],G[1]);
125 # Handle changing a set of arbitary fields
127 def DoDel(Str,Attrs):
128 Match = re.match("^del (.*)$",Str);
133 if DelItems.has_key(G[0]) == 0:
134 return "Cannot erase entry %s"%(G[0]);
136 Attrs.append((ldap.MOD_DELETE,G[0],None));
137 return "Removed entry %s"%(G[0]);
139 # Handle a position change message, the line format is:
140 # Lat: -12412.23 Long: +12341.2342
141 def DoPosition(Str,Attrs):
142 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$",string.lower(Str));
148 sLat = LocDecode(G[0],"ns");
149 sLong = LocDecode(G[1],"ew");
150 Lat = DecDegree(sLat,1);
151 Long = DecDegree(sLong,1);
153 raise Error, "Positions were found, but they are not correctly formed";
155 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
156 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
157 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
159 # Handle a SSH RSA authentication key, the line format is:
160 # [options] 1024 35 13188913666680[..] [comment]
161 def DoSSH(Str,Attrs):
162 Match = SSHAuthSplit.match(Str);
168 Attrs.append((ldap.MOD_ADD,"sshrsaauthkey",Str));
169 return "SSH Key added "+FormatSSHAuth(Str);
171 Attrs.append((ldap.MOD_REPLACE,"sshrsaauthkey",Str));
173 return "SSH Keys replaced with "+FormatSSHAuth(Str);
175 # Handle changing a dns entry
176 # host in a 12.12.12.12
177 # host in cname foo.bar. <- Trailing dot is required
178 def DoDNS(Str,Attrs,DnRecord):
179 if re.match('^[\w-]+\s+in\s+a\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',\
180 Str,re.IGNORECASE) == None and \
181 re.match("^[\w-]+\s+in\s+cname\s+[\w.\-]+\.$",Str,re.IGNORECASE) == None and \
182 re.match("^[\w-]+\s+in\s+mx\s+\d{1,3}\s+[\w.\-]+\.$",Str,re.IGNORECASE) == None:
185 # Check if the name is already taken
186 G = re.match('^([\w-+]+)\s',Str).groups();
188 # Check for collisions
190 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"dnszoneentry="+G[0]+" *",["uid"]);
192 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
193 return "DNS entry is already owned by " + GetAttr(x,"uid")
197 Attrs.append((ldap.MOD_ADD,"dnszoneentry",Str));
198 return "DNS Entry added "+Str;
200 Attrs.append((ldap.MOD_REPLACE,"dnszoneentry",Str));
202 return "DNS Entry replaced with "+Str;
204 # Handle an [almost] arbitary change
205 def HandleChange(Reply,DnRecord,Key):
207 Lines = re.split("\n *\r",PlainText);
213 Line = string.strip(Line);
217 # Try to process a command line
218 Result = Result + "> "+Line+"\n";
224 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
225 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
229 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
231 # Fail, if someone tries to send someone elses signed email to the
232 # daemon then we want to abort ASAP.
234 Result = Result + "Command is not understood. Halted\n";
236 Result = Result + Res + "\n";
238 # Connect to the ldap server
239 l = ldap.open(LDAPServer);
240 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
241 AccessPass = string.split(string.strip(F.readline())," ");
245 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
246 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
247 l.modify_s(Dn,Attrs);
251 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
253 raise Error, "User not found"
254 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
257 Subst["__FROM__"] = ChangeFrom;
258 Subst["__EMAIL__"] = EmailAddress(DnRecord);
259 Subst["__ADMIN__"] = ReplyTo;
260 Subst["__RESULT__"] = Result;
261 Subst["__ATTR__"] = Attribs;
263 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
265 # Handle ping handles an email sent to the 'ping' address (ie this program
266 # called with a ping argument) It replies with a dump of the public records.
267 def HandlePing(Reply,DnRecord,Key):
269 Subst["__FROM__"] = PingFrom;
270 Subst["__EMAIL__"] = EmailAddress(DnRecord);
271 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
272 Subst["__ADMIN__"] = ReplyTo;
274 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
276 # Handle a change password email sent to the change password address
277 # (this program called with the chpass argument)
278 def HandleChPass(Reply,DnRecord,Key):
279 # Generate a random password
280 Password = GenPass();
281 Pass = HashPass(Password);
283 # Use GPG to encrypt it
284 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
289 raise Error, "Unable to generate the encrypted reply, gpg failed.";
292 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
294 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
295 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
298 Subst["__FROM__"] = ChPassFrom;
299 Subst["__EMAIL__"] = EmailAddress(DnRecord);
300 Subst["__CRYPTTYPE__"] = Type;
301 Subst["__PASSWORD__"] = Message;
302 Subst["__ADMIN__"] = ReplyTo;
303 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
305 # Connect to the ldap server
306 l = ldap.open(LDAPServer);
307 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
308 AccessPass = string.split(string.strip(F.readline())," ");
310 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
312 # Check for a locked account
313 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
314 if (string.find(GetAttr(Attrs[0],"userpassword"),"*LK*") != -1):
315 raise Error, "This account is locked";
317 # Modify the password
318 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
319 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
324 # Start of main program
326 # Drop messages from a mailer daemon.
327 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
330 ErrMsg = "Indeterminate Error";
331 ErrType = EX_TEMPFAIL;
333 # Startup the replay cache
334 ErrType = EX_TEMPFAIL;
335 ErrMsg = "Failed to initialize the replay cache:";
336 RC = ReplayCache(ReplayCacheFile);
340 ErrType = EX_PERMFAIL;
341 ErrMsg = "Failed to understand the email or find a signature:";
342 Email = mimetools.Message(sys.stdin,0);
343 Msg = GetClearSig(Email);
345 ErrMsg = "Message is not PGP signed:"
346 if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1:
347 raise Error, "No PGP signature";
349 # Check the signature
350 ErrMsg = "Unable to check the signature or the signature was invalid:";
351 Res = GPGCheckSig(Msg[0]);
357 raise Error, "Null signature text";
359 # Extract the plain message text in the event of mime encoding
361 ErrMsg = "Problem stripping MIME headers from the decoded message"
364 Index = string.index(Res[3],"\n\n") + 2;
366 Index = string.index(Res[3],"\n\r\n") + 3;
367 PlainText = Res[3][Index:];
371 # Check the signature against the replay cache
372 ErrMsg = "The replay cache rejected your message. Check your clock!";
373 Rply = RC.Check(Res[1]);
378 # Connect to the ldap server
379 ErrType = EX_TEMPFAIL;
380 ErrMsg = "An error occured while performing the LDAP lookup";
382 l = ldap.open(LDAPServer);
383 l.simple_bind_s("","");
385 # Search for the matching key fingerprint
386 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + Res[2][1]);
388 raise Error, "Key not found"
390 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
392 # Determine the sender address
393 ErrType = EX_PERMFAIL;
394 ErrMsg = "A problem occured while trying to formulate the reply";
395 Sender = Email.getheader("Reply-To");
397 Sender = Email.getheader("From");
399 raise Error, "Unable to determine the sender's address";
401 if (string.find(GetAttr(Attrs[0],"userpassword"),"*LK*") != -1):
402 raise Error, "This account is locked";
405 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
406 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
409 if sys.argv[1] == "ping":
410 Reply = HandlePing(Reply,Attrs[0],Res[2]);
411 elif sys.argv[1] == "chpass":
412 if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
413 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
414 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
415 elif sys.argv[1] == "change":
416 Reply = HandleChange(Reply,Attrs[0],Res[2]);
419 raise Error, "Incorrect Invokation";
421 # Send the message through sendmail
422 ErrMsg = "A problem occured while trying to send the reply";
423 Child = os.popen("/usr/sbin/sendmail -t","w");
424 # Child = os.popen("cat","w");
426 if Child.close() != None:
427 raise Error, "Sendmail gave a non-zero return code";
431 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
432 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
436 Subst["__ERROR__"] = ErrMsg;
437 Subst["__ADMIN__"] = ReplyTo;
439 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
440 List = traceback.extract_tb(sys.exc_traceback);
442 Trace = Trace + "Python Stack Trace:\n";
444 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
446 Subst["__TRACE__"] = Trace;
448 # Try to send the bounce
450 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
452 Child = os.popen("/usr/sbin/sendmail -t","w");
453 Child.write(ErrReplyHead);
454 Child.write(ErrReply);
455 if Child.close() != None:
456 raise Error, "Sendmail gave a non-zero return code";
458 sys.exit(EX_TEMPFAIL);
460 if ErrType != EX_PERMFAIL: