1 # Changes a FSMO role owner
3 # Copyright Nadezhda Ivanova 2009
4 # Copyright Jelmer Vernooij 2009
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 import samba.getopt as options
23 from ldb import LdbError
24 from samba.dcerpc import drsuapi, misc
25 from samba.auth import system_session
26 from samba.netcmd import (
32 from samba.samdb import SamDB
35 def get_fsmo_roleowner(samdb, roledn, role):
36 """Gets the owner of an FSMO role
38 :param roledn: The DN of the FSMO role
39 :param role: The FSMO role
42 res = samdb.search(roledn,
43 scope=ldb.SCOPE_BASE, attrs=["fSMORoleOwner"])
44 except LdbError as e7:
46 if num == ldb.ERR_NO_SUCH_OBJECT:
47 raise CommandError("The '%s' role is not present in this domain" % role)
50 if 'fSMORoleOwner' in res[0]:
51 master_owner = (ldb.Dn(samdb, res[0]["fSMORoleOwner"][0].decode('utf8')))
58 def transfer_dns_role(outf, sambaopts, credopts, role, samdb):
59 """Transfer dns FSMO role. """
61 if role == "domaindns":
62 domain_dn = samdb.domain_dn()
63 role_object = "CN=Infrastructure,DC=DomainDnsZones," + domain_dn
64 elif role == "forestdns":
65 forest_dn = samba.dn_from_dns_name(samdb.forest_dns_name())
66 role_object = "CN=Infrastructure,DC=ForestDnsZones," + forest_dn
68 new_host_dns_name = samdb.host_dns_name()
70 res = samdb.search(role_object,
71 attrs=["fSMORoleOwner"],
73 controls=["extended_dn:1:1"])
75 if 'fSMORoleOwner' in res[0]:
77 master_guid = str(misc.GUID(ldb.Dn(samdb,
78 res[0]['fSMORoleOwner'][0].decode('utf8'))
79 .get_extended_component('GUID')))
80 master_owner = str(ldb.Dn(samdb, res[0]['fSMORoleOwner'][0].decode('utf8')))
81 except LdbError as e3:
83 raise CommandError("No GUID found in naming master DN %s : %s \n" %
84 (res[0]['fSMORoleOwner'][0], msg))
86 outf.write("* The '%s' role does not have an FSMO roleowner\n" % role)
89 if role == "domaindns":
90 master_dns_name = '%s._msdcs.%s' % (master_guid,
91 samdb.domain_dns_name())
92 new_dns_name = '%s._msdcs.%s' % (samdb.get_ntds_GUID(),
93 samdb.domain_dns_name())
94 elif role == "forestdns":
95 master_dns_name = '%s._msdcs.%s' % (master_guid,
96 samdb.forest_dns_name())
97 new_dns_name = '%s._msdcs.%s' % (samdb.get_ntds_GUID(),
98 samdb.forest_dns_name())
100 new_owner = samdb.get_dsServiceName()
102 if master_dns_name != new_dns_name:
103 lp = sambaopts.get_loadparm()
104 creds = credopts.get_credentials(lp, fallback_machine=True)
105 samdb = SamDB(url="ldap://%s" % (master_dns_name),
106 session_info=system_session(),
107 credentials=creds, lp=lp)
110 m.dn = ldb.Dn(samdb, role_object)
111 m["fSMORoleOwner"] = ldb.MessageElement(master_owner,
117 except LdbError as e4:
119 raise CommandError("Failed to delete role '%s': %s" %
123 m.dn = ldb.Dn(samdb, role_object)
124 m["fSMORoleOwner"] = ldb.MessageElement(new_owner,
129 except LdbError as e5:
131 raise CommandError("Failed to add role '%s': %s" % (role, msg))
134 connection = samba.drs_utils.drsuapi_connect(new_host_dns_name,
136 except samba.drs_utils.drsException as e:
137 raise CommandError("Drsuapi Connect failed", e)
140 drsuapi_connection = connection[0]
141 drsuapi_handle = connection[1]
142 req_options = drsuapi.DRSUAPI_DRS_WRIT_REP
143 NC = role_object[18:]
144 samba.drs_utils.sendDsReplicaSync(drsuapi_connection,
148 except samba.drs_utils.drsException as estr:
149 raise CommandError("Replication failed", estr)
151 outf.write("FSMO transfer of '%s' role successful\n" % role)
154 outf.write("This DC already has the '%s' FSMO role\n" % role)
158 def transfer_role(outf, role, samdb):
159 """Transfer standard FSMO role. """
161 domain_dn = samdb.domain_dn()
162 rid_dn = "CN=RID Manager$,CN=System," + domain_dn
163 naming_dn = "CN=Partitions,%s" % samdb.get_config_basedn()
164 infrastructure_dn = "CN=Infrastructure," + domain_dn
165 schema_dn = str(samdb.get_schema_basedn())
166 new_owner = ldb.Dn(samdb, samdb.get_dsServiceName())
168 m.dn = ldb.Dn(samdb, "")
170 master_owner = get_fsmo_roleowner(samdb, rid_dn, role)
171 m["becomeRidMaster"] = ldb.MessageElement(
172 "1", ldb.FLAG_MOD_REPLACE,
175 master_owner = get_fsmo_roleowner(samdb, domain_dn, role)
177 res = samdb.search(domain_dn,
178 scope=ldb.SCOPE_BASE, attrs=["objectSid"])
180 sid = res[0]["objectSid"][0]
181 m["becomePdc"] = ldb.MessageElement(
182 sid, ldb.FLAG_MOD_REPLACE,
184 elif role == "naming":
185 master_owner = get_fsmo_roleowner(samdb, naming_dn, role)
186 m["becomeDomainMaster"] = ldb.MessageElement(
187 "1", ldb.FLAG_MOD_REPLACE,
188 "becomeDomainMaster")
189 elif role == "infrastructure":
190 master_owner = get_fsmo_roleowner(samdb, infrastructure_dn, role)
191 m["becomeInfrastructureMaster"] = ldb.MessageElement(
192 "1", ldb.FLAG_MOD_REPLACE,
193 "becomeInfrastructureMaster")
194 elif role == "schema":
195 master_owner = get_fsmo_roleowner(samdb, schema_dn, role)
196 m["becomeSchemaMaster"] = ldb.MessageElement(
197 "1", ldb.FLAG_MOD_REPLACE,
198 "becomeSchemaMaster")
200 raise CommandError("Invalid FSMO role.")
202 if master_owner is None:
203 outf.write("Cannot transfer, no DC assigned to the %s role. Try 'seize' instead\n" % role)
206 if master_owner != new_owner:
209 except LdbError as e6:
211 raise CommandError("Transfer of '%s' role failed: %s" %
214 outf.write("FSMO transfer of '%s' role successful\n" % role)
217 outf.write("This DC already has the '%s' FSMO role\n" % role)
221 class cmd_fsmo_seize(Command):
222 """Seize the role."""
224 synopsis = "%prog [options]"
226 takes_optiongroups = {
227 "sambaopts": options.SambaOptions,
228 "credopts": options.CredentialsOptions,
229 "versionopts": options.VersionOptions,
233 Option("-H", "--URL", help="LDB URL for database or target server",
234 type=str, metavar="URL", dest="H"),
236 help="Force seizing of role without attempting to transfer.",
237 action="store_true"),
238 Option("--role", type="choice", choices=["rid", "pdc", "infrastructure",
239 "schema", "naming", "domaindns", "forestdns", "all"],
240 help="""The FSMO role to seize or transfer.\n
241 rid=RidAllocationMasterRole\n
242 schema=SchemaMasterRole\n
243 pdc=PdcEmulationMasterRole\n
244 naming=DomainNamingMasterRole\n
245 infrastructure=InfrastructureMasterRole\n
246 domaindns=DomainDnsZonesMasterRole\n
247 forestdns=ForestDnsZonesMasterRole\n
248 all=all of the above\n
249 You must provide an Admin user and password."""),
254 def seize_role(self, role, samdb, force):
255 """Seize standard fsmo role. """
257 serviceName = samdb.get_dsServiceName()
258 domain_dn = samdb.domain_dn()
259 self.infrastructure_dn = "CN=Infrastructure," + domain_dn
260 self.naming_dn = "CN=Partitions,%s" % samdb.get_config_basedn()
261 self.schema_dn = str(samdb.get_schema_basedn())
262 self.rid_dn = "CN=RID Manager$,CN=System," + domain_dn
266 m.dn = ldb.Dn(samdb, self.rid_dn)
268 m.dn = ldb.Dn(samdb, domain_dn)
269 elif role == "naming":
270 m.dn = ldb.Dn(samdb, self.naming_dn)
271 elif role == "infrastructure":
272 m.dn = ldb.Dn(samdb, self.infrastructure_dn)
273 elif role == "schema":
274 m.dn = ldb.Dn(samdb, self.schema_dn)
276 raise CommandError("Invalid FSMO role.")
277 # first try to transfer to avoid problem if the owner is still active
279 master_owner = get_fsmo_roleowner(samdb, m.dn, role)
280 # if there is a different owner
281 if master_owner is not None:
282 # if there is a different owner
283 if master_owner != serviceName:
284 # if --force isn't given, attempt transfer
286 self.message("Attempting transfer...")
288 transfer_role(self.outf, role, samdb)
290 # transfer failed, use the big axe...
292 self.message("Transfer unsuccessful, seizing...")
294 self.message("Transfer successful, not seizing role")
297 self.outf.write("This DC already has the '%s' FSMO role\n" %
303 if force is not None or seize:
304 self.message("Seizing %s FSMO role..." % role)
305 m["fSMORoleOwner"] = ldb.MessageElement(
306 serviceName, ldb.FLAG_MOD_REPLACE,
309 samdb.transaction_start()
313 # We may need to allocate the initial RID Set
314 samdb.create_own_rid_set()
316 except LdbError as e1:
318 if role == "rid" and num == ldb.ERR_ENTRY_ALREADY_EXISTS:
320 # Try again without the RID Set allocation
321 # (normal). We have to manage the transaction as
322 # we do not have nested transactions and creating
323 # a RID set touches multiple objects. :-(
324 samdb.transaction_cancel()
325 samdb.transaction_start()
328 except LdbError as e:
330 samdb.transaction_cancel()
331 raise CommandError("Failed to seize '%s' role: %s" %
335 samdb.transaction_cancel()
336 raise CommandError("Failed to seize '%s' role: %s" %
338 samdb.transaction_commit()
339 self.outf.write("FSMO seize of '%s' role successful\n" % role)
343 def seize_dns_role(self, role, samdb, credopts, sambaopts,
345 """Seize DNS FSMO role. """
347 serviceName = samdb.get_dsServiceName()
348 domain_dn = samdb.domain_dn()
349 forest_dn = samba.dn_from_dns_name(samdb.forest_dns_name())
350 self.domaindns_dn = "CN=Infrastructure,DC=DomainDnsZones," + domain_dn
351 self.forestdns_dn = "CN=Infrastructure,DC=ForestDnsZones," + forest_dn
354 if role == "domaindns":
355 m.dn = ldb.Dn(samdb, self.domaindns_dn)
356 elif role == "forestdns":
357 m.dn = ldb.Dn(samdb, self.forestdns_dn)
359 raise CommandError("Invalid FSMO role.")
360 # first try to transfer to avoid problem if the owner is still active
362 master_owner = get_fsmo_roleowner(samdb, m.dn, role)
363 if master_owner is not None:
364 # if there is a different owner
365 if master_owner != serviceName:
366 # if --force isn't given, attempt transfer
368 self.message("Attempting transfer...")
370 transfer_dns_role(self.outf, sambaopts, credopts, role,
373 # transfer failed, use the big axe...
375 self.message("Transfer unsuccessful, seizing...")
377 self.message("Transfer successful, not seizing role\n")
380 self.outf.write("This DC already has the '%s' FSMO role\n" %
386 if force is not None or seize:
387 self.message("Seizing %s FSMO role..." % role)
388 m["fSMORoleOwner"] = ldb.MessageElement(
389 serviceName, ldb.FLAG_MOD_REPLACE,
393 except LdbError as e2:
395 raise CommandError("Failed to seize '%s' role: %s" %
397 self.outf.write("FSMO seize of '%s' role successful\n" % role)
400 def run(self, force=None, H=None, role=None,
401 credopts=None, sambaopts=None, versionopts=None):
403 lp = sambaopts.get_loadparm()
404 creds = credopts.get_credentials(lp, fallback_machine=True)
406 samdb = SamDB(url=H, session_info=system_session(),
407 credentials=creds, lp=lp)
410 self.seize_role("rid", samdb, force)
411 self.seize_role("pdc", samdb, force)
412 self.seize_role("naming", samdb, force)
413 self.seize_role("infrastructure", samdb, force)
414 self.seize_role("schema", samdb, force)
415 self.seize_dns_role("domaindns", samdb, credopts, sambaopts,
417 self.seize_dns_role("forestdns", samdb, credopts, sambaopts,
420 if role == "domaindns" or role == "forestdns":
421 self.seize_dns_role(role, samdb, credopts, sambaopts,
424 self.seize_role(role, samdb, force)
427 class cmd_fsmo_show(Command):
428 """Show the roles."""
430 synopsis = "%prog [options]"
432 takes_optiongroups = {
433 "sambaopts": options.SambaOptions,
434 "credopts": options.CredentialsOptions,
435 "versionopts": options.VersionOptions,
439 Option("-H", "--URL", help="LDB URL for database or target server",
440 type=str, metavar="URL", dest="H"),
445 def run(self, H=None, credopts=None, sambaopts=None, versionopts=None):
446 lp = sambaopts.get_loadparm()
447 creds = credopts.get_credentials(lp, fallback_machine=True)
449 samdb = SamDB(url=H, session_info=system_session(),
450 credentials=creds, lp=lp)
452 domain_dn = samdb.domain_dn()
453 forest_dn = samba.dn_from_dns_name(samdb.forest_dns_name())
454 infrastructure_dn = "CN=Infrastructure," + domain_dn
455 naming_dn = "CN=Partitions,%s" % samdb.get_config_basedn()
456 schema_dn = samdb.get_schema_basedn()
457 rid_dn = "CN=RID Manager$,CN=System," + domain_dn
458 domaindns_dn = "CN=Infrastructure,DC=DomainDnsZones," + domain_dn
459 forestdns_dn = "CN=Infrastructure,DC=ForestDnsZones," + forest_dn
461 masters = [(schema_dn, "schema", "SchemaMasterRole"),
462 (infrastructure_dn, "infrastructure", "InfrastructureMasterRole"),
463 (rid_dn, "rid", "RidAllocationMasterRole"),
464 (domain_dn, "pdc", "PdcEmulationMasterRole"),
465 (naming_dn, "naming", "DomainNamingMasterRole"),
466 (domaindns_dn, "domaindns", "DomainDnsZonesMasterRole"),
467 (forestdns_dn, "forestdns", "ForestDnsZonesMasterRole"),
470 for master in masters:
471 (dn, short_name, long_name) = master
473 master = get_fsmo_roleowner(samdb, dn, short_name)
474 if master is not None:
475 self.message("%s owner: %s" % (long_name, str(master)))
477 self.message("%s has no current owner" % (long_name))
478 except CommandError as e:
479 self.message("%s: * %s" % (long_name, e.message))
482 class cmd_fsmo_transfer(Command):
483 """Transfer the role."""
485 synopsis = "%prog [options]"
487 takes_optiongroups = {
488 "sambaopts": options.SambaOptions,
489 "credopts": options.CredentialsOptions,
490 "versionopts": options.VersionOptions,
494 Option("-H", "--URL", help="LDB URL for database or target server",
495 type=str, metavar="URL", dest="H"),
496 Option("--role", type="choice", choices=["rid", "pdc", "infrastructure",
497 "schema", "naming", "domaindns", "forestdns", "all"],
498 help="""The FSMO role to seize or transfer.\n
499 rid=RidAllocationMasterRole\n
500 schema=SchemaMasterRole\n
501 pdc=PdcEmulationMasterRole\n
502 naming=DomainNamingMasterRole\n
503 infrastructure=InfrastructureMasterRole\n
504 domaindns=DomainDnsZonesMasterRole\n
505 forestdns=ForestDnsZonesMasterRole\n
506 all=all of the above\n
507 You must provide an Admin user and password."""),
512 def run(self, force=None, H=None, role=None,
513 credopts=None, sambaopts=None, versionopts=None):
515 lp = sambaopts.get_loadparm()
516 creds = credopts.get_credentials(lp, fallback_machine=True)
518 samdb = SamDB(url=H, session_info=system_session(),
519 credentials=creds, lp=lp)
522 transfer_role(self.outf, "rid", samdb)
523 transfer_role(self.outf, "pdc", samdb)
524 transfer_role(self.outf, "naming", samdb)
525 transfer_role(self.outf, "infrastructure", samdb)
526 transfer_role(self.outf, "schema", samdb)
527 transfer_dns_role(self.outf, sambaopts, credopts,
529 transfer_dns_role(self.outf, sambaopts, credopts, "forestdns",
532 if role == "domaindns" or role == "forestdns":
533 transfer_dns_role(self.outf, sambaopts, credopts, role, samdb)
535 transfer_role(self.outf, role, samdb)
538 class cmd_fsmo(SuperCommand):
539 """Flexible Single Master Operations (FSMO) roles management."""
542 subcommands["seize"] = cmd_fsmo_seize()
543 subcommands["show"] = cmd_fsmo_show()
544 subcommands["transfer"] = cmd_fsmo_transfer()