[PATCH] make samba-tool aware of all 7 fsmo roles

Rowland Penny repenny241155 at gmail.com
Sat May 30 09:34:52 MDT 2015


On 29/05/15 10:32, Rowland Penny wrote:
> On 28/05/15 20:48, Stefan (metze) Metzmacher wrote:
>> Am 28.05.2015 um 21:41 schrieb Rowland Penny:
>>> On 28/05/15 20:10, Stefan (metze) Metzmacher wrote:
>>>> Hi Rowland,
>>>>
>>>>>> You also need use forest_dn instead of domain_dn when constructing
>>>>>> forestdns_dn.
>>>>> Done this, unlike the domain_dn, there doesn't seem to be a python
>>>>> 'subroutine' for this, so I came up with a one-liner with
>>>>> 'samdb.forest_dns_name()'
>>>> You can add this next to domain_dn() as a first commit.
>>>>
>>>>       def forest_dn(self):
>>>>           '''return the forest root DN'''
>>>>           return str(self.get_root_basedn())
>>> I used: forest_dn = "DC=" + samdb.forest_dns_name().replace(".", 
>>> ",DC=")
>>>
>>> Please remember that I am very new to this,
>> I'm sure you'll find your way through all the new things you learn :-)
>>
>>> so I hope you don't mind me
>>> asking this, but what do you mean by 'first commit' ?
>> Just that you add the above new function to python/samba/samdb.py
>> and commit the change on its own and it needs to be the first commit
>> (before the main commit that uses it).
>>
>> It is more or less simple to reorder patches using something like:
>> git rebase -i origin/master
>> (it opens an editor, so you may want to use export EDITOR=vim or
>> something similar,
>> I'm not sure what the default is maybe nano...)
>>
>>>>>> Please also test with and without the --force option.
>>>>> Test what ?
>>>> samba-tool fsmo seize with and without --force.
>>> OK, I understand now, but testing of another part has raised a 
>>> problem I
>>> wasn't aware of, so I will have to sort that out first.
>> Good luck:-)
>>
>> metze
>>
>
> Hi Stefan, is this a bug or a feature ?
>
> First check who owns the FSMO roles:
> root at testdc2:~# samba-tool fsmo show
> SchemaMasterRole owner: CN=NTDS 
> Settings,CN=TESTDC2,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=sambadom,DC=example,DC=com
> InfrastructureMasterRole owner: CN=NTDS 
> Settings,CN=TESTDC1,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=sambadom,DC=example,DC=com
> RidAllocationMasterRole owner: CN=NTDS 
> Settings,CN=TESTDC1,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=sambadom,DC=example,DC=com
> PdcEmulationMasterRole owner: CN=NTDS 
> Settings,CN=TESTDC1,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=sambadom,DC=example,DC=com
> DomainNamingMasterRole owner: CN=NTDS 
> Settings,CN=TESTDC1,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=sambadom,DC=example,DC=com
> DomainDnsZonesMasterRole owner: CN=NTDS 
> Settings,CN=TESTDC1,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=sambadom,DC=example,DC=com
> ForestDnsZonesMasterRole owner: CN=NTDS 
> Settings,CN=TESTDC1,CN=Servers,CN=Default-First-Site-Name,CN=Sites,CN=Configuration,DC=sambadom,DC=example,DC=com
>
> Now transfer them:
> root at testdc2:~# samba-tool fsmo transfer --role=all -UAdministrator 
> --password=XXXXXXXXX
> FSMO transfer of 'rid' role successful
> FSMO transfer of 'pdc' role successful
> FSMO transfer of 'naming' role successful
> FSMO transfer of 'infrastructure' role successful
> FSMO transfer of 'schema' role successful
> FSMO transfer of 'domaindns' role successful
> FSMO transfer of 'forestdns' role successful
>
> Now try to transfer them again (on the same DC):
> root at testdc2:~# samba-tool fsmo transfer --role=all -UAdministrator 
> --password=XXXXXXXXX
> FSMO transfer of 'rid' role successful
> FSMO transfer of 'pdc' role successful
> FSMO transfer of 'naming' role successful
> FSMO transfer of 'infrastructure' role successful
> FSMO transfer of 'schema' role successful
> This DC already has the 'domaindns' FSMO role
> This DC already has the 'forestdns' FSMO role
>
> It says it has successfully transferred the known 5 again !!
>
> Rowland

