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