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
39 def drsuapi_connect(ctx
):
40 '''make a DRSUAPI connection to the server'''
42 (ctx
.drsuapi
, ctx
.drsuapi_handle
, ctx
.bind_supported_extensions
) = drs_utils
.drsuapi_connect(ctx
.server
, ctx
.lp
, ctx
.creds
)
44 raise CommandError("DRS connection to %s failed" % ctx
.server
, e
)
46 def samdb_connect(ctx
):
47 '''make a ldap connection to the server'''
49 ctx
.samdb
= SamDB(url
="ldap://%s" % ctx
.server
,
50 session_info
=system_session(),
51 credentials
=ctx
.creds
, lp
=ctx
.lp
)
53 raise CommandError("LDAP connection to %s failed" % ctx
.server
, e
)
56 '''return "was successful" or an error string'''
57 (ecode
, estring
) = werr
59 return "was successful"
60 return "failed, result %u (%s)" % (ecode
, estring
)
64 def attr_default(msg
, attrname
, default
):
65 '''get an attribute from a ldap msg with a default'''
67 return msg
[attrname
][0]
72 def drs_parse_ntds_dn(ntds_dn
):
73 '''parse a NTDS DN returning a site and server'''
74 a
= ntds_dn
.split(',')
75 if a
[0] != "CN=NTDS Settings" or a
[2] != "CN=Servers" or a
[4] != 'CN=Sites':
76 raise RuntimeError("bad NTDS DN %s" % ntds_dn
)
77 server
= a
[1].split('=')[1]
78 site
= a
[3].split('=')[1]
85 class cmd_drs_showrepl(Command
):
86 """show replication status"""
88 synopsis
= "%prog [<DC>] [options]"
92 def print_neighbour(self
, n
):
93 '''print one set of neighbour information'''
94 self
.message("%s" % n
.naming_context_dn
)
96 (site
, server
) = drs_parse_ntds_dn(n
.source_dsa_obj_dn
)
97 self
.message("\t%s\%s via RPC" % (site
, server
))
99 self
.message("\tNTDS DN: %s" % n
.source_dsa_obj_dn
)
100 self
.message("\t\tDSA object GUID: %s" % n
.source_dsa_obj_guid
)
101 self
.message("\t\tLast attempt @ %s %s" % (nttime2string(n
.last_attempt
),
102 drs_errmsg(n
.result_last_attempt
)))
103 self
.message("\t\t%u consecutive failure(s)." % n
.consecutive_sync_failures
)
104 self
.message("\t\tLast success @ %s" % nttime2string(n
.last_success
))
107 def drsuapi_ReplicaInfo(ctx
, info_type
):
108 '''call a DsReplicaInfo'''
110 req1
= drsuapi
.DsReplicaGetInfoRequest1()
111 req1
.info_type
= info_type
113 (info_type
, info
) = ctx
.drsuapi
.DsReplicaGetInfo(ctx
.drsuapi_handle
, 1, req1
)
115 raise CommandError("DsReplicaGetInfo of type %u failed" % info_type
, e
)
116 return (info_type
, info
)
118 def run(self
, DC
=None, sambaopts
=None,
119 credopts
=None, versionopts
=None, server
=None):
121 self
.lp
= sambaopts
.get_loadparm()
123 DC
= common
.netcmd_dnsname(self
.lp
)
125 self
.creds
= credopts
.get_credentials(self
.lp
, fallback_machine
=True)
127 drsuapi_connect(self
)
130 # show domain information
131 ntds_dn
= self
.samdb
.get_dsServiceName()
132 server_dns
= self
.samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dnsHostName"])[0]['dnsHostName'][0]
134 (site
, server
) = drs_parse_ntds_dn(ntds_dn
)
136 ntds
= self
.samdb
.search(base
=ntds_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=['options', 'objectGUID', 'invocationId'])
138 raise CommandError("Failed to search NTDS DN %s" % ntds_dn
)
139 conn
= self
.samdb
.search(base
=ntds_dn
, expression
="(objectClass=nTDSConnection)")
141 self
.message("%s\\%s" % (site
, server
))
142 self
.message("DSA Options: 0x%08x" % int(attr_default(ntds
[0], "options", 0)))
143 self
.message("DSA object GUID: %s" % self
.samdb
.schema_format_value("objectGUID", ntds
[0]["objectGUID"][0]))
144 self
.message("DSA invocationId: %s\n" % self
.samdb
.schema_format_value("objectGUID", ntds
[0]["invocationId"][0]))
146 self
.message("==== INBOUND NEIGHBORS ====\n")
147 (info_type
, info
) = self
.drsuapi_ReplicaInfo(drsuapi
.DRSUAPI_DS_REPLICA_INFO_NEIGHBORS
)
149 self
.print_neighbour(n
)
152 self
.message("==== OUTBOUND NEIGHBORS ====\n")
153 (info_type
, info
) = self
.drsuapi_ReplicaInfo(drsuapi
.DRSUAPI_DS_REPLICA_INFO_REPSTO
)
155 self
.print_neighbour(n
)
157 reasons
= ['NTDSCONN_KCC_GC_TOPOLOGY',
158 'NTDSCONN_KCC_RING_TOPOLOGY',
159 'NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY',
160 'NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY',
161 'NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY',
162 'NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY',
163 'NTDSCONN_KCC_INTERSITE_TOPOLOGY',
164 'NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY',
165 'NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY',
166 'NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY']
168 self
.message("==== KCC CONNECTION OBJECTS ====\n")
170 self
.message("Connection --")
171 self
.message("\tConnection name: %s" % c
['name'][0])
172 self
.message("\tEnabled : %s" % attr_default(c
, 'enabledConnection', 'TRUE'))
173 self
.message("\tServer DNS name : %s" % server_dns
)
174 self
.message("\tServer DN name : %s" % c
['fromServer'][0])
175 self
.message("\t\tTransportType: RPC")
176 self
.message("\t\toptions: 0x%08X" % int(attr_default(c
, 'options', 0)))
177 if not 'mS-DS-ReplicatesNCReason' in c
:
178 self
.message("Warning: No NC replicated for Connection!")
180 for r
in c
['mS-DS-ReplicatesNCReason']:
181 a
= str(r
).split(':')
182 self
.message("\t\tReplicatesNC: %s" % a
[3])
183 self
.message("\t\tReason: 0x%08x" % int(a
[2]))
185 if getattr(dsdb
, s
, 0) & int(a
[2]):
186 self
.message("\t\t\t%s" % s
)
190 class cmd_drs_kcc(Command
):
191 """trigger knowledge consistency center run"""
193 synopsis
= "%prog [<DC>] [options]"
197 def run(self
, DC
=None, sambaopts
=None,
198 credopts
=None, versionopts
=None, server
=None):
200 self
.lp
= sambaopts
.get_loadparm()
202 DC
= common
.netcmd_dnsname(self
.lp
)
205 self
.creds
= credopts
.get_credentials(self
.lp
, fallback_machine
=True)
207 drsuapi_connect(self
)
209 req1
= drsuapi
.DsExecuteKCC1()
211 self
.drsuapi
.DsExecuteKCC(self
.drsuapi_handle
, 1, req1
)
213 raise CommandError("DsExecuteKCC failed", e
)
214 self
.message("Consistency check on %s successful." % DC
)
218 def drs_local_replicate(self
, SOURCE_DC
, NC
):
219 '''replicate from a source DC to the local SAM'''
221 self
.server
= SOURCE_DC
222 drsuapi_connect(self
)
224 self
.local_samdb
= SamDB(session_info
=system_session(), url
=None,
225 credentials
=self
.creds
, lp
=self
.lp
)
227 self
.samdb
= SamDB(url
="ldap://%s" % self
.server
,
228 session_info
=system_session(),
229 credentials
=self
.creds
, lp
=self
.lp
)
231 # work out the source and destination GUIDs
232 res
= self
.local_samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dsServiceName"])
233 self
.ntds_dn
= res
[0]["dsServiceName"][0]
235 res
= self
.local_samdb
.search(base
=self
.ntds_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["objectGUID"])
236 self
.ntds_guid
= misc
.GUID(self
.samdb
.schema_format_value("objectGUID", res
[0]["objectGUID"][0]))
239 source_dsa_invocation_id
= misc
.GUID(self
.samdb
.get_invocation_id())
240 destination_dsa_guid
= self
.ntds_guid
242 self
.samdb
.transaction_start()
243 repl
= drs_utils
.drs_Replicate("ncacn_ip_tcp:%s[seal]" % self
.server
, self
.lp
,
244 self
.creds
, self
.local_samdb
)
246 repl
.replicate(NC
, source_dsa_invocation_id
, destination_dsa_guid
)
248 raise CommandError("Error replicating DN %s" % NC
, e
)
249 self
.samdb
.transaction_commit()
253 class cmd_drs_replicate(Command
):
254 """replicate a naming context between two DCs"""
256 synopsis
= "%prog <destinationDC> <sourceDC> <NC> [options]"
258 takes_args
= ["DEST_DC", "SOURCE_DC", "NC"]
261 Option("--add-ref", help="use ADD_REF to add to repsTo on source", action
="store_true"),
262 Option("--sync-forced", help="use SYNC_FORCED to force inbound replication", action
="store_true"),
263 Option("--sync-all", help="use SYNC_ALL to replicate from all DCs", action
="store_true"),
264 Option("--full-sync", help="resync all objects", action
="store_true"),
265 Option("--local", help="pull changes directly into the local database (destination DC is ignored)", action
="store_true"),
268 def run(self
, DEST_DC
, SOURCE_DC
, NC
,
269 add_ref
=False, sync_forced
=False, sync_all
=False, full_sync
=False,
270 local
=False, sambaopts
=None, credopts
=None, versionopts
=None, server
=None):
272 self
.server
= DEST_DC
273 self
.lp
= sambaopts
.get_loadparm()
275 self
.creds
= credopts
.get_credentials(self
.lp
, fallback_machine
=True)
278 drs_local_replicate(self
, SOURCE_DC
, NC
)
281 drsuapi_connect(self
)
284 # we need to find the NTDS GUID of the source DC
285 msg
= self
.samdb
.search(base
=self
.samdb
.get_config_basedn(),
286 expression
="(&(objectCategory=server)(|(name=%s)(dNSHostName=%s)))" % (
287 ldb
.binary_encode(SOURCE_DC
),
288 ldb
.binary_encode(SOURCE_DC
)),
291 raise CommandError("Failed to find source DC %s" % SOURCE_DC
)
292 server_dn
= msg
[0]['dn']
294 msg
= self
.samdb
.search(base
=server_dn
, scope
=ldb
.SCOPE_ONELEVEL
,
295 expression
="(|(objectCategory=nTDSDSA)(objectCategory=nTDSDSARO))",
296 attrs
=['objectGUID', 'options'])
298 raise CommandError("Failed to find source NTDS DN %s" % SOURCE_DC
)
299 source_dsa_guid
= msg
[0]['objectGUID'][0]
300 dsa_options
= int(attr_default(msg
, 'options', 0))
304 if not (dsa_options
& dsdb
.DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL
):
305 req_options |
= drsuapi
.DRSUAPI_DRS_WRIT_REP
307 req_options |
= drsuapi
.DRSUAPI_DRS_ADD_REF
309 req_options |
= drsuapi
.DRSUAPI_DRS_SYNC_FORCED
311 req_options |
= drsuapi
.DRSUAPI_DRS_SYNC_ALL
313 req_options |
= drsuapi
.DRSUAPI_DRS_FULL_SYNC_NOW
316 drs_utils
.sendDsReplicaSync(self
.drsuapi
, self
.drsuapi_handle
, source_dsa_guid
, NC
, req_options
)
317 except drs_utils
.drsException
, estr
:
318 raise CommandError("DsReplicaSync failed", estr
)
319 self
.message("Replicate from %s to %s was successful." % (SOURCE_DC
, DEST_DC
))
323 class cmd_drs_bind(Command
):
324 """show DRS capabilities of a server"""
326 synopsis
= "%prog [<DC>] [options]"
330 def run(self
, DC
=None, sambaopts
=None,
331 credopts
=None, versionopts
=None, server
=None):
333 self
.lp
= sambaopts
.get_loadparm()
335 DC
= common
.netcmd_dnsname(self
.lp
)
337 self
.creds
= credopts
.get_credentials(self
.lp
, fallback_machine
=True)
339 drsuapi_connect(self
)
342 bind_info
= drsuapi
.DsBindInfoCtr()
343 bind_info
.length
= 28
344 bind_info
.info
= drsuapi
.DsBindInfo28()
345 (info
, handle
) = self
.drsuapi
.DsBind(misc
.GUID(drsuapi
.DRSUAPI_DS_BIND_GUID
), bind_info
)
348 ("DRSUAPI_SUPPORTED_EXTENSION_BASE", "DRS_EXT_BASE"),
349 ("DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION", "DRS_EXT_ASYNCREPL"),
350 ("DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI", "DRS_EXT_REMOVEAPI"),
351 ("DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2", "DRS_EXT_MOVEREQ_V2"),
352 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS", "DRS_EXT_GETCHG_DEFLATE"),
353 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1", "DRS_EXT_DCINFO_V1"),
354 ("DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION", "DRS_EXT_RESTORE_USN_OPTIMIZATION"),
355 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY", "DRS_EXT_ADDENTRY"),
356 ("DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE", "DRS_EXT_KCC_EXECUTE"),
357 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2", "DRS_EXT_ADDENTRY_V2"),
358 ("DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION", "DRS_EXT_LINKED_VALUE_REPLICATION"),
359 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2", "DRS_EXT_DCINFO_V2"),
360 ("DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD","DRS_EXT_INSTANCE_TYPE_NOT_REQ_ON_MOD"),
361 ("DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND", "DRS_EXT_CRYPTO_BIND"),
362 ("DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO", "DRS_EXT_GET_REPL_INFO"),
363 ("DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION", "DRS_EXT_STRONG_ENCRYPTION"),
364 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01", "DRS_EXT_DCINFO_VFFFFFFFF"),
365 ("DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP", "DRS_EXT_TRANSITIVE_MEMBERSHIP"),
366 ("DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY", "DRS_EXT_ADD_SID_HISTORY"),
367 ("DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3", "DRS_EXT_POST_BETA3"),
368 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V5", "DRS_EXT_GETCHGREQ_V5"),
369 ("DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2", "DRS_EXT_GETMEMBERSHIPS2"),
370 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6", "DRS_EXT_GETCHGREQ_V6"),
371 ("DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS", "DRS_EXT_NONDOMAIN_NCS"),
372 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8", "DRS_EXT_GETCHGREQ_V8"),
373 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5", "DRS_EXT_GETCHGREPLY_V5"),
374 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6", "DRS_EXT_GETCHGREPLY_V6"),
375 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3", "DRS_EXT_WHISTLER_BETA3"),
376 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7", "DRS_EXT_WHISTLER_BETA3"),
377 ("DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT", "DRS_EXT_WHISTLER_BETA3"),
378 ("DRSUAPI_SUPPORTED_EXTENSION_XPRESS_COMPRESS", "DRS_EXT_W2K3_DEFLATE"),
379 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10", "DRS_EXT_GETCHGREQ_V10"),
380 ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART2", "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART2"),
381 ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART3", "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART3")
385 ("DRSUAPI_SUPPORTED_EXTENSION_ADAM", "DRS_EXT_ADAM"),
386 ("DRSUAPI_SUPPORTED_EXTENSION_LH_BETA2", "DRS_EXT_LH_BETA2"),
387 ("DRSUAPI_SUPPORTED_EXTENSION_RECYCLE_BIN", "DRS_EXT_RECYCLE_BIN")]
389 self
.message("Bind to %s succeeded." % DC
)
390 self
.message("Extensions supported:")
391 for (opt
, str) in optmap
:
392 optval
= getattr(drsuapi
, opt
, 0)
393 if info
.info
.supported_extensions
& optval
:
397 self
.message(" %-60s: %s (%s)" % (opt
, yesno
, str))
399 if isinstance(info
.info
, drsuapi
.DsBindInfo48
):
400 self
.message("\nExtended Extensions supported:")
401 for (opt
, str) in optmap_ext
:
402 optval
= getattr(drsuapi
, opt
, 0)
403 if info
.info
.supported_extensions_ext
& optval
:
407 self
.message(" %-60s: %s (%s)" % (opt
, yesno
, str))
409 self
.message("\nSite GUID: %s" % info
.info
.site_guid
)
410 self
.message("Repl epoch: %u" % info
.info
.repl_epoch
)
411 if isinstance(info
.info
, drsuapi
.DsBindInfo48
):
412 self
.message("Forest GUID: %s" % info
.info
.config_dn_guid
)
416 class cmd_drs_options(Command
):
417 """query or change 'options' for NTDS Settings object of a domain controller"""
419 synopsis
= "%prog [<DC>] [options]"
424 Option("--dsa-option", help="DSA option to enable/disable", type="str",
425 metavar
="{+|-}IS_GC | {+|-}DISABLE_INBOUND_REPL | {+|-}DISABLE_OUTBOUND_REPL | {+|-}DISABLE_NTDSCONN_XLATE" ),
428 option_map
= {"IS_GC": 0x00000001,
429 "DISABLE_INBOUND_REPL": 0x00000002,
430 "DISABLE_OUTBOUND_REPL": 0x00000004,
431 "DISABLE_NTDSCONN_XLATE": 0x00000008}
433 def run(self
, DC
=None, dsa_option
=None,
434 sambaopts
=None, credopts
=None, versionopts
=None):
436 self
.lp
= sambaopts
.get_loadparm()
438 DC
= common
.netcmd_dnsname(self
.lp
)
440 self
.creds
= credopts
.get_credentials(self
.lp
, fallback_machine
=True)
444 ntds_dn
= self
.samdb
.get_dsServiceName()
445 res
= self
.samdb
.search(base
=ntds_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=["options"])
446 dsa_opts
= int(res
[0]["options"][0])
448 # print out current DSA options
449 cur_opts
= [x
for x
in self
.option_map
if self
.option_map
[x
] & dsa_opts
]
450 self
.message("Current DSA options: " + ", ".join(cur_opts
))
454 if dsa_option
[:1] not in ("+", "-"):
455 raise CommandError("Unknown option %s" % dsa_option
)
456 flag
= dsa_option
[1:]
457 if flag
not in self
.option_map
.keys():
458 raise CommandError("Unknown option %s" % dsa_option
)
459 if dsa_option
[:1] == "+":
460 dsa_opts |
= self
.option_map
[flag
]
462 dsa_opts
&= ~self
.option_map
[flag
]
465 m
.dn
= ldb
.Dn(self
.samdb
, ntds_dn
)
466 m
["options"]= ldb
.MessageElement(str(dsa_opts
), ldb
.FLAG_MOD_REPLACE
, "options")
468 # print out new DSA options
469 cur_opts
= [x
for x
in self
.option_map
if self
.option_map
[x
] & dsa_opts
]
470 self
.message("New DSA options: " + ", ".join(cur_opts
))
473 class cmd_drs(SuperCommand
):
474 """Directory Replication Services (DRS) management"""
477 subcommands
["bind"] = cmd_drs_bind()
478 subcommands
["kcc"] = cmd_drs_kcc()
479 subcommands
["replicate"] = cmd_drs_replicate()
480 subcommands
["showrepl"] = cmd_drs_showrepl()
481 subcommands
["options"] = cmd_drs_options()