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;
48 UseSSL = ConfModule.usessl;
49 except AttributeError:
52 # Break up the keyring list
53 userdir_gpg.SetKeyrings(ConfModule.keyrings.split(":"))
55 # This is a list of common last-name prefixes
56 LastNamesPre = {"van": None, "von": None, "le": None, "de": None, "di": None};
58 # This is a list of common groups on Debian hosts
65 # ObjectClasses for different object types
66 UserObjectClasses = ("top", "inetOrgPerson", "debianAccount", "shadowAccount", "debianDeveloper")
67 RoleObjectClasses = ("top", "debianAccount", "shadowAccount", "debianRoleAccount")
68 GroupObjectClasses = ("top", "debianGroup")
70 # SSH Key splitting. The result is:
71 # (options,size,modulous,exponent,comment)
72 SSHAuthSplit = re.compile('^(.* )?(\d+) (\d+) (\d+) ?(.+)$');
73 SSH2AuthSplit = re.compile('^(.* )?ssh-(dss|rsa) ([a-zA-Z0-9=/+]+) ?(.+)$');
74 #'^([^\d](?:[^ "]+(?:".*")?)*)? ?(\d+) (\d+) (\d+) (.+)$');
76 AddressSplit = re.compile("(.*).*<([^@]*)@([^>]*)>");
78 # Safely get an attribute from a tuple representing a dn and an attribute
79 # list. It returns the first attribute if there are multi.
80 def GetAttr(DnRecord,Attribute,Default = ""):
82 return DnRecord[1][Attribute][0];
89 # Return a printable email address from the attributes.
90 def EmailAddress(DnRecord):
91 cn = GetAttr(DnRecord,"cn");
92 sn = GetAttr(DnRecord,"sn");
93 uid = GetAttr(DnRecord,"uid");
94 if cn == "" and sn == "":
95 return "<" + uid + "@" + EmailAppend + ">";
96 return cn + " " + sn + " <" + uid + "@" + EmailAppend + ">"
98 # Show a dump like ldapsearch
99 def PrettyShow(DnRecord):
101 List = DnRecord[1].keys();
104 Rec = DnRecord[1][x];
106 Result = Result + "%s: %s\n" % (x,i);
109 def connectLDAP(server = None):
113 l = ldap.open(server);
119 # Function to prompt for a password
120 def getpass(prompt = "Password: "):
122 fd = sys.stdin.fileno();
123 old = termios.tcgetattr(fd);
124 new = termios.tcgetattr(fd);
125 new[3] = new[3] & ~termios.ECHO; # lflags
127 termios.tcsetattr(fd, termios.TCSADRAIN, new);
129 passwd = raw_input(prompt);
130 except KeyboardInterrupt:
131 termios.tcsetattr(fd, termios.TCSADRAIN, old);
137 termios.tcsetattr(fd, termios.TCSADRAIN, old);
141 def passwdAccessLDAP(BaseDn, AdminUser):
143 Ask for the AdminUser's password and connect to the LDAP server.
144 Returns the connection handle.
146 print "Accessing LDAP directory as '" + AdminUser + "'";
148 Password = getpass(AdminUser + "'s password: ");
150 if len(Password) == 0:
154 UserDn = "uid=" + AdminUser + "," + BaseDn;
156 # Connect to the ldap server
158 l.simple_bind_s(UserDn,Password);
159 except ldap.INVALID_CREDENTIALS:
164 # Split up a name into multiple components. This tries to best guess how
167 Words = re.split(" ", Name.strip())
169 # Insert an empty middle name
170 if (len(Words) == 2):
175 # Put a dot after any 1 letter words, must be an initial
176 for x in range(0,len(Words)):
177 if len(Words[x]) == 1:
178 Words[x] = Words[x] + '.';
180 # If a word starts with a -, ( or [ we assume it marks the start of some
181 # Non-name information and remove the remainder of the string
182 for x in range(0,len(Words)):
183 if len(Words[x]) != 0 and (Words[x][0] == '-' or \
184 Words[x][0] == '(' or Words[x][0] == '['):
188 # Merge any of the middle initials
189 while len(Words) > 2 and len(Words[2]) == 2 and Words[2][1] == '.':
190 Words[1] = Words[1] + Words[2];
193 while len(Words) < 2:
196 # Merge any of the last name prefixes into one big last name
197 while LastNamesPre.has_key(Words[-2].lower()):
198 Words[-1] = Words[-2] + " " + Words[-1];
201 # Fix up a missing middle name after lastname globbing
202 if (len(Words) == 2):
205 # If the name is multi-word then we glob them all into the last name and
206 # do not worry about a middle name
208 Words[2] = " ".join(Words[1:])
211 return (Words[0].strip(), Words[1].strip(), Words[2].strip());
213 # Compute a random password using /dev/urandom
215 # Generate a 10 character random string
216 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
217 Rand = open("/dev/urandom");
219 for i in range(0,15):
220 Password = Password + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
223 # Compute the MD5 crypted version of the given password
224 def HashPass(Password):
225 # Hash it telling glibc to use the MD5 algorithm - if you dont have
226 # glibc then just change Salt = "$1$" to Salt = "";
227 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/.";
229 Rand = open("/dev/urandom");
230 for x in range(0,10):
231 Salt = Salt + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
232 Pass = crypt.crypt(Password,Salt);
234 raise "Password Error", "MD5 password hashing failed, not changing the password!";
237 # Sync with the server, we count the number of async requests that are pending
238 # and make sure result has been called that number of times
239 def FlushOutstanding(l,Outstanding,Fast=0):
240 # Sync with the remote end
242 print "Waiting for",Outstanding,"requests:",
243 while (Outstanding > 0):
245 if Fast == 0 or Outstanding > 50:
246 sys.stdout.write(".",);
248 if (l.result(ldap.RES_ANY,1) != (None,None)):
249 Outstanding = Outstanding - 1;
251 if (l.result(ldap.RES_ANY,1,0) != (None,None)):
252 Outstanding = Outstanding - 1;
255 except ldap.TYPE_OR_VALUE_EXISTS:
256 Outstanding = Outstanding - 1;
257 except ldap.NO_SUCH_ATTRIBUTE:
258 Outstanding = Outstanding - 1;
259 except ldap.NO_SUCH_OBJECT:
260 Outstanding = Outstanding - 1;
265 # Convert a lat/long attribute into Decimal degrees
266 def DecDegree(Posn,Anon=0):
267 Parts = re.match('[-+]?(\d*)\\.?(\d*)',Posn).groups();
270 if (abs(Val) >= 1806060.0):
271 raise ValueError,"Too Big";
274 if abs(Val) >= 18060.0 or len(Parts[0]) > 5:
276 Secs = Val - long(Val);
277 Val = long(Val)/100.0;
278 Min = Val - long(Val);
279 Val = long(Val) + (Min*100.0 + Secs*100.0/60.0)/60.0;
282 elif abs(Val) >= 180 or len(Parts[0]) > 3:
284 Min = Val - long(Val);
285 Val = long(Val) + Min*100.0/60.0;
295 def FormatSSH2Auth(Str):
296 Match = SSH2AuthSplit.match(Str);
298 return "<unknown format>";
302 return "ssh-%s %s..%s %s"%(G[1],G[2][:8],G[2][-8:],G[3]);
303 return "%s ssh-%s %s..%s %s"%(G[0],G[1],G[2][:8],G[2][-8:],G[3]);
305 def FormatSSHAuth(Str):
306 Match = SSHAuthSplit.match(Str);
308 return FormatSSH2Auth(Str);
313 return "%s %s %s..%s %s"%(G[1],G[2],G[3][:8],G[3][-8:],G[4]);
314 return "%s %s %s %s..%s %s"%(G[0],G[1],G[2],G[3][:8],G[3][-8:],G[4]);
316 def FormatPGPKey(Str):
322 while (I < len(Str)):
324 Res = "%s %s%s "%(Res,Str[I],Str[I+1]);
326 Res = "%s%s%s "%(Res,Str[I],Str[I+1]);
328 elif (len(Str) == 40):
331 while (I < len(Str)):
333 Res = "%s %s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
335 Res = "%s%s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
341 # Take an email address and split it into 3 parts, (Name,UID,Domain)
342 def SplitEmail(Addr):
343 # Is not an email address at all
344 if Addr.find('@') == -1:
347 Res1 = rfc822.AddrlistClass(Addr).getaddress();
352 return (Res1[0],"","");
354 # If there is no @ then the address was not parsed well. Try the alternate
355 # Parsing scheme. This is particularly important when scanning PGP keys.
356 Res2 = Res1[1].split("@");
358 Match = AddressSplit.match(Addr);
361 return Match.groups();
363 return (Res1[0],Res2[0],Res2[1]);
365 # Convert the PGP name string to a uid value. The return is a tuple of
366 # (uid,[message strings]). UnknownMpa is a hash from email to uid that
367 # overrides normal searching.
368 def GetUID(l,Name,UnknownMap = {}):
369 # Crack up the email address into a best guess first/middle/last name
370 (cn,mn,sn) = NameSplit(re.sub('["]','',Name[0]))
372 # Brackets anger the ldap searcher
373 cn = re.sub('[(")]','?',cn);
374 sn = re.sub('[(")]','?',sn);
376 # First check the unknown map for the email address
377 if UnknownMap.has_key(Name[1] + '@' + Name[2]):
378 Stat = "unknown map hit for "+str(Name);
379 return (UnknownMap[Name[1] + '@' + Name[2]],[Stat]);
381 # Then the cruft component (ie there was no email address to match)
382 if UnknownMap.has_key(Name[2]):
383 Stat = "unknown map hit for"+str(Name);
384 return (UnknownMap[Name[2]],[Stat]);
386 # Then the name component (another ie there was no email address to match)
387 if UnknownMap.has_key(Name[0]):
388 Stat = "unknown map hit for"+str(Name);
389 return (UnknownMap[Name[0]],[Stat]);
391 # Search for a possible first/last name hit
393 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(&(cn=%s)(sn=%s))"%(cn,sn),["uid"]);
394 except ldap.FILTER_ERROR:
395 Stat = "Filter failure: (&(cn=%s)(sn=%s))"%(cn,sn);
396 return (None,[Stat]);
398 # Try matching on the email address
399 if (len(Attrs) != 1):
401 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"emailforward=%s"%(Name[2]),["uid"]);
402 except ldap.FILTER_ERROR:
405 # Hmm, more than one/no return
406 if (len(Attrs) != 1):
407 # Key claims a local address
408 if Name[2] == EmailAppend:
410 # Pull out the record for the claimed user
411 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(uid=%s)"%(Name[1]),["uid","sn","cn"]);
413 # We require the UID surname to be someplace in the key name, this
414 # deals with special purpose keys like 'James Troup (Alternate Debian key)'
415 # Some people put their names backwards on their key too.. check that as well
416 if len(Attrs) == 1 and \
417 ( sn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 or \
418 cn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 ):
419 Stat = EmailAppend+" hit for "+str(Name);
420 return (Name[1],[Stat]);
422 # Attempt to give some best guess suggestions for use in editing the
424 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(sn~=%s)"%(sn),["uid","sn","cn"]);
428 Stat = ["None for %s"%(str(Name))];
430 Stat.append("But might be: %s %s <%s@debian.org>"%(x[1]["cn"][0],x[1]["sn"][0],x[1]["uid"][0]));
433 return (Attrs[0][1]["uid"][0],None);
437 def Group2GID(l, name):
439 Returns the numerical id of a common group
442 for g in DebianGroups.keys():
444 return DebianGroups[g]
446 filter = "(gid=%s)" % name
447 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["gidNumber"]);
449 return int(GetAttr(res[0], "gidNumber"))
454 File = open(PassDir+"/key-hmac-"+pwd.getpwuid(os.getuid())[0],"r");
455 HmacKey = File.readline().strip()
457 return hmac.new(HmacKey, str, sha1_module).hexdigest()
459 def make_passwd_hmac(status, purpose, uid, uuid, hosts, cryptedpass):
460 return make_hmac(':'.join([status, purpose, uid, uuid, hosts, cryptedpass]))