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:
94 # Check the supplementary groups
95 for I in DnRecord[1]["supplementaryGid"]:
98 if len(s) == 2 and s[1] != CurrentHost:
100 if Allowed.has_key(group):
109 try: os.remove(File + ".tmp");
111 try: os.remove(File + ".tdb.tmp");
114 def Done(File,F,Fdb):
117 os.rename(File + ".tmp",File);
120 os.rename(File + ".tdb.tmp",File+".tdb");
122 # Generate the password list
123 def GenPasswd(l,File,HomePrefix,PwdMarker):
126 F = open(File + ".tdb.tmp","w");
129 # Fetch all the users
131 if PasswdAttrs == None:
135 for x in PasswdAttrs:
136 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
139 # Do not let people try to buffer overflow some busted passwd parser.
140 if len(GetAttr(x,"gecos")) > 100 or len(GetAttr(x,"loginShell")) > 50:
143 userlist[GetAttr(x, "uid")] = int(GetAttr(x, "gidNumber"))
144 Line = "%s:%s:%s:%s:%s:%s%s:%s" % (GetAttr(x,"uid"),\
146 GetAttr(x,"uidNumber"),GetAttr(x,"gidNumber"),\
147 GetAttr(x,"gecos"),HomePrefix,GetAttr(x,"uid"),\
148 GetAttr(x,"loginShell"));
150 Line = Sanitize(Line) + "\n";
151 F.write("0%u %s" % (I,Line));
152 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
153 F.write("=%s %s" % (GetAttr(x,"uidNumber"),Line));
156 # Oops, something unspeakable happened.
162 # Return the list of users so we know which keys to export
165 # Generate the shadow list
166 def GenShadow(l,File):
169 OldMask = os.umask(0077);
170 F = open(File + ".tdb.tmp","w",0600);
173 # Fetch all the users
175 if PasswdAttrs == None:
179 for x in PasswdAttrs:
180 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
183 Pass = GetAttr(x,"userPassword");
184 if Pass[0:7] != "{crypt}" or len(Pass) > 50:
189 # If the account is locked, mark it as such in shadow
190 # See Debian Bug #308229 for why we set it to 1 instead of 0
191 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
192 or GetAttr(x,"userPassword").startswith("!"):
195 ShadowExpire = GetAttr(x,"shadowExpire")
197 Line = "%s:%s:%s:%s:%s:%s:%s:%s:" % (GetAttr(x,"uid"),\
198 Pass,GetAttr(x,"shadowLastChange"),\
199 GetAttr(x,"shadowMin"),GetAttr(x,"shadowMax"),\
200 GetAttr(x,"shadowWarning"),GetAttr(x,"shadowInactive"),\
202 Line = Sanitize(Line) + "\n";
203 F.write("0%u %s" % (I,Line));
204 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
207 # Oops, something unspeakable happened.
213 # Generate the sudo passwd file
214 def GenShadowSudo(l,File, untrusted):
217 OldMask = os.umask(0077);
218 F = open(File + ".tmp","w",0600);
221 # Fetch all the users
223 if PasswdAttrs == None:
226 for x in PasswdAttrs:
228 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
231 if x[1].has_key('sudoPassword'):
232 for entry in x[1]['sudoPassword']:
233 Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*]+) ([^ ]+)$').match(entry)
236 uuid = Match.group(1)
237 status = Match.group(2)
238 hosts = Match.group(3)
239 cryptedpass = Match.group(4)
241 if status != 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', x[1]['uid'][0], uuid, hosts, cryptedpass):
243 for_all = hosts == "*"
244 for_this_host = CurrentHost in hosts.split(',')
245 if not (for_all or for_this_host):
247 # ignore * passwords for untrusted hosts, but copy host specific passwords
248 if for_all and untrusted:
251 if for_this_host: # this makes sure we take a per-host entry over the for-all entry
256 Line = "%s:%s" % (GetAttr(x,"uid"), Pass)
257 Line = Sanitize(Line) + "\n";
258 F.write("%s" % (Line));
260 # Oops, something unspeakable happened.
266 # Generate the shadow list
268 # Fetch all the users
273 if PasswdAttrs == None:
276 safe_rmtree(os.path.join(GlobalDir, 'userkeys'))
277 safe_makedirs(os.path.join(GlobalDir, 'userkeys'))
279 for x in PasswdAttrs:
280 # If the account is locked, do not write it.
281 # This is a partial stop-gap. The ssh also needs to change this
282 # to ignore ~/.ssh/authorized* files.
283 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
284 or GetAttr(x,"userPassword").startswith("!"):
287 if x[1].has_key("uidNumber") == 0 or \
288 x[1].has_key("sshRSAAuthKey") == 0:
290 User = GetAttr(x,"uid");
294 OldMask = os.umask(0077);
295 File = os.path.join(GlobalDir, 'userkeys', User)
296 F = open(File + ".tmp","w",0600);
299 for I in x[1]["sshRSAAuthKey"]:
300 MultipleLine = "%s" % I
301 MultipleLine = Sanitize(MultipleLine) + "\n"
302 F.write(MultipleLine)
305 userfiles.append(os.path.basename(File))
307 # Oops, something unspeakable happened.
310 Die(masterFileName,masterFile,None)
315 def GenSSHtarballs(userlist, SSHFiles, grouprevmap, target):
316 OldMask = os.umask(0077);
317 tf = tarfile.open(name=os.path.join(GlobalDir, 'ssh-keys-%s.tar.gz' % CurrentHost), mode='w:gz')
319 for f in userlist.keys():
320 if f not in SSHFiles:
322 # If we're not exporting their primary group, don't export
325 if userlist[f] in grouprevmap.keys():
326 grname = grouprevmap[userlist[f]]
329 if int(userlist[f]) <= 100:
330 # In these cases, look it up in the normal way so we
331 # deal with cases where, for instance, users are in group
332 # users as their primary group.
333 grname = grp.getgrgid(userlist[f])[0]
338 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])
341 to = tf.gettarinfo(os.path.join(GlobalDir, 'userkeys', f), f)
342 # These will only be used where the username doesn't
343 # exist on the target system for some reason; hence,
344 # in those cases, the safest thing is for the file to
345 # be owned by root but group nobody. This deals with
346 # the bloody obscure case where the group fails to exist
347 # whilst the user does (in which case we want to avoid
348 # ending up with a file which is owned user:root to avoid
349 # a fairly obvious attack vector)
352 # Using the username / groupname fields avoids any need
353 # to give a shit^W^W^Wcare about the UIDoffset stuff.
357 tf.addfile(to, file(os.path.join(GlobalDir, 'userkeys', f)))
360 os.rename(os.path.join(GlobalDir, 'ssh-keys-%s.tar.gz' % CurrentHost), target)
362 # add a list of groups to existing groups,
363 # including all subgroups thereof, recursively.
364 # basically this proceduces the transitive hull of the groups in
366 def addGroups(existingGroups, newGroups, uid):
367 for group in newGroups:
368 # if it's a <group>@host, split it and verify it's on the current host.
369 s = group.split('@', 1)
370 if len(s) == 2 and s[1] != CurrentHost:
374 # let's see if we handled this group already
375 if group in existingGroups:
378 if not GroupIDMap.has_key(group):
379 print "Group", group, "does not exist but", uid, "is in it"
382 existingGroups.append(group)
384 if SubGroupMap.has_key(group):
385 addGroups(existingGroups, SubGroupMap[group], uid)
387 # Generate the group list
388 def GenGroup(l,File):
392 F = open(File + ".tdb.tmp","w");
394 # Generate the GroupMap
396 for x in GroupIDMap.keys():
399 # Fetch all the users
401 if PasswdAttrs == None:
404 # Sort them into a list of groups having a set of users
405 for x in PasswdAttrs:
406 uid = GetAttr(x,"uid")
407 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
409 if x[1].has_key("supplementaryGid") == 0:
413 addGroups(supgroups, x[1]["supplementaryGid"], uid)
415 GroupMap[g].append(uid);
417 # Output the group file.
419 for x in GroupMap.keys():
420 grouprevmap[GroupIDMap[x]] = x
421 if GroupIDMap.has_key(x) == 0:
423 Line = "%s:x:%u:" % (x,GroupIDMap[x]);
425 for I in GroupMap[x]:
426 Line = Line + ("%s%s" % (Comma,I));
428 Line = Sanitize(Line) + "\n";
429 F.write("0%u %s" % (J,Line));
430 F.write(".%s %s" % (x,Line));
431 F.write("=%u %s" % (GroupIDMap[x],Line));
434 # Oops, something unspeakable happened.
442 # Generate the email forwarding list
443 def GenForward(l,File):
446 OldMask = os.umask(0022);
447 F = open(File + ".tmp","w",0644);
450 # Fetch all the users
452 if PasswdAttrs == None:
455 # Write out the email address for each user
456 for x in PasswdAttrs:
457 if x[1].has_key("emailForward") == 0 or IsInGroup(x) == 0:
460 # Do not allow people to try to buffer overflow busted parsers
461 if len(GetAttr(x,"emailForward")) > 200:
464 # Check the forwarding address
465 if EmailCheck.match(GetAttr(x,"emailForward")) == None:
467 Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
468 Line = Sanitize(Line) + "\n";
471 # Oops, something unspeakable happened.
477 def GenAllForward(l,File):
480 OldMask = os.umask(0022);
481 Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
484 # Fetch all the users
486 if PasswdAttrs == None:
489 # Write out the email address for each user
490 for x in PasswdAttrs:
491 if x[1].has_key("emailForward") == 0:
494 # Do not allow people to try to buffer overflow busted parsers
495 Forward = GetAttr(x,"emailForward");
496 if len(Forward) > 200:
499 # Check the forwarding address
500 if EmailCheck.match(Forward) == None:
503 User = GetAttr(x,"uid");
504 Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
506 # Oops, something unspeakable happened.
510 if Fdb.close() != None:
511 raise "cdbmake gave an error";
513 # Generate the anon XEarth marker file
514 def GenMarkers(l,File):
517 F = open(File + ".tmp","w");
519 # Fetch all the users
521 if PasswdAttrs == None:
524 # Write out the position for each user
525 for x in PasswdAttrs:
526 if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
529 Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
530 Line = Sanitize(Line) + "\n";
535 # Oops, something unspeakable happened.
541 # Generate the debian-private subscription list
542 def GenPrivate(l,File):
545 F = open(File + ".tmp","w");
547 # Fetch all the users
549 if PasswdAttrs == None:
552 # Write out the position for each user
553 for x in PasswdAttrs:
554 if x[1].has_key("privateSub") == 0:
557 # If the account is locked, do not write it
558 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
559 or GetAttr(x,"userPassword").startswith("!"):
562 # If the account has no PGP key, do not write it
563 if x[1].has_key("keyFingerPrint") == 0:
566 # Must be in the Debian group (yuk, hard coded for now)
567 if GetAttr(x,"gidNumber") != "800":
571 Line = "%s"%(GetAttr(x,"privateSub"));
572 Line = Sanitize(Line) + "\n";
577 # Oops, something unspeakable happened.
583 # Generate a list of locked accounts
584 def GenDisabledAccounts(l,File):
587 F = open(File + ".tmp","w");
589 # Fetch all the users
591 if PasswdAttrs == None:
595 for x in PasswdAttrs:
596 if x[1].has_key("uidNumber") == 0:
599 Pass = GetAttr(x,"userPassword");
601 # *LK* is the reference value for a locked account
602 # password starting with ! is also a locked account
603 if Pass.find("*LK*") != -1 or Pass.startswith("!"):
604 # Format is <login>:<reason>
605 Line = "%s:%s" % (GetAttr(x,"uid"), "Account is locked")
608 F.write(Sanitize(Line) + "\n")
610 # Oops, something unspeakable happened.
616 # Generate the list of local addresses that refuse all mail
617 def GenMailDisable(l,File):
620 F = open(File + ".tmp","w");
622 # Fetch all the users
624 if PasswdAttrs == None:
627 for x in PasswdAttrs:
630 if x[1].has_key("mailDisableMessage"):
631 Reason = GetAttr(x,"mailDisableMessage")
635 # Must be in the Debian group (yuk, hard coded for now)
636 if GetAttr(x,"gidNumber") != "800":
640 Line = "%s: %s"%(GetAttr(x,"uid"),Reason);
641 Line = Sanitize(Line) + "\n";
646 # Oops, something unspeakable happened.
652 # Generate a list of uids that should have boolean affects applied
653 def GenMailBool(l,File,Key):
656 F = open(File + ".tmp","w");
658 # Fetch all the users
660 if PasswdAttrs == None:
663 for x in PasswdAttrs:
666 if x[1].has_key(Key) == 0:
669 # Must be in the Debian group (yuk, hard coded for now)
670 if GetAttr(x,"gidNumber") != "800":
673 if GetAttr(x,Key) != "TRUE":
677 Line = "%s"%(GetAttr(x,"uid"));
678 Line = Sanitize(Line) + "\n";
683 # Oops, something unspeakable happened.
689 # Generate a list of hosts for RBL or whitelist purposes.
690 def GenMailList(l,File,Key):
693 F = open(File + ".tmp","w");
695 # Fetch all the users
697 if PasswdAttrs == None:
700 for x in PasswdAttrs:
703 if x[1].has_key(Key) == 0:
706 # Must be in the Debian group (yuk, hard coded for now)
707 if GetAttr(x,"gidNumber") != "800":
714 if Key == "mailWhitelist":
715 if re.match('^[-\w.]+(/[\d]+)?$',z) == None:
718 if re.match('^[-\w.]+$',z) == None:
722 Line = GetAttr(x,"uid")
726 if Key == "mailRHSBL":
727 Line += "/$sender_address_domain"
730 Line = Sanitize(Line) + "\n";
735 # Oops, something unspeakable happened.
741 # Generate the DNS Zone file
742 def GenDNS(l,File,HomePrefix):
745 F = open(File + ".tmp","w");
747 # Fetch all the users
749 if PasswdAttrs == None:
752 # Write out the zone file entry for each user
753 for x in PasswdAttrs:
754 if x[1].has_key("dnsZoneEntry") == 0:
757 # If the account has no PGP key, do not write it
758 if x[1].has_key("keyFingerPrint") == 0:
761 F.write("; %s\n"%(EmailAddress(x)));
762 for z in x[1]["dnsZoneEntry"]:
763 Split = z.lower().split()
764 if Split[1].lower() == 'in':
765 for y in range(0,len(Split)):
768 Line = " ".join(Split) + "\n";
771 Host = Split[0] + DNSZone;
772 if BSMTPCheck.match(Line) != None:
773 F.write("; Has BSMTP\n");
775 # Write some identification information
776 if Split[2].lower() == "a":
777 Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
778 for y in x[1]["keyFingerPrint"]:
779 Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
782 Line = "; Err %s"%(str(Split));
787 F.write("; Errors\n");
790 # Oops, something unspeakable happened.
796 # Generate the DNS SSHFP records
797 def GenSSHFP(l,File,HomePrefix):
800 F = open(File + ".tmp","w")
802 # Fetch all the hosts
804 if HostAttrs == None:
808 if x[1].has_key("hostname") == 0 or \
809 x[1].has_key("sshRSAHostKey") == 0:
811 Host = GetAttr(x,"hostname");
813 for I in x[1]["sshRSAHostKey"]:
815 if Split[0] == 'ssh-rsa':
817 if Split[0] == 'ssh-dss':
819 if Algorithm == None:
821 Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
822 Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
823 Line = Sanitize(Line) + "\n"
825 # Oops, something unspeakable happened.
831 # Generate the BSMTP file
832 def GenBSMTP(l,File,HomePrefix):
835 F = open(File + ".tmp","w");
837 # Fetch all the users
839 if PasswdAttrs == None:
842 # Write out the zone file entry for each user
843 for x in PasswdAttrs:
844 if x[1].has_key("dnsZoneEntry") == 0:
847 # If the account has no PGP key, do not write it
848 if x[1].has_key("keyFingerPrint") == 0:
851 for z in x[1]["dnsZoneEntry"]:
852 Split = z.lower().split()
853 if Split[1].lower() == 'in':
854 for y in range(0,len(Split)):
857 Line = " ".join(Split) + "\n";
859 Host = Split[0] + DNSZone;
860 if BSMTPCheck.match(Line) != None:
861 F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
862 GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
865 F.write("; Errors\n");
868 # Oops, something unspeakable happened.
878 if not Host in HostToIPCache:
881 IPAdressesT = list(set([ (a[0],a[4][0]) for a in socket.getaddrinfo(Host, None)]))
882 except socket.gaierror, (code):
883 if code[0] != -2: raise
885 for addr in IPAdressesT:
886 if addr[0] == socket.AF_INET: IPAdresses += [addr[1], "::ffff:"+addr[1]]
887 else: IPAdresses += [addr[1]]
888 HostToIPCache[Host] = IPAdresses
889 return HostToIPCache[Host]
892 # Generate the ssh known hosts file
893 def GenSSHKnown(l,File,mode=None):
896 OldMask = os.umask(0022);
897 F = open(File + ".tmp","w",0644);
901 if HostAttrs == None:
905 if x[1].has_key("hostname") == 0 or \
906 x[1].has_key("sshRSAHostKey") == 0:
908 Host = GetAttr(x,"hostname");
910 if Host.endswith(HostDomain):
911 HostNames.append(Host[:-(len(HostDomain)+1)])
913 # in the purpose field [[host|some other text]] (where some other text is optional)
914 # makes a hyperlink on the web thing. we now also add these hosts to the ssh known_hosts
915 # file. But so that we don't have to add everything we link we can add an asterisk
916 # and say [[*... to ignore it. In order to be able to add stuff to ssh without
917 # http linking it we also support [[-hostname]] entries.
918 for i in x[1].get("purpose",[]):
919 m = PurposeHostField.match(i)
922 # we ignore [[*..]] entries
923 if m.startswith('*'):
925 if m.startswith('-'):
929 if m.endswith(HostDomain):
930 HostNames.append(m[:-(len(HostDomain)+1)])
932 for I in x[1]["sshRSAHostKey"]:
933 if mode and mode == 'authorized_keys':
934 #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)
935 Line = 'command="rsync --server --sender -pr . /var/cache/userdir-ldap/hosts/%s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding %s' % (Host,I)
937 Line = "%s %s" %(",".join(HostNames + HostToIP(Host)), I);
938 Line = Sanitize(Line) + "\n";
940 # Oops, something unspeakable happened.
946 # Generate the debianhosts file (list of all IP addresses)
947 def GenHosts(l,File):
950 OldMask = os.umask(0022);
951 F = open(File + ".tmp","w",0644);
954 # Fetch all the hosts
955 HostNames = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"hostname=*",\
958 if HostNames == None:
962 if x[1].has_key("hostname") == 0:
964 Host = GetAttr(x,"hostname");
966 Addr = socket.gethostbyname(Host);
967 F.write(Addr + "\n");
970 # Oops, something unspeakable happened.
976 def GenKeyrings(l,OutDir):
978 shutil.copy(k, OutDir)
981 # Connect to the ldap server
983 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
984 Pass = F.readline().strip().split(" ")
986 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
988 # Fetch all the groups
990 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
991 ["gid","gidNumber","subGroup"]);
993 # Generate the SubGroupMap and GroupIDMap
995 if x[1].has_key("gidNumber") == 0:
997 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
998 if x[1].has_key("subGroup") != 0:
999 SubGroupMap.setdefault(x[1]["gid"][0], []).extend(x[1]["subGroup"]);
1001 # Fetch all the users
1002 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
1003 ["uid","uidNumber","gidNumber","supplementaryGid",\
1004 "gecos","loginShell","userPassword","shadowLastChange",\
1005 "shadowMin","shadowMax","shadowWarning","shadowInactive",
1006 "shadowExpire","emailForward","latitude","longitude",\
1007 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
1008 "keyFingerPrint","privateSub","mailDisableMessage",\
1009 "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
1010 "mailWhitelist", "sudoPassword"]);
1011 # Fetch all the hosts
1012 HostAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
1013 ["hostname","sshRSAHostKey","purpose"]);
1015 # Open the control file
1016 if len(sys.argv) == 1:
1017 F = open(GenerateConf,"r");
1019 F = open(sys.argv[1],"r")
1021 # Generate global things
1022 GlobalDir = GenerateDir+"/";
1023 SSHFiles = GenSSHShadow(l);
1024 GenAllForward(l,GlobalDir+"mail-forward.cdb");
1025 GenMarkers(l,GlobalDir+"markers");
1026 GenPrivate(l,GlobalDir+"debian-private");
1027 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
1028 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
1029 #GenSSHKnown(l,GlobalDir+"authorized_keys", 'authorized_keys');
1030 GenHosts(l,GlobalDir+"debianhosts");
1031 GenMailDisable(l,GlobalDir+"mail-disable");
1032 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
1033 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
1034 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
1035 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
1036 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
1037 GenKeyrings(l,GlobalDir);
1040 GenForward(l,GlobalDir+"forward-alias");
1043 Line = F.readline();
1052 Split = Line.split(" ")
1053 OutDir = GenerateDir + '/' + Split[0] + '/';
1054 try: os.mkdir(OutDir);
1057 # Get the group list and convert any named groups to numerics
1062 ExtraList[I] = None;
1064 GroupList[I] = None;
1065 if GroupIDMap.has_key(I):
1066 GroupList[str(GroupIDMap[I])] = None;
1068 Allowed = GroupList;
1071 CurrentHost = Split[0];
1073 DoLink(GlobalDir,OutDir,"debianhosts");
1074 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
1075 DoLink(GlobalDir,OutDir,"disabled-accounts")
1078 if ExtraList.has_key("[NOPASSWD]"):
1079 userlist = GenPasswd(l,OutDir+"passwd",Split[1], "*");
1081 userlist = GenPasswd(l,OutDir+"passwd",Split[1], "x");
1083 grouprevmap = GenGroup(l,OutDir+"group");
1084 GenShadowSudo(l, OutDir+"sudo-passwd", ExtraList.has_key("[UNTRUSTED]") or ExtraList.has_key("[NOPASSWD]"))
1086 # Now we know who we're allowing on the machine, export
1087 # the relevant ssh keys
1088 GenSSHtarballs(userlist, SSHFiles, grouprevmap, os.path.join(OutDir, 'ssh-keys.tar.gz'))
1090 if ExtraList.has_key("[UNTRUSTED]"):
1091 print "[UNTRUSTED] tag is obsolete and may be removed in the future."
1093 if not ExtraList.has_key("[NOPASSWD]"):
1094 GenShadow(l,OutDir+"shadow");
1096 # Link in global things
1097 if not ExtraList.has_key("[NOMARKERS]"):
1098 DoLink(GlobalDir,OutDir,"markers");
1099 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
1100 DoLink(GlobalDir,OutDir,"mail-disable");
1101 DoLink(GlobalDir,OutDir,"mail-greylist");
1102 DoLink(GlobalDir,OutDir,"mail-callout");
1103 DoLink(GlobalDir,OutDir,"mail-rbl");
1104 DoLink(GlobalDir,OutDir,"mail-rhsbl");
1105 DoLink(GlobalDir,OutDir,"mail-whitelist");
1108 DoLink(GlobalDir,OutDir,"forward-alias");
1110 if ExtraList.has_key("[DNS]"):
1111 GenDNS(l,OutDir+"dns-zone",Split[1]);
1112 GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
1114 if ExtraList.has_key("[BSMTP]"):
1115 GenBSMTP(l,OutDir+"bsmtp",Split[1])
1117 if ExtraList.has_key("[PRIVATE]"):
1118 DoLink(GlobalDir,OutDir,"debian-private")
1120 if ExtraList.has_key("[KEYRING]"):
1122 DoLink(GlobalDir,OutDir,os.path.basename(k))
1125 try: posix.remove(OutDir+os.path.basename(k));
1130 # vim:set shiftwidth=3: