provision: fix nTSecurityDescriptor of containers in the DnsZones (bug #9481)
[metze/samba/wip.git] / source4 / scripting / python / samba / provision / sambadns.py
index b3e5bdc64b12b5d687cb0f03335940b294b2e7d2..740dd384176fc2c0104b0b35fc986c05590dab25 100644 (file)
@@ -28,72 +28,34 @@ import ldb
 from base64 import b64encode
 import samba
 from samba.ndr import ndr_pack, ndr_unpack
-from samba import read_and_sub_file, setup_file
+from samba import setup_file
 from samba.dcerpc import dnsp, misc, security
 from samba.dsdb import (
     DS_DOMAIN_FUNCTION_2000,
     DS_DOMAIN_FUNCTION_2003,
-    DS_DOMAIN_FUNCTION_2008,
     DS_DOMAIN_FUNCTION_2008_R2
     )
-from base64 import b64encode
 from samba.provision.descriptor import (
     get_domain_descriptor,
-    get_dns_partition_descriptor
+    get_domain_delete_protected1_descriptor,
+    get_domain_delete_protected2_descriptor,
+    get_dns_partition_descriptor,
+    get_dns_forest_microsoft_dns_descriptor,
+    get_dns_domain_microsoft_dns_descriptor
+    )
+from samba.provision.common import (
+    setup_path,
+    setup_add_ldif,
+    setup_modify_ldif,
+    setup_ldb
     )
 
 
-def add_ldif(ldb, ldif_file, subst_vars, controls=["relax:0"]):
-    ldif_file_path = os.path.join(samba.param.setup_dir(), ldif_file)
-    data = read_and_sub_file(ldif_file_path, subst_vars)
-    ldb.add_ldif(data, controls)
-
-def modify_ldif(ldb, ldif_file, subst_vars, controls=["relax:0"]):
-    ldif_file_path = os.path.join(samba.param.setup_dir(), ldif_file)
-    data = read_and_sub_file(ldif_file_path, subst_vars)
-    ldb.modify_ldif(data, controls)
-
-def setup_ldb(ldb, ldif_path, subst_vars):
-    """Import a LDIF a file into a LDB handle, optionally substituting
-    variables.
-
-    :note: Either all LDIF data will be added or none (using transactions).
-
-    :param ldb: LDB file to import into.
-    :param ldif_path: Path to the LDIF file.
-    :param subst_vars: Dictionary with substitution variables.
-    """
-    assert ldb is not None
-    ldb.transaction_start()
-    try:
-        add_ldif(ldb, ldif_path, subst_vars)
-    except Exception:
-        ldb.transaction_cancel()
-        raise
-    else:
-        ldb.transaction_commit()
-
-def setup_path(file):
-    """Return an absolute path to the provision tempate file specified by file"""
-    return os.path.join(samba.param.setup_dir(), file)
-
 def get_domainguid(samdb, domaindn):
     res = samdb.search(base=domaindn, scope=ldb.SCOPE_BASE, attrs=["objectGUID"])
     domainguid =  str(ndr_unpack(misc.GUID, res[0]["objectGUID"][0]))
     return domainguid
 
-def get_ntdsguid(samdb, domaindn):
-    configdn = samdb.get_config_basedn()
-
-    res1 = samdb.search(base="OU=Domain Controllers,%s" % domaindn, scope=ldb.SCOPE_ONELEVEL,
-                        attrs=["dNSHostName"])
-
-    res2 = samdb.search(expression="serverReference=%s" % res1[0].dn, base=configdn)
-
-    res3 = samdb.search(base="CN=NTDS Settings,%s" % res2[0].dn, scope=ldb.SCOPE_BASE,
-                        attrs=["objectGUID"])
-    ntdsguid = str(ndr_unpack(misc.GUID, res3[0]["objectGUID"][0]))
-    return ntdsguid
 
 def get_dnsadmins_sid(samdb, domaindn):
     res = samdb.search(base="CN=DnsAdmins,CN=Users,%s" % domaindn, scope=ldb.SCOPE_BASE,
@@ -101,7 +63,9 @@ def get_dnsadmins_sid(samdb, domaindn):
     dnsadmins_sid = ndr_unpack(security.dom_sid, res[0]["objectSid"][0])
     return dnsadmins_sid
 
+
 class ARecord(dnsp.DnssrvRpcRecord):
+
     def __init__(self, ip_addr, serial=1, ttl=900, rank=dnsp.DNS_RANK_ZONE):
         super(ARecord, self).__init__()
         self.wType = dnsp.DNS_TYPE_A
@@ -110,7 +74,9 @@ class ARecord(dnsp.DnssrvRpcRecord):
         self.dwTtlSeconds = ttl
         self.data = ip_addr
 
+
 class AAAARecord(dnsp.DnssrvRpcRecord):
+
     def __init__(self, ip6_addr, serial=1, ttl=900, rank=dnsp.DNS_RANK_ZONE):
         super(AAAARecord, self).__init__()
         self.wType = dnsp.DNS_TYPE_AAAA
@@ -119,7 +85,9 @@ class AAAARecord(dnsp.DnssrvRpcRecord):
         self.dwTtlSeconds = ttl
         self.data = ip6_addr
 
+
 class CNameRecord(dnsp.DnssrvRpcRecord):
+
     def __init__(self, cname, serial=1, ttl=900, rank=dnsp.DNS_RANK_ZONE):
         super(CNameRecord, self).__init__()
         self.wType = dnsp.DNS_TYPE_CNAME
@@ -128,7 +96,9 @@ class CNameRecord(dnsp.DnssrvRpcRecord):
         self.dwTtlSeconds = ttl
         self.data = cname
 
+
 class NSRecord(dnsp.DnssrvRpcRecord):
+
     def __init__(self, dns_server, serial=1, ttl=900, rank=dnsp.DNS_RANK_ZONE):
         super(NSRecord, self).__init__()
         self.wType = dnsp.DNS_TYPE_NS
@@ -137,7 +107,9 @@ class NSRecord(dnsp.DnssrvRpcRecord):
         self.dwTtlSeconds = ttl
         self.data = dns_server
 
+
 class SOARecord(dnsp.DnssrvRpcRecord):
+
     def __init__(self, mname, rname, serial=1, refresh=900, retry=600,
                  expire=86400, minimum=3600, ttl=3600, rank=dnsp.DNS_RANK_ZONE):
         super(SOARecord, self).__init__()
@@ -154,7 +126,9 @@ class SOARecord(dnsp.DnssrvRpcRecord):
         soa.rname = rname
         self.data = soa
 
+
 class SRVRecord(dnsp.DnssrvRpcRecord):
+
     def __init__(self, target, port, priority=0, weight=100, serial=1, ttl=900,
                 rank=dnsp.DNS_RANK_ZONE):
         super(SRVRecord, self).__init__()
@@ -169,11 +143,97 @@ class SRVRecord(dnsp.DnssrvRpcRecord):
         srv.wWeight = weight
         self.data = srv
 
-def setup_dns_partitions(samdb, domainsid, domaindn, forestdn, configdn, serverdn):
+
+class TXTRecord(dnsp.DnssrvRpcRecord):
+
+    def __init__(self, slist, serial=1, ttl=900, rank=dnsp.DNS_RANK_ZONE):
+        super(TXTRecord, self).__init__()
+        self.wType = dnsp.DNS_TYPE_TXT
+        self.rank = rank
+        self.dwSerial = serial
+        self.dwTtlSeconds = ttl
+        stringlist = dnsp.string_list()
+        stringlist.count = len(slist)
+        stringlist.str = slist
+        self.data = stringlist
+
+
+class TypeProperty(dnsp.DnsProperty):
+
+    def __init__(self, zone_type=dnsp.DNS_ZONE_TYPE_PRIMARY):
+        super(TypeProperty, self).__init__()
+        self.wDataLength = 1
+        self.version = 1
+        self.id = dnsp.DSPROPERTY_ZONE_TYPE
+        self.data = zone_type
+
+
+class AllowUpdateProperty(dnsp.DnsProperty):
+
+    def __init__(self, allow_update=dnsp.DNS_ZONE_UPDATE_SECURE):
+        super(AllowUpdateProperty, self).__init__()
+        self.wDataLength = 1
+        self.version = 1
+        self.id = dnsp.DSPROPERTY_ZONE_ALLOW_UPDATE
+        self.data = allow_update
+
+
+class SecureTimeProperty(dnsp.DnsProperty):
+
+    def __init__(self, secure_time=0):
+        super(SecureTimeProperty, self).__init__()
+        self.wDataLength = 1
+        self.version = 1
+        self.id = dnsp.DSPROPERTY_ZONE_SECURE_TIME
+        self.data = secure_time
+
+
+class NorefreshIntervalProperty(dnsp.DnsProperty):
+
+    def __init__(self, norefresh_interval=0):
+        super(NorefreshIntervalProperty, self).__init__()
+        self.wDataLength = 1
+        self.version = 1
+        self.id = dnsp.DSPROPERTY_ZONE_NOREFRESH_INTERVAL
+        self.data = norefresh_interval
+
+
+class RefreshIntervalProperty(dnsp.DnsProperty):
+
+    def __init__(self, refresh_interval=0):
+        super(RefreshIntervalProperty, self).__init__()
+        self.wDataLength = 1
+        self.version = 1
+        self.id = dnsp.DSPROPERTY_ZONE_REFRESH_INTERVAL
+        self.data = refresh_interval
+
+
+class AgingStateProperty(dnsp.DnsProperty):
+
+    def __init__(self, aging_enabled=0):
+        super(AgingStateProperty, self).__init__()
+        self.wDataLength = 1
+        self.version = 1
+        self.id = dnsp.DSPROPERTY_ZONE_AGING_STATE
+        self.data = aging_enabled
+
+
+class AgingEnabledTimeProperty(dnsp.DnsProperty):
+
+    def __init__(self, next_cycle_hours=0):
+        super(AgingEnabledTimeProperty, self).__init__()
+        self.wDataLength = 1
+        self.version = 1;
+        self.id = dnsp.DSPROPERTY_ZONE_AGING_ENABLED_TIME
+        self.data = next_cycle_hours
+
+
+def setup_dns_partitions(samdb, domainsid, domaindn, forestdn, configdn,
+        serverdn):
     domainzone_dn = "DC=DomainDnsZones,%s" % domaindn
     forestzone_dn = "DC=ForestDnsZones,%s" % forestdn
     descriptor = get_dns_partition_descriptor(domainsid)
-    add_ldif(samdb, "provision_dnszones_partitions.ldif", {
+    setup_add_ldif(samdb, setup_path("provision_dnszones_partitions.ldif"), {
         "DOMAINZONE_DN": domainzone_dn,
         "FORESTZONE_DN": forestzone_dn,
         "SECDESC"      : b64encode(descriptor)
@@ -188,7 +248,9 @@ def setup_dns_partitions(samdb, domainsid, domaindn, forestdn, configdn, serverd
     domainzone_dns = ldb.Dn(samdb, domainzone_dn).canonical_ex_str().strip()
     forestzone_dns = ldb.Dn(samdb, forestzone_dn).canonical_ex_str().strip()
 
-    add_ldif(samdb, "provision_dnszones_add.ldif", {
+    protected1_desc = get_domain_delete_protected1_descriptor(domainsid)
+    protected2_desc = get_domain_delete_protected2_descriptor(domainsid)
+    setup_add_ldif(samdb, setup_path("provision_dnszones_add.ldif"), {
         "DOMAINZONE_DN": domainzone_dn,
         "FORESTZONE_DN": forestzone_dn,
         "DOMAINZONE_GUID": domainzone_guid,
@@ -197,9 +259,11 @@ def setup_dns_partitions(samdb, domainsid, domaindn, forestdn, configdn, serverd
         "FORESTZONE_DNS": forestzone_dns,
         "CONFIGDN": configdn,
         "SERVERDN": serverdn,
+        "LOSTANDFOUND_DESCRIPTOR": b64encode(protected2_desc),
+        "INFRASTRUCTURE_DESCRIPTOR": b64encode(protected1_desc),
         })
 
-    modify_ldif(samdb, "provision_dnszones_modify.ldif", {
+    setup_modify_ldif(samdb, setup_path("provision_dnszones_modify.ldif"), {
         "CONFIGDN": configdn,
         "SERVERDN": serverdn,
         "DOMAINZONE_DN": domainzone_dn,
@@ -208,24 +272,27 @@ def setup_dns_partitions(samdb, domainsid, domaindn, forestdn, configdn, serverd
 
 
 def add_dns_accounts(samdb, domaindn):
-    add_ldif(samdb, "provision_dns_accounts_add.ldif", {
+    setup_add_ldif(samdb, setup_path("provision_dns_accounts_add.ldif"), {
         "DOMAINDN": domaindn,
         })
 
-def add_dns_container(samdb, domaindn, prefix, domainsid, dnsadmins_sid):
+
+def add_dns_container(samdb, domaindn, prefix, domain_sid, dnsadmins_sid, forest=False):
+    name_map = {'DnsAdmins': str(dnsadmins_sid)}
+    if forest is True:
+        sd_val = get_dns_forest_microsoft_dns_descriptor(domain_sid,
+                                                         name_map=name_map)
+    else:
+        sd_val = get_dns_domain_microsoft_dns_descriptor(domain_sid,
+                                                         name_map=name_map)
     # CN=MicrosoftDNS,<PREFIX>,<DOMAINDN>
-    sddl = "O:SYG:SYD:AI" \
-    "(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;DA)" \
-    "(A;CI;RPWPCRCCDCLCRCWOWDSDDTSW;;;%s)" \
-    "(A;;RPWPCRCCDCLCLORCWOWDSDDTSW;;;SY)" \
-    "(A;CI;RPWPCRCCDCLCRCWOWDSDDTSW;;;ED)" \
-    "S:AI" % dnsadmins_sid
-    sec = security.descriptor.from_sddl(sddl, domainsid)
     msg = ldb.Message(ldb.Dn(samdb, "CN=MicrosoftDNS,%s,%s" % (prefix, domaindn)))
     msg["objectClass"] = ["top", "container"]
-    msg["nTSecurityDescriptor"] = ndr_pack(sec)
+    msg["nTSecurityDescriptor"] = ldb.MessageElement(sd_val, ldb.FLAG_MOD_ADD,
+        "nTSecurityDescriptor")
     samdb.add(msg)
 
+
 def add_rootservers(samdb, domaindn, prefix):
     rootservers = {}
     rootservers["a.root-servers.net"] = "198.41.0.4"
@@ -254,8 +321,17 @@ def add_rootservers(samdb, domaindn, prefix):
 
     # Add DC=RootDNSServers,CN=MicrosoftDNS,<PREFIX>,<DOMAINDN>
     msg = ldb.Message(ldb.Dn(samdb, container_dn))
+    props = []
+    props.append(ndr_pack(TypeProperty(zone_type=dnsp.DNS_ZONE_TYPE_CACHE)))
+    props.append(ndr_pack(AllowUpdateProperty(allow_update=dnsp.DNS_ZONE_UPDATE_OFF)))
+    props.append(ndr_pack(SecureTimeProperty()))
+    props.append(ndr_pack(NorefreshIntervalProperty()))
+    props.append(ndr_pack(RefreshIntervalProperty()))
+    props.append(ndr_pack(AgingStateProperty()))
+    props.append(ndr_pack(AgingEnabledTimeProperty()))
     msg["objectClass"] = ["top", "dnsZone"]
     msg["cn"] = ldb.MessageElement("Zone", ldb.FLAG_MOD_ADD, "cn")
+    msg["dNSProperty"] = ldb.MessageElement(props, ldb.FLAG_MOD_ADD, "dNSProperty")
     samdb.add(msg)
 
     # Add DC=@,DC=RootDNSServers,CN=MicrosoftDNS,<PREFIX>,<DOMAINDN>
@@ -308,6 +384,7 @@ def add_at_record(samdb, container_dn, prefix, hostname, dnsdomain, hostip, host
     msg["dnsRecord"] = ldb.MessageElement(at_records, ldb.FLAG_MOD_ADD, "dnsRecord")
     samdb.add(msg)
 
+
 def add_srv_record(samdb, container_dn, prefix, host, port):
     srv_record = SRVRecord(host, port)
     msg = ldb.Message(ldb.Dn(samdb, "%s,%s" % (prefix, container_dn)))
@@ -315,6 +392,7 @@ def add_srv_record(samdb, container_dn, prefix, host, port):
     msg["dnsRecord"] = ldb.MessageElement(ndr_pack(srv_record), ldb.FLAG_MOD_ADD, "dnsRecord")
     samdb.add(msg)
 
+
 def add_ns_record(samdb, container_dn, prefix, host):
     ns_record = NSRecord(host)
     msg = ldb.Message(ldb.Dn(samdb, "%s,%s" % (prefix, container_dn)))
@@ -322,6 +400,7 @@ def add_ns_record(samdb, container_dn, prefix, host):
     msg["dnsRecord"] = ldb.MessageElement(ndr_pack(ns_record), ldb.FLAG_MOD_ADD, "dnsRecord")
     samdb.add(msg)
 
+
 def add_ns_glue_record(samdb, container_dn, prefix, host):
     ns_record = NSRecord(host, rank=dnsp.DNS_RANK_NS_GLUE)
     msg = ldb.Message(ldb.Dn(samdb, "%s,%s" % (prefix, container_dn)))
@@ -329,6 +408,7 @@ def add_ns_glue_record(samdb, container_dn, prefix, host):
     msg["dnsRecord"] = ldb.MessageElement(ndr_pack(ns_record), ldb.FLAG_MOD_ADD, "dnsRecord")
     samdb.add(msg)
 
+
 def add_cname_record(samdb, container_dn, prefix, host):
     cname_record = CNameRecord(host)
     msg = ldb.Message(ldb.Dn(samdb, "%s,%s" % (prefix, container_dn)))
@@ -336,6 +416,7 @@ def add_cname_record(samdb, container_dn, prefix, host):
     msg["dnsRecord"] = ldb.MessageElement(ndr_pack(cname_record), ldb.FLAG_MOD_ADD, "dnsRecord")
     samdb.add(msg)
 
+
 def add_host_record(samdb, container_dn, prefix, hostip, hostip6):
     host_records = []
     if hostip:
@@ -350,6 +431,7 @@ def add_host_record(samdb, container_dn, prefix, hostip, hostip6):
         msg["dnsRecord"] = ldb.MessageElement(host_records, ldb.FLAG_MOD_ADD, "dnsRecord")
         samdb.add(msg)
 
+
 def add_domain_record(samdb, domaindn, prefix, dnsdomain, domainsid, dnsadmins_sid):
     # DC=<DNSDOMAIN>,CN=MicrosoftDNS,<PREFIX>,<DOMAINDN>
     sddl = "O:SYG:BAD:AI" \
@@ -366,11 +448,22 @@ def add_domain_record(samdb, domaindn, prefix, dnsdomain, domainsid, dnsadmins_s
     "(A;CIID;RPWPCRCCLCLORCWOWDSDSW;;;BA)" \
     "S:AI" % dnsadmins_sid
     sec = security.descriptor.from_sddl(sddl, domainsid)
+    props = []
+    props.append(ndr_pack(TypeProperty()))
+    props.append(ndr_pack(AllowUpdateProperty()))
+    props.append(ndr_pack(SecureTimeProperty()))
+    props.append(ndr_pack(NorefreshIntervalProperty(norefresh_interval=168)))
+    props.append(ndr_pack(RefreshIntervalProperty(refresh_interval=168)))
+    props.append(ndr_pack(AgingStateProperty()))
+    props.append(ndr_pack(AgingEnabledTimeProperty()))
     msg = ldb.Message(ldb.Dn(samdb, "DC=%s,CN=MicrosoftDNS,%s,%s" % (dnsdomain, prefix, domaindn)))
     msg["objectClass"] = ["top", "dnsZone"]
-    msg["ntSecurityDescriptor"] = ndr_pack(sec)
+    msg["ntSecurityDescriptor"] = ldb.MessageElement(ndr_pack(sec), ldb.FLAG_MOD_ADD,
+        "nTSecurityDescriptor")
+    msg["dNSProperty"] = ldb.MessageElement(props, ldb.FLAG_MOD_ADD, "dNSProperty")
     samdb.add(msg)
 
+
 def add_msdcs_record(samdb, forestdn, prefix, dnsforest):
     # DC=_msdcs.<DNSFOREST>,CN=MicrosoftDNS,<PREFIX>,<FORESTDN>
     msg = ldb.Message(ldb.Dn(samdb, "DC=_msdcs.%s,CN=MicrosoftDNS,%s,%s" %
@@ -379,7 +472,8 @@ def add_msdcs_record(samdb, forestdn, prefix, dnsforest):
     samdb.add(msg)
 
 
-def add_dc_domain_records(samdb, domaindn, prefix, site, dnsdomain, hostname, hostip, hostip6):
+def add_dc_domain_records(samdb, domaindn, prefix, site, dnsdomain, hostname,
+        hostip, hostip6):
 
     fqdn_hostname = "%s.%s" % (hostname, dnsdomain)
 
@@ -388,33 +482,40 @@ def add_dc_domain_records(samdb, domaindn, prefix, site, dnsdomain, hostname, ho
                                     (dnsdomain, prefix, domaindn))
 
     # DC=@ record
-    add_at_record(samdb, domain_container_dn, "DC=@", hostname, dnsdomain, hostip, hostip6)
+    add_at_record(samdb, domain_container_dn, "DC=@", hostname, dnsdomain,
+            hostip, hostip6)
 
     # DC=<HOSTNAME> record
-    add_host_record(samdb, domain_container_dn, "DC=%s" % hostname, hostip, hostip6)
+    add_host_record(samdb, domain_container_dn, "DC=%s" % hostname, hostip,
+            hostip6)
 
     # DC=_kerberos._tcp record
-    add_srv_record(samdb, domain_container_dn, "DC=_kerberos._tcp", fqdn_hostname, 88)
+    add_srv_record(samdb, domain_container_dn, "DC=_kerberos._tcp",
+            fqdn_hostname, 88)
 
     # DC=_kerberos._tcp.<SITENAME>._sites record
-    add_srv_record(samdb, domain_container_dn, "DC=_kerberos._tcp.%s._sites" % site,
-                    fqdn_hostname, 88)
+    add_srv_record(samdb, domain_container_dn, "DC=_kerberos._tcp.%s._sites" %
+            site, fqdn_hostname, 88)
 
     # DC=_kerberos._udp record
-    add_srv_record(samdb, domain_container_dn, "DC=_kerberos._udp", fqdn_hostname, 88)
+    add_srv_record(samdb, domain_container_dn, "DC=_kerberos._udp",
+            fqdn_hostname, 88)
 
     # DC=_kpasswd._tcp record
-    add_srv_record(samdb, domain_container_dn, "DC=_kpasswd._tcp", fqdn_hostname, 464)
+    add_srv_record(samdb, domain_container_dn, "DC=_kpasswd._tcp",
+            fqdn_hostname, 464)
 
     # DC=_kpasswd._udp record
-    add_srv_record(samdb, domain_container_dn, "DC=_kpasswd._udp", fqdn_hostname, 464)
+    add_srv_record(samdb, domain_container_dn, "DC=_kpasswd._udp",
+            fqdn_hostname, 464)
 
     # DC=_ldap._tcp record
-    add_srv_record(samdb, domain_container_dn, "DC=_ldap._tcp", fqdn_hostname, 389)
+    add_srv_record(samdb, domain_container_dn, "DC=_ldap._tcp", fqdn_hostname,
+            389)
 
     # DC=_ldap._tcp.<SITENAME>._sites record
-    add_srv_record(samdb, domain_container_dn, "DC=_ldap._tcp.%s._sites" % site,
-                    fqdn_hostname, 389)
+    add_srv_record(samdb, domain_container_dn, "DC=_ldap._tcp.%s._sites" %
+            site, fqdn_hostname, 389)
 
     # FIXME: The number of SRV records depend on the various roles this DC has.
     #        _gc and _msdcs records are added if the we are the forest dc and not subdomain dc
@@ -422,10 +523,12 @@ def add_dc_domain_records(samdb, domaindn, prefix, site, dnsdomain, hostname, ho
     # Assumption: current DC is GC and add all the entries
 
     # DC=_gc._tcp record
-    add_srv_record(samdb, domain_container_dn, "DC=_gc._tcp", fqdn_hostname, 3268)
+    add_srv_record(samdb, domain_container_dn, "DC=_gc._tcp", fqdn_hostname,
+            3268)
 
     # DC=_gc._tcp.<SITENAME>,_sites record
-    add_srv_record(samdb, domain_container_dn, "DC=_gc._tcp.%s._sites" % site, fqdn_hostname, 3268)
+    add_srv_record(samdb, domain_container_dn, "DC=_gc._tcp.%s._sites" % site,
+            fqdn_hostname, 3268)
 
     # DC=_msdcs record
     add_ns_glue_record(samdb, domain_container_dn, "DC=_msdcs", fqdn_hostname)
@@ -436,12 +539,14 @@ def add_dc_domain_records(samdb, domaindn, prefix, site, dnsdomain, hostname, ho
     # Assumption: Additional entries won't hurt on os_level = 2000
 
     # DC=_ldap._tcp.<SITENAME>._sites.DomainDnsZones
-    add_srv_record(samdb, domain_container_dn, "DC=_ldap._tcp.%s._sites.DomainDnsZones" % site,
-                    fqdn_hostname, 389)
+    add_srv_record(samdb, domain_container_dn,
+            "DC=_ldap._tcp.%s._sites.DomainDnsZones" % site, fqdn_hostname,
+            389)
 
     # DC=_ldap._tcp.<SITENAME>._sites.ForestDnsZones
-    add_srv_record(samdb, domain_container_dn, "DC=_ldap._tcp.%s._sites.ForestDnsZones" % site,
-                    fqdn_hostname, 389)
+    add_srv_record(samdb, domain_container_dn,
+            "DC=_ldap._tcp.%s._sites.ForestDnsZones" % site, fqdn_hostname,
+            389)
 
     # DC=_ldap._tcp.DomainDnsZones
     add_srv_record(samdb, domain_container_dn, "DC=_ldap._tcp.DomainDnsZones",
@@ -452,10 +557,12 @@ def add_dc_domain_records(samdb, domaindn, prefix, site, dnsdomain, hostname, ho
                     fqdn_hostname, 389)
 
     # DC=DomainDnsZones
-    add_host_record(samdb, domain_container_dn, "DC=DomainDnsZones", hostip, hostip6)
+    add_host_record(samdb, domain_container_dn, "DC=DomainDnsZones", hostip,
+            hostip6)
 
     # DC=ForestDnsZones
-    add_host_record(samdb, domain_container_dn, "DC=ForestDnsZones", hostip, hostip6)
+    add_host_record(samdb, domain_container_dn, "DC=ForestDnsZones", hostip,
+            hostip6)
 
 
 def add_dc_msdcs_records(samdb, forestdn, prefix, site, dnsforest, hostname,
@@ -468,41 +575,47 @@ def add_dc_msdcs_records(samdb, forestdn, prefix, site, dnsforest, hostname,
                                     (dnsforest, prefix, forestdn))
 
     # DC=@ record
-    add_at_record(samdb, forest_container_dn, "DC=@", hostname, dnsforest, None, None)
+    add_at_record(samdb, forest_container_dn, "DC=@", hostname, dnsforest,
+            None, None)
 
     # DC=_kerberos._tcp.dc record
-    add_srv_record(samdb, forest_container_dn, "DC=_kerberos._tcp.dc", fqdn_hostname, 88)
+    add_srv_record(samdb, forest_container_dn, "DC=_kerberos._tcp.dc",
+            fqdn_hostname, 88)
 
     # DC=_kerberos._tcp.<SITENAME>._sites.dc record
-    add_srv_record(samdb, forest_container_dn, "DC=_kerberos._tcp.%s._sites.dc" % site,
-                    fqdn_hostname, 88)
+    add_srv_record(samdb, forest_container_dn,
+            "DC=_kerberos._tcp.%s._sites.dc" % site, fqdn_hostname, 88)
 
     # DC=_ldap._tcp.dc record
-    add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.dc", fqdn_hostname, 389)
+    add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.dc",
+            fqdn_hostname, 389)
 
     # DC=_ldap._tcp.<SITENAME>._sites.dc record
-    add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.%s._sites.dc" % site,
-                    fqdn_hostname, 389)
+    add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.%s._sites.dc" %
+            site, fqdn_hostname, 389)
 
     # DC=_ldap._tcp.<SITENAME>._sites.gc record
-    add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.%s._sites.gc" % site,
-                    fqdn_hostname, 3268)
+    add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.%s._sites.gc" %
+            site, fqdn_hostname, 3268)
 
     # DC=_ldap._tcp.gc record
-    add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.gc", fqdn_hostname, 3268)
+    add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.gc",
+            fqdn_hostname, 3268)
 
     # DC=_ldap._tcp.pdc record
-    add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.pdc", fqdn_hostname, 389)
+    add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.pdc",
+            fqdn_hostname, 389)
 
     # DC=gc record
     add_host_record(samdb, forest_container_dn, "DC=gc", hostip, hostip6)
 
     # DC=_ldap._tcp.<DOMAINGUID>.domains record
-    add_srv_record(samdb, forest_container_dn, "DC=_ldap._tcp.%s.domains" % domainguid,
-                    fqdn_hostname, 389)
+    add_srv_record(samdb, forest_container_dn,
+            "DC=_ldap._tcp.%s.domains" % domainguid, fqdn_hostname, 389)
 
     # DC=<NTDSGUID>
-    add_cname_record(samdb, forest_container_dn, "DC=%s" % ntdsguid, fqdn_hostname)
+    add_cname_record(samdb, forest_container_dn, "DC=%s" % ntdsguid,
+            fqdn_hostname)
 
 
 def secretsdb_setup_dns(secretsdb, names, private_dir, realm,
@@ -625,67 +738,95 @@ def create_zone_file(lp, logger, paths, targetdir, dnsdomain,
         os.system(rndc + " unfreeze " + lp.get("realm"))
 
 
-def create_samdb_copy(logger, paths, names, domainsid, domainguid):
+def tdb_copy(logger, file1, file2):
+    """Copy tdb file using tdbbackup utility and rename it
+    """
+    # Find the location of tdbbackup tool
+    dirs = ["bin", samba.param.bin_dir()] + os.getenv('PATH').split(os.pathsep)
+    for d in dirs:
+        toolpath = os.path.join(d, "tdbbackup")
+        if os.path.exists(toolpath):
+            break
+    status = os.system("%s -s '.dns' %s" % (toolpath, file1))
+    if status == 0:
+        os.rename("%s.dns" % file1, file2)
+    else:
+        raise Exception("Error copying %s" % file1)
+
+
+def create_samdb_copy(samdb, logger, paths, names, domainsid, domainguid):
     """Create a copy of samdb and give write permissions to named for dns partitions
     """
     private_dir = paths.private_dir
     samldb_dir = os.path.join(private_dir, "sam.ldb.d")
     dns_dir = os.path.dirname(paths.dns)
     dns_samldb_dir = os.path.join(dns_dir, "sam.ldb.d")
-    domainpart_file = "%s.ldb" % names.domaindn.upper()
-    configpart_file = "%s.ldb" % names.configdn.upper()
-    schemapart_file = "%s.ldb" % names.schemadn.upper()
-    domainzone_file = "DC=DOMAINDNSZONES,%s.ldb" % names.domaindn.upper()
-    forestzone_file = "DC=FORESTDNSZONES,%s.ldb" % names.rootdn.upper()
-    metadata_file = "metadata.tdb"
 
-    # Copy config, schema partitions, create empty domain partition
+    # Find the partitions and corresponding filenames
+    partfile = {}
+    res = samdb.search(base="@PARTITION", scope=ldb.SCOPE_BASE, attrs=["partition"])
+    for tmp in res[0]["partition"]:
+        (nc, fname) = tmp.split(':')
+        partfile[nc.upper()] = fname
+
+    # Create empty domain partition
+    domaindn = names.domaindn.upper()
+    domainpart_file = os.path.join(dns_dir, partfile[domaindn])
     try:
-        shutil.copyfile(os.path.join(private_dir, "sam.ldb"),
-                        os.path.join(dns_dir, "sam.ldb"))
         os.mkdir(dns_samldb_dir)
-        file(os.path.join(dns_samldb_dir, domainpart_file), 'w').close()
-        shutil.copyfile(os.path.join(samldb_dir, configpart_file),
-                        os.path.join(dns_samldb_dir, configpart_file))
-        shutil.copyfile(os.path.join(samldb_dir, schemapart_file),
-                        os.path.join(dns_samldb_dir, schemapart_file))
-    except:
-        logger.error("Failed to setup database for BIND, AD based DNS cannot be used")
-        raise
+        file(domainpart_file, 'w').close()
 
-    # Link metadata and dns partitions
-    try:
-        os.link(os.path.join(samldb_dir, metadata_file),
-            os.path.join(dns_samldb_dir, metadata_file))
-        os.link(os.path.join(samldb_dir, domainzone_file),
-            os.path.join(dns_samldb_dir, domainzone_file))
-        os.link(os.path.join(samldb_dir, forestzone_file),
-            os.path.join(dns_samldb_dir, forestzone_file))
-    except OSError, e:
-        try:
-            os.symlink(os.path.join(samldb_dir, metadata_file),
-                os.path.join(dns_samldb_dir, metadata_file))
-            os.symlink(os.path.join(samldb_dir, domainzone_file),
-                os.path.join(dns_samldb_dir, domainzone_file))
-            os.symlink(os.path.join(samldb_dir, forestzone_file),
-                os.path.join(dns_samldb_dir, forestzone_file))
-        except OSError, e:
-            logger.error("Failed to setup database for BIND, AD based DNS cannot be used")
-            raise
-
-    # Fill the basedn and @OPTION records in domain partition
-    try:
-        ldb = samba.Ldb(os.path.join(dns_samldb_dir, domainpart_file))
+        # Fill the basedn and @OPTION records in domain partition
+        dom_ldb = samba.Ldb(domainpart_file)
         domainguid_line = "objectGUID: %s\n-" % domainguid
         descr = b64encode(get_domain_descriptor(domainsid))
-        add_ldif(ldb, "provision_basedn.ldif", {
+        setup_add_ldif(dom_ldb, setup_path("provision_basedn.ldif"), {
             "DOMAINDN" : names.domaindn,
             "DOMAINGUID" : domainguid_line,
             "DOMAINSID" : str(domainsid),
             "DESCRIPTOR" : descr})
-        add_ldif(ldb, "provision_basedn_options.ldif", None)
+        setup_add_ldif(dom_ldb,
+            setup_path("provision_basedn_options.ldif"), None)
     except:
-        logger.error("Failed to setup database for BIND, AD based DNS cannot be used")
+        logger.error(
+            "Failed to setup database for BIND, AD based DNS cannot be used")
+        raise
+    del partfile[domaindn]
+
+    # Link dns partitions and metadata
+    domainzonedn = "DC=DOMAINDNSZONES,%s" % names.domaindn.upper()
+    forestzonedn = "DC=FORESTDNSZONES,%s" % names.rootdn.upper()
+    domainzone_file = partfile[domainzonedn]
+    forestzone_file = partfile[forestzonedn]
+    metadata_file = "metadata.tdb"
+    try:
+        os.link(os.path.join(samldb_dir, metadata_file),
+            os.path.join(dns_samldb_dir, metadata_file))
+        os.link(os.path.join(private_dir, domainzone_file),
+            os.path.join(dns_dir, domainzone_file))
+        os.link(os.path.join(private_dir, forestzone_file),
+            os.path.join(dns_dir, forestzone_file))
+    except OSError:
+        logger.error(
+            "Failed to setup database for BIND, AD based DNS cannot be used")
+        raise
+    del partfile[domainzonedn]
+    del partfile[forestzonedn]
+
+    # Copy root, config, schema partitions (and any other if any)
+    # Since samdb is open in the current process, copy them in a child process
+    try:
+        tdb_copy(logger,
+                 os.path.join(private_dir, "sam.ldb"),
+                 os.path.join(dns_dir, "sam.ldb"))
+        for nc in partfile:
+            pfile = partfile[nc]
+            tdb_copy(logger,
+                     os.path.join(private_dir, pfile),
+                     os.path.join(dns_dir, pfile))
+    except:
+        logger.error(
+            "Failed to setup database for BIND, AD based DNS cannot be used")
         raise
 
     # Give bind read/write permissions dns partitions
@@ -693,25 +834,21 @@ def create_samdb_copy(logger, paths, names, domainsid, domainguid):
         try:
             os.chown(samldb_dir, -1, paths.bind_gid)
             os.chmod(samldb_dir, 0750)
-            os.chown(os.path.join(dns_dir, "sam.ldb"), -1, paths.bind_gid)
-            os.chmod(os.path.join(dns_dir, "sam.ldb"), 0660)
-            os.chown(dns_samldb_dir, -1, paths.bind_gid)
-            os.chmod(dns_samldb_dir, 0770)
-            os.chown(os.path.join(dns_samldb_dir, domainpart_file), -1, paths.bind_gid)
-            os.chmod(os.path.join(dns_samldb_dir, domainpart_file), 0660)
-            os.chown(os.path.join(dns_samldb_dir, configpart_file), -1, paths.bind_gid)
-            os.chmod(os.path.join(dns_samldb_dir, configpart_file), 0660)
-            os.chown(os.path.join(dns_samldb_dir, schemapart_file), -1, paths.bind_gid)
-            os.chmod(os.path.join(dns_samldb_dir, schemapart_file), 0660)
-            os.chown(os.path.join(samldb_dir, metadata_file), -1, paths.bind_gid)
-            os.chmod(os.path.join(samldb_dir, metadata_file), 0660)
-            os.chown(os.path.join(samldb_dir, domainzone_file), -1, paths.bind_gid)
-            os.chmod(os.path.join(samldb_dir, domainzone_file), 0660)
-            os.chown(os.path.join(samldb_dir, forestzone_file), -1, paths.bind_gid)
-            os.chmod(os.path.join(samldb_dir, forestzone_file), 0660)
+
+            for dirname, dirs, files in os.walk(dns_dir):
+                for d in dirs:
+                    dpath = os.path.join(dirname, d)
+                    os.chown(dpath, -1, paths.bind_gid)
+                    os.chmod(dpath, 0770)
+                for f in files:
+                    if f.endswith('.ldb') or f.endswith('.tdb'):
+                        fpath = os.path.join(dirname, f)
+                        os.chown(fpath, -1, paths.bind_gid)
+                        os.chmod(fpath, 0660)
         except OSError:
             if not os.environ.has_key('SAMBA_SELFTEST'):
-                logger.error("Failed to set permissions to sam.ldb* files, fix manually")
+                logger.error(
+                    "Failed to set permissions to sam.ldb* files, fix manually")
     else:
         if not os.environ.has_key('SAMBA_SELFTEST'):
             logger.warning("""Unable to find group id for BIND,
@@ -750,15 +887,12 @@ def create_named_conf(paths, realm, dnsdomain, dns_backend):
         setup_file(setup_path("named.conf.update"), paths.namedconf_update)
 
     elif dns_backend == "BIND9_DLZ":
-        dlz_module_path = os.path.join(samba.param.modules_dir(),
-                                        "bind9/dlz_bind9.so")
         setup_file(setup_path("named.conf.dlz"), paths.namedconf, {
                     "NAMED_CONF": paths.namedconf,
-                    "BIND9_DLZ_MODULE": dlz_module_path,
+                    "MODULESDIR" : samba.param.modules_dir(),
                     })
 
 
-
 def create_named_txt(path, realm, dnsdomain, dnsname, private_dir,
     keytab_name):
     """Write out a file containing zone statements suitable for inclusion in a
@@ -781,20 +915,97 @@ def create_named_txt(path, realm, dnsdomain, dnsname, private_dir,
 
 
 def is_valid_dns_backend(dns_backend):
-        return dns_backend in ("BIND9_FLATFILE", "BIND9_DLZ", "SAMBA_INTERNAL", "NONE")
+    return dns_backend in ("BIND9_FLATFILE", "BIND9_DLZ", "SAMBA_INTERNAL", "NONE")
 
 
 def is_valid_os_level(os_level):
     return DS_DOMAIN_FUNCTION_2000 <= os_level <= DS_DOMAIN_FUNCTION_2008_R2
 
 
-def setup_ad_dns(samdb, secretsdb, domainsid, names, paths, lp, logger, dns_backend,
-                 os_level, site, dnspass=None, hostip=None, hostip6=None,
-                 targetdir=None):
+def create_dns_legacy(samdb, domainsid, forestdn, dnsadmins_sid):
+    # Set up MicrosoftDNS container
+    add_dns_container(samdb, forestdn, "CN=System", domainsid, dnsadmins_sid)
+    # Add root servers
+    add_rootservers(samdb, forestdn, "CN=System")
+
+
+def fill_dns_data_legacy(samdb, domainsid, forestdn, dnsdomain, site, hostname,
+                         hostip, hostip6, dnsadmins_sid):
+    # Add domain record
+    add_domain_record(samdb, forestdn, "CN=System", dnsdomain, domainsid,
+                      dnsadmins_sid)
+
+    # Add DNS records for a DC in domain
+    add_dc_domain_records(samdb, forestdn, "CN=System", site, dnsdomain,
+                          hostname, hostip, hostip6)
+
+
+def create_dns_partitions(samdb, domainsid, names, domaindn, forestdn,
+                          dnsadmins_sid):
+    # Set up additional partitions (DomainDnsZones, ForstDnsZones)
+    setup_dns_partitions(samdb, domainsid, domaindn, forestdn,
+                        names.configdn, names.serverdn)
+
+    # Set up MicrosoftDNS containers
+    add_dns_container(samdb, domaindn, "DC=DomainDnsZones", domainsid,
+                      dnsadmins_sid)
+    add_dns_container(samdb, forestdn, "DC=ForestDnsZones", domainsid,
+                      dnsadmins_sid, forest=True)
+
+
+def fill_dns_data_partitions(samdb, domainsid, site, domaindn, forestdn,
+                            dnsdomain, dnsforest, hostname, hostip, hostip6,
+                            domainguid, ntdsguid, dnsadmins_sid, autofill=True):
+    """Fill data in various AD partitions
+
+    :param samdb: LDB object connected to sam.ldb file
+    :param domainsid: Domain SID (as dom_sid object)
+    :param site: Site name to create hostnames in
+    :param domaindn: DN of the domain
+    :param forestdn: DN of the forest
+    :param dnsdomain: DNS name of the domain
+    :param dnsforest: DNS name of the forest
+    :param hostname: Host name of this DC
+    :param hostip: IPv4 addresses
+    :param hostip6: IPv6 addresses
+    :param domainguid: Domain GUID
+    :param ntdsguid: NTDS GUID
+    :param dnsadmins_sid: SID for DnsAdmins group
+    :param autofill: Create DNS records (using fixed template)
+    """
+
+    ##### Set up DC=DomainDnsZones,<DOMAINDN>
+    # Add rootserver records
+    add_rootservers(samdb, domaindn, "DC=DomainDnsZones")
+
+    # Add domain record
+    add_domain_record(samdb, domaindn, "DC=DomainDnsZones", dnsdomain,
+                      domainsid, dnsadmins_sid)
+
+    # Add DNS records for a DC in domain
+    if autofill:
+        add_dc_domain_records(samdb, domaindn, "DC=DomainDnsZones", site,
+                              dnsdomain, hostname, hostip, hostip6)
+
+    ##### Set up DC=ForestDnsZones,<DOMAINDN>
+    # Add _msdcs record
+    add_msdcs_record(samdb, forestdn, "DC=ForestDnsZones", dnsforest)
+
+    # Add DNS records for a DC in forest
+    if autofill:
+        add_dc_msdcs_records(samdb, forestdn, "DC=ForestDnsZones", site,
+                             dnsforest, hostname, hostip, hostip6,
+                             domainguid, ntdsguid)
+
+
+def setup_ad_dns(samdb, secretsdb, domainsid, names, paths, lp, logger,
+        dns_backend, os_level, site, dnspass=None, hostip=None, hostip6=None,
+        targetdir=None):
     """Provision DNS information (assuming GC role)
 
     :param samdb: LDB object connected to sam.ldb file
     :param secretsdb: LDB object connected to secrets.ldb file
+    :param domainsid: Domain SID (as dom_sid object)
     :param names: Names shortcut
     :param paths: Paths shortcut
     :param lp: Loadparm object
@@ -814,10 +1025,14 @@ def setup_ad_dns(samdb, secretsdb, domainsid, names, paths, lp, logger, dns_back
     if not is_valid_os_level(os_level):
         raise Exception("Invalid os level: %r" % os_level)
 
-    if dns_backend is "NONE":
+    if dns_backend == "NONE":
         logger.info("No DNS backend set, not configuring DNS")
         return
 
+    # Add dns accounts (DnsAdmins, DnsUpdateProxy) in domain
+    logger.info("Adding DNS accounts")
+    add_dns_accounts(samdb, names.domaindn)
+
     # If dns_backend is BIND9_FLATFILE
     #   Populate only CN=MicrosoftDNS,CN=System,<FORESTDN>
     #
@@ -833,7 +1048,6 @@ def setup_ad_dns(samdb, secretsdb, domainsid, names, paths, lp, logger, dns_back
     #   Domain records are in CN=MicrosoftDNS,CN=System,<FORESTDN>
     #   Domain records are in CN=MicrosoftDNS,DC=DomainDnsZones,<DOMAINDN>
     #   Forest records are in CN=MicrosoftDNS,DC=ForestDnsZones,<FORESTDN>
-
     domaindn = names.domaindn
     forestdn = samdb.get_root_basedn().get_linearized()
 
@@ -842,96 +1056,97 @@ def setup_ad_dns(samdb, secretsdb, domainsid, names, paths, lp, logger, dns_back
 
     hostname = names.netbiosname.lower()
 
-    domainguid = get_domainguid(samdb, domaindn)
-    ntdsguid = get_ntdsguid(samdb, domaindn)
-
-    # Add dns accounts (DnsAdmins, DnsUpdateProxy) in domain
-    logger.info("Adding DNS accounts")
-    add_dns_accounts(samdb, domaindn)
     dnsadmins_sid = get_dnsadmins_sid(samdb, domaindn)
+    domainguid = get_domainguid(samdb, domaindn)
 
-    logger.info("Populating CN=MicrosoftDNS,CN=System,%s" % forestdn)
-
-    # Set up MicrosoftDNS container
-    add_dns_container(samdb, forestdn, "CN=System", domainsid, dnsadmins_sid)
-
-    # Add root servers
-    add_rootservers(samdb, forestdn, "CN=System")
+    # Create CN=System
+    logger.info("Creating CN=MicrosoftDNS,CN=System,%s" % forestdn)
+    create_dns_legacy(samdb, domainsid, forestdn, dnsadmins_sid)
 
     if os_level == DS_DOMAIN_FUNCTION_2000:
-
-        # Add domain record
-        add_domain_record(samdb, forestdn, "CN=System", dnsdomain, domainsid, dnsadmins_sid)
-
-        # Add DNS records for a DC in domain
-        add_dc_domain_records(samdb, forestdn, "CN=System", site, dnsdomain,
-                                hostname, hostip, hostip6)
+        # Populating legacy dns
+        logger.info("Populating CN=MicrosoftDNS,CN=System,%s" % forestdn)
+        fill_dns_data_legacy(samdb, domainsid, forestdn, dnsdomain, site,
+                             hostname, hostip, hostip6, dnsadmins_sid)
 
     elif dns_backend in ("SAMBA_INTERNAL", "BIND9_DLZ") and \
             os_level >= DS_DOMAIN_FUNCTION_2003:
 
-        # Set up additional partitions (DomainDnsZones, ForstDnsZones)
+        # Create DNS partitions
         logger.info("Creating DomainDnsZones and ForestDnsZones partitions")
-        setup_dns_partitions(samdb, domainsid, domaindn, forestdn,
-                            names.configdn, names.serverdn)
+        create_dns_partitions(samdb, domainsid, names, domaindn, forestdn,
+                              dnsadmins_sid)
 
-        ##### Set up DC=DomainDnsZones,<DOMAINDN>
-        logger.info("Populating DomainDnsZones partition")
+        # Populating dns partitions
+        logger.info("Populating DomainDnsZones and ForestDnsZones partitions")
+        fill_dns_data_partitions(samdb, domainsid, site, domaindn, forestdn,
+                                dnsdomain, dnsforest, hostname, hostip, hostip6,
+                                domainguid, names.ntdsguid, dnsadmins_sid)
 
-        # Set up MicrosoftDNS container
-        add_dns_container(samdb, domaindn, "DC=DomainDnsZones", domainsid, dnsadmins_sid)
+    if dns_backend.startswith("BIND9_"):
+        setup_bind9_dns(samdb, secretsdb, domainsid, names, paths, lp, logger,
+            dns_backend, os_level, site=site, dnspass=dnspass, hostip=hostip,
+            hostip6=hostip6, targetdir=targetdir)
 
-        # Add rootserver records
-        add_rootservers(samdb, domaindn, "DC=DomainDnsZones")
 
-        # Add domain record
-        add_domain_record(samdb, domaindn, "DC=DomainDnsZones", dnsdomain, domainsid,
-                          dnsadmins_sid)
+def setup_bind9_dns(samdb, secretsdb, domainsid, names, paths, lp, logger,
+        dns_backend, os_level, site=None, dnspass=None, hostip=None,
+        hostip6=None, targetdir=None):
+    """Provision DNS information (assuming BIND9 backend in DC role)
 
-        # Add DNS records for a DC in domain
-        add_dc_domain_records(samdb, domaindn, "DC=DomainDnsZones", site, dnsdomain,
-                                hostname, hostip, hostip6)
+    :param samdb: LDB object connected to sam.ldb file
+    :param secretsdb: LDB object connected to secrets.ldb file
+    :param domainsid: Domain SID (as dom_sid object)
+    :param names: Names shortcut
+    :param paths: Paths shortcut
+    :param lp: Loadparm object
+    :param logger: Logger object
+    :param dns_backend: Type of DNS backend
+    :param os_level: Functional level (treated as os level)
+    :param site: Site to create hostnames in
+    :param dnspass: Password for bind's DNS account
+    :param hostip: IPv4 address
+    :param hostip6: IPv6 address
+    :param targetdir: Target directory for creating DNS-related files for BIND9
+    """
+
+    if (not is_valid_dns_backend(dns_backend) or
+        not dns_backend.startswith("BIND9_")):
+        raise Exception("Invalid dns backend: %r" % dns_backend)
+
+    if not is_valid_os_level(os_level):
+        raise Exception("Invalid os level: %r" % os_level)
 
-        ##### Set up DC=ForestDnsZones,<DOMAINDN>
-        logger.info("Populating ForestDnsZones partition")
+    domaindn = names.domaindn
 
-        # Set up MicrosoftDNS container
-        add_dns_container(samdb, forestdn, "DC=ForestDnsZones", domainsid, dnsadmins_sid)
+    domainguid = get_domainguid(samdb, domaindn)
 
-        # Add _msdcs record
-        add_msdcs_record(samdb, forestdn, "DC=ForestDnsZones", dnsforest)
+    secretsdb_setup_dns(secretsdb, names,
+                        paths.private_dir, realm=names.realm,
+                        dnsdomain=names.dnsdomain,
+                        dns_keytab_path=paths.dns_keytab, dnspass=dnspass)
 
-        # Add DNS records for a DC in forest
-        add_dc_msdcs_records(samdb, forestdn, "DC=ForestDnsZones", site, dnsforest,
-                                hostname, hostip, hostip6, domainguid, ntdsguid)
+    create_dns_dir(logger, paths)
 
-    if dns_backend.startswith("BIND9_"):
-        secretsdb_setup_dns(secretsdb, names,
-                            paths.private_dir, realm=names.realm,
-                            dnsdomain=names.dnsdomain,
-                            dns_keytab_path=paths.dns_keytab, dnspass=dnspass)
-
-        create_dns_dir(logger, paths)
-
-        # Only make a zone file on the first DC, it should be
-        # replicated with DNS replication
-        if dns_backend == "BIND9_FLATFILE":
-            create_zone_file(lp, logger, paths, targetdir, site=site,
-                             dnsdomain=names.dnsdomain, hostip=hostip, hostip6=hostip6,
-                             hostname=names.hostname, realm=names.realm,
-                             domainguid=domainguid, ntdsguid=names.ntdsguid)
-
-        if dns_backend == "BIND9_DLZ" and os_level >= DS_DOMAIN_FUNCTION_2003:
-            create_samdb_copy(logger, paths, names, domainsid, domainguid)
-
-        create_named_conf(paths, realm=names.realm,
-                          dnsdomain=names.dnsdomain, dns_backend=dns_backend)
-
-        create_named_txt(paths.namedtxt,
-                         realm=names.realm, dnsdomain=names.dnsdomain,
-                         dnsname = "%s.%s" % (names.hostname, names.dnsdomain),
-                         private_dir=paths.private_dir,
-                         keytab_name=paths.dns_keytab)
-        logger.info("See %s for an example configuration include file for BIND", paths.namedconf)
-        logger.info("and %s for further documentation required for secure DNS "
-                    "updates", paths.namedtxt)
+    if dns_backend == "BIND9_FLATFILE":
+        create_zone_file(lp, logger, paths, targetdir, site=site,
+                         dnsdomain=names.dnsdomain, hostip=hostip,
+                         hostip6=hostip6, hostname=names.hostname,
+                         realm=names.realm, domainguid=domainguid,
+                         ntdsguid=names.ntdsguid)
+
+    if dns_backend == "BIND9_DLZ" and os_level >= DS_DOMAIN_FUNCTION_2003:
+        create_samdb_copy(samdb, logger, paths, names, domainsid, domainguid)
+
+    create_named_conf(paths, realm=names.realm,
+                      dnsdomain=names.dnsdomain, dns_backend=dns_backend)
+
+    create_named_txt(paths.namedtxt,
+                     realm=names.realm, dnsdomain=names.dnsdomain,
+                     dnsname = "%s.%s" % (names.hostname, names.dnsdomain),
+                     private_dir=paths.private_dir,
+                     keytab_name=paths.dns_keytab)
+    logger.info("See %s for an example configuration include file for BIND",
+                paths.namedconf)
+    logger.info("and %s for further documentation required for secure DNS "
+                "updates", paths.namedtxt)