s4-drs: lock down key DRS calls
[samba.git] / source4 / rpc_server / drsuapi / getncchanges.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    implement the DRSUpdateRefs call
5
6    Copyright (C) Anatoliy Atanasov 2009
7    Copyright (C) Andrew Tridgell 2009
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 #include "includes.h"
24 #include "librpc/gen_ndr/ndr_drsuapi.h"
25 #include "rpc_server/dcerpc_server.h"
26 #include "rpc_server/common/common.h"
27 #include "dsdb/samdb/samdb.h"
28 #include "lib/ldb/include/ldb_errors.h"
29 #include "param/param.h"
30 #include "librpc/gen_ndr/ndr_drsblobs.h"
31 #include "auth/auth.h"
32 #include "rpc_server/drsuapi/dcesrv_drsuapi.h"
33 #include "rpc_server/dcerpc_server_proto.h"
34 #include "../libcli/drsuapi/drsuapi.h"
35 #include "../libcli/security/dom_sid.h"
36 #include "libcli/security/security.h"
37
38 /* 
39   drsuapi_DsGetNCChanges for one object
40 */
41 static WERROR get_nc_changes_build_object(struct drsuapi_DsReplicaObjectListItemEx *obj,
42                                           struct ldb_message *msg,
43                                           struct ldb_context *sam_ctx,
44                                           struct ldb_dn *ncRoot_dn,
45                                           struct dsdb_schema *schema,
46                                           DATA_BLOB *session_key,
47                                           uint64_t highest_usn)
48 {
49         const struct ldb_val *md_value;
50         int i, n;
51         struct ldb_dn *obj_dn;
52         struct replPropertyMetaDataBlob md;
53         struct dom_sid *sid;
54         uint32_t rid = 0;
55         enum ndr_err_code ndr_err;
56         uint32_t *attids;
57
58         if (ldb_dn_compare(ncRoot_dn, msg->dn) == 0) {
59                 obj->is_nc_prefix = true;
60                 obj->parent_object_guid = NULL;
61         } else {
62                 obj->is_nc_prefix = false;
63                 obj->parent_object_guid = talloc(obj, struct GUID);
64                 *obj->parent_object_guid = samdb_result_guid(msg, "parentGUID");
65         }
66         obj->next_object = NULL;
67         
68         md_value = ldb_msg_find_ldb_val(msg, "replPropertyMetaData");
69         if (!md_value) {
70                 /* nothing to send */
71                 return WERR_OK;
72         }
73
74         ndr_err = ndr_pull_struct_blob(md_value, obj,
75                                        lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")), &md,
76                                        (ndr_pull_flags_fn_t)ndr_pull_replPropertyMetaDataBlob);
77         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
78                 return WERR_DS_DRA_INTERNAL_ERROR;
79         }
80         
81         if (md.version != 1) {
82                 return WERR_DS_DRA_INTERNAL_ERROR;
83         }
84
85         obj->meta_data_ctr = talloc(obj, struct drsuapi_DsReplicaMetaDataCtr);
86         attids = talloc_array(obj, uint32_t, md.ctr.ctr1.count);
87         
88         obj->meta_data_ctr->meta_data = talloc_array(obj, struct drsuapi_DsReplicaMetaData, md.ctr.ctr1.count);
89         for (n=i=0; i<md.ctr.ctr1.count; i++) {
90                 if (md.ctr.ctr1.array[i].local_usn < highest_usn) continue;
91                 obj->meta_data_ctr->meta_data[n].originating_change_time = md.ctr.ctr1.array[i].originating_change_time;
92                 obj->meta_data_ctr->meta_data[n].version = md.ctr.ctr1.array[i].version;
93                 obj->meta_data_ctr->meta_data[n].originating_invocation_id = md.ctr.ctr1.array[i].originating_invocation_id;
94                 obj->meta_data_ctr->meta_data[n].originating_usn = md.ctr.ctr1.array[i].originating_usn;
95                 attids[n] = md.ctr.ctr1.array[i].attid;
96                 n++;
97         }
98
99         /*
100           note that if n==0 we still need to send the change, as it
101           could be a rename, which changes the uSNChanged, but not any
102           of the replicated attributes
103          */
104
105         obj->meta_data_ctr->count = n;
106
107         obj->object.identifier = talloc(obj, struct drsuapi_DsReplicaObjectIdentifier);
108         obj_dn = ldb_msg_find_attr_as_dn(sam_ctx, obj, msg, "distinguishedName");
109         obj->object.identifier->dn = ldb_dn_get_linearized(obj_dn);
110         obj->object.identifier->guid = samdb_result_guid(msg, "objectGUID");
111         sid = samdb_result_dom_sid(obj, msg, "objectSid");
112         if (sid) {
113                 dom_sid_split_rid(NULL, sid, NULL, &rid);
114                 obj->object.identifier->sid = *sid;
115         } else {
116                 ZERO_STRUCT(obj->object.identifier->sid);
117         }
118
119         obj->object.attribute_ctr.num_attributes = obj->meta_data_ctr->count;
120         obj->object.attribute_ctr.attributes = talloc_array(obj, struct drsuapi_DsReplicaAttribute,
121                                                             obj->object.attribute_ctr.num_attributes);
122
123         /*
124          * Note that the meta_data array and the attributes array must
125          * be the same size and in the same order
126          */
127         for (i=0; i<obj->object.attribute_ctr.num_attributes; i++) {
128                 const struct dsdb_attribute *sa;
129                 struct ldb_message_element *el;
130                 WERROR werr;
131
132                 sa = dsdb_attribute_by_attributeID_id(schema, attids[i]);
133                 if (!sa) {
134                         DEBUG(0,("Unable to find attributeID %u in schema\n", attids[i]));
135                         return WERR_DS_DRA_INTERNAL_ERROR;
136                 }
137
138                 el = ldb_msg_find_element(msg, sa->lDAPDisplayName);
139                 if (el == NULL) {
140                         DEBUG(0,("No element '%s' for attributeID %u in message\n", 
141                                  sa->lDAPDisplayName, attids[i]));
142                         ZERO_STRUCT(obj->object.attribute_ctr.attributes[i]);
143                         obj->object.attribute_ctr.attributes[i].attid = attids[i];
144                 } else {
145                         werr = dsdb_attribute_ldb_to_drsuapi(sam_ctx, schema, el, obj,
146                                                              &obj->object.attribute_ctr.attributes[i]);
147                         if (!W_ERROR_IS_OK(werr)) {
148                                 DEBUG(0,("Unable to convert %s to DRS object - %s\n", 
149                                          sa->lDAPDisplayName, win_errstr(werr)));
150                                 return werr;
151                         }
152
153                         /* some attributes needs to be encrypted
154                            before being sent */
155                         werr = drsuapi_encrypt_attribute(obj, session_key, rid, 
156                                                          &obj->object.attribute_ctr.attributes[i]);
157                         if (!W_ERROR_IS_OK(werr)) {
158                                 DEBUG(0,("Unable to encrypt %s in DRS object - %s\n", 
159                                          sa->lDAPDisplayName, win_errstr(werr)));
160                                 return werr;
161                         }
162                 }
163         }
164
165         return WERR_OK;
166 }
167
168 static int replmd_drsuapi_DsReplicaCursor2_compare(const struct drsuapi_DsReplicaCursor2 *c1,
169                                                    const struct drsuapi_DsReplicaCursor2 *c2)
170 {
171         return GUID_compare(&c1->source_dsa_invocation_id, &c2->source_dsa_invocation_id);
172 }
173
174 /*
175   load replUpToDateVector from a DN
176  */
177 static WERROR load_udv(struct ldb_context *sam_ctx, TALLOC_CTX *mem_ctx,
178                        struct ldb_dn *dn, struct replUpToDateVectorBlob *ouv)
179 {
180         const char *attrs[] = { "replUpToDateVector", NULL };
181         struct ldb_result *res = NULL;
182         TALLOC_CTX *tmp_ctx = talloc_new(mem_ctx);
183         struct ldb_message_element *el;
184         enum ndr_err_code ndr_err;
185
186         ZERO_STRUCTP(ouv);
187
188         if (ldb_search(sam_ctx, tmp_ctx, &res, dn, LDB_SCOPE_BASE, attrs, NULL) != LDB_SUCCESS ||
189             res->count < 1) {
190                 DEBUG(0,("load_udv: failed to read partition object\n"));
191                 talloc_free(tmp_ctx);
192                 return WERR_DS_DRA_INTERNAL_ERROR;
193         }
194
195         el = ldb_msg_find_element(res->msgs[0], "replUpToDateVector");
196         if (el == NULL || el->num_values < 1) {
197                 talloc_free(tmp_ctx);
198                 ouv->version = 2;
199                 return WERR_OK;
200         }
201
202         ndr_err = ndr_pull_struct_blob(&el->values[0], 
203                                        mem_ctx, lp_iconv_convenience(ldb_get_opaque(sam_ctx, "loadparm")),
204                                        ouv, 
205                                        (ndr_pull_flags_fn_t)ndr_pull_replUpToDateVectorBlob);
206         talloc_free(tmp_ctx);
207         if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
208                 DEBUG(0,(__location__ ": Failed to parse replUpToDateVector for %s\n",
209                          ldb_dn_get_linearized(dn)));
210                 return WERR_DS_DRA_INTERNAL_ERROR;
211         }
212         
213         return WERR_OK;
214         
215 }
216
217 /*
218   fill in the cursors return based on the replUpToDateVector for the ncRoot_dn
219  */
220 static WERROR get_nc_changes_udv(struct ldb_context *sam_ctx,
221                                  struct ldb_dn *ncRoot_dn,
222                                  struct drsuapi_DsReplicaCursor2CtrEx *udv)
223 {
224         WERROR werr;
225         struct drsuapi_DsReplicaCursor2 *tmp_cursor;
226         uint64_t highest_commited_usn;
227         NTTIME now;
228         time_t t = time(NULL);
229         int ret;
230         struct replUpToDateVectorBlob ouv;
231
232         werr = load_udv(sam_ctx, udv, ncRoot_dn, &ouv);
233         if (!W_ERROR_IS_OK(werr)) {
234                 return werr;
235         }
236         
237         ret = ldb_sequence_number(sam_ctx, LDB_SEQ_HIGHEST_SEQ, &highest_commited_usn);
238         if (ret != LDB_SUCCESS) {
239                 return WERR_DS_DRA_INTERNAL_ERROR;
240         }
241
242         tmp_cursor = talloc(udv, struct drsuapi_DsReplicaCursor2);
243         tmp_cursor->source_dsa_invocation_id = *(samdb_ntds_invocation_id(sam_ctx));
244         tmp_cursor->highest_usn = highest_commited_usn;
245         unix_to_nt_time(&now, t);
246         tmp_cursor->last_sync_success = now;
247
248         udv->count = ouv.ctr.ctr2.count + 1;
249         udv->cursors = talloc_steal(udv, ouv.ctr.ctr2.cursors);
250         udv->cursors = talloc_realloc(udv, udv->cursors, struct drsuapi_DsReplicaCursor2, udv->count);
251         if (!udv->cursors) {
252                 return WERR_DS_DRA_INTERNAL_ERROR;
253         }
254         udv->cursors[udv->count - 1] = *tmp_cursor;
255         
256         qsort(udv->cursors, udv->count,
257               sizeof(struct drsuapi_DsReplicaCursor2),
258               (comparison_fn_t)replmd_drsuapi_DsReplicaCursor2_compare);
259
260         return WERR_OK;
261 }
262
263 /* 
264   drsuapi_DsGetNCChanges
265 */
266 WERROR dcesrv_drsuapi_DsGetNCChanges(struct dcesrv_call_state *dce_call, TALLOC_CTX *mem_ctx,
267                                      struct drsuapi_DsGetNCChanges *r)
268 {
269         struct ldb_result *site_res;
270         struct drsuapi_DsReplicaObjectIdentifier *ncRoot;
271         struct ldb_context *sam_ctx;
272         struct ldb_dn *ncRoot_dn;
273         int ret;
274         int i;
275         struct dsdb_schema *schema;
276         struct drsuapi_DsReplicaOIDMapping_Ctr *ctr;
277         struct drsuapi_DsReplicaObjectListItemEx **currentObject;
278         NTSTATUS status;
279         DATA_BLOB session_key;
280         const char *attrs[] = { "*", "parentGUID", NULL };
281         WERROR werr;
282         
283         *r->out.level_out = 6;
284         /* TODO: linked attributes*/
285         r->out.ctr->ctr6.linked_attributes_count = 0;
286         r->out.ctr->ctr6.linked_attributes = NULL;
287
288         r->out.ctr->ctr6.object_count = 0;
289         r->out.ctr->ctr6.more_data = false;
290         r->out.ctr->ctr6.uptodateness_vector = NULL;
291
292         /* Check request revision. */
293         if (r->in.level != 8) {
294                 return WERR_REVISION_MISMATCH;
295         }
296
297         /* Perform access checks. */
298         if (r->in.req->req8.naming_context == NULL) {
299                 return WERR_DS_DRA_INVALID_PARAMETER;
300         }
301
302         ncRoot = r->in.req->req8.naming_context;
303         if (ncRoot == NULL) {
304                 return WERR_DS_DRA_BAD_NC;
305         }
306
307         if (security_session_user_level(dce_call->conn->auth_state.session_info) <
308             SECURITY_DOMAIN_CONTROLLER) {
309                 DEBUG(0,("getncchanges refused for security token\n"));
310                 return WERR_DS_DRA_ACCESS_DENIED;
311         }
312
313         /*
314          * connect to the samdb. TODO: We need to check that the caller
315          * has the rights to do this. This exposes all attributes,
316          * including all passwords.
317          */
318         sam_ctx = samdb_connect(mem_ctx, dce_call->event_ctx, dce_call->conn->dce_ctx->lp_ctx, 
319                                 system_session(mem_ctx, dce_call->conn->dce_ctx->lp_ctx));
320         if (!sam_ctx) {
321                 return WERR_FOOBAR;
322         }
323
324         /* we need the session key for encrypting password attributes */
325         status = dcesrv_inherited_session_key(dce_call->conn, &session_key);
326         if (!NT_STATUS_IS_OK(status)) {
327                 DEBUG(0,(__location__ ": Failed to get session key\n"));
328                 return WERR_DS_DRA_INTERNAL_ERROR;              
329         }
330
331         /* Construct response. */
332         ncRoot_dn = ldb_dn_new(mem_ctx, sam_ctx, ncRoot->dn);
333         ret = drsuapi_search_with_extended_dn(sam_ctx, mem_ctx, &site_res,
334                                               ncRoot_dn, LDB_SCOPE_SUBTREE, attrs,
335                                               "(uSNChanged>=%llu)", 
336                                               (unsigned long long)(r->in.req->req8.highwatermark.highest_usn+1));
337         if (ret != LDB_SUCCESS) {
338                 return WERR_DS_DRA_INTERNAL_ERROR;
339         }
340
341
342         /* Prefix mapping */
343         schema = dsdb_get_schema(sam_ctx);
344         if (!schema) {
345                 DEBUG(0,("No schema in sam_ctx\n"));
346                 return WERR_DS_DRA_INTERNAL_ERROR;
347         }
348
349         r->out.ctr->ctr6.naming_context = talloc(mem_ctx, struct drsuapi_DsReplicaObjectIdentifier);
350         *r->out.ctr->ctr6.naming_context = *ncRoot;
351
352         dsdb_get_oid_mappings_drsuapi(schema, true, mem_ctx, &ctr);
353         r->out.ctr->ctr6.mapping_ctr = *ctr;
354
355         r->out.ctr->ctr6.source_dsa_guid = *(samdb_ntds_objectGUID(sam_ctx));
356         r->out.ctr->ctr6.source_dsa_invocation_id = *(samdb_ntds_invocation_id(sam_ctx));
357
358         r->out.ctr->ctr6.old_highwatermark = r->in.req->req8.highwatermark;
359         r->out.ctr->ctr6.new_highwatermark = r->in.req->req8.highwatermark;
360
361         r->out.ctr->ctr6.uptodateness_vector = talloc(mem_ctx, struct drsuapi_DsReplicaCursor2CtrEx);
362         r->out.ctr->ctr6.uptodateness_vector->version = 2;
363         r->out.ctr->ctr6.uptodateness_vector->reserved1 = 0;
364         r->out.ctr->ctr6.uptodateness_vector->reserved2 = 0;
365
366         r->out.ctr->ctr6.first_object = NULL;
367         currentObject = &r->out.ctr->ctr6.first_object;
368
369         for(i=0; i<site_res->count; i++) {
370                 int uSN;
371                 struct drsuapi_DsReplicaObjectListItemEx *obj;
372                 obj = talloc_zero(mem_ctx, struct drsuapi_DsReplicaObjectListItemEx);
373
374                 uSN = ldb_msg_find_attr_as_int(site_res->msgs[i], "uSNChanged", -1);
375                 if (uSN > r->out.ctr->ctr6.new_highwatermark.highest_usn) {
376                         r->out.ctr->ctr6.new_highwatermark.tmp_highest_usn = uSN;
377                         r->out.ctr->ctr6.new_highwatermark.highest_usn = uSN;
378                 }
379
380                 werr = get_nc_changes_build_object(obj, site_res->msgs[i], sam_ctx, ncRoot_dn, 
381                                                    schema, &session_key, r->in.req->req8.highwatermark.highest_usn);
382                 if (!W_ERROR_IS_OK(werr)) {
383                         return werr;
384                 }
385
386                 if (obj->meta_data_ctr == NULL) {
387                         /* no attributes to send */
388                         talloc_free(obj);
389                         continue;
390                 }
391
392                 r->out.ctr->ctr6.object_count++;
393                 
394                 *currentObject = obj;
395                 currentObject = &obj->next_object;
396         }
397
398         werr = get_nc_changes_udv(sam_ctx, ncRoot_dn, r->out.ctr->ctr6.uptodateness_vector);
399         if (!W_ERROR_IS_OK(werr)) {
400                 return werr;
401         }
402
403
404         DEBUG(3,("DsGetNCChanges with uSNChanged >= %llu on %s gave %u objects\n", 
405                  (unsigned long long)(r->in.req->req8.highwatermark.highest_usn+1),
406                  ncRoot->dn, r->out.ctr->ctr6.object_count));
407
408         if (r->out.ctr->ctr6.object_count <= 10 && DEBUGLVL(6)) {
409                 NDR_PRINT_FUNCTION_DEBUG(drsuapi_DsGetNCChanges, NDR_IN|NDR_OUT, r);
410         }
411
412         return WERR_OK;
413 }