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