samba-tool drs show_repl: simplify the collection of DC lists
[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 import samba.getopt as options
22 import ldb
23 import logging
24 import common
25 import json
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 from samba import colour
41 import logging
42
43
44 def drsuapi_connect(ctx):
45     '''make a DRSUAPI connection to the server'''
46     try:
47         (ctx.drsuapi, ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drsuapi_connect(ctx.server, ctx.lp, ctx.creds)
48     except Exception as e:
49         raise CommandError("DRS connection to %s failed" % ctx.server, e)
50
51 def samdb_connect(ctx):
52     '''make a ldap connection to the server'''
53     try:
54         ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
55                           session_info=system_session(),
56                           credentials=ctx.creds, lp=ctx.lp)
57     except Exception as e:
58         raise CommandError("LDAP connection to %s failed" % ctx.server, e)
59
60 def drs_errmsg(werr):
61     '''return "was successful" or an error string'''
62     (ecode, estring) = werr
63     if ecode == 0:
64         return "was successful"
65     return "failed, result %u (%s)" % (ecode, estring)
66
67
68
69 def attr_default(msg, attrname, default):
70     '''get an attribute from a ldap msg with a default'''
71     if attrname in msg:
72         return msg[attrname][0]
73     return default
74
75
76
77 def drs_parse_ntds_dn(ntds_dn):
78     '''parse a NTDS DN returning a site and server'''
79     a = ntds_dn.split(',')
80     if a[0] != "CN=NTDS Settings" or a[2] != "CN=Servers" or a[4] != 'CN=Sites':
81         raise RuntimeError("bad NTDS DN %s" % ntds_dn)
82     server = a[1].split('=')[1]
83     site   = a[3].split('=')[1]
84     return (site, server)
85
86
87 DEFAULT_SHOWREPL_FORMAT = 'classic'
88
89 class cmd_drs_showrepl(Command):
90     """Show replication status."""
91
92     synopsis = "%prog [<DC>] [options]"
93
94     takes_optiongroups = {
95         "sambaopts": options.SambaOptions,
96         "versionopts": options.VersionOptions,
97         "credopts": options.CredentialsOptions,
98     }
99
100     takes_options = [
101         Option("--json", help="replication details in JSON format",
102                dest='format', action='store_const', const='json'),
103         Option("--summary", help="summarize local DRS health",
104                dest='format', action='store_const', const='summary'),
105         Option("--classic", help="print local replication details",
106                dest='format', action='store_const', const='classic',
107                default=DEFAULT_SHOWREPL_FORMAT),
108         Option("-v", "--verbose", help="Be verbose", action="store_true"),
109         Option("--color", help="Use colour output (yes|no|auto)",
110                default='no'),
111     ]
112
113     takes_args = ["DC?"]
114
115     def parse_neighbour(self, n):
116         """Convert an ldb neighbour object into a python dictionary"""
117         d = {
118             'NC dn': n.naming_context_dn,
119             "DSA objectGUID": str(n.source_dsa_obj_guid),
120             "last attempt time": nttime2string(n.last_attempt),
121             "last attempt message": drs_errmsg(n.result_last_attempt),
122             "consecutive failures": n.consecutive_sync_failures,
123             "last success": nttime2string(n.last_success),
124             "NTDS DN": str(n.source_dsa_obj_dn)
125         }
126
127         try:
128             (site, server) = drs_parse_ntds_dn(n.source_dsa_obj_dn)
129             d["DSA"] = "%s\%s" % (site, server)
130         except RuntimeError:
131             pass
132         return d
133
134     def print_neighbour(self, d):
135         '''print one set of neighbour information'''
136         self.message("%s" % d['NC dn'])
137         if 'DSA' in d:
138             self.message("\t%s via RPC" % d['DSA'])
139         else:
140             self.message("\tNTDS DN: %s" % d['NTDS DN'])
141         self.message("\t\tDSA object GUID: %s" % d['DSA objectGUID'])
142         self.message("\t\tLast attempt @ %s %s" % (d['last attempt time'],
143                                                    d['last attempt message']))
144         self.message("\t\t%u consecutive failure(s)." %
145                      d['consecutive failures'])
146         self.message("\t\tLast success @ %s" % d['last success'])
147         self.message("")
148
149     def get_neighbours(self, info_type):
150         req1 = drsuapi.DsReplicaGetInfoRequest1()
151         req1.info_type = info_type
152         try:
153             (info_type, info) = self.drsuapi.DsReplicaGetInfo(
154                 self.drsuapi_handle, 1, req1)
155         except Exception as e:
156             raise CommandError("DsReplicaGetInfo of type %u failed" % info_type, e)
157
158         reps = [self.parse_neighbour(n) for n in info.array]
159         return reps
160
161     def run(self, DC=None, sambaopts=None,
162             credopts=None, versionopts=None,
163             format=DEFAULT_SHOWREPL_FORMAT,
164             verbose=False, color='no'):
165         self.apply_colour_choice(color)
166         self.lp = sambaopts.get_loadparm()
167         if DC is None:
168             DC = common.netcmd_dnsname(self.lp)
169         self.server = DC
170         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
171         self.verbose = verbose
172
173         output_function = {
174             'summary': self.summary_output,
175             'json': self.json_output,
176             'classic': self.classic_output,
177         }.get(format)
178         if output_function is None:
179             raise CommandError("unknown showrepl format %s" % format)
180
181         return output_function()
182
183     def json_output(self):
184         data = self.get_local_repl_data()
185         del data['site']
186         del data['server']
187         json.dump(data, self.outf, indent=2)
188
189     def summary_output(self):
190         """Print a short message if every seems fine, but print details of any
191         links that seem broken."""
192         failing_repsto = []
193         failing_repsfrom = []
194
195         local_data = self.get_local_repl_data()
196         for rep in local_data['repsTo']:
197             if rep["consecutive failures"] != 0 or rep["last success"] == 0:
198                 failing_repsto.append(rep)
199
200         for rep in local_data['repsFrom']:
201             if rep["consecutive failures"] != 0 or rep["last success"] == 0:
202                 failing_repsto.append(rep)
203
204         if failing_repsto or failing_repsfrom:
205             self.message(colour.c_RED("There are failing connections"))
206             if failing_repsto:
207                 self.message(colour.c_RED("Failing outbound connections:"))
208                 for rep in failing_repsto:
209                     self.print_neighbour(rep)
210             if failing_repsfrom:
211                 self.message(colour.c_RED("Failing inbound connection:"))
212                 for rep in failing_repsfrom:
213                     self.print_neighbour(rep)
214
215             return 1
216
217         self.message(colour.c_GREEN("[ALL GOOD]"))
218
219
220     def get_local_repl_data(self):
221         drsuapi_connect(self)
222         samdb_connect(self)
223
224         # show domain information
225         ntds_dn = self.samdb.get_dsServiceName()
226
227         (site, server) = drs_parse_ntds_dn(ntds_dn)
228         try:
229             ntds = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=['options', 'objectGUID', 'invocationId'])
230         except Exception as e:
231             raise CommandError("Failed to search NTDS DN %s" % ntds_dn)
232
233         dsa_details = {
234             "options": int(attr_default(ntds[0], "options", 0)),
235             "objectGUID": self.samdb.schema_format_value(
236                 "objectGUID", ntds[0]["objectGUID"][0]),
237             "invocationId": self.samdb.schema_format_value(
238                 "objectGUID", ntds[0]["invocationId"][0])
239         }
240
241         conn = self.samdb.search(base=ntds_dn, expression="(objectClass=nTDSConnection)")
242         repsfrom = self.get_neighbours(drsuapi.DRSUAPI_DS_REPLICA_INFO_NEIGHBORS)
243         repsto = self.get_neighbours(drsuapi.DRSUAPI_DS_REPLICA_INFO_REPSTO)
244
245         conn_details = []
246         for c in conn:
247             c_rdn, sep, c_server_dn = c['fromServer'][0].partition(',')
248             d = {
249                 'name': str(c['name']),
250                 'remote DN': c['fromServer'][0],
251                 'options': int(attr_default(c, 'options', 0)),
252                 'enabled': (attr_default(c, 'enabledConnection',
253                                          'TRUE').upper() == 'TRUE')
254             }
255
256             conn_details.append(d)
257             try:
258                 c_server_res = self.samdb.search(base=c_server_dn,
259                                                  scope=ldb.SCOPE_BASE,
260                                                  attrs=["dnsHostName"])
261                 d['dns name'] = c_server_res[0]["dnsHostName"][0]
262             except ldb.LdbError as e:
263                 (errno, _) = e.args
264                 if errno == ldb.ERR_NO_SUCH_OBJECT:
265                     d['is deleted'] = True
266             except KeyError:
267                 pass
268
269             d['replicates NC'] = []
270             for r in c.get('mS-DS-ReplicatesNCReason', []):
271                 a = str(r).split(':')
272                 d['replicates NC'].append((a[3], int(a[2])))
273
274         return {
275             'dsa': dsa_details,
276             'repsFrom': repsfrom,
277             'repsTo': repsto,
278             'NTDSConnections': conn_details,
279             'site': site,
280             'server': server
281         }
282
283     def classic_output(self):
284         data = self.get_local_repl_data()
285         dsa_details = data['dsa']
286         repsfrom = data['repsFrom']
287         repsto = data['repsTo']
288         conn_details = data['NTDSConnections']
289         site = data['site']
290         server = data['server']
291
292         self.message("%s\\%s" % (site, server))
293         self.message("DSA Options: 0x%08x" % dsa_details["options"])
294         self.message("DSA object GUID: %s" % dsa_details["objectGUID"])
295         self.message("DSA invocationId: %s\n" % dsa_details["invocationId"])
296
297         self.message("==== INBOUND NEIGHBORS ====\n")
298         for n in repsfrom:
299             self.print_neighbour(n)
300
301         self.message("==== OUTBOUND NEIGHBORS ====\n")
302         for n in repsto:
303             self.print_neighbour(n)
304
305         reasons = ['NTDSCONN_KCC_GC_TOPOLOGY',
306                    'NTDSCONN_KCC_RING_TOPOLOGY',
307                    'NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY',
308                    'NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY',
309                    'NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY',
310                    'NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY',
311                    'NTDSCONN_KCC_INTERSITE_TOPOLOGY',
312                    'NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY',
313                    'NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY',
314                    'NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY']
315
316         self.message("==== KCC CONNECTION OBJECTS ====\n")
317         for d in conn_details:
318             self.message("Connection --")
319             if d.get('is deleted'):
320                 self.message("\tWARNING: Connection to DELETED server!")
321
322             self.message("\tConnection name: %s" % d['name'])
323             self.message("\tEnabled        : %s" % str(d['enabled']).upper())
324             self.message("\tServer DNS name : %s" % d['dns name'])
325             self.message("\tServer DN name  : %s" % d['remote DN'])
326             self.message("\t\tTransportType: RPC")
327             self.message("\t\toptions: 0x%08X" % d['options'])
328
329             if d['replicates NC']:
330                 for nc, reason in d['replicates NC']:
331                     self.message("\t\tReplicatesNC: %s" % nc)
332                     self.message("\t\tReason: 0x%08x" % reason)
333                     for s in reasons:
334                         if getattr(dsdb, s, 0) & reason:
335                             self.message("\t\t\t%s" % s)
336             else:
337                 self.message("Warning: No NC replicated for Connection!")
338
339
340 class cmd_drs_kcc(Command):
341     """Trigger knowledge consistency center run."""
342
343     synopsis = "%prog [<DC>] [options]"
344
345     takes_optiongroups = {
346         "sambaopts": options.SambaOptions,
347         "versionopts": options.VersionOptions,
348         "credopts": options.CredentialsOptions,
349     }
350
351     takes_args = ["DC?"]
352
353     def run(self, DC=None, sambaopts=None,
354             credopts=None, versionopts=None):
355
356         self.lp = sambaopts.get_loadparm()
357         if DC is None:
358             DC = common.netcmd_dnsname(self.lp)
359         self.server = DC
360
361         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
362
363         drsuapi_connect(self)
364
365         req1 = drsuapi.DsExecuteKCC1()
366         try:
367             self.drsuapi.DsExecuteKCC(self.drsuapi_handle, 1, req1)
368         except Exception as e:
369             raise CommandError("DsExecuteKCC failed", e)
370         self.message("Consistency check on %s successful." % DC)
371
372
373 class cmd_drs_replicate(Command):
374     """Replicate a naming context between two DCs."""
375
376     synopsis = "%prog <destinationDC> <sourceDC> <NC> [options]"
377
378     takes_optiongroups = {
379         "sambaopts": options.SambaOptions,
380         "versionopts": options.VersionOptions,
381         "credopts": options.CredentialsOptions,
382     }
383
384     takes_args = ["DEST_DC", "SOURCE_DC", "NC"]
385
386     takes_options = [
387         Option("--add-ref", help="use ADD_REF to add to repsTo on source", action="store_true"),
388         Option("--sync-forced", help="use SYNC_FORCED to force inbound replication", action="store_true"),
389         Option("--sync-all", help="use SYNC_ALL to replicate from all DCs", action="store_true"),
390         Option("--full-sync", help="resync all objects", action="store_true"),
391         Option("--local", help="pull changes directly into the local database (destination DC is ignored)", action="store_true"),
392         Option("--local-online", help="pull changes into the local database (destination DC is ignored) as a normal online replication", action="store_true"),
393         Option("--async-op", help="use ASYNC_OP for the replication", action="store_true"),
394         Option("--single-object", help="Replicate only the object specified, instead of the whole Naming Context (only with --local)", action="store_true"),
395         ]
396
397     def drs_local_replicate(self, SOURCE_DC, NC, full_sync=False,
398                             single_object=False,
399                             sync_forced=False):
400         '''replicate from a source DC to the local SAM'''
401
402         self.server = SOURCE_DC
403         drsuapi_connect(self)
404
405         self.local_samdb = SamDB(session_info=system_session(), url=None,
406                                  credentials=self.creds, lp=self.lp)
407
408         self.samdb = SamDB(url="ldap://%s" % self.server,
409                            session_info=system_session(),
410                            credentials=self.creds, lp=self.lp)
411
412         # work out the source and destination GUIDs
413         res = self.local_samdb.search(base="", scope=ldb.SCOPE_BASE,
414                                       attrs=["dsServiceName"])
415         self.ntds_dn = res[0]["dsServiceName"][0]
416
417         res = self.local_samdb.search(base=self.ntds_dn, scope=ldb.SCOPE_BASE,
418                                       attrs=["objectGUID"])
419         self.ntds_guid = misc.GUID(
420             self.samdb.schema_format_value("objectGUID",
421                                            res[0]["objectGUID"][0]))
422
423         source_dsa_invocation_id = misc.GUID(self.samdb.get_invocation_id())
424         dest_dsa_invocation_id = misc.GUID(self.local_samdb.get_invocation_id())
425         destination_dsa_guid = self.ntds_guid
426
427         exop = drsuapi.DRSUAPI_EXOP_NONE
428
429         if single_object:
430             exop = drsuapi.DRSUAPI_EXOP_REPL_OBJ
431             full_sync = True
432
433         self.samdb.transaction_start()
434         repl = drs_utils.drs_Replicate("ncacn_ip_tcp:%s[seal]" % self.server,
435                                        self.lp,
436                                        self.creds, self.local_samdb,
437                                        dest_dsa_invocation_id)
438
439         # Work out if we are an RODC, so that a forced local replicate
440         # with the admin pw does not sync passwords
441         rodc = self.local_samdb.am_rodc()
442         try:
443             (num_objects, num_links) = repl.replicate(NC,
444                                                       source_dsa_invocation_id,
445                                                       destination_dsa_guid,
446                                                       rodc=rodc,
447                                                       full_sync=full_sync,
448                                                       exop=exop,
449                                                       sync_forced=sync_forced)
450         except Exception as e:
451             raise CommandError("Error replicating DN %s" % NC, e)
452         self.samdb.transaction_commit()
453
454         if full_sync:
455             self.message("Full Replication of all %d objects and %d links "
456                          "from %s to %s was successful." %
457                          (num_objects, num_links, SOURCE_DC,
458                           self.local_samdb.url))
459         else:
460             self.message("Incremental replication of %d objects and %d links "
461                          "from %s to %s was successful." %
462                          (num_objects, num_links, SOURCE_DC,
463                           self.local_samdb.url))
464
465     def run(self, DEST_DC, SOURCE_DC, NC,
466             add_ref=False, sync_forced=False, sync_all=False, full_sync=False,
467             local=False, local_online=False, async_op=False, single_object=False,
468             sambaopts=None, credopts=None, versionopts=None):
469
470         self.server = DEST_DC
471         self.lp = sambaopts.get_loadparm()
472
473         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
474
475         if local:
476             self.drs_local_replicate(SOURCE_DC, NC, full_sync=full_sync,
477                                      single_object=single_object,
478                                      sync_forced=sync_forced)
479             return
480
481         if local_online:
482             server_bind = drsuapi.drsuapi("irpc:dreplsrv", lp_ctx=self.lp)
483             server_bind_handle = misc.policy_handle()
484         else:
485             drsuapi_connect(self)
486             server_bind = self.drsuapi
487             server_bind_handle = self.drsuapi_handle
488
489         if not async_op:
490             # Give the sync replication 5 minutes time
491             server_bind.request_timeout = 5 * 60
492
493         samdb_connect(self)
494
495         # we need to find the NTDS GUID of the source DC
496         msg = self.samdb.search(base=self.samdb.get_config_basedn(),
497                                 expression="(&(objectCategory=server)(|(name=%s)(dNSHostName=%s)))" % (
498             ldb.binary_encode(SOURCE_DC),
499             ldb.binary_encode(SOURCE_DC)),
500                                 attrs=[])
501         if len(msg) == 0:
502             raise CommandError("Failed to find source DC %s" % SOURCE_DC)
503         server_dn = msg[0]['dn']
504
505         msg = self.samdb.search(base=server_dn, scope=ldb.SCOPE_ONELEVEL,
506                                 expression="(|(objectCategory=nTDSDSA)(objectCategory=nTDSDSARO))",
507                                 attrs=['objectGUID', 'options'])
508         if len(msg) == 0:
509             raise CommandError("Failed to find source NTDS DN %s" % SOURCE_DC)
510         source_dsa_guid = msg[0]['objectGUID'][0]
511         dsa_options = int(attr_default(msg, 'options', 0))
512
513
514         req_options = 0
515         if not (dsa_options & dsdb.DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL):
516             req_options |= drsuapi.DRSUAPI_DRS_WRIT_REP
517         if add_ref:
518             req_options |= drsuapi.DRSUAPI_DRS_ADD_REF
519         if sync_forced:
520             req_options |= drsuapi.DRSUAPI_DRS_SYNC_FORCED
521         if sync_all:
522             req_options |= drsuapi.DRSUAPI_DRS_SYNC_ALL
523         if full_sync:
524             req_options |= drsuapi.DRSUAPI_DRS_FULL_SYNC_NOW
525         if async_op:
526             req_options |= drsuapi.DRSUAPI_DRS_ASYNC_OP
527
528         try:
529             drs_utils.sendDsReplicaSync(server_bind, server_bind_handle, source_dsa_guid, NC, req_options)
530         except drs_utils.drsException as estr:
531             raise CommandError("DsReplicaSync failed", estr)
532         if async_op:
533             self.message("Replicate from %s to %s was started." % (SOURCE_DC, DEST_DC))
534         else:
535             self.message("Replicate from %s to %s was successful." % (SOURCE_DC, DEST_DC))
536
537
538
539 class cmd_drs_bind(Command):
540     """Show DRS capabilities of a server."""
541
542     synopsis = "%prog [<DC>] [options]"
543
544     takes_optiongroups = {
545         "sambaopts": options.SambaOptions,
546         "versionopts": options.VersionOptions,
547         "credopts": options.CredentialsOptions,
548     }
549
550     takes_args = ["DC?"]
551
552     def run(self, DC=None, sambaopts=None,
553             credopts=None, versionopts=None):
554
555         self.lp = sambaopts.get_loadparm()
556         if DC is None:
557             DC = common.netcmd_dnsname(self.lp)
558         self.server = DC
559         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
560
561         drsuapi_connect(self)
562
563         bind_info = drsuapi.DsBindInfoCtr()
564         bind_info.length = 28
565         bind_info.info = drsuapi.DsBindInfo28()
566         (info, handle) = self.drsuapi.DsBind(misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID), bind_info)
567
568         optmap = [
569             ("DRSUAPI_SUPPORTED_EXTENSION_BASE",     "DRS_EXT_BASE"),
570             ("DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION",   "DRS_EXT_ASYNCREPL"),
571             ("DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI",    "DRS_EXT_REMOVEAPI"),
572             ("DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2",   "DRS_EXT_MOVEREQ_V2"),
573             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS",   "DRS_EXT_GETCHG_DEFLATE"),
574             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1",    "DRS_EXT_DCINFO_V1"),
575             ("DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION",   "DRS_EXT_RESTORE_USN_OPTIMIZATION"),
576             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY",    "DRS_EXT_ADDENTRY"),
577             ("DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE",   "DRS_EXT_KCC_EXECUTE"),
578             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2",   "DRS_EXT_ADDENTRY_V2"),
579             ("DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION",   "DRS_EXT_LINKED_VALUE_REPLICATION"),
580             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2",    "DRS_EXT_DCINFO_V2"),
581             ("DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD","DRS_EXT_INSTANCE_TYPE_NOT_REQ_ON_MOD"),
582             ("DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND",   "DRS_EXT_CRYPTO_BIND"),
583             ("DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO",   "DRS_EXT_GET_REPL_INFO"),
584             ("DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION",   "DRS_EXT_STRONG_ENCRYPTION"),
585             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01",   "DRS_EXT_DCINFO_VFFFFFFFF"),
586             ("DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP",  "DRS_EXT_TRANSITIVE_MEMBERSHIP"),
587             ("DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY",   "DRS_EXT_ADD_SID_HISTORY"),
588             ("DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3",   "DRS_EXT_POST_BETA3"),
589             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V5",   "DRS_EXT_GETCHGREQ_V5"),
590             ("DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2",   "DRS_EXT_GETMEMBERSHIPS2"),
591             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6",   "DRS_EXT_GETCHGREQ_V6"),
592             ("DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS",   "DRS_EXT_NONDOMAIN_NCS"),
593             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8",   "DRS_EXT_GETCHGREQ_V8"),
594             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5",   "DRS_EXT_GETCHGREPLY_V5"),
595             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6",   "DRS_EXT_GETCHGREPLY_V6"),
596             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3",   "DRS_EXT_WHISTLER_BETA3"),
597             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7",   "DRS_EXT_WHISTLER_BETA3"),
598             ("DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT",   "DRS_EXT_WHISTLER_BETA3"),
599             ("DRSUAPI_SUPPORTED_EXTENSION_XPRESS_COMPRESS",   "DRS_EXT_W2K3_DEFLATE"),
600             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10",   "DRS_EXT_GETCHGREQ_V10"),
601             ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART2",   "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART2"),
602             ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART3", "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART3")
603             ]
604
605         optmap_ext = [
606             ("DRSUAPI_SUPPORTED_EXTENSION_ADAM", "DRS_EXT_ADAM"),
607             ("DRSUAPI_SUPPORTED_EXTENSION_LH_BETA2", "DRS_EXT_LH_BETA2"),
608             ("DRSUAPI_SUPPORTED_EXTENSION_RECYCLE_BIN", "DRS_EXT_RECYCLE_BIN")]
609
610         self.message("Bind to %s succeeded." % DC)
611         self.message("Extensions supported:")
612         for (opt, str) in optmap:
613             optval = getattr(drsuapi, opt, 0)
614             if info.info.supported_extensions & optval:
615                 yesno = "Yes"
616             else:
617                 yesno = "No "
618             self.message("  %-60s: %s (%s)" % (opt, yesno, str))
619
620         if isinstance(info.info, drsuapi.DsBindInfo48):
621             self.message("\nExtended Extensions supported:")
622             for (opt, str) in optmap_ext:
623                 optval = getattr(drsuapi, opt, 0)
624                 if info.info.supported_extensions_ext & optval:
625                     yesno = "Yes"
626                 else:
627                     yesno = "No "
628                 self.message("  %-60s: %s (%s)" % (opt, yesno, str))
629
630         self.message("\nSite GUID: %s" % info.info.site_guid)
631         self.message("Repl epoch: %u" % info.info.repl_epoch)
632         if isinstance(info.info, drsuapi.DsBindInfo48):
633             self.message("Forest GUID: %s" % info.info.config_dn_guid)
634
635
636
637 class cmd_drs_options(Command):
638     """Query or change 'options' for NTDS Settings object of a Domain Controller."""
639
640     synopsis = "%prog [<DC>] [options]"
641
642     takes_optiongroups = {
643         "sambaopts": options.SambaOptions,
644         "versionopts": options.VersionOptions,
645         "credopts": options.CredentialsOptions,
646     }
647
648     takes_args = ["DC?"]
649
650     takes_options = [
651         Option("--dsa-option", help="DSA option to enable/disable", type="str",
652                metavar="{+|-}IS_GC | {+|-}DISABLE_INBOUND_REPL | {+|-}DISABLE_OUTBOUND_REPL | {+|-}DISABLE_NTDSCONN_XLATE" ),
653         ]
654
655     option_map = {"IS_GC": 0x00000001,
656                   "DISABLE_INBOUND_REPL": 0x00000002,
657                   "DISABLE_OUTBOUND_REPL": 0x00000004,
658                   "DISABLE_NTDSCONN_XLATE": 0x00000008}
659
660     def run(self, DC=None, dsa_option=None,
661             sambaopts=None, credopts=None, versionopts=None):
662
663         self.lp = sambaopts.get_loadparm()
664         if DC is None:
665             DC = common.netcmd_dnsname(self.lp)
666         self.server = DC
667         self.creds = credopts.get_credentials(self.lp, fallback_machine=True)
668
669         samdb_connect(self)
670
671         ntds_dn = self.samdb.get_dsServiceName()
672         res = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=["options"])
673         dsa_opts = int(res[0]["options"][0])
674
675         # print out current DSA options
676         cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts]
677         self.message("Current DSA options: " + ", ".join(cur_opts))
678
679         # modify options
680         if dsa_option:
681             if dsa_option[:1] not in ("+", "-"):
682                 raise CommandError("Unknown option %s" % dsa_option)
683             flag = dsa_option[1:]
684             if flag not in self.option_map.keys():
685                 raise CommandError("Unknown option %s" % dsa_option)
686             if dsa_option[:1] == "+":
687                 dsa_opts |= self.option_map[flag]
688             else:
689                 dsa_opts &= ~self.option_map[flag]
690             #save new options
691             m = ldb.Message()
692             m.dn = ldb.Dn(self.samdb, ntds_dn)
693             m["options"]= ldb.MessageElement(str(dsa_opts), ldb.FLAG_MOD_REPLACE, "options")
694             self.samdb.modify(m)
695             # print out new DSA options
696             cur_opts = [x for x in self.option_map if self.option_map[x] & dsa_opts]
697             self.message("New DSA options: " + ", ".join(cur_opts))
698
699
700 class cmd_drs_clone_dc_database(Command):
701     """Replicate an initial clone of domain, but DO NOT JOIN it."""
702
703     synopsis = "%prog <dnsdomain> [options]"
704
705     takes_optiongroups = {
706         "sambaopts": options.SambaOptions,
707         "versionopts": options.VersionOptions,
708         "credopts": options.CredentialsOptions,
709     }
710
711     takes_options = [
712         Option("--server", help="DC to join", type=str),
713         Option("--targetdir", help="where to store provision (required)", type=str),
714         Option("-q", "--quiet", help="Be quiet", action="store_true"),
715         Option("--include-secrets", help="Also replicate secret values", action="store_true"),
716         Option("-v", "--verbose", help="Be verbose", action="store_true")
717        ]
718
719     takes_args = ["domain"]
720
721     def run(self, domain, sambaopts=None, credopts=None,
722             versionopts=None, server=None, targetdir=None,
723             quiet=False, verbose=False, include_secrets=False):
724         lp = sambaopts.get_loadparm()
725         creds = credopts.get_credentials(lp)
726
727         logger = self.get_logger()
728         if verbose:
729             logger.setLevel(logging.DEBUG)
730         elif quiet:
731             logger.setLevel(logging.WARNING)
732         else:
733             logger.setLevel(logging.INFO)
734
735         if targetdir is None:
736             raise CommandError("--targetdir option must be specified")
737
738
739         join_clone(logger=logger, server=server, creds=creds, lp=lp, domain=domain,
740                    targetdir=targetdir, include_secrets=include_secrets)
741
742
743 class cmd_drs(SuperCommand):
744     """Directory Replication Services (DRS) management."""
745
746     subcommands = {}
747     subcommands["bind"] = cmd_drs_bind()
748     subcommands["kcc"] = cmd_drs_kcc()
749     subcommands["replicate"] = cmd_drs_replicate()
750     subcommands["showrepl"] = cmd_drs_showrepl()
751     subcommands["options"] = cmd_drs_options()
752     subcommands["clone-dc-database"] = cmd_drs_clone_dc_database()