samba-tool/drs: do partial replication when --local is given by default
[nivanova/samba-autobuild/.git] / python / samba / netcmd / drs.py
1 # implement samba_tool drs commands
2 #
3 # Copyright Andrew Tridgell 2010
4 # Copyright Andrew Bartlett 2017
5 #
6 # based on C implementation by Kamen Mazdrashki <kamen.mazdrashki@postpath.com>
7 #
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.
12 #
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.
17 #
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/>.
20 #
21
22 import samba.getopt as options
23 import ldb
24 import logging
25 import common
26
27 from samba.auth import system_session
28 from samba.netcmd import (
29     Command,
30     CommandError,
31     Option,
32     SuperCommand,
33     )
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
41 def drsuapi_connect(ctx):
42     '''make a DRSUAPI connection to the server'''
43     try:
44         (ctx.drsuapi, ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drsuapi_connect(ctx.server, ctx.lp, ctx.creds)
45     except Exception, e:
46         raise CommandError("DRS connection to %s failed" % ctx.server, e)
47
48 def samdb_connect(ctx):
49     '''make a ldap connection to the server'''
50     try:
51         ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
52                           session_info=system_session(),
53                           credentials=ctx.creds, lp=ctx.lp)
54     except Exception, e:
55         raise CommandError("LDAP connection to %s failed" % ctx.server, e)
56
57 def drs_errmsg(werr):
58     '''return "was successful" or an error string'''
59     (ecode, estring) = werr
60     if ecode == 0:
61         return "was successful"
62     return "failed, result %u (%s)" % (ecode, estring)
63
64
65
66 def attr_default(msg, attrname, default):
67     '''get an attribute from a ldap msg with a default'''
68     if attrname in msg:
69         return msg[attrname][0]
70     return default
71
72
73
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]
81     return (site, server)
82
83
84
85
86
87 class cmd_drs_showrepl(Command):
88     """Show replication status."""
89
90     synopsis = "%prog [<DC>] [options]"
91
92     takes_optiongroups = {
93         "sambaopts": options.SambaOptions,
94         "versionopts": options.VersionOptions,
95         "credopts": options.CredentialsOptions,
96     }
97
98     takes_args = ["DC?"]
99
100     def print_neighbour(self, n):
101         '''print one set of neighbour information'''
102         self.message("%s" % n.naming_context_dn)
103         try:
104             (site, server) = drs_parse_ntds_dn(n.source_dsa_obj_dn)
105             self.message("\t%s\%s via RPC" % (site, server))
106         except RuntimeError:
107             self.message("\tNTDS DN: %s" % n.source_dsa_obj_dn)
108         self.message("\t\tDSA object GUID: %s" % n.source_dsa_obj_guid)
109         self.message("\t\tLast attempt @ %s %s" % (nttime2string(n.last_attempt),
110                                                    drs_errmsg(n.result_last_attempt)))
111         self.message("\t\t%u consecutive failure(s)." % n.consecutive_sync_failures)
112         self.message("\t\tLast success @ %s" % nttime2string(n.last_success))
113         self.message("")
114
115     def drsuapi_ReplicaInfo(ctx, info_type):
116         '''call a DsReplicaInfo'''
117
118         req1 = drsuapi.DsReplicaGetInfoRequest1()
119         req1.info_type = info_type
120         try:
121             (info_type, info) = ctx.drsuapi.DsReplicaGetInfo(ctx.drsuapi_handle, 1, req1)
122         except Exception, e:
123             raise CommandError("DsReplicaGetInfo of type %u failed" % info_type, e)
124         return (info_type, info)
125
126     def run(self, DC=None, sambaopts=None,
127             credopts=None, versionopts=None, server=None):
128
129         self.lp = sambaopts.get_loadparm()
130         if DC is None:
131             DC = common.netcmd_dnsname(self.lp)
132         self.server = DC
133         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
134
135         drsuapi_connect(self)
136         samdb_connect(self)
137
138         # show domain information
139         ntds_dn = self.samdb.get_dsServiceName()
140         server_dns = self.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])[0]['dnsHostName'][0]
141
142         (site, server) = drs_parse_ntds_dn(ntds_dn)
143         try:
144             ntds = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=['options', 'objectGUID', 'invocationId'])
145         except Exception, e:
146             raise CommandError("Failed to search NTDS DN %s" % ntds_dn)
147         conn = self.samdb.search(base=ntds_dn, expression="(objectClass=nTDSConnection)")
148
149         self.message("%s\\%s" % (site, server))
150         self.message("DSA Options: 0x%08x" % int(attr_default(ntds[0], "options", 0)))
151         self.message("DSA object GUID: %s" % self.samdb.schema_format_value("objectGUID", ntds[0]["objectGUID"][0]))
152         self.message("DSA invocationId: %s\n" % self.samdb.schema_format_value("objectGUID", ntds[0]["invocationId"][0]))
153
154         self.message("==== INBOUND NEIGHBORS ====\n")
155         (info_type, info) = self.drsuapi_ReplicaInfo(drsuapi.DRSUAPI_DS_REPLICA_INFO_NEIGHBORS)
156         for n in info.array:
157             self.print_neighbour(n)
158
159
160         self.message("==== OUTBOUND NEIGHBORS ====\n")
161         (info_type, info) = self.drsuapi_ReplicaInfo(drsuapi.DRSUAPI_DS_REPLICA_INFO_REPSTO)
162         for n in info.array:
163             self.print_neighbour(n)
164
165         reasons = ['NTDSCONN_KCC_GC_TOPOLOGY',
166                    'NTDSCONN_KCC_RING_TOPOLOGY',
167                    'NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY',
168                    'NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY',
169                    'NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY',
170                    'NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY',
171                    'NTDSCONN_KCC_INTERSITE_TOPOLOGY',
172                    'NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY',
173                    'NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY',
174                    'NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY']
175
176         self.message("==== KCC CONNECTION OBJECTS ====\n")
177         for c in conn:
178             self.message("Connection --")
179
180             c_rdn, sep, c_server_dn = c['fromServer'][0].partition(',')
181             try:
182                 c_server_res = self.samdb.search(base=c_server_dn, scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])
183                 c_server_dns = c_server_res[0]["dnsHostName"][0]
184             except ldb.LdbError, (errno, _):
185                 if errno == ldb.ERR_NO_SUCH_OBJECT:
186                     self.message("\tWARNING: Connection to DELETED server!")
187                 c_server_dns = ""
188             except KeyError:
189                 c_server_dns = ""
190
191             self.message("\tConnection name: %s" % c['name'][0])
192             self.message("\tEnabled        : %s" % attr_default(c, 'enabledConnection', 'TRUE'))
193             self.message("\tServer DNS name : %s" % c_server_dns)
194             self.message("\tServer DN name  : %s" % c['fromServer'][0])
195             self.message("\t\tTransportType: RPC")
196             self.message("\t\toptions: 0x%08X" % int(attr_default(c, 'options', 0)))
197             if not 'mS-DS-ReplicatesNCReason' in c:
198                 self.message("Warning: No NC replicated for Connection!")
199                 continue
200             for r in c['mS-DS-ReplicatesNCReason']:
201                 a = str(r).split(':')
202                 self.message("\t\tReplicatesNC: %s" % a[3])
203                 self.message("\t\tReason: 0x%08x" % int(a[2]))
204                 for s in reasons:
205                     if getattr(dsdb, s, 0) & int(a[2]):
206                         self.message("\t\t\t%s" % s)
207
208
209
210 class cmd_drs_kcc(Command):
211     """Trigger knowledge consistency center run."""
212
213     synopsis = "%prog [<DC>] [options]"
214
215     takes_optiongroups = {
216         "sambaopts": options.SambaOptions,
217         "versionopts": options.VersionOptions,
218         "credopts": options.CredentialsOptions,
219     }
220
221     takes_args = ["DC?"]
222
223     def run(self, DC=None, sambaopts=None,
224             credopts=None, versionopts=None, server=None):
225
226         self.lp = sambaopts.get_loadparm()
227         if DC is None:
228             DC = common.netcmd_dnsname(self.lp)
229         self.server = DC
230
231         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
232
233         drsuapi_connect(self)
234
235         req1 = drsuapi.DsExecuteKCC1()
236         try:
237             self.drsuapi.DsExecuteKCC(self.drsuapi_handle, 1, req1)
238         except Exception, e:
239             raise CommandError("DsExecuteKCC failed", e)
240         self.message("Consistency check on %s successful." % DC)
241
242
243
244 def drs_local_replicate(self, SOURCE_DC, NC, full_sync=False):
245     '''replicate from a source DC to the local SAM'''
246
247     self.server = SOURCE_DC
248     drsuapi_connect(self)
249
250     self.local_samdb = SamDB(session_info=system_session(), url=None,
251                              credentials=self.creds, lp=self.lp)
252
253     self.samdb = SamDB(url="ldap://%s" % self.server,
254                        session_info=system_session(),
255                        credentials=self.creds, lp=self.lp)
256
257     # work out the source and destination GUIDs
258     res = self.local_samdb.search(base="", scope=ldb.SCOPE_BASE,
259                                   attrs=["dsServiceName"])
260     self.ntds_dn = res[0]["dsServiceName"][0]
261
262     res = self.local_samdb.search(base=self.ntds_dn, scope=ldb.SCOPE_BASE,
263                                   attrs=["objectGUID"])
264     self.ntds_guid = misc.GUID(self.samdb.schema_format_value("objectGUID", res[0]["objectGUID"][0]))
265
266     source_dsa_invocation_id = misc.GUID(self.samdb.get_invocation_id())
267     dest_dsa_invocation_id = misc.GUID(self.local_samdb.get_invocation_id())
268     destination_dsa_guid = self.ntds_guid
269
270     # If we can't find an upToDateVector, replicate fully
271     hwm = drsuapi.DsReplicaHighWaterMark()
272     hwm.tmp_highest_usn = 0
273     hwm.reserved_usn = 0
274     hwm.highest_usn = 0
275
276     udv = None
277     if not full_sync:
278         res = self.local_samdb.search(base=NC, scope=ldb.SCOPE_BASE,
279                                       attrs=["repsFrom"])
280         if "repsFrom" in res[0]:
281             for reps_from_packed in res[0]["repsFrom"]:
282                 reps_from_obj = ndr_unpack(drsblobs.repsFromToBlob, reps_from_packed)
283                 if reps_from_obj.ctr.source_dsa_invocation_id == source_dsa_invocation_id:
284                     hwm = reps_from_obj.ctr.highwatermark
285
286         udv = drsuapi.DsReplicaCursorCtrEx()
287         udv.version = 1
288         udv.reserved1 = 0
289         udv.reserved2 = 0
290
291         cursors_v1 = []
292         cursors_v2 = dsdb._dsdb_load_udv_v2(self.local_samdb,
293                                             self.local_samdb.get_default_basedn())
294         for cursor_v2 in cursors_v2:
295             cursor_v1 = drsuapi.DsReplicaCursor()
296             cursor_v1.source_dsa_invocation_id = cursor_v2.source_dsa_invocation_id
297             cursor_v1.highest_usn = cursor_v2.highest_usn
298             cursors_v1.append(cursor_v1)
299
300         udv.cursors = cursors_v1
301         udv.count = len(cursors_v1)
302
303     self.samdb.transaction_start()
304     repl = drs_utils.drs_Replicate("ncacn_ip_tcp:%s[seal]" % self.server, self.lp,
305                                    self.creds, self.local_samdb, dest_dsa_invocation_id)
306
307     # Work out if we are an RODC, so that a forced local replicate
308     # with the admin pw does not sync passwords
309     rodc = self.local_samdb.am_rodc()
310     try:
311         (num_objects, num_links) = repl.replicate(NC,
312                                                   source_dsa_invocation_id, destination_dsa_guid,
313                                                   rodc=rodc, highwatermark=hwm, udv=udv)
314     except Exception, e:
315         raise CommandError("Error replicating DN %s" % NC, e)
316     self.samdb.transaction_commit()
317
318     if full_sync:
319         self.message("Full Replication of all %d objects and %d links from %s to %s was successful."
320                      % (num_objects, num_links, SOURCE_DC, self.local_samdb.url))
321     else:
322         self.message("Incremental replication of %d objects and %d links from %s to %s was successful."
323                      % (num_objects, num_links, SOURCE_DC, self.local_samdb.url))
324
325
326 class cmd_drs_replicate(Command):
327     """Replicate a naming context between two DCs."""
328
329     synopsis = "%prog <destinationDC> <sourceDC> <NC> [options]"
330
331     takes_optiongroups = {
332         "sambaopts": options.SambaOptions,
333         "versionopts": options.VersionOptions,
334         "credopts": options.CredentialsOptions,
335     }
336
337     takes_args = ["DEST_DC", "SOURCE_DC", "NC"]
338
339     takes_options = [
340         Option("--add-ref", help="use ADD_REF to add to repsTo on source", action="store_true"),
341         Option("--sync-forced", help="use SYNC_FORCED to force inbound replication", action="store_true"),
342         Option("--sync-all", help="use SYNC_ALL to replicate from all DCs", action="store_true"),
343         Option("--full-sync", help="resync all objects", action="store_true"),
344         Option("--local", help="pull changes directly into the local database (destination DC is ignored)", action="store_true"),
345         Option("--local-online", help="pull changes into the local database (destination DC is ignored) as a normal online replication", action="store_true"),
346         Option("--async-op", help="use ASYNC_OP for the replication", action="store_true"),
347         ]
348
349     def run(self, DEST_DC, SOURCE_DC, NC,
350             add_ref=False, sync_forced=False, sync_all=False, full_sync=False,
351             local=False, local_online=False, async_op=False,
352             sambaopts=None, credopts=None, versionopts=None, server=None):
353
354         self.server = DEST_DC
355         self.lp = sambaopts.get_loadparm()
356
357         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
358
359         if local:
360             drs_local_replicate(self, SOURCE_DC, NC, full_sync=full_sync)
361             return
362
363         if local_online:
364             server_bind = drsuapi.drsuapi("irpc:dreplsrv", lp_ctx=self.lp)
365             server_bind_handle = misc.policy_handle()
366         else:
367             drsuapi_connect(self)
368             server_bind = self.drsuapi
369             server_bind_handle = self.drsuapi_handle
370
371         if not async_op:
372             # Give the sync replication 5 minutes time
373             server_bind.request_timeout = 5 * 60
374
375         samdb_connect(self)
376
377         # we need to find the NTDS GUID of the source DC
378         msg = self.samdb.search(base=self.samdb.get_config_basedn(),
379                                 expression="(&(objectCategory=server)(|(name=%s)(dNSHostName=%s)))" % (
380             ldb.binary_encode(SOURCE_DC),
381             ldb.binary_encode(SOURCE_DC)),
382                                 attrs=[])
383         if len(msg) == 0:
384             raise CommandError("Failed to find source DC %s" % SOURCE_DC)
385         server_dn = msg[0]['dn']
386
387         msg = self.samdb.search(base=server_dn, scope=ldb.SCOPE_ONELEVEL,
388                                 expression="(|(objectCategory=nTDSDSA)(objectCategory=nTDSDSARO))",
389                                 attrs=['objectGUID', 'options'])
390         if len(msg) == 0:
391             raise CommandError("Failed to find source NTDS DN %s" % SOURCE_DC)
392         source_dsa_guid = msg[0]['objectGUID'][0]
393         dsa_options = int(attr_default(msg, 'options', 0))
394
395
396         req_options = 0
397         if not (dsa_options & dsdb.DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL):
398             req_options |= drsuapi.DRSUAPI_DRS_WRIT_REP
399         if add_ref:
400             req_options |= drsuapi.DRSUAPI_DRS_ADD_REF
401         if sync_forced:
402             req_options |= drsuapi.DRSUAPI_DRS_SYNC_FORCED
403         if sync_all:
404             req_options |= drsuapi.DRSUAPI_DRS_SYNC_ALL
405         if full_sync:
406             req_options |= drsuapi.DRSUAPI_DRS_FULL_SYNC_NOW
407         if async_op:
408             req_options |= drsuapi.DRSUAPI_DRS_ASYNC_OP
409
410         try:
411             drs_utils.sendDsReplicaSync(server_bind, server_bind_handle, source_dsa_guid, NC, req_options)
412         except drs_utils.drsException, estr:
413             raise CommandError("DsReplicaSync failed", estr)
414         if async_op:
415             self.message("Replicate from %s to %s was started." % (SOURCE_DC, DEST_DC))
416         else:
417             self.message("Replicate from %s to %s was successful." % (SOURCE_DC, DEST_DC))
418
419
420
421 class cmd_drs_bind(Command):
422     """Show DRS capabilities of a server."""
423
424     synopsis = "%prog [<DC>] [options]"
425
426     takes_optiongroups = {
427         "sambaopts": options.SambaOptions,
428         "versionopts": options.VersionOptions,
429         "credopts": options.CredentialsOptions,
430     }
431
432     takes_args = ["DC?"]
433
434     def run(self, DC=None, sambaopts=None,
435             credopts=None, versionopts=None, server=None):
436
437         self.lp = sambaopts.get_loadparm()
438         if DC is None:
439             DC = common.netcmd_dnsname(self.lp)
440         self.server = DC
441         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
442
443         drsuapi_connect(self)
444
445         bind_info = drsuapi.DsBindInfoCtr()
446         bind_info.length = 28
447         bind_info.info = drsuapi.DsBindInfo28()
448         (info, handle) = self.drsuapi.DsBind(misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID), bind_info)
449
450         optmap = [
451             ("DRSUAPI_SUPPORTED_EXTENSION_BASE",     "DRS_EXT_BASE"),
452             ("DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION",   "DRS_EXT_ASYNCREPL"),
453             ("DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI",    "DRS_EXT_REMOVEAPI"),
454             ("DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2",   "DRS_EXT_MOVEREQ_V2"),
455             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS",   "DRS_EXT_GETCHG_DEFLATE"),
456             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1",    "DRS_EXT_DCINFO_V1"),
457             ("DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION",   "DRS_EXT_RESTORE_USN_OPTIMIZATION"),
458             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY",    "DRS_EXT_ADDENTRY"),
459             ("DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE",   "DRS_EXT_KCC_EXECUTE"),
460             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2",   "DRS_EXT_ADDENTRY_V2"),
461             ("DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION",   "DRS_EXT_LINKED_VALUE_REPLICATION"),
462             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2",    "DRS_EXT_DCINFO_V2"),
463             ("DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD","DRS_EXT_INSTANCE_TYPE_NOT_REQ_ON_MOD"),
464             ("DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND",   "DRS_EXT_CRYPTO_BIND"),
465             ("DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO",   "DRS_EXT_GET_REPL_INFO"),
466             ("DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION",   "DRS_EXT_STRONG_ENCRYPTION"),
467             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01",   "DRS_EXT_DCINFO_VFFFFFFFF"),
468             ("DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP",  "DRS_EXT_TRANSITIVE_MEMBERSHIP"),
469             ("DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY",   "DRS_EXT_ADD_SID_HISTORY"),
470             ("DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3",   "DRS_EXT_POST_BETA3"),
471             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V5",   "DRS_EXT_GETCHGREQ_V5"),
472             ("DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2",   "DRS_EXT_GETMEMBERSHIPS2"),
473             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6",   "DRS_EXT_GETCHGREQ_V6"),
474             ("DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS",   "DRS_EXT_NONDOMAIN_NCS"),
475             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8",   "DRS_EXT_GETCHGREQ_V8"),
476             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5",   "DRS_EXT_GETCHGREPLY_V5"),
477             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6",   "DRS_EXT_GETCHGREPLY_V6"),
478             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3",   "DRS_EXT_WHISTLER_BETA3"),
479             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7",   "DRS_EXT_WHISTLER_BETA3"),
480             ("DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT",   "DRS_EXT_WHISTLER_BETA3"),
481             ("DRSUAPI_SUPPORTED_EXTENSION_XPRESS_COMPRESS",   "DRS_EXT_W2K3_DEFLATE"),
482             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10",   "DRS_EXT_GETCHGREQ_V10"),
483             ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART2",   "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART2"),
484             ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART3", "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART3")
485             ]
486
487         optmap_ext = [
488             ("DRSUAPI_SUPPORTED_EXTENSION_ADAM", "DRS_EXT_ADAM"),
489             ("DRSUAPI_SUPPORTED_EXTENSION_LH_BETA2", "DRS_EXT_LH_BETA2"),
490             ("DRSUAPI_SUPPORTED_EXTENSION_RECYCLE_BIN", "DRS_EXT_RECYCLE_BIN")]
491
492         self.message("Bind to %s succeeded." % DC)
493         self.message("Extensions supported:")
494         for (opt, str) in optmap:
495             optval = getattr(drsuapi, opt, 0)
496             if info.info.supported_extensions & optval:
497                 yesno = "Yes"
498             else:
499                 yesno = "No "
500             self.message("  %-60s: %s (%s)" % (opt, yesno, str))
501
502         if isinstance(info.info, drsuapi.DsBindInfo48):
503             self.message("\nExtended Extensions supported:")
504             for (opt, str) in optmap_ext:
505                 optval = getattr(drsuapi, opt, 0)
506                 if info.info.supported_extensions_ext & optval:
507                     yesno = "Yes"
508                 else:
509                     yesno = "No "
510                 self.message("  %-60s: %s (%s)" % (opt, yesno, str))
511
512         self.message("\nSite GUID: %s" % info.info.site_guid)
513         self.message("Repl epoch: %u" % info.info.repl_epoch)
514         if isinstance(info.info, drsuapi.DsBindInfo48):
515             self.message("Forest GUID: %s" % info.info.config_dn_guid)
516
517
518
519 class cmd_drs_options(Command):
520     """Query or change 'options' for NTDS Settings object of a Domain Controller."""
521
522     synopsis = "%prog [<DC>] [options]"
523
524     takes_optiongroups = {
525         "sambaopts": options.SambaOptions,
526         "versionopts": options.VersionOptions,
527         "credopts": options.CredentialsOptions,
528     }
529
530     takes_args = ["DC?"]
531
532     takes_options = [
533         Option("--dsa-option", help="DSA option to enable/disable", type="str",
534                metavar="{+|-}IS_GC | {+|-}DISABLE_INBOUND_REPL | {+|-}DISABLE_OUTBOUND_REPL | {+|-}DISABLE_NTDSCONN_XLATE" ),
535         ]
536
537     option_map = {"IS_GC": 0x00000001,
538                   "DISABLE_INBOUND_REPL": 0x00000002,
539                   "DISABLE_OUTBOUND_REPL": 0x00000004,
540                   "DISABLE_NTDSCONN_XLATE": 0x00000008}
541
542     def run(self, DC=None, dsa_option=None,
543             sambaopts=None, credopts=None, versionopts=None):
544
545         self.lp = sambaopts.get_loadparm()
546         if DC is None:
547             DC = common.netcmd_dnsname(self.lp)
548         self.server = DC
549         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
550
551         samdb_connect(self)
552
553         ntds_dn = self.samdb.get_dsServiceName()
554         res = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=["options"])
555         dsa_opts = int(res[0]["options"][0])
556
557         # print out current DSA options
558         cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts]
559         self.message("Current DSA options: " + ", ".join(cur_opts))
560
561         # modify options
562         if dsa_option:
563             if dsa_option[:1] not in ("+", "-"):
564                 raise CommandError("Unknown option %s" % dsa_option)
565             flag = dsa_option[1:]
566             if flag not in self.option_map.keys():
567                 raise CommandError("Unknown option %s" % dsa_option)
568             if dsa_option[:1] == "+":
569                 dsa_opts |= self.option_map[flag]
570             else:
571                 dsa_opts &= ~self.option_map[flag]
572             #save new options
573             m = ldb.Message()
574             m.dn = ldb.Dn(self.samdb, ntds_dn)
575             m["options"]= ldb.MessageElement(str(dsa_opts), ldb.FLAG_MOD_REPLACE, "options")
576             self.samdb.modify(m)
577             # print out new DSA options
578             cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts]
579             self.message("New DSA options: " + ", ".join(cur_opts))
580
581
582 class cmd_drs_clone_dc_database(Command):
583     """Replicate an initial clone of domain, but DO NOT JOIN it."""
584
585     synopsis = "%prog <dnsdomain> [options]"
586
587     takes_optiongroups = {
588         "sambaopts": options.SambaOptions,
589         "versionopts": options.VersionOptions,
590         "credopts": options.CredentialsOptions,
591     }
592
593     takes_options = [
594         Option("--server", help="DC to join", type=str),
595         Option("--targetdir", help="where to store provision (required)", type=str),
596         Option("--quiet", help="Be quiet", action="store_true"),
597         Option("--include-secrets", help="Also replicate secret values", action="store_true"),
598         Option("--verbose", help="Be verbose", action="store_true")
599        ]
600
601     takes_args = ["domain"]
602
603     def run(self, domain, sambaopts=None, credopts=None,
604             versionopts=None, server=None, targetdir=None,
605             quiet=False, verbose=False, include_secrets=False):
606         lp = sambaopts.get_loadparm()
607         creds = credopts.get_credentials(lp)
608
609         logger = self.get_logger()
610         if verbose:
611             logger.setLevel(logging.DEBUG)
612         elif quiet:
613             logger.setLevel(logging.WARNING)
614         else:
615             logger.setLevel(logging.INFO)
616
617         if targetdir is None:
618             raise CommandError("--targetdir option must be specified")
619
620
621         join_clone(logger=logger, server=server, creds=creds, lp=lp, domain=domain,
622                    targetdir=targetdir, include_secrets=include_secrets)
623
624
625 class cmd_drs(SuperCommand):
626     """Directory Replication Services (DRS) management."""
627
628     subcommands = {}
629     subcommands["bind"] = cmd_drs_bind()
630     subcommands["kcc"] = cmd_drs_kcc()
631     subcommands["replicate"] = cmd_drs_replicate()
632     subcommands["showrepl"] = cmd_drs_showrepl()
633     subcommands["options"] = cmd_drs_options()
634     subcommands["clone-dc-database"] = cmd_drs_clone_dc_database()