smbd: improve reinit_after_fork error handling
[Samba.git] / python / samba / netcmd / drs.py
blobc5a9f48ad5e67d6756831106da2952a78e535d83
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/>.
22 import samba.getopt as options
23 import ldb
24 import logging
25 from . import common
26 import json
28 from samba.auth import system_session
29 from samba.netcmd import (
30 Command,
31 CommandError,
32 Option,
33 SuperCommand,
35 from samba.netcmd.common import attr_default
36 from samba.samdb import SamDB
37 from samba import drs_utils, nttime2string, dsdb
38 from samba.dcerpc import drsuapi, misc
39 from samba.join import join_clone
40 from samba import colour
42 from samba.uptodateness import (
43 get_partition_maps,
44 get_utdv_edges,
45 get_utdv_distances,
46 get_utdv_summary,
47 get_kcc_and_dsas,
49 from samba.common import get_string
50 from samba.samdb import get_default_backend_store
52 def drsuapi_connect(ctx):
53 """make a DRSUAPI connection to the server"""
54 try:
55 (ctx.drsuapi, ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drsuapi_connect(ctx.server, ctx.lp, ctx.creds)
56 except Exception as e:
57 raise CommandError("DRS connection to %s failed" % ctx.server, e)
60 def samdb_connect(ctx):
61 """make a ldap connection to the server"""
62 try:
63 ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
64 session_info=system_session(),
65 credentials=ctx.creds, lp=ctx.lp)
66 except Exception as e:
67 raise CommandError("LDAP connection to %s failed" % ctx.server, e)
70 def drs_errmsg(werr):
71 """return "was successful" or an error string"""
72 (ecode, estring) = werr
73 if ecode == 0:
74 return "was successful"
75 return "failed, result %u (%s)" % (ecode, estring)
78 def drs_parse_ntds_dn(ntds_dn):
79 """parse a NTDS DN returning a site and server"""
80 a = ntds_dn.split(',')
81 if a[0] != "CN=NTDS Settings" or a[2] != "CN=Servers" or a[4] != 'CN=Sites':
82 raise RuntimeError("bad NTDS DN %s" % ntds_dn)
83 server = a[1].split('=')[1]
84 site = a[3].split('=')[1]
85 return (site, server)
88 DEFAULT_SHOWREPL_FORMAT = 'classic'
91 class cmd_drs_showrepl(Command):
92 """Show replication status."""
94 synopsis = "%prog [<DC>] [options]"
96 takes_optiongroups = {
97 "sambaopts": options.SambaOptions,
98 "versionopts": options.VersionOptions,
99 "credopts": options.CredentialsOptions,
102 takes_options = [
103 Option("--json", help="replication details in JSON format",
104 dest='format', action='store_const', const='json'),
105 Option("--summary", help=("summarize overall DRS health as seen "
106 "from this server"),
107 dest='format', action='store_const', const='summary'),
108 Option("--pull-summary", help=("Have we successfully replicated "
109 "from all relevant servers?"),
110 dest='format', action='store_const', const='pull_summary'),
111 Option("--notify-summary", action='store_const',
112 const='notify_summary', dest='format',
113 help=("Have we successfully notified all relevant servers of "
114 "local changes, and did they say they successfully "
115 "replicated?")),
116 Option("--classic", help="print local replication details",
117 dest='format', action='store_const', const='classic',
118 default=DEFAULT_SHOWREPL_FORMAT),
119 Option("-v", "--verbose", help="Be verbose", action="store_true"),
122 takes_args = ["DC?"]
124 def parse_neighbour(self, n):
125 """Convert an ldb neighbour object into a python dictionary"""
126 dsa_objectguid = str(n.source_dsa_obj_guid)
127 d = {
128 'NC dn': n.naming_context_dn,
129 "DSA objectGUID": dsa_objectguid,
130 "last attempt time": nttime2string(n.last_attempt),
131 "last attempt message": drs_errmsg(n.result_last_attempt),
132 "consecutive failures": n.consecutive_sync_failures,
133 "last success": nttime2string(n.last_success),
134 "NTDS DN": str(n.source_dsa_obj_dn),
135 'is deleted': False
138 try:
139 self.samdb.search(base="<GUID=%s>" % dsa_objectguid,
140 scope=ldb.SCOPE_BASE,
141 attrs=[])
142 except ldb.LdbError as e:
143 (errno, _) = e.args
144 if errno == ldb.ERR_NO_SUCH_OBJECT:
145 d['is deleted'] = True
146 else:
147 raise
148 try:
149 (site, server) = drs_parse_ntds_dn(n.source_dsa_obj_dn)
150 d["DSA"] = "%s\\%s" % (site, server)
151 except RuntimeError:
152 pass
153 return d
155 def print_neighbour(self, d):
156 """print one set of neighbour information"""
157 self.message("%s" % d['NC dn'])
158 if 'DSA' in d:
159 self.message("\t%s via RPC" % d['DSA'])
160 else:
161 self.message("\tNTDS DN: %s" % d['NTDS DN'])
162 self.message("\t\tDSA object GUID: %s" % d['DSA objectGUID'])
163 self.message("\t\tLast attempt @ %s %s" % (d['last attempt time'],
164 d['last attempt message']))
165 self.message("\t\t%u consecutive failure(s)." %
166 d['consecutive failures'])
167 self.message("\t\tLast success @ %s" % d['last success'])
168 self.message("")
170 def get_neighbours(self, info_type):
171 req1 = drsuapi.DsReplicaGetInfoRequest1()
172 req1.info_type = info_type
173 try:
174 (info_type, info) = self.drsuapi.DsReplicaGetInfo(
175 self.drsuapi_handle, 1, req1)
176 except Exception as e:
177 raise CommandError("DsReplicaGetInfo of type %u failed" % info_type, e)
179 reps = [self.parse_neighbour(n) for n in info.array]
180 return reps
182 def run(self, DC=None, sambaopts=None,
183 credopts=None, versionopts=None,
184 format=DEFAULT_SHOWREPL_FORMAT,
185 verbose=False):
186 self.lp = sambaopts.get_loadparm()
187 if DC is None:
188 DC = common.netcmd_dnsname(self.lp)
189 self.server = DC
190 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
191 self.verbose = verbose
193 output_function = {
194 'summary': self.summary_output,
195 'notify_summary': self.notify_summary_output,
196 'pull_summary': self.pull_summary_output,
197 'json': self.json_output,
198 'classic': self.classic_output,
199 }.get(format)
200 if output_function is None:
201 raise CommandError("unknown showrepl format %s" % format)
203 return output_function()
205 def json_output(self):
206 data = self.get_local_repl_data()
207 del data['site']
208 del data['server']
209 json.dump(data, self.outf, indent=2)
211 def summary_output_handler(self, typeof_output):
212 """Print a short message if every seems fine, but print details of any
213 links that seem broken."""
214 failing_repsto = []
215 failing_repsfrom = []
217 local_data = self.get_local_repl_data()
219 if typeof_output != "pull_summary":
220 for rep in local_data['repsTo']:
221 if rep['is deleted']:
222 continue
223 if rep["consecutive failures"] != 0 or rep["last success"] == 0:
224 failing_repsto.append(rep)
226 if typeof_output != "notify_summary":
227 for rep in local_data['repsFrom']:
228 if rep['is deleted']:
229 continue
230 if rep["consecutive failures"] != 0 or rep["last success"] == 0:
231 failing_repsfrom.append(rep)
233 if failing_repsto or failing_repsfrom:
234 self.message(colour.c_RED("There are failing connections"))
235 if failing_repsto:
236 self.message(colour.c_RED("Failing outbound connections:"))
237 for rep in failing_repsto:
238 self.print_neighbour(rep)
239 if failing_repsfrom:
240 self.message(colour.c_RED("Failing inbound connection:"))
241 for rep in failing_repsfrom:
242 self.print_neighbour(rep)
244 return 1
246 self.message(colour.c_GREEN("[ALL GOOD]"))
248 def summary_output(self):
249 return self.summary_output_handler("summary")
251 def notify_summary_output(self):
252 return self.summary_output_handler("notify_summary")
254 def pull_summary_output(self):
255 return self.summary_output_handler("pull_summary")
257 def get_local_repl_data(self):
258 drsuapi_connect(self)
259 samdb_connect(self)
261 # show domain information
262 ntds_dn = self.samdb.get_dsServiceName()
264 (site, server) = drs_parse_ntds_dn(ntds_dn)
265 try:
266 ntds = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=['options', 'objectGUID', 'invocationId'])
267 except Exception as e:
268 raise CommandError("Failed to search NTDS DN %s" % ntds_dn)
270 dsa_details = {
271 "options": int(attr_default(ntds[0], "options", 0)),
272 "objectGUID": get_string(self.samdb.schema_format_value(
273 "objectGUID", ntds[0]["objectGUID"][0])),
274 "invocationId": get_string(self.samdb.schema_format_value(
275 "objectGUID", ntds[0]["invocationId"][0]))
278 conn = self.samdb.search(base=ntds_dn, expression="(objectClass=nTDSConnection)")
279 repsfrom = self.get_neighbours(drsuapi.DRSUAPI_DS_REPLICA_INFO_NEIGHBORS)
280 repsto = self.get_neighbours(drsuapi.DRSUAPI_DS_REPLICA_INFO_REPSTO)
282 conn_details = []
283 for c in conn:
284 c_rdn, sep, c_server_dn = str(c['fromServer'][0]).partition(',')
285 d = {
286 'name': str(c['name']),
287 'remote DN': str(c['fromServer'][0]),
288 'options': int(attr_default(c, 'options', 0)),
289 'enabled': (get_string(attr_default(c, 'enabledConnection',
290 'TRUE')).upper() == 'TRUE')
293 conn_details.append(d)
294 try:
295 c_server_res = self.samdb.search(base=c_server_dn,
296 scope=ldb.SCOPE_BASE,
297 attrs=["dnsHostName"])
298 d['dns name'] = str(c_server_res[0]["dnsHostName"][0])
299 except ldb.LdbError as e:
300 (errno, _) = e.args
301 if errno == ldb.ERR_NO_SUCH_OBJECT:
302 d['is deleted'] = True
303 except (KeyError, IndexError):
304 pass
306 d['replicates NC'] = []
307 for r in c.get('mS-DS-ReplicatesNCReason', []):
308 a = str(r).split(':')
309 d['replicates NC'].append((a[3], int(a[2])))
311 return {
312 'dsa': dsa_details,
313 'repsFrom': repsfrom,
314 'repsTo': repsto,
315 'NTDSConnections': conn_details,
316 'site': site,
317 'server': server
320 def classic_output(self):
321 data = self.get_local_repl_data()
322 dsa_details = data['dsa']
323 repsfrom = data['repsFrom']
324 repsto = data['repsTo']
325 conn_details = data['NTDSConnections']
326 site = data['site']
327 server = data['server']
329 self.message("%s\\%s" % (site, server))
330 self.message("DSA Options: 0x%08x" % dsa_details["options"])
331 self.message("DSA object GUID: %s" % dsa_details["objectGUID"])
332 self.message("DSA invocationId: %s\n" % dsa_details["invocationId"])
334 self.message("==== INBOUND NEIGHBORS ====\n")
335 for n in repsfrom:
336 self.print_neighbour(n)
338 self.message("==== OUTBOUND NEIGHBORS ====\n")
339 for n in repsto:
340 self.print_neighbour(n)
342 reasons = ['NTDSCONN_KCC_GC_TOPOLOGY',
343 'NTDSCONN_KCC_RING_TOPOLOGY',
344 'NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY',
345 'NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY',
346 'NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY',
347 'NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY',
348 'NTDSCONN_KCC_INTERSITE_TOPOLOGY',
349 'NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY',
350 'NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY',
351 'NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY']
353 self.message("==== KCC CONNECTION OBJECTS ====\n")
354 for d in conn_details:
355 self.message("Connection --")
356 if d.get('is deleted'):
357 self.message("\tWARNING: Connection to DELETED server!")
359 self.message("\tConnection name: %s" % d['name'])
360 self.message("\tEnabled : %s" % str(d['enabled']).upper())
361 self.message("\tServer DNS name : %s" % d.get('dns name'))
362 self.message("\tServer DN name : %s" % d['remote DN'])
363 self.message("\t\tTransportType: RPC")
364 self.message("\t\toptions: 0x%08X" % d['options'])
366 if d['replicates NC']:
367 for nc, reason in d['replicates NC']:
368 self.message("\t\tReplicatesNC: %s" % nc)
369 self.message("\t\tReason: 0x%08x" % reason)
370 for s in reasons:
371 if getattr(dsdb, s, 0) & reason:
372 self.message("\t\t\t%s" % s)
373 else:
374 self.message("Warning: No NC replicated for Connection!")
377 class cmd_drs_kcc(Command):
378 """Trigger knowledge consistency center run."""
380 synopsis = "%prog [<DC>] [options]"
382 takes_optiongroups = {
383 "sambaopts": options.SambaOptions,
384 "versionopts": options.VersionOptions,
385 "credopts": options.CredentialsOptions,
388 takes_args = ["DC?"]
390 def run(self, DC=None, sambaopts=None,
391 credopts=None, versionopts=None):
393 self.lp = sambaopts.get_loadparm()
394 if DC is None:
395 DC = common.netcmd_dnsname(self.lp)
396 self.server = DC
398 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
400 drsuapi_connect(self)
402 req1 = drsuapi.DsExecuteKCC1()
403 try:
404 self.drsuapi.DsExecuteKCC(self.drsuapi_handle, 1, req1)
405 except Exception as e:
406 raise CommandError("DsExecuteKCC failed", e)
407 self.message("Consistency check on %s successful." % DC)
410 class cmd_drs_replicate(Command):
411 """Replicate a naming context between two DCs."""
413 synopsis = "%prog <destinationDC> <sourceDC> <NC> [options]"
415 takes_optiongroups = {
416 "sambaopts": options.SambaOptions,
417 "versionopts": options.VersionOptions,
418 "credopts": options.CredentialsOptions,
421 takes_args = ["DEST_DC", "SOURCE_DC", "NC"]
423 takes_options = [
424 Option("--add-ref", help="use ADD_REF to add to repsTo on source", action="store_true"),
425 Option("--sync-forced", help="use SYNC_FORCED to force inbound replication", action="store_true"),
426 Option("--sync-all", help="use SYNC_ALL to replicate from all DCs", action="store_true"),
427 Option("--full-sync", help="resync all objects", action="store_true"),
428 Option("--local", help="pull changes directly into the local database (destination DC is ignored)", action="store_true"),
429 Option("--local-online", help="pull changes into the local database (destination DC is ignored) as a normal online replication", action="store_true"),
430 Option("--async-op", help="use ASYNC_OP for the replication", action="store_true"),
431 Option("--single-object", help="Replicate only the object specified, instead of the whole Naming Context (only with --local)", action="store_true"),
434 def drs_local_replicate(self, SOURCE_DC, NC, full_sync=False,
435 single_object=False,
436 sync_forced=False):
437 """replicate from a source DC to the local SAM"""
439 self.server = SOURCE_DC
440 drsuapi_connect(self)
442 # Override the default flag LDB_FLG_DONT_CREATE_DB
443 self.local_samdb = SamDB(session_info=system_session(), url=None,
444 credentials=self.creds, lp=self.lp,
445 flags=0)
447 self.samdb = SamDB(url="ldap://%s" % self.server,
448 session_info=system_session(),
449 credentials=self.creds, lp=self.lp)
451 # work out the source and destination GUIDs
452 res = self.local_samdb.search(base="", scope=ldb.SCOPE_BASE,
453 attrs=["dsServiceName"])
454 self.ntds_dn = res[0]["dsServiceName"][0]
456 res = self.local_samdb.search(base=self.ntds_dn, scope=ldb.SCOPE_BASE,
457 attrs=["objectGUID"])
458 self.ntds_guid = misc.GUID(
459 self.samdb.schema_format_value("objectGUID",
460 res[0]["objectGUID"][0]))
462 source_dsa_invocation_id = misc.GUID(self.samdb.get_invocation_id())
463 dest_dsa_invocation_id = misc.GUID(self.local_samdb.get_invocation_id())
464 destination_dsa_guid = self.ntds_guid
466 exop = drsuapi.DRSUAPI_EXOP_NONE
468 if single_object:
469 exop = drsuapi.DRSUAPI_EXOP_REPL_OBJ
470 full_sync = True
472 self.samdb.transaction_start()
473 repl = drs_utils.drs_Replicate("ncacn_ip_tcp:%s[seal]" % self.server,
474 self.lp,
475 self.creds, self.local_samdb,
476 dest_dsa_invocation_id)
478 # Work out if we are an RODC, so that a forced local replicate
479 # with the admin pw does not sync passwords
480 rodc = self.local_samdb.am_rodc()
481 try:
482 (num_objects, num_links) = repl.replicate(NC,
483 source_dsa_invocation_id,
484 destination_dsa_guid,
485 rodc=rodc,
486 full_sync=full_sync,
487 exop=exop,
488 sync_forced=sync_forced)
489 except Exception as e:
490 raise CommandError("Error replicating DN %s" % NC, e)
491 self.samdb.transaction_commit()
493 if full_sync:
494 self.message("Full Replication of all %d objects and %d links "
495 "from %s to %s was successful." %
496 (num_objects, num_links, SOURCE_DC,
497 self.local_samdb.url))
498 else:
499 self.message("Incremental replication of %d objects and %d links "
500 "from %s to %s was successful." %
501 (num_objects, num_links, SOURCE_DC,
502 self.local_samdb.url))
504 def run(self, DEST_DC, SOURCE_DC, NC,
505 add_ref=False, sync_forced=False, sync_all=False, full_sync=False,
506 local=False, local_online=False, async_op=False, single_object=False,
507 sambaopts=None, credopts=None, versionopts=None):
509 self.server = DEST_DC
510 self.lp = sambaopts.get_loadparm()
512 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
514 if local:
515 self.drs_local_replicate(SOURCE_DC, NC, full_sync=full_sync,
516 single_object=single_object,
517 sync_forced=sync_forced)
518 return
520 if local_online:
521 server_bind = drsuapi.drsuapi("irpc:dreplsrv", lp_ctx=self.lp)
522 server_bind_handle = misc.policy_handle()
523 else:
524 drsuapi_connect(self)
525 server_bind = self.drsuapi
526 server_bind_handle = self.drsuapi_handle
528 if not async_op:
529 # Give the sync replication 5 minutes time
530 server_bind.request_timeout = 5 * 60
532 samdb_connect(self)
534 # we need to find the NTDS GUID of the source DC
535 msg = self.samdb.search(base=self.samdb.get_config_basedn(),
536 expression="(&(objectCategory=server)(|(name=%s)(dNSHostName=%s)))" % (
537 ldb.binary_encode(SOURCE_DC),
538 ldb.binary_encode(SOURCE_DC)),
539 attrs=[])
540 if len(msg) == 0:
541 raise CommandError("Failed to find source DC %s" % SOURCE_DC)
542 server_dn = msg[0]['dn']
544 msg = self.samdb.search(base=server_dn, scope=ldb.SCOPE_ONELEVEL,
545 expression="(|(objectCategory=nTDSDSA)(objectCategory=nTDSDSARO))",
546 attrs=['objectGUID', 'options'])
547 if len(msg) == 0:
548 raise CommandError("Failed to find source NTDS DN %s" % SOURCE_DC)
549 source_dsa_guid = msg[0]['objectGUID'][0]
550 dsa_options = int(attr_default(msg, 'options', 0))
552 req_options = 0
553 if not (dsa_options & dsdb.DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL):
554 req_options |= drsuapi.DRSUAPI_DRS_WRIT_REP
555 if add_ref:
556 req_options |= drsuapi.DRSUAPI_DRS_ADD_REF
557 if sync_forced:
558 req_options |= drsuapi.DRSUAPI_DRS_SYNC_FORCED
559 if sync_all:
560 req_options |= drsuapi.DRSUAPI_DRS_SYNC_ALL
561 if full_sync:
562 req_options |= drsuapi.DRSUAPI_DRS_FULL_SYNC_NOW
563 if async_op:
564 req_options |= drsuapi.DRSUAPI_DRS_ASYNC_OP
566 try:
567 drs_utils.sendDsReplicaSync(server_bind, server_bind_handle, source_dsa_guid, NC, req_options)
568 except drs_utils.drsException as estr:
569 raise CommandError("DsReplicaSync failed", estr)
570 if async_op:
571 self.message("Replicate from %s to %s was started." % (SOURCE_DC, DEST_DC))
572 else:
573 self.message("Replicate from %s to %s was successful." % (SOURCE_DC, DEST_DC))
576 class cmd_drs_bind(Command):
577 """Show DRS capabilities of a server."""
579 synopsis = "%prog [<DC>] [options]"
581 takes_optiongroups = {
582 "sambaopts": options.SambaOptions,
583 "versionopts": options.VersionOptions,
584 "credopts": options.CredentialsOptions,
587 takes_args = ["DC?"]
589 def run(self, DC=None, sambaopts=None,
590 credopts=None, versionopts=None):
592 self.lp = sambaopts.get_loadparm()
593 if DC is None:
594 DC = common.netcmd_dnsname(self.lp)
595 self.server = DC
596 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
598 drsuapi_connect(self)
600 bind_info = drsuapi.DsBindInfoCtr()
601 bind_info.length = 28
602 bind_info.info = drsuapi.DsBindInfo28()
603 (info, handle) = self.drsuapi.DsBind(misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID), bind_info)
605 optmap = [
606 ("DRSUAPI_SUPPORTED_EXTENSION_BASE", "DRS_EXT_BASE"),
607 ("DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION", "DRS_EXT_ASYNCREPL"),
608 ("DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI", "DRS_EXT_REMOVEAPI"),
609 ("DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2", "DRS_EXT_MOVEREQ_V2"),
610 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS", "DRS_EXT_GETCHG_DEFLATE"),
611 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1", "DRS_EXT_DCINFO_V1"),
612 ("DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION", "DRS_EXT_RESTORE_USN_OPTIMIZATION"),
613 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY", "DRS_EXT_ADDENTRY"),
614 ("DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE", "DRS_EXT_KCC_EXECUTE"),
615 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2", "DRS_EXT_ADDENTRY_V2"),
616 ("DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION", "DRS_EXT_LINKED_VALUE_REPLICATION"),
617 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2", "DRS_EXT_DCINFO_V2"),
618 ("DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD", "DRS_EXT_INSTANCE_TYPE_NOT_REQ_ON_MOD"),
619 ("DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND", "DRS_EXT_CRYPTO_BIND"),
620 ("DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO", "DRS_EXT_GET_REPL_INFO"),
621 ("DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION", "DRS_EXT_STRONG_ENCRYPTION"),
622 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01", "DRS_EXT_DCINFO_VFFFFFFFF"),
623 ("DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP", "DRS_EXT_TRANSITIVE_MEMBERSHIP"),
624 ("DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY", "DRS_EXT_ADD_SID_HISTORY"),
625 ("DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3", "DRS_EXT_POST_BETA3"),
626 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V5", "DRS_EXT_GETCHGREQ_V5"),
627 ("DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2", "DRS_EXT_GETMEMBERSHIPS2"),
628 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6", "DRS_EXT_GETCHGREQ_V6"),
629 ("DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS", "DRS_EXT_NONDOMAIN_NCS"),
630 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8", "DRS_EXT_GETCHGREQ_V8"),
631 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5", "DRS_EXT_GETCHGREPLY_V5"),
632 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6", "DRS_EXT_GETCHGREPLY_V6"),
633 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3", "DRS_EXT_WHISTLER_BETA3"),
634 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7", "DRS_EXT_WHISTLER_BETA3"),
635 ("DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT", "DRS_EXT_WHISTLER_BETA3"),
636 ("DRSUAPI_SUPPORTED_EXTENSION_XPRESS_COMPRESS", "DRS_EXT_W2K3_DEFLATE"),
637 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10", "DRS_EXT_GETCHGREQ_V10"),
638 ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART2", "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART2"),
639 ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART3", "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART3")
642 optmap_ext = [
643 ("DRSUAPI_SUPPORTED_EXTENSION_ADAM", "DRS_EXT_ADAM"),
644 ("DRSUAPI_SUPPORTED_EXTENSION_LH_BETA2", "DRS_EXT_LH_BETA2"),
645 ("DRSUAPI_SUPPORTED_EXTENSION_RECYCLE_BIN", "DRS_EXT_RECYCLE_BIN")]
647 self.message("Bind to %s succeeded." % DC)
648 self.message("Extensions supported:")
649 for (opt, str) in optmap:
650 optval = getattr(drsuapi, opt, 0)
651 if info.info.supported_extensions & optval:
652 yesno = "Yes"
653 else:
654 yesno = "No "
655 self.message(" %-60s: %s (%s)" % (opt, yesno, str))
657 if isinstance(info.info, drsuapi.DsBindInfo48):
658 self.message("\nExtended Extensions supported:")
659 for (opt, str) in optmap_ext:
660 optval = getattr(drsuapi, opt, 0)
661 if info.info.supported_extensions_ext & optval:
662 yesno = "Yes"
663 else:
664 yesno = "No "
665 self.message(" %-60s: %s (%s)" % (opt, yesno, str))
667 self.message("\nSite GUID: %s" % info.info.site_guid)
668 self.message("Repl epoch: %u" % info.info.repl_epoch)
669 if isinstance(info.info, drsuapi.DsBindInfo48):
670 self.message("Forest GUID: %s" % info.info.config_dn_guid)
673 class cmd_drs_options(Command):
674 """Query or change 'options' for NTDS Settings object of a Domain Controller."""
676 synopsis = "%prog [<DC>] [options]"
678 takes_optiongroups = {
679 "sambaopts": options.SambaOptions,
680 "versionopts": options.VersionOptions,
681 "credopts": options.CredentialsOptions,
684 takes_args = ["DC?"]
686 takes_options = [
687 Option("--dsa-option", help="DSA option to enable/disable", type="str",
688 metavar="{+|-}IS_GC | {+|-}DISABLE_INBOUND_REPL | {+|-}DISABLE_OUTBOUND_REPL | {+|-}DISABLE_NTDSCONN_XLATE"),
691 option_map = {"IS_GC": 0x00000001,
692 "DISABLE_INBOUND_REPL": 0x00000002,
693 "DISABLE_OUTBOUND_REPL": 0x00000004,
694 "DISABLE_NTDSCONN_XLATE": 0x00000008}
696 def run(self, DC=None, dsa_option=None,
697 sambaopts=None, credopts=None, versionopts=None):
699 self.lp = sambaopts.get_loadparm()
700 if DC is None:
701 DC = common.netcmd_dnsname(self.lp)
702 self.server = DC
703 self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
705 samdb_connect(self)
707 ntds_dn = self.samdb.get_dsServiceName()
708 res = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=["options"])
709 dsa_opts = int(res[0]["options"][0])
711 # print out current DSA options
712 cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts]
713 self.message("Current DSA options: " + ", ".join(cur_opts))
715 # modify options
716 if dsa_option:
717 if dsa_option[:1] not in ("+", "-"):
718 raise CommandError("Unknown option %s" % dsa_option)
719 flag = dsa_option[1:]
720 if flag not in self.option_map.keys():
721 raise CommandError("Unknown option %s" % dsa_option)
722 if dsa_option[:1] == "+":
723 dsa_opts |= self.option_map[flag]
724 else:
725 dsa_opts &= ~self.option_map[flag]
726 # save new options
727 m = ldb.Message()
728 m.dn = ldb.Dn(self.samdb, ntds_dn)
729 m["options"] = ldb.MessageElement(str(dsa_opts), ldb.FLAG_MOD_REPLACE, "options")
730 self.samdb.modify(m)
731 # print out new DSA options
732 cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts]
733 self.message("New DSA options: " + ", ".join(cur_opts))
736 class cmd_drs_clone_dc_database(Command):
737 """Replicate an initial clone of domain, but DO NOT JOIN it."""
739 synopsis = "%prog <dnsdomain> [options]"
741 takes_optiongroups = {
742 "sambaopts": options.SambaOptions,
743 "versionopts": options.VersionOptions,
744 "credopts": options.CredentialsOptions,
747 takes_options = [
748 Option("--server", help="DC to join", type=str),
749 Option("--targetdir", help="where to store provision (required)", type=str),
750 Option("-q", "--quiet", help="Be quiet", action="store_true"),
751 Option("--include-secrets", help="Also replicate secret values", action="store_true"),
752 Option("--backend-store", type="choice", metavar="BACKENDSTORE",
753 choices=["tdb", "mdb"],
754 help="Specify the database backend to be used "
755 "(default is %s)" % get_default_backend_store()),
756 Option("--backend-store-size", type="bytes", metavar="SIZE",
757 help="Specify the size of the backend database, currently" +
758 "only supported by lmdb backends (default is 8 Gb).")
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 backend_store=None, backend_store_size=None):
767 lp = sambaopts.get_loadparm()
768 creds = credopts.get_credentials(lp)
770 logger = self.get_logger(verbose=verbose, quiet=quiet)
772 if targetdir is None:
773 raise CommandError("--targetdir option must be specified")
775 join_clone(logger=logger, server=server, creds=creds, lp=lp,
776 domain=domain, dns_backend='SAMBA_INTERNAL',
777 targetdir=targetdir, include_secrets=include_secrets,
778 backend_store=backend_store,
779 backend_store_size=backend_store_size)
782 class cmd_drs_uptodateness(Command):
783 """Show uptodateness status"""
785 synopsis = "%prog [options]"
787 takes_optiongroups = {
788 "sambaopts": options.SambaOptions,
789 "versionopts": options.VersionOptions,
790 "credopts": options.CredentialsOptions,
793 takes_options = [
794 Option("-H", "--URL", metavar="URL", dest="H",
795 help="LDB URL for database or target server"),
796 Option("-p", "--partition",
797 help="restrict to this partition"),
798 Option("--json", action='store_true',
799 help="Print data in json format"),
800 Option("--maximum", action='store_true',
801 help="Print maximum out-of-date-ness only"),
802 Option("--median", action='store_true',
803 help="Print median out-of-date-ness only"),
804 Option("--full", action='store_true',
805 help="Print full out-of-date-ness data"),
808 def format_as_json(self, partitions_summaries):
809 return json.dumps(partitions_summaries, indent=2)
811 def format_as_text(self, partitions_summaries):
812 lines = []
813 for part_name, summary in partitions_summaries.items():
814 items = ['%s: %s' % (k, v) for k, v in summary.items()]
815 line = '%-15s %s' % (part_name, ' '.join(items))
816 lines.append(line)
817 return '\n'.join(lines)
819 def run(self, H=None, partition=None,
820 json=False, maximum=False, median=False, full=False,
821 sambaopts=None, credopts=None, versionopts=None,
822 quiet=False, verbose=False):
824 lp = sambaopts.get_loadparm()
825 creds = credopts.get_credentials(lp, fallback_machine=True)
826 local_kcc, dsas = get_kcc_and_dsas(H, lp, creds)
827 samdb = local_kcc.samdb
828 short_partitions, _ = get_partition_maps(samdb)
829 if partition:
830 if partition in short_partitions:
831 part_dn = short_partitions[partition]
832 # narrow down to specified partition only
833 short_partitions = {partition: part_dn}
834 else:
835 raise CommandError("unknown partition %s" % partition)
837 filters = []
838 if maximum:
839 filters.append('maximum')
840 if median:
841 filters.append('median')
843 partitions_distances = {}
844 partitions_summaries = {}
845 for part_name, part_dn in short_partitions.items():
846 utdv_edges = get_utdv_edges(local_kcc, dsas, part_dn, lp, creds)
847 distances = get_utdv_distances(utdv_edges, dsas)
848 summary = get_utdv_summary(distances, filters=filters)
849 partitions_distances[part_name] = distances
850 partitions_summaries[part_name] = summary
852 if full:
853 # always print json format
854 output = self.format_as_json(partitions_distances)
855 else:
856 if json:
857 output = self.format_as_json(partitions_summaries)
858 else:
859 output = self.format_as_text(partitions_summaries)
861 print(output, file=self.outf)
864 class cmd_drs(SuperCommand):
865 """Directory Replication Services (DRS) management."""
867 subcommands = {}
868 subcommands["bind"] = cmd_drs_bind()
869 subcommands["kcc"] = cmd_drs_kcc()
870 subcommands["replicate"] = cmd_drs_replicate()
871 subcommands["showrepl"] = cmd_drs_showrepl()
872 subcommands["options"] = cmd_drs_options()
873 subcommands["clone-dc-database"] = cmd_drs_clone_dc_database()
874 subcommands["uptodateness"] = cmd_drs_uptodateness()