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 *;
42 UUID_FORMAT = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
44 EmailCheck = re.compile("^([^ <>@]+@[^ ,<>@]+)?$");
45 BSMTPCheck = re.compile(".*mx 0 (gluck)\.debian\.org\..*",re.DOTALL);
46 PurposeHostField = re.compile(r"\[\[([\*\-]?[a-z0-9.\-]*)(?:\|.*)?\]\]")
47 DNSZone = ".debian.net"
48 Keyrings = ConfModule.sync_keyrings.split(":")
50 def safe_makedirs(dir):
54 if e.errno == errno.EEXIST:
63 if e.errno == errno.ENOENT:
69 return Str.translate(string.maketrans("\n\r\t","$$$"))
71 def DoLink(From,To,File):
72 try: posix.remove(To+File);
74 posix.link(From+File,To+File);
76 def IsRetired(DnRecord):
78 Looks for accountStatus in the LDAP record and tries to
79 match it against one of the known retired statuses
82 status = GetAttr(DnRecord,"accountStatus", None)
86 if status.find("inactive") != -1:
89 if status.find("memorial") != -1:
92 if status.find("retiring") != -1:
94 # We'll give them a few extra days over what we said
95 age = 6 * 31 * 24 * 60 * 60
96 if (time.time() - time.mktime(time.strptime(line[1], "%Y-%m-%d")) > (age):
101 # See if this user is in the group list
102 def IsInGroup(DnRecord):
106 # See if the primary group is in the list
107 if Allowed.has_key(GetAttr(DnRecord,"gidNumber")) != 0:
110 # Check the host based ACL
111 if DnRecord[1].has_key("allowedHost") != 0:
112 for I in DnRecord[1]["allowedHost"]:
116 # See if there are supplementary groups
117 if DnRecord[1].has_key("supplementaryGid") == 0:
121 addGroups(supgroups, DnRecord[1]["supplementaryGid"], GetAttr(DnRecord,"uid"))
123 if Allowed.has_key(g):
132 try: os.remove(File + ".tmp");
134 try: os.remove(File + ".tdb.tmp");
137 def Done(File,F,Fdb):
140 os.rename(File + ".tmp",File);
143 os.rename(File + ".tdb.tmp",File+".tdb");
145 # Generate the password list
146 def GenPasswd(l,File,HomePrefix,PwdMarker):
149 F = open(File + ".tdb.tmp","w");
152 # Fetch all the users
154 if PasswdAttrs == None:
158 for x in PasswdAttrs:
162 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
165 # Do not let people try to buffer overflow some busted passwd parser.
166 if len(GetAttr(x,"gecos")) > 100 or len(GetAttr(x,"loginShell")) > 50:
169 userlist[GetAttr(x, "uid")] = int(GetAttr(x, "gidNumber"))
170 Line = "%s:%s:%s:%s:%s:%s%s:%s" % (GetAttr(x,"uid"),\
172 GetAttr(x,"uidNumber"),GetAttr(x,"gidNumber"),\
173 GetAttr(x,"gecos"),HomePrefix,GetAttr(x,"uid"),\
174 GetAttr(x,"loginShell"));
176 Line = Sanitize(Line) + "\n";
177 F.write("0%u %s" % (I,Line));
178 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
179 F.write("=%s %s" % (GetAttr(x,"uidNumber"),Line));
182 # Oops, something unspeakable happened.
188 # Return the list of users so we know which keys to export
191 # Generate the shadow list
192 def GenShadow(l,File):
195 OldMask = os.umask(0077);
196 F = open(File + ".tdb.tmp","w",0600);
199 # Fetch all the users
201 if PasswdAttrs == None:
205 for x in PasswdAttrs:
209 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
212 Pass = GetAttr(x,"userPassword");
213 if Pass[0:7] != "{crypt}" or len(Pass) > 50:
218 # If the account is locked, mark it as such in shadow
219 # See Debian Bug #308229 for why we set it to 1 instead of 0
220 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
221 or GetAttr(x,"userPassword").startswith("!"):
224 ShadowExpire = GetAttr(x,"shadowExpire")
226 Line = "%s:%s:%s:%s:%s:%s:%s:%s:" % (GetAttr(x,"uid"),\
227 Pass,GetAttr(x,"shadowLastChange"),\
228 GetAttr(x,"shadowMin"),GetAttr(x,"shadowMax"),\
229 GetAttr(x,"shadowWarning"),GetAttr(x,"shadowInactive"),\
231 Line = Sanitize(Line) + "\n";
232 F.write("0%u %s" % (I,Line));
233 F.write(".%s %s" % (GetAttr(x,"uid"),Line));
236 # Oops, something unspeakable happened.
242 # Generate the sudo passwd file
243 def GenShadowSudo(l,File, untrusted):
246 OldMask = os.umask(0077);
247 F = open(File + ".tmp","w",0600);
250 # Fetch all the users
252 if PasswdAttrs == None:
255 for x in PasswdAttrs:
260 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
263 if x[1].has_key('sudoPassword'):
264 for entry in x[1]['sudoPassword']:
265 Match = re.compile('^('+UUID_FORMAT+') (confirmed:[0-9a-f]{40}|unconfirmed) ([a-z0-9.,*]+) ([^ ]+)$').match(entry)
268 uuid = Match.group(1)
269 status = Match.group(2)
270 hosts = Match.group(3)
271 cryptedpass = Match.group(4)
273 if status != 'confirmed:'+make_passwd_hmac('password-is-confirmed', 'sudo', x[1]['uid'][0], uuid, hosts, cryptedpass):
275 for_all = hosts == "*"
276 for_this_host = CurrentHost in hosts.split(',')
277 if not (for_all or for_this_host):
279 # ignore * passwords for untrusted hosts, but copy host specific passwords
280 if for_all and untrusted:
283 if for_this_host: # this makes sure we take a per-host entry over the for-all entry
288 Line = "%s:%s" % (GetAttr(x,"uid"), Pass)
289 Line = Sanitize(Line) + "\n";
290 F.write("%s" % (Line));
292 # Oops, something unspeakable happened.
298 # Generate the shadow list
300 # Fetch all the users
305 if PasswdAttrs == None:
308 safe_rmtree(os.path.join(GlobalDir, 'userkeys'))
309 safe_makedirs(os.path.join(GlobalDir, 'userkeys'))
311 for x in PasswdAttrs:
315 # If the account is locked, do not write it.
316 # This is a partial stop-gap. The ssh also needs to change this
317 # to ignore ~/.ssh/authorized* files.
318 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
319 or GetAttr(x,"userPassword").startswith("!"):
322 if x[1].has_key("uidNumber") == 0 or \
323 x[1].has_key("sshRSAAuthKey") == 0:
325 User = GetAttr(x,"uid");
329 OldMask = os.umask(0077);
330 File = os.path.join(GlobalDir, 'userkeys', User)
331 F = open(File + ".tmp","w",0600);
334 for I in x[1]["sshRSAAuthKey"]:
335 MultipleLine = "%s" % I
336 MultipleLine = Sanitize(MultipleLine) + "\n"
337 F.write(MultipleLine)
340 userfiles.append(os.path.basename(File))
342 # Oops, something unspeakable happened.
345 Die(masterFileName,masterFile,None)
350 def GenSSHtarballs(userlist, SSHFiles, grouprevmap, target):
351 OldMask = os.umask(0077);
352 tf = tarfile.open(name=os.path.join(GlobalDir, 'ssh-keys-%s.tar.gz' % CurrentHost), mode='w:gz')
354 for f in userlist.keys():
355 if f not in SSHFiles:
357 # If we're not exporting their primary group, don't export
360 if userlist[f] in grouprevmap.keys():
361 grname = grouprevmap[userlist[f]]
364 if int(userlist[f]) <= 100:
365 # In these cases, look it up in the normal way so we
366 # deal with cases where, for instance, users are in group
367 # users as their primary group.
368 grname = grp.getgrgid(userlist[f])[0]
373 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])
376 to = tf.gettarinfo(os.path.join(GlobalDir, 'userkeys', f), f)
377 # These will only be used where the username doesn't
378 # exist on the target system for some reason; hence,
379 # in those cases, the safest thing is for the file to
380 # be owned by root but group nobody. This deals with
381 # the bloody obscure case where the group fails to exist
382 # whilst the user does (in which case we want to avoid
383 # ending up with a file which is owned user:root to avoid
384 # a fairly obvious attack vector)
387 # Using the username / groupname fields avoids any need
388 # to give a shit^W^W^Wcare about the UIDoffset stuff.
392 tf.addfile(to, file(os.path.join(GlobalDir, 'userkeys', f)))
395 os.rename(os.path.join(GlobalDir, 'ssh-keys-%s.tar.gz' % CurrentHost), target)
397 # add a list of groups to existing groups,
398 # including all subgroups thereof, recursively.
399 # basically this proceduces the transitive hull of the groups in
401 def addGroups(existingGroups, newGroups, uid):
402 for group in newGroups:
403 # if it's a <group>@host, split it and verify it's on the current host.
404 s = group.split('@', 1)
405 if len(s) == 2 and s[1] != CurrentHost:
409 # let's see if we handled this group already
410 if group in existingGroups:
413 if not GroupIDMap.has_key(group):
414 print "Group", group, "does not exist but", uid, "is in it"
417 existingGroups.append(group)
419 if SubGroupMap.has_key(group):
420 addGroups(existingGroups, SubGroupMap[group], uid)
422 # Generate the group list
423 def GenGroup(l,File):
427 F = open(File + ".tdb.tmp","w");
429 # Generate the GroupMap
431 for x in GroupIDMap.keys():
434 # Fetch all the users
436 if PasswdAttrs == None:
439 # Sort them into a list of groups having a set of users
440 for x in PasswdAttrs:
441 uid = GetAttr(x,"uid")
442 if x[1].has_key("uidNumber") == 0 or IsInGroup(x) == 0:
444 if x[1].has_key("supplementaryGid") == 0:
448 addGroups(supgroups, x[1]["supplementaryGid"], uid)
450 GroupMap[g].append(uid);
452 # Output the group file.
454 for x in GroupMap.keys():
455 grouprevmap[GroupIDMap[x]] = x
456 if GroupIDMap.has_key(x) == 0:
458 Line = "%s:x:%u:" % (x,GroupIDMap[x]);
460 for I in GroupMap[x]:
461 Line = Line + ("%s%s" % (Comma,I));
463 Line = Sanitize(Line) + "\n";
464 F.write("0%u %s" % (J,Line));
465 F.write(".%s %s" % (x,Line));
466 F.write("=%u %s" % (GroupIDMap[x],Line));
469 # Oops, something unspeakable happened.
477 # Generate the email forwarding list
478 def GenForward(l,File):
481 OldMask = os.umask(0022);
482 F = open(File + ".tmp","w",0644);
485 # Fetch all the users
487 if PasswdAttrs == None:
490 # Write out the email address for each user
491 for x in PasswdAttrs:
495 if x[1].has_key("emailForward") == 0 or IsInGroup(x) == 0:
498 # Do not allow people to try to buffer overflow busted parsers
499 if len(GetAttr(x,"emailForward")) > 200:
502 # Check the forwarding address
503 if EmailCheck.match(GetAttr(x,"emailForward")) == None:
505 Line = "%s: %s" % (GetAttr(x,"uid"),GetAttr(x,"emailForward"));
506 Line = Sanitize(Line) + "\n";
509 # Oops, something unspeakable happened.
515 def GenAllForward(l,File):
518 OldMask = os.umask(0022);
519 Fdb = os.popen("cdbmake %s %s.tmp"%(File,File),"w");
522 # Fetch all the users
524 if PasswdAttrs == None:
527 # Write out the email address for each user
528 for x in PasswdAttrs:
532 if x[1].has_key("emailForward") == 0:
535 # Do not allow people to try to buffer overflow busted parsers
536 Forward = GetAttr(x,"emailForward");
537 if len(Forward) > 200:
540 # Check the forwarding address
541 if EmailCheck.match(Forward) == None:
544 User = GetAttr(x,"uid");
545 Fdb.write("+%d,%d:%s->%s\n"%(len(User),len(Forward),User,Forward));
547 # Oops, something unspeakable happened.
551 if Fdb.close() != None:
552 raise "cdbmake gave an error";
554 # Generate the anon XEarth marker file
555 def GenMarkers(l,File):
558 F = open(File + ".tmp","w");
560 # Fetch all the users
562 if PasswdAttrs == None:
565 # Write out the position for each user
566 for x in PasswdAttrs:
570 if x[1].has_key("latitude") == 0 or x[1].has_key("longitude") == 0:
573 Line = "%8s %8s \"\""%(DecDegree(GetAttr(x,"latitude"),1),DecDegree(GetAttr(x,"longitude"),1));
574 Line = Sanitize(Line) + "\n";
579 # Oops, something unspeakable happened.
585 # Generate the debian-private subscription list
586 def GenPrivate(l,File):
589 F = open(File + ".tmp","w");
591 # Fetch all the users
593 if PasswdAttrs == None:
596 # Write out the position for each user
597 for x in PasswdAttrs:
601 if x[1].has_key("privateSub") == 0:
604 # If the account is locked, do not write it
605 if (GetAttr(x,"userPassword").find("*LK*") != -1) \
606 or GetAttr(x,"userPassword").startswith("!"):
609 # If the account has no PGP key, do not write it
610 if x[1].has_key("keyFingerPrint") == 0:
613 # Must be in the Debian group (yuk, hard coded for now)
614 if GetAttr(x,"gidNumber") != "800":
618 Line = "%s"%(GetAttr(x,"privateSub"));
619 Line = Sanitize(Line) + "\n";
624 # Oops, something unspeakable happened.
630 # Generate a list of locked accounts
631 def GenDisabledAccounts(l,File):
634 F = open(File + ".tmp","w");
636 # Fetch all the users
639 if PasswdAttrs == None:
643 for x in PasswdAttrs:
644 if x[1].has_key("uidNumber") == 0:
647 Pass = GetAttr(x,"userPassword");
649 # *LK* is the reference value for a locked account
650 # password starting with ! is also a locked account
651 if Pass.find("*LK*") != -1 or Pass.startswith("!"):
652 # Format is <login>:<reason>
653 Line = "%s:%s" % (GetAttr(x,"uid"), "Account is locked")
656 F.write(Sanitize(Line) + "\n")
658 disabledusers.append(x)
660 # Oops, something unspeakable happened.
666 # Generate the list of local addresses that refuse all mail
667 def GenMailDisable(l,File):
670 F = open(File + ".tmp","w");
672 # Fetch all the users
674 if PasswdAttrs == None:
677 for x in PasswdAttrs:
683 if x[1].has_key("mailDisableMessage"):
684 Reason = GetAttr(x,"mailDisableMessage")
688 # Must be in the Debian group (yuk, hard coded for now)
689 if GetAttr(x,"gidNumber") != "800":
693 Line = "%s: %s"%(GetAttr(x,"uid"),Reason);
694 Line = Sanitize(Line) + "\n";
699 # Oops, something unspeakable happened.
705 # Generate a list of uids that should have boolean affects applied
706 def GenMailBool(l,File,Key):
709 F = open(File + ".tmp","w");
711 # Fetch all the users
713 if PasswdAttrs == None:
716 for x in PasswdAttrs:
722 if x[1].has_key(Key) == 0:
725 # Must be in the Debian group (yuk, hard coded for now)
726 if GetAttr(x,"gidNumber") != "800":
729 if GetAttr(x,Key) != "TRUE":
733 Line = "%s"%(GetAttr(x,"uid"));
734 Line = Sanitize(Line) + "\n";
739 # Oops, something unspeakable happened.
745 # Generate a list of hosts for RBL or whitelist purposes.
746 def GenMailList(l,File,Key):
749 F = open(File + ".tmp","w");
751 # Fetch all the users
753 if PasswdAttrs == None:
756 for x in PasswdAttrs:
762 if x[1].has_key(Key) == 0:
765 # Must be in the Debian group (yuk, hard coded for now)
766 if GetAttr(x,"gidNumber") != "800":
773 if Key == "mailWhitelist":
774 if re.match('^[-\w.]+(/[\d]+)?$',z) == None:
777 if re.match('^[-\w.]+$',z) == None:
781 Line = GetAttr(x,"uid")
785 if Key == "mailRHSBL":
786 Line += "/$sender_address_domain"
789 Line = Sanitize(Line) + "\n";
794 # Oops, something unspeakable happened.
800 def isRoleAccount(pwEntry):
801 if not pwEntry.has_key("objectClass"):
802 raise "pwEntry has no objectClass"
803 oc = pwEntry['objectClass']
805 i = oc.index('debianRoleAccount')
810 # Generate the DNS Zone file
811 def GenDNS(l,File,HomePrefix):
814 F = open(File + ".tmp","w");
816 # Fetch all the users
818 if PasswdAttrs == None:
821 # Write out the zone file entry for each user
822 for x in PasswdAttrs:
823 if x[1].has_key("dnsZoneEntry") == 0:
826 # If the account has no PGP key, do not write it
827 if x[1].has_key("keyFingerPrint") == 0 and not isRoleAccount(x[1]):
830 F.write("; %s\n"%(EmailAddress(x)));
831 for z in x[1]["dnsZoneEntry"]:
832 Split = z.lower().split()
833 if Split[1].lower() == 'in':
834 for y in range(0,len(Split)):
837 Line = " ".join(Split) + "\n";
840 Host = Split[0] + DNSZone;
841 if BSMTPCheck.match(Line) != None:
842 F.write("; Has BSMTP\n");
844 # Write some identification information
845 if Split[2].lower() == "a":
846 Line = "%s IN TXT \"%s\"\n"%(Split[0],EmailAddress(x));
847 for y in x[1]["keyFingerPrint"]:
848 Line = Line + "%s IN TXT \"PGP %s\"\n"%(Split[0],FormatPGPKey(y));
851 Line = "; Err %s"%(str(Split));
856 F.write("; Errors\n");
859 # Oops, something unspeakable happened.
865 # Generate the DNS SSHFP records
866 def GenSSHFP(l,File,HomePrefix):
869 F = open(File + ".tmp","w")
871 # Fetch all the hosts
873 if HostAttrs == None:
877 if x[1].has_key("hostname") == 0 or \
878 x[1].has_key("sshRSAHostKey") == 0:
880 Host = GetAttr(x,"hostname");
882 for I in x[1]["sshRSAHostKey"]:
884 if Split[0] == 'ssh-rsa':
886 if Split[0] == 'ssh-dss':
888 if Algorithm == None:
890 Fingerprint = sha.new(base64.decodestring(Split[1])).hexdigest()
891 Line = "%s. IN SSHFP %u 1 %s" % (Host,Algorithm,Fingerprint)
892 Line = Sanitize(Line) + "\n"
894 # Oops, something unspeakable happened.
900 # Generate the BSMTP file
901 def GenBSMTP(l,File,HomePrefix):
904 F = open(File + ".tmp","w");
906 # Fetch all the users
908 if PasswdAttrs == None:
911 # Write out the zone file entry for each user
912 for x in PasswdAttrs:
913 if x[1].has_key("dnsZoneEntry") == 0:
916 # If the account has no PGP key, do not write it
917 if x[1].has_key("keyFingerPrint") == 0:
920 for z in x[1]["dnsZoneEntry"]:
921 Split = z.lower().split()
922 if Split[1].lower() == 'in':
923 for y in range(0,len(Split)):
926 Line = " ".join(Split) + "\n";
928 Host = Split[0] + DNSZone;
929 if BSMTPCheck.match(Line) != None:
930 F.write("%s: user=%s group=Debian file=%s%s/bsmtp/%s\n"%(Host,
931 GetAttr(x,"uid"),HomePrefix,GetAttr(x,"uid"),Host));
934 F.write("; Errors\n");
937 # Oops, something unspeakable happened.
947 if not Host in HostToIPCache:
950 IPAdressesT = list(set([ (a[0],a[4][0]) for a in socket.getaddrinfo(Host, None)]))
951 except socket.gaierror, (code):
952 if code[0] != -2: raise
954 if not IPAdressesT is None:
955 for addr in IPAdressesT:
956 if addr[0] == socket.AF_INET: IPAdresses += [addr[1], "::ffff:"+addr[1]]
957 else: IPAdresses += [addr[1]]
958 HostToIPCache[Host] = IPAdresses
959 return HostToIPCache[Host]
962 # Generate the ssh known hosts file
963 def GenSSHKnown(l,File,mode=None):
966 OldMask = os.umask(0022);
967 F = open(File + ".tmp","w",0644);
971 if HostAttrs == None:
975 if x[1].has_key("hostname") == 0 or \
976 x[1].has_key("sshRSAHostKey") == 0:
978 Host = GetAttr(x,"hostname");
980 if Host.endswith(HostDomain):
981 HostNames.append(Host[:-(len(HostDomain)+1)])
983 # in the purpose field [[host|some other text]] (where some other text is optional)
984 # makes a hyperlink on the web thing. we now also add these hosts to the ssh known_hosts
985 # file. But so that we don't have to add everything we link we can add an asterisk
986 # and say [[*... to ignore it. In order to be able to add stuff to ssh without
987 # http linking it we also support [[-hostname]] entries.
988 for i in x[1].get("purpose",[]):
989 m = PurposeHostField.match(i)
992 # we ignore [[*..]] entries
993 if m.startswith('*'):
995 if m.startswith('-'):
999 if m.endswith(HostDomain):
1000 HostNames.append(m[:-(len(HostDomain)+1)])
1002 for I in x[1]["sshRSAHostKey"]:
1003 if mode and mode == 'authorized_keys':
1004 #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)
1005 Line = 'command="rsync --server --sender -pr . /var/cache/userdir-ldap/hosts/%s",no-port-forwarding,no-X11-forwarding,no-agent-forwarding %s' % (Host,I)
1007 Line = "%s %s" %(",".join(HostNames + HostToIP(Host)), I);
1008 Line = Sanitize(Line) + "\n";
1010 # Oops, something unspeakable happened.
1016 # Generate the debianhosts file (list of all IP addresses)
1017 def GenHosts(l,File):
1020 OldMask = os.umask(0022)
1021 F = open(File + ".tmp","w",0644)
1024 # Fetch all the hosts
1025 hostnames = l.search_s(HostBaseDn, ldap.SCOPE_ONELEVEL, "hostname=*",
1028 if hostnames == None:
1033 host = GetAttr(x,"hostname", None)
1037 addrs += socket.getaddrinfo(host, None, socket.AF_INET)
1038 except socket.error:
1041 addrs += socket.getaddrinfo(host, None, socket.AF_INET6)
1042 except socket.error:
1045 for addrinfo in addrs:
1046 if addrinfo[0] in (socket.AF_INET, socket.AF_INET6):
1047 addr = addrinfo[4][0]
1048 if addr not in seen:
1049 print >> F, addrinfo[4][0]
1051 # Oops, something unspeakable happened.
1057 def GenKeyrings(l,OutDir):
1059 shutil.copy(k, OutDir)
1062 # Connect to the ldap server
1064 F = open(PassDir+"/pass-"+pwd.getpwuid(os.getuid())[0],"r");
1065 Pass = F.readline().strip().split(" ")
1067 l.simple_bind_s("uid="+Pass[0]+","+BaseDn,Pass[1]);
1069 # Fetch all the groups
1071 Attrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"gid=*",\
1072 ["gid","gidNumber","subGroup"]);
1074 # Generate the SubGroupMap and GroupIDMap
1076 if x[1].has_key("gidNumber") == 0:
1078 GroupIDMap[x[1]["gid"][0]] = int(x[1]["gidNumber"][0]);
1079 if x[1].has_key("subGroup") != 0:
1080 SubGroupMap.setdefault(x[1]["gid"][0], []).extend(x[1]["subGroup"]);
1082 # Fetch all the users
1083 PasswdAttrs = l.search_s(BaseDn,ldap.SCOPE_ONELEVEL,"uid=*",\
1084 ["uid","uidNumber","gidNumber","supplementaryGid",\
1085 "gecos","loginShell","userPassword","shadowLastChange",\
1086 "shadowMin","shadowMax","shadowWarning","shadowInactive",
1087 "shadowExpire","emailForward","latitude","longitude",\
1088 "allowedHost","sshRSAAuthKey","dnsZoneEntry","cn","sn",\
1089 "keyFingerPrint","privateSub","mailDisableMessage",\
1090 "mailGreylisting","mailCallout","mailRBL","mailRHSBL",\
1091 "mailWhitelist", "sudoPassword", "objectClass", "accountStatus"]);
1092 # Fetch all the hosts
1093 HostAttrs = l.search_s(HostBaseDn,ldap.SCOPE_ONELEVEL,"sshRSAHostKey=*",\
1094 ["hostname","sshRSAHostKey","purpose"]);
1096 # Open the control file
1097 if len(sys.argv) == 1:
1098 F = open(GenerateConf,"r");
1100 F = open(sys.argv[1],"r")
1102 # Generate global things
1103 GlobalDir = GenerateDir+"/";
1104 SSHFiles = GenSSHShadow(l);
1105 GenAllForward(l,GlobalDir+"mail-forward.cdb");
1106 GenMarkers(l,GlobalDir+"markers");
1107 GenPrivate(l,GlobalDir+"debian-private");
1108 GenDisabledAccounts(l,GlobalDir+"disabled-accounts");
1109 GenSSHKnown(l,GlobalDir+"ssh_known_hosts");
1110 #GenSSHKnown(l,GlobalDir+"authorized_keys", 'authorized_keys');
1111 GenHosts(l,GlobalDir+"debianhosts");
1112 GenMailDisable(l,GlobalDir+"mail-disable");
1113 GenMailBool(l,GlobalDir+"mail-greylist","mailGreylisting");
1114 GenMailBool(l,GlobalDir+"mail-callout","mailCallout");
1115 GenMailList(l,GlobalDir+"mail-rbl","mailRBL");
1116 GenMailList(l,GlobalDir+"mail-rhsbl","mailRHSBL");
1117 GenMailList(l,GlobalDir+"mail-whitelist","mailWhitelist");
1118 GenKeyrings(l,GlobalDir);
1121 GenForward(l,GlobalDir+"forward-alias");
1123 PasswdAttrs = filter(lambda x: not x in disabledusers, PasswdAttrs)
1126 Line = F.readline();
1135 Split = Line.split(" ")
1136 OutDir = GenerateDir + '/' + Split[0] + '/';
1137 try: os.mkdir(OutDir);
1140 # Get the group list and convert any named groups to numerics
1145 ExtraList[I] = None;
1147 GroupList[I] = None;
1148 if GroupIDMap.has_key(I):
1149 GroupList[str(GroupIDMap[I])] = None;
1151 Allowed = GroupList;
1154 CurrentHost = Split[0];
1156 DoLink(GlobalDir,OutDir,"debianhosts");
1157 DoLink(GlobalDir,OutDir,"ssh_known_hosts");
1158 DoLink(GlobalDir,OutDir,"disabled-accounts")
1161 if ExtraList.has_key("[NOPASSWD]"):
1162 userlist = GenPasswd(l,OutDir+"passwd",Split[1], "*");
1164 userlist = GenPasswd(l,OutDir+"passwd",Split[1], "x");
1166 grouprevmap = GenGroup(l,OutDir+"group");
1167 GenShadowSudo(l, OutDir+"sudo-passwd", ExtraList.has_key("[UNTRUSTED]") or ExtraList.has_key("[NOPASSWD]"))
1169 # Now we know who we're allowing on the machine, export
1170 # the relevant ssh keys
1171 GenSSHtarballs(userlist, SSHFiles, grouprevmap, os.path.join(OutDir, 'ssh-keys.tar.gz'))
1173 if ExtraList.has_key("[UNTRUSTED]"):
1174 print "[UNTRUSTED] tag is obsolete and may be removed in the future."
1176 if not ExtraList.has_key("[NOPASSWD]"):
1177 GenShadow(l,OutDir+"shadow");
1179 # Link in global things
1180 if not ExtraList.has_key("[NOMARKERS]"):
1181 DoLink(GlobalDir,OutDir,"markers");
1182 DoLink(GlobalDir,OutDir,"mail-forward.cdb");
1183 DoLink(GlobalDir,OutDir,"mail-disable");
1184 DoLink(GlobalDir,OutDir,"mail-greylist");
1185 DoLink(GlobalDir,OutDir,"mail-callout");
1186 DoLink(GlobalDir,OutDir,"mail-rbl");
1187 DoLink(GlobalDir,OutDir,"mail-rhsbl");
1188 DoLink(GlobalDir,OutDir,"mail-whitelist");
1191 DoLink(GlobalDir,OutDir,"forward-alias");
1193 if ExtraList.has_key("[DNS]"):
1194 GenDNS(l,OutDir+"dns-zone",Split[1]);
1195 GenSSHFP(l,OutDir+"dns-sshfp",Split[1])
1197 if ExtraList.has_key("[BSMTP]"):
1198 GenBSMTP(l,OutDir+"bsmtp",Split[1])
1200 if ExtraList.has_key("[PRIVATE]"):
1201 DoLink(GlobalDir,OutDir,"debian-private")
1203 if ExtraList.has_key("[KEYRING]"):
1205 DoLink(GlobalDir,OutDir,os.path.basename(k))
1208 try: posix.remove(OutDir+os.path.basename(k));
1213 # vim:set shiftwidth=3: