Update from samosa: Only use SSH2AuthSplit.match(), maybe it's superior?
[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    if ArbChanges.has_key(G[0]) == 0:
119       return None;
120       
121    if re.match(ArbChanges[G[0]],G[1]) == None:
122       raise Error, "Item does not match the required format"+ArbChanges[G[0]];
123
124    Attrs.append((ldap.MOD_REPLACE,G[0],G[1]));
125    return "Changed entry %s to %s"%(G[0],G[1]);
126
127 # Handle changing a set of arbitary fields
128 #  <field>: value
129 def DoDel(Str,Attrs):
130    Match = re.match("^del (.*)$",Str);
131    if Match == None:
132       return None;
133    G = Match.groups();
134  
135    if DelItems.has_key(G[0]) == 0:
136       return "Cannot erase entry %s"%(G[0]);
137
138    Attrs.append((ldap.MOD_DELETE,G[0],None));
139    return "Removed entry %s"%(G[0]);
140
141 # Handle a position change message, the line format is:
142 #  Lat: -12412.23 Long: +12341.2342
143 def DoPosition(Str,Attrs):
144    Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$",string.lower(Str));
145    if Match == None:
146       return None;
147
148    G = Match.groups();
149    try:
150       sLat = LocDecode(G[0],"ns");
151       sLong = LocDecode(G[1],"ew");
152       Lat = DecDegree(sLat,1);
153       Long = DecDegree(sLong,1);
154    except:
155       raise Error, "Positions were found, but they are not correctly formed";
156
157    Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
158    Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
159    return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
160
161 # Handle an SSH authentication key, the line format is:
162 #  [options] 1024 35 13188913666680[..] [comment]
163 def DoSSH(Str,Attrs):
164    Match = SSH2AuthSplit.match(Str);
165    if Match == None:
166       return None;
167    
168    global SeenKey;
169    if SeenKey:
170      Attrs.append((ldap.MOD_ADD,"sshRSAAuthKey",Str));
171      return "SSH Key added "+FormatSSHAuth(Str);
172       
173    Attrs.append((ldap.MOD_REPLACE,"sshRSAAuthKey",Str));
174    SeenKey = 1;
175    return "SSH Keys replaced with "+FormatSSHAuth(Str);
176
177 # Handle changing a dns entry
178 #  host in a 12.12.12.12
179 #  host in cname foo.bar.    <- Trailing dot is required
180 def DoDNS(Str,Attrs,DnRecord):
181    cname = re.match("^[-\w]+\s+in\s+cname\s+[-\w.]+\.$",Str,re.IGNORECASE);
182    if re.match('^[-\w]+\s+in\s+a\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',\
183         Str,re.IGNORECASE) == None and cname == None and \
184       re.match("^[-\w]+\s+in\s+mx\s+\d{1,3}\s+[-\w.]+\.$",Str,re.IGNORECASE) == None:
185      return None;     
186
187    # Check if the name is already taken
188    G = re.match('^([-\w+]+)\s',Str).groups();
189
190    # Check for collisions
191    global l;
192    Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"dnsZoneEntry="+G[0]+" *",["uid"]);
193    for x in Rec:
194       if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
195          return "DNS entry is already owned by " + GetAttr(x,"uid")
196
197    global SeenDNS;
198    global DNS;
199
200    if cname:
201      if DNS.has_key(G[0]):
202        return "CNAME and other RR types not allowed: "+Str
203      else:
204        DNS[G[0]] = 2
205    else:
206      if DNS.has_key(G[0]) and DNS[G[0]] == 2:
207        return "CNAME and other RR types not allowed: "+Str
208      else:
209        DNS[G[0]] = 1
210      
211    if SeenDNS:
212      Attrs.append((ldap.MOD_ADD,"dnsZoneEntry",Str));
213      return "DNS Entry added "+Str;
214       
215    Attrs.append((ldap.MOD_REPLACE,"dnsZoneEntry",Str));
216    SeenDNS = 1;
217    return "DNS Entry replaced with "+Str;
218
219 # Handle an [almost] arbitary change
220 def HandleChange(Reply,DnRecord,Key):
221    global PlainText;
222    Lines = re.split("\n *\r?",PlainText);
223
224    Result = "";
225    Attrs = [];
226    Show = 0;
227    for Line in Lines: 
228       Line = string.strip(Line);
229       if Line == "":
230          continue;
231
232       # Try to process a command line
233       Result = Result + "> "+Line+"\n";
234       try:
235          if Line == "show":
236            Show = 1;
237            Res = "OK";
238          else:
239            Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
240                  DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
241                  DoDel(Line,Attrs);
242       except:
243          Res = None;
244          Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
245          
246       # Fail, if someone tries to send someone elses signed email to the
247       # daemon then we want to abort ASAP.
248       if Res == None:
249          Result = Result + "Command is not understood. Halted\n";
250          break;
251       Result = Result + Res + "\n";
252
253    # Connect to the ldap server
254    l = ldap.open(LDAPServer);
255    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
256    AccessPass = string.split(string.strip(F.readline())," ");
257    F.close();
258
259    # Modify the record
260    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
261    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
262    l.modify_s(Dn,Attrs);
263
264    Attribs = "";
265    if Show == 1:
266       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
267       if len(Attrs) == 0:
268          raise Error, "User not found"
269       Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
270       
271    Subst = {};
272    Subst["__FROM__"] = ChangeFrom;
273    Subst["__EMAIL__"] = EmailAddress(DnRecord);
274    Subst["__ADMIN__"] = ReplyTo;
275    Subst["__RESULT__"] = Result;
276    Subst["__ATTR__"] = Attribs;
277
278    return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
279    
280 # Handle ping handles an email sent to the 'ping' address (ie this program
281 # called with a ping argument) It replies with a dump of the public records.
282 def HandlePing(Reply,DnRecord,Key):
283    Subst = {};
284    Subst["__FROM__"] = PingFrom;
285    Subst["__EMAIL__"] = EmailAddress(DnRecord);
286    Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
287    Subst["__ADMIN__"] = ReplyTo;
288
289    return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
290
291 # Handle a change password email sent to the change password address
292 # (this program called with the chpass argument)
293 def HandleChPass(Reply,DnRecord,Key):
294    # Generate a random password
295    Password = GenPass();
296    Pass = HashPass(Password);
297       
298    # Use GPG to encrypt it      
299    Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
300                         "0x"+Key[1],Key[4]);
301    Password = None;
302
303    if Message == None:
304       raise Error, "Unable to generate the encrypted reply, gpg failed.";
305
306    if (Key[4] == 1):
307       Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
308    else:
309       Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
310              "mode, without IDEA. This message cannot be decoded using PGP 2.x";
311    
312    Subst = {};
313    Subst["__FROM__"] = ChPassFrom;
314    Subst["__EMAIL__"] = EmailAddress(DnRecord);
315    Subst["__CRYPTTYPE__"] = Type;
316    Subst["__PASSWORD__"] = Message;
317    Subst["__ADMIN__"] = ReplyTo;
318    Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
319    
320    # Connect to the ldap server
321    l = ldap.open(LDAPServer);
322    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
323    AccessPass = string.split(string.strip(F.readline())," ");
324    F.close();
325    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
326
327    # Check for a locked account
328    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
329    if (string.find(GetAttr(Attrs[0],"userPassword"),"*LK*")  != -1):
330       raise Error, "This account is locked";
331
332    # Modify the password
333    Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
334    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
335    l.modify_s(Dn,Rec);
336
337    return Reply;
338       
339 # Start of main program
340
341 # Drop messages from a mailer daemon.
342 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
343    sys.exit(0);
344
345 ErrMsg = "Indeterminate Error";
346 ErrType = EX_TEMPFAIL;
347 try:
348    # Startup the replay cache
349    ErrType = EX_TEMPFAIL;
350    ErrMsg = "Failed to initialize the replay cache:";
351    RC = ReplayCache(ReplayCacheFile);
352    RC.Clean();
353
354    # Get the email 
355    ErrType = EX_PERMFAIL;
356    ErrMsg = "Failed to understand the email or find a signature:";
357    Email = mimetools.Message(sys.stdin,0);
358    Msg = GetClearSig(Email);
359
360    ErrMsg = "Message is not PGP signed:"
361    if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1 and \
362       string.find(Msg[0],"-----BEGIN PGP MESSAGE-----") == -1:
363       raise Error, "No PGP signature";
364    
365    # Check the signature
366    ErrMsg = "Unable to check the signature or the signature was invalid:";
367    Res = GPGCheckSig(Msg[0]);
368
369    if Res[0] != None:
370       raise Error, Res[0];
371       
372    if Res[3] == None:
373       raise Error, "Null signature text";
374
375    # Extract the plain message text in the event of mime encoding
376    global PlainText;
377    ErrMsg = "Problem stripping MIME headers from the decoded message"
378    if Msg[1] == 1:
379       try:
380          Index = string.index(Res[3],"\n\n") + 2;
381       except ValueError:
382          Index = string.index(Res[3],"\n\r\n") + 3;
383       PlainText = Res[3][Index:];
384    else:
385       PlainText = Res[3];   
386
387    # Check the signature against the replay cache
388    ErrMsg = "The replay cache rejected your message. Check your clock!";
389    Rply = RC.Check(Res[1]);
390    if Rply != None:
391       raise Error, Rply;
392    RC.Add(Res[1]);
393
394    # Connect to the ldap server
395    ErrType = EX_TEMPFAIL;
396    ErrMsg = "An error occured while performing the LDAP lookup";
397    global l;
398    l = ldap.open(LDAPServer);
399    l.simple_bind_s("","");
400
401    # Search for the matching key fingerprint
402    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyFingerPrint=" + Res[2][1]);
403    if len(Attrs) == 0:
404       raise Error, "Key not found"
405    if len(Attrs) != 1:
406       raise Error, "Oddly your key fingerprint is assigned to more than one account.."
407
408    # Determine the sender address
409    ErrType = EX_PERMFAIL;
410    ErrMsg = "A problem occured while trying to formulate the reply";
411    Sender = Email.getheader("Reply-To");
412    if Sender == None:
413       Sender = Email.getheader("From");
414    if Sender == None:
415       raise Error, "Unable to determine the sender's address";
416
417    if (string.find(GetAttr(Attrs[0],"userPassword"),"*LK*")  != -1):
418       raise Error, "This account is locked";
419
420    # Formulate a reply
421    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
422    Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
423
424    # Dispatch
425    if sys.argv[1] == "ping":
426       Reply = HandlePing(Reply,Attrs[0],Res[2]);
427    elif sys.argv[1] == "chpass":
428       if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
429          raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
430       Reply = HandleChPass(Reply,Attrs[0],Res[2]);
431    elif sys.argv[1] == "change":
432       Reply = HandleChange(Reply,Attrs[0],Res[2]);
433    else:
434       print sys.argv;
435       raise Error, "Incorrect Invokation";
436
437    # Send the message through sendmail      
438    ErrMsg = "A problem occured while trying to send the reply";
439    Child = os.popen("/usr/sbin/sendmail -t","w");
440 #   Child = os.popen("cat","w");
441    Child.write(Reply);
442    if Child.close() != None:
443       raise Error, "Sendmail gave a non-zero return code";
444
445 except:
446    # Error Reply Header
447    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
448    ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
449
450    # Error Body
451    Subst = {};
452    Subst["__ERROR__"] = ErrMsg;
453    Subst["__ADMIN__"] = ReplyTo;
454
455    Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
456    List = traceback.extract_tb(sys.exc_traceback);
457    if len(List) > 1:
458       Trace = Trace + "Python Stack Trace:\n";
459       for x in List:
460          Trace = Trace +  "   %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
461
462    Subst["__TRACE__"] = Trace;
463
464    # Try to send the bounce
465    try:
466       ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
467
468       Child = os.popen("/usr/sbin/sendmail -t","w");
469       Child.write(ErrReplyHead);
470       Child.write(ErrReply);
471       if Child.close() != None:
472          raise Error, "Sendmail gave a non-zero return code";
473    except:
474       sys.exit(EX_TEMPFAIL);
475       
476    if ErrType != EX_PERMFAIL:
477       sys.exit(ErrType);
478    sys.exit(0);
479