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