Locked account bugfix
[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:
182      return None;     
183
184    # Check if the name is already taken
185    G = re.match('^([\w-+]+)\s',Str).groups();
186
187    # Check for collisions
188    global l;
189    Rec = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"dnszoneentry="+G[0]+" *",["uid"]);
190    for x in Rec:
191       if GetAttr(x,"uid") != GetAttr(DnRecord,"uid"):
192          return "DNS entry is already owned by " + GetAttr(x,"uid")
193
194    global SeenDNS;
195    if SeenDNS:
196      Attrs.append((ldap.MOD_ADD,"dnszoneentry",Str));
197      return "DNS Entry added "+Str;
198       
199    Attrs.append((ldap.MOD_REPLACE,"dnszoneentry",Str));
200    SeenDNS = 1;
201    return "DNS Entry replaced with "+Str;
202
203 # Handle an [almost] arbitary change
204 def HandleChange(Reply,DnRecord,Key):
205    global PlainText;
206    Lines = string.split(PlainText,"\r\n");
207
208    Result = "";
209    Attrs = [];
210    Show = 0;
211    for Line in Lines: 
212       Line = string.strip(Line);
213       if Line == "":
214          continue;
215
216       # Try to process a command line
217       Result = Result + "> "+Line+"\n";
218       try:
219          if Line == "show":
220            Show = 1;
221            Res = "OK";
222          else:
223            Res = DoPosition(Line,Attrs) or DoDNS(Line,Attrs,DnRecord) or \
224                  DoArbChange(Line,Attrs) or DoSSH(Line,Attrs) or \
225                  DoDel(Line,Attrs);
226       except:
227          Res = None;
228          Result = Result + "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
229          
230       # Fail, if someone tries to send someone elses signed email to the
231       # daemon then we want to abort ASAP.
232       if Res == None:
233          Result = Result + "Command is not understood. Halted\n";
234          break;
235       Result = Result + Res + "\n";
236
237    # Connect to the ldap server
238    l = ldap.open(LDAPServer);
239    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
240    AccessPass = string.split(string.strip(F.readline())," ");
241    F.close();
242
243    # Modify the record
244    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
245    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
246    l.modify_s(Dn,Attrs);
247
248    Attribs = "";
249    if Show == 1:
250       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
251       if len(Attrs) == 0:
252          raise Error, "User not found"
253       Attribs = GPGEncrypt(PrettyShow(Attrs[0])+"\n","0x"+Key[1],Key[4]);
254       
255    Subst = {};
256    Subst["__FROM__"] = ChangeFrom;
257    Subst["__EMAIL__"] = EmailAddress(DnRecord);
258    Subst["__ADMIN__"] = ReplyTo;
259    Subst["__RESULT__"] = Result;
260    Subst["__ATTR__"] = Attribs;
261
262    return Reply + TemplateSubst(Subst,open(TemplatesDir+"change-reply","r").read());
263    
264 # Handle ping handles an email sent to the 'ping' address (ie this program
265 # called with a ping argument) It replies with a dump of the public records.
266 def HandlePing(Reply,DnRecord,Key):
267    Subst = {};
268    Subst["__FROM__"] = PingFrom;
269    Subst["__EMAIL__"] = EmailAddress(DnRecord);
270    Subst["__LDAPFIELDS__"] = PrettyShow(DnRecord);
271    Subst["__ADMIN__"] = ReplyTo;
272
273    return Reply + TemplateSubst(Subst,open(TemplatesDir+"ping-reply","r").read());
274
275 # Handle a change password email sent to the change password address
276 # (this program called with the chpass argument)
277 def HandleChPass(Reply,DnRecord,Key):
278    # Generate a random password
279    Password = GenPass();
280    Pass = HashPass(Password);
281       
282    # Use GPG to encrypt it      
283    Message = GPGEncrypt("Your new password is '" + Password + "'\n",\
284                         "0x"+Key[1],Key[4]);
285    Password = None;
286
287    if Message == None:
288       raise Error, "Unable to generate the encrypted reply, gpg failed.";
289
290    if (Key[4] == 1):
291       Type = "Your message was encrypted using PGP 2.x\ncompatibility mode.";
292    else:
293       Type = "Your message was encrypted using GPG (OpenPGP)\ncompatibility "\
294              "mode, without IDEA. This message cannot be decoded using PGP 2.x";
295    
296    Subst = {};
297    Subst["__FROM__"] = ChPassFrom;
298    Subst["__EMAIL__"] = EmailAddress(DnRecord);
299    Subst["__CRYPTTYPE__"] = Type;
300    Subst["__PASSWORD__"] = Message;
301    Subst["__ADMIN__"] = ReplyTo;
302    Reply = Reply + TemplateSubst(Subst,open(TemplatesDir+"passwd-changed","r").read());
303    
304    # Connect to the ldap server
305    l = ldap.open(LDAPServer);
306    F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
307    AccessPass = string.split(string.strip(F.readline())," ");
308    F.close();
309    l.simple_bind_s("uid="+AccessPass[0]+","+BaseDn,AccessPass[1]);
310
311    # Check for a locked account
312    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid="+GetAttr(DnRecord,"uid"));
313    if (string.find(GetAttr(Attrs[0],"userpassword"),"*LK*")  != -1):
314       raise Error, "This account is locked";
315
316    # Modify the password
317    Rec = [(ldap.MOD_REPLACE,"userPassword","{crypt}"+Pass)];
318    Dn = "uid=" + GetAttr(DnRecord,"uid") + "," + BaseDn;
319    l.modify_s(Dn,Rec);
320
321    return Reply;
322       
323 # Start of main program
324
325 # Drop messages from a mailer daemon.
326 if os.environ.has_key('SENDER') == 0 or len(os.environ['SENDER']) == 0:
327    sys.exit(0);
328
329 ErrMsg = "Indeterminate Error";
330 ErrType = EX_TEMPFAIL;
331 try:
332    # Startup the replay cache
333    ErrType = EX_TEMPFAIL;
334    ErrMsg = "Failed to initialize the replay cache:";
335    RC = ReplayCache(ReplayCacheFile);
336    RC.Clean();
337
338    # Get the email 
339    ErrType = EX_PERMFAIL;
340    ErrMsg = "Failed to understand the email or find a signature:";
341    Email = mimetools.Message(sys.stdin,0);
342    Msg = GetClearSig(Email);
343
344    ErrMsg = "Message is not PGP signed:"
345    if string.find(Msg[0],"-----BEGIN PGP SIGNED MESSAGE-----") == -1:
346       raise Error, "No PGP signature";
347    
348    # Check the signature
349    ErrMsg = "Unable to check the signature or the signature was invalid:";
350    Res = GPGCheckSig(Msg[0]);
351
352    if Res[0] != None:
353       raise Error, Res[0];
354       
355    if Res[3] == None:
356       raise Error, "Null signature text";
357
358    # Extract the plain message text in the event of mime encoding
359    global PlainText;
360    ErrMsg = "Problem stripping MIME headers from the decoded message"
361    if Msg[1] == 1:
362       try:
363          Index = string.index(Res[3],"\n\n") + 2;
364       except ValueError:
365          Index = string.index(Res[3],"\n\r\n") + 3;
366       PlainText = Res[3][Index:];
367    else:
368       PlainText = Res[3];   
369
370    # Check the signature against the replay cache
371    ErrMsg = "The replay cache rejected your message. Check your clock!";
372    Rply = RC.Check(Res[1]);
373    if Rply != None:
374       raise Error, Rply;
375    RC.Add(Res[1]);
376
377    # Connect to the ldap server
378    ErrType = EX_TEMPFAIL;
379    ErrMsg = "An error occured while performing the LDAP lookup";
380    global l;
381    l = ldap.open(LDAPServer);
382    l.simple_bind_s("","");
383
384    # Search for the matching key fingerprint
385    Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"keyfingerprint=" + Res[2][1]);
386    if len(Attrs) == 0:
387       raise Error, "Key not found"
388    if len(Attrs) != 1:
389       raise Error, "Oddly your key fingerprint is assigned to more than one account.."
390
391    # Determine the sender address
392    ErrType = EX_PERMFAIL;
393    ErrMsg = "A problem occured while trying to formulate the reply";
394    Sender = Email.getheader("Reply-To");
395    if Sender == None:
396       Sender = Email.getheader("From");
397    if Sender == None:
398       raise Error, "Unable to determine the sender's address";
399
400    if (string.find(GetAttr(Attrs[0],"userpassword"),"*LK*")  != -1):
401       raise Error, "This account is locked";
402
403    # Formulate a reply
404    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
405    Reply = "To: %s\nReply-To: %s\nDate: %s\n" % (Sender,ReplyTo,Date);
406
407    # Dispatch
408    if sys.argv[1] == "ping":
409       Reply = HandlePing(Reply,Attrs[0],Res[2]);
410    elif sys.argv[1] == "chpass":
411       if string.find(string.strip(PlainText),"Please change my Debian password") != 0:
412          raise Error,"Please send a signed message where the first line of text is the string 'Please change my Debian password'";
413       Reply = HandleChPass(Reply,Attrs[0],Res[2]);
414    elif sys.argv[1] == "change":
415       Reply = HandleChange(Reply,Attrs[0],Res[2]);
416    else:
417       print sys.argv;
418       raise Error, "Incorrect Invokation";
419
420    # Send the message through sendmail      
421    ErrMsg = "A problem occured while trying to send the reply";
422    Child = os.popen("/usr/sbin/sendmail -t","w");
423 #   Child = os.popen("cat","w");
424    Child.write(Reply);
425    if Child.close() != None:
426       raise Error, "Sendmail gave a non-zero return code";
427
428 except:
429    # Error Reply Header
430    Date = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime(time.time()));
431    ErrReplyHead = "To: %s\nReply-To: %s\nDate: %s\n" % (os.environ['SENDER'],ReplyTo,Date);
432
433    # Error Body
434    Subst = {};
435    Subst["__ERROR__"] = ErrMsg;
436    Subst["__ADMIN__"] = ReplyTo;
437
438    Trace = "==> %s: %s\n" %(sys.exc_type,sys.exc_value);
439    List = traceback.extract_tb(sys.exc_traceback);
440    if len(List) > 1:
441       Trace = Trace + "Python Stack Trace:\n";
442       for x in List:
443          Trace = Trace +  "   %s %s:%u: %s\n" %(x[2],x[0],x[1],x[3]);
444
445    Subst["__TRACE__"] = Trace;
446
447    # Try to send the bounce
448    try:
449       ErrReply = TemplateSubst(Subst,open(TemplatesDir+"error-reply","r").read());
450
451       Child = os.popen("/usr/sbin/sendmail -t","w");
452       Child.write(ErrReplyHead);
453       Child.write(ErrReply);
454       if Child.close() != None:
455          raise Error, "Sendmail gave a non-zero return code";
456    except:
457       sys.exit(EX_TEMPFAIL);
458       
459    if ErrType != EX_PERMFAIL:
460       sys.exit(ErrType);
461    sys.exit(0);
462