3 # Generates passwd, shadow and group files from the ldap directory.
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 # Copyright (c) 2008 Peter Palfrader <peter@palfrader.org>
10 # Copyright (c) 2008 Andreas Barth <aba@not.so.argh.org>
11 # Copyright (c) 2008 Mark Hymers <mhy@debian.org>
12 # Copyright (c) 2008 Luk Claes <luk@debian.org>
13 # Copyright (c) 2008 Thomas Viehmann <tv@beamnet.de>
15 # This program is free software; you can redistribute it and/or modify
16 # it under the terms of the GNU General Public License as published by
17 # the Free Software Foundation; either version 2 of the License, or
18 # (at your option) any later version.
20 # This program is distributed in the hope that it will be useful,
21 # but WITHOUT ANY WARRANTY; without even the implied warranty of
22 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 import string, re, time, ldap, getopt, sys, os, pwd, posix, socket, base64, sha, shutil, errno, tarfile, grp
30 from userdir_ldap import *;
41 UUID_FORMAT = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
43 EmailCheck = re.compile("^([^ <>@]+@[^ ,<>@]+)?$");
44 BSMTPCheck = re.compile(".*mx 0 (gluck)\.debian\.org\..*",re.DOTALL);
45 PurposeHostField = re.compile(r"\[\[([\*\-]?[a-z0-9.\-]*)(?:\|.*)?\]\]")
46 DNSZone = ".debian.net"
47 Keyrings = ConfModule.sync_keyrings.split(":")
49 def safe_makedirs(dir):
53 if e.errno == errno.EEXIST:
62 if e.errno == errno.ENOENT:
68 return Str.translate(string.maketrans("\n\r\t","$$$"))
70 def DoLink(From,To,File):
71 try: posix.remove(To+File);
73 posix.link(From+File,To+File);
75 # See if this user is in the group list
76 def IsInGroup(DnRecord):
80 # See if the primary group is in the list
81 if Allowed.has_key(GetAttr(DnRecord,"gidNumber")) != 0:
84 # Check the host based ACL
85 if DnRecord[1].has_key("allowedHost") != 0:
86 for I in DnRecord[1]["allowedHost"]:
90 # See if there are supplementary groups
91 if DnRecord[1].has_key("supplementaryGid") == 0:
95 addGroups(supgroups, DnRecord[1]["supplementaryGid"], GetAttr(DnRecord,"uid"))
97 if Allowed.has_key(g):
106 try: os.remove(File + ".tmp");
108 try: os.remove(File + ".tdb.tmp");
111 def Done(File,F,Fdb):
114 os.rename(File + ".tmp",File);
117 os.rename(File + ".tdb.tmp",File+".tdb");
119 # Generate the password list
120 def GenPasswd(l,File,HomePrefix,PwdMarker):
123 F = open(File + ".tdb.tmp","w");
126 # Fetch all the users
128 if PasswdAttrs == None:
132 for x in PasswdAttrs:
133 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
136 # Do not let people try to buffer overflow some busted passwd parser.
137 if len(GetAttr(x,"gecos")) > 100 or len(GetAttr(x,"loginShell")) > 50:
140 userlist[GetAttr(x, "uid")] = int(GetAttr(x, "gidNumber"))
141 Line = "%s:%s:%s:%s:%s:%s%s:%s" % (GetAttr(x,"uid"),\
143 GetAttr(x,"uidNumber"),GetAttr(x,"gidNumber"),\
144 GetAttr(x,"gecos"),HomePrefix,GetAttr(x,"uid"),\
145 GetAttr(x,"loginShell"));
147 Line = Sanitize(Line) + "\n";
148 F.write("0%u %s" % (I,Line));
149 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
150 F.write("=%s %s" % (GetAttr(x,"uidNumber"),Line));
153 # Oops, something unspeakable happened.
159 # Return the list of users so we know which keys to export
162 # Generate the shadow list
163 def GenShadow(l,File):
166 OldMask = os.umask(0077);
167 F = open(File + ".tdb.tmp","w",0600);
170 # Fetch all the users
172 if PasswdAttrs == None:
176 for x in PasswdAttrs:
177 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
180 Pass = GetAttr(x,"userPassword");
181 if Pass[0:7] != "{crypt}" or len(Pass) > 50:
186 # If the account is locked, mark it as such in shadow
187 # See Debian Bug #308229 for why we set it to 1 instead of 0
188 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
189 or GetAttr(x,"userPassword").startswith("!"):
192 ShadowExpire = GetAttr(x,"shadowExpire")
194 Line = "%s:%s:%s:%s:%s:%s:%s:%s:" % (GetAttr(x,"uid"),\
195 Pass,GetAttr(x,"shadowLastChange"),\
196 GetAttr(x,"shadowMin"),GetAttr(x,"shadowMax"),\
197 GetAttr(x,"shadowWarning"),GetAttr(x,"shadowInactive"),\
199 Line = Sanitize(Line) + "\n";
200 F.write("0%u %s" % (I,Line));
201 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
204 # Oops, something unspeakable happened.
210 # Generate the sudo passwd file
211 def GenShadowSudo(l,File, untrusted):
214 OldMask = os.umask(0077);
215 F = open(File + ".tmp","w",0600);
218 # Fetch all the users
220 if PasswdAttrs == None:
223 for x in PasswdAttrs:
225 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
228 if x[1].has_key('sudoPassword'):
229 for entry in x[1]['sudoPassword']:
230 Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*]+) ([^ ]+)$').match(entry)
233 uuid = Match.group(1)
234 status = Match.group(2)
235 hosts = Match.group(3)
236 cryptedpass = Match.group(4)
238 if status != 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', x[1]['uid'][0], uuid, hosts, cryptedpass):
240 for_all = hosts == "*"
241 for_this_host = CurrentHost in hosts.split(',')
242 if not (for_all or for_this_host):
244 # ignore * passwords for untrusted hosts, but copy host specific passwords
245 if for_all and untrusted:
248 if for_this_host: # this makes sure we take a per-host entry over the for-all entry
253 Line = "%s:%s" % (GetAttr(x,"uid"), Pass)
254 Line = Sanitize(Line) + "\n";
255 F.write("%s" % (Line));
257 # Oops, something unspeakable happened.
263 # Generate the shadow list
265 # Fetch all the users
270 if PasswdAttrs == None:
273 safe_rmtree(os.path.join(GlobalDir, 'userkeys'))
274 safe_makedirs(os.path.join(GlobalDir, 'userkeys'))
276 for x in PasswdAttrs:
277 # If the account is locked, do not write it.
278 # This is a partial stop-gap. The ssh also needs to change this
279 # to ignore ~/.ssh/authorized* files.
280 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
281 or GetAttr(x,"userPassword").startswith("!"):
284 if x[1].has_key("uidNumber") == 0 or \
285 x[1].has_key("sshRSAAuthKey") == 0:
287 User = GetAttr(x,"uid");
291 OldMask = os.umask(0077);
292 File = os.path.join(GlobalDir, 'userkeys', User)
293 F = open(File + ".tmp","w",0600);
296 for I in x[1]["sshRSAAuthKey"]:
297 MultipleLine = "%s" % I
298 MultipleLine = Sanitize(MultipleLine) + "\n"
299 F.write(MultipleLine)
302 userfiles.append(os.path.basename(File))
304 # Oops, something unspeakable happened.
307 Die(masterFileName,masterFile,None)
312 def GenSSHtarballs(userlist, SSHFiles, grouprevmap, target):
313 OldMask = os.umask(0077);
314 tf = tarfile.open(name=os.path.join(GlobalDir, 'ssh-keys-%s.tar.gz' % CurrentHost), mode='w:gz')
316 for f in userlist.keys():
317 if f not in SSHFiles:
319 # If we're not exporting their primary group, don't export
322 if userlist[f] in grouprevmap.keys():
323 grname = grouprevmap[userlist[f]]
326 if int(userlist[f]) <= 100:
327 # In these cases, look it up in the normal way so we
328 # deal with cases where, for instance, users are in group
329 # users as their primary group.
330 grname = grp.getgrgid(userlist[f])[0]
335 print "User %s is supposed to have their key exported to host %s but their primary group (gid: %d) isn't in LDAP" % (f, CurrentHost, userlist[f])
338 to = tf.gettarinfo(os.path.join(GlobalDir, 'userkeys', f), f)
339 # These will only be used where the username doesn't
340 # exist on the target system for some reason; hence,
341 # in those cases, the safest thing is for the file to
342 # be owned by root but group nobody. This deals with
343 # the bloody obscure case where the group fails to exist
344 # whilst the user does (in which case we want to avoid
345 # ending up with a file which is owned user:root to avoid
346 # a fairly obvious attack vector)
349 # Using the username / groupname fields avoids any need
350 # to give a shit^W^W^Wcare about the UIDoffset stuff.
354 tf.addfile(to, file(os.path.join(GlobalDir, 'userkeys', f)))
357 os.rename(os.path.join(GlobalDir, 'ssh-keys-%s.tar.gz' % CurrentHost), target)
359 # add a list of groups to existing groups,
360 # including all subgroups thereof, recursively.
361 # basically this proceduces the transitive hull of the groups in
363 def addGroups(existingGroups, newGroups, uid):
364 for group in newGroups:
365 # if it's a <group>@host, split it and verify it's on the current host.
366 s = group.split('@', 1)
367 if len(s) == 2 and s[1] != CurrentHost:
371 # let's see if we handled this group already
372 if group in existingGroups:
375 if not GroupIDMap.has_key(group):
376 print "Group", group, "does not exist but", uid, "is in it"
379 existingGroups.append(group)
381 if SubGroupMap.has_key(group):
382 addGroups(existingGroups, SubGroupMap[group], uid)
384 # Generate the group list
385 def GenGroup(l,File):
389 F = open(File + ".tdb.tmp","w");
391 # Generate the GroupMap
393 for x in GroupIDMap.keys():
396 # Fetch all the users
398 if PasswdAttrs == None:
401 # Sort them into a list of groups having a set of users
402 for x in PasswdAttrs:
403 uid = GetAttr(x,"uid")
404 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
406 if x[1].has_key("supplementaryGid") == 0:
410 addGroups(supgroups, x[1]["supplementaryGid"], uid)
412 GroupMap[g].append(uid);
414 # Output the group file.
416 for x in GroupMap.keys():
417 grouprevmap[GroupIDMap[x]] = x
418 if GroupIDMap.has_key(x) == 0:
420 Line = "%s:x:%u:" % (x,GroupIDMap[x]);
422 for I in GroupMap[x]:
423 Line = Line + ("%s%s" % (Comma,I));
425 Line = Sanitize(Line) + "\n";
426 F.write("0%u %s" % (J,Line));
427 F.write(".%s %s" % (x,Line));
428 F.write("=%u %s" % (GroupIDMap[x],Line));
431 # Oops, something unspeakable happened.
439 # Generate the email forwarding list
440 def GenForward(l,File):
443 OldMask = os.umask(0022);
444 F = open(File + ".tmp","w",0644);
447 # Fetch all the users
449 if PasswdAttrs == None:
452 # Write out the email address for each user
453 for x in PasswdAttrs:
454 if x[1].has_key("emailForward") == 0 or IsInGroup(x) == 0:
457 # Do not allow people to try to buffer overflow busted parsers
458 if len(GetAttr(x,"emailForward")) > 200:
461 # Check the forwarding address
462 if EmailCheck.match(GetAttr(x,"emailForward")) == None:
464 Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
465 Line = Sanitize(Line) + "\n";
468 # Oops, something unspeakable happened.
474 def GenAllForward(l,File):
477 OldMask = os.umask(0022);
478 Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
481 # Fetch all the users
483 if PasswdAttrs == None:
486 # Write out the email address for each user
487 for x in PasswdAttrs:
488 if x[1].has_key("emailForward") == 0:
491 # Do not allow people to try to buffer overflow busted parsers
492 Forward = GetAttr(x,"emailForward");
493 if len(Forward) > 200:
496 # Check the forwarding address
497 if EmailCheck.match(Forward) == None:
500 User = GetAttr(x,"uid");
501 Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
503 # Oops, something unspeakable happened.
507 if Fdb.close() != None:
508 raise "cdbmake gave an error";
510 # Generate the anon XEarth marker file
511 def GenMarkers(l,File):
514 F = open(File + ".tmp","w");
516 # Fetch all the users
518 if PasswdAttrs == None:
521 # Write out the position for each user
522 for x in PasswdAttrs:
523 if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
526 Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
527 Line = Sanitize(Line) + "\n";
532 # Oops, something unspeakable happened.
538 # Generate the debian-private subscription list
539 def GenPrivate(l,File):
542 F = open(File + ".tmp","w");
544 # Fetch all the users
546 if PasswdAttrs == None:
549 # Write out the position for each user
550 for x in PasswdAttrs:
551 if x[1].has_key("privateSub") == 0:
554 # If the account is locked, do not write it
555 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
556 or GetAttr(x,"userPassword").startswith("!"):
559 # If the account has no PGP key, do not write it
560 if x[1].has_key("keyFingerPrint") == 0:
563 # Must be in the Debian group (yuk, hard coded for now)
564 if GetAttr(x,"gidNumber") != "800":
568 Line = "%s"%(GetAttr(x,"privateSub"));
569 Line = Sanitize(Line) + "\n";
574 # Oops, something unspeakable happened.
580 # Generate a list of locked accounts
581 def GenDisabledAccounts(l,File):
584 F = open(File + ".tmp","w");
586 # Fetch all the users
588 if PasswdAttrs == None:
592 for x in PasswdAttrs:
593 if x[1].has_key("uidNumber") == 0:
596 Pass = GetAttr(x,"userPassword");
598 # *LK* is the reference value for a locked account
599 # password starting with ! is also a locked account
600 if Pass.find("*LK*") != -1 or Pass.startswith("!"):
601 # Format is <login>:<reason>
602 Line = "%s:%s" % (GetAttr(x,"uid"), "Account is locked")
605 F.write(Sanitize(Line) + "\n")
607 # Oops, something unspeakable happened.
613 # Generate the list of local addresses that refuse all mail
614 def GenMailDisable(l,File):
617 F = open(File + ".tmp","w");
619 # Fetch all the users
621 if PasswdAttrs == None:
624 for x in PasswdAttrs:
627 if x[1].has_key("mailDisableMessage"):
628 Reason = GetAttr(x,"mailDisableMessage")
632 # Must be in the Debian group (yuk, hard coded for now)
633 if GetAttr(x,"gidNumber") != "800":
637 Line = "%s: %s"%(GetAttr(x,"uid"),Reason);
638 Line = Sanitize(Line) + "\n";
643 # Oops, something unspeakable happened.
649 # Generate a list of uids that should have boolean affects applied
650 def GenMailBool(l,File,Key):
653 F = open(File + ".tmp","w");
655 # Fetch all the users
657 if PasswdAttrs == None:
660 for x in PasswdAttrs:
663 if x[1].has_key(Key) == 0:
666 # Must be in the Debian group (yuk, hard coded for now)
667 if GetAttr(x,"gidNumber") != "800":
670 if GetAttr(x,Key) != "TRUE":
674 Line = "%s"%(GetAttr(x,"uid"));
675 Line = Sanitize(Line) + "\n";
680 # Oops, something unspeakable happened.
686 # Generate a list of hosts for RBL or whitelist purposes.
687 def GenMailList(l,File,Key):
690 F = open(File + ".tmp","w");
692 # Fetch all the users
694 if PasswdAttrs == None:
697 for x in PasswdAttrs:
700 if x[1].has_key(Key) == 0:
703 # Must be in the Debian group (yuk, hard coded for now)
704 if GetAttr(x,"gidNumber") != "800":
711 if Key == "mailWhitelist":
712 if re.match('^[-\w.]+(/[\d]+)?$',z) == None:
715 if re.match('^[-\w.]+$',z) == None:
719 Line = GetAttr(x,"uid")
723 if Key == "mailRHSBL":
724 Line += "/$sender_address_domain"
727 Line = Sanitize(Line) + "\n";
732 # Oops, something unspeakable happened.
738 # Generate the DNS Zone file
739 def GenDNS(l,File,HomePrefix):
742 F = open(File + ".tmp","w");
744 # Fetch all the users
746 if PasswdAttrs == None:
749 # Write out the zone file entry for each user
750 for x in PasswdAttrs:
751 if x[1].has_key("dnsZoneEntry") == 0:
754 # If the account has no PGP key, do not write it
755 if x[1].has_key("keyFingerPrint") == 0:
758 F.write("; %s\n"%(EmailAddress(x)));
759 for z in x[1]["dnsZoneEntry"]:
760 Split = z.lower().split()
761 if Split[1].lower() == 'in':
762 for y in range(0,len(Split)):
765 Line = " ".join(Split) + "\n";
768 Host = Split[0] + DNSZone;
769 if BSMTPCheck.match(Line) != None:
770 F.write("; Has BSMTP\n");
772 # Write some identification information
773 if Split[2].lower() == "a":
774 Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
775 for y in x[1]["keyFingerPrint"]:
776 Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
779 Line = "; Err %s"%(str(Split));
784 F.write("; Errors\n");
787 # Oops, something unspeakable happened.
793 # Generate the DNS SSHFP records
794 def GenSSHFP(l,File,HomePrefix):
797 F = open(File + ".tmp","w")
799 # Fetch all the hosts
801 if HostAttrs == None:
805 if x[1].has_key("hostname") == 0 or \
806 x[1].has_key("sshRSAHostKey") == 0:
808 Host = GetAttr(x,"hostname");
810 for I in x[1]["sshRSAHostKey"]:
812 if Split[0] == 'ssh-rsa':
814 if Split[0] == 'ssh-dss':
816 if Algorithm == None:
818 Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
819 Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
820 Line = Sanitize(Line) + "\n"
822 # Oops, something unspeakable happened.
828 # Generate the BSMTP file
829 def GenBSMTP(l,File,HomePrefix):
832 F = open(File + ".tmp","w");
834 # Fetch all the users
836 if PasswdAttrs == None:
839 # Write out the zone file entry for each user
840 for x in PasswdAttrs:
841 if x[1].has_key("dnsZoneEntry") == 0:
844 # If the account has no PGP key, do not write it
845 if x[1].has_key("keyFingerPrint") == 0:
848 for z in x[1]["dnsZoneEntry"]:
849 Split = z.lower().split()
850 if Split[1].lower() == 'in':
851 for y in range(0,len(Split)):
854 Line = " ".join(Split) + "\n";
856 Host = Split[0] + DNSZone;
857 if BSMTPCheck.match(Line) != None:
858 F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
859 GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
862 F.write("; Errors\n");
865 # Oops, something unspeakable happened.
875 if not Host in HostToIPCache:
878 IPAdressesT = list(set([ (a[0],a[4][0]) for a in socket.getaddrinfo(Host, None)]))
879 except socket.gaierror, (code):
880 if code[0] != -2: raise
882 for addr in IPAdressesT:
883 if addr[0] == socket.AF_INET: IPAdresses += [addr[1], "::ffff:"+addr[1]]
884 else: IPAdresses += [addr[1]]
885 HostToIPCache[Host] = IPAdresses
886 return HostToIPCache[Host]
889 # Generate the ssh known hosts file
890 def GenSSHKnown(l,File,mode=None):
893 OldMask = os.umask(0022);
894 F = open(File + ".tmp","w",0644);
898 if HostAttrs == None:
902 if x[1].has_key("hostname") == 0 or \
903 x[1].has_key("sshRSAHostKey") == 0:
905 Host = GetAttr(x,"hostname");
907 if Host.endswith(HostDomain):
908 HostNames.append(Host[:-(len(HostDomain)+1)])
910 # in the purpose field [[host|some other text]] (where some other text is optional)
911 # makes a hyperlink on the web thing. we now also add these hosts to the ssh known_hosts
912 # file. But so that we don't have to add everything we link we can add an asterisk
913 # and say [[*... to ignore it. In order to be able to add stuff to ssh without
914 # http linking it we also support [[-hostname]] entries.
915 for i in x[1].get("purpose",[]):
916 m = PurposeHostField.match(i)
919 # we ignore [[*..]] entries
920 if m.startswith('*'):
922 if m.startswith('-'):
926 if m.endswith(HostDomain):
927 HostNames.append(m[:-(len(HostDomain)+1)])
929 for I in x[1]["sshRSAHostKey"]:
930 if mode and mode == 'authorized_keys':
931 #Line = 'command="rsync --server --sender -pr . /var/cache/userdir-ldap/hosts/%s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding,from="%s" %s' % (Host, ",".join(HNames + HostToIP(Host)), I)
932 Line = 'command="rsync --server --sender -pr . /var/cache/userdir-ldap/hosts/%s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding %s' % (Host,I)
934 Line = "%s %s" %(",".join(HostNames + HostToIP(Host)), I);
935 Line = Sanitize(Line) + "\n";
937 # Oops, something unspeakable happened.
943 # Generate the debianhosts file (list of all IP addresses)
944 def GenHosts(l,File):
947 OldMask = os.umask(0022)
948 F = open(File + ".tmp","w",0644)
951 # Fetch all the hosts
952 hostnames = l.search_s(HostBaseDn, ldap.SCOPE_ONELEVEL, "hostname=*",
955 if hostnames == None:
960 host = GetAttr(x,"hostname", None)
964 addrs += socket.getaddrinfo(host, None, socket.AF_INET)
968 addrs += socket.getaddrinfo(host, None, socket.AF_INET6)
972 for addrinfo in addrs:
973 if addrinfo[0] in (socket.AF_INET, socket.AF_INET6):
974 addr = addrinfo[4][0]
976 print >> F, addrinfo[4][0]
978 # Oops, something unspeakable happened.
984 def GenKeyrings(l,OutDir):
986 shutil.copy(k, OutDir)
989 # Connect to the ldap server
991 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
992 Pass = F.readline().strip().split(" ")
994 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
996 # Fetch all the groups
998 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
999 ["gid","gidNumber","subGroup"]);
1001 # Generate the SubGroupMap and GroupIDMap
1003 if x[1].has_key("gidNumber") == 0:
1005 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
1006 if x[1].has_key("subGroup") != 0:
1007 SubGroupMap.setdefault(x[1]["gid"][0], []).extend(x[1]["subGroup"]);
1009 # Fetch all the users
1010 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
1011 ["uid","uidNumber","gidNumber","supplementaryGid",\
1012 "gecos","loginShell","userPassword","shadowLastChange",\
1013 "shadowMin","shadowMax","shadowWarning","shadowInactive",
1014 "shadowExpire","emailForward","latitude","longitude",\
1015 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
1016 "keyFingerPrint","privateSub","mailDisableMessage",\
1017 "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
1018 "mailWhitelist", "sudoPassword"]);
1019 # Fetch all the hosts
1020 HostAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
1021 ["hostname","sshRSAHostKey","purpose"]);
1023 # Open the control file
1024 if len(sys.argv) == 1:
1025 F = open(GenerateConf,"r");
1027 F = open(sys.argv[1],"r")
1029 # Generate global things
1030 GlobalDir = GenerateDir+"/";
1031 SSHFiles = GenSSHShadow(l);
1032 GenAllForward(l,GlobalDir+"mail-forward.cdb");
1033 GenMarkers(l,GlobalDir+"markers");
1034 GenPrivate(l,GlobalDir+"debian-private");
1035 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
1036 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
1037 #GenSSHKnown(l,GlobalDir+"authorized_keys", 'authorized_keys');
1038 GenHosts(l,GlobalDir+"debianhosts");
1039 GenMailDisable(l,GlobalDir+"mail-disable");
1040 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
1041 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
1042 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
1043 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
1044 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
1045 GenKeyrings(l,GlobalDir);
1048 GenForward(l,GlobalDir+"forward-alias");
1051 Line = F.readline();
1060 Split = Line.split(" ")
1061 OutDir = GenerateDir + '/' + Split[0] + '/';
1062 try: os.mkdir(OutDir);
1065 # Get the group list and convert any named groups to numerics
1070 ExtraList[I] = None;
1072 GroupList[I] = None;
1073 if GroupIDMap.has_key(I):
1074 GroupList[str(GroupIDMap[I])] = None;
1076 Allowed = GroupList;
1079 CurrentHost = Split[0];
1081 DoLink(GlobalDir,OutDir,"debianhosts");
1082 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
1083 DoLink(GlobalDir,OutDir,"disabled-accounts")
1086 if ExtraList.has_key("[NOPASSWD]"):
1087 userlist = GenPasswd(l,OutDir+"passwd",Split[1], "*");
1089 userlist = GenPasswd(l,OutDir+"passwd",Split[1], "x");
1091 grouprevmap = GenGroup(l,OutDir+"group");
1092 GenShadowSudo(l, OutDir+"sudo-passwd", ExtraList.has_key("[UNTRUSTED]") or ExtraList.has_key("[NOPASSWD]"))
1094 # Now we know who we're allowing on the machine, export
1095 # the relevant ssh keys
1096 GenSSHtarballs(userlist, SSHFiles, grouprevmap, os.path.join(OutDir, 'ssh-keys.tar.gz'))
1098 if ExtraList.has_key("[UNTRUSTED]"):
1099 print "[UNTRUSTED] tag is obsolete and may be removed in the future."
1101 if not ExtraList.has_key("[NOPASSWD]"):
1102 GenShadow(l,OutDir+"shadow");
1104 # Link in global things
1105 if not ExtraList.has_key("[NOMARKERS]"):
1106 DoLink(GlobalDir,OutDir,"markers");
1107 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
1108 DoLink(GlobalDir,OutDir,"mail-disable");
1109 DoLink(GlobalDir,OutDir,"mail-greylist");
1110 DoLink(GlobalDir,OutDir,"mail-callout");
1111 DoLink(GlobalDir,OutDir,"mail-rbl");
1112 DoLink(GlobalDir,OutDir,"mail-rhsbl");
1113 DoLink(GlobalDir,OutDir,"mail-whitelist");
1116 DoLink(GlobalDir,OutDir,"forward-alias");
1118 if ExtraList.has_key("[DNS]"):
1119 GenDNS(l,OutDir+"dns-zone",Split[1]);
1120 GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
1122 if ExtraList.has_key("[BSMTP]"):
1123 GenBSMTP(l,OutDir+"bsmtp",Split[1])
1125 if ExtraList.has_key("[PRIVATE]"):
1126 DoLink(GlobalDir,OutDir,"debian-private")
1128 if ExtraList.has_key("[KEYRING]"):
1130 DoLink(GlobalDir,OutDir,os.path.basename(k))
1133 try: posix.remove(OutDir+os.path.basename(k));
1138 # vim:set shiftwidth=3: