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