daily pastebin goal
34%
SHARE
TWEET

Untitled

a guest May 22nd, 2018 106 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.             if len(hostips) > 1:
  2.                 logger.warning("More than one IPv4 address found. Using %s",
  3.                     hostip)
  4.     if hostip == "127.0.0.1":
  5.         hostip = None
  6.     if hostip is None:
  7.         logger.warning("No IPv4 address will be assigned")
  8.  
  9.     if hostip6 is None:
  10.         logger.info("Looking up IPv6 addresses")
  11.         hostips = interface_ips_v6(lp, linklocal=False)
  12.         if hostips:
  13.             hostip6 = hostips[0]
  14.         if len(hostips) > 1:
  15.             logger.warning("More than one IPv6 address found. Using %s", hostip6)
  16.     if hostip6 is None:
  17.         logger.warning("No IPv6 address will be assigned")
  18.  
  19.     if serverrole is None:
  20.         serverrole = lp.get("server role")
  21.  
  22.     assert serverrole in ("domain controller", "member server", "standalone")
  23.     if invocationid is None:
  24.         invocationid = str(uuid.uuid4())
  25.  
  26.     if not os.path.exists(paths.private_dir):
  27.         os.mkdir(paths.private_dir)
  28.     if not os.path.exists(os.path.join(paths.private_dir, "tls")):
  29.         os.mkdir(os.path.join(paths.private_dir, "tls"))
  30.  
  31.     ldapi_url = "ldapi://%s" % urllib.quote(paths.s4_ldapi_path, safe="")
  32.  
  33.     schema = Schema(domainsid, invocationid=invocationid,
  34.         schemadn=names.schemadn)
  35.  
  36.     if backend_type == "ldb":
  37.         provision_backend = LDBBackend(backend_type, paths=paths,
  38.             lp=lp, credentials=credentials,
  39.             names=names, logger=logger)
  40.     elif backend_type == "existing":
  41.         provision_backend = ExistingBackend(backend_type, paths=paths,
  42.             lp=lp, credentials=credentials,
  43.             names=names, logger=logger,
  44.             ldap_backend_forced_uri=ldap_backend_forced_uri)
  45.     elif backend_type == "fedora-ds":
  46.         provision_backend = FDSBackend(backend_type, paths=paths,
  47.             lp=lp, credentials=credentials,
  48.             names=names, logger=logger, domainsid=domainsid,
  49.             schema=schema, hostname=hostname, ldapadminpass=ldapadminpass,
  50.             slapd_path=slapd_path,
  51.             ldap_backend_extra_port=ldap_backend_extra_port,
  52.             ldap_dryrun_mode=ldap_dryrun_mode, root=root,
  53.             setup_ds_path=setup_ds_path,
  54.             ldap_backend_forced_uri=ldap_backend_forced_uri)
  55.     elif backend_type == "openldap":
  56.         provision_backend = OpenLDAPBackend(backend_type, paths=paths,
  57.             lp=lp, credentials=credentials,
  58.             names=names, logger=logger, domainsid=domainsid,
  59.             schema=schema, hostname=hostname, ldapadminpass=ldapadminpass,
  60.             slapd_path=slapd_path,
  61.             ldap_backend_extra_port=ldap_backend_extra_port,
  62.             ldap_dryrun_mode=ldap_dryrun_mode, ol_mmr_urls=ol_mmr_urls,
  63.             nosync=nosync,
  64.             ldap_backend_forced_uri=ldap_backend_forced_uri)
  65.     else:
  66.         raise ValueError("Unknown LDAP backend type selected")
  67.  
  68.     provision_backend.init()
  69.     provision_backend.start()
  70.  
  71.     # only install a new shares config db if there is none
  72.     if not os.path.exists(paths.shareconf):
  73.         logger.info("Setting up share.ldb")
  74.         share_ldb = Ldb(paths.shareconf, session_info=session_info,
  75.                         lp=lp)
  76.         share_ldb.load_ldif_file_add(setup_path("share.ldif"))
  77.  
  78.     logger.info("Setting up secrets.ldb")
  79.     secrets_ldb = setup_secretsdb(paths,
  80.         session_info=session_info,
  81.         backend_credentials=provision_backend.secrets_credentials, lp=lp)
  82.  
  83.     try:
  84.         logger.info("Setting up the registry")
  85.         setup_registry(paths.hklm, session_info,
  86.                        lp=lp)
  87.  
  88.         logger.info("Setting up the privileges database")
  89.         setup_privileges(paths.privilege, session_info, lp=lp)
  90.  
  91.         logger.info("Setting up idmap db")
  92.         idmap = setup_idmapdb(paths.idmapdb,
  93.             session_info=session_info, lp=lp)
  94.  
  95.         logger.info("Setting up SAM db")
  96.         samdb = setup_samdb(paths.samdb, session_info,
  97.             provision_backend, lp, names, logger=logger,
  98.             domainsid=domainsid, schema=schema, domainguid=domainguid,
  99.             policyguid=policyguid, policyguid_dc=policyguid_dc,
  100.             fill=samdb_fill, adminpass=adminpass, krbtgtpass=krbtgtpass,
  101.             invocationid=invocationid, machinepass=machinepass,
  102.             dnspass=dnspass, ntdsguid=ntdsguid, serverrole=serverrole,
  103.             dom_for_fun_level=dom_for_fun_level, am_rodc=am_rodc,
  104.             next_rid=next_rid)
  105.  
  106.         if serverrole == "domain controller":
  107.             if paths.netlogon is None:
  108.                 logger.info("Existing smb.conf does not have a [netlogon] share, but you are configuring a DC.")
  109.                 logger.info("Please either remove %s or see the template at %s" %
  110.                         (paths.smbconf, setup_path("provision.smb.conf.dc")))
  111.                 assert paths.netlogon is not None
  112.  
  113.             if paths.sysvol is None:
  114.                 logger.info("Existing smb.conf does not have a [sysvol] share, but you"
  115.                         " are configuring a DC.")
  116.                 logger.info("Please either remove %s or see the template at %s" %
  117.                         (paths.smbconf, setup_path("provision.smb.conf.dc")))
  118.                 assert paths.sysvol is not None
  119.  
  120.             if not os.path.isdir(paths.netlogon):
  121.                 os.makedirs(paths.netlogon, 0755)
  122.  
  123.         if samdb_fill == FILL_FULL:
  124.             setup_name_mappings(samdb, idmap, str(domainsid), names.domaindn,
  125.                                 root_uid=root_uid, nobody_uid=nobody_uid,
  126.                                 users_gid=users_gid, wheel_gid=wheel_gid)
  127.  
  128.             if serverrole == "domain controller":
  129.                 # Set up group policies (domain policy and domain controller
  130.                 # policy)
  131.                 create_default_gpo(paths.sysvol, names.dnsdomain, policyguid,
  132.                     policyguid_dc)
  133.                 setsysvolacl(samdb, paths.netlogon, paths.sysvol, wheel_gid,
  134.                     domainsid, names.dnsdomain, names.domaindn, lp)
  135.  
  136.             logger.info("Setting up sam.ldb rootDSE marking as synchronized")
  137.             setup_modify_ldif(samdb, setup_path("provision_rootdse_modify.ldif"))
  138.  
  139.             secretsdb_self_join(secrets_ldb, domain=names.domain,
  140.                 realm=names.realm, dnsdomain=names.dnsdomain,
  141.                 netbiosname=names.netbiosname, domainsid=domainsid,
  142.                 machinepass=machinepass, secure_channel_type=SEC_CHAN_BDC)
  143.  
  144.             # Now set up the right msDS-SupportedEncryptionTypes into the DB
  145.             # In future, this might be determined from some configuration
  146.             kerberos_enctypes = str(ENC_ALL_TYPES)
  147.  
  148.             try:
  149.                 msg = ldb.Message(ldb.Dn(samdb,
  150.                     samdb.searchone("distinguishedName",
  151.                         expression="samAccountName=%s$" % names.netbiosname,
  152.                         scope=ldb.SCOPE_SUBTREE)))
  153.                 msg["msDS-SupportedEncryptionTypes"] = ldb.MessageElement(
  154.                     elements=kerberos_enctypes, flags=ldb.FLAG_MOD_REPLACE,
  155.                     name="msDS-SupportedEncryptionTypes")
  156.                 samdb.modify(msg)
  157.             except ldb.LdbError, (enum, estr):
  158.                 if enum != ldb.ERR_NO_SUCH_ATTRIBUTE:
  159.                     # It might be that this attribute does not exist in this schema
  160.                     raise
  161.  
  162.             if serverrole == "domain controller":
  163.                 secretsdb_setup_dns(secrets_ldb, names,
  164.                     paths.private_dir, realm=names.realm,
  165.                     dnsdomain=names.dnsdomain,
  166.                     dns_keytab_path=paths.dns_keytab, dnspass=dnspass)
  167.  
  168.                 setup_ad_dns(samdb, names=names, hostip=hostip, hostip6=hostip6)
  169.  
  170.                 domainguid = samdb.searchone(basedn=domaindn,
  171.                     attribute="objectGUID")
  172.                 assert isinstance(domainguid, str)
  173.  
  174.                 # Only make a zone file on the first DC, it should be
  175.                 # replicated with DNS replication
  176.                 create_zone_file(lp, logger, paths, targetdir,
  177.                     dnsdomain=names.dnsdomain, hostip=hostip, hostip6=hostip6,
  178.                     hostname=names.hostname, realm=names.realm,
  179.                     domainguid=domainguid, ntdsguid=names.ntdsguid)
  180.  
  181.                 create_named_conf(paths, realm=names.realm,
  182.                     dnsdomain=names.dnsdomain, private_dir=paths.private_dir)
  183.  
  184.                 create_named_txt(paths.namedtxt,
  185.                     realm=names.realm, dnsdomain=names.dnsdomain,
  186.                     dnsname = "%s.%s" % (names.hostname, names.dnsdomain),
  187.                     private_dir=paths.private_dir,
  188.                     keytab_name=paths.dns_keytab)
  189.                 logger.info("See %s for an example configuration include file for BIND", paths.namedconf)
  190.                 logger.info("and %s for further documentation required for secure DNS "
  191.                         "updates", paths.namedtxt)
  192.  
  193.             lastProvisionUSNs = get_last_provision_usn(samdb)
  194.             maxUSN = get_max_usn(samdb, str(names.rootdn))
  195.             if lastProvisionUSNs is not None:
  196.                 update_provision_usn(samdb, 0, maxUSN, invocationid, 1)
  197.             else:
  198.                 set_provision_usn(samdb, 0, maxUSN, invocationid)
  199.  
  200.         create_krb5_conf(paths.krb5conf,
  201.                          dnsdomain=names.dnsdomain, hostname=names.hostname,
  202.                          realm=names.realm)
  203.         logger.info("A Kerberos configuration suitable for Samba 4 has been "
  204.                     "generated at %s", paths.krb5conf)
  205.  
  206.         if serverrole == "domain controller":
  207.             create_dns_update_list(lp, logger, paths)
  208.  
  209.         provision_backend.post_setup()
  210.         provision_backend.shutdown()
  211.  
  212.         create_phpldapadmin_config(paths.phpldapadminconfig,
  213.                                    ldapi_url)
  214.     except Exception:
  215.         secrets_ldb.transaction_cancel()
  216.         raise
  217.  
  218.     # Now commit the secrets.ldb to disk
  219.     secrets_ldb.transaction_commit()
  220.  
  221.     # the commit creates the dns.keytab, now chown it
  222.     dns_keytab_path = os.path.join(paths.private_dir, paths.dns_keytab)
  223.     if os.path.isfile(dns_keytab_path) and paths.bind_gid is not None:
  224.         try:
  225.             os.chmod(dns_keytab_path, 0640)
  226.             os.chown(dns_keytab_path, -1, paths.bind_gid)
  227.         except OSError:
  228.             if not os.environ.has_key('SAMBA_SELFTEST'):
  229.                 logger.info("Failed to chown %s to bind gid %u",
  230.                             dns_keytab_path, paths.bind_gid)
  231.  
  232.     if samdb_fill != FILL_DRS:
  233.         # fix any dangling GUIDs from the provision
  234.         logger.info("Fixing provision GUIDs")
  235.         chk = dbcheck(samdb, samdb_schema=samdb,  verbose=False, fix=True, yes=True, quiet=True)
  236.         samdb.transaction_start()
  237.         # a small number of GUIDs are missing because of ordering issues in the
  238.         # provision code
  239.         for schema_obj in ['CN=Domain', 'CN=Organizational-Person', 'CN=Contact', 'CN=inetOrgPerson']:
  240.             chk.check_database(DN="%s,%s" % (schema_obj, names.schemadn),
  241.                                scope=ldb.SCOPE_BASE, attrs=['defaultObjectCategory'])
  242.         chk.check_database(DN="CN=IP Security,CN=System,%s" % names.domaindn,
  243.                            scope=ldb.SCOPE_ONELEVEL,
  244.                            attrs=['ipsecOwnersReference',
  245.                                   'ipsecFilterReference',
  246.                                   'ipsecISAKMPReference',
  247.                                   'ipsecNegotiationPolicyReference',
  248.                                   'ipsecNFAReference'])
  249.         samdb.transaction_commit()
  250.  
  251.  
  252.     logger.info("Please install the phpLDAPadmin configuration located at %s into /etc/phpldapadmin/config.php",
  253.             paths.phpldapadminconfig)
  254.  
  255.     logger.info("Once the above files are installed, your Samba4 server will be ready to use")
  256.     logger.info("Server Role:           %s" % serverrole)
  257.     logger.info("Hostname:              %s" % names.hostname)
  258.     logger.info("NetBIOS Domain:        %s" % names.domain)
  259.     logger.info("DNS Domain:            %s" % names.dnsdomain)
  260.     logger.info("DOMAIN SID:            %s" % str(domainsid))
  261.     if samdb_fill == FILL_FULL:
  262.         logger.info("Admin password:        %s" % adminpass)
  263.     if provision_backend.type is not "ldb":
  264.         if provision_backend.credentials.get_bind_dn() is not None:
  265.             logger.info("LDAP Backend Admin DN: %s" %
  266.                 provision_backend.credentials.get_bind_dn())
  267.         else:
  268.             logger.info("LDAP Admin User:       %s" %
  269.                 provision_backend.credentials.get_username())
  270.  
  271.         logger.info("LDAP Admin Password:   %s" %
  272.             provision_backend.credentials.get_password())
  273.  
  274.         if provision_backend.slapd_command_escaped is not None:
  275.             # now display slapd_command_file.txt to show how slapd must be
  276.             # started next time
  277.             logger.info("Use later the following commandline to start slapd, then Samba:")
  278.             logger.info(provision_backend.slapd_command_escaped)
  279.             logger.info("This slapd-Commandline is also stored under: %s/ldap_backend_startup.sh",
  280.                     provision_backend.ldapdir)
  281.  
  282.     result = ProvisionResult()
  283.     result.domaindn = domaindn
  284.     result.paths = paths
  285.     result.lp = lp
  286.     result.samdb = samdb
  287.     return result
  288.  
  289.  
  290. def provision_become_dc(smbconf=None, targetdir=None,
  291.         realm=None, rootdn=None, domaindn=None, schemadn=None, configdn=None,
  292.         serverdn=None, domain=None, hostname=None, domainsid=None,
  293.         adminpass=None, krbtgtpass=None, domainguid=None, policyguid=None,
  294.         policyguid_dc=None, invocationid=None, machinepass=None, dnspass=None,
  295.         root=None, nobody=None, users=None, wheel=None, backup=None,
  296.         serverrole=None, ldap_backend=None, ldap_backend_type=None,
  297.         sitename=None, debuglevel=1):
  298.  
  299.     logger = logging.getLogger("provision")
  300.     samba.set_debug_level(debuglevel)
  301.  
  302.     res = provision(logger, system_session(), None,
  303.         smbconf=smbconf, targetdir=targetdir, samdb_fill=FILL_DRS,
  304.         realm=realm, rootdn=rootdn, domaindn=domaindn, schemadn=schemadn,
  305.         configdn=configdn, serverdn=serverdn, domain=domain,
  306.         hostname=hostname, hostip=None, domainsid=domainsid,
  307.         machinepass=machinepass, serverrole="domain controller",
  308.         sitename=sitename)
  309.     res.lp.set("debuglevel", str(debuglevel))
  310.     return res
  311.  
  312.  
  313. def create_phpldapadmin_config(path, ldapi_uri):
  314.     """Create a PHP LDAP admin configuration file.
  315.  
  316.     :param path: Path to write the configuration to.
  317.     """
  318.     setup_file(setup_path("phpldapadmin-config.php"), path,
  319.             {"S4_LDAPI_URI": ldapi_uri})
  320.  
  321.  
  322. def create_zone_file(lp, logger, paths, targetdir, dnsdomain,
  323.                      hostip, hostip6, hostname, realm, domainguid,
  324.                      ntdsguid):
  325.     """Write out a DNS zone file, from the info in the current database.
  326.  
  327.     :param paths: paths object
  328.     :param dnsdomain: DNS Domain name
  329.     :param domaindn: DN of the Domain
  330.     :param hostip: Local IPv4 IP
  331.     :param hostip6: Local IPv6 IP
  332.     :param hostname: Local hostname
  333.     :param realm: Realm name
  334.     :param domainguid: GUID of the domain.
  335.     :param ntdsguid: GUID of the hosts nTDSDSA record.
  336.     """
  337.     assert isinstance(domainguid, str)
  338.  
  339.     if hostip6 is not None:
  340.         hostip6_base_line = "            IN AAAA    " + hostip6
  341.         hostip6_host_line = hostname + "        IN AAAA    " + hostip6
  342.         gc_msdcs_ip6_line = "gc._msdcs               IN AAAA    " + hostip6
  343.     else:
  344.         hostip6_base_line = ""
  345.         hostip6_host_line = ""
  346.         gc_msdcs_ip6_line = ""
  347.  
  348.     if hostip is not None:
  349.         hostip_base_line = "            IN A    " + hostip
  350.         hostip_host_line = hostname + "        IN A    " + hostip
  351.         gc_msdcs_ip_line = "gc._msdcs               IN A    " + hostip
  352.     else:
  353.         hostip_base_line = ""
  354.         hostip_host_line = ""
  355.         gc_msdcs_ip_line = ""
  356.  
  357.     dns_dir = os.path.dirname(paths.dns)
  358.  
  359.     try:
  360.         shutil.rmtree(dns_dir, True)
  361.     except OSError:
  362.         pass
  363.  
  364.     os.mkdir(dns_dir, 0775)
  365.  
  366.     # we need to freeze the zone while we update the contents
  367.     if targetdir is None:
  368.         rndc = ' '.join(lp.get("rndc command"))
  369.         os.system(rndc + " freeze " + lp.get("realm"))
  370.  
  371.     setup_file(setup_path("provision.zone"), paths.dns, {
  372.             "HOSTNAME": hostname,
  373.             "DNSDOMAIN": dnsdomain,
  374.             "REALM": realm,
  375.             "HOSTIP_BASE_LINE": hostip_base_line,
  376.             "HOSTIP_HOST_LINE": hostip_host_line,
  377.             "DOMAINGUID": domainguid,
  378.             "DATESTRING": time.strftime("%Y%m%d%H"),
  379.             "DEFAULTSITE": DEFAULTSITE,
  380.             "NTDSGUID": ntdsguid,
  381.             "HOSTIP6_BASE_LINE": hostip6_base_line,
  382.             "HOSTIP6_HOST_LINE": hostip6_host_line,
  383.             "GC_MSDCS_IP_LINE": gc_msdcs_ip_line,
  384.             "GC_MSDCS_IP6_LINE": gc_msdcs_ip6_line,
  385.         })
  386.  
  387.     # note that we use no variable substitution on this file
  388.     # the substitution is done at runtime by samba_dnsupdate
  389.     setup_file(setup_path("dns_update_list"), paths.dns_update_list, None)
  390.  
  391.     # and the SPN update list
  392.     setup_file(setup_path("spn_update_list"), paths.spn_update_list, None)
  393.  
  394.     if paths.bind_gid is not None:
  395.         try:
  396.             os.chown(dns_dir, -1, paths.bind_gid)
  397.             os.chown(paths.dns, -1, paths.bind_gid)
  398.             # chmod needed to cope with umask
  399.             os.chmod(dns_dir, 0775)
  400.             os.chmod(paths.dns, 0664)
  401.         except OSError:
  402.             if not os.environ.has_key('SAMBA_SELFTEST'):
  403.                 logger.error("Failed to chown %s to bind gid %u" % (
  404.                     dns_dir, paths.bind_gid))
  405.  
  406.     if targetdir is None:
  407.         os.system(rndc + " unfreeze " + lp.get("realm"))
  408.  
  409.  
  410. def create_dns_update_list(lp, logger, paths):
  411.     """Write out a dns_update_list file"""
  412.     # note that we use no variable substitution on this file
  413.     # the substitution is done at runtime by samba_dnsupdate
  414.     setup_file(setup_path("dns_update_list"), paths.dns_update_list, None)
  415.     setup_file(setup_path("spn_update_list"), paths.spn_update_list, None)
  416.  
  417.  
  418. def create_named_conf(paths, realm, dnsdomain,
  419.                       private_dir):
  420.     """Write out a file containing zone statements suitable for inclusion in a
  421.     named.conf file (including GSS-TSIG configuration).
  422.  
  423.     :param paths: all paths
  424.     :param realm: Realm name
  425.     :param dnsdomain: DNS Domain name
  426.     :param private_dir: Path to private directory
  427.     :param keytab_name: File name of DNS keytab file
  428.     """
  429.  
  430.     setup_file(setup_path("named.conf"), paths.namedconf, {
  431.             "DNSDOMAIN": dnsdomain,
  432.             "REALM": realm,
  433.             "ZONE_FILE": paths.dns,
  434.             "REALM_WC": "*." + ".".join(realm.split(".")[1:]),
  435.             "NAMED_CONF": paths.namedconf,
  436.             "NAMED_CONF_UPDATE": paths.namedconf_update
  437.             })
  438.  
  439.     setup_file(setup_path("named.conf.update"), paths.namedconf_update)
  440.  
  441.  
  442. def create_named_txt(path, realm, dnsdomain, dnsname, private_dir,
  443.     keytab_name):
  444.     """Write out a file containing zone statements suitable for inclusion in a
  445.     named.conf file (including GSS-TSIG configuration).
  446.  
  447.     :param path: Path of the new named.conf file.
  448.     :param realm: Realm name
  449.     :param dnsdomain: DNS Domain name
  450.     :param private_dir: Path to private directory
  451.     :param keytab_name: File name of DNS keytab file
  452.     """
  453.     setup_file(setup_path("named.txt"), path, {
  454.             "DNSDOMAIN": dnsdomain,
  455.             "DNSNAME" : dnsname,
  456.             "REALM": realm,
  457.             "DNS_KEYTAB": keytab_name,
  458.             "DNS_KEYTAB_ABS": os.path.join(private_dir, keytab_name),
  459.             "PRIVATE_DIR": private_dir
  460.         })
  461.  
  462.  
  463. def create_krb5_conf(path, dnsdomain, hostname, realm):
  464.     """Write out a file containing zone statements suitable for inclusion in a
  465.     named.conf file (including GSS-TSIG configuration).
  466.  
  467.     :param path: Path of the new named.conf file.
  468.     :param dnsdomain: DNS Domain name
  469.     :param hostname: Local hostname
  470.     :param realm: Realm name
  471.     """
  472.     setup_file(setup_path("krb5.conf"), path, {
  473.             "DNSDOMAIN": dnsdomain,
  474.             "HOSTNAME": hostname,
  475.             "REALM": realm,
  476.         })
  477.  
  478.  
  479. class ProvisioningError(Exception):
  480.     """A generic provision error."""
  481.  
  482.     def __init__(self, value):
  483.         self.value = value
  484.  
  485.     def __str__(self):
  486.         return "ProvisioningError: " + self.value
  487.  
  488.  
  489. class InvalidNetbiosName(Exception):
  490.     """A specified name was not a valid NetBIOS name."""
  491.     def __init__(self, name):
  492.         super(InvalidNetbiosName, self).__init__(
  493.             "The name '%r' is not a valid NetBIOS name" % name)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top