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