s4-samba-tool: fixed exception handling in subcommands
[metze/samba/wip.git] / source4 / scripting / python / samba / netcmd / drs.py
1 #!/usr/bin/env python
2 #
3 # implement samba_tool drs commands
4 #
5 # Copyright Andrew Tridgell 2010
6 #
7 # based on C implementation by Kamen Mazdrashki <kamen.mazdrashki@postpath.com>
8 #
9 # This program is free software; you can redistribute it and/or modify
10 # it under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # This program is distributed in the hope that it will be useful,
15 # but WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
21 #
22
23 import samba.getopt as options
24 import ldb
25
26 from samba.auth import system_session
27 from samba.netcmd import (
28     Command,
29     CommandError,
30     Option,
31     SuperCommand,
32     )
33 from samba.samdb import SamDB
34 from samba import drs_utils, nttime2string, dsdb
35 from samba.dcerpc import drsuapi, misc
36
37
38 def drsuapi_connect(ctx):
39     '''make a DRSUAPI connection to the server'''
40     binding_options = "seal"
41     if ctx.lp.get("log level") >= 5:
42         binding_options += ",print"
43     binding_string = "ncacn_ip_tcp:%s[%s]" % (ctx.server, binding_options)
44     try:
45         ctx.drsuapi = drsuapi.drsuapi(binding_string, ctx.lp, ctx.creds)
46         (ctx.drsuapi_handle, ctx.bind_supported_extensions) = drs_utils.drs_DsBind(ctx.drsuapi)
47     except Exception, e:
48         raise CommandError("DRS connection to %s failed" % ctx.server, e)
49
50
51 def samdb_connect(ctx):
52     '''make a ldap connection to the server'''
53     try:
54         ctx.samdb = SamDB(url="ldap://%s" % ctx.server,
55                           session_info=system_session(),
56                           credentials=ctx.creds, lp=ctx.lp)
57     except Exception, e:
58         raise CommandError("LDAP connection to %s failed" % ctx.server, e)
59
60
61 def drs_errmsg(werr):
62     '''return "was successful" or an error string'''
63     (ecode, estring) = werr
64     if ecode == 0:
65         return "was successful"
66     return "failed, result %u (%s)" % (ecode, estring)
67
68
69 def attr_default(msg, attrname, default):
70     '''get an attribute from a ldap msg with a default'''
71     if attrname in msg:
72         return msg[attrname][0]
73     return default
74
75
76 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 class cmd_drs_showrepl(Command):
87     """show replication status"""
88
89     synopsis = "%prog drs showrepl <DC>"
90
91     takes_optiongroups = {
92         "sambaopts": options.SambaOptions,
93         "versionopts": options.VersionOptions,
94         "credopts": options.CredentialsOptions,
95     }
96
97     takes_args = ["DC"]
98
99     def print_neighbour(self, n):
100         '''print one set of neighbour information'''
101         (site, server) = drs_parse_ntds_dn(n.source_dsa_obj_dn)
102         print("%s" % n.naming_context_dn)
103         print("\t%s\%s via RPC" % (site, server))
104         print("\t\tDSA object GUID: %s" % n.source_dsa_obj_guid)
105         print("\t\tLast attempt @ %s %s" % (nttime2string(n.last_attempt), drs_errmsg(n.result_last_attempt)))
106         print("\t\t%u consecutive failure(s)." % n.consecutive_sync_failures)
107         print("\t\tLast success @ %s" % nttime2string(n.last_success))
108         print("")
109
110     def get_dsServiceName(ctx):
111         '''get the NTDS DN from the rootDSE'''
112         res = ctx.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dsServiceName"])
113         return res[0]["dsServiceName"][0]
114
115     def drsuapi_ReplicaInfo(ctx, info_type):
116         '''call a DsReplicaInfo'''
117
118         req1 = drsuapi.DsReplicaGetInfoRequest1()
119         req1.info_type = info_type
120         try:
121             (info_type, info) = ctx.drsuapi.DsReplicaGetInfo(ctx.drsuapi_handle, 1, req1)
122         except Exception, e:
123             raise CommandError("DsReplicaGetInfo of type %u failed" % info_type, e)
124         return (info_type, info)
125
126
127     def run(self, DC, sambaopts=None,
128             credopts=None, versionopts=None, server=None):
129
130         self.server = DC
131         self.lp = sambaopts.get_loadparm()
132
133         self.creds = credopts.get_credentials(self.lp)
134         if not self.creds.authentication_requested():
135             self.creds.set_machine_account(self.lp)
136
137         drsuapi_connect(self)
138         samdb_connect(self)
139
140         # show domain information
141         ntds_dn = self.get_dsServiceName()
142         server_dns = self.samdb.search(base="", scope=ldb.SCOPE_BASE, attrs=["dnsHostName"])[0]['dnsHostName'][0]
143
144         (site, server) = drs_parse_ntds_dn(ntds_dn)
145         ntds = self.samdb.search(base=ntds_dn, scope=ldb.SCOPE_BASE, attrs=['options', 'objectGUID', 'invocationId'])
146         conn = self.samdb.search(base=ntds_dn, expression="(objectClass=nTDSConnection)")
147
148         print("%s\\%s" % (site, server))
149         print("DSA Options: 0x%08x" % int(ntds[0]["options"][0]))
150         print("DSA object GUID: %s" % self.samdb.schema_format_value("objectGUID", ntds[0]["objectGUID"][0]))
151         print("DSA invocationId: %s\n" % self.samdb.schema_format_value("objectGUID", ntds[0]["invocationId"][0]))
152
153         print("==== INBOUND NEIGHBORS ====\n")
154         (info_type, info) = self.drsuapi_ReplicaInfo(drsuapi.DRSUAPI_DS_REPLICA_INFO_NEIGHBORS)
155         for n in info.array:
156             self.print_neighbour(n)
157
158
159         print("==== OUTBOUND NEIGHBORS ====\n")
160         (info_type, info) = self.drsuapi_ReplicaInfo(drsuapi.DRSUAPI_DS_REPLICA_INFO_REPSTO)
161         for n in info.array:
162             self.print_neighbour(n)
163
164         reasons = ['NTDSCONN_KCC_GC_TOPOLOGY',
165                    'NTDSCONN_KCC_RING_TOPOLOGY',
166                    'NTDSCONN_KCC_MINIMIZE_HOPS_TOPOLOGY',
167                    'NTDSCONN_KCC_STALE_SERVERS_TOPOLOGY',
168                    'NTDSCONN_KCC_OSCILLATING_CONNECTION_TOPOLOGY',
169                    'NTDSCONN_KCC_INTERSITE_GC_TOPOLOGY',
170                    'NTDSCONN_KCC_INTERSITE_TOPOLOGY',
171                    'NTDSCONN_KCC_SERVER_FAILOVER_TOPOLOGY',
172                    'NTDSCONN_KCC_SITE_FAILOVER_TOPOLOGY',
173                    'NTDSCONN_KCC_REDUNDANT_SERVER_TOPOLOGY']
174
175         print("==== KCC CONNECTION OBJECTS ====\n")
176         for c in conn:
177             print("Connection --")
178             print("\tConnection name: %s" % c['name'][0])
179             print("\tEnabled        : %s" % attr_default(c, 'enabledConnection', 'TRUE'))
180             print("\tServer DNS name : %s" % server_dns)
181             print("\tServer DN name  : %s" % c['fromServer'][0])
182             print("\t\tTransportType: RPC")
183             print("\t\toptions: 0x%08X" % int(attr_default(c, 'options', 0)))
184             if not 'mS-DS-ReplicatesNCReason' in c:
185                 print("Warning: No NC replicated for Connection!")
186                 continue
187             for r in c['mS-DS-ReplicatesNCReason']:
188                 a = str(r).split(':')
189                 print("\t\tReplicatesNC: %s" % a[3])
190                 print("\t\tReason: 0x%08x" % int(a[2]))
191                 for s in reasons:
192                     if getattr(dsdb, s, 0) & int(a[2]):
193                         print("\t\t\t%s" % s)
194
195
196 class cmd_drs_kcc(Command):
197     """trigger knowledge consistency center run"""
198
199     synopsis = "%prog drs kcc <DC>"
200
201     takes_optiongroups = {
202         "sambaopts": options.SambaOptions,
203         "versionopts": options.VersionOptions,
204         "credopts": options.CredentialsOptions,
205     }
206
207     takes_args = ["DC"]
208
209     def run(self, DC, sambaopts=None,
210             credopts=None, versionopts=None, server=None):
211
212         self.server = DC
213         self.lp = sambaopts.get_loadparm()
214
215         self.creds = credopts.get_credentials(self.lp)
216         if not self.creds.authentication_requested():
217             self.creds.set_machine_account(self.lp)
218
219         drsuapi_connect(self)
220
221         req1 = drsuapi.DsExecuteKCC1()
222         try:
223             self.drsuapi.DsExecuteKCC(self.drsuapi_handle, 1, req1)
224         except Exception, e:
225             raise CommandError("DsExecuteKCC failed", e)
226         print("Consistency check on %s successful." % DC)
227
228
229
230 class cmd_drs_replicate(Command):
231     """replicate a naming context between two DCs"""
232
233     synopsis = "%prog drs replicate <DEST_DC> <SOURCE_DC> <NC>"
234
235     takes_optiongroups = {
236         "sambaopts": options.SambaOptions,
237         "versionopts": options.VersionOptions,
238         "credopts": options.CredentialsOptions,
239     }
240
241     takes_args = ["DEST_DC", "SOURCE_DC", "NC"]
242
243     takes_options = [
244         Option("--add-ref", help="use ADD_REF to add to repsTo on source", action="store_true"),
245         ]
246
247     def run(self, DEST_DC, SOURCE_DC, NC, add_ref=False,
248             sambaopts=None,
249             credopts=None, versionopts=None, server=None):
250
251         self.server = DEST_DC
252         self.lp = sambaopts.get_loadparm()
253
254         self.creds = credopts.get_credentials(self.lp)
255         if not self.creds.authentication_requested():
256             self.creds.set_machine_account(self.lp)
257
258         drsuapi_connect(self)
259         samdb_connect(self)
260
261         # we need to find the NTDS GUID of the source DC
262         msg = self.samdb.search(base=self.samdb.get_config_basedn(),
263                                 expression="(&(objectCategory=server)(|(name=%s)(dNSHostName=%s)))" % (SOURCE_DC,
264                                                                                                        SOURCE_DC),
265                                 attrs=[])
266         if len(msg) == 0:
267             raise CommandError("Failed to find source DC %s" % SOURCE_DC)
268         server_dn = msg[0]['dn']
269
270         msg = self.samdb.search(base=server_dn, scope=ldb.SCOPE_ONELEVEL,
271                                 expression="(|(objectCategory=nTDSDSA)(objectCategory=nTDSDSARO))",
272                                 attrs=['objectGUID', 'options'])
273         if len(msg) == 0:
274             raise CommandError("Failed to find source NTDS DN %s" % SOURCE_DC)
275         source_dsa_guid = msg[0]['objectGUID'][0]
276         options = int(attr_default(msg, 'options', 0))
277
278         nc = drsuapi.DsReplicaObjectIdentifier()
279         nc.dn = NC
280
281         req1 = drsuapi.DsReplicaSyncRequest1()
282         req1.naming_context = nc;
283         req1.options = 0
284         if not (options & dsdb.DS_NTDSDSA_OPT_DISABLE_OUTBOUND_REPL):
285             req1.options |= drsuapi.DRSUAPI_DRS_WRIT_REP
286         if add_ref:
287             req1.options |= drsuapi.DRSUAPI_DRS_ADD_REF
288         req1.source_dsa_guid = misc.GUID(source_dsa_guid)
289
290         try:
291             self.drsuapi.DsReplicaSync(self.drsuapi_handle, 1, req1)
292         except Exception, e:
293             raise CommandError("DsReplicaSync failed", estr)
294         print("Replicate from %s to %s was successful." % (SOURCE_DC, DEST_DC))
295
296
297
298 class cmd_drs_bind(Command):
299     """show DRS capabilities of a server"""
300
301     synopsis = "%prog drs bind <DC>"
302
303     takes_optiongroups = {
304         "sambaopts": options.SambaOptions,
305         "versionopts": options.VersionOptions,
306         "credopts": options.CredentialsOptions,
307     }
308
309     takes_args = ["DC"]
310
311     def run(self, DC, sambaopts=None,
312             credopts=None, versionopts=None, server=None):
313
314         self.server = DC
315         self.lp = sambaopts.get_loadparm()
316
317         self.creds = credopts.get_credentials(self.lp)
318         if not self.creds.authentication_requested():
319             self.creds.set_machine_account(self.lp)
320
321         drsuapi_connect(self)
322         samdb_connect(self)
323
324         bind_info = drsuapi.DsBindInfoCtr()
325         bind_info.length = 28
326         bind_info.info = drsuapi.DsBindInfo28()
327         (info, handle) = self.drsuapi.DsBind(misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID), bind_info)
328
329         optmap = [
330             ("DRSUAPI_SUPPORTED_EXTENSION_BASE" ,                       "DRS_EXT_BASE"),
331             ("DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION" ,          "DRS_EXT_ASYNCREPL"),
332             ("DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI" ,                  "DRS_EXT_REMOVEAPI"),
333             ("DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2" ,                 "DRS_EXT_MOVEREQ_V2"),
334             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS" ,            "DRS_EXT_GETCHG_DEFLATE"),
335             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1" ,                  "DRS_EXT_DCINFO_V1"),
336             ("DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION" ,   "DRS_EXT_RESTORE_USN_OPTIMIZATION"),
337             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY" ,                   "DRS_EXT_ADDENTRY"),
338             ("DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE" ,                "DRS_EXT_KCC_EXECUTE"),
339             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2" ,                "DRS_EXT_ADDENTRY_V2"),
340             ("DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION" ,   "DRS_EXT_LINKED_VALUE_REPLICATION"),
341             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2" ,                  "DRS_EXT_DCINFO_V2"),
342             ("DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD","DRS_EXT_INSTANCE_TYPE_NOT_REQ_ON_MOD"),
343             ("DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND" ,                "DRS_EXT_CRYPTO_BIND"),
344             ("DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO" ,              "DRS_EXT_GET_REPL_INFO"),
345             ("DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION" ,          "DRS_EXT_STRONG_ENCRYPTION"),
346             ("DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01" ,                 "DRS_EXT_DCINFO_VFFFFFFFF"),
347             ("DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP" ,      "DRS_EXT_TRANSITIVE_MEMBERSHIP"),
348             ("DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY" ,            "DRS_EXT_ADD_SID_HISTORY"),
349             ("DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3" ,                 "DRS_EXT_POST_BETA3"),
350             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V5" ,               "DRS_EXT_GETCHGREQ_V5"),
351             ("DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2" ,           "DRS_EXT_GETMEMBERSHIPS2"),
352             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6" ,               "DRS_EXT_GETCHGREQ_V6"),
353             ("DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS" ,              "DRS_EXT_NONDOMAIN_NCS"),
354             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8" ,               "DRS_EXT_GETCHGREQ_V8"),
355             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5" ,             "DRS_EXT_GETCHGREPLY_V5"),
356             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6" ,             "DRS_EXT_GETCHGREPLY_V6"),
357             ("DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3" ,           "DRS_EXT_WHISTLER_BETA3"),
358             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7" ,             "DRS_EXT_WHISTLER_BETA3"),
359             ("DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT" ,              "DRS_EXT_WHISTLER_BETA3"),
360             ("DRSUAPI_SUPPORTED_EXTENSION_XPRESS_COMPRESS" ,            "DRS_EXT_W2K3_DEFLATE"),
361             ("DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10" ,              "DRS_EXT_GETCHGREQ_V10"),
362             ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART2" ,             "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART2"),
363             ("DRSUAPI_SUPPORTED_EXTENSION_RESERVED_PART3" ,             "DRS_EXT_RESERVED_FOR_WIN2K_OR_DOTNET_PART3")
364             ]
365
366         optmap_ext = [
367             ("DRSUAPI_SUPPORTED_EXTENSION_ADAM",                        "DRS_EXT_ADAM"),
368             ("DRSUAPI_SUPPORTED_EXTENSION_LH_BETA2",                    "DRS_EXT_LH_BETA2"),
369             ("DRSUAPI_SUPPORTED_EXTENSION_RECYCLE_BIN",                 "DRS_EXT_RECYCLE_BIN")]
370
371         print("Bind to %s succeeded." % DC)
372         print("Extensions supported:")
373         for (opt, str) in optmap:
374             optval = getattr(drsuapi, opt, 0)
375             if info.info.supported_extensions & optval:
376                 yesno = "Yes"
377             else:
378                 yesno = "No "
379             print("  %-60s: %s (%s)" % (opt, yesno, str))
380
381         if isinstance(info.info, drsuapi.DsBindInfo48):
382             print("\nExtended Extensions supported:")
383             for (opt, str) in optmap_ext:
384                 optval = getattr(drsuapi, opt, 0)
385                 if info.info.supported_extensions_ext & optval:
386                     yesno = "Yes"
387                 else:
388                     yesno = "No "
389                 print("  %-60s: %s (%s)" % (opt, yesno, str))
390
391         print("\nSite GUID: %s" % info.info.site_guid)
392         print("Repl epoch: %u" % info.info.repl_epoch)
393         if isinstance(info.info, drsuapi.DsBindInfo48):
394             print("Forest GUID: %s" % info.info.config_dn_guid)
395
396
397 class cmd_drs(SuperCommand):
398     """DRS commands"""
399
400     subcommands = {}
401     subcommands["bind"] = cmd_drs_bind()
402     subcommands["kcc"] = cmd_drs_kcc()
403     subcommands["replicate"] = cmd_drs_replicate()
404     subcommands["showrepl"] = cmd_drs_showrepl()