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