feab89b0d8e02eb4dd04a4f44f037d8fbaf13d39
[bbaumbach/samba-autobuild/.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 drs_DsBind(drs):
96     '''make a DsBind call, returning the binding handle'''
97     bind_info = drsuapi.DsBindInfoCtr()
98     bind_info.length = 28
99     bind_info.info = drsuapi.DsBindInfo28()
100     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_BASE
101     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION
102     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI
103     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2
104     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS
105     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1
106     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION
107     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE
108     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2
109     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION
110     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2
111     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD
112     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND
113     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO
114     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION
115     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01
116     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP
117     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY
118     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3
119     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2
120     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6
121     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS
122     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8
123     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5
124     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6
125     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3
126     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7
127     bind_info.info.supported_extensions |= drsuapi.DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT
128     (info, handle) = drs.DsBind(misc.GUID(drsuapi.DRSUAPI_DS_BIND_GUID), bind_info)
129
130     return (handle, info.info.supported_extensions)
131
132
133 def drs_get_rodc_partial_attribute_set(samdb):
134     '''get a list of attributes for RODC replication'''
135     partial_attribute_set = drsuapi.DsPartialAttributeSet()
136     partial_attribute_set.version = 1
137
138     attids = []
139
140     # the exact list of attids we send is quite critical. Note that
141     # we do ask for the secret attributes, but set SPECIAL_SECRET_PROCESSING
142     # to zero them out
143     schema_dn = samdb.get_schema_basedn()
144     res = samdb.search(base=schema_dn, scope=ldb.SCOPE_SUBTREE,
145                        expression="objectClass=attributeSchema",
146                        attrs=["lDAPDisplayName", "systemFlags",
147                               "searchFlags"])
148
149     for r in res:
150         ldap_display_name = str(r["lDAPDisplayName"][0])
151         if "systemFlags" in r:
152             system_flags      = r["systemFlags"][0]
153             if (int(system_flags) & (samba.dsdb.DS_FLAG_ATTR_NOT_REPLICATED |
154                                      samba.dsdb.DS_FLAG_ATTR_IS_CONSTRUCTED)):
155                 continue
156         if "searchFlags" in r:
157             search_flags = r["searchFlags"][0]
158             if (int(search_flags) & samba.dsdb.SEARCH_FLAG_RODC_ATTRIBUTE):
159                 continue
160         attid = samdb.get_attid_from_lDAPDisplayName(ldap_display_name)
161         attids.append(int(attid))
162
163     # the attids do need to be sorted, or windows doesn't return
164     # all the attributes we need
165     attids.sort()
166     partial_attribute_set.attids         = attids
167     partial_attribute_set.num_attids = len(attids)
168     return partial_attribute_set
169
170
171 def drs_copy_highwater_mark(hwm, new_hwm):
172     """
173     Copies the highwater mark by value, rather than by object reference. (This
174     avoids lingering talloc references to old GetNCChanges reply messages).
175     """
176     hwm.tmp_highest_usn = new_hwm.tmp_highest_usn
177     hwm.reserved_usn = new_hwm.reserved_usn
178     hwm.highest_usn = new_hwm.highest_usn
179
180
181 class drs_Replicate(object):
182     '''DRS replication calls'''
183
184     def __init__(self, binding_string, lp, creds, samdb, invocation_id):
185         self.drs = drsuapi.drsuapi(binding_string, lp, creds)
186         (self.drs_handle, self.supports_ext) = drs_DsBind(self.drs)
187         self.net = Net(creds=creds, lp=lp)
188         self.samdb = samdb
189         if not isinstance(invocation_id, misc.GUID):
190             raise RuntimeError("Must supply GUID for invocation_id")
191         if invocation_id == misc.GUID("00000000-0000-0000-0000-000000000000"):
192             raise RuntimeError("Must not set GUID 00000000-0000-0000-0000-000000000000 as invocation_id")
193         self.replication_state = self.net.replicate_init(self.samdb, lp, self.drs, invocation_id)
194         self.more_flags = 0
195
196     def _should_retry_with_get_tgt(self, error_code, req):
197
198         # If the error indicates we fail to resolve a target object for a
199         # linked attribute, then we should retry the request with GET_TGT
200         # (if we support it and haven't already tried that)
201         supports_ext = self.supports_ext
202
203         # TODO fix up the below line when we next update werror_err_table.txt
204         # and pull in the new error-code
205         # return (error_code == werror.WERR_DS_DRA_RECYCLED_TARGET and
206         return (error_code == 0x21bf and
207                 supports_ext & DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10 and
208                 (req.more_flags & drsuapi.DRSUAPI_DRS_GET_TGT) == 0)
209
210     def process_chunk(self, level, ctr, schema, req_level, req, first_chunk):
211         '''Processes a single chunk of received replication data'''
212         # pass the replication into the py_net.c python bindings for processing
213         self.net.replicate_chunk(self.replication_state, level, ctr,
214                                  schema=schema, req_level=req_level, req=req)
215
216     def replicate(self, dn, source_dsa_invocation_id, destination_dsa_guid,
217                   schema=False, exop=drsuapi.DRSUAPI_EXOP_NONE, rodc=False,
218                   replica_flags=None, full_sync=True, sync_forced=False, more_flags=0):
219         '''replicate a single DN'''
220
221         # setup for a GetNCChanges call
222         if self.supports_ext & DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10:
223             req = drsuapi.DsGetNCChangesRequest10()
224             req.more_flags = (more_flags | self.more_flags)
225             req_level = 10
226         else:
227             req_level = 8
228             req = drsuapi.DsGetNCChangesRequest8()
229
230         req.destination_dsa_guid = destination_dsa_guid
231         req.source_dsa_invocation_id = source_dsa_invocation_id
232         req.naming_context = drsuapi.DsReplicaObjectIdentifier()
233         req.naming_context.dn = dn
234
235         # Default to a full replication if we don't find an upToDatenessVector
236         udv = None
237         hwm = drsuapi.DsReplicaHighWaterMark()
238         hwm.tmp_highest_usn = 0
239         hwm.reserved_usn = 0
240         hwm.highest_usn = 0
241
242         if not full_sync:
243             res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
244                                     attrs=["repsFrom"])
245             if "repsFrom" in res[0]:
246                 for reps_from_packed in res[0]["repsFrom"]:
247                     reps_from_obj = ndr_unpack(drsblobs.repsFromToBlob, reps_from_packed)
248                     if reps_from_obj.ctr.source_dsa_invocation_id == source_dsa_invocation_id:
249                         hwm = reps_from_obj.ctr.highwatermark
250
251             udv = drsuapi.DsReplicaCursorCtrEx()
252             udv.version = 1
253             udv.reserved1 = 0
254             udv.reserved2 = 0
255
256             cursors_v1 = []
257             cursors_v2 = dsdb._dsdb_load_udv_v2(self.samdb,
258                                                 self.samdb.get_default_basedn())
259             for cursor_v2 in cursors_v2:
260                 cursor_v1 = drsuapi.DsReplicaCursor()
261                 cursor_v1.source_dsa_invocation_id = cursor_v2.source_dsa_invocation_id
262                 cursor_v1.highest_usn = cursor_v2.highest_usn
263                 cursors_v1.append(cursor_v1)
264
265             udv.cursors = cursors_v1
266             udv.count = len(cursors_v1)
267
268         req.highwatermark = hwm
269         req.uptodateness_vector = udv
270
271         if replica_flags is not None:
272             req.replica_flags = replica_flags
273         elif exop == drsuapi.DRSUAPI_EXOP_REPL_SECRET:
274             req.replica_flags = 0
275         else:
276             req.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
277                                  drsuapi.DRSUAPI_DRS_PER_SYNC |
278                                  drsuapi.DRSUAPI_DRS_GET_ANC |
279                                  drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
280                                  drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
281             if rodc:
282                 req.replica_flags |= (
283                      drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING)
284             else:
285                 req.replica_flags |= drsuapi.DRSUAPI_DRS_WRIT_REP
286
287         if sync_forced:
288             req.replica_flags |= drsuapi.DRSUAPI_DRS_SYNC_FORCED
289
290         req.max_object_count = 402
291         req.max_ndr_size = 402116
292         req.extended_op = exop
293         req.fsmo_info = 0
294         req.partial_attribute_set = None
295         req.partial_attribute_set_ex = None
296         req.mapping_ctr.num_mappings = 0
297         req.mapping_ctr.mappings = None
298
299         if not schema and rodc:
300             req.partial_attribute_set = drs_get_rodc_partial_attribute_set(self.samdb)
301
302         if not self.supports_ext & DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8:
303             req_level = 5
304             req5 = drsuapi.DsGetNCChangesRequest5()
305             for a in dir(req5):
306                 if a[0] != '_':
307                     setattr(req5, a, getattr(req, a))
308             req = req5
309
310         num_objects = 0
311         num_links = 0
312         first_chunk = True
313
314         while True:
315             (level, ctr) = self.drs.DsGetNCChanges(self.drs_handle, req_level, req)
316             if ctr.first_object is None and ctr.object_count != 0:
317                 raise RuntimeError("DsGetNCChanges: NULL first_object with object_count=%u" % (ctr.object_count))
318
319             try:
320                 self.process_chunk(level, ctr, schema, req_level, req, first_chunk)
321             except WERRORError as e:
322                 # Check if retrying with the GET_TGT flag set might resolve this error
323                 if self._should_retry_with_get_tgt(e.args[0], req):
324
325                     print("Missing target object - retrying with DRS_GET_TGT")
326                     req.more_flags |= drsuapi.DRSUAPI_DRS_GET_TGT
327
328                     # try sending the request again (this has the side-effect
329                     # of causing the DC to restart the replication from scratch)
330                     first_chunk = True
331                     continue
332                 else:
333                     raise e
334
335             first_chunk = False
336             num_objects += ctr.object_count
337
338             # Cope with servers that do not return level 6, so do not return any links
339             try:
340                 num_links += ctr.linked_attributes_count
341             except AttributeError:
342                 pass
343
344             if ctr.more_data == 0:
345                 break
346
347             # update the request's HWM so we get the next chunk
348             drs_copy_highwater_mark(req.highwatermark, ctr.new_highwatermark)
349
350         return (num_objects, num_links)
351
352
353 # Handles the special case of creating a new clone of a DB, while also renaming
354 # the entire DB's objects on the way through
355 class drs_ReplicateRenamer(drs_Replicate):
356     '''Uses DRS replication to rename the entire DB'''
357
358     def __init__(self, binding_string, lp, creds, samdb, invocation_id,
359                  old_base_dn, new_base_dn):
360         super(drs_ReplicateRenamer, self).__init__(binding_string, lp, creds,
361                                                    samdb, invocation_id)
362         self.old_base_dn = old_base_dn
363         self.new_base_dn = new_base_dn
364
365         # because we're renaming the DNs, we know we're going to have trouble
366         # resolving link targets. Normally we'd get to the end of replication
367         # only to find we need to retry the whole replication with the GET_TGT
368         # flag set. Always setting the GET_TGT flag avoids this extra work.
369         self.more_flags = drsuapi.DRSUAPI_DRS_GET_TGT
370
371     def rename_dn(self, dn_str):
372         '''Uses string substitution to replace the base DN'''
373         return re.sub('%s$' % self.old_base_dn, self.new_base_dn, dn_str)
374
375     def update_name_attr(self, base_obj):
376         '''Updates the 'name' attribute for the base DN object'''
377         for attr in base_obj.attribute_ctr.attributes:
378             if attr.attid == DRSUAPI_ATTID_name:
379                 base_dn = ldb.Dn(self.samdb, base_obj.identifier.dn)
380                 new_name = base_dn.get_rdn_value()
381                 attr.value_ctr.values[0].blob = new_name.encode('utf-16-le')
382
383     def rename_top_level_object(self, first_obj):
384         '''Renames the first/top-level object in a partition'''
385         old_dn = first_obj.identifier.dn
386         first_obj.identifier.dn = self.rename_dn(first_obj.identifier.dn)
387         print("Renaming partition %s --> %s" % (old_dn,
388                                                 first_obj.identifier.dn))
389
390         # we also need to fix up the 'name' attribute for the base DN,
391         # otherwise the RDNs won't match
392         if first_obj.identifier.dn == self.new_base_dn:
393             self.update_name_attr(first_obj)
394
395     def process_chunk(self, level, ctr, schema, req_level, req, first_chunk):
396         '''Processes a single chunk of received replication data'''
397
398         # we need to rename the NC in every chunk - this gets used in searches
399         # when applying the chunk
400         if ctr.naming_context:
401             ctr.naming_context.dn = self.rename_dn(ctr.naming_context.dn)
402
403         # rename the first object in each partition. This will cause every
404         # subsequent object in the partiton to be renamed as a side-effect
405         if first_chunk and ctr.object_count != 0:
406             self.rename_top_level_object(ctr.first_object.object)
407
408         # then do the normal repl processing to apply this chunk to our DB
409         super(drs_ReplicateRenamer, self).process_chunk(level, ctr, schema,
410                                                         req_level, req,
411                                                         first_chunk)