OK, here is an updated patch, this should address all of the problems 
raised by Stefan and it also only tries to transfer/seize the role if 
the DC isn't already the owner, something the original doesn't.

Rowland
-------------- next part --------------
From a12c46a8b64e025c30b3d8a717c67cb3b164a5d0 Mon Sep 17 00:00:00 2001
From: Rowland Penny <repenny241155 at gmail.com>
Date: Sat, 30 May 2015 16:23:11 +0100
Subject: [PATCH] samba-tool: make 'samba-tool fsmo *' aware of all 7 fsmo
 roles

BUG: https://bugzilla.samba.org/show_bug.cgi?id=10734

Signed-off-by: Rowland Penny <repenny241155 at gmail.com>
---
 python/samba/netcmd/fsmo.py |  282 ++++++++++++++++++++++++++++++++++++-------
 1 file changed, 236 insertions(+), 46 deletions(-)

diff --git a/python/samba/netcmd/fsmo.py b/python/samba/netcmd/fsmo.py
index 1bc4a96..031b927 100644
--- a/python/samba/netcmd/fsmo.py
+++ b/python/samba/netcmd/fsmo.py
@@ -17,10 +17,11 @@
 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
 #
 
+import samba
 import samba.getopt as options
 import ldb
 from ldb import LdbError
