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