3 # implement samba_tool drs commands
5 # Copyright Andrew Tridgell 2010
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program. If not, see <http://www.gnu.org/licenses/>.
21 import samba
.getopt
as options
24 from samba
.auth
import system_session
25 from samba
.netcmd
import (
31 from samba
.samdb
import SamDB
32 from samba
import drs_utils
, nttime2string
, dsdb
33 from samba
.dcerpc
import drsuapi
, misc
36 def drsuapi_connect(ctx
):
37 '''make a DRSUAPI connection to the server'''
38 binding_options
= "seal"
39 if ctx
.lp
.get("log level") >= 5:
40 binding_options
+= ",print"
41 binding_string
= "ncacn_ip_tcp:%s[%s]" % (ctx
.server
, binding_options
)
43 ctx
.drsuapi
= drsuapi
.drsuapi(binding_string
, ctx
.lp
, ctx
.creds
)
44 (ctx
.drsuapi_handle
, ctx
.bind_supported_extensions
) = drs_utils
.drs_DsBind(ctx
.drsuapi
)
45 except Exception, estr
:
46 raise CommandError("DRS connection to %s failed - %s" % (ctx
.server
, estr
))
49 def samdb_connect(ctx
):
50 '''make a ldap connection to the server'''
52 ctx
.samdb
= SamDB(url
="ldap://%s" % ctx
.server
,
53 session_info
=system_session(),
54 credentials
=ctx
.creds
, lp
=ctx
.lp
)
55 except Exception, estr
:
56 raise CommandError("LDAP connection to %s failed - %s" % (ctx
.server
, estr
))
60 '''return "was successful" or an error string'''
61 (ecode
, estring
) = werr
63 return "was successful"
64 return "failed, result %u (%s)" % (ecode
, estring
)
67 def attr_default(msg
, attrname
, default
):
68 '''get an attribute from a ldap msg with a default'''
70 return msg
[attrname
][0]
74 def drs_parse_ntds_dn(ntds_dn
):
75 '''parse a NTDS DN returning a site and server'''
76 a
= ntds_dn
.split(',')
77 if a
[0] != "CN=NTDS Settings" or a
[2] != "CN=Servers" or a
[4] != 'CN=Sites':
78 raise RuntimeError("bad NTDS DN %s" % ntds_dn
)
79 server
= a
[1].split('=')[1]
80 site
= a
[3].split('=')[1]
84 class cmd_drs_showrepl(Command
):
85 """show replication status"""
87 synopsis
= "%prog drs showrepl <DC>"
89 takes_optiongroups
= {
90 "sambaopts": options
.SambaOptions
,
91 "versionopts": options
.VersionOptions
,
92 "credopts": options
.CredentialsOptions
,
97 def print_neighbour(self
, n
):
98 '''print one set of neighbour information'''
99 (site
, server
) = drs_parse_ntds_dn(n
.source_dsa_obj_dn
)
100 print("%s" % n
.naming_context_dn
)
101 print("\t%s\%s via RPC" % (site
, server
))
102 print("\t\tDSA object GUID: %s" % n
.source_dsa_obj_guid
)
103 print("\t\tLast attempt @ %s %s" % (nttime2string(n
.last_attempt
), drs_errmsg(n
.result_last_attempt
)))
104 print("\t\t%u consecutive failure(s)." % n
.consecutive_sync_failures
)
105 print("\t\tLast success @ %s" % nttime2string(n
.last_success
))
108 def get_dsServiceName(ctx
):
109 '''get the NTDS DN from the rootDSE'''
110 res
= ctx
.samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dsServiceName"])
111 return res
[0]["dsServiceName"][0]
113 def drsuapi_ReplicaInfo(ctx
, info_type
):
114 '''call a DsReplicaInfo'''
116 req1
= drsuapi
.DsReplicaGetInfoRequest1()
117 req1
.info_type
= info_type
119 (info_type
, info
) = ctx
.drsuapi
.DsReplicaGetInfo(ctx
.drsuapi_handle
, 1, req1
)
120 except Exception, estr
:
121 raise CommandError("DsReplicaGetInfo failed : %s" % estr
)
122 return (info_type
, info
)
125 def run(self
, DC
, sambaopts
=None,
126 credopts
=None, versionopts
=None, server
=None):
129 self
.lp
= sambaopts
.get_loadparm()
131 self
.creds
= credopts
.get_credentials(self
.lp
)
132 if not self
.creds
.authentication_requested():
133 self
.creds
.set_machine_account(self
.lp
)
135 drsuapi_connect(self
)
138 # show domain information
139 ntds_dn
= self
.get_dsServiceName()
140 server_dns
= self
.samdb
.search(base
="", scope
=ldb
.SCOPE_BASE
, attrs
=["dnsHostName"])[0]['dnsHostName'][0]
142 (site
, server
) = drs_parse_ntds_dn(ntds_dn
)
143 ntds
= self
.samdb
.search(base
=ntds_dn
, scope
=ldb
.SCOPE_BASE
, attrs
=['options', 'objectGUID', 'invocationId'])
144 conn
= self
.samdb
.search(base
=ntds_dn
, expression
="(objectClass=nTDSConnection)")
146 print("%s\\%s" % (site
, server
))
147 print("DSA Options: 0x%08x" % int(ntds
[0]["options"][0]))
148 print("DSA object GUID: %s" % self
.samdb
.schema_format_value("objectGUID", ntds
[0]["objectGUID"][0]))
149 print("DSA invocationId: %s\n" % self
.samdb
.schema_format_value("objectGUID", ntds
[0]["invocationId"][0]))
151 print("==== INBOUND NEIGHBORS ====\n")
152 (info_type
, info
) = self
.drsuapi_ReplicaInfo(drsuapi
.DRSUAPI_DS_REPLICA_INFO_NEIGHBORS
)
154 self
.print_neighbour(n
)
157 print("==== OUTBOUND NEIGHBORS ====\n")
158 (info_type
, info
) = self
.drsuapi_ReplicaInfo(drsuapi
.DRSUAPI_DS_REPLICA_INFO_REPSTO
)
160 self
.print_neighbour(n
)
162 reasons
= ['NTDSCONN_KCC_GC_TOPOLOGY',
163 'NTDSCONN_KCC_RING_TOPOLOGY',
164 'NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY',
165 'NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY',
166 'NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY',
167 'NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY',
168 'NTDSCONN_KCC_INTERSITE_TOPOLOGY',
169 'NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY',
170 'NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY',
171 'NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY']
173 print("==== KCC CONNECTION OBJECTS ====\n")
175 print("Connection --")
176 print("\tConnection name: %s" % c
['name'][0])
177 print("\tEnabled : %s" % attr_default(c
, 'enabledConnection', 'TRUE'))
178 print("\tServer DNS name : %s" % server_dns
)
179 print("\tServer DN name : %s" % c
['fromServer'][0])
180 print("\t\tTransportType: RPC")
181 print("\t\toptions: 0x%08X" % int(attr_default(c
, 'options', 0)))
182 if not 'mS-DS-ReplicatesNCReason' in c
:
183 print("Warning: No NC replicated for Connection!")
185 for r
in c
['mS-DS-ReplicatesNCReason']:
186 a
= str(r
).split(':')
187 print("\t\tReplicatesNC: %s" % a
[3])
188 print("\t\tReason: 0x%08x" % int(a
[2]))
190 if getattr(dsdb
, s
, 0) & int(a
[2]):
191 print("\t\t\t%s" % s
)
194 class cmd_drs_kcc(Command
):
195 """trigger knowledge consistency center run"""
197 synopsis
= "%prog drs kcc <DC>"
199 takes_optiongroups
= {
200 "sambaopts": options
.SambaOptions
,
201 "versionopts": options
.VersionOptions
,
202 "credopts": options
.CredentialsOptions
,
207 def run(self
, DC
, sambaopts
=None,
208 credopts
=None, versionopts
=None, server
=None):
211 self
.lp
= sambaopts
.get_loadparm()
213 self
.creds
= credopts
.get_credentials(self
.lp
)
214 if not self
.creds
.authentication_requested():
215 self
.creds
.set_machine_account(self
.lp
)
217 drsuapi_connect(self
)
219 req1
= drsuapi
.DsExecuteKCC1()
221 self
.drsuapi
.DsExecuteKCC(self
.drsuapi_handle
, 1, req1
)
222 except Exception, (ecode
, estr
):
223 raise CommandError("DsExecuteKCC failed - %s" % estr
)
224 print("Consistency check on %s successful." % DC
)
228 class cmd_drs_replicate(Command
):
229 """replicate a naming context between two DCs"""
231 synopsis
= "%prog drs replicate <DEST_DC> <SOURCE_DC> <NC>"
233 takes_optiongroups
= {
234 "sambaopts": options
.SambaOptions
,
235 "versionopts": options
.VersionOptions
,
236 "credopts": options
.CredentialsOptions
,
239 takes_args
= ["DEST_DC", "SOURCE_DC", "NC"]
242 Option("--add-ref", help="use ADD_REF to add to repsTo on source", action
="store_true"),
245 def run(self
, DEST_DC
, SOURCE_DC
, NC
, add_ref
=False,
247 credopts
=None, versionopts
=None, server
=None):
249 self
.server
= DEST_DC
250 self
.lp
= sambaopts
.get_loadparm()
252 self
.creds
= credopts
.get_credentials(self
.lp
)
253 if not self
.creds
.authentication_requested():
254 self
.creds
.set_machine_account(self
.lp
)
256 drsuapi_connect(self
)
259 # we need to find the NTDS GUID of the source DC
260 msg
= self
.samdb
.search(base
=self
.samdb
.get_config_basedn(),
261 expression
="(&(objectClass=server)(|(name=%s)(dNSHostName=%s)))" % (SOURCE_DC
,
265 raise CommandError("Failed to find source DC %s" % SOURCE_DC
)
266 server_dn
= msg
[0]['dn']
268 msg
= self
.samdb
.search(base
=server_dn
, scope
=ldb
.SCOPE_ONELEVEL
,
269 expression
="(objectClass=nTDSDSA)",
270 attrs
=['objectGUID', 'options'])
272 raise CommandError("Failed to find source NTDS DN %s" % SOURCE_DC
)
273 source_dsa_guid
= msg
[0]['objectGUID'][0]
274 options
= int(attr_default(msg
, 'options', 0))
276 nc
= drsuapi
.DsReplicaObjectIdentifier()
279 req1
= drsuapi
.DsReplicaSyncRequest1()
280 req1
.naming_context
= nc
;
282 if not (options
& dsdb
.DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL
):
283 req1
.options |
= drsuapi
.DRSUAPI_DRS_WRIT_REP
285 req1
.options |
= drsuapi
.DRSUAPI_DRS_ADD_REF
286 req1
.source_dsa_guid
= misc
.GUID(source_dsa_guid
)
289 self
.drsuapi
.DsReplicaSync(self
.drsuapi_handle
, 1, req1
)
290 except Exception, (ecode
, estr
):
291 raise CommandError("DsReplicaSync failed - %s" % estr
)
292 print("Replicate from %s to %s was successful." % (SOURCE_DC
, DEST_DC
))
296 class cmd_drs_bind(Command
):
297 """show DRS capabilities of a server"""
299 synopsis
= "%prog drs bind <DC>"
301 takes_optiongroups
= {
302 "sambaopts": options
.SambaOptions
,
303 "versionopts": options
.VersionOptions
,
304 "credopts": options
.CredentialsOptions
,
309 def run(self
, DC
, sambaopts
=None,
310 credopts
=None, versionopts
=None, server
=None):
313 self
.lp
= sambaopts
.get_loadparm()
315 self
.creds
= credopts
.get_credentials(self
.lp
)
316 if not self
.creds
.authentication_requested():
317 self
.creds
.set_machine_account(self
.lp
)
319 drsuapi_connect(self
)
322 bind_info
= drsuapi
.DsBindInfoCtr()
323 bind_info
.length
= 28
324 bind_info
.info
= drsuapi
.DsBindInfo28()
325 (info
, handle
) = self
.drsuapi
.DsBind(misc
.GUID(drsuapi
.DRSUAPI_DS_BIND_GUID
), bind_info
)
328 ("DRSUAPI_SUPPORTED_EXTENSION_BASE" , "DRS_EXT_BASE"),
329 ("DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION" , "DRS_EXT_ASYNCREPL"),
330 ("DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI" , "DRS_EXT_REMOVEAPI"),
331 ("DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2" , "DRS_EXT_MOVEREQ_V2"),
332 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS" , "DRS_EXT_GETCHG_DEFLATE"),
333 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1" , "DRS_EXT_DCINFO_V1"),
334 ("DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION" , "DRS_EXT_RESTORE_USN_OPTIMIZATION"),
335 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY" , "DRS_EXT_ADDENTRY"),
336 ("DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE" , "DRS_EXT_KCC_EXECUTE"),
337 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2" , "DRS_EXT_ADDENTRY_V2"),
338 ("DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION" , "DRS_EXT_LINKED_VALUE_REPLICATION"),
339 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2" , "DRS_EXT_DCINFO_V2"),
340 ("DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD","DRS_EXT_INSTANCE_TYPE_NOT_REQ_ON_MOD"),
341 ("DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND" , "DRS_EXT_CRYPTO_BIND"),
342 ("DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO" , "DRS_EXT_GET_REPL_INFO"),
343 ("DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION" , "DRS_EXT_STRONG_ENCRYPTION"),
344 ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01" , "DRS_EXT_DCINFO_VFFFFFFFF"),
345 ("DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP" , "DRS_EXT_TRANSITIVE_MEMBERSHIP"),
346 ("DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY" , "DRS_EXT_ADD_SID_HISTORY"),
347 ("DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3" , "DRS_EXT_POST_BETA3"),
348 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V5" , "DRS_EXT_GETCHGREQ_V5"),
349 ("DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2" , "DRS_EXT_GETMEMBERSHIPS2"),
350 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6" , "DRS_EXT_GETCHGREQ_V6"),
351 ("DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS" , "DRS_EXT_NONDOMAIN_NCS"),
352 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8" , "DRS_EXT_GETCHGREQ_V8"),
353 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5" , "DRS_EXT_GETCHGREPLY_V5"),
354 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6" , "DRS_EXT_GETCHGREPLY_V6"),
355 ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3" , "DRS_EXT_WHISTLER_BETA3"),
356 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7" , "DRS_EXT_WHISTLER_BETA3"),
357 ("DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT" , "DRS_EXT_WHISTLER_BETA3"),
358 ("DRSUAPI_SUPPORTED_EXTENSION_XPRESS_COMPRESS" , "DRS_EXT_W2K3_DEFLATE"),
359 ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10" , "DRS_EXT_GETCHGREQ_V10"),
360 ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART2" , "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART2"),
361 ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART3" , "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART3")
365 ("DRSUAPI_SUPPORTED_EXTENSION_ADAM", "DRS_EXT_ADAM"),
366 ("DRSUAPI_SUPPORTED_EXTENSION_LH_BETA2", "DRS_EXT_LH_BETA2"),
367 ("DRSUAPI_SUPPORTED_EXTENSION_RECYCLE_BIN", "DRS_EXT_RECYCLE_BIN")]
369 print("Bind to %s succeeded." % DC
)
370 print("Extensions supported:")
371 for (opt
, str) in optmap
:
372 optval
= getattr(drsuapi
, opt
, 0)
373 if info
.info
.supported_extensions
& optval
:
377 print(" %-60s: %s (%s)" % (opt
, yesno
, str))
379 if isinstance(info
.info
, drsuapi
.DsBindInfo48
):
380 print("\nExtended Extensions supported:")
381 for (opt
, str) in optmap_ext
:
382 optval
= getattr(drsuapi
, opt
, 0)
383 if info
.info
.supported_extensions_ext
& optval
:
387 print(" %-60s: %s (%s)" % (opt
, yesno
, str))
389 print("\nSite GUID: %s" % info
.info
.site_guid
)
390 print("Repl epoch: %u" % info
.info
.repl_epoch
)
391 if isinstance(info
.info
, drsuapi
.DsBindInfo48
):
392 print("Forest GUID: %s" % info
.info
.config_dn_guid
)
395 class cmd_drs(SuperCommand
):
399 subcommands
["bind"] = cmd_drs_bind()
400 subcommands
["kcc"] = cmd_drs_kcc()
401 subcommands
["replicate"] = cmd_drs_replicate()
402 subcommands
["showrepl"] = cmd_drs_showrepl()