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