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