testprogs/blackbox: PY3 bulk change for python scripts use correct python
[amitay/samba.git] / python / samba / drs_utils.py
1 # DRS utility code
2 #
3 # Copyright Andrew Tridgell 2010
4 # Copyright Andrew Bartlett 2017
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 #
19
20 from samba.dcerpc import drsuapi, misc, drsblobs
21 from samba.net import Net
22 from samba.ndr import ndr_unpack
23 from samba import dsdb
24 from samba import werror
25 from samba import WERRORError
26 import samba
27 import ldb
28 from samba.dcerpc.drsuapi import (DRSUAPI_ATTID_name,
29                                   DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8,
30                                   DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10)
31 import re
32
33
34 class drsException(Exception):
35     """Base element for drs errors"""
36
37     def __init__(self, value):
38         self.value = value
39
40     def __str__(self):
41         return "drsException: " + self.value
42
43
44 def drsuapi_connect(server, lp, creds):
45     """Make a DRSUAPI connection to the server.
46
47     :param server: the name of the server to connect to
48     :param lp: a samba line parameter object
49     :param creds: credential used for the connection
50     :return: A tuple with the drsuapi bind object, the drsuapi handle
51                 and the supported extensions.
52     :raise drsException: if the connection fails
53     """
54
55     binding_options = "seal"
56     if lp.log_level() >= 9:
57         binding_options += ",print"
58     binding_string = "ncacn_ip_tcp:%s[%s]" % (server, binding_options)
59     try:
60         drsuapiBind = drsuapi.drsuapi(binding_string, lp, creds)
61         (drsuapiHandle, bindSupportedExtensions) = drs_DsBind(drsuapiBind)
62     except Exception as e:
63         raise drsException("DRS connection to %s failed: %s" % (server, e))
64
65     return (drsuapiBind, drsuapiHandle, bindSupportedExtensions)
66
67
68 def sendDsReplicaSync(drsuapiBind, drsuapi_handle, source_dsa_guid,
69                       naming_context, req_option):
70     """Send DS replica sync request.
71
72     :param drsuapiBind: a drsuapi Bind object
73     :param drsuapi_handle: a drsuapi handle on the drsuapi connection
74     :param source_dsa_guid: the guid of the source dsa for the replication
75     :param naming_context: the DN of the naming context to replicate
76     :param req_options: replication options for the DsReplicaSync call
77     :raise drsException: if any error occur while sending and receiving the
78         reply for the dsReplicaSync
79     """
80
81     nc = drsuapi.DsReplicaObjectIdentifier()
82     nc.dn = naming_context
83
84     req1 = drsuapi.DsReplicaSyncRequest1()
85     req1.naming_context = nc
86     req1.options = req_option
87     req1.source_dsa_guid = misc.GUID(source_dsa_guid)
88
89     try:
90         drsuapiBind.DsReplicaSync(drsuapi_handle, 1, req1)
91     except Exception as estr:
92         raise drsException("DsReplicaSync failed %s" % estr)
93
94
95 def sendRemoveDsServer(drsuapiBind, drsuapi_handle, server_dsa_dn, domain):
96     """Send RemoveDSServer request.
97
98     :param drsuapiBind: a drsuapi Bind object
99     :param drsuapi_handle: a drsuapi handle on the drsuapi connection
100     :param server_dsa_dn: a DN object of the server's dsa that we want to
101         demote
102     :param domain: a DN object of the server's domain
103     :raise drsException: if any error occur while sending and receiving the
104         reply for the DsRemoveDSServer
105     """
106
107     try:
108         req1 = drsuapi.DsRemoveDSServerRequest1()
109         req1.server_dn = str(server_dsa_dn)
110         req1.domain_dn = str(domain)
111         req1.commit = 1
112
113         drsuapiBind.DsRemoveDSServer(drsuapi_handle, 1, req1)
114     except Exception as estr:
115         raise drsException("DsRemoveDSServer failed %s" % estr)
116
117
118 def drs_DsBind(drs):
119     '''make a DsBind call, returning the binding handle'''
120     bind_info = drsuapi.DsBindInfoCtr()
121     bind_info.length = 28
122     bind_info.info = drsuapi.DsBindInfo28()
123     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_BASE
124     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION
125     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI
126     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2
127     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS
128     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1
129     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION
130     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE
131     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2
132     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION
133     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2
134     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD
135     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND
136     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO
137     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION
138     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01
139     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP
140     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY
141     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3
142     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2
143     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6
144     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS
145     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8
146     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5
147     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6
148     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3
149     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7
150     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT
151     (info, handle) = drs.DsBind(misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID), bind_info)
152
153     return (handle, info.info.supported_extensions)
154
155
156 def drs_get_rodc_partial_attribute_set(samdb):
157     '''get a list of attributes for RODC replication'''
158     partial_attribute_set = drsuapi.DsPartialAttributeSet()
159     partial_attribute_set.version = 1
160
161     attids = []
162
163     # the exact list of attids we send is quite critical. Note that
164     # we do ask for the secret attributes, but set SPECIAL_SECRET_PROCESSING
165     # to zero them out
166     schema_dn = samdb.get_schema_basedn()
167     res = samdb.search(base=schema_dn, scope=ldb.SCOPE_SUBTREE,
168                        expression="objectClass=attributeSchema",
169                        attrs=["lDAPDisplayName", "systemFlags",
170                               "searchFlags"])
171
172     for r in res:
173         ldap_display_name = str(r["lDAPDisplayName"][0])
174         if "systemFlags" in r:
175             system_flags      = r["systemFlags"][0]
176             if (int(system_flags) & (samba.dsdb.DS_FLAG_ATTR_NOT_REPLICATED |
177                                      samba.dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED)):
178                 continue
179         if "searchFlags" in r:
180             search_flags = r["searchFlags"][0]
181             if (int(search_flags) & samba.dsdb.SEARCH_FLAG_RODC_ATTRIBUTE):
182                 continue
183         attid = samdb.get_attid_from_lDAPDisplayName(ldap_display_name)
184         attids.append(int(attid))
185
186     # the attids do need to be sorted, or windows doesn't return
187     # all the attributes we need
188     attids.sort()
189     partial_attribute_set.attids         = attids
190     partial_attribute_set.num_attids = len(attids)
191     return partial_attribute_set
192
193
194 def drs_copy_highwater_mark(hwm, new_hwm):
195     """
196     Copies the highwater mark by value, rather than by object reference. (This
197     avoids lingering talloc references to old GetNCChanges reply messages).
198     """
199     hwm.tmp_highest_usn = new_hwm.tmp_highest_usn
200     hwm.reserved_usn = new_hwm.reserved_usn
201     hwm.highest_usn = new_hwm.highest_usn
202
203
204 class drs_Replicate(object):
205     '''DRS replication calls'''
206
207     def __init__(self, binding_string, lp, creds, samdb, invocation_id):
208         self.drs = drsuapi.drsuapi(binding_string, lp, creds)
209         (self.drs_handle, self.supports_ext) = drs_DsBind(self.drs)
210         self.net = Net(creds=creds, lp=lp)
211         self.samdb = samdb
212         if not isinstance(invocation_id, misc.GUID):
213             raise RuntimeError("Must supply GUID for invocation_id")
214         if invocation_id == misc.GUID("00000000-0000-0000-0000-000000000000"):
215             raise RuntimeError("Must not set GUID 00000000-0000-0000-0000-000000000000 as invocation_id")
216         self.replication_state = self.net.replicate_init(self.samdb, lp, self.drs, invocation_id)
217         self.more_flags = 0
218
219     def _should_retry_with_get_tgt(self, error_code, req):
220
221         # If the error indicates we fail to resolve a target object for a
222         # linked attribute, then we should retry the request with GET_TGT
223         # (if we support it and haven't already tried that)
224         supports_ext = self.supports_ext
225
226         # TODO fix up the below line when we next update werror_err_table.txt
227         # and pull in the new error-code
228         # return (error_code == werror.WERR_DS_DRA_RECYCLED_TARGET and
229         return (error_code == 0x21bf and
230                 supports_ext & DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10 and
231                 (req.more_flags & drsuapi.DRSUAPI_DRS_GET_TGT) == 0)
232
233     def process_chunk(self, level, ctr, schema, req_level, req, first_chunk):
234         '''Processes a single chunk of received replication data'''
235         # pass the replication into the py_net.c python bindings for processing
236         self.net.replicate_chunk(self.replication_state, level, ctr,
237                                  schema=schema, req_level=req_level, req=req)
238
239     def replicate(self, dn, source_dsa_invocation_id, destination_dsa_guid,
240                   schema=False, exop=drsuapi.DRSUAPI_EXOP_NONE, rodc=False,
241                   replica_flags=None, full_sync=True, sync_forced=False, more_flags=0):
242         '''replicate a single DN'''
243
244         # setup for a GetNCChanges call
245         if self.supports_ext & DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10:
246             req = drsuapi.DsGetNCChangesRequest10()
247             req.more_flags = (more_flags | self.more_flags)
248             req_level = 10
249         else:
250             req_level = 8
251             req = drsuapi.DsGetNCChangesRequest8()
252
253         req.destination_dsa_guid = destination_dsa_guid
254         req.source_dsa_invocation_id = source_dsa_invocation_id
255         req.naming_context = drsuapi.DsReplicaObjectIdentifier()
256         req.naming_context.dn = dn
257
258         # Default to a full replication if we don't find an upToDatenessVector
259         udv = None
260         hwm = drsuapi.DsReplicaHighWaterMark()
261         hwm.tmp_highest_usn = 0
262         hwm.reserved_usn = 0
263         hwm.highest_usn = 0
264
265         if not full_sync:
266             res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
267                                     attrs=["repsFrom"])
268             if "repsFrom" in res[0]:
269                 for reps_from_packed in res[0]["repsFrom"]:
270                     reps_from_obj = ndr_unpack(drsblobs.repsFromToBlob, reps_from_packed)
271                     if reps_from_obj.ctr.source_dsa_invocation_id == source_dsa_invocation_id:
272                         hwm = reps_from_obj.ctr.highwatermark
273
274             udv = drsuapi.DsReplicaCursorCtrEx()
275             udv.version = 1
276             udv.reserved1 = 0
277             udv.reserved2 = 0
278
279             cursors_v1 = []
280             cursors_v2 = dsdb._dsdb_load_udv_v2(self.samdb,
281                                                 self.samdb.get_default_basedn())
282             for cursor_v2 in cursors_v2:
283                 cursor_v1 = drsuapi.DsReplicaCursor()
284                 cursor_v1.source_dsa_invocation_id = cursor_v2.source_dsa_invocation_id
285                 cursor_v1.highest_usn = cursor_v2.highest_usn
286                 cursors_v1.append(cursor_v1)
287
288             udv.cursors = cursors_v1
289             udv.count = len(cursors_v1)
290
291         req.highwatermark = hwm
292         req.uptodateness_vector = udv
293
294         if replica_flags is not None:
295             req.replica_flags = replica_flags
296         elif exop == drsuapi.DRSUAPI_EXOP_REPL_SECRET:
297             req.replica_flags = 0
298         else:
299             req.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
300                                  drsuapi.DRSUAPI_DRS_PER_SYNC |
301                                  drsuapi.DRSUAPI_DRS_GET_ANC |
302                                  drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
303                                  drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
304             if rodc:
305                 req.replica_flags |= (
306                      drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING)
307             else:
308                 req.replica_flags |= drsuapi.DRSUAPI_DRS_WRIT_REP
309
310         if sync_forced:
311             req.replica_flags |= drsuapi.DRSUAPI_DRS_SYNC_FORCED
312
313         req.max_object_count = 402
314         req.max_ndr_size = 402116
315         req.extended_op = exop
316         req.fsmo_info = 0
317         req.partial_attribute_set = None
318         req.partial_attribute_set_ex = None
319         req.mapping_ctr.num_mappings = 0
320         req.mapping_ctr.mappings = None
321
322         if not schema and rodc:
323             req.partial_attribute_set = drs_get_rodc_partial_attribute_set(self.samdb)
324
325         if not self.supports_ext & DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8:
326             req_level = 5
327             req5 = drsuapi.DsGetNCChangesRequest5()
328             for a in dir(req5):
329                 if a[0] != '_':
330                     setattr(req5, a, getattr(req, a))
331             req = req5
332
333         num_objects = 0
334         num_links = 0
335         first_chunk = True
336
337         while True:
338             (level, ctr) = self.drs.DsGetNCChanges(self.drs_handle, req_level, req)
339             if ctr.first_object is None and ctr.object_count != 0:
340                 raise RuntimeError("DsGetNCChanges: NULL first_object with object_count=%u" % (ctr.object_count))
341
342             try:
343                 self.process_chunk(level, ctr, schema, req_level, req, first_chunk)
344             except WERRORError as e:
345                 # Check if retrying with the GET_TGT flag set might resolve this error
346                 if self._should_retry_with_get_tgt(e.args[0], req):
347
348                     print("Missing target object - retrying with DRS_GET_TGT")
349                     req.more_flags |= drsuapi.DRSUAPI_DRS_GET_TGT
350
351                     # try sending the request again (this has the side-effect
352                     # of causing the DC to restart the replication from scratch)
353                     first_chunk = True
354                     continue
355                 else:
356                     raise e
357
358             first_chunk = False
359             num_objects += ctr.object_count
360
361             # Cope with servers that do not return level 6, so do not return any links
362             try:
363                 num_links += ctr.linked_attributes_count
364             except AttributeError:
365                 pass
366
367             if ctr.more_data == 0:
368                 break
369
370             # update the request's HWM so we get the next chunk
371             drs_copy_highwater_mark(req.highwatermark, ctr.new_highwatermark)
372
373         return (num_objects, num_links)
374
375
376 # Handles the special case of creating a new clone of a DB, while also renaming
377 # the entire DB's objects on the way through
378 class drs_ReplicateRenamer(drs_Replicate):
379     '''Uses DRS replication to rename the entire DB'''
380
381     def __init__(self, binding_string, lp, creds, samdb, invocation_id,
382                  old_base_dn, new_base_dn):
383         super(drs_ReplicateRenamer, self).__init__(binding_string, lp, creds,
384                                                    samdb, invocation_id)
385         self.old_base_dn = old_base_dn
386         self.new_base_dn = new_base_dn
387
388         # because we're renaming the DNs, we know we're going to have trouble
389         # resolving link targets. Normally we'd get to the end of replication
390         # only to find we need to retry the whole replication with the GET_TGT
391         # flag set. Always setting the GET_TGT flag avoids this extra work.
392         self.more_flags = drsuapi.DRSUAPI_DRS_GET_TGT
393
394     def rename_dn(self, dn_str):
395         '''Uses string substitution to replace the base DN'''
396         return re.sub('%s$' % self.old_base_dn, self.new_base_dn, dn_str)
397
398     def update_name_attr(self, base_obj):
399         '''Updates the 'name' attribute for the base DN object'''
400         for attr in base_obj.attribute_ctr.attributes:
401             if attr.attid == DRSUAPI_ATTID_name:
402                 base_dn = ldb.Dn(self.samdb, base_obj.identifier.dn)
403                 new_name = base_dn.get_rdn_value()
404                 attr.value_ctr.values[0].blob = new_name.encode('utf-16-le')
405
406     def rename_top_level_object(self, first_obj):
407         '''Renames the first/top-level object in a partition'''
408         old_dn = first_obj.identifier.dn
409         first_obj.identifier.dn = self.rename_dn(first_obj.identifier.dn)
410         print("Renaming partition %s --> %s" % (old_dn,
411                                                 first_obj.identifier.dn))
412
413         # we also need to fix up the 'name' attribute for the base DN,
414         # otherwise the RDNs won't match
415         if first_obj.identifier.dn == self.new_base_dn:
416             self.update_name_attr(first_obj)
417
418     def process_chunk(self, level, ctr, schema, req_level, req, first_chunk):
419         '''Processes a single chunk of received replication data'''
420
421         # we need to rename the NC in every chunk - this gets used in searches
422         # when applying the chunk
423         if ctr.naming_context:
424             ctr.naming_context.dn = self.rename_dn(ctr.naming_context.dn)
425
426         # rename the first object in each partition. This will cause every
427         # subsequent object in the partiton to be renamed as a side-effect
428         if first_chunk and ctr.object_count != 0:
429             self.rename_top_level_object(ctr.first_object.object)
430
431         # then do the normal repl processing to apply this chunk to our DB
432         super(drs_ReplicateRenamer, self).process_chunk(level, ctr, schema,
433                                                         req_level, req,
434                                                         first_chunk)