-
+from samba.dcerpc import drsuapi, misc
 from samba.auth import system_session
 from samba.netcmd import (
     Command,
@@ -30,15 +31,103 @@ from samba.netcmd import (
     )
 from samba.samdb import SamDB
 
+def transfer_dns_role(outf, sambaopts, credopts, role, samdb):
+    if role == "domaindns":
+        domain_dn = samdb.domain_dn()
+        role_object = "CN=Infrastructure,DC=DomainDnsZones," + domain_dn
+    elif role == "forestdns":
+        forest_dn = "DC=" + samdb.forest_dns_name().replace(".", ",DC=")
+        role_object = "CN=Infrastructure,DC=ForestDnsZones," + forest_dn
+
+    try:
+        res = samdb.search(role_object, attrs=["fSMORoleOwner"],
+                           scope=ldb.SCOPE_BASE, controls=["extended_dn:1:1"])
+
+        if 'fSMORoleOwner' in res[0]:
+            try:
+                master_guid = str(misc.GUID(ldb.Dn(samdb, res[0]['fSMORoleOwner'][0]).get_extended_component('GUID')))
+                master_owner = str(ldb.Dn(samdb, res[0]['fSMORoleOwner'][0]))
+            except:
+                print "Can't find GUID in naming master on partition DN %s" % res[0]['fSMORoleOwner'][0]
+                return
+    except LdbError, (num, msg):
+        raise CommandError("DNS partion %s not found : %s" % (role, msg))
+        return
+
+    if role == "domaindns":
+        master_dns_name = '%s._msdcs.%s' % (master_guid, samdb.domain_dns_name())
+        new_dns_name = '%s._msdcs.%s' % (samdb.get_ntds_GUID(), samdb.domain_dns_name())
+    elif role == "forestdns":
+        master_dns_name = '%s._msdcs.%s' % (master_guid, samdb.forest_dns_name())
+        new_dns_name = '%s._msdcs.%s' % (samdb.get_ntds_GUID(), samdb.forest_dns_name())
+
+    new_owner = samdb.get_dsServiceName()
+
+    if master_dns_name != new_dns_name:
+        lp = sambaopts.get_loadparm()
+        creds = credopts.get_credentials(lp, fallback_machine=True)
+        samdb = SamDB(url="ldap://%s" % (master_dns_name), session_info=system_session(),
+                      credentials=creds, lp=lp)
+
+        m = ldb.Message()
+        m.dn = ldb.Dn(samdb, role_object)
+        m["fSMORoleOwner"]= ldb.MessageElement(
+            "%s" % master_owner, ldb.FLAG_MOD_DELETE,
+            "fSMORoleOwner")
+
+        try:
+            samdb.modify(m)
+        except LdbError, (num, msg):
+            raise CommandError("Failed to delete role '%s': %s" % (role, msg))
+        else:
+             m = ldb.Message()
+             m.dn = ldb.Dn(samdb, role_object)
+             m["fSMORoleOwner"]= ldb.MessageElement(
+                 "%s" % new_owner, ldb.FLAG_MOD_ADD,
+                 "fSMORoleOwner")
+             try:
+                 samdb.modify(m)
+             except LdbError, (num, msg):
+                 raise CommandError("Failed to add role '%s': %s" % (role, msg))
+             else:
+                  try:
+                      connection = (samba.drs_utils.drsuapi_connect(samdb.host_dns_name(), lp, creds))
+                  except samba.drs_utils.drsException, estr:
+                      raise CommandError("Drsuapi Connect failed", estr)
+                  else:
+                       try:
+                           drsuapi_connection = connection[0]
+                           drsuapi_handle = connection[1]
+                           req_options = drsuapi.DRSUAPI_DRS_WRIT_REP
+                           NC = role_object[18:]
+                           samba.drs_utils.sendDsReplicaSync(drsuapi_connection, drsuapi_handle, master_guid, NC, req_options)
+                       except samba.drs_utils.drsException, estr:
+                           raise CommandError("Replication failed", estr)
+
+        outf.write("FSMO transfer of '%s' role successful\n" % role)
+    else:
+        print "This DC already has the '%s' FSMO role" % role
+
+
 def transfer_role(outf, role, samdb):
+    domain_dn = samdb.domain_dn()
+    new_owner = samdb.get_dsServiceName()
     m = ldb.Message()
     m.dn = ldb.Dn(samdb, "")
     if role == "rid":
+        rid_dn = "CN=RID Manager$,CN=System," + domain_dn
+        res = samdb.search(rid_dn,
+                           scope=ldb.SCOPE_BASE, attrs=["fSMORoleOwner"])
+        assert len(res) == 1
+        master_owner = res[0]["fSMORoleOwner"][0]
         m["becomeRidMaster"]= ldb.MessageElement(
             "1", ldb.FLAG_MOD_REPLACE,
             "becomeRidMaster")
     elif role == "pdc":
-        domain_dn = samdb.domain_dn()
+        res = samdb.search(domain_dn,
+                           scope=ldb.SCOPE_BASE, attrs=["fSMORoleOwner"])
+        assert len(res) == 1
+        master_owner = res[0]["fSMORoleOwner"][0]
         res = samdb.search(domain_dn,
                            scope=ldb.SCOPE_BASE, attrs=["objectSid"])
         assert len(res) == 1
@@ -47,24 +136,44 @@ def transfer_role(outf, role, samdb):
             sid, ldb.FLAG_MOD_REPLACE,
             "becomePdc")
     elif role == "naming":
+        naming_dn = "CN=Partitions,%s" % samdb.get_config_basedn()
+        res = samdb.search(naming_dn,
+                           scope=ldb.SCOPE_BASE, attrs=["fSMORoleOwner"])
+        assert len(res) == 1
+        master_owner = res[0]["fSMORoleOwner"][0]
         m["becomeDomainMaster"]= ldb.MessageElement(
             "1", ldb.FLAG_MOD_REPLACE,
             "becomeDomainMaster")
     elif role == "infrastructure":
+        infrastructure_dn = "CN=Infrastructure," + domain_dn
+        res = samdb.search(infrastructure_dn,
+                           scope=ldb.SCOPE_BASE, attrs=["fSMORoleOwner"])
+        assert len(res) == 1
+        master_owner = res[0]["fSMORoleOwner"][0]
         m["becomeInfrastructureMaster"]= ldb.MessageElement(
             "1", ldb.FLAG_MOD_REPLACE,
             "becomeInfrastructureMaster")
     elif role == "schema":
