Cute dns entries
[mirror/userdir-ldap.git] / ud-generate
1 #!/usr/bin/env python
2 # -*- mode: python -*-
3 # Generates passwd, shadow and group files from the ldap directory.
4
5 import string, re, time, ldap, getopt, sys, os, posix, pwd;
6 from userdir_ldap import *;
7
8 PasswdAttrs = None;
9 GroupIDMap = {};
10 Allowed = None;
11 CurrentHost = "";
12
13 def Sanitize(Str):
14   return string.translate(Str,string.maketrans("\n\r\t","$$$"));
15
16 # See if this user is in the group list
17 def IsInGroup(DnRecord):
18   global Allowed,CurrentHost;
19   if Allowed == None:
20      return 1;
21
22   # See if the primary group is in the list
23   if Allowed.has_key(GetAttr(DnRecord,"gidnumber")) != 0:
24      return 1;
25
26   # Check the host based ACL
27   if DnRecord[1].has_key("allowedhosts") != 0:
28      for I in DnRecord[1]["allowedhosts"]:
29         if CurrentHost == I:
30            return 1;
31
32   # See if there are supplementary groups
33   if DnRecord[1].has_key("supplementarygid") == 0:
34      return 0;
35
36   # Check the supplementary groups
37   for I in DnRecord[1]["supplementarygid"]:
38      if Allowed.has_key(I):
39         return 1;
40   return 0;
41
42 def Die(F,Fdb):
43    if F != None:
44       F.close();
45    if Fdb != None:
46       Fdb.close();
47    try: os.remove(File + ".tmp");
48    except: pass;
49    try: os.remove(File + ".tdb.tmp");
50    except: pass;
51
52 def Done(File,F,Fdb):
53   if F != None:
54     F.close();
55     os.rename(File + ".tmp",File);
56   if Fdb != None:
57     Fdb.close();
58     os.rename(File + ".tdb.tmp",File+".tdb");
59   
60 # Generate the password list
61 def GenPasswd(l,File,HomePrefix):
62   F = None;
63   Fdb = None;
64   try:
65    F = open(File + ".tmp","w");
66    Fdb = open(File + ".tdb.tmp","w");
67
68    # Fetch all the users
69    global PasswdAttrs;
70    if PasswdAttrs == None:
71       raise "No Users";
72
73    I = 0;
74    for x in PasswdAttrs:
75       if x[1].has_key("uidnumber") == 0 or IsInGroup(x) == 0:
76          continue;
77
78       # Do not let people try to buffer overflow some busted passwd parser.
79       if len(GetAttr(x,"gecos")) > 100 or len(GetAttr(x,"loginshell")) > 50:
80          continue;
81
82       Line = "%s:x:%s:%s:%s:%s%s:%s\n" % (GetAttr(x,"uid"),\
83               GetAttr(x,"uidnumber"),GetAttr(x,"gidnumber"),\
84               GetAttr(x,"gecos"),HomePrefix,GetAttr(x,"uid"),\
85               GetAttr(x,"loginshell"));
86       F.write(Line);
87       Fdb.write("0%u %s" % (I,Line));
88       Fdb.write(".%s %s" % (GetAttr(x,"uid"),Line));
89       Fdb.write("=%s %s" % (GetAttr(x,"uidnumber"),Line));
90       I = I + 1;
91
92   # Oops, something unspeakable happened.
93   except:
94    Die(F,Fdb);
95    raise;
96   Done(File,F,Fdb);
97
98 # Generate the shadow list
99 def GenShadow(l,File):
100   F = None;
101   Fdb = None;
102   try:
103    OldMask = os.umask(0077);
104    F = open(File + ".tmp","w",0600);
105    Fdb = open(File + ".tdb.tmp","w",0600);
106    os.umask(OldMask);
107
108    # Fetch all the users
109    global PasswdAttrs;
110    if PasswdAttrs == None:
111       raise "No Users";
112
113    I = 0;
114    for x in PasswdAttrs:
115       if x[1].has_key("uidnumber") == 0 or IsInGroup(x) == 0:
116          continue;
117          
118       Pass = GetAttr(x,"userpassword");
119       if Pass[0:7] != "{crypt}" or len(Pass) > 50:
120          Pass = '*';
121       else:
122          Pass = Pass[7:];
123       Line = "%s:%s:%s:%s:%s:%s:%s:%s:" % (GetAttr(x,"uid"),\
124               Pass,GetAttr(x,"shadowlastchange"),\
125               GetAttr(x,"shadowmin"),GetAttr(x,"shadowmax"),\
126               GetAttr(x,"shadowwarning"),GetAttr(x,"shadowinactive"),\
127               GetAttr(x,"shadowexpire"));
128       Line = Sanitize(Line) + "\n";
129       F.write(Line);
130       Fdb.write("0%u %s" % (I,Line));
131       Fdb.write(".%s %s" % (GetAttr(x,"uid"),Line));
132       I = I + 1;
133
134   # Oops, something unspeakable happened.
135   except:
136    Die(F,Fdb);
137    raise;
138   Done(File,F,Fdb);
139
140 # Generate the shadow list
141 def GenSSHShadow(l,File):
142   F = None;
143   Fdb = None;
144   try:
145    OldMask = os.umask(0077);
146    F = open(File + ".tmp","w",0600);
147    Fdb = None;
148    os.umask(OldMask);
149
150    # Fetch all the users
151    global PasswdAttrs;
152    if PasswdAttrs == None:
153       raise "No Users";
154
155    I = 0;
156    for x in PasswdAttrs:
157       if x[1].has_key("uidnumber") == 0 or IsInGroup(x) == 0 or \
158          x[1].has_key("sshrsaauthkey") == 0:
159          continue;
160       for I in x[1]["sshrsaauthkey"]:
161          Line = "%s: %s" %(GetAttr(x,"uid"),I);
162          Line = Sanitize(Line) + "\n";
163          F.write(Line);
164
165   # Oops, something unspeakable happened.
166   except:
167    Die(F,Fdb);
168    raise;
169   Done(File,F,Fdb);
170
171 # Generate the group list
172 def GenGroup(l,File):
173   F = None;
174   Fdb = None;
175   try:
176    F = open(File + ".tmp","w");
177    Fdb = open(File + ".tdb.tmp","w");
178
179    # Generate the GroupMap
180    GroupMap = {};
181    for x in GroupIDMap.keys():
182       GroupMap[x] = [];
183       
184    # Fetch all the users
185    global PasswdAttrs;
186    if PasswdAttrs == None:
187       raise "No Users";
188
189    # Sort them into a list of groups having a set of users
190    for x in PasswdAttrs:
191       if x[1].has_key("uidnumber") == 0 or IsInGroup(x) == 0:
192          continue;
193       if x[1].has_key("supplementarygid") == 0:
194          continue;
195          
196       for I in x[1]["supplementarygid"]:
197          if GroupMap.has_key(I):
198             GroupMap[I].append(GetAttr(x,"uid"));
199          else:
200             print "Group does not exist ",I,"but",GetAttr(x,"uid"),"is in it";
201             
202    # Output the group file.
203    Counter = 0; 
204    for x in GroupMap.keys():
205       Line = "%s:x:%u:" % (x,GroupIDMap[x]);
206       Comma = '';
207       for I in GroupMap[x]:
208         Line = Line + ("%s%s" % (Comma,I));
209         Comma = ',';
210       Line = Sanitize(Line) + "\n";
211       F.write(Line);
212       Fdb.write("0%u %s" % (Counter,Line));
213       Fdb.write(".%s %s" % (x,Line));
214       Fdb.write("=%u %s" % (GroupIDMap[x],Line));
215       Counter = Counter + 1;
216       
217   # Oops, something unspeakable happened.
218   except:
219    Die(F,Fdb);
220    raise;
221   Done(File,F,Fdb);
222
223 # Generate the email forwarding list
224 def GenForward(l,File):
225   F = None;
226   Fdb = None;
227   try:
228    OldMask = os.umask(0022);
229    F = open(File + ".tmp","w",0644);
230    Fdb = None;
231    os.umask(OldMask);
232
233    # Fetch all the users
234    global PasswdAttrs;
235    if PasswdAttrs == None:
236       raise "No Users";
237
238    # Write out the email address for each user
239    for x in PasswdAttrs:
240       if x[1].has_key("emailforward") == 0 or IsInGroup(x) == 0:
241          continue;
242       
243       # Do not allow people to try to buffer overflow busted parsers
244       if len(GetAttr(x,"emailforward")) > 200:
245          continue;
246
247       Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailforward"));
248       Line = Sanitize(Line) + "\n";
249       F.write(Line);
250       
251   # Oops, something unspeakable happened.
252   except:
253    Die(F,Fdb);
254    raise;
255   Done(File,F,Fdb);
256
257 # Generate the anon XEarth marker file 
258 def GenMarkers(l,File):
259   F = None;
260   Fdb = None;
261   try:
262    F = open(File + ".tmp","w");
263    Fdb = None;
264
265    # Fetch all the users
266    global PasswdAttrs;
267    if PasswdAttrs == None:
268       raise "No Users";
269
270    # Write out the position for each user
271    for x in PasswdAttrs:
272       if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
273          continue;       
274       try:
275          Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
276          Line = Sanitize(Line) + "\n";
277          F.write(Line);
278       except:
279          pass;
280       
281   # Oops, something unspeakable happened.
282   except:
283    Die(F,Fdb);
284    raise;
285   Done(File,F,Fdb);
286   
287 # Generate the DNS Zone file
288 def GenDNS(l,File):
289   F = None;
290   Fdb = None;
291   try:
292    F = open(File + ".tmp","w");
293    Fdb = None;
294
295    # Fetch all the users
296    global PasswdAttrs;
297    if PasswdAttrs == None:
298       raise "No Users";
299
300    # Write out the zone file entry for each user
301    for x in PasswdAttrs:
302       if x[1].has_key("dnszoneentry") == 0:
303          continue;
304       try:
305          F.write("; %s\n"%(EmailAddress(x)));
306          for z in x[1]["dnszoneentry"]:
307             Split = string.split(string.lower(z));
308             if string.lower(Split[1]) == 'in':
309                for y in range(0,len(Split)):
310                   if Split[y] == "$":
311                      Split[y] = "\n\t";
312                Line = string.join(Split," ") + "\n";
313                F.write(Line);
314                
315                # Write some identication information
316                if string.lower(Split[2]) != "cname":
317                   Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
318                   for y in x[1]["keyfingerprint"]:
319                      Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
320                   F.write(Line);
321             else:
322                Line = "; Err %s"%(str(Split));
323                F.write(Line);
324
325          F.write("\n");
326       except:
327          pass;
328       
329   # Oops, something unspeakable happened.
330   except:
331    Die(F,Fdb);
332    raise;
333   Done(File,F,Fdb);
334
335 # Connect to the ldap server
336 l = ldap.open(LDAPServer);
337 F = open(PassDir+"/pass-"+pwd.getpwuid(posix.getuid())[0],"r");
338 Pass = string.split(string.strip(F.readline())," ");
339 F.close();
340 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
341
342 # Fetch all the groups
343 GroupIDMap = {};
344 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
345                   ["gid","gidnumber"]);
346
347 # Generate the GroupMap and GroupIDMap
348 for x in Attrs:
349    if x[1].has_key("gidnumber") == 0:
350       continue;
351    GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidnumber"][0]);
352
353 # Fetch all the users
354 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
355                 ["uid","uidnumber","gidnumber","supplementarygid",\
356                  "gecos","loginshell","userpassword","shadowlastchange",\
357                  "shadowmin","shadowmax","shadowwarning","shadowinactive",
358                  "shadowexpire","emailforward","latitude","longitude",\
359                  "allowedhosts","sshrsaauthkey","dnszoneentry","cn","sn",\
360                  "keyfingerprint"]);
361
362 # Open the control file
363 if len(sys.argv) == 1:
364    F = open(GenerateConf,"r");
365 else:
366    F = open(sys.argv[1],"r")
367 while(1):
368    Line = F.readline();
369    if Line == "":
370       break;
371    Line = string.strip(Line);
372    if Line == "":
373       continue;
374    if Line[0] == '#':
375       continue;
376
377    Split = string.split(Line," ");
378    OutDir = GenerateDir + '/' + Split[0] + '/';
379    try: os.mkdir(OutDir);
380    except: pass;
381
382    # Get the group list and convert any named groups to numerics
383    GroupList = {};
384    ExtraList = {};
385    for I in Split[2:]:
386       if I[0] == '[':
387          ExtraList[I] = None;
388          continue;
389       GroupList[I] = None;
390       if GroupIDMap.has_key(I):
391          GroupList[str(GroupIDMap[I])] = None;
392
393    global Allowed,CurrentHost;
394    Allowed = GroupList;
395    CurrentHost = Split[0];
396
397    GenPasswd(l,OutDir+"passwd",Split[1]);
398    GenGroup(l,OutDir+"group");
399    GenShadow(l,OutDir+"shadow");
400    GenSSHShadow(l,OutDir+"ssh-rsa-shadow");
401    GenForward(l,OutDir+"forward-alias");
402    GenMarkers(l,OutDir+"markers");
403
404    if ExtraList.has_key("[DNS]"):
405       GenDNS(l,OutDir+"dns-zone");
406