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