+        schema_dn = str(samdb.get_schema_basedn())
+        res = samdb.search(schema_dn,
+                           scope=ldb.SCOPE_BASE, attrs=["fSMORoleOwner"])
+        assert len(res) == 1
+        master_owner = res[0]["fSMORoleOwner"][0]
         m["becomeSchemaMaster"]= ldb.MessageElement(
             "1", ldb.FLAG_MOD_REPLACE,
             "becomeSchemaMaster")
     else:
         raise CommandError("Invalid FSMO role.")
-    try:
-        samdb.modify(m)
-    except LdbError, (num, msg):
-        raise CommandError("Failed to initiate transfer of '%s' role: %s" % (role, msg))
-    outf.write("FSMO transfer of '%s' role successful\n" % role)
+
+    if master_owner != new_owner:
+        try:
+            samdb.modify(m)
+        except LdbError, (num, msg):
+            raise CommandError("Failed to initiate transfer of '%s' role: %s" % (role, msg))
+        else:
+            outf.write("FSMO transfer of '%s' role successful\n" % role)
+    else:
+        print "This DC already has the '%s' FSMO role" % role
 
 
 class cmd_fsmo_seize(Command):
@@ -82,23 +191,23 @@ class cmd_fsmo_seize(Command):
         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
         Option("--force", help="Force seizing of the role without attempting to transfer first.", action="store_true"),
-        Option("--role", type="choice", choices=["rid", "pdc", "infrastructure","schema","naming","all"],
+        Option("--role", type="choice", choices=["rid", "pdc", "infrastructure","schema","naming","domaindns","forestdns","all"],
                help="""The FSMO role to seize or transfer.\n
-rid=RidAllocationMasterRole\n
-schema=SchemaMasterRole\n
-pdc=PdcEmulationMasterRole\n
-naming=DomainNamingMasterRole\n
-infrastructure=InfrastructureMasterRole\n
-all=all of the above"""),
+rid=RidAllocationMasterRole                         \n
+schema=SchemaMasterRole                             \n
+pdc=PdcEmulationMasterRole                          \n
+naming=DomainNamingMasterRole                       \n
+infrastructure=InfrastructureMasterRole             \n
+domaindns=DomainDnsZonesMasterRole                  \n
+forestdns=ForestDnsZonesMasterRole                  \n
+all=all of the above                                \n
+You must provide an Admin user and password."""),
         ]
 
     takes_args = []
 
     def seize_role(self, role, samdb, force):
-        res = samdb.search("",
-                           scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
-        assert len(res) == 1
-        serviceName = res[0]["dsServiceName"][0]
+        serviceName = samdb.get_dsServiceName()
         domain_dn = samdb.domain_dn()
         self.infrastructure_dn = "CN=Infrastructure," + domain_dn
         self.naming_dn = "CN=Partitions,%s" % samdb.get_config_basedn()
@@ -119,26 +228,78 @@ all=all of the above"""),
         else:
             raise CommandError("Invalid FSMO role.")
         #first try to transfer to avoid problem if the owner is still active
-        if force is None:
-            self.message("Attempting transfer...")
+        res = samdb.search(m.dn,
+                           scope=ldb.SCOPE_BASE, attrs=["fSMORoleOwner"])
+        assert len(res) == 1
+        master_owner = res[0]["fSMORoleOwner"][0]
+        if master_owner != serviceName:
+            if force is None:
+                self.message("Attempting transfer...")
+                try:
+                    transfer_role(self.outf, role, samdb)
+                    self.outf.write("FSMO seize was not required, as transfer of '%s' role was successful\n" % role)
+                    return
+                except CommandError:
+                    #transfer failed, use the big axe...
+                    self.message("Transfer unsuccessful, seizing...")
+            else:
+                self.message("Will not attempt transfer, seizing...")
+
+            m["fSMORoleOwner"]= ldb.MessageElement(
+                serviceName, ldb.FLAG_MOD_REPLACE,
+                "fSMORoleOwner")
             try:
