Echelon
[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 # Safely get an attribute from a tuple representing a dn and an attribute
34 # list. It returns the first attribute if there are multi.
35 def GetAttr(DnRecord,Attribute,Default = ""):
36    try:
37       return DnRecord[1][Attribute][0];
38    except IndexError:
39       return Default;
40    except KeyError:
41       return Default;
42    return Default;
43
44 # Return a printable email address from the attributes.
45 def EmailAddress(DnRecord):
46    cn = GetAttr(DnRecord,"cn");
47    sn = GetAttr(DnRecord,"sn");
48    uid = GetAttr(DnRecord,"uid");
49    if cn == "" and sn == "":
50       return "<" + uid + "@" + EmailAppend + ">";
51    return cn + " " + sn + " <" + uid + "@" + EmailAppend + ">"
52
53 # Show a dump like ldapsearch
54 def PrettyShow(DnRecord):
55    Result = "";
56    List = DnRecord[1].keys();
57    List.sort();
58    for x in List:
59       Rec = DnRecord[1][x];
60       for i in Rec:
61          Result = Result + "%s: %s\n" % (x,i);
62    return Result[:-1];
63
64 # Function to prompt for a password 
65 def getpass(prompt = "Password: "):
66    import termios, TERMIOS, sys;
67    fd = sys.stdin.fileno();
68    old = termios.tcgetattr(fd);
69    new = termios.tcgetattr(fd);
70    new[3] = new[3] & ~TERMIOS.ECHO;          # lflags
71    try:
72       termios.tcsetattr(fd, TERMIOS.TCSADRAIN, new);
73       passwd = raw_input(prompt);
74    finally:
75       termios.tcsetattr(fd, TERMIOS.TCSADRAIN, old);
76    print;
77    return passwd;
78
79 # Split up a name into multiple components. This tries to best guess how
80 # to split up a name
81 def NameSplit(Name):
82    Words = re.split(" ",string.strip(Name));
83
84    # Insert an empty middle name
85    if (len(Words) == 2):
86       Words.insert(1,"");
87    if (len(Words) < 2):
88       Words.append("");
89
90    # Put a dot after any 1 letter words, must be an initial
91    for x in range(0,len(Words)):
92       if len(Words[x]) == 1:
93          Words[x] = Words[x] + '.';
94
95    # If a word starts with a -, ( or [ we assume it marks the start of some
96    # Non-name information and remove the remainder of the string
97    for x in range(0,len(Words)):
98       if len(Words[x]) != 0 and (Words[x][0] == '-' or \
99           Words[x][0] == '(' or Words[x][0] == '['):
100          Words = Words[0:x];
101          break;
102          
103    # Merge any of the middle initials
104    if len(Words) > 2:
105       while len(Words[2]) == 2 and Words[2][1] == '.':
106          Words[1] = Words[1] +  Words[2];
107          del Words[2];
108
109    while len(Words) < 2:
110       Words.append('');
111    
112    # Merge any of the last name prefixes into one big last name
113    while LastNamesPre.has_key(string.lower(Words[-2])):
114       Words[-1] = Words[-2] + " " + Words[-1];
115       del Words[-2];
116
117    # Fix up a missing middle name after lastname globbing
118    if (len(Words) == 2):
119       Words.insert(1,"");
120
121    # If the name is multi-word then we glob them all into the last name and
122    # do not worry about a middle name
123    if (len(Words) > 3):
124       Words[2] = string.join(Words[1:]);
125       Words[1] = "";
126
127    return (string.strip(Words[0]),string.strip(Words[1]),string.strip(Words[2]));
128
129 # Compute a random password using /dev/urandom
130 def GenPass():   
131    # Generate a 10 character random string
132    SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
133    Rand = open("/dev/urandom");
134    Password = "";
135    for i in range(0,10):
136       Password = Password + SaltVals[ord(Rand.read(1)[0]) % len(SaltVals)];
137    return Password;
138
139 # Compute the MD5 crypted version of the given password
140 def HashPass(Password):
141    # Hash it telling glibc to use the MD5 algorithm - if you dont have
142    # glibc then just change Salt = "$1$" to Salt = "";
143    SaltVals = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.";
144    Salt  = "$1$";
145    for x in range(0,10):
146       Salt = Salt + SaltVals[whrandom.randint(0,len(SaltVals)-1)];
147    Pass = crypt.crypt(Password,Salt);
148    if len(Pass) < 14:
149       raise "Password Error", "MD5 password hashing failed, not changing the password!";
150    return Pass;
151
152 # Sync with the server, we count the number of async requests that are pending
153 # and make sure result has been called that number of times
154 def FlushOutstanding(l,Outstanding,Fast=0):
155    # Sync with the remote end
156    if Fast == 0:
157       print "Waiting for",Outstanding,"requests:",
158    while (Outstanding > 0):
159       try:
160          if Fast == 0 or Outstanding > 50:
161             sys.stdout.write(".",);
162             sys.stdout.flush();
163             if (l.result(ldap.RES_ANY,1) != (None,None)):
164                Outstanding = Outstanding - 1;
165          else:
166             if (l.result(ldap.RES_ANY,1,0) != (None,None)):
167                Outstanding = Outstanding - 1;
168             else:
169                break;
170       except ldap.TYPE_OR_VALUE_EXISTS:
171          Outstanding = Outstanding - 1;
172       except ldap.NO_SUCH_ATTRIBUTE:
173          Outstanding = Outstanding - 1;
174       except ldap.NO_SUCH_OBJECT:
175          Outstanding = Outstanding - 1;
176    if Fast == 0:
177       print;
178    return Outstanding;
179
180 # Convert a lat/long attribute into Decimal degrees
181 def DecDegree(Posn,Anon=0):
182   Parts = re.match('[+-]?(\d*)\\.?(\d*)?',Posn).groups();
183   Val = string.atof(Posn);
184
185   if (abs(Val) >= 1806060.0):
186      raise ValueError,"Too Big";
187
188   # Val is in DGMS
189   if abs(Val) >= 18060.0 or len(Parts[0]) > 5:
190      Val = Val/100.0;
191      Secs = Val - long(Val);
192      Val = long(Val)/100.0;
193      Min = Val - long(Val);
194      Val = long(Val) + (Min*100.0 + Secs*100.0/60.0)/60.0;
195
196   # Val is in DGM
197   elif abs(Val) >= 180 or len(Parts[0]) > 3:
198      Val = Val/100.0;
199      Min = Val - long(Val);
200      Val = long(Val) + Min*100.0/60.0;
201      
202   if Anon != 0:
203       Str = "%3.2f"%(Val);
204   else:
205       Str = str(Val);
206   if Val >= 0:
207      return "+" + Str;
208   return Str;
209
210 def FormatSSHAuth(Str):
211    Match = SSHAuthSplit.match(Str);
212    if Match == None:
213       return "<unknown format>";
214    G = Match.groups();
215
216    # No options
217    if G[0] == None:
218       return "%s %s %s..%s %s"%(G[1],G[2],G[3][:8],G[3][-8:],G[4]);
219    return "%s %s %s %s..%s %s"%(G[0],G[1],G[2],G[3][:8],G[3][-8:],G[4]);
220
221 def FormatPGPKey(Str):
222    Res = "";
223
224    # PGP 2.x Print
225    if (len(Str) == 32):
226       I = 0;
227       while (I < len(Str)):
228          if I+2 == 32/2:
229             Res = "%s %s%s "%(Res,Str[I],Str[I+1]);
230          else:
231             Res = "%s%s%s "%(Res,Str[I],Str[I+1]);
232          I = I + 2;
233    elif (len(Str) == 40):
234       # OpenPGP Print
235       I = 0;
236       while (I < len(Str)):
237          if I+4 == 40/2:
238             Res = "%s %s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
239          else:
240             Res = "%s%s%s%s%s "%(Res,Str[I],Str[I+1],Str[I+2],Str[I+3]);
241          I = I + 4;
242    else:
243       Res = Str;
244    return string.strip(Res);
245
246 # Take an email address and split it into 3 parts, (Name,UID,Domain)
247 def SplitEmail(Addr):
248    Res1 = rfc822.AddrlistClass(Addr).getaddress();
249    if len(Res1) != 1:
250       return ("","",Addr);
251    Res1 = Res1[0];
252    if Res1[1] == None:
253       return (Res1[0],"","");
254    Res2 = string.split(Res1[1],"@");
255    if len(Res2) != 2:
256       return (Res1[0],"",Res1[1]);
257    return (Res1[0],Res2[0],Res2[1]);