python/samba3: import passdb in the manner it is used
[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 = str(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 def drs_copy_highwater_mark(hwm, new_hwm):
193     """
194     Copies the highwater mark by value, rather than by object reference. (This
195     avoids lingering talloc references to old GetNCChanges reply messages).
196     """
197     hwm.tmp_highest_usn = new_hwm.tmp_highest_usn
198     hwm.reserved_usn = new_hwm.reserved_usn
199     hwm.highest_usn = new_hwm.highest_usn
200
201
202 class drs_Replicate(object):
203     '''DRS replication calls'''
204
205     def __init__(self, binding_string, lp, creds, samdb, invocation_id):
206         self.drs = drsuapi.drsuapi(binding_string, lp, creds)
207         (self.drs_handle, self.supported_extensions) = drs_DsBind(self.drs)
208         self.net = Net(creds=creds, lp=lp)
209         self.samdb = samdb
210         if not isinstance(invocation_id, misc.GUID):
211             raise RuntimeError("Must supply GUID for invocation_id")
212         if invocation_id == misc.GUID("00000000-0000-0000-0000-000000000000"):
213             raise RuntimeError("Must not set GUID 00000000-0000-0000-0000-000000000000 as invocation_id")
214         self.replication_state = self.net.replicate_init(self.samdb, lp, self.drs, invocation_id)
215         self.more_flags = 0
216
217     def _should_retry_with_get_tgt(self, error_code, req):
218
219         # If the error indicates we fail to resolve a target object for a
220         # linked attribute, then we should retry the request with GET_TGT
221         # (if we support it and haven't already tried that)
222
223         # TODO fix up the below line when we next update werror_err_table.txt
224         # and pull in the new error-code
225         # return (error_code == werror.WERR_DS_DRA_RECYCLED_TARGET and
226         return (error_code == 0x21bf and
227                 (req.more_flags & drsuapi.DRSUAPI_DRS_GET_TGT) == 0 and
228                 self.supported_extensions & drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10)
229
230     def process_chunk(self, level, ctr, schema, req_level, req, first_chunk):
231         '''Processes a single chunk of received replication data'''
232         # pass the replication into the py_net.c python bindings for processing
233         self.net.replicate_chunk(self.replication_state, level, ctr,
234                                  schema=schema, req_level=req_level, req=req)
235
236     def replicate(self, dn, source_dsa_invocation_id, destination_dsa_guid,
237                   schema=False, exop=drsuapi.DRSUAPI_EXOP_NONE, rodc=False,
238                   replica_flags=None, full_sync=True, sync_forced=False, more_flags=0):
239         '''replicate a single DN'''
240
241         # setup for a GetNCChanges call
242         if self.supported_extensions & drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V10:
243             req = drsuapi.DsGetNCChangesRequest10()
244             req.more_flags = (more_flags | self.more_flags)
245             req_level = 10
246         else:
247             req_level = 8
248             req = drsuapi.DsGetNCChangesRequest8()
249
250         req.destination_dsa_guid = destination_dsa_guid
251         req.source_dsa_invocation_id = source_dsa_invocation_id
252         req.naming_context = drsuapi.DsReplicaObjectIdentifier()
253         req.naming_context.dn = dn
254
255         # Default to a full replication if we don't find an upToDatenessVector
256         udv = None
257         hwm = drsuapi.DsReplicaHighWaterMark()
258         hwm.tmp_highest_usn = 0
259         hwm.reserved_usn = 0
260         hwm.highest_usn = 0
261
262         if not full_sync:
263             res = self.samdb.search(base=dn, scope=ldb.SCOPE_BASE,
264                                     attrs=["repsFrom"])
265             if "repsFrom" in res[0]:
266                 for reps_from_packed in res[0]["repsFrom"]:
267                     reps_from_obj = ndr_unpack(drsblobs.repsFromToBlob, reps_from_packed)
268                     if reps_from_obj.ctr.source_dsa_invocation_id == source_dsa_invocation_id:
269                         hwm = reps_from_obj.ctr.highwatermark
270
271             udv = drsuapi.DsReplicaCursorCtrEx()
272             udv.version = 1
273             udv.reserved1 = 0
274             udv.reserved2 = 0
275
276             cursors_v1 = []
277             cursors_v2 = dsdb._dsdb_load_udv_v2(self.samdb,
278                                                 self.samdb.get_default_basedn())
279             for cursor_v2 in cursors_v2:
280                 cursor_v1 = drsuapi.DsReplicaCursor()
281                 cursor_v1.source_dsa_invocation_id = cursor_v2.source_dsa_invocation_id
282                 cursor_v1.highest_usn = cursor_v2.highest_usn
283                 cursors_v1.append(cursor_v1)
284
285             udv.cursors = cursors_v1
286             udv.count = len(cursors_v1)
287
288         req.highwatermark = hwm
289         req.uptodateness_vector = udv
290
291         if replica_flags is not None:
292             req.replica_flags = replica_flags
293         elif exop == drsuapi.DRSUAPI_EXOP_REPL_SECRET:
294             req.replica_flags = 0
295         else:
296             req.replica_flags = (drsuapi.DRSUAPI_DRS_INIT_SYNC |
297                                  drsuapi.DRSUAPI_DRS_PER_SYNC |
298                                  drsuapi.DRSUAPI_DRS_GET_ANC |
299                                  drsuapi.DRSUAPI_DRS_NEVER_SYNCED |
300                                  drsuapi.DRSUAPI_DRS_GET_ALL_GROUP_MEMBERSHIP)
301             if rodc:
302                 req.replica_flags |= (
303                      drsuapi.DRSUAPI_DRS_SPECIAL_SECRET_PROCESSING)
304             else:
305                 req.replica_flags |= drsuapi.DRSUAPI_DRS_WRIT_REP
306
307         if sync_forced:
308             req.replica_flags |= drsuapi.DRSUAPI_DRS_SYNC_FORCED
309
310         req.max_object_count = 402
311         req.max_ndr_size = 402116
312         req.extended_op = exop
313         req.fsmo_info = 0
314         req.partial_attribute_set = None
315         req.partial_attribute_set_ex = None
316         req.mapping_ctr.num_mappings = 0
317         req.mapping_ctr.mappings = None
318
319         if not schema and rodc:
320             req.partial_attribute_set = drs_get_rodc_partial_attribute_set(self.samdb)
321
322         if not self.supported_extensions & drsuapi.DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8:
323             req_level = 5
324             req5 = drsuapi.DsGetNCChangesRequest5()
325             for a in dir(req5):
326                 if a[0] != '_':
327                     setattr(req5, a, getattr(req, a))
328             req = req5
329
330         num_objects = 0
331         num_links = 0
332         first_chunk = True
333
334         while True:
335             (level, ctr) = self.drs.DsGetNCChanges(self.drs_handle, req_level, req)
336             if ctr.first_object is None and ctr.object_count != 0:
337                 raise RuntimeError("DsGetNCChanges: NULL first_object with object_count=%u" % (ctr.object_count))
338
339             try:
340                 self.process_chunk(level, ctr, schema, req_level, req, first_chunk)
341             except WERRORError as e:
342                 # Check if retrying with the GET_TGT flag set might resolve this error
343                 if self._should_retry_with_get_tgt(e.args[0], req):
344
345                     print("Missing target object - retrying with DRS_GET_TGT")
346                     req.more_flags |= drsuapi.DRSUAPI_DRS_GET_TGT
347
348                     # try sending the request again (this has the side-effect
349                     # of causing the DC to restart the replication from scratch)
350                     first_chunk = True
351                     continue
352                 else:
353                     raise e
354
355             first_chunk = False
356             num_objects += ctr.object_count
357
358             # Cope with servers that do not return level 6, so do not return any links
359             try:
360                 num_links += ctr.linked_attributes_count
361             except AttributeError:
362                 pass
363
364             if ctr.more_data == 0:
365                 break
366
367             # update the request's HWM so we get the next chunk
368             drs_copy_highwater_mark(req.highwatermark, ctr.new_highwatermark)
369
370         return (num_objects, num_links)
371
372
373 # Handles the special case of creating a new clone of a DB, while also renaming
374 # the entire DB's objects on the way through
375 class drs_ReplicateRenamer(drs_Replicate):
376     '''Uses DRS replication to rename the entire DB'''
377
378     def __init__(self, binding_string, lp, creds, samdb, invocation_id,
379                  old_base_dn, new_base_dn):
380         super(drs_ReplicateRenamer, self).__init__(binding_string, lp, creds,
381                                                    samdb, invocation_id)
382         self.old_base_dn = old_base_dn
383         self.new_base_dn = new_base_dn
384
385         # because we're renaming the DNs, we know we're going to have trouble
386         # resolving link targets. Normally we'd get to the end of replication
387         # only to find we need to retry the whole replication with the GET_TGT
388         # flag set. Always setting the GET_TGT flag avoids this extra work.
389         self.more_flags = drsuapi.DRSUAPI_DRS_GET_TGT
390
391     def rename_dn(self, dn_str):
392         '''Uses string substitution to replace the base DN'''
393         return re.sub('%s$' % self.old_base_dn, self.new_base_dn, dn_str)
394
395     def update_name_attr(self, base_obj):
396         '''Updates the 'name' attribute for the base DN object'''
397         for attr in base_obj.attribute_ctr.attributes:
398             if attr.attid == DRSUAPI_ATTID_name:
399                 base_dn = ldb.Dn(self.samdb, base_obj.identifier.dn)
400                 new_name = base_dn.get_rdn_value()
401                 attr.value_ctr.values[0].blob = new_name.encode('utf-16-le')
402
403     def rename_top_level_object(self, first_obj):
404         '''Renames the first/top-level object in a partition'''
405         old_dn = first_obj.identifier.dn
406         first_obj.identifier.dn = self.rename_dn(first_obj.identifier.dn)
407         print("Renaming partition %s --> %s" % (old_dn,
408                                                 first_obj.identifier.dn))
409
410         # we also need to fix up the 'name' attribute for the base DN,
411         # otherwise the RDNs won't match
412         if first_obj.identifier.dn == self.new_base_dn:
413             self.update_name_attr(first_obj)
414
415     def process_chunk(self, level, ctr, schema, req_level, req, first_chunk):
416         '''Processes a single chunk of received replication data'''
417
418         # we need to rename the NC in every chunk - this gets used in searches
419         # when applying the chunk
420         if ctr.naming_context:
421             ctr.naming_context.dn = self.rename_dn(ctr.naming_context.dn)
422
423         # rename the first object in each partition. This will cause every
424         # subsequent object in the partiton to be renamed as a side-effect
425         if first_chunk and ctr.object_count != 0:
426             self.rename_top_level_object(ctr.first_object.object)
427
428         # then do the normal repl processing to apply this chunk to our DB
429         super(drs_ReplicateRenamer, self).process_chunk(level, ctr, schema,
430                                                         req_level, req,
431                                                         first_chunk)