-                transfer_role(self.outf, role, samdb)
-                self.outf.write("FSMO seize was not required, as transfer of '%s' role was successful\n" % role)
-                return
-            except CommandError:
-            #transfer failed, use the big axe...
-                self.message("Transfer unsuccessful, seizing...")
+                samdb.modify(m)
+            except LdbError, (num, msg):
+                raise CommandError("Failed to initiate role seize of '%s' role: %s" % (role, msg))
+            else:
+                self.outf.write("FSMO seize of '%s' role successful\n" % role)
         else:
-            self.message("Will not attempt transfer, seizing...")
+            print "This DC already has the '%s' FSMO role" % role
 
-        m["fSMORoleOwner"]= ldb.MessageElement(
-            serviceName, ldb.FLAG_MOD_REPLACE,
-            "fSMORoleOwner")
-        try:
-            samdb.modify(m)
-        except LdbError, (num, msg):
-            raise CommandError("Failed to initiate role seize of '%s' role: %s" % (role, msg))
-        self.outf.write("FSMO seize of '%s' role successful\n" % role)
+    def seize_dns_role(self, role, samdb, credopts, sambaopts, versionopts, force):
+        serviceName = samdb.get_dsServiceName()
+        domain_dn = samdb.domain_dn()
+        forest_dn = "DC=" + samdb.forest_dns_name().replace(".", ",DC=")
+        self.domaindns_dn = "CN=Infrastructure,DC=DomainDnsZones," + domain_dn
+        self.forestdns_dn = "CN=Infrastructure,DC=ForestDnsZones," + forest_dn
+
+        m = ldb.Message()
+        if role == "domaindns":
+            m.dn = ldb.Dn(samdb, self.domaindns_dn)
+        elif role == "forestdns":
+            m.dn = ldb.Dn(samdb, self.forestdns_dn)
+        else:
+            raise CommandError("Invalid FSMO role.")
+        #first try to transfer to avoid problem if the owner is still active
+        res = samdb.search(m.dn,
+                           scope=ldb.SCOPE_BASE, attrs=["fSMORoleOwner"])
+        assert len(res) == 1
+        master_owner = res[0]["fSMORoleOwner"][0]
+        if master_owner != serviceName:
+            if force is None:
+                self.message("Attempting transfer...")
+                try:
+                    transfer_dns_role(self.outf, sambaopts, credopts, role, samdb)
+                    self.outf.write("FSMO seize was not required, as transfer of '%s' role was successful\n" % role)
+                    return
+                except CommandError:
+                #transfer failed, use the big axe...
+                    self.message("Transfer unsuccessful, seizing...")
+            else:
+                self.message("Will not attempt transfer, seizing...")
+
+            m["fSMORoleOwner"]= ldb.MessageElement(
+                serviceName, ldb.FLAG_MOD_REPLACE,
+                "fSMORoleOwner")
+            try:
+                samdb.modify(m)
+            except LdbError, (num, msg):
+                raise CommandError("Failed to initiate role seize of '%s' role: %s" % (role, msg))
+            else:
+                self.outf.write("FSMO seize of '%s' role successful\n" % role)
+        else:
+            print "This DC already has the '%s' FSMO role" % role
 
     def run(self, force=None, H=None, role=None,
             credopts=None, sambaopts=None, versionopts=None):
