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
25 import sha as sha1_module
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 DefaultGID = ConfModule.defaultgid;
44 TemplatesDir = ConfModule.templatesdir;
45 PassDir = ConfModule.passdir;
46 Ech_ErrorLog = ConfModule.ech_errorlog;
47 Ech_MainLog = ConfModule.ech_mainlog;
48 HostDomain = getattr(ConfModule, "hostdomain", EmailAppend)
51 UseSSL = ConfModule.usessl;
52 except AttributeError:
55 # Break up the keyring list
56 userdir_gpg.SetKeyrings(ConfModule.keyrings.split(":"))
58 # This is a list of common last-name prefixes
59 LastNamesPre = {"van": None, "von": None, "le": None, "de": None, "di": None};
61 # This is a list of common groups on Debian hosts
68 # ObjectClasses for different object types
69 UserObjectClasses = ("top", "inetOrgPerson", "debianAccount", "shadowAccount", "debianDeveloper")
70 RoleObjectClasses = ("top", "debianAccount", "shadowAccount", "debianRoleAccount")
71 GroupObjectClasses = ("top", "debianGroup")
73 # SSH Key splitting. The result is:
74 # (options,size,modulous,exponent,comment)
75 SSHAuthSplit = re.compile('^(.* )?(\d+) (\d+) (\d+) ?(.+)$');
76 SSH2AuthSplit = re.compile('^(.* )?ssh-(dss|rsa) ([a-zA-Z0-9=/+]+) ?(.+)$');
77 #'^([^\d](?:[^ "]+(?:".*")?)*)? ?(\d+) (\d+) (\d+) (.+)$');
79 AddressSplit = re.compile("(.*).*<([^@]*)@([^>]*)>");
81 # Safely get an attribute from a tuple representing a dn and an attribute
82 # list. It returns the first attribute if there are multi.
83 def GetAttr(DnRecord,Attribute,Default = ""):
85 return DnRecord[1][Attribute][0];
92 # Return a printable email address from the attributes.
93 def EmailAddress(DnRecord):
94 cn = GetAttr(DnRecord,"cn");
95 sn = GetAttr(DnRecord,"sn");
96 uid = GetAttr(DnRecord,"uid");
97 if cn == "" and sn == "":
98 return "<" + uid + "@" + EmailAppend + ">";
99 return cn + " " + sn + " <" + uid + "@" + EmailAppend + ">"
101 # Show a dump like ldapsearch
102 def PrettyShow(DnRecord):
104 List = DnRecord[1].keys();
107 Rec = DnRecord[1][x];
109 Result = Result + "%s: %s\n" % (x,i);
112 def connectLDAP(server = None):
116 l = ldap.open(server);
122 def passwdAccessLDAP(BaseDn, AdminUser):
124 Ask for the AdminUser's password and connect to the LDAP server.
125 Returns the connection handle.
127 print "Accessing LDAP directory as '" + AdminUser + "'";
129 Password = getpass.getpass(AdminUser + "'s password: ")
131 if len(Password) == 0:
135 UserDn = "uid=" + AdminUser + "," + BaseDn;
137 # Connect to the ldap server
139 l.simple_bind_s(UserDn,Password);
140 except ldap.INVALID_CREDENTIALS:
145 # Split up a name into multiple components. This tries to best guess how
148 Words = re.split(" ", Name.strip())
150 # Insert an empty middle name
151 if (len(Words) == 2):
156 # Put a dot after any 1 letter words, must be an initial
157 for x in range(0,len(Words)):
158 if len(Words[x]) == 1:
159 Words[x] = Words[x] + '.';
161 # If a word starts with a -, ( or [ we assume it marks the start of some
162 # Non-name information and remove the remainder of the string
163 for x in range(0,len(Words)):
164 if len(Words[x]) != 0 and (Words[x][0] == '-' or \
165 Words[x][0] == '(' or Words[x][0] == '['):
169 # Merge any of the middle initials
170 while len(Words) > 2 and len(Words[2]) == 2 and Words[2][1] == '.':
171 Words[1] = Words[1] + Words[2];
174 while len(Words) < 2:
177 # Merge any of the last name prefixes into one big last name
178 while LastNamesPre.has_key(Words[-2].lower()):
179 Words[-1] = Words[-2] + " " + Words[-1];
182 # Fix up a missing middle name after lastname globbing
183 if (len(Words) == 2):
186 # If the name is multi-word then we glob them all into the last name and
187 # do not worry about a middle name
189 Words[2] = " ".join(Words[1:])
192 return (Words[0].strip(), Words[1].strip(), Words[2].strip());
194 # Compute a random password using /dev/urandom
196 # Generate a 10 character random string
197 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
198 Rand = open("/dev/urandom");
200 for i in range(0,15):
201 Password = Password + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
204 # Compute the MD5 crypted version of the given password
205 def HashPass(Password):
206 # Hash it telling glibc to use the MD5 algorithm - if you dont have
207 # glibc then just change Salt = "$1$" to Salt = "";
208 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/.";
210 Rand = open("/dev/urandom");
211 for x in range(0,10):
212 Salt = Salt + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
213 Pass = crypt.crypt(Password,Salt);
215 raise "Password Error", "MD5 password hashing failed, not changing the password!";
218 # Sync with the server, we count the number of async requests that are pending
219 # and make sure result has been called that number of times
220 def FlushOutstanding(l,Outstanding,Fast=0):
221 # Sync with the remote end
223 print "Waiting for",Outstanding,"requests:",
224 while (Outstanding > 0):
226 if Fast == 0 or Outstanding > 50:
227 sys.stdout.write(".",);
229 if (l.result(ldap.RES_ANY,1) != (None,None)):
230 Outstanding = Outstanding - 1;
232 if (l.result(ldap.RES_ANY,1,0) != (None,None)):
233 Outstanding = Outstanding - 1;
236 except ldap.TYPE_OR_VALUE_EXISTS:
237 Outstanding = Outstanding - 1;
238 except ldap.NO_SUCH_ATTRIBUTE:
239 Outstanding = Outstanding - 1;
240 except ldap.NO_SUCH_OBJECT:
241 Outstanding = Outstanding - 1;
246 # Convert a lat/long attribute into Decimal degrees
247 def DecDegree(Posn,Anon=0):
248 Parts = re.match('[-+]?(\d*)\\.?(\d*)',Posn).groups();
251 if (abs(Val) >= 1806060.0):
252 raise ValueError,"Too Big";
255 if abs(Val) >= 18060.0 or len(Parts[0]) > 5:
257 Secs = Val - long(Val);
258 Val = long(Val)/100.0;
259 Min = Val - long(Val);
260 Val = long(Val) + (Min*100.0 + Secs*100.0/60.0)/60.0;
263 elif abs(Val) >= 180 or len(Parts[0]) > 3:
265 Min = Val - long(Val);
266 Val = long(Val) + Min*100.0/60.0;
276 def FormatSSH2Auth(Str):
277 Match = SSH2AuthSplit.match(Str);
279 return "<unknown format>";
283 return "ssh-%s %s..%s %s"%(G[1],G[2][:8],G[2][-8:],G[3]);
284 return "%s ssh-%s %s..%s %s"%(G[0],G[1],G[2][:8],G[2][-8:],G[3]);
286 def FormatSSHAuth(Str):
287 Match = SSHAuthSplit.match(Str);
289 return FormatSSH2Auth(Str);
294 return "%s %s %s..%s %s"%(G[1],G[2],G[3][:8],G[3][-8:],G[4]);
295 return "%s %s %s %s..%s %s"%(G[0],G[1],G[2],G[3][:8],G[3][-8:],G[4]);
297 def FormatPGPKey(Str):
303 while (I < len(Str)):
305 Res = "%s %s%s "%(Res,Str[I],Str[I+1]);
307 Res = "%s%s%s "%(Res,Str[I],Str[I+1]);
309 elif (len(Str) == 40):
312 while (I < len(Str)):
314 Res = "%s %s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
316 Res = "%s%s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
322 # Take an email address and split it into 3 parts, (Name,UID,Domain)
323 def SplitEmail(Addr):
324 # Is not an email address at all
325 if Addr.find('@') == -1:
328 Res1 = rfc822.AddrlistClass(Addr).getaddress();
333 return (Res1[0],"","");
335 # If there is no @ then the address was not parsed well. Try the alternate
336 # Parsing scheme. This is particularly important when scanning PGP keys.
337 Res2 = Res1[1].split("@");
339 Match = AddressSplit.match(Addr);
342 return Match.groups();
344 return (Res1[0],Res2[0],Res2[1]);
346 # Convert the PGP name string to a uid value. The return is a tuple of
347 # (uid,[message strings]). UnknownMpa is a hash from email to uid that
348 # overrides normal searching.
349 def GetUID(l,Name,UnknownMap = {}):
350 # Crack up the email address into a best guess first/middle/last name
351 (cn,mn,sn) = NameSplit(re.sub('["]','',Name[0]))
353 # Brackets anger the ldap searcher
354 cn = re.sub('[(")]','?',cn);
355 sn = re.sub('[(")]','?',sn);
357 # First check the unknown map for the email address
358 if UnknownMap.has_key(Name[1] + '@' + Name[2]):
359 Stat = "unknown map hit for "+str(Name);
360 return (UnknownMap[Name[1] + '@' + Name[2]],[Stat]);
362 # Then the cruft component (ie there was no email address to match)
363 if UnknownMap.has_key(Name[2]):
364 Stat = "unknown map hit for"+str(Name);
365 return (UnknownMap[Name[2]],[Stat]);
367 # Then the name component (another ie there was no email address to match)
368 if UnknownMap.has_key(Name[0]):
369 Stat = "unknown map hit for"+str(Name);
370 return (UnknownMap[Name[0]],[Stat]);
372 # Search for a possible first/last name hit
374 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(&(cn=%s)(sn=%s))"%(cn,sn),["uid"]);
375 except ldap.FILTER_ERROR:
376 Stat = "Filter failure: (&(cn=%s)(sn=%s))"%(cn,sn);
377 return (None,[Stat]);
379 # Try matching on the email address
380 if (len(Attrs) != 1):
382 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"emailforward=%s"%(Name[2]),["uid"]);
383 except ldap.FILTER_ERROR:
386 # Hmm, more than one/no return
387 if (len(Attrs) != 1):
388 # Key claims a local address
389 if Name[2] == EmailAppend:
391 # Pull out the record for the claimed user
392 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(uid=%s)"%(Name[1]),["uid","sn","cn"]);
394 # We require the UID surname to be someplace in the key name, this
395 # deals with special purpose keys like 'James Troup (Alternate Debian key)'
396 # Some people put their names backwards on their key too.. check that as well
397 if len(Attrs) == 1 and \
398 ( sn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 or \
399 cn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 ):
400 Stat = EmailAppend+" hit for "+str(Name);
401 return (Name[1],[Stat]);
403 # Attempt to give some best guess suggestions for use in editing the
405 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(sn~=%s)"%(sn),["uid","sn","cn"]);
409 Stat = ["None for %s"%(str(Name))];
411 Stat.append("But might be: %s %s <%s@debian.org>"%(x[1]["cn"][0],x[1]["sn"][0],x[1]["uid"][0]));
414 return (Attrs[0][1]["uid"][0],None);
418 def Group2GID(l, name):
420 Returns the numerical id of a common group
423 for g in DebianGroups.keys():
425 return DebianGroups[g]
427 filter = "(gid=%s)" % name
428 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["gidNumber"]);
430 return int(GetAttr(res[0], "gidNumber"))
435 File = open(PassDir+"/key-hmac-"+pwd.getpwuid(os.getuid())[0],"r");
436 HmacKey = File.readline().strip()
438 return hmac.new(HmacKey, str, sha1_module).hexdigest()
440 def make_passwd_hmac(status, purpose, uid, uuid, hosts, cryptedpass):
441 return make_hmac(':'.join([status, purpose, uid, uuid, hosts, cryptedpass]))