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,
48 "sshrsaauthkey": None,
49 "sshdsaauthkey": None};
51 # Decode a GPS location from some common forms
52 def LocDecode(Str,Dir):
53 # Check for Decimal degrees, DGM, or DGMS
54 if re.match("^[+-]?[\d.]+$",Str) != None:
57 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
59 # Check for DDDxMM.MMMM where x = [nsew]
60 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
63 Deg = G[0]; Min = G[2]; Dr = G[1];
66 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
69 Deg = G[0]; Dr = G[1];
71 # Check for DD:MM.MM x
72 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
75 Deg = G[0]; Min = G[1]; Dr = G[2];
77 # Check for DD:MM:SS.SS x
78 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
81 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
85 raise "Failed","Bad degrees";
86 if Min != None and float(Min) > 60:
87 raise "Failed","Bad minutes";
88 if Sec != None and float(Sec) > 60:
89 raise "Failed","Bad seconds";
91 # Pad on an extra leading 0 to disambiguate small numbers
92 if len(Deg) <= 1 or Deg[1] == '.':
94 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
96 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
99 # Construct a DGM/DGMS type value from the components.
110 # Handle changing a set of arbitary fields
112 def DoArbChange(Str,Attrs):
113 Match = re.match("^([^ :]+): (.*)$",Str);
118 if ArbChanges.has_key(G[0]) == 0:
121 if re.match(ArbChanges[G[0]],G[1]) == None:
122 raise Error, "Item does not match the required format"+ArbChanges[G[0]];
124 Attrs.append((ldap.MOD_REPLACE,G[0],G[1]));
125 return "Changed entry %s to %s"%(G[0],G[1]);
127 # Handle changing a set of arbitary fields
129 def DoDel(Str,Attrs):
130 Match = re.match("^del (.*)$",Str);
135 if DelItems.has_key(G[0]) == 0:
136 return "Cannot erase entry %s"%(G[0]);
138 Attrs.append((ldap.MOD_DELETE,G[0],None));
139 return "Removed entry %s"%(G[0]);
141 # Handle a position change message, the line format is:
142 # Lat: -12412.23 Long: +12341.2342
143 def DoPosition(Str,Attrs):
144 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$",string.lower(Str));
150 sLat = LocDecode(G[0],"ns");
151 sLong = LocDecode(G[1],"ew");
152 Lat = DecDegree(sLat,1);
153 Long = DecDegree(sLong,1);
155 raise Error, "Positions were found, but they are not correctly formed";
157 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
158 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
159 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
161 # Handle a SSH RSA authentication key, the line format is:
162 # [options] 1024 35 13188913666680[..] [comment]
163 def DoSSH(Str,Attrs):
164 Match = SSHAuthSplit.match(Str);
170 Attrs.append((ldap.MOD_ADD,"sshrsaauthkey",Str));
171 return "SSH Key added "+FormatSSHAuth(Str);
173 Attrs.append((ldap.MOD_REPLACE,"sshrsaauthkey",Str));
175 return "SSH Keys replaced with "+FormatSSHAuth(Str);
177 # Handle a SSH DSA authentication key, the line format is:
178 # ssh-dss [key] [comment]
179 def DoSSH2(Str,Attrs):
180 Match = SSHDSAAuthSplit.match(Str);
186 Attrs.append((ldap.MOD_ADD,"sshdsaauthkey",Str));
187 return "SSH2 Key added "+FormatSSH2Auth(Str);
189 Attrs.append((ldap.MOD_REPLACE,"sshdsaauthkey",Str));
191 return "SSH2 Keys replaced with "+FormatSSH2Auth(Str);
193 # Handle changing a dns entry
194 # host in a 12.12.12.12
195 # host in cname foo.bar. <- Trailing dot is required
196 def DoDNS(Str,Attrs,DnRecord):
197 if re.match('^[\w-]+\s+in\s+a\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',\
198 Str,re.IGNORECASE) == None and \
199 re.match("^[\w-]+\s+in\s+cname\s+[\w.\-]+\.$",Str,re.IGNORECASE) == None and \
200 re.match("^[\w-]+\s+in\s+mx\s+\d{1,3}\s+[\w.\-]+\.$",Str,re.IGNORECASE) == None:
203 # Check if the name is already taken
204 G = re.match('^([\w-+]+)\s',Str).groups();
206 # Check for collisions
208 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"dnszoneentry="+G[0]+" *",["uid"]);
210 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
211 return "DNS entry is already owned by " + GetAttr(x,"uid")
215 Attrs.append((ldap.MOD_ADD,"dnszoneentry",Str));
216 return "DNS Entry added "+Str;
218 Attrs.append((ldap.MOD_REPLACE,"dnszoneentry",Str));
220 return "DNS Entry replaced with "+Str;
222 # Handle an [almost] arbitary change
223 def HandleChange(Reply,DnRecord,Key):
225 Lines = re.split("\n *\r?",PlainText);
231 Line = string.strip(Line);
235 # Try to process a command line
236 Result = Result + "> "+Line+"\n";
242 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
243 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
244 DoSSH2(Line,Attrs) or DoDel(Line,Attrs);
247 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
249 # Fail, if someone tries to send someone elses signed email to the
250 # daemon then we want to abort ASAP.
252 Result = Result + "Command is not understood. Halted\n";
254 Result = Result + Res + "\n";
256 # Connect to the ldap server
257 l = ldap.open(LDAPServer);
258 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
259 AccessPass = string.split(string.strip(F.readline())," ");
263 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
264 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
265 l.modify_s(Dn,Attrs);
269 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
271 raise Error, "User not found"
272 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
275 Subst["__FROM__"] = ChangeFrom;
276 Subst["__EMAIL__"] = EmailAddress(DnRecord);
277 Subst["__ADMIN__"] = ReplyTo;
278 Subst["__RESULT__"] = Result;
279 Subst["__ATTR__"] = Attribs;
281 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
283 # Handle ping handles an email sent to the 'ping' address (ie this program
284 # called with a ping argument) It replies with a dump of the public records.
285 def HandlePing(Reply,DnRecord,Key):
287 Subst["__FROM__"] = PingFrom;
288 Subst["__EMAIL__"] = EmailAddress(DnRecord);
289 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
290 Subst["__ADMIN__"] = ReplyTo;
292 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
294 # Handle a change password email sent to the change password address
295 # (this program called with the chpass argument)
296 def HandleChPass(Reply,DnRecord,Key):
297 # Generate a random password
298 Password = GenPass();
299 Pass = HashPass(Password);
301 # Use GPG to encrypt it
302 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
307 raise Error, "Unable to generate the encrypted reply, gpg failed.";
310 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
312 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
313 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
316 Subst["__FROM__"] = ChPassFrom;
317 Subst["__EMAIL__"] = EmailAddress(DnRecord);
318 Subst["__CRYPTTYPE__"] = Type;
319 Subst["__PASSWORD__"] = Message;
320 Subst["__ADMIN__"] = ReplyTo;
321 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
323 # Connect to the ldap server
324 l = ldap.open(LDAPServer);
325 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
326 AccessPass = string.split(string.strip(F.readline())," ");
328 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
330 # Check for a locked account
331 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
332 if (string.find(GetAttr(Attrs[0],"userpassword"),"*LK*") != -1):
333 raise Error, "This account is locked";
335 # Modify the password
336 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
337 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
342 # Start of main program
344 # Drop messages from a mailer daemon.
345 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
348 ErrMsg = "Indeterminate Error";
349 ErrType = EX_TEMPFAIL;
351 # Startup the replay cache
352 ErrType = EX_TEMPFAIL;
353 ErrMsg = "Failed to initialize the replay cache:";
354 RC = ReplayCache(ReplayCacheFile);
358 ErrType = EX_PERMFAIL;
359 ErrMsg = "Failed to understand the email or find a signature:";
360 Email = mimetools.Message(sys.stdin,0);
361 Msg = GetClearSig(Email);
363 ErrMsg = "Message is not PGP signed:"
364 if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1:
365 raise Error, "No PGP signature";
367 # Check the signature
368 ErrMsg = "Unable to check the signature or the signature was invalid:";
369 Res = GPGCheckSig(Msg[0]);
375 raise Error, "Null signature text";
377 # Extract the plain message text in the event of mime encoding
379 ErrMsg = "Problem stripping MIME headers from the decoded message"
382 Index = string.index(Res[3],"\n\n") + 2;
384 Index = string.index(Res[3],"\n\r\n") + 3;
385 PlainText = Res[3][Index:];
389 # Check the signature against the replay cache
390 ErrMsg = "The replay cache rejected your message. Check your clock!";
391 Rply = RC.Check(Res[1]);
396 # Connect to the ldap server
397 ErrType = EX_TEMPFAIL;
398 ErrMsg = "An error occured while performing the LDAP lookup";
400 l = ldap.open(LDAPServer);
401 l.simple_bind_s("","");
403 # Search for the matching key fingerprint
404 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + Res[2][1]);
406 raise Error, "Key not found"
408 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
410 # Determine the sender address
411 ErrType = EX_PERMFAIL;
412 ErrMsg = "A problem occured while trying to formulate the reply";
413 Sender = Email.getheader("Reply-To");
415 Sender = Email.getheader("From");
417 raise Error, "Unable to determine the sender's address";
419 if (string.find(GetAttr(Attrs[0],"userpassword"),"*LK*") != -1):
420 raise Error, "This account is locked";
423 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
424 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
427 if sys.argv[1] == "ping":
428 Reply = HandlePing(Reply,Attrs[0],Res[2]);
429 elif sys.argv[1] == "chpass":
430 if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
431 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
432 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
433 elif sys.argv[1] == "change":
434 Reply = HandleChange(Reply,Attrs[0],Res[2]);
437 raise Error, "Incorrect Invokation";
439 # Send the message through sendmail
440 ErrMsg = "A problem occured while trying to send the reply";
441 Child = os.popen("/usr/sbin/sendmail -t","w");
442 # Child = os.popen("cat","w");
444 if Child.close() != None:
445 raise Error, "Sendmail gave a non-zero return code";
449 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
450 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
454 Subst["__ERROR__"] = ErrMsg;
455 Subst["__ADMIN__"] = ReplyTo;
457 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
458 List = traceback.extract_tb(sys.exc_traceback);
460 Trace = Trace + "Python Stack Trace:\n";
462 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
464 Subst["__TRACE__"] = Trace;
466 # Try to send the bounce
468 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
470 Child = os.popen("/usr/sbin/sendmail -t","w");
471 Child.write(ErrReplyHead);
472 Child.write(ErrReply);
473 if Child.close() != None:
474 raise Error, "Sendmail gave a non-zero return code";
476 sys.exit(EX_TEMPFAIL);
478 if ErrType != EX_PERMFAIL: