1 # implement samba_tool drs commands
3 # Copyright Andrew Tridgell 2010
4 # Copyright Andrew Bartlett 2017
6 # based on C implementation by Kamen Mazdrashki <kamen.mazdrashki@postpath.com>
8 # This program is free software; you can redistribute it and/or modify
9 # it under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # This program is distributed in the hope that it will be useful,
14 # but WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 import samba.getopt as options
27 from samba.auth import system_session
28 from samba.netcmd import (
34 from samba.samdb import SamDB
35 from samba import drs_utils, nttime2string, dsdb
36 from samba.dcerpc import drsuapi, misc
37 from samba.join import join_clone
38 from samba.ndr import ndr_unpack
39 from samba.dcerpc import drsblobs
40 from samba import colour
44 def drsuapi_connect(ctx):
45 '''make a DRSUAPI connection to the server'''
47 (ctx.drsuapi, ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drsuapi_connect(ctx.server, ctx.lp, ctx.creds)
48 except Exception as e:
49 raise CommandError("DRS connection to %s failed" % ctx.server, e)
52 def samdb_connect(ctx):
53 '''make a ldap connection to the server'''
55 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
56 session_info=system_session(),
57 credentials=ctx.creds, lp=ctx.lp)
58 except Exception as e:
59 raise CommandError("LDAP connection to %s failed" % ctx.server, e)
63 '''return "was successful" or an error string'''
64 (ecode, estring) = werr
66 return "was successful"
67 return "failed, result %u (%s)" % (ecode, estring)
71 def attr_default(msg, attrname, default):
72 '''get an attribute from a ldap msg with a default'''
74 return msg[attrname][0]
79 def drs_parse_ntds_dn(ntds_dn):
80 '''parse a NTDS DN returning a site and server'''
81 a = ntds_dn.split(',')
82 if a[0] != "CN=NTDS Settings" or a[2] != "CN=Servers" or a[4] != 'CN=Sites':
83 raise RuntimeError("bad NTDS DN %s" % ntds_dn)
84 server = a[1].split('=')[1]
85 site = a[3].split('=')[1]
89 DEFAULT_SHOWREPL_FORMAT = 'classic'
92 class cmd_drs_showrepl(Command):
93 """Show replication status."""
95 synopsis = "%prog [<DC>] [options]"
97 takes_optiongroups = {
98 "sambaopts": options.SambaOptions,
99 "versionopts": options.VersionOptions,
100 "credopts": options.CredentialsOptions,
104 Option("--json", help="replication details in JSON format",
105 dest='format', action='store_const', const='json'),
106 Option("--summary", help=("summarize overall DRS health as seen "
108 dest='format', action='store_const', const='summary'),
109 Option("--pull-summary", help=("Have we successfully replicated "
110 "from all relevent servers?"),
111 dest='format', action='store_const', const='pull_summary'),
112 Option("--notify-summary", action='store_const',
113 const='notify_summary', dest='format',
114 help=("Have we successfully notified all relevent servers of "
115 "local changes, and did they say they successfully "
117 Option("--classic", help="print local replication details",
118 dest='format', action='store_const', const='classic',
119 default=DEFAULT_SHOWREPL_FORMAT),
120 Option("-v", "--verbose", help="Be verbose", action="store_true"),
121 Option("--color", help="Use colour output (yes|no|auto)",
127 def parse_neighbour(self, n):
128 """Convert an ldb neighbour object into a python dictionary"""
129 dsa_objectguid = str(n.source_dsa_obj_guid)
131 'NC dn': n.naming_context_dn,
132 "DSA objectGUID": dsa_objectguid,
133 "last attempt time": nttime2string(n.last_attempt),
134 "last attempt message": drs_errmsg(n.result_last_attempt),
135 "consecutive failures": n.consecutive_sync_failures,
136 "last success": nttime2string(n.last_success),
137 "NTDS DN": str(n.source_dsa_obj_dn),
142 self.samdb.search(base="<GUID=%s>" % dsa_objectguid,
143 scope=ldb.SCOPE_BASE,
145 except ldb.LdbError as e:
147 if errno == ldb.ERR_NO_SUCH_OBJECT:
148 d['is deleted'] = True
152 (site, server) = drs_parse_ntds_dn(n.source_dsa_obj_dn)
153 d["DSA"] = "%s\%s" % (site, server)
158 def print_neighbour(self, d):
159 '''print one set of neighbour information'''
160 self.message("%s" % d['NC dn'])
162 self.message("\t%s via RPC" % d['DSA'])
164 self.message("\tNTDS DN: %s" % d['NTDS DN'])
165 self.message("\t\tDSA object GUID: %s" % d['DSA objectGUID'])
166 self.message("\t\tLast attempt @ %s %s" % (d['last attempt time'],
167 d['last attempt message']))
168 self.message("\t\t%u consecutive failure(s)." %
169 d['consecutive failures'])
170 self.message("\t\tLast success @ %s" % d['last success'])
173 def get_neighbours(self, info_type):
174 req1 = drsuapi.DsReplicaGetInfoRequest1()
175 req1.info_type = info_type
177 (info_type, info) = self.drsuapi.DsReplicaGetInfo(
178 self.drsuapi_handle, 1, req1)
179 except Exception as e:
180 raise CommandError("DsReplicaGetInfo of type %u failed" % info_type, e)
182 reps = [self.parse_neighbour(n) for n in info.array]
185 def run(self, DC=None, sambaopts=None,
186 credopts=None, versionopts=None,
187 format=DEFAULT_SHOWREPL_FORMAT,
188 verbose=False, color='no'):
189 self.apply_colour_choice(color)
190 self.lp = sambaopts.get_loadparm()
192 DC = common.netcmd_dnsname(self.lp)
194 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
195 self.verbose = verbose
198 'summary': self.summary_output,
199 'notify_summary': self.notify_summary_output,
200 'pull_summary': self.pull_summary_output,
201 'json': self.json_output,
202 'classic': self.classic_output,
204 if output_function is None:
205 raise CommandError("unknown showrepl format %s" % format)
207 return output_function()
209 def json_output(self):
210 data = self.get_local_repl_data()
213 json.dump(data, self.outf, indent=2)
215 def summary_output_handler(self, typeof_output):
216 """Print a short message if every seems fine, but print details of any
217 links that seem broken."""
219 failing_repsfrom = []
221 local_data = self.get_local_repl_data()
223 if typeof_output != "pull_summary":
224 for rep in local_data['repsTo']:
225 if rep['is deleted']:
227 if rep["consecutive failures"] != 0 or rep["last success"] == 0:
228 failing_repsto.append(rep)
230 if typeof_output != "notify_summary":
231 for rep in local_data['repsFrom']:
232 if rep['is deleted']:
234 if rep["consecutive failures"] != 0 or rep["last success"] == 0:
235 failing_repsfrom.append(rep)
237 if failing_repsto or failing_repsfrom:
238 self.message(colour.c_RED("There are failing connections"))
240 self.message(colour.c_RED("Failing outbound connections:"))
241 for rep in failing_repsto:
242 self.print_neighbour(rep)
244 self.message(colour.c_RED("Failing inbound connection:"))
245 for rep in failing_repsfrom:
246 self.print_neighbour(rep)
250 self.message(colour.c_GREEN("[ALL GOOD]"))
253 def summary_output(self):
254 return self.summary_output_handler("summary")
256 def notify_summary_output(self):
257 return self.summary_output_handler("notify_summary")
259 def pull_summary_output(self):
260 return self.summary_output_handler("pull_summary")
262 def get_local_repl_data(self):
263 drsuapi_connect(self)
266 # show domain information
267 ntds_dn = self.samdb.get_dsServiceName()
269 (site, server) = drs_parse_ntds_dn(ntds_dn)
271 ntds = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=['options', 'objectGUID', 'invocationId'])
272 except Exception as e:
273 raise CommandError("Failed to search NTDS DN %s" % ntds_dn)
276 "options": int(attr_default(ntds[0], "options", 0)),
277 "objectGUID": self.samdb.schema_format_value(
278 "objectGUID", ntds[0]["objectGUID"][0]),
279 "invocationId": self.samdb.schema_format_value(
280 "objectGUID", ntds[0]["invocationId"][0])
283 conn = self.samdb.search(base=ntds_dn, expression="(objectClass=nTDSConnection)")
284 repsfrom = self.get_neighbours(drsuapi.DRSUAPI_DS_REPLICA_INFO_NEIGHBORS)
285 repsto = self.get_neighbours(drsuapi.DRSUAPI_DS_REPLICA_INFO_REPSTO)
289 c_rdn, sep, c_server_dn = c['fromServer'][0].partition(',')
291 'name': str(c['name']),
292 'remote DN': c['fromServer'][0],
293 'options': int(attr_default(c, 'options', 0)),
294 'enabled': (attr_default(c, 'enabledConnection',
295 'TRUE').upper() == 'TRUE')
298 conn_details.append(d)
300 c_server_res = self.samdb.search(base=c_server_dn,
301 scope=ldb.SCOPE_BASE,
302 attrs=["dnsHostName"])
303 d['dns name'] = c_server_res[0]["dnsHostName"][0]
304 except ldb.LdbError as e:
306 if errno == ldb.ERR_NO_SUCH_OBJECT:
307 d['is deleted'] = True
311 d['replicates NC'] = []
312 for r in c.get('mS-DS-ReplicatesNCReason', []):
313 a = str(r).split(':')
314 d['replicates NC'].append((a[3], int(a[2])))
318 'repsFrom': repsfrom,
320 'NTDSConnections': conn_details,
325 def classic_output(self):
326 data = self.get_local_repl_data()
327 dsa_details = data['dsa']
328 repsfrom = data['repsFrom']
329 repsto = data['repsTo']
330 conn_details = data['NTDSConnections']
332 server = data['server']
334 self.message("%s\\%s" % (site, server))
335 self.message("DSA Options: 0x%08x" % dsa_details["options"])
336 self.message("DSA object GUID: %s" % dsa_details["objectGUID"])
337 self.message("DSA invocationId: %s\n" % dsa_details["invocationId"])
339 self.message("==== INBOUND NEIGHBORS ====\n")
341 self.print_neighbour(n)
343 self.message("==== OUTBOUND NEIGHBORS ====\n")
345 self.print_neighbour(n)
347 reasons = ['NTDSCONN_KCC_GC_TOPOLOGY',
348 'NTDSCONN_KCC_RING_TOPOLOGY',
349 'NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY',
350 'NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY',
351 'NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY',
352 'NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY',
353 'NTDSCONN_KCC_INTERSITE_TOPOLOGY',
354 'NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY',
355 'NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY',
356 'NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY']
358 self.message("==== KCC CONNECTION OBJECTS ====\n")
359 for d in conn_details:
360 self.message("Connection --")
361 if d.get('is deleted'):
362 self.message("\tWARNING: Connection to DELETED server!")
364 self.message("\tConnection name: %s" % d['name'])
365 self.message("\tEnabled : %s" % str(d['enabled']).upper())
366 self.message("\tServer DNS name : %s" % d['dns name'])
367 self.message("\tServer DN name : %s" % d['remote DN'])
368 self.message("\t\tTransportType: RPC")
369 self.message("\t\toptions: 0x%08X" % d['options'])
371 if d['replicates NC']:
372 for nc, reason in d['replicates NC']:
373 self.message("\t\tReplicatesNC: %s" % nc)
374 self.message("\t\tReason: 0x%08x" % reason)
376 if getattr(dsdb, s, 0) & reason:
377 self.message("\t\t\t%s" % s)
379 self.message("Warning: No NC replicated for Connection!")
382 class cmd_drs_kcc(Command):
383 """Trigger knowledge consistency center run."""
385 synopsis = "%prog [<DC>] [options]"
387 takes_optiongroups = {
388 "sambaopts": options.SambaOptions,
389 "versionopts": options.VersionOptions,
390 "credopts": options.CredentialsOptions,
395 def run(self, DC=None, sambaopts=None,
396 credopts=None, versionopts=None):
398 self.lp = sambaopts.get_loadparm()
400 DC = common.netcmd_dnsname(self.lp)
403 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
405 drsuapi_connect(self)
407 req1 = drsuapi.DsExecuteKCC1()
409 self.drsuapi.DsExecuteKCC(self.drsuapi_handle, 1, req1)
410 except Exception as e:
411 raise CommandError("DsExecuteKCC failed", e)
412 self.message("Consistency check on %s successful." % DC)
415 class cmd_drs_replicate(Command):
416 """Replicate a naming context between two DCs."""
418 synopsis = "%prog <destinationDC> <sourceDC> <NC> [options]"
420 takes_optiongroups = {
421 "sambaopts": options.SambaOptions,
422 "versionopts": options.VersionOptions,
423 "credopts": options.CredentialsOptions,
426 takes_args = ["DEST_DC", "SOURCE_DC", "NC"]
429 Option("--add-ref", help="use ADD_REF to add to repsTo on source", action="store_true"),
430 Option("--sync-forced", help="use SYNC_FORCED to force inbound replication", action="store_true"),
431 Option("--sync-all", help="use SYNC_ALL to replicate from all DCs", action="store_true"),
432 Option("--full-sync", help="resync all objects", action="store_true"),
433 Option("--local", help="pull changes directly into the local database (destination DC is ignored)", action="store_true"),
434 Option("--local-online", help="pull changes into the local database (destination DC is ignored) as a normal online replication", action="store_true"),
435 Option("--async-op", help="use ASYNC_OP for the replication", action="store_true"),
436 Option("--single-object", help="Replicate only the object specified, instead of the whole Naming Context (only with --local)", action="store_true"),
439 def drs_local_replicate(self, SOURCE_DC, NC, full_sync=False,
442 '''replicate from a source DC to the local SAM'''
444 self.server = SOURCE_DC
445 drsuapi_connect(self)
447 self.local_samdb = SamDB(session_info=system_session(), url=None,
448 credentials=self.creds, lp=self.lp)
450 self.samdb = SamDB(url="ldap://%s" % self.server,
451 session_info=system_session(),
452 credentials=self.creds, lp=self.lp)
454 # work out the source and destination GUIDs
455 res = self.local_samdb.search(base="", scope=ldb.SCOPE_BASE,
456 attrs=["dsServiceName"])
457 self.ntds_dn = res[0]["dsServiceName"][0]
459 res = self.local_samdb.search(base=self.ntds_dn, scope=ldb.SCOPE_BASE,
460 attrs=["objectGUID"])
461 self.ntds_guid = misc.GUID(
462 self.samdb.schema_format_value("objectGUID",
463 res[0]["objectGUID"][0]))
465 source_dsa_invocation_id = misc.GUID(self.samdb.get_invocation_id())
466 dest_dsa_invocation_id = misc.GUID(self.local_samdb.get_invocation_id())
467 destination_dsa_guid = self.ntds_guid
469 exop = drsuapi.DRSUAPI_EXOP_NONE
472 exop = drsuapi.DRSUAPI_EXOP_REPL_OBJ
475 self.samdb.transaction_start()
476 repl = drs_utils.drs_Replicate("ncacn_ip_tcp:%s[seal]" % self.server,
478 self.creds, self.local_samdb,
479 dest_dsa_invocation_id)
481 # Work out if we are an RODC, so that a forced local replicate
482 # with the admin pw does not sync passwords
483 rodc = self.local_samdb.am_rodc()
485 (num_objects, num_links) = repl.replicate(NC,
486 source_dsa_invocation_id,
487 destination_dsa_guid,
491 sync_forced=sync_forced)
492 except Exception as e:
493 raise CommandError("Error replicating DN %s" % NC, e)
494 self.samdb.transaction_commit()
497 self.message("Full Replication of all %d objects and %d links "
498 "from %s to %s was successful." %
499 (num_objects, num_links, SOURCE_DC,
500 self.local_samdb.url))
502 self.message("Incremental replication of %d objects and %d links "
503 "from %s to %s was successful." %
504 (num_objects, num_links, SOURCE_DC,
505 self.local_samdb.url))
507 def run(self, DEST_DC, SOURCE_DC, NC,
508 add_ref=False, sync_forced=False, sync_all=False, full_sync=False,
509 local=False, local_online=False, async_op=False, single_object=False,
510 sambaopts=None, credopts=None, versionopts=None):
512 self.server = DEST_DC
513 self.lp = sambaopts.get_loadparm()
515 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
518 self.drs_local_replicate(SOURCE_DC, NC, full_sync=full_sync,
519 single_object=single_object,
520 sync_forced=sync_forced)
524 server_bind = drsuapi.drsuapi("irpc:dreplsrv", lp_ctx=self.lp)
525 server_bind_handle = misc.policy_handle()
527 drsuapi_connect(self)
528 server_bind = self.drsuapi
529 server_bind_handle = self.drsuapi_handle
532 # Give the sync replication 5 minutes time
533 server_bind.request_timeout = 5 * 60
537 # we need to find the NTDS GUID of the source DC
538 msg = self.samdb.search(base=self.samdb.get_config_basedn(),
539 expression="(&(objectCategory=server)(|(name=%s)(dNSHostName=%s)))" % (
540 ldb.binary_encode(SOURCE_DC),
541 ldb.binary_encode(SOURCE_DC)),
544 raise CommandError("Failed to find source DC %s" % SOURCE_DC)
545 server_dn = msg[0]['dn']
547 msg = self.samdb.search(base=server_dn, scope=ldb.SCOPE_ONELEVEL,
548 expression="(|(objectCategory=nTDSDSA)(objectCategory=nTDSDSARO))",
549 attrs=['objectGUID', 'options'])
551 raise CommandError("Failed to find source NTDS DN %s" % SOURCE_DC)
552 source_dsa_guid = msg[0]['objectGUID'][0]
553 dsa_options = int(attr_default(msg, 'options', 0))
557 if not (dsa_options & dsdb.DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL):
558 req_options |= drsuapi.DRSUAPI_DRS_WRIT_REP
560 req_options |= drsuapi.DRSUAPI_DRS_ADD_REF
562 req_options |= drsuapi.DRSUAPI_DRS_SYNC_FORCED
564 req_options |= drsuapi.DRSUAPI_DRS_SYNC_ALL
566 req_options |= drsuapi.DRSUAPI_DRS_FULL_SYNC_NOW
568 req_options |= drsuapi.DRSUAPI_DRS_ASYNC_OP
571 drs_utils.sendDsReplicaSync(server_bind, server_bind_handle, source_dsa_guid, NC, req_options)
572 except drs_utils.drsException as estr:
573 raise CommandError("DsReplicaSync failed", estr)
575 self.message("Replicate from %s to %s was started." % (SOURCE_DC, DEST_DC))
577 self.message("Replicate from %s to %s was successful." % (SOURCE_DC, DEST_DC))
581 class cmd_drs_bind(Command):
582 """Show DRS capabilities of a server."""
584 synopsis = "%prog [<DC>] [options]"
586 takes_optiongroups = {
587 "sambaopts": options.SambaOptions,
588 "versionopts": options.VersionOptions,
589 "credopts": options.CredentialsOptions,
594 def run(self, DC=None, sambaopts=None,
595 credopts=None, versionopts=None):
597 self.lp = sambaopts.get_loadparm()
599 DC = common.netcmd_dnsname(self.lp)
601 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
603 drsuapi_connect(self)
605 bind_info = drsuapi.DsBindInfoCtr()
606 bind_info.length = 28
607 bind_info.info = drsuapi.DsBindInfo28()
608 (info, handle) = self.drsuapi.DsBind(misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID), bind_info)
611 ("DRSUAPI_SUPPORTED_EXTENSION_BASE", "DRS_EXT_BASE"),
612 ("DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION", "DRS_EXT_ASYNCREPL"),
613 ("DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI", "DRS_EXT_REMOVEAPI"),
614 ("DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2", "DRS_EXT_MOVEREQ_V2"),
615 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS", "DRS_EXT_GETCHG_DEFLATE"),
616 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1", "DRS_EXT_DCINFO_V1"),
617 ("DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION", "DRS_EXT_RESTORE_USN_OPTIMIZATION"),
618 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY", "DRS_EXT_ADDENTRY"),
619 ("DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE", "DRS_EXT_KCC_EXECUTE"),
620 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2", "DRS_EXT_ADDENTRY_V2"),
621 ("DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION", "DRS_EXT_LINKED_VALUE_REPLICATION"),
622 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2", "DRS_EXT_DCINFO_V2"),
623 ("DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD", "DRS_EXT_INSTANCE_TYPE_NOT_REQ_ON_MOD"),
624 ("DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND", "DRS_EXT_CRYPTO_BIND"),
625 ("DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO", "DRS_EXT_GET_REPL_INFO"),
626 ("DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION", "DRS_EXT_STRONG_ENCRYPTION"),
627 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01", "DRS_EXT_DCINFO_VFFFFFFFF"),
628 ("DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP", "DRS_EXT_TRANSITIVE_MEMBERSHIP"),
629 ("DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY", "DRS_EXT_ADD_SID_HISTORY"),
630 ("DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3", "DRS_EXT_POST_BETA3"),
631 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V5", "DRS_EXT_GETCHGREQ_V5"),
632 ("DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2", "DRS_EXT_GETMEMBERSHIPS2"),
633 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6", "DRS_EXT_GETCHGREQ_V6"),
634 ("DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS", "DRS_EXT_NONDOMAIN_NCS"),
635 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8", "DRS_EXT_GETCHGREQ_V8"),
636 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5", "DRS_EXT_GETCHGREPLY_V5"),
637 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6", "DRS_EXT_GETCHGREPLY_V6"),
638 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3", "DRS_EXT_WHISTLER_BETA3"),
639 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7", "DRS_EXT_WHISTLER_BETA3"),
640 ("DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT", "DRS_EXT_WHISTLER_BETA3"),
641 ("DRSUAPI_SUPPORTED_EXTENSION_XPRESS_COMPRESS", "DRS_EXT_W2K3_DEFLATE"),
642 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10", "DRS_EXT_GETCHGREQ_V10"),
643 ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART2", "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART2"),
644 ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART3", "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART3")
648 ("DRSUAPI_SUPPORTED_EXTENSION_ADAM", "DRS_EXT_ADAM"),
649 ("DRSUAPI_SUPPORTED_EXTENSION_LH_BETA2", "DRS_EXT_LH_BETA2"),
650 ("DRSUAPI_SUPPORTED_EXTENSION_RECYCLE_BIN", "DRS_EXT_RECYCLE_BIN")]
652 self.message("Bind to %s succeeded." % DC)
653 self.message("Extensions supported:")
654 for (opt, str) in optmap:
655 optval = getattr(drsuapi, opt, 0)
656 if info.info.supported_extensions & optval:
660 self.message(" %-60s: %s (%s)" % (opt, yesno, str))
662 if isinstance(info.info, drsuapi.DsBindInfo48):
663 self.message("\nExtended Extensions supported:")
664 for (opt, str) in optmap_ext:
665 optval = getattr(drsuapi, opt, 0)
666 if info.info.supported_extensions_ext & optval:
670 self.message(" %-60s: %s (%s)" % (opt, yesno, str))
672 self.message("\nSite GUID: %s" % info.info.site_guid)
673 self.message("Repl epoch: %u" % info.info.repl_epoch)
674 if isinstance(info.info, drsuapi.DsBindInfo48):
675 self.message("Forest GUID: %s" % info.info.config_dn_guid)
679 class cmd_drs_options(Command):
680 """Query or change 'options' for NTDS Settings object of a Domain Controller."""
682 synopsis = "%prog [<DC>] [options]"
684 takes_optiongroups = {
685 "sambaopts": options.SambaOptions,
686 "versionopts": options.VersionOptions,
687 "credopts": options.CredentialsOptions,
693 Option("--dsa-option", help="DSA option to enable/disable", type="str",
694 metavar="{+|-}IS_GC | {+|-}DISABLE_INBOUND_REPL | {+|-}DISABLE_OUTBOUND_REPL | {+|-}DISABLE_NTDSCONN_XLATE"),
697 option_map = {"IS_GC": 0x00000001,
698 "DISABLE_INBOUND_REPL": 0x00000002,
699 "DISABLE_OUTBOUND_REPL": 0x00000004,
700 "DISABLE_NTDSCONN_XLATE": 0x00000008}
702 def run(self, DC=None, dsa_option=None,
703 sambaopts=None, credopts=None, versionopts=None):
705 self.lp = sambaopts.get_loadparm()
707 DC = common.netcmd_dnsname(self.lp)
709 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
713 ntds_dn = self.samdb.get_dsServiceName()
714 res = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=["options"])
715 dsa_opts = int(res[0]["options"][0])
717 # print out current DSA options
718 cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts]
719 self.message("Current DSA options: " + ", ".join(cur_opts))
723 if dsa_option[:1] not in ("+", "-"):
724 raise CommandError("Unknown option %s" % dsa_option)
725 flag = dsa_option[1:]
726 if flag not in self.option_map.keys():
727 raise CommandError("Unknown option %s" % dsa_option)
728 if dsa_option[:1] == "+":
729 dsa_opts |= self.option_map[flag]
731 dsa_opts &= ~self.option_map[flag]
734 m.dn = ldb.Dn(self.samdb, ntds_dn)
735 m["options"] = ldb.MessageElement(str(dsa_opts), ldb.FLAG_MOD_REPLACE, "options")
737 # print out new DSA options
738 cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts]
739 self.message("New DSA options: " + ", ".join(cur_opts))
742 class cmd_drs_clone_dc_database(Command):
743 """Replicate an initial clone of domain, but DO NOT JOIN it."""
745 synopsis = "%prog <dnsdomain> [options]"
747 takes_optiongroups = {
748 "sambaopts": options.SambaOptions,
749 "versionopts": options.VersionOptions,
750 "credopts": options.CredentialsOptions,
754 Option("--server", help="DC to join", type=str),
755 Option("--targetdir", help="where to store provision (required)", type=str),
756 Option("-q", "--quiet", help="Be quiet", action="store_true"),
757 Option("--include-secrets", help="Also replicate secret values", action="store_true"),
758 Option("-v", "--verbose", help="Be verbose", action="store_true")
761 takes_args = ["domain"]
763 def run(self, domain, sambaopts=None, credopts=None,
764 versionopts=None, server=None, targetdir=None,
765 quiet=False, verbose=False, include_secrets=False):
766 lp = sambaopts.get_loadparm()
767 creds = credopts.get_credentials(lp)
769 logger = self.get_logger()
771 logger.setLevel(logging.DEBUG)
773 logger.setLevel(logging.WARNING)
775 logger.setLevel(logging.INFO)
777 if targetdir is None:
778 raise CommandError("--targetdir option must be specified")
780 join_clone(logger=logger, server=server, creds=creds, lp=lp,
781 domain=domain, dns_backend='SAMBA_INTERNAL',
782 targetdir=targetdir, include_secrets=include_secrets)
785 class cmd_drs(SuperCommand):
786 """Directory Replication Services (DRS) management."""
789 subcommands["bind"] = cmd_drs_bind()
790 subcommands["kcc"] = cmd_drs_kcc()
791 subcommands["replicate"] = cmd_drs_replicate()
792 subcommands["showrepl"] = cmd_drs_showrepl()
793 subcommands["options"] = cmd_drs_options()
794 subcommands["clone-dc-database"] = cmd_drs_clone_dc_database()