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