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 def isRoleAccount(pwEntry):
739 if not pwEntry.has_key("objectClass"):
740 raise "pwEntry has no objectClass"
741 oc = pwEntry['objectClass']
743 i = oc.index('debianRoleAccount')
748 # Generate the DNS Zone file
749 def GenDNS(l,File,HomePrefix):
752 F = open(File + ".tmp","w");
754 # Fetch all the users
756 if PasswdAttrs == None:
759 # Write out the zone file entry for each user
760 for x in PasswdAttrs:
761 if x[1].has_key("dnsZoneEntry") == 0:
764 # If the account has no PGP key, do not write it
765 if x[1].has_key("keyFingerPrint") == 0 and not isRoleAccount(x[1]):
768 F.write("; %s\n"%(EmailAddress(x)));
769 for z in x[1]["dnsZoneEntry"]:
770 Split = z.lower().split()
771 if Split[1].lower() == 'in':
772 for y in range(0,len(Split)):
775 Line = " ".join(Split) + "\n";
778 Host = Split[0] + DNSZone;
779 if BSMTPCheck.match(Line) != None:
780 F.write("; Has BSMTP\n");
782 # Write some identification information
783 if Split[2].lower() == "a":
784 Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
785 for y in x[1]["keyFingerPrint"]:
786 Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
789 Line = "; Err %s"%(str(Split));
794 F.write("; Errors\n");
797 # Oops, something unspeakable happened.
803 # Generate the DNS SSHFP records
804 def GenSSHFP(l,File,HomePrefix):
807 F = open(File + ".tmp","w")
809 # Fetch all the hosts
811 if HostAttrs == None:
815 if x[1].has_key("hostname") == 0 or \
816 x[1].has_key("sshRSAHostKey") == 0:
818 Host = GetAttr(x,"hostname");
820 for I in x[1]["sshRSAHostKey"]:
822 if Split[0] == 'ssh-rsa':
824 if Split[0] == 'ssh-dss':
826 if Algorithm == None:
828 Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
829 Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
830 Line = Sanitize(Line) + "\n"
832 # Oops, something unspeakable happened.
838 # Generate the BSMTP file
839 def GenBSMTP(l,File,HomePrefix):
842 F = open(File + ".tmp","w");
844 # Fetch all the users
846 if PasswdAttrs == None:
849 # Write out the zone file entry for each user
850 for x in PasswdAttrs:
851 if x[1].has_key("dnsZoneEntry") == 0:
854 # If the account has no PGP key, do not write it
855 if x[1].has_key("keyFingerPrint") == 0:
858 for z in x[1]["dnsZoneEntry"]:
859 Split = z.lower().split()
860 if Split[1].lower() == 'in':
861 for y in range(0,len(Split)):
864 Line = " ".join(Split) + "\n";
866 Host = Split[0] + DNSZone;
867 if BSMTPCheck.match(Line) != None:
868 F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
869 GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
872 F.write("; Errors\n");
875 # Oops, something unspeakable happened.
885 if not Host in HostToIPCache:
888 IPAdressesT = list(set([ (a[0],a[4][0]) for a in socket.getaddrinfo(Host, None)]))
889 except socket.gaierror, (code):
890 if code[0] != -2: raise
892 for addr in IPAdressesT:
893 if addr[0] == socket.AF_INET: IPAdresses += [addr[1], "::ffff:"+addr[1]]
894 else: IPAdresses += [addr[1]]
895 HostToIPCache[Host] = IPAdresses
896 return HostToIPCache[Host]
899 # Generate the ssh known hosts file
900 def GenSSHKnown(l,File,mode=None):
903 OldMask = os.umask(0022);
904 F = open(File + ".tmp","w",0644);
908 if HostAttrs == None:
912 if x[1].has_key("hostname") == 0 or \
913 x[1].has_key("sshRSAHostKey") == 0:
915 Host = GetAttr(x,"hostname");
917 if Host.endswith(HostDomain):
918 HostNames.append(Host[:-(len(HostDomain)+1)])
920 # in the purpose field [[host|some other text]] (where some other text is optional)
921 # makes a hyperlink on the web thing. we now also add these hosts to the ssh known_hosts
922 # file. But so that we don't have to add everything we link we can add an asterisk
923 # and say [[*... to ignore it. In order to be able to add stuff to ssh without
924 # http linking it we also support [[-hostname]] entries.
925 for i in x[1].get("purpose",[]):
926 m = PurposeHostField.match(i)
929 # we ignore [[*..]] entries
930 if m.startswith('*'):
932 if m.startswith('-'):
936 if m.endswith(HostDomain):
937 HostNames.append(m[:-(len(HostDomain)+1)])
939 for I in x[1]["sshRSAHostKey"]:
940 if mode and mode == 'authorized_keys':
941 #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)
942 Line = 'command="rsync --server --sender -pr . /var/cache/userdir-ldap/hosts/%s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding %s' % (Host,I)
944 Line = "%s %s" %(",".join(HostNames + HostToIP(Host)), I);
945 Line = Sanitize(Line) + "\n";
947 # Oops, something unspeakable happened.
953 # Generate the debianhosts file (list of all IP addresses)
954 def GenHosts(l,File):
957 OldMask = os.umask(0022)
958 F = open(File + ".tmp","w",0644)
961 # Fetch all the hosts
962 hostnames = l.search_s(HostBaseDn, ldap.SCOPE_ONELEVEL, "hostname=*",
965 if hostnames == None:
970 host = GetAttr(x,"hostname", None)
974 addrs += socket.getaddrinfo(host, None, socket.AF_INET)
978 addrs += socket.getaddrinfo(host, None, socket.AF_INET6)
982 for addrinfo in addrs:
983 if addrinfo[0] in (socket.AF_INET, socket.AF_INET6):
984 addr = addrinfo[4][0]
986 print >> F, addrinfo[4][0]
988 # Oops, something unspeakable happened.
994 def GenKeyrings(l,OutDir):
996 shutil.copy(k, OutDir)
999 # Connect to the ldap server
1001 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
1002 Pass = F.readline().strip().split(" ")
1004 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
1006 # Fetch all the groups
1008 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
1009 ["gid","gidNumber","subGroup"]);
1011 # Generate the SubGroupMap and GroupIDMap
1013 if x[1].has_key("gidNumber") == 0:
1015 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
1016 if x[1].has_key("subGroup") != 0:
1017 SubGroupMap.setdefault(x[1]["gid"][0], []).extend(x[1]["subGroup"]);
1019 # Fetch all the users
1020 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
1021 ["uid","uidNumber","gidNumber","supplementaryGid",\
1022 "gecos","loginShell","userPassword","shadowLastChange",\
1023 "shadowMin","shadowMax","shadowWarning","shadowInactive",
1024 "shadowExpire","emailForward","latitude","longitude",\
1025 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
1026 "keyFingerPrint","privateSub","mailDisableMessage",\
1027 "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
1028 "mailWhitelist", "sudoPassword", "objectClass"]);
1029 # Fetch all the hosts
1030 HostAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
1031 ["hostname","sshRSAHostKey","purpose"]);
1033 # Open the control file
1034 if len(sys.argv) == 1:
1035 F = open(GenerateConf,"r");
1037 F = open(sys.argv[1],"r")
1039 # Generate global things
1040 GlobalDir = GenerateDir+"/";
1041 SSHFiles = GenSSHShadow(l);
1042 GenAllForward(l,GlobalDir+"mail-forward.cdb");
1043 GenMarkers(l,GlobalDir+"markers");
1044 GenPrivate(l,GlobalDir+"debian-private");
1045 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
1046 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
1047 #GenSSHKnown(l,GlobalDir+"authorized_keys", 'authorized_keys');
1048 GenHosts(l,GlobalDir+"debianhosts");
1049 GenMailDisable(l,GlobalDir+"mail-disable");
1050 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
1051 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
1052 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
1053 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
1054 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
1055 GenKeyrings(l,GlobalDir);
1058 GenForward(l,GlobalDir+"forward-alias");
1061 Line = F.readline();
1070 Split = Line.split(" ")
1071 OutDir = GenerateDir + '/' + Split[0] + '/';
1072 try: os.mkdir(OutDir);
1075 # Get the group list and convert any named groups to numerics
1080 ExtraList[I] = None;
1082 GroupList[I] = None;
1083 if GroupIDMap.has_key(I):
1084 GroupList[str(GroupIDMap[I])] = None;
1086 Allowed = GroupList;
1089 CurrentHost = Split[0];
1091 DoLink(GlobalDir,OutDir,"debianhosts");
1092 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
1093 DoLink(GlobalDir,OutDir,"disabled-accounts")
1096 if ExtraList.has_key("[NOPASSWD]"):
1097 userlist = GenPasswd(l,OutDir+"passwd",Split[1], "*");
1099 userlist = GenPasswd(l,OutDir+"passwd",Split[1], "x");
1101 grouprevmap = GenGroup(l,OutDir+"group");
1102 GenShadowSudo(l, OutDir+"sudo-passwd", ExtraList.has_key("[UNTRUSTED]") or ExtraList.has_key("[NOPASSWD]"))
1104 # Now we know who we're allowing on the machine, export
1105 # the relevant ssh keys
1106 GenSSHtarballs(userlist, SSHFiles, grouprevmap, os.path.join(OutDir, 'ssh-keys.tar.gz'))
1108 if ExtraList.has_key("[UNTRUSTED]"):
1109 print "[UNTRUSTED] tag is obsolete and may be removed in the future."
1111 if not ExtraList.has_key("[NOPASSWD]"):
1112 GenShadow(l,OutDir+"shadow");
1114 # Link in global things
1115 if not ExtraList.has_key("[NOMARKERS]"):
1116 DoLink(GlobalDir,OutDir,"markers");
1117 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
1118 DoLink(GlobalDir,OutDir,"mail-disable");
1119 DoLink(GlobalDir,OutDir,"mail-greylist");
1120 DoLink(GlobalDir,OutDir,"mail-callout");
1121 DoLink(GlobalDir,OutDir,"mail-rbl");
1122 DoLink(GlobalDir,OutDir,"mail-rhsbl");
1123 DoLink(GlobalDir,OutDir,"mail-whitelist");
1126 DoLink(GlobalDir,OutDir,"forward-alias");
1128 if ExtraList.has_key("[DNS]"):
1129 GenDNS(l,OutDir+"dns-zone",Split[1]);
1130 GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
1132 if ExtraList.has_key("[BSMTP]"):
1133 GenBSMTP(l,OutDir+"bsmtp",Split[1])
1135 if ExtraList.has_key("[PRIVATE]"):
1136 DoLink(GlobalDir,OutDir,"debian-private")
1138 if ExtraList.has_key("[KEYRING]"):
1140 DoLink(GlobalDir,OutDir,os.path.basename(k))
1143 try: posix.remove(OutDir+os.path.basename(k));
1148 # vim:set shiftwidth=3: