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>
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.
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.
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.
19 # Some routines and configuration that are used by the ldap progams
20 import termios, re, imp, ldap, sys, crypt, rfc822, pwd, os;
23 import sha as sha1_module
26 File = open("/etc/userdir-ldap/userdir-ldap.conf");
28 File = open("userdir-ldap.conf");
29 ConfModule = imp.load_source("userdir_config","/etc/userdir-ldap.conf",File);
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;
46 File = open(PassDir+"/key-hmac-"+pwd.getpwuid(os.getuid())[0],"r");
47 HmacKey = File.readline().strip()
50 # For backwards compatibility, we default to the old behaviour
51 MultipleSSHFiles = getattr(ConfModule, 'multiplesshfiles', False)
52 SingleSSHFile = getattr(ConfModule, 'singlesshfile', True)
55 UseSSL = ConfModule.usessl;
56 except AttributeError:
59 # Break up the keyring list
60 userdir_gpg.SetKeyrings(ConfModule.keyrings.split(":"))
62 # This is a list of common last-name prefixes
63 LastNamesPre = {"van": None, "von": None, "le": None, "de": None, "di": None};
65 # This is a list of common groups on Debian hosts
72 # ObjectClasses for different object types
73 UserObjectClasses = ("top", "inetOrgPerson", "debianAccount", "shadowAccount", "debianDeveloper")
74 RoleObjectClasses = ("top", "debianAccount", "shadowAccount", "debianRoleAccount")
75 GroupObjectClasses = ("top", "debianGroup")
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+) (.+)$');
83 AddressSplit = re.compile("(.*).*<([^@]*)@([^>]*)>");
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 = ""):
89 return DnRecord[1][Attribute][0];
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 + ">"
105 # Show a dump like ldapsearch
106 def PrettyShow(DnRecord):
108 List = DnRecord[1].keys();
111 Rec = DnRecord[1][x];
113 Result = Result + "%s: %s\n" % (x,i);
116 def connectLDAP(server = None):
120 l = ldap.open(server);
126 # Function to prompt for a password
127 def getpass(prompt = "Password: "):
129 fd = sys.stdin.fileno();
130 old = termios.tcgetattr(fd);
131 new = termios.tcgetattr(fd);
132 new[3] = new[3] & ~termios.ECHO; # lflags
134 termios.tcsetattr(fd, termios.TCSADRAIN, new);
136 passwd = raw_input(prompt);
137 except KeyboardInterrupt:
138 termios.tcsetattr(fd, termios.TCSADRAIN, old);
144 termios.tcsetattr(fd, termios.TCSADRAIN, old);
148 def passwdAccessLDAP(BaseDn, AdminUser):
150 Ask for the AdminUser's password and connect to the LDAP server.
151 Returns the connection handle.
153 print "Accessing LDAP directory as '" + AdminUser + "'";
155 Password = getpass(AdminUser + "'s password: ");
157 if len(Password) == 0:
161 UserDn = "uid=" + AdminUser + "," + BaseDn;
163 # Connect to the ldap server
165 l.simple_bind_s(UserDn,Password);
166 except ldap.INVALID_CREDENTIALS:
171 # Split up a name into multiple components. This tries to best guess how
174 Words = re.split(" ", Name.strip())
176 # Insert an empty middle name
177 if (len(Words) == 2):
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] + '.';
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] == '['):
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];
200 while len(Words) < 2:
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];
208 # Fix up a missing middle name after lastname globbing
209 if (len(Words) == 2):
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
215 Words[2] = " ".join(Words[1:])
218 return (Words[0].strip(), Words[1].strip(), Words[2].strip());
220 # Compute a random password using /dev/urandom
222 # Generate a 10 character random string
223 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
224 Rand = open("/dev/urandom");
226 for i in range(0,15):
227 Password = Password + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
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/.";
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);
241 raise "Password Error", "MD5 password hashing failed, not changing the password!";
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
249 print "Waiting for",Outstanding,"requests:",
250 while (Outstanding > 0):
252 if Fast == 0 or Outstanding > 50:
253 sys.stdout.write(".",);
255 if (l.result(ldap.RES_ANY,1) != (None,None)):
256 Outstanding = Outstanding - 1;
258 if (l.result(ldap.RES_ANY,1,0) != (None,None)):
259 Outstanding = Outstanding - 1;
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;
272 # Convert a lat/long attribute into Decimal degrees
273 def DecDegree(Posn,Anon=0):
274 Parts = re.match('[-+]?(\d*)\\.?(\d*)',Posn).groups();
277 if (abs(Val) >= 1806060.0):
278 raise ValueError,"Too Big";
281 if abs(Val) >= 18060.0 or len(Parts[0]) > 5:
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;
289 elif abs(Val) >= 180 or len(Parts[0]) > 3:
291 Min = Val - long(Val);
292 Val = long(Val) + Min*100.0/60.0;
302 def FormatSSH2Auth(Str):
303 Match = SSH2AuthSplit.match(Str);
305 return "<unknown format>";
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]);
312 def FormatSSHAuth(Str):
313 Match = SSHAuthSplit.match(Str);
315 return FormatSSH2Auth(Str);
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]);
323 def FormatPGPKey(Str):
329 while (I < len(Str)):
331 Res = "%s %s%s "%(Res,Str[I],Str[I+1]);
333 Res = "%s%s%s "%(Res,Str[I],Str[I+1]);
335 elif (len(Str) == 40):
338 while (I < len(Str)):
340 Res = "%s %s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
342 Res = "%s%s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
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:
354 Res1 = rfc822.AddrlistClass(Addr).getaddress();
359 return (Res1[0],"","");
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("@");
365 Match = AddressSplit.match(Addr);
368 return Match.groups();
370 return (Res1[0],Res2[0],Res2[1]);
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]))
379 # Brackets anger the ldap searcher
380 cn = re.sub('[(")]','?',cn);
381 sn = re.sub('[(")]','?',sn);
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]);
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]);
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]);
398 # Search for a possible first/last name hit
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]);
405 # Try matching on the email address
406 if (len(Attrs) != 1):
408 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"emailforward=%s"%(Name[2]),["uid"]);
409 except ldap.FILTER_ERROR:
412 # Hmm, more than one/no return
413 if (len(Attrs) != 1):
414 # Key claims a local address
415 if Name[2] == EmailAppend:
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"]);
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]);
429 # Attempt to give some best guess suggestions for use in editing the
431 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(sn~=%s)"%(sn),["uid","sn","cn"]);
435 Stat = ["None for %s"%(str(Name))];
437 Stat.append("But might be: %s %s <%s@debian.org>"%(x[1]["cn"][0],x[1]["sn"][0],x[1]["uid"][0]));
440 return (Attrs[0][1]["uid"][0],None);
444 def Group2GID(l, name):
446 Returns the numerical id of a common group
449 for g in DebianGroups.keys():
451 return DebianGroups[g]
453 filter = "(gid=%s)" % name
454 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["gidNumber"]);
456 return int(GetAttr(res[0], "gidNumber"))
461 return hmac.new(HmacKey, str, sha1_module).hexdigest()
463 def make_sudopasswd_hmac(purpose, uuid, hosts, cryptedpass):
464 return make_hmac(':'.join([purpose, uuid, hosts, cryptedpass]))