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