1 # Some routines and configuration that are used by the ldap progams
2 import termios, TERMIOS, re, string, imp, ldap, sys, whrandom, crypt, rfc822;
5 File = open("/etc/userdir-ldap/userdir-ldap.conf");
7 File = open("userdir-ldap.conf");
8 ConfModule = imp.load_source("userdir_config","/etc/userdir-ldap.conf",File);
12 BaseDn = ConfModule.basedn;
13 BaseDn = ConfModule.basedn;
14 LDAPServer = ConfModule.ldaphost;
15 EmailAppend = ConfModule.emailappend;
16 AdminUser = ConfModule.adminuser;
17 GenerateDir = ConfModule.generatedir;
18 GenerateConf = ConfModule.generateconf;
19 DefaultGID = ConfModule.defaultgid;
20 TemplatesDir = ConfModule.templatesdir;
21 PassDir = ConfModule.passdir;
22 Ech_ErrorLog = ConfModule.ech_errorlog;
23 Ech_MainLog = ConfModule.ech_mainlog;
25 # This is a list of common last-name prefixes
26 LastNamesPre = {"van": None, "le": None, "de": None, "di": None};
28 # SSH Key splitting. The result is:
29 # (options,size,modulous,exponent,comment)
30 SSHAuthSplit = re.compile('^(.* )?(\d+) (\d+) (\d+) ?(.+)$');
31 #'^([^\d](?:[^ "]+(?:".*")?)*)? ?(\d+) (\d+) (\d+) (.+)$');
33 AddressSplit = re.compile("(.*).*<([^@]*)@([^>]*)>");
35 # Safely get an attribute from a tuple representing a dn and an attribute
36 # list. It returns the first attribute if there are multi.
37 def GetAttr(DnRecord,Attribute,Default = ""):
39 return DnRecord[1][Attribute][0];
46 # Return a printable email address from the attributes.
47 def EmailAddress(DnRecord):
48 cn = GetAttr(DnRecord,"cn");
49 sn = GetAttr(DnRecord,"sn");
50 uid = GetAttr(DnRecord,"uid");
51 if cn == "" and sn == "":
52 return "<" + uid + "@" + EmailAppend + ">";
53 return cn + " " + sn + " <" + uid + "@" + EmailAppend + ">"
55 # Show a dump like ldapsearch
56 def PrettyShow(DnRecord):
58 List = DnRecord[1].keys();
63 Result = Result + "%s: %s\n" % (x,i);
66 # Function to prompt for a password
67 def getpass(prompt = "Password: "):
68 import termios, TERMIOS, sys;
69 fd = sys.stdin.fileno();
70 old = termios.tcgetattr(fd);
71 new = termios.tcgetattr(fd);
72 new[3] = new[3] & ~TERMIOS.ECHO; # lflags
74 termios.tcsetattr(fd, TERMIOS.TCSADRAIN, new);
75 passwd = raw_input(prompt);
77 termios.tcsetattr(fd, TERMIOS.TCSADRAIN, old);
81 # Split up a name into multiple components. This tries to best guess how
84 Words = re.split(" ",string.strip(Name));
86 # Insert an empty middle name
92 # Put a dot after any 1 letter words, must be an initial
93 for x in range(0,len(Words)):
94 if len(Words[x]) == 1:
95 Words[x] = Words[x] + '.';
97 # If a word starts with a -, ( or [ we assume it marks the start of some
98 # Non-name information and remove the remainder of the string
99 for x in range(0,len(Words)):
100 if len(Words[x]) != 0 and (Words[x][0] == '-' or \
101 Words[x][0] == '(' or Words[x][0] == '['):
105 # Merge any of the middle initials
106 while len(Words) > 2 and len(Words[2]) == 2 and Words[2][1] == '.':
107 Words[1] = Words[1] + Words[2];
110 while len(Words) < 2:
113 # Merge any of the last name prefixes into one big last name
114 while LastNamesPre.has_key(string.lower(Words[-2])):
115 Words[-1] = Words[-2] + " " + Words[-1];
118 # Fix up a missing middle name after lastname globbing
119 if (len(Words) == 2):
122 # If the name is multi-word then we glob them all into the last name and
123 # do not worry about a middle name
125 Words[2] = string.join(Words[1:]);
128 return (string.strip(Words[0]),string.strip(Words[1]),string.strip(Words[2]));
130 # Compute a random password using /dev/urandom
132 # Generate a 10 character random string
133 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
134 Rand = open("/dev/urandom");
136 for i in range(0,10):
137 Password = Password + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
140 # Compute the MD5 crypted version of the given password
141 def HashPass(Password):
142 # Hash it telling glibc to use the MD5 algorithm - if you dont have
143 # glibc then just change Salt = "$1$" to Salt = "";
144 SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
146 for x in range(0,10):
147 Salt = Salt + SaltVals[whrandom.randint(0,len(SaltVals)-1)];
148 Pass = crypt.crypt(Password,Salt);
150 raise "Password Error", "MD5 password hashing failed, not changing the password!";
153 # Sync with the server, we count the number of async requests that are pending
154 # and make sure result has been called that number of times
155 def FlushOutstanding(l,Outstanding,Fast=0):
156 # Sync with the remote end
158 print "Waiting for",Outstanding,"requests:",
159 while (Outstanding > 0):
161 if Fast == 0 or Outstanding > 50:
162 sys.stdout.write(".",);
164 if (l.result(ldap.RES_ANY,1) != (None,None)):
165 Outstanding = Outstanding - 1;
167 if (l.result(ldap.RES_ANY,1,0) != (None,None)):
168 Outstanding = Outstanding - 1;
171 except ldap.TYPE_OR_VALUE_EXISTS:
172 Outstanding = Outstanding - 1;
173 except ldap.NO_SUCH_ATTRIBUTE:
174 Outstanding = Outstanding - 1;
175 except ldap.NO_SUCH_OBJECT:
176 Outstanding = Outstanding - 1;
181 # Convert a lat/long attribute into Decimal degrees
182 def DecDegree(Posn,Anon=0):
183 Parts = re.match('[+-]?(\d*)\\.?(\d*)?',Posn).groups();
184 Val = string.atof(Posn);
186 if (abs(Val) >= 1806060.0):
187 raise ValueError,"Too Big";
190 if abs(Val) >= 18060.0 or len(Parts[0]) > 5:
192 Secs = Val - long(Val);
193 Val = long(Val)/100.0;
194 Min = Val - long(Val);
195 Val = long(Val) + (Min*100.0 + Secs*100.0/60.0)/60.0;
198 elif abs(Val) >= 180 or len(Parts[0]) > 3:
200 Min = Val - long(Val);
201 Val = long(Val) + Min*100.0/60.0;
211 def FormatSSHAuth(Str):
212 Match = SSHAuthSplit.match(Str);
214 return "<unknown format>";
219 return "%s %s %s..%s %s"%(G[1],G[2],G[3][:8],G[3][-8:],G[4]);
220 return "%s %s %s %s..%s %s"%(G[0],G[1],G[2],G[3][:8],G[3][-8:],G[4]);
222 def FormatPGPKey(Str):
228 while (I < len(Str)):
230 Res = "%s %s%s "%(Res,Str[I],Str[I+1]);
232 Res = "%s%s%s "%(Res,Str[I],Str[I+1]);
234 elif (len(Str) == 40):
237 while (I < len(Str)):
239 Res = "%s %s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
241 Res = "%s%s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
245 return string.strip(Res);
247 # Take an email address and split it into 3 parts, (Name,UID,Domain)
248 def SplitEmail(Addr):
249 Res1 = rfc822.AddrlistClass(Addr).getaddress();
254 return (Res1[0],"","");
256 # If there is no @ then the address was not parsed well. Try the alternate
257 # Parsing scheme. This is particularly important when scanning PGP keys.
258 Res2 = string.split(Res1[1],"@");
260 Match = AddressSplit.match(Addr);
263 return Match.groups();
265 return (Res1[0],Res2[0],Res2[1]);
267 # Convert the PGP name string to a uid value. The return is a tuple of
268 # (uid,[message strings]). UnknownMpa is a hash from email to uid that
269 # overrides normal searching.
270 def GetUID(l,Name,UnknownMap = {}):
271 # Crack up the email address into a best guess first/middle/last name
272 (cn,mn,sn) = NameSplit(re.sub('["]','',Name[0]))
274 # Brackets anger the ldap searcher
275 cn = re.sub('[(")]','?',cn);
276 sn = re.sub('[(")]','?',sn);
278 # First check the unknown map for the email address
279 if UnknownMap.has_key(Name[1] + '@' + Name[2]):
280 Stat = "unknown map hit for "+str(Name);
281 return (UnknownMap[Name[1] + '@' + Name[2]],[Stat]);
283 # Then the cruft component (ie there was no email address to match)
284 if UnknownMap.has_key(Name[2]):
285 Stat = "unknown map hit for"+str(Name);
286 return (UnknownMap[Name[2]],[Stat]);
288 # Search for a possible first/last name hit
290 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(&(cn=%s)(sn=%s))"%(cn,sn),["uid"]);
291 except ldap.FILTER_ERROR:
292 Stat = "Filter failure: (&(cn=%s)(sn=%s))"%(cn,sn);
293 return (None,[Stat]);
295 # Try matching on the email address
296 if (len(Attrs) != 1):
298 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"emailforward=%s"%(Name[2]),["uid"]);
299 except ldap.FILTER_ERROR:
302 # Hmm, more than one/no return
303 if (len(Attrs) != 1):
304 # Key claims a local address
305 if Name[2] == EmailAppend:
307 # Pull out the record for the claimed user
308 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(uid=%s)"%(Name[1]),["uid","sn","cn"]);
310 # We require the UID surname to be someplace in the key name, this
311 # deals with special purpose keys like 'James Troup (Alternate Debian key)'
312 # Some people put their names backwards on their key too.. check that as well
313 if len(Attrs) == 1 and \
314 (string.find(string.lower(sn),string.lower(Attrs[0][1]["sn"][0])) != -1 or \
315 string.find(string.lower(cn),string.lower(Attrs[0][1]["sn"][0])) != -1):
316 Stat = EmailAppend+" hit for "+str(Name);
317 return (Name[1],[Stat]);
319 # Attempt to give some best guess suggestions for use in editing the
321 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(sn~=%s)"%(sn),["uid","sn","cn"]);
325 Stat = ["None for %s"%(str(Name))];
327 Stat.append("But might be: %s %s <%s@debian.org>"%(x[1]["cn"][0],x[1]["sn"][0],x[1]["uid"][0]));
330 return (Attrs[0][1]["uid"][0],None);