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:
959 if x[1].has_key("hostname") == 0:
961 Host = GetAttr(x,"hostname");
963 Addr = socket.gethostbyname(Host);
964 F.write(Addr + "\n");
967 # Oops, something unspeakable happened.
973 def GenKeyrings(l,OutDir):
975 shutil.copy(k, OutDir)
978 # Connect to the ldap server
980 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
981 Pass = F.readline().strip().split(" ")
983 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
985 # Fetch all the groups
987 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
988 ["gid","gidNumber","subGroup"]);
990 # Generate the SubGroupMap and GroupIDMap
992 if x[1].has_key("gidNumber") == 0:
994 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
995 if x[1].has_key("subGroup") != 0:
996 SubGroupMap.setdefault(x[1]["gid"][0], []).extend(x[1]["subGroup"]);
998 # Fetch all the users
999 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
1000 ["uid","uidNumber","gidNumber","supplementaryGid",\
1001 "gecos","loginShell","userPassword","shadowLastChange",\
1002 "shadowMin","shadowMax","shadowWarning","shadowInactive",
1003 "shadowExpire","emailForward","latitude","longitude",\
1004 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
1005 "keyFingerPrint","privateSub","mailDisableMessage",\
1006 "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
1007 "mailWhitelist", "sudoPassword"]);
1008 # Fetch all the hosts
1009 HostAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
1010 ["hostname","sshRSAHostKey","purpose"]);
1012 # Open the control file
1013 if len(sys.argv) == 1:
1014 F = open(GenerateConf,"r");
1016 F = open(sys.argv[1],"r")
1018 # Generate global things
1019 GlobalDir = GenerateDir+"/";
1020 SSHFiles = GenSSHShadow(l);
1021 GenAllForward(l,GlobalDir+"mail-forward.cdb");
1022 GenMarkers(l,GlobalDir+"markers");
1023 GenPrivate(l,GlobalDir+"debian-private");
1024 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
1025 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
1026 #GenSSHKnown(l,GlobalDir+"authorized_keys", 'authorized_keys');
1027 GenHosts(l,GlobalDir+"debianhosts");
1028 GenMailDisable(l,GlobalDir+"mail-disable");
1029 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
1030 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
1031 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
1032 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
1033 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
1034 GenKeyrings(l,GlobalDir);
1037 GenForward(l,GlobalDir+"forward-alias");
1040 Line = F.readline();
1049 Split = Line.split(" ")
1050 OutDir = GenerateDir + '/' + Split[0] + '/';
1051 try: os.mkdir(OutDir);
1054 # Get the group list and convert any named groups to numerics
1059 ExtraList[I] = None;
1061 GroupList[I] = None;
1062 if GroupIDMap.has_key(I):
1063 GroupList[str(GroupIDMap[I])] = None;
1065 Allowed = GroupList;
1068 CurrentHost = Split[0];
1070 DoLink(GlobalDir,OutDir,"debianhosts");
1071 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
1072 DoLink(GlobalDir,OutDir,"disabled-accounts")
1075 if ExtraList.has_key("[NOPASSWD]"):
1076 userlist = GenPasswd(l,OutDir+"passwd",Split[1], "*");
1078 userlist = GenPasswd(l,OutDir+"passwd",Split[1], "x");
1080 grouprevmap = GenGroup(l,OutDir+"group");
1081 GenShadowSudo(l, OutDir+"sudo-passwd", ExtraList.has_key("[UNTRUSTED]") or ExtraList.has_key("[NOPASSWD]"))
1083 # Now we know who we're allowing on the machine, export
1084 # the relevant ssh keys
1085 GenSSHtarballs(userlist, SSHFiles, grouprevmap, os.path.join(OutDir, 'ssh-keys.tar.gz'))
1087 if ExtraList.has_key("[UNTRUSTED]"):
1088 print "[UNTRUSTED] tag is obsolete and may be removed in the future."
1090 if not ExtraList.has_key("[NOPASSWD]"):
1091 GenShadow(l,OutDir+"shadow");
1093 # Link in global things
1094 if not ExtraList.has_key("[NOMARKERS]"):
1095 DoLink(GlobalDir,OutDir,"markers");
1096 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
1097 DoLink(GlobalDir,OutDir,"mail-disable");
1098 DoLink(GlobalDir,OutDir,"mail-greylist");
1099 DoLink(GlobalDir,OutDir,"mail-callout");
1100 DoLink(GlobalDir,OutDir,"mail-rbl");
1101 DoLink(GlobalDir,OutDir,"mail-rhsbl");
1102 DoLink(GlobalDir,OutDir,"mail-whitelist");
1105 DoLink(GlobalDir,OutDir,"forward-alias");
1107 if ExtraList.has_key("[DNS]"):
1108 GenDNS(l,OutDir+"dns-zone",Split[1]);
1109 GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
1111 if ExtraList.has_key("[BSMTP]"):
1112 GenBSMTP(l,OutDir+"bsmtp",Split[1])
1114 if ExtraList.has_key("[PRIVATE]"):
1115 DoLink(GlobalDir,OutDir,"debian-private")
1117 if ExtraList.has_key("[KEYRING]"):
1119 DoLink(GlobalDir,OutDir,os.path.basename(k))
1122 try: posix.remove(OutDir+os.path.basename(k));
1127 # vim:set shiftwidth=3: