Merge branch 'v4-0-test' of git://git.samba.org/samba into 4-0-abartlet
[kai/samba.git] / source / torture / libnet / libnet_BecomeDC.c
1 /* 
2    Unix SMB/CIFS implementation.
3
4    libnet_BecomeDC() tests
5
6    Copyright (C) Stefan Metzmacher <metze@samba.org> 2006
7    
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "lib/cmdline/popt_common.h"
24 #include "torture/torture.h"
25 #include "torture/rpc/rpc.h"
26 #include "libnet/libnet.h"
27 #include "lib/events/events.h"
28 #include "dsdb/samdb/samdb.h"
29 #include "lib/util/dlinklist.h"
30 #include "lib/ldb/include/ldb.h"
31 #include "lib/ldb/include/ldb_errors.h"
32 #include "librpc/ndr/libndr.h"
33 #include "librpc/gen_ndr/ndr_drsuapi.h"
34 #include "librpc/gen_ndr/ndr_drsblobs.h"
35 #include "librpc/gen_ndr/ndr_misc.h"
36 #include "system/time.h"
37 #include "auth/auth.h"
38 #include "lib/ldb_wrap.h"
39
40 struct test_become_dc_state {
41         struct libnet_context *ctx;
42         struct torture_context *tctx;
43         const char *netbios_name;
44         struct test_join *tj;
45         struct cli_credentials *machine_account;
46         struct dsdb_schema *self_made_schema;
47         const struct dsdb_schema *schema;
48
49         struct ldb_context *ldb;
50
51         struct {
52                 uint32_t object_count;
53                 struct drsuapi_DsReplicaObjectListItemEx *first_object;
54                 struct drsuapi_DsReplicaObjectListItemEx *last_object;
55         } schema_part;
56
57         struct {
58                 const char *samdb_ldb;
59                 const char *domaindn_ldb;
60                 const char *configdn_ldb;
61                 const char *schemadn_ldb;
62                 const char *secrets_ldb;
63                 const char *templates_ldb;
64                 const char *secrets_keytab;
65                 const char *dns_keytab;
66         } path;
67 };
68
69 static NTSTATUS test_become_dc_check_options(void *private_data,
70                                              const struct libnet_BecomeDC_CheckOptions *o)
71 {
72         struct test_become_dc_state *s = talloc_get_type(private_data, struct test_become_dc_state);
73
74         DEBUG(0,("Become DC [%s] of Domain[%s]/[%s]\n",
75                 s->netbios_name,
76                 o->domain->netbios_name, o->domain->dns_name));
77
78         DEBUG(0,("Promotion Partner is Server[%s] from Site[%s]\n",
79                 o->source_dsa->dns_name, o->source_dsa->site_name));
80
81         DEBUG(0,("Options:crossRef behavior_version[%u]\n"
82                        "\tschema object_version[%u]\n"
83                        "\tdomain behavior_version[%u]\n"
84                        "\tdomain w2k3_update_revision[%u]\n", 
85                 o->forest->crossref_behavior_version,
86                 o->forest->schema_object_version,
87                 o->domain->behavior_version,
88                 o->domain->w2k3_update_revision));
89
90         return NT_STATUS_OK;
91 }
92
93 #include "lib/appweb/ejs/ejs.h"
94 #include "lib/appweb/ejs/ejsInternal.h"
95 #include "scripting/ejs/smbcalls.h"
96
97 static EjsId eid;
98 static int ejs_error;
99
100 static void test_ejs_exception(const char *reason)
101 {
102         Ejs *ep = ejsPtr(eid);
103         ejsSetErrorMsg(eid, "%s", reason);
104         fprintf(stderr, "%s", ep->error);
105         ejs_error = 127;
106 }
107
108 static int test_run_ejs(char *script)
109 {
110         EjsHandle handle = 0;
111         MprVar result;
112         char *emsg;
113         TALLOC_CTX *mem_ctx = talloc_new(NULL);
114         struct MprVar *return_var;
115
116         mprSetCtx(mem_ctx);
117
118         if (ejsOpen(NULL, NULL, NULL) != 0) {
119                 d_printf("ejsOpen(): unable to initialise EJS subsystem\n");
120                 ejs_error = 127;
121                 goto failed;
122         }
123
124         smb_setup_ejs_functions(test_ejs_exception);
125
126         if ((eid = ejsOpenEngine(handle, 0)) == (EjsId)-1) {
127                 d_printf("smbscript: ejsOpenEngine(): unable to initialise an EJS engine\n");
128                 ejs_error = 127;
129                 goto failed;
130         }
131
132         mprSetVar(ejsGetGlobalObject(eid), "ARGV", mprList("ARGV", NULL));
133
134         /* run the script */
135         if (ejsEvalScript(eid, script, &result, &emsg) == -1) {
136                 d_printf("smbscript: ejsEvalScript(): %s\n", emsg);
137                 if (ejs_error == 0) ejs_error = 127;
138                 goto failed;
139         }
140
141         return_var = ejsGetReturnValue(eid);
142         ejs_error = mprVarToNumber(return_var);
143
144 failed:
145         ejsClose();
146         talloc_free(mem_ctx);
147         return ejs_error;
148 }
149
150 static NTSTATUS test_become_dc_prepare_db_ejs(void *private_data,
151                                               const struct libnet_BecomeDC_PrepareDB *p)
152 {
153         struct test_become_dc_state *s = talloc_get_type(private_data, struct test_become_dc_state);
154         char *ejs;
155         int ret;
156         bool ok;
157
158         DEBUG(0,("Provision for Become-DC test using EJS\n"));
159
160         DEBUG(0,("New Server[%s] in Site[%s]\n",
161                 p->dest_dsa->dns_name, p->dest_dsa->site_name));
162
163         DEBUG(0,("DSA Instance [%s]\n"
164                 "\tobjectGUID[%s]\n"
165                 "\tinvocationId[%s]\n",
166                 p->dest_dsa->ntds_dn_str,
167                 GUID_string(s, &p->dest_dsa->ntds_guid),
168                 GUID_string(s, &p->dest_dsa->invocation_id)));
169
170         DEBUG(0,("Pathes under PRIVATEDIR[%s]\n"
171                  "SAMDB[%s] SECRETS[%s] KEYTAB[%s]\n",
172                 lp_private_dir(s->tctx->lp_ctx),
173                 s->path.samdb_ldb,
174                 s->path.secrets_ldb,
175                 s->path.secrets_keytab));
176
177         DEBUG(0,("Schema Partition[%s => %s]\n",
178                 p->forest->schema_dn_str, s->path.schemadn_ldb));
179
180         DEBUG(0,("Config Partition[%s => %s]\n",
181                 p->forest->config_dn_str, s->path.configdn_ldb));
182
183         DEBUG(0,("Domain Partition[%s => %s]\n",
184                 p->domain->dn_str, s->path.domaindn_ldb));
185
186         ejs = talloc_asprintf(s,
187                 "libinclude(\"base.js\");\n"
188                 "libinclude(\"provision.js\");\n"
189                 "\n"
190                 "function message() { print(vsprintf(arguments)); }\n"
191                 "\n"
192                 "var subobj = provision_guess();\n"
193                 "subobj.ROOTDN       = \"%s\";\n"
194                 "subobj.DOMAINDN     = \"%s\";\n"
195                 "subobj.DOMAINDN_LDB = \"%s\";\n"
196                 "subobj.CONFIGDN     = \"%s\";\n"
197                 "subobj.CONFIGDN_LDB = \"%s\";\n"
198                 "subobj.SCHEMADN     = \"%s\";\n"
199                 "subobj.SCHEMADN_LDB = \"%s\";\n"
200                 "subobj.HOSTNAME     = \"%s\";\n"
201                 "subobj.REALM        = \"%s\";\n"
202                 "subobj.DOMAIN       = \"%s\";\n"
203                 "subobj.DEFAULTSITE  = \"%s\";\n"
204                 "\n"
205                 "subobj.KRBTGTPASS   = \"_NOT_USED_\";\n"
206                 "subobj.MACHINEPASS  = \"%s\";\n"
207                 "subobj.ADMINPASS    = \"_NOT_USED_\";\n"
208                 "\n"
209                 "var paths = provision_default_paths(subobj);\n"
210                 "paths.samdb = \"%s\";\n"
211                 "paths.secrets = \"%s\";\n"
212                 "paths.templates = \"%s\";\n"
213                 "paths.keytab = \"%s\";\n"
214                 "paths.dns_keytab = \"%s\";\n"
215                 "\n"
216                 "var system_session = system_session();\n"
217                 "\n"
218                 "var ok = provision_become_dc(subobj, message, true, paths, system_session);\n"
219                 "assert(ok);\n"
220                 "\n"
221                 "return 0;\n",
222                 p->forest->root_dn_str,         /* subobj.ROOTDN */
223                 p->domain->dn_str,              /* subobj.DOMAINDN */
224                 s->path.domaindn_ldb,           /* subobj.DOMAINDN_LDB */
225                 p->forest->config_dn_str,       /* subobj.CONFIGDN */
226                 s->path.configdn_ldb,           /* subobj.CONFIGDN_LDB */
227                 p->forest->schema_dn_str,       /* subobj.SCHEMADN */
228                 s->path.schemadn_ldb,           /* subobj.SCHEMADN_LDB */
229                 p->dest_dsa->netbios_name,      /* subobj.HOSTNAME */
230                 torture_join_dom_dns_name(s->tj),/* subobj.REALM */
231                 torture_join_dom_netbios_name(s->tj),/* subobj.DOMAIN */
232                 p->dest_dsa->site_name,         /* subobj.DEFAULTSITE */
233                 cli_credentials_get_password(s->machine_account),/* subobj.MACHINEPASS */
234                 s->path.samdb_ldb,              /* paths.samdb */
235                 s->path.templates_ldb,          /* paths.templates */
236                 s->path.secrets_ldb,            /* paths.secrets */
237                 s->path.secrets_keytab,         /* paths.keytab */
238                 s->path.dns_keytab);            /* paths.dns_keytab */
239         NT_STATUS_HAVE_NO_MEMORY(ejs);
240
241         ret = test_run_ejs(ejs);
242         if (ret != 0) {
243                 DEBUG(0,("Failed to run ejs script: %d:\n%s",
244                         ret, ejs));
245                 talloc_free(ejs);
246                 return NT_STATUS_FOOBAR;
247         }
248         talloc_free(ejs);
249
250         talloc_free(s->ldb);
251
252         DEBUG(0,("Open the SAM LDB with system credentials: %s\n", 
253                  s->path.samdb_ldb));
254
255         s->ldb = ldb_wrap_connect(s, s->tctx->lp_ctx, s->path.samdb_ldb,
256                                   system_session(s, s->tctx->lp_ctx),
257                                   NULL, 0, NULL);
258         if (!s->ldb) {
259                 DEBUG(0,("Failed to open '%s'\n",
260                         s->path.samdb_ldb));
261                 return NT_STATUS_INTERNAL_DB_ERROR;
262         }
263
264         ok = samdb_set_ntds_invocation_id(s->ldb, &p->dest_dsa->invocation_id);
265         if (!ok) {
266                 DEBUG(0,("Failed to set cached ntds invocationId\n"));
267                 return NT_STATUS_FOOBAR;
268         }
269         ok = samdb_set_ntds_objectGUID(s->ldb, &p->dest_dsa->ntds_guid);
270         if (!ok) {
271                 DEBUG(0,("Failed to set cached ntds objectGUID\n"));
272                 return NT_STATUS_FOOBAR;
273         }
274
275         return NT_STATUS_OK;
276 }
277
278 #ifdef HAVE_WORKING_PYTHON
279 #include "param/param.h"
280 #include <Python.h>
281 #include "scripting/python/modules.h"
282
283 static NTSTATUS test_become_dc_prepare_db_py(void *private_data,
284                                              const struct libnet_BecomeDC_PrepareDB *p)
285 {
286         struct test_become_dc_state *s = talloc_get_type(private_data, struct test_become_dc_state);
287         bool ok;
288         PyObject *provision_fn, *result, *parameters;
289
290         DEBUG(0,("Provision for Become-DC test using PYTHON\n"));
291
292         py_load_samba_modules();
293         Py_Initialize();
294
295         py_update_path("bin"); /* FIXME: Can't assume this always runs in source/... */
296
297         provision_fn = PyImport_Import(PyString_FromString("samba.provision.provision"));
298
299         if (provision_fn == NULL) {
300                 DEBUG(0, ("Unable to import provision Python module.\n"));
301                 return NT_STATUS_UNSUCCESSFUL;
302         }
303         
304         DEBUG(0,("New Server[%s] in Site[%s]\n",
305                 p->dest_dsa->dns_name, p->dest_dsa->site_name));
306
307         DEBUG(0,("DSA Instance [%s]\n"
308                 "\tobjectGUID[%s]\n"
309                 "\tinvocationId[%s]\n",
310                 p->dest_dsa->ntds_dn_str,
311                 GUID_string(s, &p->dest_dsa->ntds_guid),
312                 GUID_string(s, &p->dest_dsa->invocation_id)));
313
314         DEBUG(0,("Pathes under PRIVATEDIR[%s]\n"
315                  "SAMDB[%s] SECRETS[%s] KEYTAB[%s]\n",
316                 lp_private_dir(s->tctx->lp_ctx),
317                 s->path.samdb_ldb,
318                 s->path.secrets_ldb,
319                 s->path.secrets_keytab));
320
321         DEBUG(0,("Schema Partition[%s => %s]\n",
322                 p->forest->schema_dn_str, s->path.schemadn_ldb));
323
324         DEBUG(0,("Config Partition[%s => %s]\n",
325                 p->forest->config_dn_str, s->path.configdn_ldb));
326
327         DEBUG(0,("Domain Partition[%s => %s]\n",
328                 p->domain->dn_str, s->path.domaindn_ldb));
329
330         parameters = PyDict_New();
331
332         PyDict_SetItemString(parameters, "rootdn", PyString_FromString(p->forest->root_dn_str));
333         PyDict_SetItemString(parameters, "domaindn", PyString_FromString(p->domain->dn_str));
334         PyDict_SetItemString(parameters, "domaindn_ldb", PyString_FromString(s->path.domaindn_ldb));
335         PyDict_SetItemString(parameters, "configdn", PyString_FromString(p->forest->config_dn_str));
336         PyDict_SetItemString(parameters, "configdn_ldb", PyString_FromString(s->path.configdn_ldb));
337         PyDict_SetItemString(parameters, "schema_dn_str", PyString_FromString(p->forest->schema_dn_str));
338         PyDict_SetItemString(parameters, "schemadn_ldb", PyString_FromString(s->path.schemadn_ldb));
339         PyDict_SetItemString(parameters, "netbios_name", PyString_FromString(p->dest_dsa->netbios_name));
340         PyDict_SetItemString(parameters, "dnsname", PyString_FromString(p->dest_dsa->dns_name));
341         PyDict_SetItemString(parameters, "defaultsite", PyString_FromString(p->dest_dsa->site_name));
342         PyDict_SetItemString(parameters, "machinepass", PyString_FromString(cli_credentials_get_password(s->machine_account)));
343         PyDict_SetItemString(parameters, "samdb", PyString_FromString(s->path.samdb_ldb));
344         PyDict_SetItemString(parameters, "secrets_ldb", PyString_FromString(s->path.secrets_ldb));
345         PyDict_SetItemString(parameters, "secrets_keytab", PyString_FromString(s->path.secrets_keytab));
346
347         result = PyEval_CallObjectWithKeywords(provision_fn, NULL, parameters);
348
349         Py_DECREF(parameters);
350
351         if (result == NULL) {
352                 PyErr_Print();
353                 PyErr_Clear();
354                 return NT_STATUS_UNSUCCESSFUL;
355         }
356
357         talloc_free(s->ldb);
358
359         DEBUG(0,("Open the SAM LDB with system credentials: %s\n", 
360                  s->path.samdb_ldb));
361
362         s->ldb = ldb_wrap_connect(s, s->tctx->lp_ctx, s->path.samdb_ldb,
363                                   system_session(s, s->tctx->lp_ctx),
364                                   NULL, 0, NULL);
365         if (!s->ldb) {
366                 DEBUG(0,("Failed to open '%s'\n",
367                         s->path.samdb_ldb));
368                 return NT_STATUS_INTERNAL_DB_ERROR;
369         }
370
371         ok = samdb_set_ntds_invocation_id(s->ldb, &p->dest_dsa->invocation_id);
372         if (!ok) {
373                 DEBUG(0,("Failed to set cached ntds invocationId\n"));
374                 return NT_STATUS_FOOBAR;
375         }
376         ok = samdb_set_ntds_objectGUID(s->ldb, &p->dest_dsa->ntds_guid);
377         if (!ok) {
378                 DEBUG(0,("Failed to set cached ntds objectGUID\n"));
379                 return NT_STATUS_FOOBAR;
380         }
381
382         return NT_STATUS_OK;
383 }
384 #endif /* HAVE_WORKING_PYTHON */
385
386 static NTSTATUS test_apply_schema(struct test_become_dc_state *s,
387                                   const struct libnet_BecomeDC_StoreChunk *c)
388 {
389         WERROR status;
390         const struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr;
391         uint32_t total_object_count;
392         uint32_t object_count;
393         struct drsuapi_DsReplicaObjectListItemEx *first_object;
394         struct drsuapi_DsReplicaObjectListItemEx *cur;
395         uint32_t linked_attributes_count;
396         struct drsuapi_DsReplicaLinkedAttribute *linked_attributes;
397         const struct drsuapi_DsReplicaCursor2CtrEx *uptodateness_vector;
398         struct dsdb_extended_replicated_objects *objs;
399         struct repsFromTo1 *s_dsa;
400         char *tmp_dns_name;
401         struct ldb_message *msg;
402         struct ldb_val prefixMap_val;
403         struct ldb_message_element *prefixMap_el;
404         struct ldb_val schemaInfo_val;
405         uint32_t i;
406         int ret;
407         bool ok;
408
409         DEBUG(0,("Analyze and apply schema objects\n"));
410
411         s_dsa                   = talloc_zero(s, struct repsFromTo1);
412         NT_STATUS_HAVE_NO_MEMORY(s_dsa);
413         s_dsa->other_info       = talloc(s_dsa, struct repsFromTo1OtherInfo);
414         NT_STATUS_HAVE_NO_MEMORY(s_dsa->other_info);
415
416         switch (c->ctr_level) {
417         case 1:
418                 mapping_ctr                     = &c->ctr1->mapping_ctr;
419                 total_object_count              = c->ctr1->total_object_count;
420                 object_count                    = s->schema_part.object_count;
421                 first_object                    = s->schema_part.first_object;
422                 linked_attributes_count         = 0;
423                 linked_attributes               = NULL;
424                 s_dsa->highwatermark            = c->ctr1->new_highwatermark;
425                 s_dsa->source_dsa_obj_guid      = c->ctr1->source_dsa_guid;
426                 s_dsa->source_dsa_invocation_id = c->ctr1->source_dsa_invocation_id;
427                 uptodateness_vector             = NULL; /* TODO: map it */
428                 break;
429         case 6:
430                 mapping_ctr                     = &c->ctr6->mapping_ctr;
431                 total_object_count              = c->ctr6->total_object_count;
432                 object_count                    = s->schema_part.object_count;
433                 first_object                    = s->schema_part.first_object;
434                 linked_attributes_count         = 0; /* TODO: ! */
435                 linked_attributes               = NULL; /* TODO: ! */;
436                 s_dsa->highwatermark            = c->ctr6->new_highwatermark;
437                 s_dsa->source_dsa_obj_guid      = c->ctr6->source_dsa_guid;
438                 s_dsa->source_dsa_invocation_id = c->ctr6->source_dsa_invocation_id;
439                 uptodateness_vector             = c->ctr6->uptodateness_vector;
440                 break;
441         default:
442                 return NT_STATUS_INVALID_PARAMETER;
443         }
444
445         s_dsa->replica_flags            = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
446                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
447                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS;
448         memset(s_dsa->schedule, 0x11, sizeof(s_dsa->schedule));
449
450         tmp_dns_name    = GUID_string(s_dsa->other_info, &s_dsa->source_dsa_obj_guid);
451         NT_STATUS_HAVE_NO_MEMORY(tmp_dns_name);
452         tmp_dns_name    = talloc_asprintf_append_buffer(tmp_dns_name, "._msdcs.%s", c->forest->dns_name);
453         NT_STATUS_HAVE_NO_MEMORY(tmp_dns_name);
454         s_dsa->other_info->dns_name = tmp_dns_name;
455
456         for (cur = first_object; cur; cur = cur->next_object) {
457                 bool is_attr = false;
458                 bool is_class = false;
459
460                 for (i=0; i < cur->object.attribute_ctr.num_attributes; i++) {
461                         struct drsuapi_DsReplicaAttribute *a;
462                         uint32_t j;
463                         const char *oid = NULL;
464
465                         a = &cur->object.attribute_ctr.attributes[i];
466                         status = dsdb_map_int2oid(s->self_made_schema, a->attid, s, &oid);
467                         if (!W_ERROR_IS_OK(status)) {
468                                 return werror_to_ntstatus(status);
469                         }
470
471                         switch (a->attid) {
472                         case DRSUAPI_ATTRIBUTE_objectClass:
473                                 for (j=0; j < a->value_ctr.num_values; j++) {
474                                         uint32_t val = 0xFFFFFFFF;
475
476                                         if (a->value_ctr.values[i].blob
477                                             && a->value_ctr.values[i].blob->length == 4) {
478                                                 val = IVAL(a->value_ctr.values[i].blob->data,0);
479                                         }
480
481                                         if (val == DRSUAPI_OBJECTCLASS_attributeSchema) {
482                                                 is_attr = true;
483                                         }
484                                         if (val == DRSUAPI_OBJECTCLASS_classSchema) {
485                                                 is_class = true;
486                                         }
487                                 }
488
489                                 break;
490                         default:
491                                 break;
492                         }
493                 }
494
495                 if (is_attr) {
496                         struct dsdb_attribute *sa;
497
498                         sa = talloc_zero(s->self_made_schema, struct dsdb_attribute);
499                         NT_STATUS_HAVE_NO_MEMORY(sa);
500
501                         status = dsdb_attribute_from_drsuapi(s->self_made_schema, &cur->object, s, sa);
502                         if (!W_ERROR_IS_OK(status)) {
503                                 return werror_to_ntstatus(status);
504                         }
505
506                         DLIST_ADD_END(s->self_made_schema->attributes, sa, struct dsdb_attribute *);
507                 }
508
509                 if (is_class) {
510                         struct dsdb_class *sc;
511
512                         sc = talloc_zero(s->self_made_schema, struct dsdb_class);
513                         NT_STATUS_HAVE_NO_MEMORY(sc);
514
515                         status = dsdb_class_from_drsuapi(s->self_made_schema, &cur->object, s, sc);
516                         if (!W_ERROR_IS_OK(status)) {
517                                 return werror_to_ntstatus(status);
518                         }
519
520                         DLIST_ADD_END(s->self_made_schema->classes, sc, struct dsdb_class *);
521                 }
522         }
523
524         /* attach the schema to the ldb */
525         ret = dsdb_set_schema(s->ldb, s->self_made_schema);
526         if (ret != LDB_SUCCESS) {
527                 return NT_STATUS_FOOBAR;
528         }
529         /* we don't want to access the self made schema anymore */
530         s->self_made_schema = NULL;
531         s->schema = dsdb_get_schema(s->ldb);
532
533         status = dsdb_extended_replicated_objects_commit(s->ldb,
534                                                          c->partition->nc.dn,
535                                                          mapping_ctr,
536                                                          object_count,
537                                                          first_object,
538                                                          linked_attributes_count,
539                                                          linked_attributes,
540                                                          s_dsa,
541                                                          uptodateness_vector,
542                                                          c->gensec_skey,
543                                                          s, &objs);
544         if (!W_ERROR_IS_OK(status)) {
545                 DEBUG(0,("Failed to commit objects: %s\n", win_errstr(status)));
546                 return werror_to_ntstatus(status);
547         }
548
549         if (lp_parm_bool(s->tctx->lp_ctx, NULL, "become dc", "dump objects", false)) {
550                 for (i=0; i < objs->num_objects; i++) {
551                         struct ldb_ldif ldif;
552                         fprintf(stdout, "#\n");
553                         ldif.changetype = LDB_CHANGETYPE_NONE;
554                         ldif.msg = objs->objects[i].msg;
555                         ldb_ldif_write_file(s->ldb, stdout, &ldif);
556                         NDR_PRINT_DEBUG(replPropertyMetaDataBlob, objs->objects[i].meta_data);
557                 }
558         }
559
560         msg = ldb_msg_new(objs);
561         NT_STATUS_HAVE_NO_MEMORY(msg);
562         msg->dn = objs->partition_dn;
563
564         status = dsdb_get_oid_mappings_ldb(s->schema, msg, &prefixMap_val, &schemaInfo_val);
565         if (!W_ERROR_IS_OK(status)) {
566                 DEBUG(0,("Failed dsdb_get_oid_mappings_ldb(%s)\n", win_errstr(status)));
567                 return werror_to_ntstatus(status);
568         }
569
570         /* we only add prefixMap here, because schemaInfo is a replicated attribute and already applied */
571         ret = ldb_msg_add_value(msg, "prefixMap", &prefixMap_val, &prefixMap_el);
572         if (ret != LDB_SUCCESS) {
573                 return NT_STATUS_FOOBAR;
574         }
575         prefixMap_el->flags = LDB_FLAG_MOD_REPLACE;
576
577         ret = ldb_modify(s->ldb, msg);
578         if (ret != LDB_SUCCESS) {
579                 DEBUG(0,("Failed to add prefixMap and schemaInfo %s\n", ldb_strerror(ret)));
580                 return NT_STATUS_FOOBAR;
581         }
582
583         talloc_free(s_dsa);
584         talloc_free(objs);
585
586         /* reopen the ldb */
587         talloc_free(s->ldb); /* this also free's the s->schema, because dsdb_set_schema() steals it */
588         s->schema = NULL;
589
590         DEBUG(0,("Reopen the SAM LDB with system credentials and a already stored schema: %s\n", s->path.samdb_ldb));
591         s->ldb = ldb_wrap_connect(s, s->tctx->lp_ctx, s->path.samdb_ldb,
592                                   system_session(s, s->tctx->lp_ctx),
593                                   NULL, 0, NULL);
594         if (!s->ldb) {
595                 DEBUG(0,("Failed to open '%s'\n",
596                         s->path.samdb_ldb));
597                 return NT_STATUS_INTERNAL_DB_ERROR;
598         }
599
600         ok = samdb_set_ntds_invocation_id(s->ldb, &c->dest_dsa->invocation_id);
601         if (!ok) {
602                 DEBUG(0,("Failed to set cached ntds invocationId\n"));
603                 return NT_STATUS_FOOBAR;
604         }
605         ok = samdb_set_ntds_objectGUID(s->ldb, &c->dest_dsa->ntds_guid);
606         if (!ok) {
607                 DEBUG(0,("Failed to set cached ntds objectGUID\n"));
608                 return NT_STATUS_FOOBAR;
609         }
610
611         s->schema = dsdb_get_schema(s->ldb);
612         if (!s->schema) {
613                 DEBUG(0,("Failed to get loaded dsdb_schema\n"));
614                 return NT_STATUS_FOOBAR;
615         }
616
617         return NT_STATUS_OK;
618 }
619
620 static NTSTATUS test_become_dc_schema_chunk(void *private_data,
621                                             const struct libnet_BecomeDC_StoreChunk *c)
622 {
623         struct test_become_dc_state *s = talloc_get_type(private_data, struct test_become_dc_state);
624         WERROR status;
625         const struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr;
626         uint32_t total_object_count;
627         uint32_t object_count;
628         struct drsuapi_DsReplicaObjectListItemEx *first_object;
629         struct drsuapi_DsReplicaObjectListItemEx *cur;
630
631         switch (c->ctr_level) {
632         case 1:
633                 mapping_ctr             = &c->ctr1->mapping_ctr;
634                 total_object_count      = c->ctr1->total_object_count;
635                 object_count            = c->ctr1->object_count;
636                 first_object            = c->ctr1->first_object;
637                 break;
638         case 6:
639                 mapping_ctr             = &c->ctr6->mapping_ctr;
640                 total_object_count      = c->ctr6->total_object_count;
641                 object_count            = c->ctr6->object_count;
642                 first_object            = c->ctr6->first_object;
643                 break;
644         default:
645                 return NT_STATUS_INVALID_PARAMETER;
646         }
647
648         if (total_object_count) {
649                 DEBUG(0,("Schema-DN[%s] objects[%u/%u]\n",
650                         c->partition->nc.dn, object_count, total_object_count));
651         } else {
652                 DEBUG(0,("Schema-DN[%s] objects[%u]\n",
653                 c->partition->nc.dn, object_count));
654         }
655
656         if (!s->schema) {
657                 s->self_made_schema = talloc_zero(s, struct dsdb_schema);
658                 NT_STATUS_HAVE_NO_MEMORY(s->self_made_schema);
659
660                 status = dsdb_load_oid_mappings_drsuapi(s->self_made_schema, mapping_ctr);
661                 if (!W_ERROR_IS_OK(status)) {
662                         return werror_to_ntstatus(status);
663                 }
664
665                 s->schema = s->self_made_schema;
666         } else {
667                 status = dsdb_verify_oid_mappings_drsuapi(s->schema, mapping_ctr);
668                 if (!W_ERROR_IS_OK(status)) {
669                         return werror_to_ntstatus(status);
670                 }
671         }
672
673         if (!s->schema_part.first_object) {
674                 s->schema_part.object_count = object_count;
675                 s->schema_part.first_object = talloc_steal(s, first_object);
676         } else {
677                 s->schema_part.object_count             += object_count;
678                 s->schema_part.last_object->next_object = talloc_steal(s->schema_part.last_object,
679                                                                        first_object);
680         }
681         for (cur = first_object; cur->next_object; cur = cur->next_object) {}
682         s->schema_part.last_object = cur;
683
684         if (c->partition->highwatermark.tmp_highest_usn == c->partition->highwatermark.highest_usn) {
685                 return test_apply_schema(s, c);
686         }
687
688         return NT_STATUS_OK;
689 }
690
691 static NTSTATUS test_become_dc_store_chunk(void *private_data,
692                                            const struct libnet_BecomeDC_StoreChunk *c)
693 {
694         struct test_become_dc_state *s = talloc_get_type(private_data, struct test_become_dc_state);
695         WERROR status;
696         const struct drsuapi_DsReplicaOIDMapping_Ctr *mapping_ctr;
697         uint32_t total_object_count;
698         uint32_t object_count;
699         struct drsuapi_DsReplicaObjectListItemEx *first_object;
700         uint32_t linked_attributes_count;
701         struct drsuapi_DsReplicaLinkedAttribute *linked_attributes;
702         const struct drsuapi_DsReplicaCursor2CtrEx *uptodateness_vector;
703         struct dsdb_extended_replicated_objects *objs;
704         struct repsFromTo1 *s_dsa;
705         char *tmp_dns_name;
706         uint32_t i;
707
708         s_dsa                   = talloc_zero(s, struct repsFromTo1);
709         NT_STATUS_HAVE_NO_MEMORY(s_dsa);
710         s_dsa->other_info       = talloc(s_dsa, struct repsFromTo1OtherInfo);
711         NT_STATUS_HAVE_NO_MEMORY(s_dsa->other_info);
712
713         switch (c->ctr_level) {
714         case 1:
715                 mapping_ctr                     = &c->ctr1->mapping_ctr;
716                 total_object_count              = c->ctr1->total_object_count;
717                 object_count                    = c->ctr1->object_count;
718                 first_object                    = c->ctr1->first_object;
719                 linked_attributes_count         = 0;
720                 linked_attributes               = NULL;
721                 s_dsa->highwatermark            = c->ctr1->new_highwatermark;
722                 s_dsa->source_dsa_obj_guid      = c->ctr1->source_dsa_guid;
723                 s_dsa->source_dsa_invocation_id = c->ctr1->source_dsa_invocation_id;
724                 uptodateness_vector             = NULL; /* TODO: map it */
725                 break;
726         case 6:
727                 mapping_ctr                     = &c->ctr6->mapping_ctr;
728                 total_object_count              = c->ctr6->total_object_count;
729                 object_count                    = c->ctr6->object_count;
730                 first_object                    = c->ctr6->first_object;
731                 linked_attributes_count         = c->ctr6->linked_attributes_count;
732                 linked_attributes               = c->ctr6->linked_attributes;
733                 s_dsa->highwatermark            = c->ctr6->new_highwatermark;
734                 s_dsa->source_dsa_obj_guid      = c->ctr6->source_dsa_guid;
735                 s_dsa->source_dsa_invocation_id = c->ctr6->source_dsa_invocation_id;
736                 uptodateness_vector             = c->ctr6->uptodateness_vector;
737                 break;
738         default:
739                 return NT_STATUS_INVALID_PARAMETER;
740         }
741
742         s_dsa->replica_flags            = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
743                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
744                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS;
745         memset(s_dsa->schedule, 0x11, sizeof(s_dsa->schedule));
746
747         tmp_dns_name    = GUID_string(s_dsa->other_info, &s_dsa->source_dsa_obj_guid);
748         NT_STATUS_HAVE_NO_MEMORY(tmp_dns_name);
749         tmp_dns_name    = talloc_asprintf_append_buffer(tmp_dns_name, "._msdcs.%s", c->forest->dns_name);
750         NT_STATUS_HAVE_NO_MEMORY(tmp_dns_name);
751         s_dsa->other_info->dns_name = tmp_dns_name;
752
753         if (total_object_count) {
754                 DEBUG(0,("Partition[%s] objects[%u/%u]\n",
755                         c->partition->nc.dn, object_count, total_object_count));
756         } else {
757                 DEBUG(0,("Partition[%s] objects[%u]\n",
758                 c->partition->nc.dn, object_count));
759         }
760
761         status = dsdb_extended_replicated_objects_commit(s->ldb,
762                                                          c->partition->nc.dn,
763                                                          mapping_ctr,
764                                                          object_count,
765                                                          first_object,
766                                                          linked_attributes_count,
767                                                          linked_attributes,
768                                                          s_dsa,
769                                                          uptodateness_vector,
770                                                          c->gensec_skey,
771                                                          s, &objs);
772         if (!W_ERROR_IS_OK(status)) {
773                 DEBUG(0,("Failed to commit objects: %s\n", win_errstr(status)));
774                 return werror_to_ntstatus(status);
775         }
776
777         if (lp_parm_bool(s->tctx->lp_ctx, NULL, "become dc", "dump objects", false)) {
778                 for (i=0; i < objs->num_objects; i++) {
779                         struct ldb_ldif ldif;
780                         fprintf(stdout, "#\n");
781                         ldif.changetype = LDB_CHANGETYPE_NONE;
782                         ldif.msg = objs->objects[i].msg;
783                         ldb_ldif_write_file(s->ldb, stdout, &ldif);
784                         NDR_PRINT_DEBUG(replPropertyMetaDataBlob, objs->objects[i].meta_data);
785                 }
786         }
787         talloc_free(s_dsa);
788         talloc_free(objs);
789
790         for (i=0; i < linked_attributes_count; i++) {
791                 const struct dsdb_attribute *sa;
792
793                 if (!linked_attributes[i].identifier) {
794                         return NT_STATUS_FOOBAR;                
795                 }
796
797                 if (!linked_attributes[i].value.blob) {
798                         return NT_STATUS_FOOBAR;                
799                 }
800
801                 sa = dsdb_attribute_by_attributeID_id(s->schema,
802                                                       linked_attributes[i].attid);
803                 if (!sa) {
804                         return NT_STATUS_FOOBAR;
805                 }
806
807                 if (lp_parm_bool(s->tctx->lp_ctx, NULL, "become dc", "dump objects", false)) {
808                         DEBUG(0,("# %s\n", sa->lDAPDisplayName));
809                         NDR_PRINT_DEBUG(drsuapi_DsReplicaLinkedAttribute, &linked_attributes[i]);
810                         dump_data(0,
811                                 linked_attributes[i].value.blob->data,
812                                 linked_attributes[i].value.blob->length);
813                 }
814         }
815
816         return NT_STATUS_OK;
817 }
818
819 bool torture_net_become_dc(struct torture_context *torture)
820 {
821         bool ret = true;
822         NTSTATUS status;
823         struct libnet_BecomeDC b;
824         struct libnet_UnbecomeDC u;
825         struct test_become_dc_state *s;
826         struct ldb_message *msg;
827         int ldb_ret;
828         uint32_t i;
829
830         s = talloc_zero(torture, struct test_become_dc_state);
831         if (!s) return false;
832
833         s->tctx = torture;
834
835         s->netbios_name = lp_parm_string(torture->lp_ctx, NULL, "become dc", "smbtorture dc");
836         if (!s->netbios_name || !s->netbios_name[0]) {
837                 s->netbios_name = "smbtorturedc";
838         }
839
840         s->path.samdb_ldb       = talloc_asprintf(s, "%s_samdb.ldb", s->netbios_name);
841         if (!s->path.samdb_ldb) return false;
842         s->path.domaindn_ldb    = talloc_asprintf(s, "%s_domain.ldb", s->netbios_name);
843         if (!s->path.domaindn_ldb) return false;
844         s->path.configdn_ldb    = talloc_asprintf(s, "%s_config.ldb", s->netbios_name);
845         if (!s->path.configdn_ldb) return false;
846         s->path.schemadn_ldb    = talloc_asprintf(s, "%s_schema.ldb", s->netbios_name);
847         if (!s->path.schemadn_ldb) return false;
848         s->path.secrets_ldb     = talloc_asprintf(s, "%s_secrets.ldb", s->netbios_name);
849         if (!s->path.secrets_ldb) return false;
850         s->path.templates_ldb   = talloc_asprintf(s, "%s_templates.ldb", s->netbios_name);
851         if (!s->path.templates_ldb) return false;
852         s->path.secrets_keytab  = talloc_asprintf(s, "%s_secrets.keytab", s->netbios_name);
853         if (!s->path.secrets_keytab) return false;
854         s->path.dns_keytab      = talloc_asprintf(s, "%s_dns.keytab", s->netbios_name);
855         if (!s->path.dns_keytab) return false;
856
857         /* Join domain as a member server. */
858         s->tj = torture_join_domain(torture, s->netbios_name,
859                                  ACB_WSTRUST,
860                                  &s->machine_account);
861         if (!s->tj) {
862                 DEBUG(0, ("%s failed to join domain as workstation\n",
863                           s->netbios_name));
864                 return false;
865         }
866
867         s->ctx = libnet_context_init(torture->ev, torture->lp_ctx);
868         s->ctx->cred = cmdline_credentials;
869
870         s->ldb = ldb_init(s);
871
872         ZERO_STRUCT(b);
873         b.in.domain_dns_name            = torture_join_dom_dns_name(s->tj);
874         b.in.domain_netbios_name        = torture_join_dom_netbios_name(s->tj);
875         b.in.domain_sid                 = torture_join_sid(s->tj);
876         b.in.source_dsa_address         = torture_setting_string(torture, "host", NULL);
877         b.in.dest_dsa_netbios_name      = s->netbios_name;
878
879         b.in.callbacks.private_data     = s;
880         b.in.callbacks.check_options    = test_become_dc_check_options;
881         b.in.callbacks.prepare_db       = test_become_dc_prepare_db_ejs;
882 #ifdef HAVE_WORKING_PYTHON
883         if (getenv("PROVISION_PYTHON")) {
884                 b.in.callbacks.prepare_db = test_become_dc_prepare_db_py;
885         }
886 #endif
887         b.in.callbacks.schema_chunk     = test_become_dc_schema_chunk;
888         b.in.callbacks.config_chunk     = test_become_dc_store_chunk;
889         b.in.callbacks.domain_chunk     = test_become_dc_store_chunk;
890
891         status = libnet_BecomeDC(s->ctx, s, &b);
892         if (!NT_STATUS_IS_OK(status)) {
893                 printf("libnet_BecomeDC() failed - %s\n", nt_errstr(status));
894                 ret = false;
895                 goto cleanup;
896         }
897
898         msg = ldb_msg_new(s);
899         if (!msg) {
900                 printf("ldb_msg_new() failed\n");
901                 ret = false;
902                 goto cleanup;
903         }
904         msg->dn = ldb_dn_new(msg, s->ldb, "@ROOTDSE");
905         if (!msg->dn) {
906                 printf("ldb_msg_new(@ROOTDSE) failed\n");
907                 ret = false;
908                 goto cleanup;
909         }
910
911         ldb_ret = ldb_msg_add_string(msg, "isSynchronized", "TRUE");
912         if (ldb_ret != LDB_SUCCESS) {
913                 printf("ldb_msg_add_string(msg, isSynchronized, TRUE) failed: %d\n", ldb_ret);
914                 ret = false;
915                 goto cleanup;
916         }
917
918         for (i=0; i < msg->num_elements; i++) {
919                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
920         }
921
922         printf("mark ROOTDSE with isSynchronized=TRUE\n");
923         ldb_ret = ldb_modify(s->ldb, msg);
924         if (ldb_ret != LDB_SUCCESS) {
925                 printf("ldb_modify() failed: %d\n", ldb_ret);
926                 ret = false;
927                 goto cleanup;
928         }
929         
930         /* reopen the ldb */
931         talloc_free(s->ldb); /* this also free's the s->schema, because dsdb_set_schema() steals it */
932         s->schema = NULL;
933
934         DEBUG(0,("Reopen the SAM LDB with system credentials and all replicated data: %s\n", s->path.samdb_ldb));
935         s->ldb = ldb_wrap_connect(s, torture->lp_ctx, s->path.samdb_ldb,
936                                   system_session(s, torture->lp_ctx),
937                                   NULL, 0, NULL);
938         if (!s->ldb) {
939                 DEBUG(0,("Failed to open '%s'\n",
940                         s->path.samdb_ldb));
941                 ret = false;
942                 goto cleanup;
943         }
944
945         s->schema = dsdb_get_schema(s->ldb);
946         if (!s->schema) {
947                 DEBUG(0,("Failed to get loaded dsdb_schema\n"));
948                 ret = false;
949                 goto cleanup;
950         }
951
952         if (lp_parm_bool(torture->lp_ctx, NULL, "become dc", "do not unjoin", false)) {
953                 talloc_free(s);
954                 return ret;
955         }
956
957 cleanup:
958         ZERO_STRUCT(u);
959         u.in.domain_dns_name            = torture_join_dom_dns_name(s->tj);
960         u.in.domain_netbios_name        = torture_join_dom_netbios_name(s->tj);
961         u.in.source_dsa_address         = torture_setting_string(torture, "host", NULL);
962         u.in.dest_dsa_netbios_name      = s->netbios_name;
963
964         status = libnet_UnbecomeDC(s->ctx, s, &u);
965         if (!NT_STATUS_IS_OK(status)) {
966                 printf("libnet_UnbecomeDC() failed - %s\n", nt_errstr(status));
967                 ret = false;
968         }
969
970         /* Leave domain. */                          
971         torture_leave_domain(s->tj);
972
973         talloc_free(s);
974         return ret;
975 }