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