3 import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, posix;
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 # Decode a GPS location from some common forms
34 def LocDecode(Str,Dir):
35 # Check for Decimal degrees, DGM, or DGMS
36 if re.match("^[+-]?[\d.]+$",Str) != None:
39 Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
41 # Check for DDDxMM.MMMM where x = [nsew]
42 Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
45 Deg = G[0]; Min = G[2]; Dr = G[1];
48 Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
51 Deg = G[0]; Dr = G[1];
53 # Check for DD:MM.MM x
54 Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
57 Deg = G[0]; Min = G[1]; Dr = G[2];
59 # Check for DD:MM:SS.SS x
60 Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
63 Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
67 raise "Failed","Bad degrees";
68 if Min != None and float(Min) > 60:
69 raise "Failed","Bad minutes";
70 if Sec != None and float(Sec) > 60:
71 raise "Failed","Bad seconds";
73 # Pad on an extra leading 0 to disambiguate small numbers
74 if len(Deg) <= 1 or Deg[1] == '.':
76 if Min != None and (len(Min) <= 1 or Min[1] == '.'):
78 if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
81 # Construct a DGM/DGMS type value from the components.
92 # Handle changing a set of arbitary fields
94 def DoArbChange(Str,Attrs):
95 Match = re.match("^([^ :]+): (.*)$",Str);
100 if ArbChanges.has_key(G[0]) == 0:
103 if re.match(ArbChanges[G[0]],G[1]) == None:
104 raise Error, "Item does not match the required format"+ArbChanges[G[0]];
106 Attrs.append((ldap.MOD_REPLACE,G[0],G[1]));
107 return "Changed entry %s to %s"%(G[0],G[1]);
109 # Handle a position change message, the line format is:
110 # Lat: -12412.23 Long: +12341.2342
111 def DoPosition(Str,Attrs):
112 Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$",string.lower(Str));
118 sLat = LocDecode(G[0],"ns");
119 sLong = LocDecode(G[1],"ew");
120 Lat = DecDegree(sLat,1);
121 Long = DecDegree(sLong,1);
123 raise Error, "Positions were found, but they are not correctly formed";
125 Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
126 Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
127 return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
129 # Handle a SSH RSA authentication key, the line format is:
130 # [options] 1024 35 13188913666680[..] [comment]
131 def DoSSH(Str,Attrs):
132 Match = SSHAuthSplit.match(Str);
138 Attrs.append((ldap.MOD_ADD,"sshrsaauthkey",Str));
139 return "SSH Key added "+FormatSSHAuth(Str);
141 Attrs.append((ldap.MOD_REPLACE,"sshrsaauthkey",Str));
143 return "SSH Keys replaced with "+FormatSSHAuth(Str);
145 # Handle changing a dns entry
146 # host in a 12.12.12.12
147 # host in cname foo.bar. <- Trailing dot is required
148 def DoDNS(Str,Attrs,DnRecord):
149 if re.match('^[\w-]+\s+in\s+a\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',\
150 Str,re.IGNORECASE) == None and \
151 re.match("^[\w-]+\s+in\s+cname\s+[\w.\-]+\.$",Str,re.IGNORECASE) == None:
154 # Check if the name is already taken
155 G = re.match('^([\w-+]+)\s',Str).groups();
157 # Check for collisions
159 Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"dnszoneentry="+G[0]+" *",["uid"]);
161 if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
162 return "DNS entry is already owned by " + GetAttr(x,"uid")
166 Attrs.append((ldap.MOD_ADD,"dnszoneentry",Str));
167 return "DNS Entry added "+Str;
169 Attrs.append((ldap.MOD_REPLACE,"dnszoneentry",Str));
171 return "DNS Entry replaced with "+Str;
173 # Handle an [almost] arbitary change
174 def HandleChange(Reply,DnRecord,Key):
176 Lines = string.split(PlainText,"\r\n");
181 Line = string.strip(Line);
185 # Try to process a command line
186 Result = Result + "> "+Line+"\n";
193 Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
194 DoArbChange(Line,Attrs) or DoSSH(Line,Attrs);
197 Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
199 # Fail, if someone tries to send someone elses signed email to the
200 # daemon then we want to abort ASAP.
202 Result = Result + "Command is not understood. Halted\n";
204 Result = Result + Res + "\n";
206 # Connect to the ldap server
207 l = ldap.open(LDAPServer);
208 F = open(PassDir+"/pass-"+pwd.getpwuid(posix.getuid())[0],"r");
209 AccessPass = string.split(string.strip(F.readline())," ");
213 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
214 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
215 l.modify_s(Dn,Attrs);
219 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
221 raise Error, "User not found"
222 Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
225 Subst["__FROM__"] = ChangeFrom;
226 Subst["__EMAIL__"] = EmailAddress(DnRecord);
227 Subst["__ADMIN__"] = ReplyTo;
228 Subst["__RESULT__"] = Result;
229 Subst["__ATTR__"] = Attribs;
231 return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
233 # Handle ping handles an email sent to the 'ping' address (ie this program
234 # called with a ping argument) It replies with a dump of the public records.
235 def HandlePing(Reply,DnRecord,Key):
237 Subst["__FROM__"] = PingFrom;
238 Subst["__EMAIL__"] = EmailAddress(DnRecord);
239 Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
240 Subst["__ADMIN__"] = ReplyTo;
242 return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
244 # Handle a change password email sent to the change password address
245 # (this program called with the chpass argument)
246 def HandleChPass(Reply,DnRecord,Key):
247 # Generate a random password
248 Password = GenPass();
249 Pass = HashPass(Password);
251 # Use GPG to encrypt it
252 Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
257 raise Error, "Unable to generate the encrypted reply, gpg failed.";
260 Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
262 Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
263 "mode, without IDEA. This message cannot be decoded using PGP 2.x";
266 Subst["__FROM__"] = ChPassFrom;
267 Subst["__EMAIL__"] = EmailAddress(DnRecord);
268 Subst["__CRYPTTYPE__"] = Type;
269 Subst["__PASSWORD__"] = Message;
270 Subst["__ADMIN__"] = ReplyTo;
271 Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
273 # Connect to the ldap server
274 l = ldap.open(LDAPServer);
275 F = open(PassDir+"/pass-"+pwd.getpwuid(posix.getuid())[0],"r");
276 AccessPass = string.split(string.strip(F.readline())," ");
279 # Modify the password
280 l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
281 Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
282 Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
287 # Start of main program
288 ErrMsg = "Indeterminate Error";
289 ErrType = EX_TEMPFAIL;
291 # Startup the replay cache
292 ErrType = EX_TEMPFAIL;
293 ErrMsg = "Failed to initialize the replay cache:";
294 RC = ReplayCache(ReplayCacheFile);
298 ErrType = EX_PERMFAIL;
299 ErrMsg = "Failed to understand the email or find a signature:";
300 Email = mimetools.Message(sys.stdin,0);
301 Msg = GetClearSig(Email);
303 # Check the signature
304 ErrMsg = "Unable to check the signature or the signature was invalid:";
305 Res = GPGCheckSig(Msg[0]);
311 raise Error, "Null signature text";
313 # Extract the plain message text in the event of mime encoding
315 ErrMsg = "Problem stripping MIME headers from the decoded message"
318 Index = string.index(Res[3],"\n\n") + 2;
320 Index = string.index(Res[3],"\n\r\n") + 3;
321 PlainText = Res[3][Index:];
325 # Check the signature against the replay cache
326 ErrMsg = "The replay cache rejected your message. Check your clock!";
327 Rply = RC.Check(Res[1]);
332 # Connect to the ldap server
333 ErrType = EX_TEMPFAIL;
334 ErrMsg = "An error occured while performing the LDAP lookup";
336 l = ldap.open(LDAPServer);
337 l.simple_bind_s("","");
339 # Search for the matching key fingerprint
340 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + Res[2][1]);
342 raise Error, "Key not found"
344 raise Error, "Oddly your key fingerprint is assigned to more than one account.."
346 # Determine the sender address
347 ErrType = EX_PERMFAIL;
348 ErrMsg = "A problem occured while trying to formulate the reply";
349 Sender = Email.getheader("Reply-To");
351 Sender = Email.getheader("From");
353 raise Error, "Unable to determine the sender's address";
356 Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
357 Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
360 if sys.argv[1] == "ping":
361 Reply = HandlePing(Reply,Attrs[0],Res[2]);
362 elif sys.argv[1] == "chpass":
363 if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
364 raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
365 Reply = HandleChPass(Reply,Attrs[0],Res[2]);
366 elif sys.argv[1] == "change":
367 Reply = HandleChange(Reply,Attrs[0],Res[2]);
370 raise Error, "Incorrect Invokation";
372 # Send the message through sendmail
373 ErrMsg = "A problem occured while trying to send the reply";
374 Child = posix.popen("/usr/sbin/sendmail -t","w");
375 # Child = posix.popen("cat","w");
377 if Child.close() != None:
378 raise Error, "Sendmail gave a non-zero return code";
382 print "==> %s: %s" %(sys.exc_type,sys.exc_value);
383 List = traceback.extract_tb(sys.exc_traceback);
387 print " %s %s:%u: %s" %(x[2],x[0],x[1],x[3]);