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