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