getncchanges.py: Add test for GET_ANC and linked attributes
[nivanova/samba-autobuild/.git] / source4 / torture / drs / python / drs_base.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # Unix SMB/CIFS implementation.
5 # Copyright (C) Kamen Mazdrashki <kamenim@samba.org> 2011
6 # Copyright (C) Andrew Bartlett <abartlet@samba.org> 2016
7 # Copyright (C) Catalyst IT Ltd. 2016
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 sys
24 import time
25 import os
26 import ldb
27
28 sys.path.insert(0, "bin/python")
29 import samba.tests
30 from samba.tests.samba_tool.base import SambaToolCmdTest
31 from samba import dsdb
32 from samba.dcerpc import drsuapi, misc, drsblobs, security
33 from samba.ndr import ndr_unpack, ndr_pack
34 from samba.drs_utils import drs_DsBind
35
36 from ldb import (
37     SCOPE_BASE,
38     Message,
39     FLAG_MOD_REPLACE,
40     )
41
42
43 class DrsBaseTestCase(SambaToolCmdTest):
44     """Base class implementation for all DRS python tests.
45        It is intended to provide common initialization and
46        and functionality used by all DRS tests in drs/python
47        test package. For instance, DC1 and DC2 are always used
48        to pass URLs for DCs to test against"""
49
50     def setUp(self):
51         super(DrsBaseTestCase, self).setUp()
52
53         # connect to DCs
54         url_dc = samba.tests.env_get_var_value("DC1")
55         (self.ldb_dc1, self.info_dc1) = samba.tests.connect_samdb_ex(url_dc,
56                                                                      ldap_only=True)
57         url_dc = samba.tests.env_get_var_value("DC2")
58         (self.ldb_dc2, self.info_dc2) = samba.tests.connect_samdb_ex(url_dc,
59                                                                      ldap_only=True)
60
61         # cache some of RootDSE props
62         self.schema_dn = self.info_dc1["schemaNamingContext"][0]
63         self.domain_dn = self.info_dc1["defaultNamingContext"][0]
64         self.config_dn = self.info_dc1["configurationNamingContext"][0]
65         self.forest_level = int(self.info_dc1["forestFunctionality"][0])
66
67         # we will need DCs DNS names for 'samba-tool drs' command
68         self.dnsname_dc1 = self.info_dc1["dnsHostName"][0]
69         self.dnsname_dc2 = self.info_dc2["dnsHostName"][0]
70
71         # for debugging the test code
72         self._debug = False
73
74     def tearDown(self):
75         super(DrsBaseTestCase, self).tearDown()
76
77     def _GUID_string(self, guid):
78         return self.ldb_dc1.schema_format_value("objectGUID", guid)
79
80     def _ldap_schemaUpdateNow(self, sam_db):
81         rec = {"dn": "",
82                "schemaUpdateNow": "1"}
83         m = Message.from_dict(sam_db, rec, FLAG_MOD_REPLACE)
84         sam_db.modify(m)
85
86     def _deleted_objects_dn(self, sam_ldb):
87         wkdn = "<WKGUID=18E2EA80684F11D2B9AA00C04F79F805,%s>" % self.domain_dn
88         res = sam_ldb.search(base=wkdn,
89                              scope=SCOPE_BASE,
90                              controls=["show_deleted:1"])
91         self.assertEquals(len(res), 1)
92         return str(res[0]["dn"])
93
94     def _lost_and_found_dn(self, sam_ldb, nc):
95         wkdn = "<WKGUID=%s,%s>" % (dsdb.DS_GUID_LOSTANDFOUND_CONTAINER, nc)
96         res = sam_ldb.search(base=wkdn,
97                              scope=SCOPE_BASE)
98         self.assertEquals(len(res), 1)
99         return str(res[0]["dn"])
100
101     def _make_obj_name(self, prefix):
102         return prefix + time.strftime("%s", time.gmtime())
103
104     def _samba_tool_cmd_list(self, drs_command):
105         # make command line credentials string
106
107         ccache_name = self.get_creds_ccache_name()
108
109         # Tunnel the command line credentials down to the
110         # subcommand to avoid a new kinit
111         cmdline_auth = "--krb5-ccache=%s" % ccache_name
112
113         # bin/samba-tool drs <drs_command> <cmdline_auth>
114         return ["drs", drs_command, cmdline_auth]
115
116     def _net_drs_replicate(self, DC, fromDC, nc_dn=None, forced=True, local=False, full_sync=False):
117         if nc_dn is None:
118             nc_dn = self.domain_dn
119         # make base command line
120         samba_tool_cmdline = self._samba_tool_cmd_list("replicate")
121         # bin/samba-tool drs replicate <Dest_DC_NAME> <Src_DC_NAME> <Naming Context>
122         samba_tool_cmdline += [DC, fromDC, nc_dn]
123
124         if forced:
125             samba_tool_cmdline += ["--sync-forced"]
126         if local:
127             samba_tool_cmdline += ["--local"]
128         if full_sync:
129             samba_tool_cmdline += ["--full-sync"]
130
131         (result, out, err) = self.runsubcmd(*samba_tool_cmdline)
132         self.assertCmdSuccess(result, out, err)
133         self.assertEquals(err,"","Shouldn't be any error messages")
134
135     def _enable_inbound_repl(self, DC):
136         # make base command line
137         samba_tool_cmd = self._samba_tool_cmd_list("options")
138         # disable replication
139         samba_tool_cmd += [DC, "--dsa-option=-DISABLE_INBOUND_REPL"]
140         (result, out, err) = self.runsubcmd(*samba_tool_cmd)
141         self.assertCmdSuccess(result, out, err)
142         self.assertEquals(err,"","Shouldn't be any error messages")
143
144     def _disable_inbound_repl(self, DC):
145         # make base command line
146         samba_tool_cmd = self._samba_tool_cmd_list("options")
147         # disable replication
148         samba_tool_cmd += [DC, "--dsa-option=+DISABLE_INBOUND_REPL"]
149         (result, out, err) = self.runsubcmd(*samba_tool_cmd)
150         self.assertCmdSuccess(result, out, err)
151         self.assertEquals(err,"","Shouldn't be any error messages")
152
153     def _enable_all_repl(self, DC):
154         self._enable_inbound_repl(DC)
155         # make base command line
156         samba_tool_cmd = self._samba_tool_cmd_list("options")
157         # enable replication
158         samba_tool_cmd += [DC, "--dsa-option=-DISABLE_OUTBOUND_REPL"]
159         (result, out, err) = self.runsubcmd(*samba_tool_cmd)
160         self.assertCmdSuccess(result, out, err)
161         self.assertEquals(err,"","Shouldn't be any error messages")
162
163     def _disable_all_repl(self, DC):
164         self._disable_inbound_repl(DC)
165         # make base command line
166         samba_tool_cmd = self._samba_tool_cmd_list("options")
167         # disable replication
168         samba_tool_cmd += [DC, "--dsa-option=+DISABLE_OUTBOUND_REPL"]
169         (result, out, err) = self.runsubcmd(*samba_tool_cmd)
170         self.assertCmdSuccess(result, out, err)
171         self.assertEquals(err,"","Shouldn't be any error messages")
172
173     def _get_highest_hwm_utdv(self, ldb_conn):
174         res = ldb_conn.search("", scope=ldb.SCOPE_BASE, attrs=["highestCommittedUSN"])
175         hwm = drsuapi.DsReplicaHighWaterMark()
176         hwm.tmp_highest_usn = long(res[0]["highestCommittedUSN"][0])
177         hwm.reserved_usn = 0
178         hwm.highest_usn = hwm.tmp_highest_usn
179
180         utdv = drsuapi.DsReplicaCursorCtrEx()
181         cursors = []
182         c1 = drsuapi.DsReplicaCursor()
183         c1.source_dsa_invocation_id = misc.GUID(ldb_conn.get_invocation_id())
184         c1.highest_usn = hwm.highest_usn
185         cursors.append(c1)
186         utdv.count = len(cursors)
187         utdv.cursors = cursors
188         return (hwm, utdv)
189
190     def _get_identifier(self, ldb_conn, dn):
191         res = ldb_conn.search(dn, scope=ldb.SCOPE_BASE,
192                 attrs=["objectGUID", "objectSid"])
193         id = drsuapi.DsReplicaObjectIdentifier()
194         id.guid = ndr_unpack(misc.GUID, res[0]['objectGUID'][0])
195         if "objectSid" in res[0]:
196             id.sid = ndr_unpack(security.dom_sid, res[0]['objectSid'][0])
197         id.dn = str(res[0].dn)
198         return id
199
200     def _get_ctr6_links(self, ctr6):
201         """
202         Unpacks the linked attributes from a DsGetNCChanges response
203         and returns them as a list.
204         """
205         ctr6_links = []
206         for lidx in range(0, ctr6.linked_attributes_count):
207             l = ctr6.linked_attributes[lidx]
208             try:
209                 target = ndr_unpack(drsuapi.DsReplicaObjectIdentifier3,
210                                     l.value.blob)
211             except:
212                 target = ndr_unpack(drsuapi.DsReplicaObjectIdentifier3Binary,
213                                     l.value.blob)
214             al = AbstractLink(l.attid, l.flags,
215                               l.identifier.guid,
216                               target.guid, target.dn)
217             ctr6_links.append(al)
218
219         return ctr6_links
220
221     def _ctr6_debug(self, ctr6):
222         """
223         Displays basic info contained in a DsGetNCChanges response.
224         Having this debug code allows us to see the difference in behaviour
225         between Samba and Windows easier. Turn on the self._debug flag to see it.
226         """
227
228         if self._debug:
229             print("------------ recvd CTR6 -------------")
230
231             next_object = ctr6.first_object
232             for i in range(0, ctr6.object_count):
233                 print("Obj %d: %s %s" %(i, next_object.object.identifier.dn[:22],
234                                         next_object.object.identifier.guid))
235                 next_object = next_object.next_object
236
237             print("Linked Attributes: %d" % ctr6.linked_attributes_count)
238             ctr6_links = self._get_ctr6_links(ctr6)
239             for link in ctr6_links:
240                 print("Link Tgt %s... <-- Src %s"
241                       %(link.targetDN[:22], link.identifier))
242
243             print("HWM:     %d" %(ctr6.new_highwatermark.highest_usn))
244             print("Tmp HWM: %d" %(ctr6.new_highwatermark.tmp_highest_usn))
245             print("More data: %d" %(ctr6.more_data))
246
247     def _get_replication(self, replica_flags,
248                           drs_error=drsuapi.DRSUAPI_EXOP_ERR_NONE, drs=None, drs_handle=None,
249                           highwatermark=None, uptodateness_vector=None,
250                           more_flags=0, max_objects=133, exop=0,
251                           dest_dsa=drsuapi.DRSUAPI_DS_BIND_GUID_W2K3,
252                           source_dsa=None, invocation_id=None, nc_dn_str=None):
253         """
254         Builds a DsGetNCChanges request based on the information provided
255         and returns the response received from the DC.
256         """
257         if source_dsa is None:
258             source_dsa = self.ldb_dc1.get_ntds_GUID()
259         if invocation_id is None:
260             invocation_id = self.ldb_dc1.get_invocation_id()
261         if nc_dn_str is None:
262             nc_dn_str = self.ldb_dc1.domain_dn()
263
264         if highwatermark is None:
265             if self.default_hwm is None:
266                 (highwatermark, _) = self._get_highest_hwm_utdv(self.ldb_dc1)
267             else:
268                 highwatermark = self.default_hwm
269
270         if drs is None:
271             drs = self.drs
272         if drs_handle is None:
273             drs_handle = self.drs_handle
274
275         req10 = self._getnc_req10(dest_dsa=dest_dsa,
276                                   invocation_id=invocation_id,
277                                   nc_dn_str=nc_dn_str,
278                                   exop=exop,
279                                   max_objects=max_objects,
280                                   replica_flags=replica_flags)
281         req10.highwatermark = highwatermark
282         if uptodateness_vector is not None:
283             uptodateness_vector_v1 = drsuapi.DsReplicaCursorCtrEx()
284             cursors = []
285             for i in xrange(0, uptodateness_vector.count):
286                 c = uptodateness_vector.cursors[i]
287                 c1 = drsuapi.DsReplicaCursor()
288                 c1.source_dsa_invocation_id = c.source_dsa_invocation_id
289                 c1.highest_usn = c.highest_usn
290                 cursors.append(c1)
291             uptodateness_vector_v1.count = len(cursors)
292             uptodateness_vector_v1.cursors = cursors
293             req10.uptodateness_vector = uptodateness_vector_v1
294         (level, ctr) = drs.DsGetNCChanges(drs_handle, 10, req10)
295         self._ctr6_debug(ctr)
296
297         self.assertEqual(level, 6, "expected level 6 response!")
298         self.assertEqual(ctr.source_dsa_guid, misc.GUID(source_dsa))
299         self.assertEqual(ctr.source_dsa_invocation_id, misc.GUID(invocation_id))
300         self.assertEqual(ctr.extended_ret, drs_error)
301
302         return ctr
303
304     def _check_replication(self, expected_dns, replica_flags, expected_links=[],
305                            drs_error=drsuapi.DRSUAPI_EXOP_ERR_NONE, drs=None, drs_handle=None,
306                            highwatermark=None, uptodateness_vector=None,
307                            more_flags=0, more_data=False,
308                            dn_ordered=True, links_ordered=True,
309                            max_objects=133, exop=0,
310                            dest_dsa=drsuapi.DRSUAPI_DS_BIND_GUID_W2K3,
311                            source_dsa=None, invocation_id=None, nc_dn_str=None,
312                            nc_object_count=0, nc_linked_attributes_count=0):
313         """
314         Makes sure that replication returns the specific error given.
315         """
316
317         # send a DsGetNCChanges to the DC
318         ctr6 = self._get_replication(replica_flags,
319                                      drs_error, drs, drs_handle,
320                                      highwatermark, uptodateness_vector,
321                                      more_flags, max_objects, exop, dest_dsa,
322                                      source_dsa, invocation_id, nc_dn_str)
323
324         # check the response is what we expect
325         self._check_ctr6(ctr6, expected_dns, expected_links,
326                          nc_object_count=nc_object_count, more_data=more_data,
327                          dn_ordered=dn_ordered)
328         return (ctr6.new_highwatermark, ctr6.uptodateness_vector)
329
330
331     def _get_ctr6_dn_list(self, ctr6):
332         """
333         Returns the DNs contained in a DsGetNCChanges response.
334         """
335         dn_list = []
336         next_object = ctr6.first_object
337         for i in range(0, ctr6.object_count):
338             dn_list.append(next_object.object.identifier.dn)
339             next_object = next_object.next_object
340         self.assertEqual(next_object, None)
341
342         return dn_list
343
344
345     def _check_ctr6(self, ctr6, expected_dns=[], expected_links=[],
346                     dn_ordered=True, links_ordered=True,
347                     more_data=False, nc_object_count=0,
348                     nc_linked_attributes_count=0, drs_error=0):
349         """
350         Check that a ctr6 matches the specified parameters.
351         """
352         self.assertEqual(ctr6.object_count, len(expected_dns))
353         self.assertEqual(ctr6.linked_attributes_count, len(expected_links))
354         self.assertEqual(ctr6.more_data, more_data)
355         self.assertEqual(ctr6.nc_object_count, nc_object_count)
356         self.assertEqual(ctr6.nc_linked_attributes_count, nc_linked_attributes_count)
357         self.assertEqual(ctr6.drs_error[0], drs_error)
358
359         ctr6_dns = self._get_ctr6_dn_list(ctr6)
360
361         i = 0
362         for dn in expected_dns:
363             # Expect them back in the exact same order as specified.
364             if dn_ordered:
365                 self.assertNotEqual(ctr6_dns[i], None)
366                 self.assertEqual(ctr6_dns[i], dn)
367                 i = i + 1
368             # Don't care what order
369             else:
370                 self.assertTrue(dn in ctr6_dns, "Couldn't find DN '%s' anywhere in ctr6 response." % dn)
371
372         # Extract the links from the response
373         ctr6_links = self._get_ctr6_links(ctr6)
374         expected_links.sort()
375
376         lidx = 0
377         for el in expected_links:
378             if links_ordered:
379                 self.assertEqual(el, ctr6_links[lidx])
380                 lidx += 1
381             else:
382                 self.assertTrue(el in ctr6_links, "Couldn't find link '%s' anywhere in ctr6 response." % el)
383
384     def _exop_req8(self, dest_dsa, invocation_id, nc_dn_str, exop,
385                    replica_flags=0, max_objects=0, partial_attribute_set=None,
386                    partial_attribute_set_ex=None, mapping_ctr=None):
387         req8 = drsuapi.DsGetNCChangesRequest8()
388
389         req8.destination_dsa_guid = misc.GUID(dest_dsa) if dest_dsa else misc.GUID()
390         req8.source_dsa_invocation_id = misc.GUID(invocation_id)
391         req8.naming_context = drsuapi.DsReplicaObjectIdentifier()
392         req8.naming_context.dn = unicode(nc_dn_str)
393         req8.highwatermark = drsuapi.DsReplicaHighWaterMark()
394         req8.highwatermark.tmp_highest_usn = 0
395         req8.highwatermark.reserved_usn = 0
396         req8.highwatermark.highest_usn = 0
397         req8.uptodateness_vector = None
398         req8.replica_flags = replica_flags
399         req8.max_object_count = max_objects
400         req8.max_ndr_size = 402116
401         req8.extended_op = exop
402         req8.fsmo_info = 0
403         req8.partial_attribute_set = partial_attribute_set
404         req8.partial_attribute_set_ex = partial_attribute_set_ex
405         if mapping_ctr:
406             req8.mapping_ctr = mapping_ctr
407         else:
408             req8.mapping_ctr.num_mappings = 0
409             req8.mapping_ctr.mappings = None
410
411         return req8
412
413     def _getnc_req10(self, dest_dsa, invocation_id, nc_dn_str, exop,
414                      replica_flags=0, max_objects=0, partial_attribute_set=None,
415                      partial_attribute_set_ex=None, mapping_ctr=None,
416                      more_flags=0):
417         req10 = drsuapi.DsGetNCChangesRequest10()
418
419         req10.destination_dsa_guid = misc.GUID(dest_dsa) if dest_dsa else misc.GUID()
420         req10.source_dsa_invocation_id = misc.GUID(invocation_id)
421         req10.naming_context = drsuapi.DsReplicaObjectIdentifier()
422         req10.naming_context.dn = unicode(nc_dn_str)
423         req10.highwatermark = drsuapi.DsReplicaHighWaterMark()
424         req10.highwatermark.tmp_highest_usn = 0
425         req10.highwatermark.reserved_usn = 0
426         req10.highwatermark.highest_usn = 0
427         req10.uptodateness_vector = None
428         req10.replica_flags = replica_flags
429         req10.max_object_count = max_objects
430         req10.max_ndr_size = 402116
431         req10.extended_op = exop
432         req10.fsmo_info = 0
433         req10.partial_attribute_set = partial_attribute_set
434         req10.partial_attribute_set_ex = partial_attribute_set_ex
435         if mapping_ctr:
436             req10.mapping_ctr = mapping_ctr
437         else:
438             req10.mapping_ctr.num_mappings = 0
439             req10.mapping_ctr.mappings = None
440         req10.more_flags = more_flags
441
442         return req10
443
444     def _ds_bind(self, server_name, creds=None):
445         binding_str = "ncacn_ip_tcp:%s[seal]" % server_name
446
447         if creds is None:
448             creds = self.get_credentials()
449         drs = drsuapi.drsuapi(binding_str, self.get_loadparm(), creds)
450         (drs_handle, supported_extensions) = drs_DsBind(drs)
451         return (drs, drs_handle)
452
453
454 class AbstractLink:
455     def __init__(self, attid, flags, identifier, targetGUID,
456                  targetDN=""):
457         self.attid = attid
458         self.flags = flags
459         self.identifier = str(identifier)
460         self.selfGUID_blob = ndr_pack(identifier)
461         self.targetGUID = str(targetGUID)
462         self.targetGUID_blob = ndr_pack(targetGUID)
463         self.targetDN = targetDN
464
465     def __repr__(self):
466         return "AbstractLink(0x%08x, 0x%08x, %s, %s)" % (
467                 self.attid, self.flags, self.identifier, self.targetGUID)
468
469     def __internal_cmp__(self, other, verbose=False):
470         """See CompareLinks() in MS-DRSR section 4.1.10.5.17"""
471         if not isinstance(other, AbstractLink):
472             if verbose:
473                 print "AbstractLink.__internal_cmp__(%r, %r) => wrong type" % (self, other)
474             return NotImplemented
475
476         c = cmp(self.selfGUID_blob, other.selfGUID_blob)
477         if c != 0:
478             if verbose:
479                 print "AbstractLink.__internal_cmp__(%r, %r) => %d different identifier" % (self, other, c)
480             return c
481
482         c = other.attid - self.attid
483         if c != 0:
484             if verbose:
485                 print "AbstractLink.__internal_cmp__(%r, %r) => %d different attid" % (self, other, c)
486             return c
487
488         self_active = self.flags & drsuapi.DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE
489         other_active = other.flags & drsuapi.DRSUAPI_DS_LINKED_ATTRIBUTE_FLAG_ACTIVE
490
491         c = self_active - other_active
492         if c != 0:
493             if verbose:
494                 print "AbstractLink.__internal_cmp__(%r, %r) => %d different FLAG_ACTIVE" % (self, other, c)
495             return c
496
497         c = cmp(self.targetGUID_blob, other.targetGUID_blob)
498         if c != 0:
499             if verbose:
500                 print "AbstractLink.__internal_cmp__(%r, %r) => %d different target" % (self, other, c)
501             return c
502
503         c = self.flags - other.flags
504         if c != 0:
505             if verbose:
506                 print "AbstractLink.__internal_cmp__(%r, %r) => %d different flags" % (self, other, c)
507             return c
508
509         return 0
510
511     def __lt__(self, other):
512         c = self.__internal_cmp__(other)
513         if c == NotImplemented:
514             return NotImplemented
515         if c < 0:
516             return True
517         return False
518
519     def __le__(self, other):
520         c = self.__internal_cmp__(other)
521         if c == NotImplemented:
522             return NotImplemented
523         if c <= 0:
524             return True
525         return False
526
527     def __eq__(self, other):
528         c = self.__internal_cmp__(other, verbose=True)
529         if c == NotImplemented:
530             return NotImplemented
531         if c == 0:
532             return True
533         return False
534
535     def __ne__(self, other):
536         c = self.__internal_cmp__(other)
537         if c == NotImplemented:
538             return NotImplemented
539         if c != 0:
540             return True
541         return False
542
543     def __gt__(self, other):
544         c = self.__internal_cmp__(other)
545         if c == NotImplemented:
546             return NotImplemented
547         if c > 0:
548             return True
549         return False
550
551     def __ge__(self, other):
552         c = self.__internal_cmp__(other)
553         if c == NotImplemented:
554             return NotImplemented
555         if c >= 0:
556             return True
557         return False
558
559     def __hash__(self):
560         return hash((self.attid, self.flags, self.identifier, self.targetGUID))