586dddbd2766bb435dbf165747395a5e56f5bb11
[mirror/userdir-ldap.git] / ud-mailgate
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3 import userdir_gpg, userdir_ldap, sys, traceback, time, ldap, posix;
4 import string, pwd
5 from userdir_gpg import *;
6 from userdir_ldap import *;
7
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;
14
15 EX_TEMPFAIL = 75;
16 EX_PERMFAIL = 65;      # EX_DATAERR
17 Error = 'Message Error';
18 SeenRSA = 0;
19 SeenDNS = 0;
20
21 ArbChanges = {"c": "..",
22               "l": ".*",
23               "facsimiletelephonenumber": ".*",
24               "telephonenumber": ".*",
25               "postaladdress": ".*",
26               "postalcode": ".*",
27               "loginshell": ".*",
28               "emailforward": "^([^<>@]+@.+)?$",
29               "ircnick": ".*",
30               "onvacation": ".*",
31               "labeledurl": ".*"};
32
33 DelItems = {"c": None,
34             "l": None,
35             "facsimiletelephonenumber": None,
36             "telephonenumber": None,
37             "postaladdress": None,
38             "postalcode": None,
39             "emailforward": None,
40             "ircnick": None,
41             "onvacation": None,
42             "labeledurl": None,
43             "latitude": None,
44             "longitude": None,
45             "sshrsaauthkey": None};
46
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:
51       return Str;
52
53    Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
54    
55    # Check for DDDxMM.MMMM where x = [nsew]
56    Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
57    if Match != None:
58       G = Match.groups();
59       Deg = G[0]; Min = G[2]; Dr = G[1];
60
61    # Check for DD.DD x 
62    Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
63    if Match != None:
64       G = Match.groups();
65       Deg = G[0]; Dr = G[1];
66
67    # Check for DD:MM.MM x 
68    Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
69    if Match != None:
70       G = Match.groups();
71       Deg = G[0]; Min = G[1]; Dr = G[2];
72
73    # Check for DD:MM:SS.SS x
74    Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
75    if Match != None:
76       G = Match.groups();
77       Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
78       
79    # Some simple checks
80    if float(Deg) > 180:
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";
86       
87    # Pad on an extra leading 0 to disambiguate small numbers
88    if len(Deg) <= 1 or Deg[1] == '.':
89       Deg = '0' + Deg;
90    if Min != None and (len(Min) <= 1 or Min[1] == '.'):
91       Min = '0' + Min;
92    if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
93       Sec = '0' + Sec;
94    
95    # Construct a DGM/DGMS type value from the components.
96    Res = "+"
97    if Dr == Dir[1]:
98       Res = "-";
99    Res = Res + Deg;
100    if Min != None:
101       Res = Res + Min;
102    if Sec != None:
103       Res = Res + Sec;
104    return Res;
105               
106 # Handle changing a set of arbitary fields
107 #  <field>: value
108 def DoArbChange(Str,Attrs):
109    Match = re.match("^([^ :]+): (.*)$",Str);
110    if Match == None:
111       return None;
112    G = Match.groups();
113    
114    if ArbChanges.has_key(G[0]) == 0:
115       return None;
116       
117    if re.match(ArbChanges[G[0]],G[1]) == None:
118       raise Error, "Item does not match the required format"+ArbChanges[G[0]];
119
120    Attrs.append((ldap.MOD_REPLACE,G[0],G[1]));
121    return "Changed entry %s to %s"%(G[0],G[1]);
122
123 # Handle changing a set of arbitary fields
124 #  <field>: value
125 def DoDel(Str,Attrs):
126    Match = re.match("^del (.*)$",Str);
127    if Match == None:
128       return None;
129    G = Match.groups();
130  
131    if DelItems.has_key(G[0]) == 0:
132       return "Cannot erase entry %s"%(G[0]);
133
134    Attrs.append((ldap.MOD_DELETE,G[0],None));
135    return "Removed entry %s"%(G[0]);
136
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));
141    if Match == None:
142       return None;
143
144    G = Match.groups();
145    try:
146       sLat = LocDecode(G[0],"ns");
147       sLong = LocDecode(G[1],"ew");
148       Lat = DecDegree(sLat,1);
149       Long = DecDegree(sLong,1);
150    except:
151       raise Error, "Positions were found, but they are not correctly formed";
152
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);
156
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);
161    if Match == None:
162       return None;
163    
164    global SeenRSA;
165    if SeenRSA:
166      Attrs.append((ldap.MOD_ADD,"sshrsaauthkey",Str));
167      return "SSH Key added "+FormatSSHAuth(Str);
168       
169    Attrs.append((ldap.MOD_REPLACE,"sshrsaauthkey",Str));
170    SeenRSA = 1;
171    return "SSH Keys replaced with "+FormatSSHAuth(Str);
172
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:
180      return None;     
181
182    # Check if the name is already taken
183    G = re.match('^([\w-+]+)\s',Str).groups();
184
185    # Check for collisions
186    global l;
187    Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"dnszoneentry="+G[0]+" *",["uid"]);
188    for x in Rec:
189       if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
190          return "DNS entry is already owned by " + GetAttr(x,"uid")
191
192    global SeenDNS;
193    if SeenDNS:
194      Attrs.append((ldap.MOD_ADD,"dnszoneentry",Str));
195      return "DNS Entry added "+Str;
196       
197    Attrs.append((ldap.MOD_REPLACE,"dnszoneentry",Str));
198    SeenDNS = 1;
199    return "DNS Entry replaced with "+Str;
200
201 # Handle an [almost] arbitary change
202 def HandleChange(Reply,DnRecord,Key):
203    global PlainText;
204    Lines = string.split(PlainText,"\r\n");
205
206    Result = "";
207    Attrs = [];
208    Show = 0;
209    for Line in Lines: 
210       Line = string.strip(Line);
211       if Line == "":
212          continue;
213
214       # Try to process a command line
215       Result = Result + "> "+Line+"\n";
216       try:
217          if Line == "show":
218            Show = 1;
219            Res = "OK";
220          else:
221            Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
222                  DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
223                  DoDel(Line,Attrs);
224       except:
225          Res = None;
226          Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
227          
228       # Fail, if someone tries to send someone elses signed email to the
229       # daemon then we want to abort ASAP.
230       if Res == None:
231          Result = Result + "Command is not understood. Halted\n";
232          break;
233       Result = Result + Res + "\n";
234
235    # Connect to the ldap server
236    l = ldap.open(LDAPServer);
237    F = open(PassDir+"/pass-"+pwd.getpwuid(posix.getuid())[0],"r");
238    AccessPass = string.split(string.strip(F.readline())," ");
239    F.close();
240
241    # Modify the record
242    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
243    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
244    l.modify_s(Dn,Attrs);
245
246    Attribs = "";
247    if Show == 1:
248       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
249       if len(Attrs) == 0:
250          raise Error, "User not found"
251       Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
252       
253    Subst = {};
254    Subst["__FROM__"] = ChangeFrom;
255    Subst["__EMAIL__"] = EmailAddress(DnRecord);
256    Subst["__ADMIN__"] = ReplyTo;
257    Subst["__RESULT__"] = Result;
258    Subst["__ATTR__"] = Attribs;
259
260    return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
261    
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):
265    Subst = {};
266    Subst["__FROM__"] = PingFrom;
267    Subst["__EMAIL__"] = EmailAddress(DnRecord);
268    Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
269    Subst["__ADMIN__"] = ReplyTo;
270
271    return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
272
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);
279       
280    # Use GPG to encrypt it      
281    Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
282                         "0x"+Key[1],Key[4]);
283    Password = None;
284
285    if Message == None:
286       raise Error, "Unable to generate the encrypted reply, gpg failed.";
287
288    if (Key[4] == 1):
289       Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
290    else:
291       Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
292              "mode, without IDEA. This message cannot be decoded using PGP 2.x";
293    
294    Subst = {};
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());
301    
302    # Connect to the ldap server
303    l = ldap.open(LDAPServer);
304    F = open(PassDir+"/pass-"+pwd.getpwuid(posix.getuid())[0],"r");
305    AccessPass = string.split(string.strip(F.readline())," ");
306    F.close();
307
308    # Modify the password
309    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
310    Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
311    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
312    l.modify_s(Dn,Rec);
313
314    return Reply;
315       
316 # Start of main program
317
318 # Drop messages from a mailer daemon.
319 if posix.environ.has_key('SENDER') == 0 or len(posix.environ['SENDER']) == 0:
320    sys.exit(0);
321
322 ErrMsg = "Indeterminate Error";
323 ErrType = EX_TEMPFAIL;
324 try:
325    # Startup the replay cache
326    ErrType = EX_TEMPFAIL;
327    ErrMsg = "Failed to initialize the replay cache:";
328    RC = ReplayCache(ReplayCacheFile);
329    RC.Clean();
330
331    # Get the email 
332    ErrType = EX_PERMFAIL;
333    ErrMsg = "Failed to understand the email or find a signature:";
334    Email = mimetools.Message(sys.stdin,0);
335    Msg = GetClearSig(Email);
336
337    ErrMsg = "Message is not PGP signed:"
338    if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1:
339       raise Error, "No PGP signature";
340    
341    # Check the signature
342    ErrMsg = "Unable to check the signature or the signature was invalid:";
343    Res = GPGCheckSig(Msg[0]);
344
345    if Res[0] != None:
346       raise Error, Res[0];
347       
348    if Res[3] == None:
349       raise Error, "Null signature text";
350
351    # Extract the plain message text in the event of mime encoding
352    global PlainText;
353    ErrMsg = "Problem stripping MIME headers from the decoded message"
354    if Msg[1] == 1:
355       try:
356          Index = string.index(Res[3],"\n\n") + 2;
357       except ValueError:
358          Index = string.index(Res[3],"\n\r\n") + 3;
359       PlainText = Res[3][Index:];
360    else:
361       PlainText = Res[3];   
362
363    # Check the signature against the replay cache
364    ErrMsg = "The replay cache rejected your message. Check your clock!";
365    Rply = RC.Check(Res[1]);
366    if Rply != None:
367       raise Error, Rply;
368    RC.Add(Res[1]);
369
370    # Connect to the ldap server
371    ErrType = EX_TEMPFAIL;
372    ErrMsg = "An error occured while performing the LDAP lookup";
373    global l;
374    l = ldap.open(LDAPServer);
375    l.simple_bind_s("","");
376
377    # Search for the matching key fingerprint
378    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + Res[2][1]);
379    if len(Attrs) == 0:
380       raise Error, "Key not found"
381    if len(Attrs) != 1:
382       raise Error, "Oddly your key fingerprint is assigned to more than one account.."
383
384    # Determine the sender address
385    ErrType = EX_PERMFAIL;
386    ErrMsg = "A problem occured while trying to formulate the reply";
387    Sender = Email.getheader("Reply-To");
388    if Sender == None:
389       Sender = Email.getheader("From");
390    if Sender == None:
391       raise Error, "Unable to determine the sender's address";
392
393    if (string.find(GetAttr(Attrs[0],"userPassword"),"*LK*")  != -1):
394       raise Error, "This account is locked";
395
396    # Formulate a reply
397    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
398    Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
399
400    # Dispatch
401    if sys.argv[1] == "ping":
402       Reply = HandlePing(Reply,Attrs[0],Res[2]);
403    elif sys.argv[1] == "chpass":
404       if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
405          raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
406       Reply = HandleChPass(Reply,Attrs[0],Res[2]);
407    elif sys.argv[1] == "change":
408       Reply = HandleChange(Reply,Attrs[0],Res[2]);
409    else:
410       print sys.argv;
411       raise Error, "Incorrect Invokation";
412
413    # Send the message through sendmail      
414    ErrMsg = "A problem occured while trying to send the reply";
415    Child = posix.popen("/usr/sbin/sendmail -t","w");
416 #   Child = posix.popen("cat","w");
417    Child.write(Reply);
418    if Child.close() != None:
419       raise Error, "Sendmail gave a non-zero return code";
420
421 except:
422    # Error Reply Header
423    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
424    ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (posix.environ['SENDER'],ReplyTo,Date);
425
426    # Error Body
427    Subst = {};
428    Subst["__ERROR__"] = ErrMsg;
429    Subst["__ADMIN__"] = ReplyTo;
430
431    Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
432    List = traceback.extract_tb(sys.exc_traceback);
433    if len(List) > 1:
434       Trace = Trace + "Python Stack Trace:\n";
435       for x in List:
436          Trace = Trace +  "   %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
437
438    Subst["__TRACE__"] = Trace;
439
440    # Try to send the bounce
441    try:
442       ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
443
444       Child = posix.popen("/usr/sbin/sendmail -t","w");
445       Child.write(ErrReplyHead);
446       Child.write(ErrReply);
447       if Child.close() != None:
448          raise Error, "Sendmail gave a non-zero return code";
449    except:
450       sys.exit(EX_TEMPFAIL);
451       
452    if ErrType != EX_PERMFAIL:
453       sys.exit(ErrType);
454    sys.exit(0);
455