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": "^([^<>@]+@.+)?$",
33 DelItems = {"c": None,
35 "facsimiletelephonenumber": None,
36 "telephonenumber": None,
37 "postaladdress": None,
45 "sshrsaauthkey": None};
47 # Decode a GPS location from some common forms
48 def LocDecode(Str,Dir):
49 # Check for Decimal degrees, DGM, or DGMS
50 if re.match("^[+-]?[\d.]+$",Str) != None:
53 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
55 # Check for DDDxMM.MMMM where x = [nsew]
56 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
59 Deg = G[0]; Min = G[2]; Dr = G[1];
62 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
65 Deg = G[0]; Dr = G[1];
67 # Check for DD:MM.MM x
68 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
71 Deg = G[0]; Min = G[1]; Dr = G[2];
73 # Check for DD:MM:SS.SS x
74 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
77 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
81 raise "Failed","Bad degrees";
82 if Min != None and float(Min) > 60:
83 raise "Failed","Bad minutes";
84 if Sec != None and float(Sec) > 60:
85 raise "Failed","Bad seconds";
87 # Pad on an extra leading 0 to disambiguate small numbers
88 if len(Deg) <= 1 or Deg[1] == '.':
90 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
92 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
95 # Construct a DGM/DGMS type value from the components.
106 # Handle changing a set of arbitary fields
108 def DoArbChange(Str,Attrs):
109 Match = re.match("^([^ :]+): (.*)$",Str);
114 if ArbChanges.has_key(G[0]) == 0:
117 if re.match(ArbChanges[G[0]],G[1]) == None:
118 raise Error, "Item does not match the required format"+ArbChanges[G[0]];
120 Attrs.append((ldap.MOD_REPLACE,G[0],G[1]));
121 return "Changed entry %s to %s"%(G[0],G[1]);
123 # Handle changing a set of arbitary fields
125 def DoDel(Str,Attrs):
126 Match = re.match("^del (.*)$",Str);
131 if DelItems.has_key(G[0]) == 0:
132 return "Cannot erase entry %s"%(G[0]);
134 Attrs.append((ldap.MOD_DELETE,G[0],None));
135 return "Removed entry %s"%(G[0]);
137 # Handle a position change message, the line format is:
138 # Lat: -12412.23 Long: +12341.2342
139 def DoPosition(Str,Attrs):
140 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$",string.lower(Str));
146 sLat = LocDecode(G[0],"ns");
147 sLong = LocDecode(G[1],"ew");
148 Lat = DecDegree(sLat,1);
149 Long = DecDegree(sLong,1);
151 raise Error, "Positions were found, but they are not correctly formed";
153 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
154 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
155 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
157 # Handle a SSH RSA authentication key, the line format is:
158 # [options] 1024 35 13188913666680[..] [comment]
159 def DoSSH(Str,Attrs):
160 Match = SSHAuthSplit.match(Str);
166 Attrs.append((ldap.MOD_ADD,"sshrsaauthkey",Str));
167 return "SSH Key added "+FormatSSHAuth(Str);
169 Attrs.append((ldap.MOD_REPLACE,"sshrsaauthkey",Str));
171 return "SSH Keys replaced with "+FormatSSHAuth(Str);
173 # Handle changing a dns entry
174 # host in a 12.12.12.12
175 # host in cname foo.bar. <- Trailing dot is required
176 def DoDNS(Str,Attrs,DnRecord):
177 if re.match('^[\w-]+\s+in\s+a\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',\
178 Str,re.IGNORECASE) == None and \
179 re.match("^[\w-]+\s+in\s+cname\s+[\w.\-]+\.$",Str,re.IGNORECASE) == None:
182 # Check if the name is already taken
183 G = re.match('^([\w-+]+)\s',Str).groups();
185 # Check for collisions
187 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"dnszoneentry="+G[0]+" *",["uid"]);
189 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
190 return "DNS entry is already owned by " + GetAttr(x,"uid")
194 Attrs.append((ldap.MOD_ADD,"dnszoneentry",Str));
195 return "DNS Entry added "+Str;
197 Attrs.append((ldap.MOD_REPLACE,"dnszoneentry",Str));
199 return "DNS Entry replaced with "+Str;
201 # Handle an [almost] arbitary change
202 def HandleChange(Reply,DnRecord,Key):
204 Lines = string.split(PlainText,"\r\n");
210 Line = string.strip(Line);
214 # Try to process a command line
215 Result = Result + "> "+Line+"\n";
221 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
222 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
226 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
228 # Fail, if someone tries to send someone elses signed email to the
229 # daemon then we want to abort ASAP.
231 Result = Result + "Command is not understood. Halted\n";
233 Result = Result + Res + "\n";
235 # Connect to the ldap server
236 l = ldap.open(LDAPServer);
237 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
238 AccessPass = string.split(string.strip(F.readline())," ");
242 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
243 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
244 l.modify_s(Dn,Attrs);
248 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
250 raise Error, "User not found"
251 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
254 Subst["__FROM__"] = ChangeFrom;
255 Subst["__EMAIL__"] = EmailAddress(DnRecord);
256 Subst["__ADMIN__"] = ReplyTo;
257 Subst["__RESULT__"] = Result;
258 Subst["__ATTR__"] = Attribs;
260 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
262 # Handle ping handles an email sent to the 'ping' address (ie this program
263 # called with a ping argument) It replies with a dump of the public records.
264 def HandlePing(Reply,DnRecord,Key):
266 Subst["__FROM__"] = PingFrom;
267 Subst["__EMAIL__"] = EmailAddress(DnRecord);
268 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
269 Subst["__ADMIN__"] = ReplyTo;
271 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
273 # Handle a change password email sent to the change password address
274 # (this program called with the chpass argument)
275 def HandleChPass(Reply,DnRecord,Key):
276 # Generate a random password
277 Password = GenPass();
278 Pass = HashPass(Password);
280 # Use GPG to encrypt it
281 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
286 raise Error, "Unable to generate the encrypted reply, gpg failed.";
289 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
291 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
292 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
295 Subst["__FROM__"] = ChPassFrom;
296 Subst["__EMAIL__"] = EmailAddress(DnRecord);
297 Subst["__CRYPTTYPE__"] = Type;
298 Subst["__PASSWORD__"] = Message;
299 Subst["__ADMIN__"] = ReplyTo;
300 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
302 # Connect to the ldap server
303 l = ldap.open(LDAPServer);
304 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
305 AccessPass = string.split(string.strip(F.readline())," ");
307 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
309 # Check for a locked account
310 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
311 if (string.find(GetAttr(Attrs[0],"userPassword"),"*LK*") != -1):
312 raise Error, "This account is locked";
314 # Modify the password
315 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
316 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
321 # Start of main program
323 # Drop messages from a mailer daemon.
324 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
327 ErrMsg = "Indeterminate Error";
328 ErrType = EX_TEMPFAIL;
330 # Startup the replay cache
331 ErrType = EX_TEMPFAIL;
332 ErrMsg = "Failed to initialize the replay cache:";
333 RC = ReplayCache(ReplayCacheFile);
337 ErrType = EX_PERMFAIL;
338 ErrMsg = "Failed to understand the email or find a signature:";
339 Email = mimetools.Message(sys.stdin,0);
340 Msg = GetClearSig(Email);
342 ErrMsg = "Message is not PGP signed:"
343 if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1:
344 raise Error, "No PGP signature";
346 # Check the signature
347 ErrMsg = "Unable to check the signature or the signature was invalid:";
348 Res = GPGCheckSig(Msg[0]);
354 raise Error, "Null signature text";
356 # Extract the plain message text in the event of mime encoding
358 ErrMsg = "Problem stripping MIME headers from the decoded message"
361 Index = string.index(Res[3],"\n\n") + 2;
363 Index = string.index(Res[3],"\n\r\n") + 3;
364 PlainText = Res[3][Index:];
368 # Check the signature against the replay cache
369 ErrMsg = "The replay cache rejected your message. Check your clock!";
370 Rply = RC.Check(Res[1]);
375 # Connect to the ldap server
376 ErrType = EX_TEMPFAIL;
377 ErrMsg = "An error occured while performing the LDAP lookup";
379 l = ldap.open(LDAPServer);
380 l.simple_bind_s("","");
382 # Search for the matching key fingerprint
383 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + Res[2][1]);
385 raise Error, "Key not found"
387 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
389 # Determine the sender address
390 ErrType = EX_PERMFAIL;
391 ErrMsg = "A problem occured while trying to formulate the reply";
392 Sender = Email.getheader("Reply-To");
394 Sender = Email.getheader("From");
396 raise Error, "Unable to determine the sender's address";
398 if (string.find(GetAttr(Attrs[0],"userPassword"),"*LK*") != -1):
399 raise Error, "This account is locked";
402 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
403 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
406 if sys.argv[1] == "ping":
407 Reply = HandlePing(Reply,Attrs[0],Res[2]);
408 elif sys.argv[1] == "chpass":
409 if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
410 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
411 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
412 elif sys.argv[1] == "change":
413 Reply = HandleChange(Reply,Attrs[0],Res[2]);
416 raise Error, "Incorrect Invokation";
418 # Send the message through sendmail
419 ErrMsg = "A problem occured while trying to send the reply";
420 Child = os.popen("/usr/sbin/sendmail -t","w");
421 # Child = os.popen("cat","w");
423 if Child.close() != None:
424 raise Error, "Sendmail gave a non-zero return code";
428 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
429 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
433 Subst["__ERROR__"] = ErrMsg;
434 Subst["__ADMIN__"] = ReplyTo;
436 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
437 List = traceback.extract_tb(sys.exc_traceback);
439 Trace = Trace + "Python Stack Trace:\n";
441 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
443 Subst["__TRACE__"] = Trace;
445 # Try to send the bounce
447 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
449 Child = os.popen("/usr/sbin/sendmail -t","w");
450 Child.write(ErrReplyHead);
451 Child.write(ErrReply);
452 if Child.close() != None:
453 raise Error, "Sendmail gave a non-zero return code";
455 sys.exit(EX_TEMPFAIL);
457 if ErrType != EX_PERMFAIL: