Do SSL when connecting to the ldap server.
[mirror/userdir-ldap.git] / userdir_ldap.py
1 #   Copyright (c) 1999-2000  Jason Gunthorpe <jgg@debian.org>
2 #   Copyright (c) 2001-2003  Ryan Murray <rmurray@debian.org>
3 #   Copyright (c) 2004-2005  Joey Schulze <joey@infodrom.org>
4 #
5 #   This program is free software; you can redistribute it and/or modify
6 #   it under the terms of the GNU General Public License as published by
7 #   the Free Software Foundation; either version 2 of the License, or
8 #   (at your option) any later version.
9 #
10 #   This program is distributed in the hope that it will be useful,
11 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
12 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13 #   GNU General Public License for more details.
14 #
15 #   You should have received a copy of the GNU General Public License
16 #   along with this program; if not, write to the Free Software
17 #   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
18
19 # Some routines and configuration that are used by the ldap progams
20 import termios, re, imp, ldap, sys, crypt, rfc822;
21 import userdir_gpg
22
23 try:
24    File = open("/etc/userdir-ldap/userdir-ldap.conf");
25 except:
26    File = open("userdir-ldap.conf");
27 ConfModule = imp.load_source("userdir_config","/etc/userdir-ldap.conf",File);
28 File.close();
29
30 # Cheap hack
31 BaseDn = ConfModule.basedn;
32 HostBaseDn = ConfModule.hostbasedn;
33 LDAPServer = ConfModule.ldaphost;
34 EmailAppend = ConfModule.emailappend;
35 AdminUser = ConfModule.adminuser;
36 GenerateDir = ConfModule.generatedir;
37 GenerateConf = ConfModule.generateconf;
38 DefaultGID = ConfModule.defaultgid;
39 TemplatesDir = ConfModule.templatesdir;
40 PassDir = ConfModule.passdir;
41 Ech_ErrorLog = ConfModule.ech_errorlog;
42 Ech_MainLog = ConfModule.ech_mainlog;
43
44 # For backwards compatibility, we default to the old behaviour
45 MultipleSSHFiles = getattr(ConfModule, 'multiplesshfiles', False)
46 SingleSSHFile = getattr(ConfModule, 'singlesshfile', True)
47
48 try:
49    UseSSL = ConfModule.usessl;
50 except AttributeError:
51    UseSSL = False;
52
53 # Break up the keyring list
54 userdir_gpg.SetKeyrings(ConfModule.keyrings.split(":"))
55
56 # This is a list of common last-name prefixes
57 LastNamesPre = {"van": None, "von": None, "le": None, "de": None, "di": None};
58
59 # This is a list of common groups on Debian hosts
60 DebianGroups = {
61    "Debian": 800,
62    "guest": 60000,
63    "nogroup": 65534
64    }
65
66 # ObjectClasses for different object types
67 UserObjectClasses = ("top", "inetOrgPerson", "debianAccount", "shadowAccount", "debianDeveloper")
68 RoleObjectClasses = ("top", "debianAccount", "shadowAccount", "debianRoleAccount")
69 GroupObjectClasses = ("top", "debianGroup")
70
71 # SSH Key splitting. The result is:
72 # (options,size,modulous,exponent,comment)
73 SSHAuthSplit = re.compile('^(.* )?(\d+) (\d+) (\d+) ?(.+)$');
74 SSH2AuthSplit = re.compile('^(.* )?ssh-(dss|rsa) ([a-zA-Z0-9=/+]+) ?(.+)$');
75 #'^([^\d](?:[^ "]+(?:".*")?)*)? ?(\d+) (\d+) (\d+) (.+)$');
76
77 AddressSplit = re.compile("(.*).*<([^@]*)@([^>]*)>");
78
79 # Safely get an attribute from a tuple representing a dn and an attribute
80 # list. It returns the first attribute if there are multi.
81 def GetAttr(DnRecord,Attribute,Default = ""):
82    try:
83       return DnRecord[1][Attribute][0];
84    except IndexError:
85       return Default;
86    except KeyError:
87       return Default;
88    return Default;
89
90 # Return a printable email address from the attributes.
91 def EmailAddress(DnRecord):
92    cn = GetAttr(DnRecord,"cn");
93    sn = GetAttr(DnRecord,"sn");
94    uid = GetAttr(DnRecord,"uid");
95    if cn == "" and sn == "":
96       return "<" + uid + "@" + EmailAppend + ">";
97    return cn + " " + sn + " <" + uid + "@" + EmailAppend + ">"
98
99 # Show a dump like ldapsearch
100 def PrettyShow(DnRecord):
101    Result = "";
102    List = DnRecord[1].keys();
103    List.sort();
104    for x in List:
105       Rec = DnRecord[1][x];
106       for i in Rec:
107          Result = Result + "%s: %s\n" % (x,i);
108    return Result[:-1];
109
110 def connectLDAP(server = None):
111    if server == None:
112       global LDAPServer
113       server = LDAPServer
114    l = ldap.open(server);
115    global UseSSL
116    if UseSSL:
117       l.start_tls_s();
118    return l;
119
120 # Function to prompt for a password 
121 def getpass(prompt = "Password: "):
122    import termios, sys;
123    fd = sys.stdin.fileno();
124    old = termios.tcgetattr(fd);
125    new = termios.tcgetattr(fd);
126    new[3] = new[3] & ~termios.ECHO;          # lflags
127    try:
128       termios.tcsetattr(fd, termios.TCSADRAIN, new);
129       try:
130          passwd = raw_input(prompt);
131       except KeyboardInterrupt:
132          termios.tcsetattr(fd, termios.TCSADRAIN, old);
133          print
134          sys.exit(0)
135       except EOFError:
136          passwd = ""
137    finally:
138       termios.tcsetattr(fd, termios.TCSADRAIN, old);
139    print;
140    return passwd;
141
142 def passwdAccessLDAP(BaseDn, AdminUser):
143    """
144    Ask for the AdminUser's password and connect to the LDAP server.
145    Returns the connection handle.
146    """
147    print "Accessing LDAP directory as '" + AdminUser + "'";
148    while (1):
149       Password = getpass(AdminUser + "'s password: ");
150
151       if len(Password) == 0:
152          sys.exit(0)
153
154       l = connectLDAP()
155       UserDn = "uid=" + AdminUser + "," + BaseDn;
156
157       # Connect to the ldap server
158       try:
159          l.simple_bind_s(UserDn,Password);
160       except ldap.INVALID_CREDENTIALS:
161          continue
162       break
163    return l
164
165 # Split up a name into multiple components. This tries to best guess how
166 # to split up a name
167 def NameSplit(Name):
168    Words = re.split(" ", Name.strip())
169
170    # Insert an empty middle name
171    if (len(Words) == 2):
172       Words.insert(1,"");
173    if (len(Words) < 2):
174       Words.append("");
175
176    # Put a dot after any 1 letter words, must be an initial
177    for x in range(0,len(Words)):
178       if len(Words[x]) == 1:
179          Words[x] = Words[x] + '.';
180
181    # If a word starts with a -, ( or [ we assume it marks the start of some
182    # Non-name information and remove the remainder of the string
183    for x in range(0,len(Words)):
184       if len(Words[x]) != 0 and (Words[x][0] == '-' or \
185           Words[x][0] == '(' or Words[x][0] == '['):
186          Words = Words[0:x];
187          break;
188          
189    # Merge any of the middle initials
190    while len(Words) > 2 and len(Words[2]) == 2 and Words[2][1] == '.':
191       Words[1] = Words[1] +  Words[2];
192       del Words[2];
193
194    while len(Words) < 2:
195       Words.append('');
196    
197    # Merge any of the last name prefixes into one big last name
198    while LastNamesPre.has_key(Words[-2].lower()):
199       Words[-1] = Words[-2] + " " + Words[-1];
200       del Words[-2];
201
202    # Fix up a missing middle name after lastname globbing
203    if (len(Words) == 2):
204       Words.insert(1,"");
205
206    # If the name is multi-word then we glob them all into the last name and
207    # do not worry about a middle name
208    if (len(Words) > 3):
209       Words[2] = " ".join(Words[1:])
210       Words[1] = "";
211
212    return (Words[0].strip(), Words[1].strip(), Words[2].strip());
213
214 # Compute a random password using /dev/urandom
215 def GenPass():   
216    # Generate a 10 character random string
217    SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
218    Rand = open("/dev/urandom");
219    Password = "";
220    for i in range(0,15):
221       Password = Password + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
222    return Password;
223
224 # Compute the MD5 crypted version of the given password
225 def HashPass(Password):
226    # Hash it telling glibc to use the MD5 algorithm - if you dont have
227    # glibc then just change Salt = "$1$" to Salt = "";
228    SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/.";
229    Salt  = "$1$";
230    Rand = open("/dev/urandom");
231    for x in range(0,10):
232       Salt = Salt + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
233    Pass = crypt.crypt(Password,Salt);
234    if len(Pass) < 14:
235       raise "Password Error", "MD5 password hashing failed, not changing the password!";
236    return Pass;
237
238 # Sync with the server, we count the number of async requests that are pending
239 # and make sure result has been called that number of times
240 def FlushOutstanding(l,Outstanding,Fast=0):
241    # Sync with the remote end
242    if Fast == 0:
243       print "Waiting for",Outstanding,"requests:",
244    while (Outstanding > 0):
245       try:
246          if Fast == 0 or Outstanding > 50:
247             sys.stdout.write(".",);
248             sys.stdout.flush();
249             if (l.result(ldap.RES_ANY,1) != (None,None)):
250                Outstanding = Outstanding - 1;
251          else:
252             if (l.result(ldap.RES_ANY,1,0) != (None,None)):
253                Outstanding = Outstanding - 1;
254             else:
255                break;
256       except ldap.TYPE_OR_VALUE_EXISTS:
257          Outstanding = Outstanding - 1;
258       except ldap.NO_SUCH_ATTRIBUTE:
259          Outstanding = Outstanding - 1;
260       except ldap.NO_SUCH_OBJECT:
261          Outstanding = Outstanding - 1;
262    if Fast == 0:
263       print;
264    return Outstanding;
265
266 # Convert a lat/long attribute into Decimal degrees
267 def DecDegree(Posn,Anon=0):
268   Parts = re.match('[-+]?(\d*)\\.?(\d*)',Posn).groups();
269   Val = float(Posn);
270
271   if (abs(Val) >= 1806060.0):
272      raise ValueError,"Too Big";
273
274   # Val is in DGMS
275   if abs(Val) >= 18060.0 or len(Parts[0]) > 5:
276      Val = Val/100.0;
277      Secs = Val - long(Val);
278      Val = long(Val)/100.0;
279      Min = Val - long(Val);
280      Val = long(Val) + (Min*100.0 + Secs*100.0/60.0)/60.0;
281
282   # Val is in DGM
283   elif abs(Val) >= 180 or len(Parts[0]) > 3:
284      Val = Val/100.0;
285      Min = Val - long(Val);
286      Val = long(Val) + Min*100.0/60.0;
287      
288   if Anon != 0:
289       Str = "%3.2f"%(Val);
290   else:
291       Str = str(Val);
292   if Val >= 0:
293      return "+" + Str;
294   return Str;
295
296 def FormatSSH2Auth(Str):
297    Match = SSH2AuthSplit.match(Str);
298    if Match == None:
299       return "<unknown format>";
300    G = Match.groups();
301
302    if G[0] == None:
303       return "ssh-%s %s..%s %s"%(G[1],G[2][:8],G[2][-8:],G[3]);
304    return "%s ssh-%s %s..%s %s"%(G[0],G[1],G[2][:8],G[2][-8:],G[3]);
305
306 def FormatSSHAuth(Str):
307    Match = SSHAuthSplit.match(Str);
308    if Match == None:
309       return FormatSSH2Auth(Str);
310    G = Match.groups();
311
312    # No options
313    if G[0] == None:
314       return "%s %s %s..%s %s"%(G[1],G[2],G[3][:8],G[3][-8:],G[4]);
315    return "%s %s %s %s..%s %s"%(G[0],G[1],G[2],G[3][:8],G[3][-8:],G[4]);
316
317 def FormatPGPKey(Str):
318    Res = "";
319
320    # PGP 2.x Print
321    if (len(Str) == 32):
322       I = 0;
323       while (I < len(Str)):
324          if I+2 == 32/2:
325             Res = "%s %s%s "%(Res,Str[I],Str[I+1]);
326          else:
327             Res = "%s%s%s "%(Res,Str[I],Str[I+1]);
328          I = I + 2;
329    elif (len(Str) == 40):
330       # OpenPGP Print
331       I = 0;
332       while (I < len(Str)):
333          if I+4 == 40/2:
334             Res = "%s %s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
335          else:
336             Res = "%s%s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
337          I = I + 4;
338    else:
339       Res = Str;
340    return Res.strip()
341
342 # Take an email address and split it into 3 parts, (Name,UID,Domain)
343 def SplitEmail(Addr):
344    # Is not an email address at all
345    if Addr.find('@') == -1:
346       return (Addr,"","");
347   
348    Res1 = rfc822.AddrlistClass(Addr).getaddress();
349    if len(Res1) != 1:
350       return ("","",Addr);
351    Res1 = Res1[0];
352    if Res1[1] == None:
353       return (Res1[0],"","");
354
355    # If there is no @ then the address was not parsed well. Try the alternate
356    # Parsing scheme. This is particularly important when scanning PGP keys.
357    Res2 = Res1[1].split("@");
358    if len(Res2) != 2:
359       Match = AddressSplit.match(Addr);
360       if Match == None:
361          return ("","",Addr);
362       return Match.groups();
363
364    return (Res1[0],Res2[0],Res2[1]);
365
366 # Convert the PGP name string to a uid value. The return is a tuple of
367 # (uid,[message strings]). UnknownMpa is a hash from email to uid that 
368 # overrides normal searching.
369 def GetUID(l,Name,UnknownMap = {}):
370    # Crack up the email address into a best guess first/middle/last name
371    (cn,mn,sn) = NameSplit(re.sub('["]','',Name[0]))
372    
373    # Brackets anger the ldap searcher
374    cn = re.sub('[(")]','?',cn);
375    sn = re.sub('[(")]','?',sn);
376
377    # First check the unknown map for the email address
378    if UnknownMap.has_key(Name[1] + '@' + Name[2]):
379       Stat = "unknown map hit for "+str(Name);
380       return (UnknownMap[Name[1] + '@' + Name[2]],[Stat]);
381
382    # Then the cruft component (ie there was no email address to match)
383    if UnknownMap.has_key(Name[2]):
384       Stat = "unknown map hit for"+str(Name);
385       return (UnknownMap[Name[2]],[Stat]);
386
387    # Then the name component (another ie there was no email address to match)
388    if UnknownMap.has_key(Name[0]):
389       Stat = "unknown map hit for"+str(Name);
390       return (UnknownMap[Name[0]],[Stat]);
391   
392    # Search for a possible first/last name hit
393    try:
394       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(&(cn=%s)(sn=%s))"%(cn,sn),["uid"]);
395    except ldap.FILTER_ERROR:
396       Stat = "Filter failure: (&(cn=%s)(sn=%s))"%(cn,sn);
397       return (None,[Stat]);
398
399    # Try matching on the email address
400    if (len(Attrs) != 1):
401       try:
402          Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"emailforward=%s"%(Name[2]),["uid"]);
403       except ldap.FILTER_ERROR:
404          pass;
405
406    # Hmm, more than one/no return
407    if (len(Attrs) != 1):
408       # Key claims a local address
409       if Name[2] == EmailAppend:
410
411          # Pull out the record for the claimed user
412          Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(uid=%s)"%(Name[1]),["uid","sn","cn"]);
413
414          # We require the UID surname to be someplace in the key name, this
415          # deals with special purpose keys like 'James Troup (Alternate Debian key)'
416          # Some people put their names backwards on their key too.. check that as well
417          if len(Attrs) == 1 and \
418             ( sn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 or \
419               cn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 ):
420             Stat = EmailAppend+" hit for "+str(Name);
421             return (Name[1],[Stat]);
422
423       # Attempt to give some best guess suggestions for use in editing the
424       # override file.
425       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(sn~=%s)"%(sn),["uid","sn","cn"]);
426
427       Stat = [];
428       if len(Attrs) != 0:
429          Stat = ["None for %s"%(str(Name))];
430       for x in Attrs:
431          Stat.append("But might be: %s %s <%s@debian.org>"%(x[1]["cn"][0],x[1]["sn"][0],x[1]["uid"][0]));
432       return (None,Stat);        
433    else:
434       return (Attrs[0][1]["uid"][0],None);
435
436    return (None,None);
437
438 def Group2GID(l, name):
439    """
440    Returns the numerical id of a common group
441    on error returns -1
442    """
443    for g in DebianGroups.keys():
444       if name == g:
445          return DebianGroups[g]
446
447    filter = "(gid=%s)" % name
448    res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["gidNumber"]);
449    if res:
450       return int(GetAttr(res[0], "gidNumber"))
451
452    return -1