New mail gateway and dnszoneentry
[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 # Decode a GPS location from some common forms
34 def LocDecode(Str,Dir):
35    # Check for Decimal degrees, DGM, or DGMS
36    if re.match("^[+-]?[\d.]+$",Str) != None:
37       return Str;
38
39    Deg = '0'; Min = None; Sec = None; Dr = Dir[0];
40    
41    # Check for DDDxMM.MMMM where x = [nsew]
42    Match = re.match("^(\d+)(["+Dir+"])([\d.]+)$",Str);
43    if Match != None:
44       G = Match.groups();
45       Deg = G[0]; Min = G[2]; Dr = G[1];
46
47    # Check for DD.DD x 
48    Match = re.match("^([\d.]+) ?(["+Dir+"])$",Str);
49    if Match != None:
50       G = Match.groups();
51       Deg = G[0]; Dr = G[1];
52
53    # Check for DD:MM.MM x 
54    Match = re.match("^(\d+):([\d.]+) ?(["+Dir+"])$",Str);
55    if Match != None:
56       G = Match.groups();
57       Deg = G[0]; Min = G[1]; Dr = G[2];
58
59    # Check for DD:MM:SS.SS x
60    Match = re.match("^(\d+):(\d+):([\d.]+) ?(["+Dir+"])$",Str);
61    if Match != None:
62       G = Match.groups();
63       Deg = G[0]; Min = G[1]; Sec = G[2]; Dr = G[3];
64       
65    # Some simple checks
66    if float(Deg) > 180:
67       raise "Failed","Bad degrees";
68    if Min != None and float(Min) > 60:
69       raise "Failed","Bad minutes";
70    if Sec != None and float(Sec) > 60:
71       raise "Failed","Bad seconds";
72       
73    # Pad on an extra leading 0 to disambiguate small numbers
74    if len(Deg) <= 1 or Deg[1] == '.':
75       Deg = '0' + Deg;
76    if Min != None and (len(Min) <= 1 or Min[1] == '.'):
77       Min = '0' + Min;
78    if Sec != None and (len(Sec) <= 1 or Sec[1] == '.'):
79       Sec = '0' + Sec;
80    
81    # Construct a DGM/DGMS type value from the components.
82    Res = "+"
83    if Dr == Dir[1]:
84       Res = "-";
85    Res = Res + Deg;
86    if Min != None:
87       Res = Res + Min;
88    if Sec != None:
89       Res = Res + Sec;
90    return Res;
91               
92 # Handle changing a set of arbitary fields
93 #  <field>: value
94 def DoArbChange(Str,Attrs):
95    Match = re.match("^([^ :]+): (.*)$",Str);
96    if Match == None:
97       return None;
98    G = Match.groups();
99    
100    if ArbChanges.has_key(G[0]) == 0:
101       return None;
102       
103    if re.match(ArbChanges[G[0]],G[1]) == None:
104       raise Error, "Item does not match the required format"+ArbChanges[G[0]];
105
106    Attrs.append((ldap.MOD_REPLACE,G[0],G[1]));
107    return "Changed entry %s to %s"%(G[0],G[1]);
108
109 # Handle a position change message, the line format is:
110 #  Lat: -12412.23 Long: +12341.2342
111 def DoPosition(Str,Attrs):
112    Match = re.match("^lat: ([+\-]?[\d:.ns]+(?: ?[ns])?) long: ([+\-]?[\d:.ew]+(?: ?[ew])?)$",string.lower(Str));
113    if Match == None:
114       return None;
115
116    G = Match.groups();
117    try:
118       sLat = LocDecode(G[0],"ns");
119       sLong = LocDecode(G[1],"ew");
120       Lat = DecDegree(sLat,1);
121       Long = DecDegree(sLong,1);
122    except:
123       raise Error, "Positions were found, but they are not correctly formed";
124
125    Attrs.append((ldap.MOD_REPLACE,"latitude",sLat));
126    Attrs.append((ldap.MOD_REPLACE,"longitude",sLong));
127    return "Position set to %s/%s (%s/%s decimal degrees)"%(sLat,sLong,Lat,Long);
128
129 # Handle a SSH RSA authentication key, the line format is:
130 #  [options] 1024 35 13188913666680[..] [comment]
131 def DoSSH(Str,Attrs):
132    Match = SSHAuthSplit.match(Str);
133    if Match == None:
134       return None;
135    
136    global SeenRSA;
137    if SeenRSA:
138      Attrs.append((ldap.MOD_ADD,"sshrsaauthkey",Str));
139      return "SSH Key added "+FormatSSHAuth(Str);
140       
141    Attrs.append((ldap.MOD_REPLACE,"sshrsaauthkey",Str));
142    SeenRSA = 1;
143    return "SSH Keys replaced with "+FormatSSHAuth(Str);
144
145 # Handle changing a dns entry
146 #  host in a 12.12.12.12
147 #  host in cname foo.bar.    <- Trailing dot is required
148 def DoDNS(Str,Attrs,DnRecord):
149    if re.match('^[\w-]+\s+in\s+a\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$',\
150         Str,re.IGNORECASE) == None and \
151       re.match("^[\w-]+\s+in\s+cname\s+[\w.\-]+\.$",Str,re.IGNORECASE) == None:
152      return None;     
153
154    # Check if the name is already taken
155    G = re.match('^([\w-+]+)\s',Str).groups();
156
157    # Check for collisions
158    global l;
159    Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"dnszoneentry="+G[0]+" *",["uid"]);
160    for x in Rec:
161       if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
162          return "DNS entry is already owned by " + GetAttr(x,"uid")
163
164    global SeenDNS;
165    if SeenDNS:
166      Attrs.append((ldap.MOD_ADD,"dnszoneentry",Str));
167      return "DNS Entry added "+Str;
168       
169    Attrs.append((ldap.MOD_REPLACE,"dnszoneentry",Str));
170    SeenDNS = 1;
171    return "DNS Entry replaced with "+Str;
172
173 # Handle an [almost] arbitary change
174 def HandleChange(Reply,DnRecord,Key):
175    global PlainText;
176    Lines = string.split(PlainText,"\r\n");
177
178    Result = "";
179    Attrs = [];
180    for Line in Lines: 
181       Line = string.strip(Line);
182       if Line == "":
183          continue;
184
185       # Try to process a command line
186       Result = Result + "> "+Line+"\n";
187       Show = 0;
188       try:
189          if Line == "show":
190            Show = 1;
191            Res = "OK";
192          else:
193             Res = DoPosition(Line,Attrs) or DoSSH(Line,Attrs) or \
194                   DoDNS(Line,Attrs,DnRecord) or DoArbChange(Line,Attrs);
195       except:
196          Res = None;
197          Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
198          
199       # Fail, if someone tries to send someone elses signed email to the
200       # daemon then we want to abort ASAP.
201       if Res == None:
202          Result = Result + "Command is not understood. Halted\n";
203          break;
204       Result = Result + Res + "\n";
205
206    # Connect to the ldap server
207    l = ldap.open(LDAPServer);
208    F = open(PassDir+"/pass-"+pwd.getpwuid(posix.getuid())[0],"r");
209    AccessPass = string.split(string.strip(F.readline())," ");
210    F.close();
211
212    # Modify the record
213    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
214    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
215    l.modify_s(Dn,Attrs);
216
217    Attribs = "";
218    if Show == 1:
219       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
220       if len(Attrs) == 0:
221          raise Error, "User not found"
222       Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
223       
224    Subst = {};
225    Subst["__FROM__"] = ChangeFrom;
226    Subst["__EMAIL__"] = EmailAddress(DnRecord);
227    Subst["__ADMIN__"] = ReplyTo;
228    Subst["__RESULT__"] = Result;
229    Subst["__ATTR__"] = Attribs;
230
231    return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
232    
233 # Handle ping handles an email sent to the 'ping' address (ie this program
234 # called with a ping argument) It replies with a dump of the public records.
235 def HandlePing(Reply,DnRecord,Key):
236    Subst = {};
237    Subst["__FROM__"] = PingFrom;
238    Subst["__EMAIL__"] = EmailAddress(DnRecord);
239    Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
240    Subst["__ADMIN__"] = ReplyTo;
241
242    return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
243
244 # Handle a change password email sent to the change password address
245 # (this program called with the chpass argument)
246 def HandleChPass(Reply,DnRecord,Key):
247    # Generate a random password
248    Password = GenPass();
249    Pass = HashPass(Password);
250       
251    # Use GPG to encrypt it      
252    Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
253                         "0x"+Key[1],Key[4]);
254    Password = None;
255
256    if Message == None:
257       raise Error, "Unable to generate the encrypted reply, gpg failed.";
258
259    if (Key[4] == 1):
260       Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
261    else:
262       Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
263              "mode, without IDEA. This message cannot be decoded using PGP 2.x";
264    
265    Subst = {};
266    Subst["__FROM__"] = ChPassFrom;
267    Subst["__EMAIL__"] = EmailAddress(DnRecord);
268    Subst["__CRYPTTYPE__"] = Type;
269    Subst["__PASSWORD__"] = Message;
270    Subst["__ADMIN__"] = ReplyTo;
271    Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
272    
273    # Connect to the ldap server
274    l = ldap.open(LDAPServer);
275    F = open(PassDir+"/pass-"+pwd.getpwuid(posix.getuid())[0],"r");
276    AccessPass = string.split(string.strip(F.readline())," ");
277    F.close();
278
279    # Modify the password
280    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
281    Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
282    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
283    l.modify_s(Dn,Rec);
284
285    return Reply;
286       
287 # Start of main program
288 ErrMsg = "Indeterminate Error";
289 ErrType = EX_TEMPFAIL;
290 try:
291    # Startup the replay cache
292    ErrType = EX_TEMPFAIL;
293    ErrMsg = "Failed to initialize the replay cache:";
294    RC = ReplayCache(ReplayCacheFile);
295    RC.Clean();
296
297    # Get the email 
298    ErrType = EX_PERMFAIL;
299    ErrMsg = "Failed to understand the email or find a signature:";
300    Email = mimetools.Message(sys.stdin,0);
301    Msg = GetClearSig(Email);
302
303    # Check the signature   
304    ErrMsg = "Unable to check the signature or the signature was invalid:";
305    Res = GPGCheckSig(Msg[0]);
306
307    if Res[0] != None:
308       raise Error, Res[0];
309       
310    if Res[3] == None:
311       raise Error, "Null signature text";
312
313    # Extract the plain message text in the event of mime encoding
314    global PlainText;
315    ErrMsg = "Problem stripping MIME headers from the decoded message"
316    if Msg[1] == 1:
317       try:
318          Index = string.index(Res[3],"\n\n") + 2;
319       except ValueError:
320          Index = string.index(Res[3],"\n\r\n") + 3;
321       PlainText = Res[3][Index:];
322    else:
323       PlainText = Res[3];   
324
325    # Check the signature against the replay cache
326    ErrMsg = "The replay cache rejected your message. Check your clock!";
327    Rply = RC.Check(Res[1]);
328    if Rply != None:
329       raise Error, Rply;
330    RC.Add(Res[1]);
331
332    # Connect to the ldap server
333    ErrType = EX_TEMPFAIL;
334    ErrMsg = "An error occured while performing the LDAP lookup";
335    global l;
336    l = ldap.open(LDAPServer);
337    l.simple_bind_s("","");
338
339    # Search for the matching key fingerprint
340    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + Res[2][1]);
341    if len(Attrs) == 0:
342       raise Error, "Key not found"
343    if len(Attrs) != 1:
344       raise Error, "Oddly your key fingerprint is assigned to more than one account.."
345
346    # Determine the sender address
347    ErrType = EX_PERMFAIL;
348    ErrMsg = "A problem occured while trying to formulate the reply";
349    Sender = Email.getheader("Reply-To");
350    if Sender == None:
351       Sender = Email.getheader("From");
352    if Sender == None:
353       raise Error, "Unable to determine the sender's address";
354
355    # Formulate a reply
356    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
357    Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
358
359    # Dispatch
360    if sys.argv[1] == "ping":
361       Reply = HandlePing(Reply,Attrs[0],Res[2]);
362    elif sys.argv[1] == "chpass":
363       if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
364          raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
365       Reply = HandleChPass(Reply,Attrs[0],Res[2]);
366    elif sys.argv[1] == "change":
367       Reply = HandleChange(Reply,Attrs[0],Res[2]);
368    else:
369       print sys.argv;
370       raise Error, "Incorrect Invokation";
371
372    # Send the message through sendmail      
373    ErrMsg = "A problem occured while trying to send the reply";
374    Child = posix.popen("/usr/sbin/sendmail -t","w");
375 #   Child = posix.popen("cat","w");
376    Child.write(Reply);
377    if Child.close() != None:
378       raise Error, "Sendmail gave a non-zero return code";
379
380 except:
381    print ErrMsg;
382    print "==> %s: %s" %(sys.exc_type,sys.exc_value);
383    List = traceback.extract_tb(sys.exc_traceback);
384    if len(List) > 1:
385       print "Trace: ";
386       for x in List:
387          print "   %s %s:%u: %s" %(x[2],x[0],x[1],x[3]);
388    sys.exit(ErrType);
389