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