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 attrName = G[0].lower();
119 for i in ArbChanges.keys():
120 if i.lower() == attrName:
123 if ArbChanges.has_key(attrName) == 0:
126 if re.match(ArbChanges[attrName],G[1]) == None:
127 raise Error, "Item does not match the required format"+ArbChanges[attrName];
129 Attrs.append((ldap.MOD_REPLACE,attrName,G[1]));
130 return "Changed entry %s to %s"%(attrName,G[1]);
132 # Handle changing a set of arbitary fields
134 def DoDel(Str,Attrs):
135 Match = re.match("^del (.*)$",Str);
140 attrName = G[0].lower();
141 for i in DelItems.keys():
142 if i.lower() == attrName:
145 if DelItems.has_key(attrName) == 0:
146 return "Cannot erase entry %s"%(attrName);
148 Attrs.append((ldap.MOD_DELETE,attrName,None));
149 return "Removed entry %s"%(attrName);
151 # Handle a position change message, the line format is:
152 # Lat: -12412.23 Long: +12341.2342
153 def DoPosition(Str,Attrs):
154 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$",string.lower(Str));
160 sLat = LocDecode(G[0],"ns");
161 sLong = LocDecode(G[1],"ew");
162 Lat = DecDegree(sLat,1);
163 Long = DecDegree(sLong,1);
165 raise Error, "Positions were found, but they are not correctly formed";
167 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
168 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
169 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
171 # Handle an SSH authentication key, the line format is:
172 # [options] 1024 35 13188913666680[..] [comment]
173 def DoSSH(Str,Attrs):
174 Match = SSH2AuthSplit.match(Str);
180 Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
181 return "SSH Key added "+FormatSSHAuth(Str);
183 Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
185 return "SSH Keys replaced with "+FormatSSHAuth(Str);
187 # Handle changing a dns entry
188 # host in a 12.12.12.12
189 # host in cname foo.bar. <- Trailing dot is required
190 def DoDNS(Str,Attrs,DnRecord):
191 cname = re.match("^[-\w]+\s+in\s+cname\s+[-\w.]+\.$",Str,re.IGNORECASE);
192 if re.match('^[-\w]+\s+in\s+a\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',\
193 Str,re.IGNORECASE) == None and cname == None and \
194 re.match("^[-\w]+\s+in\s+mx\s+\d{1,3}\s+[-\w.]+\.$",Str,re.IGNORECASE) == None:
197 # Check if the name is already taken
198 G = re.match('^([-\w+]+)\s',Str).groups();
200 # Check for collisions
202 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"dnsZoneEntry="+G[0]+" *",["uid"]);
204 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
205 return "DNS entry is already owned by " + GetAttr(x,"uid")
211 if DNS.has_key(G[0]):
212 return "CNAME and other RR types not allowed: "+Str
216 if DNS.has_key(G[0]) and DNS[G[0]] == 2:
217 return "CNAME and other RR types not allowed: "+Str
222 Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",Str));
223 return "DNS Entry added "+Str;
225 Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",Str));
227 return "DNS Entry replaced with "+Str;
229 # Handle an [almost] arbitary change
230 def HandleChange(Reply,DnRecord,Key):
232 Lines = re.split("\n *\r?",PlainText);
238 Line = string.strip(Line);
242 # Try to process a command line
243 Result = Result + "> "+Line+"\n";
249 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
250 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
254 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
256 # Fail, if someone tries to send someone elses signed email to the
257 # daemon then we want to abort ASAP.
259 Result = Result + "Command is not understood. Halted\n";
261 Result = Result + Res + "\n";
263 # Connect to the ldap server
264 l = ldap.open(LDAPServer);
265 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
266 AccessPass = string.split(string.strip(F.readline())," ");
270 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
271 oldAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
272 if (string.find(GetAttr(oldAttrs[0],"userPassword"),"*LK*") != -1):
273 raise Error, "This account is locked";
274 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
275 l.modify_s(Dn,Attrs);
279 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
281 raise Error, "User not found"
282 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
285 Subst["__FROM__"] = ChangeFrom;
286 Subst["__EMAIL__"] = EmailAddress(DnRecord);
287 Subst["__ADMIN__"] = ReplyTo;
288 Subst["__RESULT__"] = Result;
289 Subst["__ATTR__"] = Attribs;
291 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
293 # Handle ping handles an email sent to the 'ping' address (ie this program
294 # called with a ping argument) It replies with a dump of the public records.
295 def HandlePing(Reply,DnRecord,Key):
297 Subst["__FROM__"] = PingFrom;
298 Subst["__EMAIL__"] = EmailAddress(DnRecord);
299 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
300 Subst["__ADMIN__"] = ReplyTo;
302 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
304 # Handle a change password email sent to the change password address
305 # (this program called with the chpass argument)
306 def HandleChPass(Reply,DnRecord,Key):
307 # Generate a random password
308 Password = GenPass();
309 Pass = HashPass(Password);
311 # Use GPG to encrypt it
312 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
317 raise Error, "Unable to generate the encrypted reply, gpg failed.";
320 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
322 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
323 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
326 Subst["__FROM__"] = ChPassFrom;
327 Subst["__EMAIL__"] = EmailAddress(DnRecord);
328 Subst["__CRYPTTYPE__"] = Type;
329 Subst["__PASSWORD__"] = Message;
330 Subst["__ADMIN__"] = ReplyTo;
331 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
333 # Connect to the ldap server
334 l = ldap.open(LDAPServer);
335 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
336 AccessPass = string.split(string.strip(F.readline())," ");
338 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
340 # Check for a locked account
341 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
342 if (string.find(GetAttr(Attrs[0],"userPassword"),"*LK*") != -1):
343 raise Error, "This account is locked";
345 # Modify the password
346 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
347 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
352 # Start of main program
354 # Drop messages from a mailer daemon.
355 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
358 ErrMsg = "Indeterminate Error";
359 ErrType = EX_TEMPFAIL;
361 # Startup the replay cache
362 ErrType = EX_TEMPFAIL;
363 ErrMsg = "Failed to initialize the replay cache:";
364 RC = ReplayCache(ReplayCacheFile);
368 ErrType = EX_PERMFAIL;
369 ErrMsg = "Failed to understand the email or find a signature:";
370 Email = mimetools.Message(sys.stdin,0);
371 Msg = GetClearSig(Email);
373 ErrMsg = "Message is not PGP signed:"
374 if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
375 string.find(Msg[0],"-----BEGIN PGP MESSAGE-----") == -1:
376 raise Error, "No PGP signature";
378 # Check the signature
379 ErrMsg = "Unable to check the signature or the signature was invalid:";
380 Res = GPGCheckSig(Msg[0]);
386 raise Error, "Null signature text";
388 # Extract the plain message text in the event of mime encoding
390 ErrMsg = "Problem stripping MIME headers from the decoded message"
393 Index = string.index(Res[3],"\n\n") + 2;
395 Index = string.index(Res[3],"\n\r\n") + 3;
396 PlainText = Res[3][Index:];
400 # Check the signature against the replay cache
401 ErrMsg = "The replay cache rejected your message. Check your clock!";
402 Rply = RC.Check(Res[1]);
406 # Connect to the ldap server
407 ErrType = EX_TEMPFAIL;
408 ErrMsg = "An error occured while performing the LDAP lookup";
410 l = ldap.open(LDAPServer);
411 l.simple_bind_s("","");
413 # Search for the matching key fingerprint
414 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
416 ErrType = EX_PERMFAIL;
418 raise Error, "Key not found"
420 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
424 # Determine the sender address
425 ErrMsg = "A problem occured while trying to formulate the reply";
426 Sender = Email.getheader("Reply-To");
428 Sender = Email.getheader("From");
430 raise Error, "Unable to determine the sender's address";
433 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
434 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
437 if sys.argv[1] == "ping":
438 Reply = HandlePing(Reply,Attrs[0],Res[2]);
439 elif sys.argv[1] == "chpass":
440 if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
441 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
442 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
443 elif sys.argv[1] == "change":
444 Reply = HandleChange(Reply,Attrs[0],Res[2]);
447 raise Error, "Incorrect Invokation";
449 # Send the message through sendmail
450 ErrMsg = "A problem occured while trying to send the reply";
451 Child = os.popen("/usr/sbin/sendmail -t","w");
452 # Child = os.popen("cat","w");
454 if Child.close() != None:
455 raise Error, "Sendmail gave a non-zero return code";
459 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
460 ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
464 Subst["__ERROR__"] = ErrMsg;
465 Subst["__ADMIN__"] = ReplyTo;
467 Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
468 List = traceback.extract_tb(sys.exc_traceback);
470 Trace = Trace + "Python Stack Trace:\n";
472 Trace = Trace + " %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
474 Subst["__TRACE__"] = Trace;
476 # Try to send the bounce
478 ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
480 Child = os.popen("/usr/sbin/sendmail -t","w");
481 Child.write(ErrReplyHead);
482 Child.write(ErrReply);
483 if Child.close() != None:
484 raise Error, "Sendmail gave a non-zero return code";
486 sys.exit(EX_TEMPFAIL);
488 if ErrType != EX_PERMFAIL: