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>
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.
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.
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.
21 # Some routines and configuration that are used by the ldap progams
22 import termios, re, imp, ldap, sys, crypt, rfc822, pwd, os, getpass
28 File = open("/etc/userdir-ldap/userdir-ldap.conf");
30 File = open("userdir-ldap.conf");
31 ConfModule = imp.load_source("userdir_config","/etc/userdir-ldap.conf",File);
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 AllowedGroupsPreload = ConfModule.allowedgroupspreload;
42 HomePrefix = ConfModule.homeprefix;
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)
50 UseSSL = ConfModule.usessl;
51 except AttributeError:
55 BaseBaseDn = ConfModule.basebasedn;
56 except AttributeError:
60 IgnoreUsersForUIDNumberGen = ConfModule.ignoreusersforuidnumbergen
61 except AttributeError:
62 IgnoreUsersForUIDNumberGen = ['nobody']
65 # Break up the keyring list
66 userdir_gpg.SetKeyrings(ConfModule.keyrings.split(":"))
68 # This is a list of common last-name prefixes
69 LastNamesPre = {"van": None, "von": None, "le": None, "de": None, "di": None};
71 # This is a list of common groups on Debian hosts
78 # ObjectClasses for different object types
79 UserObjectClasses = ("top", "inetOrgPerson", "debianAccount", "shadowAccount", "debianDeveloper")
80 RoleObjectClasses = ("top", "debianAccount", "shadowAccount", "debianRoleAccount")
81 GroupObjectClasses = ("top", "debianGroup")
83 # SSH Key splitting. The result is:
84 # (options,size,modulous,exponent,comment)
85 SSHAuthSplit = re.compile('^(.* )?(\d+) (\d+) (\d+) ?(.+)$');
86 SSH2AuthSplit = re.compile('^(.* )?ssh-(dss|rsa|ecdsa-sha2-nistp(?:256|384|521)|ed25519) ([a-zA-Z0-9=/+]+) ?(.+)$');
87 #'^([^\d](?:[^ "]+(?:".*")?)*)? ?(\d+) (\d+) (\d+) (.+)$');
89 AddressSplit = re.compile("(.*).*<([^@]*)@([^>]*)>");
91 # Safely get an attribute from a tuple representing a dn and an attribute
92 # list. It returns the first attribute if there are multi.
93 def GetAttr(DnRecord,Attribute,Default = ""):
95 return DnRecord[1][Attribute][0];
102 # Return a printable email address from the attributes.
103 def EmailAddress(DnRecord):
104 cn = GetAttr(DnRecord,"cn");
105 sn = GetAttr(DnRecord,"sn");
106 uid = GetAttr(DnRecord,"uid");
107 if cn == "" and sn == "":
108 return "<" + uid + "@" + EmailAppend + ">";
109 return cn + " " + sn + " <" + uid + "@" + EmailAppend + ">"
111 # Show a dump like ldapsearch
112 def PrettyShow(DnRecord):
114 List = DnRecord[1].keys();
117 Rec = DnRecord[1][x];
119 Result = Result + "%s: %s\n" % (x,i);
122 def connectLDAP(server = None):
126 l = ldap.open(server);
132 def passwdAccessLDAP(BaseDn, AdminUser):
134 Ask for the AdminUser's password and connect to the LDAP server.
135 Returns the connection handle.
137 print "Accessing LDAP directory as '" + AdminUser + "'";
139 if 'LDAP_PASSWORD' in os.environ:
140 Password = os.environ['LDAP_PASSWORD']
142 Password = getpass.getpass(AdminUser + "'s password: ")
144 if len(Password) == 0:
148 UserDn = "uid=" + AdminUser + "," + BaseDn;
150 # Connect to the ldap server
152 l.simple_bind_s(UserDn,Password);
153 except ldap.INVALID_CREDENTIALS:
154 if 'LDAP_PASSWORD' in os.environ:
155 print "password in environment does not work"
156 del os.environ['LDAP_PASSWORD']
161 # Split up a name into multiple components. This tries to best guess how
164 Words = re.split(" ", Name.strip())
166 # Insert an empty middle name
167 if (len(Words) == 2):
172 # Put a dot after any 1 letter words, must be an initial
173 for x in range(0,len(Words)):
174 if len(Words[x]) == 1:
175 Words[x] = Words[x] + '.';
177 # If a word starts with a -, ( or [ we assume it marks the start of some
178 # Non-name information and remove the remainder of the string
179 for x in range(0,len(Words)):
180 if len(Words[x]) != 0 and (Words[x][0] == '-' or \
181 Words[x][0] == '(' or Words[x][0] == '['):
185 # Merge any of the middle initials
186 while len(Words) > 2 and len(Words[2]) == 2 and Words[2][1] == '.':
187 Words[1] = Words[1] + Words[2];
190 while len(Words) < 2:
193 # Merge any of the last name prefixes into one big last name
194 while LastNamesPre.has_key(Words[-2].lower()):
195 Words[-1] = Words[-2] + " " + Words[-1];
198 # Fix up a missing middle name after lastname globbing
199 if (len(Words) == 2):
202 # If the name is multi-word then we glob them all into the last name and
203 # do not worry about a middle name
205 Words[2] = " ".join(Words[1:])
208 return (Words[0].strip(), Words[1].strip(), Words[2].strip());
210 # Compute a random password using /dev/urandom
212 # Generate a 10 character random string
213 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
214 Rand = open("/dev/urandom");
216 for i in range(0,15):
217 Password = Password + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
220 # Compute the MD5 crypted version of the given password
221 def HashPass(Password):
222 # Hash it telling glibc to use the MD5 algorithm - if you dont have
223 # glibc then just change Salt = "$1$" to Salt = "";
224 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/.";
226 Rand = open("/dev/urandom");
227 for x in range(0,10):
228 Salt = Salt + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
229 Pass = crypt.crypt(Password,Salt);
231 raise "Password Error", "MD5 password hashing failed, not changing the password!";
234 # Sync with the server, we count the number of async requests that are pending
235 # and make sure result has been called that number of times
236 def FlushOutstanding(l,Outstanding,Fast=0):
237 # Sync with the remote end
239 print "Waiting for",Outstanding,"requests:",
240 while (Outstanding > 0):
242 if Fast == 0 or Outstanding > 50:
243 sys.stdout.write(".",);
245 if (l.result(ldap.RES_ANY,1) != (None,None)):
246 Outstanding = Outstanding - 1;
248 if (l.result(ldap.RES_ANY,1,0) != (None,None)):
249 Outstanding = Outstanding - 1;
252 except ldap.TYPE_OR_VALUE_EXISTS:
253 Outstanding = Outstanding - 1;
254 except ldap.NO_SUCH_ATTRIBUTE:
255 Outstanding = Outstanding - 1;
256 except ldap.NO_SUCH_OBJECT:
257 Outstanding = Outstanding - 1;
262 # Convert a lat/long attribute into Decimal degrees
263 def DecDegree(Posn,Anon=0):
264 Parts = re.match('[-+]?(\d*)\\.?(\d*)',Posn).groups();
267 if (abs(Val) >= 1806060.0):
268 raise ValueError,"Too Big";
271 if abs(Val) >= 18060.0 or len(Parts[0]) > 5:
273 Secs = Val - long(Val);
274 Val = long(Val)/100.0;
275 Min = Val - long(Val);
276 Val = long(Val) + (Min*100.0 + Secs*100.0/60.0)/60.0;
279 elif abs(Val) >= 180 or len(Parts[0]) > 3:
281 Min = Val - long(Val);
282 Val = long(Val) + Min*100.0/60.0;
292 def FormatSSH2Auth(Str):
293 Match = SSH2AuthSplit.match(Str);
295 return "<unknown format>";
299 return "ssh-%s %s..%s %s"%(G[1],G[2][:8],G[2][-8:],G[3]);
300 return "%s ssh-%s %s..%s %s"%(G[0],G[1],G[2][:8],G[2][-8:],G[3]);
302 def FormatSSHAuth(Str):
303 Match = SSHAuthSplit.match(Str);
305 return FormatSSH2Auth(Str);
310 return "%s %s %s..%s %s"%(G[1],G[2],G[3][:8],G[3][-8:],G[4]);
311 return "%s %s %s %s..%s %s"%(G[0],G[1],G[2],G[3][:8],G[3][-8:],G[4]);
313 def FormatPGPKey(Str):
319 while (I < len(Str)):
321 Res = "%s %s%s "%(Res,Str[I],Str[I+1]);
323 Res = "%s%s%s "%(Res,Str[I],Str[I+1]);
325 elif (len(Str) == 40):
328 while (I < len(Str)):
330 Res = "%s %s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
332 Res = "%s%s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
338 # Take an email address and split it into 3 parts, (Name,UID,Domain)
339 def SplitEmail(Addr):
340 # Is not an email address at all
341 if Addr.find('@') == -1:
344 Res1 = rfc822.AddrlistClass(Addr).getaddress();
349 return (Res1[0],"","");
351 # If there is no @ then the address was not parsed well. Try the alternate
352 # Parsing scheme. This is particularly important when scanning PGP keys.
353 Res2 = Res1[1].split("@");
355 Match = AddressSplit.match(Addr);
358 return Match.groups();
360 return (Res1[0],Res2[0],Res2[1]);
362 # Convert the PGP name string to a uid value. The return is a tuple of
363 # (uid,[message strings]). UnknownMpa is a hash from email to uid that
364 # overrides normal searching.
365 def GetUID(l,Name,UnknownMap = {}):
366 # Crack up the email address into a best guess first/middle/last name
367 (cn,mn,sn) = NameSplit(re.sub('["]','',Name[0]))
369 # Brackets anger the ldap searcher
370 cn = re.sub('[(")]','?',cn);
371 sn = re.sub('[(")]','?',sn);
373 # First check the unknown map for the email address
374 if UnknownMap.has_key(Name[1] + '@' + Name[2]):
375 Stat = "unknown map hit for "+str(Name);
376 return (UnknownMap[Name[1] + '@' + Name[2]],[Stat]);
378 # Then the cruft component (ie there was no email address to match)
379 if UnknownMap.has_key(Name[2]):
380 Stat = "unknown map hit for"+str(Name);
381 return (UnknownMap[Name[2]],[Stat]);
383 # Then the name component (another ie there was no email address to match)
384 if UnknownMap.has_key(Name[0]):
385 Stat = "unknown map hit for"+str(Name);
386 return (UnknownMap[Name[0]],[Stat]);
388 # Search for a possible first/last name hit
390 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(&(cn=%s)(sn=%s))"%(cn,sn),["uid"]);
391 except ldap.FILTER_ERROR:
392 Stat = "Filter failure: (&(cn=%s)(sn=%s))"%(cn,sn);
393 return (None,[Stat]);
395 # Try matching on the email address
396 if (len(Attrs) != 1):
398 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"emailforward=%s"%(Name[2]),["uid"]);
399 except ldap.FILTER_ERROR:
402 # Hmm, more than one/no return
403 if (len(Attrs) != 1):
404 # Key claims a local address
405 if Name[2] == EmailAppend:
407 # Pull out the record for the claimed user
408 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(uid=%s)"%(Name[1]),["uid","sn","cn"]);
410 # We require the UID surname to be someplace in the key name, this
411 # deals with special purpose keys like 'James Troup (Alternate Debian key)'
412 # Some people put their names backwards on their key too.. check that as well
413 if len(Attrs) == 1 and \
414 ( sn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 or \
415 cn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 ):
416 Stat = EmailAppend+" hit for "+str(Name);
417 return (Name[1],[Stat]);
419 # Attempt to give some best guess suggestions for use in editing the
421 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(sn~=%s)"%(sn),["uid","sn","cn"]);
425 Stat = ["None for %s"%(str(Name))];
427 Stat.append("But might be: %s %s <%s@debian.org>"%(x[1]["cn"][0],x[1]["sn"][0],x[1]["uid"][0]));
430 return (Attrs[0][1]["uid"][0],None);
434 def Group2GID(l, name):
436 Returns the numerical id of a common group
439 for g in DebianGroups.keys():
441 return DebianGroups[g]
443 filter = "(gid=%s)" % name
444 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["gidNumber"]);
446 return int(GetAttr(res[0], "gidNumber"))
451 if 'UD_HMAC_KEY' in os.environ:
452 HmacKey = os.environ['UD_HMAC_KEY']
454 File = open(PassDir+"/key-hmac-"+pwd.getpwuid(os.getuid())[0],"r");
455 HmacKey = File.readline().strip()
457 return hmac.new(HmacKey, str, hashlib.sha1).hexdigest()
459 def make_passwd_hmac(status, purpose, uid, uuid, hosts, cryptedpass):
460 return make_hmac(':'.join([status, purpose, uid, uuid, hosts, cryptedpass]))