3 # implement samba_tool drs commands
5 # Copyright Andrew Tridgell 2010
6 # Copyright Giampaolo Lauria 2011 <lauria2@yahoo.com>
8 # based on C implementation by Kamen Mazdrashki <kamen.mazdrashki@postpath.com>
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with this program. If not, see <http://www.gnu.org/licenses/>.
24 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
41 def drsuapi_connect(ctx
):
42 '''make a DRSUAPI connection to the server'''
43 binding_options
= "seal"
44 if int(ctx
.lp
.get("log level")) >= 5:
45 binding_options
+= ",print"
46 binding_string
= "ncacn_ip_tcp:%s[%s]" % (ctx
.server
, binding_options
)
48 ctx
.drsuapi
= drsuapi
.drsuapi(binding_string
, ctx
.lp
, ctx
.creds
)
49 (ctx
.drsuapi_handle
, ctx
.bind_supported_extensions
) = drs_utils
.drs_DsBind(ctx
.drsuapi
)
51 raise CommandError("DRS connection to %s failed" % ctx
.server
, e
)
55 def samdb_connect(ctx
):
56 '''make a ldap connection to the server'''
58 ctx
.samdb
= SamDB(url
="ldap://%s" % ctx
.server
,
59 session_info
=system_session(),
60 credentials
=ctx
.creds
, lp
=ctx
.lp
)
62 raise CommandError("LDAP connection to %s failed" % ctx
.server
, e
)
67 '''return "was successful" or an error string'''
68 (ecode
, estring
) = werr
70 return "was successful"
71 return "failed, result %u (%s)" % (ecode
, estring
)
75 def attr_default(msg
, attrname
, default
):
76 '''get an attribute from a ldap msg with a default'''
78 return msg
[attrname
][0]
83 def drs_parse_ntds_dn(ntds_dn
):
84 '''parse a NTDS DN returning a site and server'''
85 a
= ntds_dn
.split(',')
86 if a
[0] != "CN=NTDS Settings" or a
[2] != "CN=Servers" or a
[4] != 'CN=Sites':
87 raise RuntimeError("bad NTDS DN %s" % ntds_dn
)
88 server
= a
[1].split('=')[1]
89 site
= a
[3].split('=')[1]
94 def get_dsServiceName(samdb
):
95 '''get the NTDS DN from the rootDSE'''
96 res
= samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dsServiceName"])
97 return res
[0]["dsServiceName"][0]
101 class cmd_drs_showrepl(Command
):
102 """show replication status"""
104 synopsis
= "%prog [<DC>] [options]"
108 def print_neighbour(self
, n
):
109 '''print one set of neighbour information'''
110 self
.message("%s" % n
.naming_context_dn
)
112 (site
, server
) = drs_parse_ntds_dn(n
.source_dsa_obj_dn
)
113 self
.message("\t%s\%s via RPC" % (site
, server
))
115 self
.message("\tNTDS DN: %s" % n
.source_dsa_obj_dn
)
116 self
.message("\t\tDSA object GUID: %s" % n
.source_dsa_obj_guid
)
117 self
.message("\t\tLast attempt @ %s %s" % (nttime2string(n
.last_attempt
),
118 drs_errmsg(n
.result_last_attempt
)))
119 self
.message("\t\t%u consecutive failure(s)." % n
.consecutive_sync_failures
)
120 self
.message("\t\tLast success @ %s" % nttime2string(n
.last_success
))
123 def drsuapi_ReplicaInfo(ctx
, info_type
):
124 '''call a DsReplicaInfo'''
126 req1
= drsuapi
.DsReplicaGetInfoRequest1()
127 req1
.info_type
= info_type
129 (info_type
, info
) = ctx
.drsuapi
.DsReplicaGetInfo(ctx
.drsuapi_handle
, 1, req1
)
131 raise CommandError("DsReplicaGetInfo of type %u failed" % info_type
, e
)
132 return (info_type
, info
)
134 def run(self
, DC
=None, sambaopts
=None,
135 credopts
=None, versionopts
=None, server
=None):
137 self
.lp
= sambaopts
.get_loadparm()
139 DC
= common
.netcmd_dnsname(self
.lp
)
141 self
.creds
= credopts
.get_credentials(self
.lp
, fallback_machine
=True)
143 drsuapi_connect(self
)
146 # show domain information
147 ntds_dn
= get_dsServiceName(self
.samdb
)
148 server_dns
= self
.samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dnsHostName"])[0]['dnsHostName'][0]
150 (site
, server
) = drs_parse_ntds_dn(ntds_dn
)
152 ntds
= self
.samdb
.search(base
=ntds_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=['options', 'objectGUID', 'invocationId'])
154 raise CommandError("Failed to search NTDS DN %s" % ntds_dn
)
155 conn
= self
.samdb
.search(base
=ntds_dn
, expression
="(objectClass=nTDSConnection)")
157 self
.message("%s\\%s" % (site
, server
))
158 self
.message("DSA Options: 0x%08x" % int(attr_default(ntds
[0], "options", 0)))
159 self
.message("DSA object GUID: %s" % self
.samdb
.schema_format_value("objectGUID", ntds
[0]["objectGUID"][0]))
160 self
.message("DSA invocationId: %s\n" % self
.samdb
.schema_format_value("objectGUID", ntds
[0]["invocationId"][0]))
162 self
.message("==== INBOUND NEIGHBORS ====\n")
163 (info_type
, info
) = self
.drsuapi_ReplicaInfo(drsuapi
.DRSUAPI_DS_REPLICA_INFO_NEIGHBORS
)
165 self
.print_neighbour(n
)
168 self
.message("==== OUTBOUND NEIGHBORS ====\n")
169 (info_type
, info
) = self
.drsuapi_ReplicaInfo(drsuapi
.DRSUAPI_DS_REPLICA_INFO_REPSTO
)
171 self
.print_neighbour(n
)
173 reasons
= ['NTDSCONN_KCC_GC_TOPOLOGY',
174 'NTDSCONN_KCC_RING_TOPOLOGY',
175 'NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY',
176 'NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY',
177 'NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY',
178 'NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY',
179 'NTDSCONN_KCC_INTERSITE_TOPOLOGY',
180 'NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY',
181 'NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY',
182 'NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY']
184 self
.message("==== KCC CONNECTION OBJECTS ====\n")
186 self
.message("Connection --")
187 self
.message("\tConnection name: %s" % c
['name'][0])
188 self
.message("\tEnabled : %s" % attr_default(c
, 'enabledConnection', 'TRUE'))
189 self
.message("\tServer DNS name : %s" % server_dns
)
190 self
.message("\tServer DN name : %s" % c
['fromServer'][0])
191 self
.message("\t\tTransportType: RPC")
192 self
.message("\t\toptions: 0x%08X" % int(attr_default(c
, 'options', 0)))
193 if not 'mS-DS-ReplicatesNCReason' in c
:
194 self
.message("Warning: No NC replicated for Connection!")
196 for r
in c
['mS-DS-ReplicatesNCReason']:
197 a
= str(r
).split(':')
198 self
.message("\t\tReplicatesNC: %s" % a
[3])
199 self
.message("\t\tReason: 0x%08x" % int(a
[2]))
201 if getattr(dsdb
, s
, 0) & int(a
[2]):
202 self
.message("\t\t\t%s" % s
)
206 class cmd_drs_kcc(Command
):
207 """trigger knowledge consistency center run"""
209 synopsis
= "%prog [<DC>] [options]"
213 def run(self
, DC
=None, sambaopts
=None,
214 credopts
=None, versionopts
=None, server
=None):
216 self
.lp
= sambaopts
.get_loadparm()
218 DC
= common
.netcmd_dnsname(self
.lp
)
221 self
.creds
= credopts
.get_credentials(self
.lp
, fallback_machine
=True)
223 drsuapi_connect(self
)
225 req1
= drsuapi
.DsExecuteKCC1()
227 self
.drsuapi
.DsExecuteKCC(self
.drsuapi_handle
, 1, req1
)
229 raise CommandError("DsExecuteKCC failed", e
)
230 self
.message("Consistency check on %s successful." % DC
)
234 def drs_local_replicate(self
, SOURCE_DC
, NC
):
235 '''replicate from a source DC to the local SAM'''
237 self
.server
= SOURCE_DC
238 drsuapi_connect(self
)
240 self
.local_samdb
= SamDB(session_info
=system_session(), url
=None,
241 credentials
=self
.creds
, lp
=self
.lp
)
243 self
.samdb
= SamDB(url
="ldap://%s" % self
.server
,
244 session_info
=system_session(),
245 credentials
=self
.creds
, lp
=self
.lp
)
247 # work out the source and destination GUIDs
248 res
= self
.local_samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dsServiceName"])
249 self
.ntds_dn
= res
[0]["dsServiceName"][0]
251 res
= self
.local_samdb
.search(base
=self
.ntds_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["objectGUID"])
252 self
.ntds_guid
= misc
.GUID(self
.samdb
.schema_format_value("objectGUID", res
[0]["objectGUID"][0]))
255 source_dsa_invocation_id
= misc
.GUID(self
.samdb
.get_invocation_id())
256 destination_dsa_guid
= self
.ntds_guid
258 self
.samdb
.transaction_start()
259 repl
= drs_utils
.drs_Replicate("ncacn_ip_tcp:%s[seal]" % self
.server
, self
.lp
,
260 self
.creds
, self
.local_samdb
)
262 repl
.replicate(NC
, source_dsa_invocation_id
, destination_dsa_guid
)
264 raise CommandError("Error replicating DN %s" % NC
, e
)
265 self
.samdb
.transaction_commit()
269 class cmd_drs_replicate(Command
):
270 """replicate a naming context between two DCs"""
272 synopsis
= "%prog <destinationDC> <sourceDC> <NC> [options]"
274 takes_args
= ["DEST_DC", "SOURCE_DC", "NC"]
277 Option("--add-ref", help="use ADD_REF to add to repsTo on source", action
="store_true"),
278 Option("--sync-forced", help="use SYNC_FORCED to force inbound replication", action
="store_true"),
279 Option("--sync-all", help="use SYNC_ALL to replicate from all DCs", action
="store_true"),
280 Option("--full-sync", help="resync all objects", action
="store_true"),
281 Option("--local", help="pull changes directly into the local database (destination DC is ignored)", action
="store_true"),
284 def run(self
, DEST_DC
, SOURCE_DC
, NC
,
285 add_ref
=False, sync_forced
=False, sync_all
=False, full_sync
=False,
286 local
=False, sambaopts
=None, credopts
=None, versionopts
=None, server
=None):
288 self
.server
= DEST_DC
289 self
.lp
= sambaopts
.get_loadparm()
291 self
.creds
= credopts
.get_credentials(self
.lp
, fallback_machine
=True)
294 drs_local_replicate(self
, SOURCE_DC
, NC
)
297 drsuapi_connect(self
)
300 # we need to find the NTDS GUID of the source DC
301 msg
= self
.samdb
.search(base
=self
.samdb
.get_config_basedn(),
302 expression
="(&(objectCategory=server)(|(name=%s)(dNSHostName=%s)))" % (
303 ldb
.binary_encode(SOURCE_DC
),
304 ldb
.binary_encode(SOURCE_DC
)),
307 raise CommandError("Failed to find source DC %s" % SOURCE_DC
)
308 server_dn
= msg
[0]['dn']
310 msg
= self
.samdb
.search(base
=server_dn
, scope
=ldb
.SCOPE_ONELEVEL
,
311 expression
="(|(objectCategory=nTDSDSA)(objectCategory=nTDSDSARO))",
312 attrs
=['objectGUID', 'options'])
314 raise CommandError("Failed to find source NTDS DN %s" % SOURCE_DC
)
315 source_dsa_guid
= msg
[0]['objectGUID'][0]
316 dsa_options
= int(attr_default(msg
, 'options', 0))
318 nc
= drsuapi
.DsReplicaObjectIdentifier()
321 req1
= drsuapi
.DsReplicaSyncRequest1()
322 req1
.naming_context
= nc
;
324 if not (dsa_options
& dsdb
.DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL
):
325 req1
.options |
= drsuapi
.DRSUAPI_DRS_WRIT_REP
327 req1
.options |
= drsuapi
.DRSUAPI_DRS_ADD_REF
329 req1
.options |
= drsuapi
.DRSUAPI_DRS_SYNC_FORCED
331 req1
.options |
= drsuapi
.DRSUAPI_DRS_SYNC_ALL
333 req1
.options |
= drsuapi
.DRSUAPI_DRS_FULL_SYNC_NOW
334 req1
.source_dsa_guid
= misc
.GUID(source_dsa_guid
)
337 self
.drsuapi
.DsReplicaSync(self
.drsuapi_handle
, 1, req1
)
338 except Exception, estr
:
339 raise CommandError("DsReplicaSync failed", estr
)
340 self
.message("Replicate from %s to %s was successful." % (SOURCE_DC
, DEST_DC
))
344 class cmd_drs_bind(Command
):
345 """show DRS capabilities of a server"""
347 synopsis
= "%prog [<DC>] [options]"
351 def run(self
, DC
=None, sambaopts
=None,
352 credopts
=None, versionopts
=None, server
=None):
354 self
.lp
= sambaopts
.get_loadparm()
356 DC
= common
.netcmd_dnsname(self
.lp
)
358 self
.creds
= credopts
.get_credentials(self
.lp
, fallback_machine
=True)
360 drsuapi_connect(self
)
363 bind_info
= drsuapi
.DsBindInfoCtr()
364 bind_info
.length
= 28
365 bind_info
.info
= drsuapi
.DsBindInfo28()
366 (info
, handle
) = self
.drsuapi
.DsBind(misc
.GUID(drsuapi
.DRSUAPI_DS_BIND_GUID
), bind_info
)
369 ("DRSUAPI_SUPPORTED_EXTENSION_BASE", "DRS_EXT_BASE"),
370 ("DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION", "DRS_EXT_ASYNCREPL"),
371 ("DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI", "DRS_EXT_REMOVEAPI"),
372 ("DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2", "DRS_EXT_MOVEREQ_V2"),
373 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS", "DRS_EXT_GETCHG_DEFLATE"),
374 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1", "DRS_EXT_DCINFO_V1"),
375 ("DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION", "DRS_EXT_RESTORE_USN_OPTIMIZATION"),
376 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY", "DRS_EXT_ADDENTRY"),
377 ("DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE", "DRS_EXT_KCC_EXECUTE"),
378 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2", "DRS_EXT_ADDENTRY_V2"),
379 ("DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION", "DRS_EXT_LINKED_VALUE_REPLICATION"),
380 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2", "DRS_EXT_DCINFO_V2"),
381 ("DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD","DRS_EXT_INSTANCE_TYPE_NOT_REQ_ON_MOD"),
382 ("DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND", "DRS_EXT_CRYPTO_BIND"),
383 ("DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO", "DRS_EXT_GET_REPL_INFO"),
384 ("DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION", "DRS_EXT_STRONG_ENCRYPTION"),
385 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01", "DRS_EXT_DCINFO_VFFFFFFFF"),
386 ("DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP", "DRS_EXT_TRANSITIVE_MEMBERSHIP"),
387 ("DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY", "DRS_EXT_ADD_SID_HISTORY"),
388 ("DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3", "DRS_EXT_POST_BETA3"),
389 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V5", "DRS_EXT_GETCHGREQ_V5"),
390 ("DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2", "DRS_EXT_GETMEMBERSHIPS2"),
391 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6", "DRS_EXT_GETCHGREQ_V6"),
392 ("DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS", "DRS_EXT_NONDOMAIN_NCS"),
393 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8", "DRS_EXT_GETCHGREQ_V8"),
394 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5", "DRS_EXT_GETCHGREPLY_V5"),
395 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6", "DRS_EXT_GETCHGREPLY_V6"),
396 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3", "DRS_EXT_WHISTLER_BETA3"),
397 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7", "DRS_EXT_WHISTLER_BETA3"),
398 ("DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT", "DRS_EXT_WHISTLER_BETA3"),
399 ("DRSUAPI_SUPPORTED_EXTENSION_XPRESS_COMPRESS", "DRS_EXT_W2K3_DEFLATE"),
400 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10", "DRS_EXT_GETCHGREQ_V10"),
401 ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART2", "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART2"),
402 ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART3", "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART3")
406 ("DRSUAPI_SUPPORTED_EXTENSION_ADAM", "DRS_EXT_ADAM"),
407 ("DRSUAPI_SUPPORTED_EXTENSION_LH_BETA2", "DRS_EXT_LH_BETA2"),
408 ("DRSUAPI_SUPPORTED_EXTENSION_RECYCLE_BIN", "DRS_EXT_RECYCLE_BIN")]
410 self
.message("Bind to %s succeeded." % DC
)
411 self
.message("Extensions supported:")
412 for (opt
, str) in optmap
:
413 optval
= getattr(drsuapi
, opt
, 0)
414 if info
.info
.supported_extensions
& optval
:
418 self
.message(" %-60s: %s (%s)" % (opt
, yesno
, str))
420 if isinstance(info
.info
, drsuapi
.DsBindInfo48
):
421 self
.message("\nExtended Extensions supported:")
422 for (opt
, str) in optmap_ext
:
423 optval
= getattr(drsuapi
, opt
, 0)
424 if info
.info
.supported_extensions_ext
& optval
:
428 self
.message(" %-60s: %s (%s)" % (opt
, yesno
, str))
430 self
.message("\nSite GUID: %s" % info
.info
.site_guid
)
431 self
.message("Repl epoch: %u" % info
.info
.repl_epoch
)
432 if isinstance(info
.info
, drsuapi
.DsBindInfo48
):
433 self
.message("Forest GUID: %s" % info
.info
.config_dn_guid
)
437 class cmd_drs_options(Command
):
438 """query or change 'options' for NTDS Settings object of a domain controller"""
440 synopsis
= "%prog [<DC>] [options]"
445 Option("--dsa-option", help="DSA option to enable/disable", type="str",
446 metavar
="{+|-}IS_GC | {+|-}DISABLE_INBOUND_REPL | {+|-}DISABLE_OUTBOUND_REPL | {+|-}DISABLE_NTDSCONN_XLATE" ),
449 option_map
= {"IS_GC": 0x00000001,
450 "DISABLE_INBOUND_REPL": 0x00000002,
451 "DISABLE_OUTBOUND_REPL": 0x00000004,
452 "DISABLE_NTDSCONN_XLATE": 0x00000008}
454 def run(self
, DC
=None, dsa_option
=None,
455 sambaopts
=None, credopts
=None, versionopts
=None):
457 self
.lp
= sambaopts
.get_loadparm()
459 DC
= common
.netcmd_dnsname(self
.lp
)
461 self
.creds
= credopts
.get_credentials(self
.lp
, fallback_machine
=True)
465 ntds_dn
= get_dsServiceName(self
.samdb
)
466 res
= self
.samdb
.search(base
=ntds_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["options"])
467 dsa_opts
= int(res
[0]["options"][0])
469 # print out current DSA options
470 cur_opts
= [x
for x
in self
.option_map
if self
.option_map
[x
] & dsa_opts
]
471 self
.message("Current DSA options: " + ", ".join(cur_opts
))
475 if dsa_option
[:1] not in ("+", "-"):
476 raise CommandError("Unknown option %s" % dsa_option
)
477 flag
= dsa_option
[1:]
478 if flag
not in self
.option_map
.keys():
479 raise CommandError("Unknown option %s" % dsa_option
)
480 if dsa_option
[:1] == "+":
481 dsa_opts |
= self
.option_map
[flag
]
483 dsa_opts
&= ~self
.option_map
[flag
]
486 m
.dn
= ldb
.Dn(self
.samdb
, ntds_dn
)
487 m
["options"]= ldb
.MessageElement(str(dsa_opts
), ldb
.FLAG_MOD_REPLACE
, "options")
489 # print out new DSA options
490 cur_opts
= [x
for x
in self
.option_map
if self
.option_map
[x
] & dsa_opts
]
491 self
.message("New DSA options: " + ", ".join(cur_opts
))
494 class cmd_drs(SuperCommand
):
495 """Directory Replication Services (DRS) management"""
498 subcommands
["bind"] = cmd_drs_bind()
499 subcommands
["kcc"] = cmd_drs_kcc()
500 subcommands
["replicate"] = cmd_drs_replicate()
501 subcommands
["showrepl"] = cmd_drs_showrepl()
502 subcommands
["options"] = cmd_drs_options()