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