Reading the hmac key only once is too troublesome
[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, pwd, os;
21 import userdir_gpg
22 import hmac
23 import sha as sha1_module
24
25 try:
26    File = open("/etc/userdir-ldap/userdir-ldap.conf");
27 except:
28    File = open("userdir-ldap.conf");
29 ConfModule = imp.load_source("userdir_config","/etc/userdir-ldap.conf",File);
30 File.close();
31
32 # Cheap hack
33 BaseDn = ConfModule.basedn;
34 HostBaseDn = ConfModule.hostbasedn;
35 LDAPServer = ConfModule.ldaphost;
36 EmailAppend = ConfModule.emailappend;
37 AdminUser = ConfModule.adminuser;
38 GenerateDir = ConfModule.generatedir;
39 GenerateConf = ConfModule.generateconf;
40 DefaultGID = ConfModule.defaultgid;
41 TemplatesDir = ConfModule.templatesdir;
42 PassDir = ConfModule.passdir;
43 Ech_ErrorLog = ConfModule.ech_errorlog;
44 Ech_MainLog = ConfModule.ech_mainlog;
45
46 # For backwards compatibility, we default to the old behaviour
47 MultipleSSHFiles = getattr(ConfModule, 'multiplesshfiles', False)
48 SingleSSHFile = getattr(ConfModule, 'singlesshfile', True)
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 # Function to prompt for a password 
123 def getpass(prompt = "Password: "):
124    import termios, sys;
125    fd = sys.stdin.fileno();
126    old = termios.tcgetattr(fd);
127    new = termios.tcgetattr(fd);
128    new[3] = new[3] & ~termios.ECHO;          # lflags
129    try:
130       termios.tcsetattr(fd, termios.TCSADRAIN, new);
131       try:
132          passwd = raw_input(prompt);
133       except KeyboardInterrupt:
134          termios.tcsetattr(fd, termios.TCSADRAIN, old);
135          print
136          sys.exit(0)
137       except EOFError:
138          passwd = ""
139    finally:
140       termios.tcsetattr(fd, termios.TCSADRAIN, old);
141    print;
142    return passwd;
143
144 def passwdAccessLDAP(BaseDn, AdminUser):
145    """
146    Ask for the AdminUser's password and connect to the LDAP server.
147    Returns the connection handle.
148    """
149    print "Accessing LDAP directory as '" + AdminUser + "'";
150    while (1):
151       Password = getpass(AdminUser + "'s password: ");
152
153       if len(Password) == 0:
154          sys.exit(0)
155
156       l = connectLDAP()
157       UserDn = "uid=" + AdminUser + "," + BaseDn;
158
159       # Connect to the ldap server
160       try:
161          l.simple_bind_s(UserDn,Password);
162       except ldap.INVALID_CREDENTIALS:
163          continue
164       break
165    return l
166
167 # Split up a name into multiple components. This tries to best guess how
168 # to split up a name
169 def NameSplit(Name):
170    Words = re.split(" ", Name.strip())
171
172    # Insert an empty middle name
173    if (len(Words) == 2):
174       Words.insert(1,"");
175    if (len(Words) < 2):
176       Words.append("");
177
178    # Put a dot after any 1 letter words, must be an initial
179    for x in range(0,len(Words)):
180       if len(Words[x]) == 1:
181          Words[x] = Words[x] + '.';
182
183    # If a word starts with a -, ( or [ we assume it marks the start of some
184    # Non-name information and remove the remainder of the string
185    for x in range(0,len(Words)):
186       if len(Words[x]) != 0 and (Words[x][0] == '-' or \
187           Words[x][0] == '(' or Words[x][0] == '['):
188          Words = Words[0:x];
189          break;
190          
191    # Merge any of the middle initials
192    while len(Words) > 2 and len(Words[2]) == 2 and Words[2][1] == '.':
193       Words[1] = Words[1] +  Words[2];
194       del Words[2];
195
196    while len(Words) < 2:
197       Words.append('');
198    
199    # Merge any of the last name prefixes into one big last name
200    while LastNamesPre.has_key(Words[-2].lower()):
201       Words[-1] = Words[-2] + " " + Words[-1];
202       del Words[-2];
203
204    # Fix up a missing middle name after lastname globbing
205    if (len(Words) == 2):
206       Words.insert(1,"");
207
208    # If the name is multi-word then we glob them all into the last name and
209    # do not worry about a middle name
210    if (len(Words) > 3):
211       Words[2] = " ".join(Words[1:])
212       Words[1] = "";
213
214    return (Words[0].strip(), Words[1].strip(), Words[2].strip());
215
216 # Compute a random password using /dev/urandom
217 def GenPass():   
218    # Generate a 10 character random string
219    SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
220    Rand = open("/dev/urandom");
221    Password = "";
222    for i in range(0,15):
223       Password = Password + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
224    return Password;
225
226 # Compute the MD5 crypted version of the given password
227 def HashPass(Password):
228    # Hash it telling glibc to use the MD5 algorithm - if you dont have
229    # glibc then just change Salt = "$1$" to Salt = "";
230    SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/.";
231    Salt  = "$1$";
232    Rand = open("/dev/urandom");
233    for x in range(0,10):
234       Salt = Salt + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
235    Pass = crypt.crypt(Password,Salt);
236    if len(Pass) < 14:
237       raise "Password Error", "MD5 password hashing failed, not changing the password!";
238    return Pass;
239
240 # Sync with the server, we count the number of async requests that are pending
241 # and make sure result has been called that number of times
242 def FlushOutstanding(l,Outstanding,Fast=0):
243    # Sync with the remote end
244    if Fast == 0:
245       print "Waiting for",Outstanding,"requests:",
246    while (Outstanding > 0):
247       try:
248          if Fast == 0 or Outstanding > 50:
249             sys.stdout.write(".",);
250             sys.stdout.flush();
251             if (l.result(ldap.RES_ANY,1) != (None,None)):
252                Outstanding = Outstanding - 1;
253          else:
254             if (l.result(ldap.RES_ANY,1,0) != (None,None)):
255                Outstanding = Outstanding - 1;
256             else:
257                break;
258       except ldap.TYPE_OR_VALUE_EXISTS:
259          Outstanding = Outstanding - 1;
260       except ldap.NO_SUCH_ATTRIBUTE:
261          Outstanding = Outstanding - 1;
262       except ldap.NO_SUCH_OBJECT:
263          Outstanding = Outstanding - 1;
264    if Fast == 0:
265       print;
266    return Outstanding;
267
268 # Convert a lat/long attribute into Decimal degrees
269 def DecDegree(Posn,Anon=0):
270   Parts = re.match('[-+]?(\d*)\\.?(\d*)',Posn).groups();
271   Val = float(Posn);
272
273   if (abs(Val) >= 1806060.0):
274      raise ValueError,"Too Big";
275
276   # Val is in DGMS
277   if abs(Val) >= 18060.0 or len(Parts[0]) > 5:
278      Val = Val/100.0;
279      Secs = Val - long(Val);
280      Val = long(Val)/100.0;
281      Min = Val - long(Val);
282      Val = long(Val) + (Min*100.0 + Secs*100.0/60.0)/60.0;
283
284   # Val is in DGM
285   elif abs(Val) >= 180 or len(Parts[0]) > 3:
286      Val = Val/100.0;
287      Min = Val - long(Val);
288      Val = long(Val) + Min*100.0/60.0;
289      
290   if Anon != 0:
291       Str = "%3.2f"%(Val);
292   else:
293       Str = str(Val);
294   if Val >= 0:
295      return "+" + Str;
296   return Str;
297
298 def FormatSSH2Auth(Str):
299    Match = SSH2AuthSplit.match(Str);
300    if Match == None:
301       return "<unknown format>";
302    G = Match.groups();
303
304    if G[0] == None:
305       return "ssh-%s %s..%s %s"%(G[1],G[2][:8],G[2][-8:],G[3]);
306    return "%s ssh-%s %s..%s %s"%(G[0],G[1],G[2][:8],G[2][-8:],G[3]);
307
308 def FormatSSHAuth(Str):
309    Match = SSHAuthSplit.match(Str);
310    if Match == None:
311       return FormatSSH2Auth(Str);
312    G = Match.groups();
313
314    # No options
315    if G[0] == None:
316       return "%s %s %s..%s %s"%(G[1],G[2],G[3][:8],G[3][-8:],G[4]);
317    return "%s %s %s %s..%s %s"%(G[0],G[1],G[2],G[3][:8],G[3][-8:],G[4]);
318
319 def FormatPGPKey(Str):
320    Res = "";
321
322    # PGP 2.x Print
323    if (len(Str) == 32):
324       I = 0;
325       while (I < len(Str)):
326          if I+2 == 32/2:
327             Res = "%s %s%s "%(Res,Str[I],Str[I+1]);
328          else:
329             Res = "%s%s%s "%(Res,Str[I],Str[I+1]);
330          I = I + 2;
331    elif (len(Str) == 40):
332       # OpenPGP Print
333       I = 0;
334       while (I < len(Str)):
335          if I+4 == 40/2:
336             Res = "%s %s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
337          else:
338             Res = "%s%s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
339          I = I + 4;
340    else:
341       Res = Str;
342    return Res.strip()
343
344 # Take an email address and split it into 3 parts, (Name,UID,Domain)
345 def SplitEmail(Addr):
346    # Is not an email address at all
347    if Addr.find('@') == -1:
348       return (Addr,"","");
349   
350    Res1 = rfc822.AddrlistClass(Addr).getaddress();
351    if len(Res1) != 1:
352       return ("","",Addr);
353    Res1 = Res1[0];
354    if Res1[1] == None:
355       return (Res1[0],"","");
356
357    # If there is no @ then the address was not parsed well. Try the alternate
358    # Parsing scheme. This is particularly important when scanning PGP keys.
359    Res2 = Res1[1].split("@");
360    if len(Res2) != 2:
361       Match = AddressSplit.match(Addr);
362       if Match == None:
363          return ("","",Addr);
364       return Match.groups();
365
366    return (Res1[0],Res2[0],Res2[1]);
367
368 # Convert the PGP name string to a uid value. The return is a tuple of
369 # (uid,[message strings]). UnknownMpa is a hash from email to uid that 
370 # overrides normal searching.
371 def GetUID(l,Name,UnknownMap = {}):
372    # Crack up the email address into a best guess first/middle/last name
373    (cn,mn,sn) = NameSplit(re.sub('["]','',Name[0]))
374    
375    # Brackets anger the ldap searcher
376    cn = re.sub('[(")]','?',cn);
377    sn = re.sub('[(")]','?',sn);
378
379    # First check the unknown map for the email address
380    if UnknownMap.has_key(Name[1] + '@' + Name[2]):
381       Stat = "unknown map hit for "+str(Name);
382       return (UnknownMap[Name[1] + '@' + Name[2]],[Stat]);
383
384    # Then the cruft component (ie there was no email address to match)
385    if UnknownMap.has_key(Name[2]):
386       Stat = "unknown map hit for"+str(Name);
387       return (UnknownMap[Name[2]],[Stat]);
388
389    # Then the name component (another ie there was no email address to match)
390    if UnknownMap.has_key(Name[0]):
391       Stat = "unknown map hit for"+str(Name);
392       return (UnknownMap[Name[0]],[Stat]);
393   
394    # Search for a possible first/last name hit
395    try:
396       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(&(cn=%s)(sn=%s))"%(cn,sn),["uid"]);
397    except ldap.FILTER_ERROR:
398       Stat = "Filter failure: (&(cn=%s)(sn=%s))"%(cn,sn);
399       return (None,[Stat]);
400
401    # Try matching on the email address
402    if (len(Attrs) != 1):
403       try:
404          Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"emailforward=%s"%(Name[2]),["uid"]);
405       except ldap.FILTER_ERROR:
406          pass;
407
408    # Hmm, more than one/no return
409    if (len(Attrs) != 1):
410       # Key claims a local address
411       if Name[2] == EmailAppend:
412
413          # Pull out the record for the claimed user
414          Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(uid=%s)"%(Name[1]),["uid","sn","cn"]);
415
416          # We require the UID surname to be someplace in the key name, this
417          # deals with special purpose keys like 'James Troup (Alternate Debian key)'
418          # Some people put their names backwards on their key too.. check that as well
419          if len(Attrs) == 1 and \
420             ( sn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 or \
421               cn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 ):
422             Stat = EmailAppend+" hit for "+str(Name);
423             return (Name[1],[Stat]);
424
425       # Attempt to give some best guess suggestions for use in editing the
426       # override file.
427       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(sn~=%s)"%(sn),["uid","sn","cn"]);
428
429       Stat = [];
430       if len(Attrs) != 0:
431          Stat = ["None for %s"%(str(Name))];
432       for x in Attrs:
433          Stat.append("But might be: %s %s <%s@debian.org>"%(x[1]["cn"][0],x[1]["sn"][0],x[1]["uid"][0]));
434       return (None,Stat);        
435    else:
436       return (Attrs[0][1]["uid"][0],None);
437
438    return (None,None);
439
440 def Group2GID(l, name):
441    """
442    Returns the numerical id of a common group
443    on error returns -1
444    """
445    for g in DebianGroups.keys():
446       if name == g:
447          return DebianGroups[g]
448
449    filter = "(gid=%s)" % name
450    res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["gidNumber"]);
451    if res:
452       return int(GetAttr(res[0], "gidNumber"))
453
454    return -1
455
456 def make_hmac(str):
457    File = open(PassDir+"/key-hmac-"+pwd.getpwuid(os.getuid())[0],"r");
458    HmacKey = File.readline().strip()
459    File.close();
460    return hmac.new(HmacKey, str, sha1_module).hexdigest()
461
462 def make_sudopasswd_hmac(purpose, uuid, hosts, cryptedpass):
463    return make_hmac(':'.join([purpose, uuid, hosts, cryptedpass]))