Added a routine to convert common Debian groups into numerical ids.
[mirror/userdir-ldap.git] / userdir_ldap.py
1 # Some routines and configuration that are used by the ldap progams
2 import termios, re, string, imp, ldap, sys, whrandom, crypt, rfc822;
3 import userdir_gpg
4
5 try:
6    File = open("/etc/userdir-ldap/userdir-ldap.conf");
7 except:
8    File = open("userdir-ldap.conf");
9 ConfModule = imp.load_source("userdir_config","/etc/userdir-ldap.conf",File);
10 File.close();
11
12 # Cheap hack
13 BaseDn = ConfModule.basedn;
14 HostBaseDn = ConfModule.hostbasedn;
15 LDAPServer = ConfModule.ldaphost;
16 EmailAppend = ConfModule.emailappend;
17 AdminUser = ConfModule.adminuser;
18 GenerateDir = ConfModule.generatedir;
19 GenerateConf = ConfModule.generateconf;
20 DefaultGID = ConfModule.defaultgid;
21 TemplatesDir = ConfModule.templatesdir;
22 PassDir = ConfModule.passdir;
23 Ech_ErrorLog = ConfModule.ech_errorlog;
24 Ech_MainLog = ConfModule.ech_mainlog;
25
26 # Break up the keyring list
27 userdir_gpg.SetKeyrings(string.split(ConfModule.keyrings,":"));
28
29 # This is a list of common last-name prefixes
30 LastNamesPre = {"van": None, "von": None, "le": None, "de": None, "di": None};
31
32 # This is a list of common groups on Debian hosts
33 DebianGroups = {"Debian": 800, "guest": 60000}
34
35 # SSH Key splitting. The result is:
36 # (options,size,modulous,exponent,comment)
37 SSHAuthSplit = re.compile('^(.* )?(\d+) (\d+) (\d+) ?(.+)$');
38 SSH2AuthSplit = re.compile('^(.* )?ssh-(dss|rsa) ([a-zA-Z0-9=/+]+) ?(.+)$');
39 #'^([^\d](?:[^ "]+(?:".*")?)*)? ?(\d+) (\d+) (\d+) (.+)$');
40
41 AddressSplit = re.compile("(.*).*<([^@]*)@([^>]*)>");
42
43 # Safely get an attribute from a tuple representing a dn and an attribute
44 # list. It returns the first attribute if there are multi.
45 def GetAttr(DnRecord,Attribute,Default = ""):
46    try:
47       return DnRecord[1][Attribute][0];
48    except IndexError:
49       return Default;
50    except KeyError:
51       return Default;
52    return Default;
53
54 # Return a printable email address from the attributes.
55 def EmailAddress(DnRecord):
56    cn = GetAttr(DnRecord,"cn");
57    sn = GetAttr(DnRecord,"sn");
58    uid = GetAttr(DnRecord,"uid");
59    if cn == "" and sn == "":
60       return "<" + uid + "@" + EmailAppend + ">";
61    return cn + " " + sn + " <" + uid + "@" + EmailAppend + ">"
62
63 # Show a dump like ldapsearch
64 def PrettyShow(DnRecord):
65    Result = "";
66    List = DnRecord[1].keys();
67    List.sort();
68    for x in List:
69       Rec = DnRecord[1][x];
70       for i in Rec:
71          Result = Result + "%s: %s\n" % (x,i);
72    return Result[:-1];
73
74 # Function to prompt for a password 
75 def getpass(prompt = "Password: "):
76    import termios, sys;
77    fd = sys.stdin.fileno();
78    old = termios.tcgetattr(fd);
79    new = termios.tcgetattr(fd);
80    new[3] = new[3] & ~termios.ECHO;          # lflags
81    try:
82       termios.tcsetattr(fd, termios.TCSADRAIN, new);
83       passwd = raw_input(prompt);
84    finally:
85       termios.tcsetattr(fd, termios.TCSADRAIN, old);
86    print;
87    return passwd;
88
89 # Split up a name into multiple components. This tries to best guess how
90 # to split up a name
91 def NameSplit(Name):
92    Words = re.split(" ",string.strip(Name));
93
94    # Insert an empty middle name
95    if (len(Words) == 2):
96       Words.insert(1,"");
97    if (len(Words) < 2):
98       Words.append("");
99
100    # Put a dot after any 1 letter words, must be an initial
101    for x in range(0,len(Words)):
102       if len(Words[x]) == 1:
103          Words[x] = Words[x] + '.';
104
105    # If a word starts with a -, ( or [ we assume it marks the start of some
106    # Non-name information and remove the remainder of the string
107    for x in range(0,len(Words)):
108       if len(Words[x]) != 0 and (Words[x][0] == '-' or \
109           Words[x][0] == '(' or Words[x][0] == '['):
110          Words = Words[0:x];
111          break;
112          
113    # Merge any of the middle initials
114    while len(Words) > 2 and len(Words[2]) == 2 and Words[2][1] == '.':
115       Words[1] = Words[1] +  Words[2];
116       del Words[2];
117
118    while len(Words) < 2:
119       Words.append('');
120    
121    # Merge any of the last name prefixes into one big last name
122    while LastNamesPre.has_key(string.lower(Words[-2])):
123       Words[-1] = Words[-2] + " " + Words[-1];
124       del Words[-2];
125
126    # Fix up a missing middle name after lastname globbing
127    if (len(Words) == 2):
128       Words.insert(1,"");
129
130    # If the name is multi-word then we glob them all into the last name and
131    # do not worry about a middle name
132    if (len(Words) > 3):
133       Words[2] = string.join(Words[1:]);
134       Words[1] = "";
135
136    return (string.strip(Words[0]),string.strip(Words[1]),string.strip(Words[2]));
137
138 # Compute a random password using /dev/urandom
139 def GenPass():   
140    # Generate a 10 character random string
141    SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
142    Rand = open("/dev/urandom");
143    Password = "";
144    for i in range(0,15):
145       Password = Password + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
146    return Password;
147
148 # Compute the MD5 crypted version of the given password
149 def HashPass(Password):
150    # Hash it telling glibc to use the MD5 algorithm - if you dont have
151    # glibc then just change Salt = "$1$" to Salt = "";
152    SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789/.";
153    Salt  = "$1$";
154    Rand = open("/dev/urandom");
155    for x in range(0,10):
156       Salt = Salt + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
157    Pass = crypt.crypt(Password,Salt);
158    if len(Pass) < 14:
159       raise "Password Error", "MD5 password hashing failed, not changing the password!";
160    return Pass;
161
162 # Sync with the server, we count the number of async requests that are pending
163 # and make sure result has been called that number of times
164 def FlushOutstanding(l,Outstanding,Fast=0):
165    # Sync with the remote end
166    if Fast == 0:
167       print "Waiting for",Outstanding,"requests:",
168    while (Outstanding > 0):
169       try:
170          if Fast == 0 or Outstanding > 50:
171             sys.stdout.write(".",);
172             sys.stdout.flush();
173             if (l.result(ldap.RES_ANY,1) != (None,None)):
174                Outstanding = Outstanding - 1;
175          else:
176             if (l.result(ldap.RES_ANY,1,0) != (None,None)):
177                Outstanding = Outstanding - 1;
178             else:
179                break;
180       except ldap.TYPE_OR_VALUE_EXISTS:
181          Outstanding = Outstanding - 1;
182       except ldap.NO_SUCH_ATTRIBUTE:
183          Outstanding = Outstanding - 1;
184       except ldap.NO_SUCH_OBJECT:
185          Outstanding = Outstanding - 1;
186    if Fast == 0:
187       print;
188    return Outstanding;
189
190 # Convert a lat/long attribute into Decimal degrees
191 def DecDegree(Posn,Anon=0):
192   Parts = re.match('[-+]?(\d*)\\.?(\d*)',Posn).groups();
193   Val = string.atof(Posn);
194
195   if (abs(Val) >= 1806060.0):
196      raise ValueError,"Too Big";
197
198   # Val is in DGMS
199   if abs(Val) >= 18060.0 or len(Parts[0]) > 5:
200      Val = Val/100.0;
201      Secs = Val - long(Val);
202      Val = long(Val)/100.0;
203      Min = Val - long(Val);
204      Val = long(Val) + (Min*100.0 + Secs*100.0/60.0)/60.0;
205
206   # Val is in DGM
207   elif abs(Val) >= 180 or len(Parts[0]) > 3:
208      Val = Val/100.0;
209      Min = Val - long(Val);
210      Val = long(Val) + Min*100.0/60.0;
211      
212   if Anon != 0:
213       Str = "%3.2f"%(Val);
214   else:
215       Str = str(Val);
216   if Val >= 0:
217      return "+" + Str;
218   return Str;
219
220 def FormatSSH2Auth(Str):
221    Match = SSH2AuthSplit.match(Str);
222    if Match == None:
223       return "<unknown format>";
224    G = Match.groups();
225
226    if G[0] == None:
227       return "ssh-%s %s..%s %s"%(G[1],G[2][:8],G[2][-8:],G[3]);
228    return "%s ssh-%s %s..%s %s"%(G[0],G[1],G[2][:8],G[2][-8:],G[3]);
229
230 def FormatSSHAuth(Str):
231    Match = SSHAuthSplit.match(Str);
232    if Match == None:
233       return FormatSSH2Auth(Str);
234    G = Match.groups();
235
236    # No options
237    if G[0] == None:
238       return "%s %s %s..%s %s"%(G[1],G[2],G[3][:8],G[3][-8:],G[4]);
239    return "%s %s %s %s..%s %s"%(G[0],G[1],G[2],G[3][:8],G[3][-8:],G[4]);
240
241 def FormatPGPKey(Str):
242    Res = "";
243
244    # PGP 2.x Print
245    if (len(Str) == 32):
246       I = 0;
247       while (I < len(Str)):
248          if I+2 == 32/2:
249             Res = "%s %s%s "%(Res,Str[I],Str[I+1]);
250          else:
251             Res = "%s%s%s "%(Res,Str[I],Str[I+1]);
252          I = I + 2;
253    elif (len(Str) == 40):
254       # OpenPGP Print
255       I = 0;
256       while (I < len(Str)):
257          if I+4 == 40/2:
258             Res = "%s %s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
259          else:
260             Res = "%s%s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
261          I = I + 4;
262    else:
263       Res = Str;
264    return string.strip(Res);
265
266 # Take an email address and split it into 3 parts, (Name,UID,Domain)
267 def SplitEmail(Addr):
268    # Is not an email address at all
269    if string.find(Addr,'@') == -1:
270       return (Addr,"","");
271   
272    Res1 = rfc822.AddrlistClass(Addr).getaddress();
273    if len(Res1) != 1:
274       return ("","",Addr);
275    Res1 = Res1[0];
276    if Res1[1] == None:
277       return (Res1[0],"","");
278
279    # If there is no @ then the address was not parsed well. Try the alternate
280    # Parsing scheme. This is particularly important when scanning PGP keys.
281    Res2 = string.split(Res1[1],"@");
282    if len(Res2) != 2:
283       Match = AddressSplit.match(Addr);
284       if Match == None:
285          return ("","",Addr);
286       return Match.groups();
287
288    return (Res1[0],Res2[0],Res2[1]);
289
290 # Convert the PGP name string to a uid value. The return is a tuple of
291 # (uid,[message strings]). UnknownMpa is a hash from email to uid that 
292 # overrides normal searching.
293 def GetUID(l,Name,UnknownMap = {}):
294    # Crack up the email address into a best guess first/middle/last name
295    (cn,mn,sn) = NameSplit(re.sub('["]','',Name[0]))
296    
297    # Brackets anger the ldap searcher
298    cn = re.sub('[(")]','?',cn);
299    sn = re.sub('[(")]','?',sn);
300
301    # First check the unknown map for the email address
302    if UnknownMap.has_key(Name[1] + '@' + Name[2]):
303       Stat = "unknown map hit for "+str(Name);
304       return (UnknownMap[Name[1] + '@' + Name[2]],[Stat]);
305
306    # Then the cruft component (ie there was no email address to match)
307    if UnknownMap.has_key(Name[2]):
308       Stat = "unknown map hit for"+str(Name);
309       return (UnknownMap[Name[2]],[Stat]);
310
311    # Then the name component (another ie there was no email address to match)
312    if UnknownMap.has_key(Name[0]):
313       Stat = "unknown map hit for"+str(Name);
314       return (UnknownMap[Name[0]],[Stat]);
315   
316    # Search for a possible first/last name hit
317    try:
318       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(&(cn=%s)(sn=%s))"%(cn,sn),["uid"]);
319    except ldap.FILTER_ERROR:
320       Stat = "Filter failure: (&(cn=%s)(sn=%s))"%(cn,sn);
321       return (None,[Stat]);
322
323    # Try matching on the email address
324    if (len(Attrs) != 1):
325       try:
326          Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"emailforward=%s"%(Name[2]),["uid"]);
327       except ldap.FILTER_ERROR:
328          pass;
329
330    # Hmm, more than one/no return
331    if (len(Attrs) != 1):
332       # Key claims a local address
333       if Name[2] == EmailAppend:
334
335          # Pull out the record for the claimed user
336          Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(uid=%s)"%(Name[1]),["uid","sn","cn"]);
337
338          # We require the UID surname to be someplace in the key name, this
339          # deals with special purpose keys like 'James Troup (Alternate Debian key)'
340          # Some people put their names backwards on their key too.. check that as well
341          if len(Attrs) == 1 and \
342             (string.find(string.lower(sn),string.lower(Attrs[0][1]["sn"][0])) != -1 or \
343             string.find(string.lower(cn),string.lower(Attrs[0][1]["sn"][0])) != -1):
344             Stat = EmailAppend+" hit for "+str(Name);
345             return (Name[1],[Stat]);
346
347       # Attempt to give some best guess suggestions for use in editing the
348       # override file.
349       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(sn~=%s)"%(sn),["uid","sn","cn"]);
350
351       Stat = [];
352       if len(Attrs) != 0:
353          Stat = ["None for %s"%(str(Name))];
354       for x in Attrs:
355          Stat.append("But might be: %s %s <%s@debian.org>"%(x[1]["cn"][0],x[1]["sn"][0],x[1]["uid"][0]));
356       return (None,Stat);        
357    else:
358       return (Attrs[0][1]["uid"][0],None);
359
360    return (None,None);
361
362 def Group2GID(name):
363    """Returns the numerical id of a common group"""
364    for g in DebianGroups.keys():
365       if name == g:
366          return DebianGroups[g]
367    return name