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