@@ -155,8 +316,13 @@ all=all of the above"""),
             self.seize_role("naming", samdb, force)
             self.seize_role("infrastructure", samdb, force)
             self.seize_role("schema", samdb, force)
+            self.seize_dns_role("domaindns", samdb, credopts, sambaopts, versionopts, force)
+            self.seize_dns_role("forestdns", samdb, credopts, sambaopts, versionopts, force)
         else:
-            self.seize_role(role, samdb, force)
+            if role == "domaindns" or role == "forestdns":
+                self.seize_dns_role(role, samdb, credopts, sambaopts, versionopts, force)
+            else:
+                self.seize_role(role, samdb, force)
 
 
 class cmd_fsmo_show(Command):
@@ -185,10 +351,14 @@ class cmd_fsmo_show(Command):
             credentials=creds, lp=lp)
 
         domain_dn = samdb.domain_dn()
+        forest_dn = "DC=" + samdb.forest_dns_name().replace(".", ",DC=")
         self.infrastructure_dn = "CN=Infrastructure," + domain_dn
         self.naming_dn = "CN=Partitions,%s" % samdb.get_config_basedn()
         self.schema_dn = samdb.get_schema_basedn()
         self.rid_dn = "CN=RID Manager$,CN=System," + domain_dn
+        self.domaindns_dn = "CN=Infrastructure,DC=DomainDnsZones," + domain_dn
+        self.forestdns_dn = "CN=Infrastructure,DC=ForestDnsZones," + forest_dn
+
 
         res = samdb.search(self.infrastructure_dn,
                            scope=ldb.SCOPE_BASE, attrs=["fSMORoleOwner"])
@@ -215,11 +385,23 @@ class cmd_fsmo_show(Command):
         assert len(res) == 1
         self.ridMaster = res[0]["fSMORoleOwner"][0]
 
+        res = samdb.search(self.domaindns_dn,
+                           scope=ldb.SCOPE_BASE, attrs=["fSMORoleOwner"])
+        assert len(res) == 1
+        self.domaindnszonesMaster = res[0]["fSMORoleOwner"][0]
+
+        res = samdb.search(self.forestdns_dn,
+                           scope=ldb.SCOPE_BASE, attrs=["fSMORoleOwner"])
+        assert len(res) == 1
+        self.forestdnszonesMaster = res[0]["fSMORoleOwner"][0]
+
+        self.message("SchemaMasterRole owner: " + self.schemaMaster)
         self.message("InfrastructureMasterRole owner: " + self.infrastructureMaster)
         self.message("RidAllocationMasterRole owner: " + self.ridMaster)
         self.message("PdcEmulationMasterRole owner: " + self.pdcEmulator)
         self.message("DomainNamingMasterRole owner: " + self.namingMaster)
-        self.message("SchemaMasterRole owner: " + self.schemaMaster)
+        self.message("DomainDnsZonesMasterRole owner: " + self.domaindnszonesMaster)
+        self.message("ForestDnsZonesMasterRole owner: " + self.forestdnszonesMaster)
 
 
 class cmd_fsmo_transfer(Command):
@@ -236,14 +418,17 @@ class cmd_fsmo_transfer(Command):
     takes_options = [
         Option("-H", "--URL", help="LDB URL for database or target server", type=str,
                metavar="URL", dest="H"),
-        Option("--role", type="choice", choices=["rid", "pdc", "infrastructure","schema","naming","all"],
-               help="""The FSMO role to seize or transfer.\n
-rid=RidAllocationMasterRole\n
-schema=SchemaMasterRole\n
-pdc=PdcEmulationMasterRole\n
-naming=DomainNamingMasterRole\n
-infrastructure=InfrastructureMasterRole\n
-all=all of the above"""),
+        Option("--role", type="choice", choices=["rid","pdc","infrastructure","schema","naming","domaindns","forestdns", "all"],
+               help="""The FSMO role to transfer.\n
+rid=RidAllocationMasterRole                         \n
+schema=SchemaMasterRole                             \n
+pdc=PdcEmulationMasterRole                          \n
+naming=DomainNamingMasterRole                       \n
+infrastructure=InfrastructureMasterRole             \n
+domaindns=DomainDnsZonesMasterRole                  \n
+forestdns=ForestDnsZonesMasterRole                  \n
+all=all of the above                               \n
+You must provide an Admin user and password."""),
         ]
 
     takes_args = []
@@ -263,8 +448,13 @@ all=all of the above"""),
             transfer_role(self.outf, "naming", samdb)
             transfer_role(self.outf, "infrastructure", samdb)
             transfer_role(self.outf, "schema", samdb)
+            transfer_dns_role(self.outf, sambaopts, credopts, "domaindns", samdb)
+            transfer_dns_role(self.outf, sambaopts, credopts, "forestdns", samdb)
         else:
-            transfer_role(self.outf, role, samdb)
+            if role == "domaindns" or role == "forestdns":
+                transfer_dns_role(self.outf, sambaopts, credopts, role, samdb)
+            else:
+                transfer_role(self.outf, role, samdb)
 
 
 class cmd_fsmo(SuperCommand):
-- 
1.7.10.4


More information about the samba-technical mailing list