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