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