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 *;
43 UUID_FORMAT = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
45 EmailCheck = re.compile("^([^ <>@]+@[^ ,<>@]+)?$");
46 BSMTPCheck = re.compile(".*mx 0 (gluck)\.debian\.org\..*",re.DOTALL);
47 PurposeHostField = re.compile(r"\[\[([\*\-]?[a-z0-9.\-]*)(?:\|.*)?\]\]")
48 DNSZone = ".debian.net"
49 Keyrings = ConfModule.sync_keyrings.split(":")
51 def safe_makedirs(dir):
55 if e.errno == errno.EEXIST:
64 if e.errno == errno.ENOENT:
70 return Str.translate(string.maketrans("\n\r\t","$$$"))
72 def DoLink(From,To,File):
73 try: posix.remove(To+File);
75 posix.link(From+File,To+File);
77 def IsRetired(DnRecord):
79 Looks for accountStatus in the LDAP record and tries to
80 match it against one of the known retired statuses
83 status = GetAttr(DnRecord,"accountStatus", None)
90 if status == "inactive":
93 elif status == "memorial":
96 elif status == "retiring":
97 # We'll give them a few extra days over what we said
98 age = 6 * 31 * 24 * 60 * 60
100 if (time.time() - time.mktime(time.strptime(line[1], "%Y-%m-%d"))) > age:
107 # See if this user is in the group list
108 def IsInGroup(DnRecord):
112 # See if the primary group is in the list
113 if Allowed.has_key(GetAttr(DnRecord,"gidNumber")) != 0:
116 # Check the host based ACL
117 if DnRecord[1].has_key("allowedHost") != 0:
118 for I in DnRecord[1]["allowedHost"]:
122 # See if there are supplementary groups
123 if DnRecord[1].has_key("supplementaryGid") == 0:
127 addGroups(supgroups, DnRecord[1]["supplementaryGid"], GetAttr(DnRecord,"uid"))
129 if Allowed.has_key(g):
138 try: os.remove(File + ".tmp");
140 try: os.remove(File + ".tdb.tmp");
143 def Done(File,F,Fdb):
146 os.rename(File + ".tmp",File);
149 os.rename(File + ".tdb.tmp",File+".tdb");
151 # Generate the password list
152 def GenPasswd(l,File,HomePrefix,PwdMarker):
155 F = open(File + ".tdb.tmp","w");
158 # Fetch all the users
162 for x in PasswdAttrs:
163 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
166 # Do not let people try to buffer overflow some busted passwd parser.
167 if len(GetAttr(x,"gecos")) > 100 or len(GetAttr(x,"loginShell")) > 50:
170 userlist[GetAttr(x, "uid")] = int(GetAttr(x, "gidNumber"))
171 Line = "%s:%s:%s:%s:%s:%s%s:%s" % (GetAttr(x,"uid"),\
173 GetAttr(x,"uidNumber"),GetAttr(x,"gidNumber"),\
174 GetAttr(x,"gecos"),HomePrefix,GetAttr(x,"uid"),\
175 GetAttr(x,"loginShell"));
177 Line = Sanitize(Line) + "\n";
178 F.write("0%u %s" % (I,Line));
179 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
180 F.write("=%s %s" % (GetAttr(x,"uidNumber"),Line));
183 # Oops, something unspeakable happened.
189 # Return the list of users so we know which keys to export
192 # Generate the shadow list
193 def GenShadow(l,File):
196 OldMask = os.umask(0077);
197 F = open(File + ".tdb.tmp","w",0600);
200 # Fetch all the users
204 for x in PasswdAttrs:
205 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
208 Pass = GetAttr(x,"userPassword");
209 if Pass[0:7] != "{crypt}" or len(Pass) > 50:
214 # If the account is locked, mark it as such in shadow
215 # See Debian Bug #308229 for why we set it to 1 instead of 0
216 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
217 or GetAttr(x,"userPassword").startswith("!"):
220 ShadowExpire = GetAttr(x,"shadowExpire")
222 Line = "%s:%s:%s:%s:%s:%s:%s:%s:" % (GetAttr(x,"uid"),\
223 Pass,GetAttr(x,"shadowLastChange"),\
224 GetAttr(x,"shadowMin"),GetAttr(x,"shadowMax"),\
225 GetAttr(x,"shadowWarning"),GetAttr(x,"shadowInactive"),\
227 Line = Sanitize(Line) + "\n";
228 F.write("0%u %s" % (I,Line));
229 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
232 # Oops, something unspeakable happened.
238 # Generate the sudo passwd file
239 def GenShadowSudo(l,File, untrusted):
242 OldMask = os.umask(0077);
243 F = open(File + ".tmp","w",0600);
246 # Fetch all the users
249 for x in PasswdAttrs:
251 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
254 if x[1].has_key('sudoPassword'):
255 for entry in x[1]['sudoPassword']:
256 Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*]+) ([^ ]+)$').match(entry)
259 uuid = Match.group(1)
260 status = Match.group(2)
261 hosts = Match.group(3)
262 cryptedpass = Match.group(4)
264 if status != 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', x[1]['uid'][0], uuid, hosts, cryptedpass):
266 for_all = hosts == "*"
267 for_this_host = CurrentHost in hosts.split(',')
268 if not (for_all or for_this_host):
270 # ignore * passwords for untrusted hosts, but copy host specific passwords
271 if for_all and untrusted:
274 if for_this_host: # this makes sure we take a per-host entry over the for-all entry
279 Line = "%s:%s" % (GetAttr(x,"uid"), Pass)
280 Line = Sanitize(Line) + "\n";
281 F.write("%s" % (Line));
283 # Oops, something unspeakable happened.
289 # Generate the shadow list
291 # Fetch all the users
297 safe_rmtree(os.path.join(GlobalDir, 'userkeys'))
298 safe_makedirs(os.path.join(GlobalDir, 'userkeys'))
300 for x in PasswdAttrs:
302 if x in DisabledUsers:
305 if x[1].has_key("uidNumber") == 0 or \
306 x[1].has_key("sshRSAAuthKey") == 0:
309 User = GetAttr(x,"uid");
313 OldMask = os.umask(0077);
314 File = os.path.join(GlobalDir, 'userkeys', User)
315 F = open(File + ".tmp","w",0600);
318 for I in x[1]["sshRSAAuthKey"]:
319 MultipleLine = "%s" % I
320 MultipleLine = Sanitize(MultipleLine) + "\n"
321 F.write(MultipleLine)
324 userfiles.append(os.path.basename(File))
326 # Oops, something unspeakable happened.
329 Die(masterFileName,masterFile,None)
334 def GenSSHtarballs(userlist, SSHFiles, grouprevmap, target):
335 OldMask = os.umask(0077);
336 tf = tarfile.open(name=os.path.join(GlobalDir, 'ssh-keys-%s.tar.gz' % CurrentHost), mode='w:gz')
338 for f in userlist.keys():
339 if f not in SSHFiles:
341 # If we're not exporting their primary group, don't export
344 if userlist[f] in grouprevmap.keys():
345 grname = grouprevmap[userlist[f]]
348 if int(userlist[f]) <= 100:
349 # In these cases, look it up in the normal way so we
350 # deal with cases where, for instance, users are in group
351 # users as their primary group.
352 grname = grp.getgrgid(userlist[f])[0]
357 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])
360 to = tf.gettarinfo(os.path.join(GlobalDir, 'userkeys', f), f)
361 # These will only be used where the username doesn't
362 # exist on the target system for some reason; hence,
363 # in those cases, the safest thing is for the file to
364 # be owned by root but group nobody. This deals with
365 # the bloody obscure case where the group fails to exist
366 # whilst the user does (in which case we want to avoid
367 # ending up with a file which is owned user:root to avoid
368 # a fairly obvious attack vector)
371 # Using the username / groupname fields avoids any need
372 # to give a shit^W^W^Wcare about the UIDoffset stuff.
376 tf.addfile(to, file(os.path.join(GlobalDir, 'userkeys', f)))
379 os.rename(os.path.join(GlobalDir, 'ssh-keys-%s.tar.gz' % CurrentHost), target)
381 # add a list of groups to existing groups,
382 # including all subgroups thereof, recursively.
383 # basically this proceduces the transitive hull of the groups in
385 def addGroups(existingGroups, newGroups, uid):
386 for group in newGroups:
387 # if it's a <group>@host, split it and verify it's on the current host.
388 s = group.split('@', 1)
389 if len(s) == 2 and s[1] != CurrentHost:
393 # let's see if we handled this group already
394 if group in existingGroups:
397 if not GroupIDMap.has_key(group):
398 print "Group", group, "does not exist but", uid, "is in it"
401 existingGroups.append(group)
403 if SubGroupMap.has_key(group):
404 addGroups(existingGroups, SubGroupMap[group], uid)
406 # Generate the group list
407 def GenGroup(l,File):
411 F = open(File + ".tdb.tmp","w");
413 # Generate the GroupMap
415 for x in GroupIDMap.keys():
418 # Fetch all the users
421 # Sort them into a list of groups having a set of users
422 for x in PasswdAttrs:
423 uid = GetAttr(x,"uid")
424 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
426 if x[1].has_key("supplementaryGid") == 0:
430 addGroups(supgroups, x[1]["supplementaryGid"], uid)
432 GroupMap[g].append(uid);
434 # Output the group file.
436 for x in GroupMap.keys():
437 grouprevmap[GroupIDMap[x]] = x
438 if GroupIDMap.has_key(x) == 0:
440 Line = "%s:x:%u:" % (x,GroupIDMap[x]);
442 for I in GroupMap[x]:
443 Line = Line + ("%s%s" % (Comma,I));
445 Line = Sanitize(Line) + "\n";
446 F.write("0%u %s" % (J,Line));
447 F.write(".%s %s" % (x,Line));
448 F.write("=%u %s" % (GroupIDMap[x],Line));
451 # Oops, something unspeakable happened.
459 # Generate the email forwarding list
460 def GenForward(l,File):
463 OldMask = os.umask(0022);
464 F = open(File + ".tmp","w",0644);
467 # Fetch all the users
470 # Write out the email address for each user
471 for x in PasswdAttrs:
472 if x[1].has_key("emailForward") == 0 or IsInGroup(x) == 0:
475 # Do not allow people to try to buffer overflow busted parsers
476 if len(GetAttr(x,"emailForward")) > 200:
479 # Check the forwarding address
480 if EmailCheck.match(GetAttr(x,"emailForward")) == None:
482 Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
483 Line = Sanitize(Line) + "\n";
486 # Oops, something unspeakable happened.
492 def GenAllForward(l,File):
495 OldMask = os.umask(0022);
496 Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
499 # Fetch all the users
502 # Write out the email address for each user
503 for x in PasswdAttrs:
504 if x[1].has_key("emailForward") == 0:
507 # Do not allow people to try to buffer overflow busted parsers
508 Forward = GetAttr(x,"emailForward");
509 if len(Forward) > 200:
512 # Check the forwarding address
513 if EmailCheck.match(Forward) == None:
516 User = GetAttr(x,"uid");
517 Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
519 # Oops, something unspeakable happened.
523 if Fdb.close() != None:
524 raise "cdbmake gave an error";
526 # Generate the anon XEarth marker file
527 def GenMarkers(l,File):
530 F = open(File + ".tmp","w");
532 # Fetch all the users
535 # Write out the position for each user
536 for x in PasswdAttrs:
537 if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
540 Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
541 Line = Sanitize(Line) + "\n";
546 # Oops, something unspeakable happened.
552 # Generate the debian-private subscription list
553 def GenPrivate(l,File):
556 F = open(File + ".tmp","w");
558 # Fetch all the users
561 # Write out the position for each user
562 for x in PasswdAttrs:
563 if x[1].has_key("privateSub") == 0:
566 # If the account has no PGP key, do not write it
567 if x[1].has_key("keyFingerPrint") == 0:
570 # Must be in the Debian group (yuk, hard coded for now)
571 if GetAttr(x,"gidNumber") != "800":
575 Line = "%s"%(GetAttr(x,"privateSub"));
576 Line = Sanitize(Line) + "\n";
581 # Oops, something unspeakable happened.
587 # Generate a list of locked accounts
588 def GenDisabledAccounts(l,File):
591 F = open(File + ".tmp","w");
593 # Fetch all the users
598 for x in PasswdAttrs:
599 if x[1].has_key("uidNumber") == 0:
602 Pass = GetAttr(x,"userPassword");
604 # *LK* is the reference value for a locked account
605 # password starting with ! is also a locked account
606 if Pass.find("*LK*") != -1 or Pass.startswith("!"):
607 # Format is <login>:<reason>
608 Line = "%s:%s" % (GetAttr(x,"uid"), "Account is locked")
611 F.write(Sanitize(Line) + "\n")
613 DisabledUsers.append(x)
615 # Oops, something unspeakable happened.
621 # Generate the list of local addresses that refuse all mail
622 def GenMailDisable(l,File):
625 F = open(File + ".tmp","w");
627 # Fetch all the users
630 for x in PasswdAttrs:
633 if x[1].has_key("mailDisableMessage"):
634 Reason = GetAttr(x,"mailDisableMessage")
638 # Must be in the Debian group (yuk, hard coded for now)
639 if GetAttr(x,"gidNumber") != "800":
643 Line = "%s: %s"%(GetAttr(x,"uid"),Reason);
644 Line = Sanitize(Line) + "\n";
649 # Oops, something unspeakable happened.
655 # Generate a list of uids that should have boolean affects applied
656 def GenMailBool(l,File,Key):
659 F = open(File + ".tmp","w");
661 # Fetch all the users
664 for x in PasswdAttrs:
667 if x[1].has_key(Key) == 0:
670 # Must be in the Debian group (yuk, hard coded for now)
671 if GetAttr(x,"gidNumber") != "800":
674 if GetAttr(x,Key) != "TRUE":
678 Line = "%s"%(GetAttr(x,"uid"));
679 Line = Sanitize(Line) + "\n";
684 # Oops, something unspeakable happened.
690 # Generate a list of hosts for RBL or whitelist purposes.
691 def GenMailList(l,File,Key):
694 F = open(File + ".tmp","w");
696 # Fetch all the users
699 for x in PasswdAttrs:
702 if x[1].has_key(Key) == 0:
705 # Must be in the Debian group (yuk, hard coded for now)
706 if GetAttr(x,"gidNumber") != "800":
713 if Key == "mailWhitelist":
714 if re.match('^[-\w.]+(/[\d]+)?$',z) == None:
717 if re.match('^[-\w.]+$',z) == None:
721 Line = GetAttr(x,"uid")
725 if Key == "mailRHSBL":
726 Line += "/$sender_address_domain"
729 Line = Sanitize(Line) + "\n";
734 # Oops, something unspeakable happened.
740 def isRoleAccount(pwEntry):
741 if not pwEntry.has_key("objectClass"):
742 raise "pwEntry has no objectClass"
743 oc = pwEntry['objectClass']
745 i = oc.index('debianRoleAccount')
750 # Generate the DNS Zone file
751 def GenDNS(l,File,HomePrefix):
754 F = open(File + ".tmp","w");
756 # Fetch all the users
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
847 # Write out the zone file entry for each user
848 for x in PasswdAttrs:
849 if x[1].has_key("dnsZoneEntry") == 0:
852 # If the account has no PGP key, do not write it
853 if x[1].has_key("keyFingerPrint") == 0:
856 for z in x[1]["dnsZoneEntry"]:
857 Split = z.lower().split()
858 if Split[1].lower() == 'in':
859 for y in range(0,len(Split)):
862 Line = " ".join(Split) + "\n";
864 Host = Split[0] + DNSZone;
865 if BSMTPCheck.match(Line) != None:
866 F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
867 GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
870 F.write("; Errors\n");
873 # Oops, something unspeakable happened.
883 if not Host in HostToIPCache:
886 IPAdressesT = list(set([ (a[0],a[4][0]) for a in socket.getaddrinfo(Host, None)]))
887 except socket.gaierror, (code):
888 if code[0] != -2: raise
890 if not IPAdressesT is None:
891 for addr in IPAdressesT:
892 if addr[0] == socket.AF_INET: IPAdresses += [addr[1], "::ffff:"+addr[1]]
893 else: IPAdresses += [addr[1]]
894 HostToIPCache[Host] = IPAdresses
895 return HostToIPCache[Host]
898 # Generate the ssh known hosts file
899 def GenSSHKnown(l,File,mode=None):
902 OldMask = os.umask(0022);
903 F = open(File + ".tmp","w",0644);
907 if HostAttrs == None:
911 if x[1].has_key("hostname") == 0 or \
912 x[1].has_key("sshRSAHostKey") == 0:
914 Host = GetAttr(x,"hostname");
916 if Host.endswith(HostDomain):
917 HostNames.append(Host[:-(len(HostDomain)+1)])
919 # in the purpose field [[host|some other text]] (where some other text is optional)
920 # makes a hyperlink on the web thing. we now also add these hosts to the ssh known_hosts
921 # file. But so that we don't have to add everything we link we can add an asterisk
922 # and say [[*... to ignore it. In order to be able to add stuff to ssh without
923 # http linking it we also support [[-hostname]] entries.
924 for i in x[1].get("purpose",[]):
925 m = PurposeHostField.match(i)
928 # we ignore [[*..]] entries
929 if m.startswith('*'):
931 if m.startswith('-'):
935 if m.endswith(HostDomain):
936 HostNames.append(m[:-(len(HostDomain)+1)])
938 for I in x[1]["sshRSAHostKey"]:
939 if mode and mode == 'authorized_keys':
940 #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)
941 Line = 'command="rsync --server --sender -pr . /var/cache/userdir-ldap/hosts/%s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding %s' % (Host,I)
943 Line = "%s %s" %(",".join(HostNames + HostToIP(Host)), I);
944 Line = Sanitize(Line) + "\n";
946 # Oops, something unspeakable happened.
952 # Generate the debianhosts file (list of all IP addresses)
953 def GenHosts(l,File):
956 OldMask = os.umask(0022)
957 F = open(File + ".tmp","w",0644)
960 # Fetch all the hosts
961 hostnames = l.search_s(HostBaseDn, ldap.SCOPE_ONELEVEL, "hostname=*",
964 if hostnames == None:
969 host = GetAttr(x,"hostname", None)
973 addrs += socket.getaddrinfo(host, None, socket.AF_INET)
977 addrs += socket.getaddrinfo(host, None, socket.AF_INET6)
981 for addrinfo in addrs:
982 if addrinfo[0] in (socket.AF_INET, socket.AF_INET6):
983 addr = addrinfo[4][0]
985 print >> F, addrinfo[4][0]
987 # Oops, something unspeakable happened.
993 def GenKeyrings(l,OutDir):
995 shutil.copy(k, OutDir)
998 # Connect to the ldap server
1000 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
1001 Pass = F.readline().strip().split(" ")
1003 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
1005 # Fetch all the groups
1007 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
1008 ["gid","gidNumber","subGroup"]);
1010 # Generate the SubGroupMap and GroupIDMap
1012 if x[1].has_key("gidNumber") == 0:
1014 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
1015 if x[1].has_key("subGroup") != 0:
1016 SubGroupMap.setdefault(x[1]["gid"][0], []).extend(x[1]["subGroup"]);
1018 # Fetch all the users
1019 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
1020 ["uid","uidNumber","gidNumber","supplementaryGid",\
1021 "gecos","loginShell","userPassword","shadowLastChange",\
1022 "shadowMin","shadowMax","shadowWarning","shadowInactive",
1023 "shadowExpire","emailForward","latitude","longitude",\
1024 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
1025 "keyFingerPrint","privateSub","mailDisableMessage",\
1026 "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
1027 "mailWhitelist", "sudoPassword", "objectClass", "accountStatus"])
1029 if PasswdAttrs is None:
1032 # Fetch all the hosts
1033 HostAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
1034 ["hostname","sshRSAHostKey","purpose"]);
1036 # Open the control file
1037 if len(sys.argv) == 1:
1038 F = open(GenerateConf,"r");
1040 F = open(sys.argv[1],"r")
1042 # Generate global things
1043 GlobalDir = GenerateDir+"/";
1044 GenMailDisable(l,GlobalDir+"mail-disable")
1046 for x in PasswdAttrs:
1048 RetiredUsers.append(x)
1050 PasswdAttrs = filter(lambda x: not x in RetiredUsers, PasswdAttrs)
1052 SSHFiles = GenSSHShadow(l);
1053 GenAllForward(l,GlobalDir+"mail-forward.cdb");
1054 GenMarkers(l,GlobalDir+"markers");
1055 GenPrivate(l,GlobalDir+"debian-private");
1056 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
1057 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
1058 #GenSSHKnown(l,GlobalDir+"authorized_keys", 'authorized_keys');
1059 GenHosts(l,GlobalDir+"debianhosts");
1060 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
1061 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
1062 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
1063 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
1064 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
1065 GenKeyrings(l,GlobalDir);
1068 GenForward(l,GlobalDir+"forward-alias");
1070 PasswdAttrs = filter(lambda x: not x in DisabledUsers, PasswdAttrs)
1073 Line = F.readline();
1082 Split = Line.split(" ")
1083 OutDir = GenerateDir + '/' + Split[0] + '/';
1084 try: os.mkdir(OutDir);
1087 # Get the group list and convert any named groups to numerics
1092 ExtraList[I] = None;
1094 GroupList[I] = None;
1095 if GroupIDMap.has_key(I):
1096 GroupList[str(GroupIDMap[I])] = None;
1098 Allowed = GroupList;
1101 CurrentHost = Split[0];
1103 DoLink(GlobalDir,OutDir,"debianhosts");
1104 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
1105 DoLink(GlobalDir,OutDir,"disabled-accounts")
1108 if ExtraList.has_key("[NOPASSWD]"):
1109 userlist = GenPasswd(l,OutDir+"passwd",Split[1], "*");
1111 userlist = GenPasswd(l,OutDir+"passwd",Split[1], "x");
1113 grouprevmap = GenGroup(l,OutDir+"group");
1114 GenShadowSudo(l, OutDir+"sudo-passwd", ExtraList.has_key("[UNTRUSTED]") or ExtraList.has_key("[NOPASSWD]"))
1116 # Now we know who we're allowing on the machine, export
1117 # the relevant ssh keys
1118 GenSSHtarballs(userlist, SSHFiles, grouprevmap, os.path.join(OutDir, 'ssh-keys.tar.gz'))
1120 if ExtraList.has_key("[UNTRUSTED]"):
1121 print "[UNTRUSTED] tag is obsolete and may be removed in the future."
1123 if not ExtraList.has_key("[NOPASSWD]"):
1124 GenShadow(l,OutDir+"shadow");
1126 # Link in global things
1127 if not ExtraList.has_key("[NOMARKERS]"):
1128 DoLink(GlobalDir,OutDir,"markers");
1129 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
1130 DoLink(GlobalDir,OutDir,"mail-disable");
1131 DoLink(GlobalDir,OutDir,"mail-greylist");
1132 DoLink(GlobalDir,OutDir,"mail-callout");
1133 DoLink(GlobalDir,OutDir,"mail-rbl");
1134 DoLink(GlobalDir,OutDir,"mail-rhsbl");
1135 DoLink(GlobalDir,OutDir,"mail-whitelist");
1138 DoLink(GlobalDir,OutDir,"forward-alias");
1140 if ExtraList.has_key("[DNS]"):
1141 GenDNS(l,OutDir+"dns-zone",Split[1]);
1142 GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
1144 if ExtraList.has_key("[BSMTP]"):
1145 GenBSMTP(l,OutDir+"bsmtp",Split[1])
1147 if ExtraList.has_key("[PRIVATE]"):
1148 DoLink(GlobalDir,OutDir,"debian-private")
1150 if ExtraList.has_key("[KEYRING]"):
1152 DoLink(GlobalDir,OutDir,os.path.basename(k))
1155 try: posix.remove(OutDir+os.path.basename(k));
1160 # vim:set shiftwidth=3: