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