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>
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 # Some routines and configuration that are used by the ldap progams
21 import termios, re, imp, ldap, sys, crypt, rfc822, pwd, os;
24 import sha as sha1_module
27 File = open("/etc/userdir-ldap/userdir-ldap.conf");
29 File = open("userdir-ldap.conf");
30 ConfModule = imp.load_source("userdir_config","/etc/userdir-ldap.conf",File);
34 BaseDn = ConfModule.basedn;
35 HostBaseDn = ConfModule.hostbasedn;
36 LDAPServer = ConfModule.ldaphost;
37 EmailAppend = ConfModule.emailappend;
38 AdminUser = ConfModule.adminuser;
39 GenerateDir = ConfModule.generatedir;
40 GenerateConf = ConfModule.generateconf;
41 DefaultGID = ConfModule.defaultgid;
42 TemplatesDir = ConfModule.templatesdir;
43 PassDir = ConfModule.passdir;
44 Ech_ErrorLog = ConfModule.ech_errorlog;
45 Ech_MainLog = ConfModule.ech_mainlog;
46 HostDomain = getattr(ConfModule, "hostdomain", EmailAppend)
49 UseSSL = ConfModule.usessl;
50 except AttributeError:
53 # Break up the keyring list
54 userdir_gpg.SetKeyrings(ConfModule.keyrings.split(":"))
56 # This is a list of common last-name prefixes
57 LastNamesPre = {"van": None, "von": None, "le": None, "de": None, "di": None};
59 # This is a list of common groups on Debian hosts
66 # ObjectClasses for different object types
67 UserObjectClasses = ("top", "inetOrgPerson", "debianAccount", "shadowAccount", "debianDeveloper")
68 RoleObjectClasses = ("top", "debianAccount", "shadowAccount", "debianRoleAccount")
69 GroupObjectClasses = ("top", "debianGroup")
71 # SSH Key splitting. The result is:
72 # (options,size,modulous,exponent,comment)
73 SSHAuthSplit = re.compile('^(.* )?(\d+) (\d+) (\d+) ?(.+)$');
74 SSH2AuthSplit = re.compile('^(.* )?ssh-(dss|rsa) ([a-zA-Z0-9=/+]+) ?(.+)$');
75 #'^([^\d](?:[^ "]+(?:".*")?)*)? ?(\d+) (\d+) (\d+) (.+)$');
77 AddressSplit = re.compile("(.*).*<([^@]*)@([^>]*)>");
79 # Safely get an attribute from a tuple representing a dn and an attribute
80 # list. It returns the first attribute if there are multi.
81 def GetAttr(DnRecord,Attribute,Default = ""):
83 return DnRecord[1][Attribute][0];
90 # Return a printable email address from the attributes.
91 def EmailAddress(DnRecord):
92 cn = GetAttr(DnRecord,"cn");
93 sn = GetAttr(DnRecord,"sn");
94 uid = GetAttr(DnRecord,"uid");
95 if cn == "" and sn == "":
96 return "<" + uid + "@" + EmailAppend + ">";
97 return cn + " " + sn + " <" + uid + "@" + EmailAppend + ">"
99 # Show a dump like ldapsearch
100 def PrettyShow(DnRecord):
102 List = DnRecord[1].keys();
105 Rec = DnRecord[1][x];
107 Result = Result + "%s: %s\n" % (x,i);
110 def connectLDAP(server = None):
114 l = ldap.open(server);
120 # Function to prompt for a password
121 def getpass(prompt = "Password: "):
123 fd = sys.stdin.fileno();
124 old = termios.tcgetattr(fd);
125 new = termios.tcgetattr(fd);
126 new[3] = new[3] & ~termios.ECHO; # lflags
128 termios.tcsetattr(fd, termios.TCSADRAIN, new);
130 passwd = raw_input(prompt);
131 except KeyboardInterrupt:
132 termios.tcsetattr(fd, termios.TCSADRAIN, old);
138 termios.tcsetattr(fd, termios.TCSADRAIN, old);
142 def passwdAccessLDAP(BaseDn, AdminUser):
144 Ask for the AdminUser's password and connect to the LDAP server.
145 Returns the connection handle.
147 print "Accessing LDAP directory as '" + AdminUser + "'";
149 Password = getpass(AdminUser + "'s password: ");
151 if len(Password) == 0:
155 UserDn = "uid=" + AdminUser + "," + BaseDn;
157 # Connect to the ldap server
159 l.simple_bind_s(UserDn,Password);
160 except ldap.INVALID_CREDENTIALS:
165 # Split up a name into multiple components. This tries to best guess how
168 Words = re.split(" ", Name.strip())
170 # Insert an empty middle name
171 if (len(Words) == 2):
176 # Put a dot after any 1 letter words, must be an initial
177 for x in range(0,len(Words)):
178 if len(Words[x]) == 1:
179 Words[x] = Words[x] + '.';
181 # If a word starts with a -, ( or [ we assume it marks the start of some
182 # Non-name information and remove the remainder of the string
183 for x in range(0,len(Words)):
184 if len(Words[x]) != 0 and (Words[x][0] == '-' or \
185 Words[x][0] == '(' or Words[x][0] == '['):
189 # Merge any of the middle initials
190 while len(Words) > 2 and len(Words[2]) == 2 and Words[2][1] == '.':
191 Words[1] = Words[1] + Words[2];
194 while len(Words) < 2:
197 # Merge any of the last name prefixes into one big last name
198 while LastNamesPre.has_key(Words[-2].lower()):
199 Words[-1] = Words[-2] + " " + Words[-1];
202 # Fix up a missing middle name after lastname globbing
203 if (len(Words) == 2):
206 # If the name is multi-word then we glob them all into the last name and
207 # do not worry about a middle name
209 Words[2] = " ".join(Words[1:])
212 return (Words[0].strip(), Words[1].strip(), Words[2].strip());
214 # Compute a random password using /dev/urandom
216 # Generate a 10 character random string
217 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
218 Rand = open("/dev/urandom");
220 for i in range(0,15):
221 Password = Password + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
224 # Compute the MD5 crypted version of the given password
225 def HashPass(Password):
226 # Hash it telling glibc to use the MD5 algorithm - if you dont have
227 # glibc then just change Salt = "$1$" to Salt = "";
228 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/.";
230 Rand = open("/dev/urandom");
231 for x in range(0,10):
232 Salt = Salt + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
233 Pass = crypt.crypt(Password,Salt);
235 raise "Password Error", "MD5 password hashing failed, not changing the password!";
238 # Sync with the server, we count the number of async requests that are pending
239 # and make sure result has been called that number of times
240 def FlushOutstanding(l,Outstanding,Fast=0):
241 # Sync with the remote end
243 print "Waiting for",Outstanding,"requests:",
244 while (Outstanding > 0):
246 if Fast == 0 or Outstanding > 50:
247 sys.stdout.write(".",);
249 if (l.result(ldap.RES_ANY,1) != (None,None)):
250 Outstanding = Outstanding - 1;
252 if (l.result(ldap.RES_ANY,1,0) != (None,None)):
253 Outstanding = Outstanding - 1;
256 except ldap.TYPE_OR_VALUE_EXISTS:
257 Outstanding = Outstanding - 1;
258 except ldap.NO_SUCH_ATTRIBUTE:
259 Outstanding = Outstanding - 1;
260 except ldap.NO_SUCH_OBJECT:
261 Outstanding = Outstanding - 1;
266 # Convert a lat/long attribute into Decimal degrees
267 def DecDegree(Posn,Anon=0):
268 Parts = re.match('[-+]?(\d*)\\.?(\d*)',Posn).groups();
271 if (abs(Val) >= 1806060.0):
272 raise ValueError,"Too Big";
275 if abs(Val) >= 18060.0 or len(Parts[0]) > 5:
277 Secs = Val - long(Val);
278 Val = long(Val)/100.0;
279 Min = Val - long(Val);
280 Val = long(Val) + (Min*100.0 + Secs*100.0/60.0)/60.0;
283 elif abs(Val) >= 180 or len(Parts[0]) > 3:
285 Min = Val - long(Val);
286 Val = long(Val) + Min*100.0/60.0;
296 def FormatSSH2Auth(Str):
297 Match = SSH2AuthSplit.match(Str);
299 return "<unknown format>";
303 return "ssh-%s %s..%s %s"%(G[1],G[2][:8],G[2][-8:],G[3]);
304 return "%s ssh-%s %s..%s %s"%(G[0],G[1],G[2][:8],G[2][-8:],G[3]);
306 def FormatSSHAuth(Str):
307 Match = SSHAuthSplit.match(Str);
309 return FormatSSH2Auth(Str);
314 return "%s %s %s..%s %s"%(G[1],G[2],G[3][:8],G[3][-8:],G[4]);
315 return "%s %s %s %s..%s %s"%(G[0],G[1],G[2],G[3][:8],G[3][-8:],G[4]);
317 def FormatPGPKey(Str):
323 while (I < len(Str)):
325 Res = "%s %s%s "%(Res,Str[I],Str[I+1]);
327 Res = "%s%s%s "%(Res,Str[I],Str[I+1]);
329 elif (len(Str) == 40):
332 while (I < len(Str)):
334 Res = "%s %s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
336 Res = "%s%s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
342 # Take an email address and split it into 3 parts, (Name,UID,Domain)
343 def SplitEmail(Addr):
344 # Is not an email address at all
345 if Addr.find('@') == -1:
348 Res1 = rfc822.AddrlistClass(Addr).getaddress();
353 return (Res1[0],"","");
355 # If there is no @ then the address was not parsed well. Try the alternate
356 # Parsing scheme. This is particularly important when scanning PGP keys.
357 Res2 = Res1[1].split("@");
359 Match = AddressSplit.match(Addr);
362 return Match.groups();
364 return (Res1[0],Res2[0],Res2[1]);
366 # Convert the PGP name string to a uid value. The return is a tuple of
367 # (uid,[message strings]). UnknownMpa is a hash from email to uid that
368 # overrides normal searching.
369 def GetUID(l,Name,UnknownMap = {}):
370 # Crack up the email address into a best guess first/middle/last name
371 (cn,mn,sn) = NameSplit(re.sub('["]','',Name[0]))
373 # Brackets anger the ldap searcher
374 cn = re.sub('[(")]','?',cn);
375 sn = re.sub('[(")]','?',sn);
377 # First check the unknown map for the email address
378 if UnknownMap.has_key(Name[1] + '@' + Name[2]):
379 Stat = "unknown map hit for "+str(Name);
380 return (UnknownMap[Name[1] + '@' + Name[2]],[Stat]);
382 # Then the cruft component (ie there was no email address to match)
383 if UnknownMap.has_key(Name[2]):
384 Stat = "unknown map hit for"+str(Name);
385 return (UnknownMap[Name[2]],[Stat]);
387 # Then the name component (another ie there was no email address to match)
388 if UnknownMap.has_key(Name[0]):
389 Stat = "unknown map hit for"+str(Name);
390 return (UnknownMap[Name[0]],[Stat]);
392 # Search for a possible first/last name hit
394 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(&(cn=%s)(sn=%s))"%(cn,sn),["uid"]);
395 except ldap.FILTER_ERROR:
396 Stat = "Filter failure: (&(cn=%s)(sn=%s))"%(cn,sn);
397 return (None,[Stat]);
399 # Try matching on the email address
400 if (len(Attrs) != 1):
402 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"emailforward=%s"%(Name[2]),["uid"]);
403 except ldap.FILTER_ERROR:
406 # Hmm, more than one/no return
407 if (len(Attrs) != 1):
408 # Key claims a local address
409 if Name[2] == EmailAppend:
411 # Pull out the record for the claimed user
412 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(uid=%s)"%(Name[1]),["uid","sn","cn"]);
414 # We require the UID surname to be someplace in the key name, this
415 # deals with special purpose keys like 'James Troup (Alternate Debian key)'
416 # Some people put their names backwards on their key too.. check that as well
417 if len(Attrs) == 1 and \
418 ( sn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 or \
419 cn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 ):
420 Stat = EmailAppend+" hit for "+str(Name);
421 return (Name[1],[Stat]);
423 # Attempt to give some best guess suggestions for use in editing the
425 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(sn~=%s)"%(sn),["uid","sn","cn"]);
429 Stat = ["None for %s"%(str(Name))];
431 Stat.append("But might be: %s %s <%s@debian.org>"%(x[1]["cn"][0],x[1]["sn"][0],x[1]["uid"][0]));
434 return (Attrs[0][1]["uid"][0],None);
438 def Group2GID(l, name):
440 Returns the numerical id of a common group
443 for g in DebianGroups.keys():
445 return DebianGroups[g]
447 filter = "(gid=%s)" % name
448 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["gidNumber"]);
450 return int(GetAttr(res[0], "gidNumber"))
455 File = open(PassDir+"/key-hmac-"+pwd.getpwuid(os.getuid())[0],"r");
456 HmacKey = File.readline().strip()
458 return hmac.new(HmacKey, str, sha1_module).hexdigest()
460 def make_passwd_hmac(status, purpose, uid, uuid, hosts, cryptedpass):
461 return make_hmac(':'.join([status, purpose, uid, uuid, hosts, cryptedpass]))