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