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