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;
24 File = open("/etc/userdir-ldap/userdir-ldap.conf");
26 File = open("userdir-ldap.conf");
27 ConfModule = imp.load_source("userdir_config","/etc/userdir-ldap.conf",File);
31 BaseDn = ConfModule.basedn;
32 HostBaseDn = ConfModule.hostbasedn;
33 LDAPServer = ConfModule.ldaphost;
34 EmailAppend = ConfModule.emailappend;
35 AdminUser = ConfModule.adminuser;
36 GenerateDir = ConfModule.generatedir;
37 GenerateConf = ConfModule.generateconf;
38 DefaultGID = ConfModule.defaultgid;
39 TemplatesDir = ConfModule.templatesdir;
40 PassDir = ConfModule.passdir;
41 Ech_ErrorLog = ConfModule.ech_errorlog;
42 Ech_MainLog = ConfModule.ech_mainlog;
44 # For backwards compatibility, we default to the old behaviour
45 MultipleSSHFiles = getattr(ConfModule, 'multiplesshfiles', False)
46 SingleSSHFile = getattr(ConfModule, 'singlesshfile', True)
48 # Break up the keyring list
49 userdir_gpg.SetKeyrings(ConfModule.keyrings.split(":"))
51 # This is a list of common last-name prefixes
52 LastNamesPre = {"van": None, "von": None, "le": None, "de": None, "di": None};
54 # This is a list of common groups on Debian hosts
61 # ObjectClasses for different object types
62 UserObjectClasses = ("top", "inetOrgPerson", "debianAccount", "shadowAccount", "debianDeveloper")
63 RoleObjectClasses = ("top", "debianAccount", "shadowAccount", "debianRoleAccount")
64 GroupObjectClasses = ("top", "debianGroup")
66 # SSH Key splitting. The result is:
67 # (options,size,modulous,exponent,comment)
68 SSHAuthSplit = re.compile('^(.* )?(\d+) (\d+) (\d+) ?(.+)$');
69 SSH2AuthSplit = re.compile('^(.* )?ssh-(dss|rsa) ([a-zA-Z0-9=/+]+) ?(.+)$');
70 #'^([^\d](?:[^ "]+(?:".*")?)*)? ?(\d+) (\d+) (\d+) (.+)$');
72 AddressSplit = re.compile("(.*).*<([^@]*)@([^>]*)>");
74 # Safely get an attribute from a tuple representing a dn and an attribute
75 # list. It returns the first attribute if there are multi.
76 def GetAttr(DnRecord,Attribute,Default = ""):
78 return DnRecord[1][Attribute][0];
85 # Return a printable email address from the attributes.
86 def EmailAddress(DnRecord):
87 cn = GetAttr(DnRecord,"cn");
88 sn = GetAttr(DnRecord,"sn");
89 uid = GetAttr(DnRecord,"uid");
90 if cn == "" and sn == "":
91 return "<" + uid + "@" + EmailAppend + ">";
92 return cn + " " + sn + " <" + uid + "@" + EmailAppend + ">"
94 # Show a dump like ldapsearch
95 def PrettyShow(DnRecord):
97 List = DnRecord[1].keys();
100 Rec = DnRecord[1][x];
102 Result = Result + "%s: %s\n" % (x,i);
105 # Function to prompt for a password
106 def getpass(prompt = "Password: "):
108 fd = sys.stdin.fileno();
109 old = termios.tcgetattr(fd);
110 new = termios.tcgetattr(fd);
111 new[3] = new[3] & ~termios.ECHO; # lflags
113 termios.tcsetattr(fd, termios.TCSADRAIN, new);
115 passwd = raw_input(prompt);
116 except KeyboardInterrupt:
117 termios.tcsetattr(fd, termios.TCSADRAIN, old);
123 termios.tcsetattr(fd, termios.TCSADRAIN, old);
127 def passwdAccessLDAP(LDAPServer, BaseDn, AdminUser):
129 Ask for the AdminUser's password and connect to the LDAP server.
130 Returns the connection handle.
132 print "Accessing LDAP directory as '" + AdminUser + "'";
134 Password = getpass(AdminUser + "'s password: ");
136 if len(Password) == 0:
139 l = ldap.open(LDAPServer);
140 UserDn = "uid=" + AdminUser + "," + BaseDn;
142 # Connect to the ldap server
144 l.simple_bind_s(UserDn,Password);
145 except ldap.INVALID_CREDENTIALS:
150 # Split up a name into multiple components. This tries to best guess how
153 Words = re.split(" ", Name.strip())
155 # Insert an empty middle name
156 if (len(Words) == 2):
161 # Put a dot after any 1 letter words, must be an initial
162 for x in range(0,len(Words)):
163 if len(Words[x]) == 1:
164 Words[x] = Words[x] + '.';
166 # If a word starts with a -, ( or [ we assume it marks the start of some
167 # Non-name information and remove the remainder of the string
168 for x in range(0,len(Words)):
169 if len(Words[x]) != 0 and (Words[x][0] == '-' or \
170 Words[x][0] == '(' or Words[x][0] == '['):
174 # Merge any of the middle initials
175 while len(Words) > 2 and len(Words[2]) == 2 and Words[2][1] == '.':
176 Words[1] = Words[1] + Words[2];
179 while len(Words) < 2:
182 # Merge any of the last name prefixes into one big last name
183 while LastNamesPre.has_key(Words[-2].lower()):
184 Words[-1] = Words[-2] + " " + Words[-1];
187 # Fix up a missing middle name after lastname globbing
188 if (len(Words) == 2):
191 # If the name is multi-word then we glob them all into the last name and
192 # do not worry about a middle name
194 Words[2] = " ".join(Words[1:])
197 return (Words[0].strip(), Words[1].strip(), Words[2].strip());
199 # Compute a random password using /dev/urandom
201 # Generate a 10 character random string
202 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
203 Rand = open("/dev/urandom");
205 for i in range(0,15):
206 Password = Password + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
209 # Compute the MD5 crypted version of the given password
210 def HashPass(Password):
211 # Hash it telling glibc to use the MD5 algorithm - if you dont have
212 # glibc then just change Salt = "$1$" to Salt = "";
213 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/.";
215 Rand = open("/dev/urandom");
216 for x in range(0,10):
217 Salt = Salt + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
218 Pass = crypt.crypt(Password,Salt);
220 raise "Password Error", "MD5 password hashing failed, not changing the password!";
223 # Sync with the server, we count the number of async requests that are pending
224 # and make sure result has been called that number of times
225 def FlushOutstanding(l,Outstanding,Fast=0):
226 # Sync with the remote end
228 print "Waiting for",Outstanding,"requests:",
229 while (Outstanding > 0):
231 if Fast == 0 or Outstanding > 50:
232 sys.stdout.write(".",);
234 if (l.result(ldap.RES_ANY,1) != (None,None)):
235 Outstanding = Outstanding - 1;
237 if (l.result(ldap.RES_ANY,1,0) != (None,None)):
238 Outstanding = Outstanding - 1;
241 except ldap.TYPE_OR_VALUE_EXISTS:
242 Outstanding = Outstanding - 1;
243 except ldap.NO_SUCH_ATTRIBUTE:
244 Outstanding = Outstanding - 1;
245 except ldap.NO_SUCH_OBJECT:
246 Outstanding = Outstanding - 1;
251 # Convert a lat/long attribute into Decimal degrees
252 def DecDegree(Posn,Anon=0):
253 Parts = re.match('[-+]?(\d*)\\.?(\d*)',Posn).groups();
256 if (abs(Val) >= 1806060.0):
257 raise ValueError,"Too Big";
260 if abs(Val) >= 18060.0 or len(Parts[0]) > 5:
262 Secs = Val - long(Val);
263 Val = long(Val)/100.0;
264 Min = Val - long(Val);
265 Val = long(Val) + (Min*100.0 + Secs*100.0/60.0)/60.0;
268 elif abs(Val) >= 180 or len(Parts[0]) > 3:
270 Min = Val - long(Val);
271 Val = long(Val) + Min*100.0/60.0;
281 def FormatSSH2Auth(Str):
282 Match = SSH2AuthSplit.match(Str);
284 return "<unknown format>";
288 return "ssh-%s %s..%s %s"%(G[1],G[2][:8],G[2][-8:],G[3]);
289 return "%s ssh-%s %s..%s %s"%(G[0],G[1],G[2][:8],G[2][-8:],G[3]);
291 def FormatSSHAuth(Str):
292 Match = SSHAuthSplit.match(Str);
294 return FormatSSH2Auth(Str);
299 return "%s %s %s..%s %s"%(G[1],G[2],G[3][:8],G[3][-8:],G[4]);
300 return "%s %s %s %s..%s %s"%(G[0],G[1],G[2],G[3][:8],G[3][-8:],G[4]);
302 def FormatPGPKey(Str):
308 while (I < len(Str)):
310 Res = "%s %s%s "%(Res,Str[I],Str[I+1]);
312 Res = "%s%s%s "%(Res,Str[I],Str[I+1]);
314 elif (len(Str) == 40):
317 while (I < len(Str)):
319 Res = "%s %s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
321 Res = "%s%s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
327 # Take an email address and split it into 3 parts, (Name,UID,Domain)
328 def SplitEmail(Addr):
329 # Is not an email address at all
330 if Addr.find('@') == -1:
333 Res1 = rfc822.AddrlistClass(Addr).getaddress();
338 return (Res1[0],"","");
340 # If there is no @ then the address was not parsed well. Try the alternate
341 # Parsing scheme. This is particularly important when scanning PGP keys.
342 Res2 = Res1[1].split("@");
344 Match = AddressSplit.match(Addr);
347 return Match.groups();
349 return (Res1[0],Res2[0],Res2[1]);
351 # Convert the PGP name string to a uid value. The return is a tuple of
352 # (uid,[message strings]). UnknownMpa is a hash from email to uid that
353 # overrides normal searching.
354 def GetUID(l,Name,UnknownMap = {}):
355 # Crack up the email address into a best guess first/middle/last name
356 (cn,mn,sn) = NameSplit(re.sub('["]','',Name[0]))
358 # Brackets anger the ldap searcher
359 cn = re.sub('[(")]','?',cn);
360 sn = re.sub('[(")]','?',sn);
362 # First check the unknown map for the email address
363 if UnknownMap.has_key(Name[1] + '@' + Name[2]):
364 Stat = "unknown map hit for "+str(Name);
365 return (UnknownMap[Name[1] + '@' + Name[2]],[Stat]);
367 # Then the cruft component (ie there was no email address to match)
368 if UnknownMap.has_key(Name[2]):
369 Stat = "unknown map hit for"+str(Name);
370 return (UnknownMap[Name[2]],[Stat]);
372 # Then the name component (another ie there was no email address to match)
373 if UnknownMap.has_key(Name[0]):
374 Stat = "unknown map hit for"+str(Name);
375 return (UnknownMap[Name[0]],[Stat]);
377 # Search for a possible first/last name hit
379 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(&(cn=%s)(sn=%s))"%(cn,sn),["uid"]);
380 except ldap.FILTER_ERROR:
381 Stat = "Filter failure: (&(cn=%s)(sn=%s))"%(cn,sn);
382 return (None,[Stat]);
384 # Try matching on the email address
385 if (len(Attrs) != 1):
387 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"emailforward=%s"%(Name[2]),["uid"]);
388 except ldap.FILTER_ERROR:
391 # Hmm, more than one/no return
392 if (len(Attrs) != 1):
393 # Key claims a local address
394 if Name[2] == EmailAppend:
396 # Pull out the record for the claimed user
397 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(uid=%s)"%(Name[1]),["uid","sn","cn"]);
399 # We require the UID surname to be someplace in the key name, this
400 # deals with special purpose keys like 'James Troup (Alternate Debian key)'
401 # Some people put their names backwards on their key too.. check that as well
402 if len(Attrs) == 1 and \
403 ( sn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 or \
404 cn.lower().find(Attrs[0][1]["sn"][0].lower()) != -1 ):
405 Stat = EmailAppend+" hit for "+str(Name);
406 return (Name[1],[Stat]);
408 # Attempt to give some best guess suggestions for use in editing the
410 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(sn~=%s)"%(sn),["uid","sn","cn"]);
414 Stat = ["None for %s"%(str(Name))];
416 Stat.append("But might be: %s %s <%s@debian.org>"%(x[1]["cn"][0],x[1]["sn"][0],x[1]["uid"][0]));
419 return (Attrs[0][1]["uid"][0],None);
423 def Group2GID(l, name):
425 Returns the numerical id of a common group
428 for g in DebianGroups.keys():
430 return DebianGroups[g]
432 filter = "(gid=%s)" % name
433 res = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,filter,["gidNumber"]);
435 return int(GetAttr(res[0], "gidNumber"))