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:
184 # Check if the name is already taken
185 G = re.match('^([\w-+]+)\s',Str).groups();
187 # Check for collisions
189 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"dnszoneentry="+G[0]+" *",["uid"]);
191 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
192 return "DNS entry is already owned by " + GetAttr(x,"uid")
196 Attrs.append((ldap.MOD_ADD,"dnszoneentry",Str));
197 return "DNS Entry added "+Str;
199 Attrs.append((ldap.MOD_REPLACE,"dnszoneentry",Str));
201 return "DNS Entry replaced with "+Str;
203 # Handle an [almost] arbitary change
204 def HandleChange(Reply,DnRecord,Key):
206 Lines = string.split(PlainText,"\r\n");
212 Line = string.strip(Line);
216 # Try to process a command line
217 Result = Result + "> "+Line+"\n";
223 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
224 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
228 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
230 # Fail, if someone tries to send someone elses signed email to the
231 # daemon then we want to abort ASAP.
233 Result = Result + "Command is not understood. Halted\n";
235 Result = Result + Res + "\n";
237 # Connect to the ldap server
238 l = ldap.open(LDAPServer);
239 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
240 AccessPass = string.split(string.strip(F.readline())," ");
244 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
245 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
246 l.modify_s(Dn,Attrs);
250 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
252 raise Error, "User not found"
253 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
256 Subst["__FROM__"] = ChangeFrom;
257 Subst["__EMAIL__"] = EmailAddress(DnRecord);
258 Subst["__ADMIN__"] = ReplyTo;
259 Subst["__RESULT__"] = Result;
260 Subst["__ATTR__"] = Attribs;
262 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
264 # Handle ping handles an email sent to the 'ping' address (ie this program
265 # called with a ping argument) It replies with a dump of the public records.
266 def HandlePing(Reply,DnRecord,Key):
268 Subst["__FROM__"] = PingFrom;
269 Subst["__EMAIL__"] = EmailAddress(DnRecord);
270 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
271 Subst["__ADMIN__"] = ReplyTo;
273 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
275 # Handle a change password email sent to the change password address
276 # (this program called with the chpass argument)
277 def HandleChPass(Reply,DnRecord,Key):
278 # Generate a random password
279 Password = GenPass();
280 Pass = HashPass(Password);
282 # Use GPG to encrypt it
283 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
288 raise Error, "Unable to generate the encrypted reply, gpg failed.";
291 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
293 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
294 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
297 Subst["__FROM__"] = ChPassFrom;
298 Subst["__EMAIL__"] = EmailAddress(DnRecord);
299 Subst["__CRYPTTYPE__"] = Type;
300 Subst["__PASSWORD__"] = Message;
301 Subst["__ADMIN__"] = ReplyTo;
302 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
304 # Connect to the ldap server
305 l = ldap.open(LDAPServer);
306 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
307 AccessPass = string.split(string.strip(F.readline())," ");
309 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
311 # Check for a locked account
312 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
313 if (string.find(GetAttr(Attrs[0],"userpassword"),"*LK*") != -1):
314 raise Error, "This account is locked";
316 # Modify the password
317 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
318 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
323 # Start of main program
325 # Drop messages from a mailer daemon.
326 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
329 ErrMsg = "Indeterminate Error";
330 ErrType = EX_TEMPFAIL;
332 # Startup the replay cache
333 ErrType = EX_TEMPFAIL;
334 ErrMsg = "Failed to initialize the replay cache:";
335 RC = ReplayCache(ReplayCacheFile);
339 ErrType = EX_PERMFAIL;
340 ErrMsg = "Failed to understand the email or find a signature:";
341 Email = mimetools.Message(sys.stdin,0);
342 Msg = GetClearSig(Email);
344 ErrMsg = "Message is not PGP signed:"
345 if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1:
346 raise Error, "No PGP signature";
348 # Check the signature
349 ErrMsg = "Unable to check the signature or the signature was invalid:";
350 Res = GPGCheckSig(Msg[0]);
356 raise Error, "Null signature text";
358 # Extract the plain message text in the event of mime encoding
360 ErrMsg = "Problem stripping MIME headers from the decoded message"
363 Index = string.index(Res[3],"\n\n") + 2;
365 Index = string.index(Res[3],"\n\r\n") + 3;
366 PlainText = Res[3][Index:];
370 # Check the signature against the replay cache
371 ErrMsg = "The replay cache rejected your message. Check your clock!";
372 Rply = RC.Check(Res[1]);
377 # Connect to the ldap server
378 ErrType = EX_TEMPFAIL;
379 ErrMsg = "An error occured while performing the LDAP lookup";
381 l = ldap.open(LDAPServer);
382 l.simple_bind_s("","");
384 # Search for the matching key fingerprint
385 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + Res[2][1]);
387 raise Error, "Key not found"
389 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
391 # Determine the sender address
392 ErrType = EX_PERMFAIL;
393 ErrMsg = "A problem occured while trying to formulate the reply";
394 Sender = Email.getheader("Reply-To");
396 Sender = Email.getheader("From");
398 raise Error, "Unable to determine the sender's address";
400 if (string.find(GetAttr(Attrs[0],"userpassword"),"*LK*") != -1):
401 raise Error, "This account is locked";
404 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
405 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
408 if sys.argv[1] == "ping":
409 Reply = HandlePing(Reply,Attrs[0],Res[2]);
410 elif sys.argv[1] == "chpass":
411 if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
412 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
413 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
414 elif sys.argv[1] == "change":
415 Reply = HandleChange(Reply,Attrs[0],Res[2]);
418 raise Error, "Incorrect Invokation";
420 # Send the message through sendmail
421 ErrMsg = "A problem occured while trying to send the reply";
422 Child = os.popen("/usr/sbin/sendmail -t","w");
423 # Child = os.popen("cat","w");
425 if Child.close() != None:
426 raise Error, "Sendmail gave a non-zero return code";
430 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
431 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
435 Subst["__ERROR__"] = ErrMsg;
436 Subst["__ADMIN__"] = ReplyTo;
438 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
439 List = traceback.extract_tb(sys.exc_traceback);
441 Trace = Trace + "Python Stack Trace:\n";
443 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
445 Subst["__TRACE__"] = Trace;
447 # Try to send the bounce
449 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
451 Child = os.popen("/usr/sbin/sendmail -t","w");
452 Child.write(ErrReplyHead);
453 Child.write(ErrReply);
454 if Child.close() != None:
455 raise Error, "Sendmail gave a non-zero return code";
457 sys.exit(EX_TEMPFAIL);
459 if ErrType != EX_PERMFAIL: