0ea96a9571cc9ded039aab066544309236e29c30
[mirror/userdir-ldap.git] / userdir_ldap.py
1 # Some routines and configuration that are used by the ldap progams
2 import termios, TERMIOS, re, string, imp, ldap, sys, whrandom, crypt, rfc822;
3
4 try:
5    File = open("/etc/userdir-ldap/userdir-ldap.conf");
6 except:
7    File = open("userdir-ldap.conf");
8 ConfModule = imp.load_source("userdir_config","/etc/userdir-ldap.conf",File);
9 File.close();
10
11 # Cheap hack
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;
24
25 # This is a list of common last-name prefixes
26 LastNamesPre = {"van": None, "le": None, "de": None, "di": None};
27
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+) (.+)$');
32
33 AddressSplit = re.compile("(.*).*<([^@]*)@([^>]*)>");
34
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 = ""):
38    try:
39       return DnRecord[1][Attribute][0];
40    except IndexError:
41       return Default;
42    except KeyError:
43       return Default;
44    return Default;
45
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 + ">"
54
55 # Show a dump like ldapsearch
56 def PrettyShow(DnRecord):
57    Result = "";
58    List = DnRecord[1].keys();
59    List.sort();
60    for x in List:
61       Rec = DnRecord[1][x];
62       for i in Rec:
63          Result = Result + "%s: %s\n" % (x,i);
64    return Result[:-1];
65
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
73    try:
74       termios.tcsetattr(fd, TERMIOS.TCSADRAIN, new);
75       passwd = raw_input(prompt);
76    finally:
77       termios.tcsetattr(fd, TERMIOS.TCSADRAIN, old);
78    print;
79    return passwd;
80
81 # Split up a name into multiple components. This tries to best guess how
82 # to split up a name
83 def NameSplit(Name):
84    Words = re.split(" ",string.strip(Name));
85
86    # Insert an empty middle name
87    if (len(Words) == 2):
88       Words.insert(1,"");
89    if (len(Words) < 2):
90       Words.append("");
91
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] + '.';
96
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] == '['):
102          Words = Words[0:x];
103          break;
104          
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];
108       del Words[2];
109
110    while len(Words) < 2:
111       Words.append('');
112    
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];
116       del Words[-2];
117
118    # Fix up a missing middle name after lastname globbing
119    if (len(Words) == 2):
120       Words.insert(1,"");
121
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
124    if (len(Words) > 3):
125       Words[2] = string.join(Words[1:]);
126       Words[1] = "";
127
128    return (string.strip(Words[0]),string.strip(Words[1]),string.strip(Words[2]));
129
130 # Compute a random password using /dev/urandom
131 def GenPass():   
132    # Generate a 10 character random string
133    SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
134    Rand = open("/dev/urandom");
135    Password = "";
136    for i in range(0,10):
137       Password = Password + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
138    return Password;
139
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/.";
145    Salt  = "$1$";
146    for x in range(0,10):
147       Salt = Salt + SaltVals[whrandom.randint(0,len(SaltVals)-1)];
148    Pass = crypt.crypt(Password,Salt);
149    if len(Pass) < 14:
150       raise "Password Error", "MD5 password hashing failed, not changing the password!";
151    return Pass;
152
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
157    if Fast == 0:
158       print "Waiting for",Outstanding,"requests:",
159    while (Outstanding > 0):
160       try:
161          if Fast == 0 or Outstanding > 50:
162             sys.stdout.write(".",);
163             sys.stdout.flush();
164             if (l.result(ldap.RES_ANY,1) != (None,None)):
165                Outstanding = Outstanding - 1;
166          else:
167             if (l.result(ldap.RES_ANY,1,0) != (None,None)):
168                Outstanding = Outstanding - 1;
169             else:
170                break;
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;
177    if Fast == 0:
178       print;
179    return Outstanding;
180
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);
185
186   if (abs(Val) >= 1806060.0):
187      raise ValueError,"Too Big";
188
189   # Val is in DGMS
190   if abs(Val) >= 18060.0 or len(Parts[0]) > 5:
191      Val = Val/100.0;
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;
196
197   # Val is in DGM
198   elif abs(Val) >= 180 or len(Parts[0]) > 3:
199      Val = Val/100.0;
200      Min = Val - long(Val);
201      Val = long(Val) + Min*100.0/60.0;
202      
203   if Anon != 0:
204       Str = "%3.2f"%(Val);
205   else:
206       Str = str(Val);
207   if Val >= 0:
208      return "+" + Str;
209   return Str;
210
211 def FormatSSHAuth(Str):
212    Match = SSHAuthSplit.match(Str);
213    if Match == None:
214       return "<unknown format>";
215    G = Match.groups();
216
217    # No options
218    if G[0] == None:
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]);
221
222 def FormatPGPKey(Str):
223    Res = "";
224
225    # PGP 2.x Print
226    if (len(Str) == 32):
227       I = 0;
228       while (I < len(Str)):
229          if I+2 == 32/2:
230             Res = "%s %s%s "%(Res,Str[I],Str[I+1]);
231          else:
232             Res = "%s%s%s "%(Res,Str[I],Str[I+1]);
233          I = I + 2;
234    elif (len(Str) == 40):
235       # OpenPGP Print
236       I = 0;
237       while (I < len(Str)):
238          if I+4 == 40/2:
239             Res = "%s %s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
240          else:
241             Res = "%s%s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
242          I = I + 4;
243    else:
244       Res = Str;
245    return string.strip(Res);
246
247 # Take an email address and split it into 3 parts, (Name,UID,Domain)
248 def SplitEmail(Addr):
249    Res1 = rfc822.AddrlistClass(Addr).getaddress();
250    if len(Res1) != 1:
251       return ("","",Addr);
252    Res1 = Res1[0];
253    if Res1[1] == None:
254       return (Res1[0],"","");
255
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],"@");
259    if len(Res2) != 2:
260       Match = AddressSplit.match(Addr);
261       if Match == None:
262          return ("","",Addr);
263       return Match.groups();
264
265    return (Res1[0],Res2[0],Res2[1]);
266
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]))
273    
274    # Brackets anger the ldap searcher
275    cn = re.sub('[(")]','?',cn);
276    sn = re.sub('[(")]','?',sn);
277
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]);
282
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]);
287
288    # Search for a possible first/last name hit
289    try:
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]);
294
295    # Try matching on the email address
296    if (len(Attrs) != 1):
297       try:
298          Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"emailforward=%s"%(Name[2]),["uid"]);
299       except ldap.FILTER_ERROR:
300          pass;
301
302    # Hmm, more than one/no return
303    if (len(Attrs) != 1):
304       # Key claims a local address
305       if Name[2] == EmailAppend:
306
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"]);
309
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]);
318
319       # Attempt to give some best guess suggestions for use in editing the
320       # override file.
321       Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"(sn~=%s)"%(sn),["uid","sn","cn"]);
322
323       Stat = [];
324       if len(Attrs) != 0:
325          Stat = ["None for %s"%(str(Name))];
326       for x in Attrs:
327          Stat.append("But might be: %s %s <%s@debian.org>"%(x[1]["cn"][0],x[1]["sn"][0],x[1]["uid"][0]));
328       return (None,Stat);        
329    else:
330       return (Attrs[0][1]["uid"][0],None);
331
332    return (None,None);
333
334