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