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