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