* Remove use of deprecated functions from the string module
[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 #   Copyright (c) 2000-2001  Jason Gunthorpe <jgg@debian.org>
6 #   Copyright (c) 2003-2004  James Troup <troup@debian.org>
7 #   Copyright (c) 2004-2005,7  Joey Schulze <joey@infodrom.org>
8 #   Copyright (c) 2001-2007  Ryan Murray <rmurray@debian.org>
9 #
10 #   This program is free software; you can redistribute it and/or modify
11 #   it under the terms of the GNU General Public License as published by
12 #   the Free Software Foundation; either version 2 of the License, or
13 #   (at your option) any later version.
14 #
15 #   This program is distributed in the hope that it will be useful,
16 #   but WITHOUT ANY WARRANTY; without even the implied warranty of
17 #   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 #   GNU General Public License for more details.
19 #
20 #   You should have received a copy of the GNU General Public License
21 #   along with this program; if not, write to the Free Software
22 #   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23
24 import string, re, time, ldap, getopt, sys, os, pwd, posix, socket, base64, sha
25 from userdir_ldap import *;
26
27 global Allowed;
28 global CurrentHost;
29
30 PasswdAttrs = None;
31 GroupIDMap = {};
32 Allowed = None;
33 CurrentHost = "";
34
35 EmailCheck = re.compile("^([^ <>@]+@[^ ,<>@]+)?$");
36 BSMTPCheck = re.compile(".*mx 0 (gluck)\.debian\.org\..*",re.DOTALL);
37 DNSZone = ".debian.net"
38
39 def Sanitize(Str):
40   return Str.translate(string.maketrans("\n\r\t","$$$"))
41
42 def DoLink(From,To,File):
43    try: posix.remove(To+File);
44    except: pass;
45    posix.link(From+File,To+File);
46
47 # See if this user is in the group list
48 def IsInGroup(DnRecord):
49   if Allowed == None:
50      return 1;
51
52   # See if the primary group is in the list
53   if Allowed.has_key(GetAttr(DnRecord,"gidNumber")) != 0:
54      return 1;
55
56   # Check the host based ACL
57   if DnRecord[1].has_key("allowedHost") != 0:
58      for I in DnRecord[1]["allowedHost"]:
59         if CurrentHost == I:
60            return 1;
61
62   # See if there are supplementary groups
63   if DnRecord[1].has_key("supplementaryGid") == 0:
64      return 0;
65
66   # Check the supplementary groups
67   for I in DnRecord[1]["supplementaryGid"]:
68      if Allowed.has_key(I):
69         return 1;
70   return 0;
71
72 def Die(File,F,Fdb):
73    if F != None:
74       F.close();
75    if Fdb != None:
76       Fdb.close();
77    try: os.remove(File + ".tmp");
78    except: pass;
79    try: os.remove(File + ".tdb.tmp");
80    except: pass;
81
82 def Done(File,F,Fdb):
83   if F != None:
84     F.close();
85     os.rename(File + ".tmp",File);
86   if Fdb != None:
87     Fdb.close();
88     os.rename(File + ".tdb.tmp",File+".tdb");
89   
90 # Generate the password list
91 def GenPasswd(l,File,HomePrefix):
92   F = None;
93   try:
94    F = open(File + ".tdb.tmp","w");
95
96    # Fetch all the users
97    global PasswdAttrs;
98    if PasswdAttrs == None:
99       raise "No Users";
100
101    I = 0;
102    for x in PasswdAttrs:
103       if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
104          continue;
105
106       # Do not let people try to buffer overflow some busted passwd parser.
107       if len(GetAttr(x,"gecos")) > 100 or len(GetAttr(x,"loginShell")) > 50:
108          continue;
109
110       Line = "%s:x:%s:%s:%s:%s%s:%s" % (GetAttr(x,"uid"),\
111               GetAttr(x,"uidNumber"),GetAttr(x,"gidNumber"),\
112               GetAttr(x,"gecos"),HomePrefix,GetAttr(x,"uid"),\
113               GetAttr(x,"loginShell"));
114
115       Line = Sanitize(Line) + "\n";
116       F.write("0%u %s" % (I,Line));
117       F.write(".%s %s" % (GetAttr(x,"uid"),Line));
118       F.write("=%s %s" % (GetAttr(x,"uidNumber"),Line));
119       I = I + 1;
120
121   # Oops, something unspeakable happened.
122   except:
123    Die(File,None,F);
124    raise;
125   Done(File,None,F);
126
127 # Generate the shadow list
128 def GenShadow(l,File):
129   F = None;
130   try:
131    OldMask = os.umask(0077);
132    F = open(File + ".tdb.tmp","w",0600);
133    os.umask(OldMask);
134
135    # Fetch all the users
136    global PasswdAttrs;
137    if PasswdAttrs == None:
138       raise "No Users";
139
140    I = 0;
141    for x in PasswdAttrs:
142       if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
143          continue;
144          
145       Pass = GetAttr(x,"userPassword");
146       if Pass[0:7] != "{crypt}" or len(Pass) > 50:
147          Pass = '*';
148       else:
149          Pass = Pass[7:];
150
151       # If the account is locked, mark it as such in shadow
152       # See Debian Bug #308229 for why we set it to 1 instead of 0
153       if (GetAttr(x,"userPassword").find("*LK*") != -1) \
154           or GetAttr(x,"userPassword").startswith("!"):
155          ShadowExpire = '1'
156       else:
157          ShadowExpire = GetAttr(x,"shadowexpire")
158
159       Line = "%s:%s:%s:%s:%s:%s:%s:%s:" % (GetAttr(x,"uid"),\
160               Pass,GetAttr(x,"shadowLastChange"),\
161               GetAttr(x,"shadowMin"),GetAttr(x,"shadowMax"),\
162               GetAttr(x,"shadowWarning"),GetAttr(x,"shadowinactive"),\
163               ShadowExpire);
164       Line = Sanitize(Line) + "\n";
165       F.write("0%u %s" % (I,Line));
166       F.write(".%s %s" % (GetAttr(x,"uid"),Line));
167       I = I + 1;
168
169   # Oops, something unspeakable happened.
170   except:
171    Die(File,None,F);
172    raise;
173   Done(File,None,F);
174
175 # Generate the shadow list
176 def GenSSHShadow(l,File):
177   F = None;
178   try:
179    OldMask = os.umask(0077);
180    F = open(File + ".tmp","w",0600);
181    os.umask(OldMask);
182
183    # Fetch all the users
184    global PasswdAttrs;
185    if PasswdAttrs == None:
186       raise "No Users";
187
188    for x in PasswdAttrs:
189       # If the account is locked, do not write it.
190       # This is a partial stop-gap. The ssh also needs to change this
191       # to ignore ~/.ssh/authorized* files.
192       if (GetAttr(x,"userPassword").find("*LK*") != -1) \
193              or GetAttr(x,"userPassword").startswith("!"):
194          continue;
195
196       if x[1].has_key("uidNumber") == 0 or \
197          x[1].has_key("sshRSAAuthKey") == 0:
198          continue;
199       for I in x[1]["sshRSAAuthKey"]:
200          User = GetAttr(x,"uid");
201          Line = "%s: %s" %(User,I);
202          Line = Sanitize(Line) + "\n";
203          F.write(Line);
204   # Oops, something unspeakable happened.
205   except:
206    Die(File,F,None);
207    raise;
208   Done(File,F,None);
209
210 # Generate the group list
211 def GenGroup(l,File):
212   F = None;
213   try:
214    F = open(File + ".tdb.tmp","w");
215
216    # Generate the GroupMap
217    GroupMap = {};
218    for x in GroupIDMap.keys():
219       GroupMap[x] = [];
220       
221    # Fetch all the users
222    global PasswdAttrs;
223    if PasswdAttrs == None:
224       raise "No Users";
225
226    # Sort them into a list of groups having a set of users
227    for x in PasswdAttrs:
228       if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
229          continue;
230       if x[1].has_key("supplementaryGid") == 0:
231          continue;
232          
233       for I in x[1]["supplementaryGid"]:
234          if GroupMap.has_key(I):
235             GroupMap[I].append(GetAttr(x,"uid"));
236          else:
237             print "Group does not exist ",I,"but",GetAttr(x,"uid"),"is in it";
238             
239    # Output the group file.
240    J = 0;
241    for x in GroupMap.keys():
242       if GroupIDMap.has_key(x) == 0:
243          continue;
244       Line = "%s:x:%u:" % (x,GroupIDMap[x]);
245       Comma = '';
246       for I in GroupMap[x]:
247         Line = Line + ("%s%s" % (Comma,I));
248         Comma = ',';
249       Line = Sanitize(Line) + "\n";
250       F.write("0%u %s" % (J,Line));
251       F.write(".%s %s" % (x,Line));
252       F.write("=%u %s" % (GroupIDMap[x],Line));
253       J = J + 1;
254       
255   # Oops, something unspeakable happened.
256   except:
257    Die(File,None,F);
258    raise;
259   Done(File,None,F);
260
261 # Generate the email forwarding list
262 def GenForward(l,File):
263   F = None;
264   try:
265    OldMask = os.umask(0022);
266    F = open(File + ".tmp","w",0644);
267    os.umask(OldMask);
268
269    # Fetch all the users
270    global PasswdAttrs;
271    if PasswdAttrs == None:
272       raise "No Users";
273
274    # Write out the email address for each user
275    for x in PasswdAttrs:
276       if x[1].has_key("emailForward") == 0 or IsInGroup(x) == 0:
277          continue;
278       
279       # Do not allow people to try to buffer overflow busted parsers
280       if len(GetAttr(x,"emailForward")) > 200:
281          continue;
282
283       # Check the forwarding address
284       if EmailCheck.match(GetAttr(x,"emailForward")) == None:
285          continue;
286       Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
287       Line = Sanitize(Line) + "\n";
288       F.write(Line);
289       
290   # Oops, something unspeakable happened.
291   except:
292    Die(File,F,None);
293    raise;
294   Done(File,F,None);
295
296 def GenAllForward(l,File):
297   Fdb = None;
298   try:
299    OldMask = os.umask(0022);
300    Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
301    os.umask(OldMask);
302
303    # Fetch all the users
304    global PasswdAttrs;
305    if PasswdAttrs == None:
306       raise "No Users";
307
308    # Write out the email address for each user
309    for x in PasswdAttrs:
310       if x[1].has_key("emailForward") == 0:
311          continue;
312       
313       # Do not allow people to try to buffer overflow busted parsers
314       Forward = GetAttr(x,"emailForward");
315       if len(Forward) > 200:
316          continue;
317
318       # Check the forwarding address
319       if EmailCheck.match(Forward) == None:
320          continue;
321          
322       User = GetAttr(x,"uid");
323       Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
324    Fdb.write("\n");
325   # Oops, something unspeakable happened.
326   except:
327     Fdb.close();
328     raise;
329   if Fdb.close() != None:
330     raise "cdbmake gave an error";
331
332 # Generate the anon XEarth marker file 
333 def GenMarkers(l,File):
334   F = None;
335   try:
336    F = open(File + ".tmp","w");
337
338    # Fetch all the users
339    global PasswdAttrs;
340    if PasswdAttrs == None:
341       raise "No Users";
342
343    # Write out the position for each user
344    for x in PasswdAttrs:
345       if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
346          continue;       
347       try:
348          Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
349          Line = Sanitize(Line) + "\n";
350          F.write(Line);
351       except:
352          pass;
353       
354   # Oops, something unspeakable happened.
355   except:
356    Die(File,F,None);
357    raise;
358   Done(File,F,None);
359
360 # Generate the debian-private subscription list
361 def GenPrivate(l,File):
362   F = None;
363   try:
364    F = open(File + ".tmp","w");
365
366    # Fetch all the users
367    global PasswdAttrs;
368    if PasswdAttrs == None:
369       raise "No Users";
370
371    # Write out the position for each user
372    for x in PasswdAttrs:
373       if x[1].has_key("privateSub") == 0:
374          continue;
375
376       # If the account is locked, do not write it
377       if (GetAttr(x,"userPassword").find("*LK*") != -1) \
378              or GetAttr(x,"userPassword").startswith("!"):
379          continue;
380
381       # If the account has no PGP key, do not write it
382       if x[1].has_key("keyFingerPrint") == 0:
383          continue;
384
385       # Must be in the Debian group (yuk, hard coded for now)
386       if GetAttr(x,"gidNumber") != "800":
387          continue;
388
389       try:
390          Line = "%s"%(GetAttr(x,"privateSub"));
391          Line = Sanitize(Line) + "\n";
392          F.write(Line);
393       except:
394          pass;
395       
396   # Oops, something unspeakable happened.
397   except:
398    Die(File,F,None);
399    raise;
400   Done(File,F,None);
401
402 # Generate a list of locked accounts
403 def GenDisabledAccounts(l,File):
404   F = None;
405   try:
406    F = open(File + ".tmp","w");
407
408    # Fetch all the users
409    global PasswdAttrs;
410    if PasswdAttrs == None:
411       raise "No Users";
412
413    I = 0;
414    for x in PasswdAttrs:
415       if x[1].has_key("uidNumber") == 0:
416          continue;
417          
418       Pass = GetAttr(x,"userPassword");
419       Line = ""
420       # *LK* is the reference value for a locked account
421       # password starting with ! is also a locked account
422       if Pass.find("*LK*") != -1 or Pass.startswith("!"):
423          # Format is <login>:<reason>
424          Line = "%s:%s" % (GetAttr(x,"uid"), "Account is locked")
425
426       if Line != "":
427          F.write(Sanitize(Line) + "\n")
428
429   # Oops, something unspeakable happened.
430   except:
431    Die(File,F,None);
432    raise;
433   Done(File,F,None);
434
435 # Generate the list of local addresses that refuse all mail
436 def GenMailDisable(l,File):
437   F = None;
438   try:
439    F = open(File + ".tmp","w");
440
441    # Fetch all the users
442    global PasswdAttrs;
443    if PasswdAttrs == None:
444       raise "No Users";
445
446    for x in PasswdAttrs:
447       Reason = None
448       
449       # If the account is locked, disable incoming mail
450       if (GetAttr(x,"userPassword").find("*LK*") != -1):
451          if GetAttr(x,"uid") == "luther":
452             continue
453          else:
454             Reason = "user account locked"
455       else:
456          if x[1].has_key("mailDisableMessage"):
457             Reason = GetAttr(x,"mailDisableMessage")
458          else:
459             continue
460
461       # Must be in the Debian group (yuk, hard coded for now)
462       if GetAttr(x,"gidNumber") != "800":
463          continue;
464
465       try:
466          Line = "%s: %s"%(GetAttr(x,"uid"),Reason);
467          Line = Sanitize(Line) + "\n";
468          F.write(Line);
469       except:
470          pass;
471       
472   # Oops, something unspeakable happened.
473   except:
474    Die(File,F,None);
475    raise;
476   Done(File,F,None);
477
478 # Generate a list of uids that should have boolean affects applied
479 def GenMailBool(l,File,Key):
480   F = None;
481   try:
482    F = open(File + ".tmp","w");
483
484    # Fetch all the users
485    global PasswdAttrs;
486    if PasswdAttrs == None:
487       raise "No Users";
488
489    for x in PasswdAttrs:
490       Reason = None
491       
492       if x[1].has_key(Key) == 0:
493          continue
494
495       # Must be in the Debian group (yuk, hard coded for now)
496       if GetAttr(x,"gidNumber") != "800":
497          continue
498
499       if GetAttr(x,Key) != "TRUE":
500          continue
501
502       try:
503          Line = "%s"%(GetAttr(x,"uid"));
504          Line = Sanitize(Line) + "\n";
505          F.write(Line);
506       except:
507          pass;
508       
509   # Oops, something unspeakable happened.
510   except:
511    Die(File,F,None);
512    raise;
513   Done(File,F,None);
514
515 # Generate a list of hosts for RBL or whitelist purposes.
516 def GenMailList(l,File,Key):
517   F = None;
518   try:
519    F = open(File + ".tmp","w");
520
521    # Fetch all the users
522    global PasswdAttrs;
523    if PasswdAttrs == None:
524       raise "No Users";
525
526    for x in PasswdAttrs:
527       Reason = None
528       
529       if x[1].has_key(Key) == 0:
530          continue
531
532       # Must be in the Debian group (yuk, hard coded for now)
533       if GetAttr(x,"gidNumber") != "800":
534          continue
535
536       try:
537          found = 0
538          Line = None
539          for z in x[1][Key]:
540              if Key == "mailWhitelist":
541                  if re.match('^[-\w.]+(/[\d]+)?$',z) == None:
542                      continue
543              else:
544                  if re.match('^[-\w.]+$',z) == None:
545                      continue
546              if found == 0:
547                  found = 1
548                  Line = GetAttr(x,"uid")
549              else:
550                  Line += " "
551              Line += ": " + z
552              if Key == "mailRHSBL":
553                  Line += "/$sender_address_domain"
554
555          if Line != None:
556              Line = Sanitize(Line) + "\n";
557              F.write(Line);
558       except:
559          pass;
560       
561   # Oops, something unspeakable happened.
562   except:
563    Die(File,F,None);
564    raise;
565   Done(File,F,None);
566
567 # Generate the DNS Zone file
568 def GenDNS(l,File,HomePrefix):
569   F = None;
570   try:
571    F = open(File + ".tmp","w");
572    
573    # Fetch all the users
574    global PasswdAttrs;
575    if PasswdAttrs == None:
576       raise "No Users";
577
578    # Write out the zone file entry for each user
579    for x in PasswdAttrs:
580       if x[1].has_key("dnsZoneEntry") == 0:
581          continue;
582
583       # If the account has no PGP key, do not write it
584       if x[1].has_key("keyFingerPrint") == 0:
585          continue;
586       try:
587          F.write("; %s\n"%(EmailAddress(x)));
588          for z in x[1]["dnsZoneEntry"]:
589             Split = z.lower().split()
590             if Split[1].lower() == 'in':
591                for y in range(0,len(Split)):
592                   if Split[y] == "$":
593                      Split[y] = "\n\t";
594                Line = " ".join(Split) + "\n";
595                F.write(Line);
596                
597                Host = Split[0] + DNSZone;
598                if BSMTPCheck.match(Line) != None:
599                    F.write("; Has BSMTP\n");
600                                
601                # Write some identification information
602                if Split[2].lower() == "a":
603                   Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
604                   for y in x[1]["keyFingerPrint"]:
605                      Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
606                   F.write(Line);
607             else:
608                Line = "; Err %s"%(str(Split));
609                F.write(Line);
610
611          F.write("\n");
612       except:
613          F.write("; Errors\n");
614          pass;
615       
616   # Oops, something unspeakable happened.
617   except:
618    Die(File,F,None);
619    raise;
620   Done(File,F,None);
621
622 # Generate the DNS SSHFP records
623 def GenSSHFP(l,File,HomePrefix):
624   F = None
625   try:
626    F = open(File + ".tmp","w")
627    
628    # Fetch all the hosts
629    global HostAttrs
630    if HostAttrs == None:
631       raise "No Hosts"
632
633    for x in HostAttrs:
634       if x[1].has_key("hostname") == 0 or \
635          x[1].has_key("sshRSAHostKey") == 0:
636          continue
637       Host = GetAttr(x,"hostname");
638       Algorithm = None
639       for I in x[1]["sshRSAHostKey"]:
640          Split = I.split()
641          if Split[0] == 'ssh-rsa':
642             Algorithm = 1
643          if Split[0] == 'ssh-dss':
644             Algorithm = 2
645          if Algorithm == None:
646             continue
647          Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
648          Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
649          Line = Sanitize(Line) + "\n"
650          F.write(Line)
651   # Oops, something unspeakable happened.
652   except:
653    Die(File,F,None)
654    raise;
655   Done(File,F,None)
656
657 # Generate the BSMTP file
658 def GenBSMTP(l,File,HomePrefix):
659   F = None;
660   try:
661    F = open(File + ".tmp","w");
662    
663    # Fetch all the users
664    global PasswdAttrs;
665    if PasswdAttrs == None:
666       raise "No Users";
667
668    # Write out the zone file entry for each user
669    for x in PasswdAttrs:
670       if x[1].has_key("dnsZoneEntry") == 0:
671          continue;
672
673       # If the account has no PGP key, do not write it
674       if x[1].has_key("keyFingerPrint") == 0:
675          continue;
676       try:
677          for z in x[1]["dnsZoneEntry"]:
678             Split = z.lower().split()
679             if Split[1].lower() == 'in':
680                for y in range(0,len(Split)):
681                   if Split[y] == "$":
682                      Split[y] = "\n\t";
683                Line = " ".join(Split) + "\n";
684                
685                Host = Split[0] + DNSZone;
686                if BSMTPCheck.match(Line) != None:
687                    F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
688                                GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
689                                
690       except:
691          F.write("; Errors\n");
692          pass;
693       
694   # Oops, something unspeakable happened.
695   except:
696    Die(File,F,None);
697    raise;
698   Done(File,F,None);
699
700 # Generate the ssh known hosts file
701 def GenSSHKnown(l,File):
702   F = None;
703   try:
704    OldMask = os.umask(0022);
705    F = open(File + ".tmp","w",0644);
706    os.umask(OldMask);
707
708    global HostAttrs
709    if HostAttrs == None:
710       raise "No Hosts";
711    
712    for x in HostAttrs:
713       if x[1].has_key("hostname") == 0 or \
714          x[1].has_key("sshRSAHostKey") == 0:
715          continue;
716       Host = GetAttr(x,"hostname");
717       SHost = Host.find(".")
718       for I in x[1]["sshRSAHostKey"]:
719          if SHost == None:
720             Line = "%s,%s %s" %(Host,socket.gethostbyname(Host),I);
721          else:
722             Line = "%s,%s,%s %s" %(Host,Host[0:SHost],socket.gethostbyname(Host),I);
723          Line = Sanitize(Line) + "\n";
724          F.write(Line);
725   # Oops, something unspeakable happened.
726   except:
727    Die(File,F,None);
728    raise;
729   Done(File,F,None);
730
731 # Generate the debianhosts file (list of all IP addresses)
732 def GenHosts(l,File):
733   F = None;
734   try:
735    OldMask = os.umask(0022);
736    F = open(File + ".tmp","w",0644);
737    os.umask(OldMask);
738
739    # Fetch all the hosts
740    HostNames = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"hostname=*",\
741                 ["hostname"]);
742    
743    if HostNames == None:
744       raise "No Hosts";
745
746    for x in HostNames:
747       if x[1].has_key("hostname") == 0:
748          continue;
749       Host = GetAttr(x,"hostname");
750       try:
751         Addr = socket.gethostbyname(Host);
752         F.write(Addr + "\n");
753       except:
754         pass
755   # Oops, something unspeakable happened.
756   except:
757    Die(File,F,None);
758    raise;
759   Done(File,F,None);
760
761 # Connect to the ldap server
762 l = ldap.open(LDAPServer);
763 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
764 Pass = F.readline().strip().split(" ")
765 F.close();
766 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
767
768 # Fetch all the groups
769 GroupIDMap = {};
770 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
771                   ["gid","gidNumber"]);
772
773 # Generate the GroupMap and GroupIDMap
774 for x in Attrs:
775    if x[1].has_key("gidNumber") == 0:
776       continue;
777    GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
778
779 # Fetch all the users
780 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
781                 ["uid","uidNumber","gidNumber","supplementaryGid",\
782                  "gecos","loginShell","userPassword","shadowLastChange",\
783                  "shadowMin","shadowMax","shadowWarning","shadowinactive",
784                  "shadowexpire","emailForward","latitude","longitude",\
785                  "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
786                  "keyFingerPrint","privateSub","mailDisableMessage",\
787                  "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
788                  "mailWhitelist"]);
789 # Fetch all the hosts
790 HostAttrs    = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
791                 ["hostname","sshRSAHostKey"]);
792
793 # Open the control file
794 if len(sys.argv) == 1:
795    F = open(GenerateConf,"r");
796 else:
797    F = open(sys.argv[1],"r")
798
799 # Generate global things
800 GlobalDir = GenerateDir+"/";
801 GenSSHShadow(l,GlobalDir+"ssh-rsa-shadow");
802 GenAllForward(l,GlobalDir+"mail-forward.cdb");
803 GenMarkers(l,GlobalDir+"markers");
804 GenPrivate(l,GlobalDir+"debian-private");
805 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
806 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
807 GenHosts(l,GlobalDir+"debianhosts");
808 GenMailDisable(l,GlobalDir+"mail-disable");
809 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
810 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
811 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
812 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
813 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
814
815 # Compatibility.
816 GenForward(l,GlobalDir+"forward-alias");
817    
818 while(1):
819    Line = F.readline();
820    if Line == "":
821       break;
822    Line = Line.strip()
823    if Line == "":
824       continue;
825    if Line[0] == '#':
826       continue;
827
828    Split = Line.split(" ")
829    OutDir = GenerateDir + '/' + Split[0] + '/';
830    try: os.mkdir(OutDir);
831    except: pass;
832
833    # Get the group list and convert any named groups to numerics
834    GroupList = {};
835    ExtraList = {};
836    for I in Split[2:]:
837       if I[0] == '[':
838          ExtraList[I] = None;
839          continue;
840       GroupList[I] = None;
841       if GroupIDMap.has_key(I):
842          GroupList[str(GroupIDMap[I])] = None;
843
844    Allowed = GroupList;
845    if Allowed == {}:
846      Allowed = None
847    CurrentHost = Split[0];
848
849    DoLink(GlobalDir,OutDir,"ssh-rsa-shadow");
850    DoLink(GlobalDir,OutDir,"debianhosts");
851    DoLink(GlobalDir,OutDir,"ssh_known_hosts");
852    DoLink(GlobalDir,OutDir,"disabled-accounts")
853
854    sys.stdout.flush();
855    GenPasswd(l,OutDir+"passwd",Split[1]);
856    sys.stdout.flush();
857    GenGroup(l,OutDir+"group");
858    if ExtraList.has_key("[UNTRUSTED]"):
859         continue;
860    if not ExtraList.has_key("[NOPASSWD]"):
861      GenShadow(l,OutDir+"shadow");
862         
863    # Link in global things   
864    DoLink(GlobalDir,OutDir,"markers");
865    DoLink(GlobalDir,OutDir,"mail-forward.cdb");
866    DoLink(GlobalDir,OutDir,"mail-disable");
867    DoLink(GlobalDir,OutDir,"mail-greylist");
868    DoLink(GlobalDir,OutDir,"mail-callout");
869    DoLink(GlobalDir,OutDir,"mail-rbl");
870    DoLink(GlobalDir,OutDir,"mail-rhsbl");
871    DoLink(GlobalDir,OutDir,"mail-whitelist");
872
873    # Compatibility.
874    DoLink(GlobalDir,OutDir,"forward-alias");
875
876    if ExtraList.has_key("[DNS]"):
877       GenDNS(l,OutDir+"dns-zone",Split[1]);
878       GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
879       
880    if ExtraList.has_key("[BSMTP]"):
881       GenBSMTP(l,OutDir+"bsmtp",Split[1])
882
883    if ExtraList.has_key("[PRIVATE]"):
884       DoLink(GlobalDir,OutDir,"debian-private")