r25920: ndr: change NTSTAUS into enum ndr_err_code (samba4 callers)
[bbaumbach/samba-autobuild/.git] / source4 / libnet / libnet_become_dc.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Copyright (C) Stefan Metzmacher <metze@samba.org> 2006
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 #include "includes.h"
21 #include "libnet/libnet.h"
22 #include "libcli/composite/composite.h"
23 #include "libcli/cldap/cldap.h"
24 #include "lib/ldb/include/ldb.h"
25 #include "lib/ldb/include/ldb_errors.h"
26 #include "lib/db_wrap.h"
27 #include "dsdb/samdb/samdb.h"
28 #include "dsdb/common/flags.h"
29 #include "librpc/gen_ndr/ndr_drsuapi_c.h"
30 #include "libcli/security/security.h"
31 #include "librpc/gen_ndr/ndr_misc.h"
32 #include "librpc/gen_ndr/ndr_security.h"
33 #include "librpc/gen_ndr/ndr_drsuapi.h"
34 #include "auth/gensec/gensec.h"
35 #include "param/param.h"
36
37 /*****************************************************************************
38  * Windows 2003 (w2k3) does the following steps when changing the server role
39  * from domain member to domain controller
40  *
41  * We mostly do the same.
42  *****************************************************************************/
43
44 /*
45  * lookup DC:
46  * - using nbt name<1C> request and a samlogon mailslot request
47  * or
48  * - using a DNS SRV _ldap._tcp.dc._msdcs. request and a CLDAP netlogon request
49  *
50  * see: becomeDC_recv_cldap() and becomeDC_send_cldap()
51  */
52
53 /*
54  * Open 1st LDAP connection to the DC using admin credentials
55  *
56  * see: becomeDC_connect_ldap1() and becomeDC_ldap_connect()
57  */
58
59 /*
60  * LDAP search 1st LDAP connection:
61  *
62  * see: becomeDC_ldap1_rootdse()
63  *
64  * Request:
65  *      basedn: ""
66  *      scope:  base
67  *      filter: (objectClass=*)
68  *      attrs:  *
69  * Result:
70  *      ""
71  *              currentTime:            20061202155100.0Z
72  *              subschemaSubentry:      CN=Aggregate,CN=Schema,CN=Configuration,<domain_partition>
73  *              dsServiceName:          CN=<netbios_name>,CN=Servers,CN=<site_name>,CN=Sites,CN=Configuration,<domain_partition>
74  *              namingContexts:         <domain_partition>
75  *                                      CN=Configuration,<domain_partition>
76  *                                      CN=Schema,CN=Configuration,<domain_partition>
77  *              defaultNamingContext:   <domain_partition>
78  *              schemaNamingContext:    CN=Schema,CN=Configuration,<domain_partition>
79  *              configurationNamingContext:CN=Configuration,<domain_partition>
80  *              rootDomainNamingContext:<domain_partition>
81  *              supportedControl:       ...
82  *              supportedLDAPVersion:   3
83  *                                      2
84  *              supportedLDAPPolicies:  ...
85  *              highestCommitedUSN:     ...
86  *              supportedSASLMechanisms:GSSAPI
87  *                                      GSS-SPNEGO
88  *                                      EXTERNAL
89  *                                      DIGEST-MD5
90  *              dnsHostName:            <dns_host_name>
91  *              ldapServiceName:        <domain_dns_name>:<netbios_name>$@<REALM>
92  *              serverName:             CN=Servers,CN=<site_name>,CN=Sites,CN=Configuration,<domain_partition>
93  *              supportedCapabilities:  ...
94  *              isSyncronized:          TRUE
95  *              isGlobalCatalogReady:   TRUE
96  *              domainFunctionality:    0
97  *              forestFunctionality:    0
98  *              domainControllerFunctionality: 2
99  */
100
101 /*
102  * LDAP search 1st LDAP connection:
103  *
104  * see: becomeDC_ldap1_crossref_behavior_version()
105  *
106  * Request:
107  *      basedn: CN=Configuration,<domain_partition>
108  *      scope:  one
109  *      filter: (cn=Partitions)
110  *      attrs:  msDS-Behavior-Version
111  * Result:
112  *      CN=Partitions,CN=Configuration,<domain_partition>
113  *              msDS-Behavior-Version:  0
114  */
115
116 /*
117  * LDAP search 1st LDAP connection:
118  *
119  * NOTE: this seems to be a bug! as the messageID of the LDAP message is corrupted!
120  *
121  * not implemented here
122  * 
123  * Request:
124  *      basedn: CN=Schema,CN=Configuration,<domain_partition>
125  *      scope:  one
126  *      filter: (cn=Partitions)
127  *      attrs:  msDS-Behavior-Version
128  * Result:
129  *      <none>
130  *
131  */
132
133 /*
134  * LDAP search 1st LDAP connection:
135  *
136  * see: becomeDC_ldap1_domain_behavior_version()
137  * 
138  * Request:
139  *      basedn: <domain_partition>
140  *      scope:  base
141  *      filter: (objectClass=*)
142  *      attrs:  msDS-Behavior-Version
143  * Result:
144  *      <domain_partition>
145  *              msDS-Behavior-Version:  0
146  */
147
148 /*
149  * LDAP search 1st LDAP connection:
150  * 
151  * see: becomeDC_ldap1_schema_object_version()
152  *
153  * Request:
154  *      basedn: CN=Schema,CN=Configuration,<domain_partition>
155  *      scope:  base
156  *      filter: (objectClass=*)
157  *      attrs:  objectVersion
158  * Result:
159  *      CN=Schema,CN=Configuration,<domain_partition>
160  *              objectVersion:  30
161  */
162
163 /*
164  * LDAP search 1st LDAP connection:
165  * 
166  * not implemented, because the information is already there
167  *
168  * Request:
169  *      basedn: ""
170  *      scope:  base
171  *      filter: (objectClass=*)
172  *      attrs:  defaultNamingContext
173  *              dnsHostName
174  * Result:
175  *      ""
176  *              defaultNamingContext:   <domain_partition>
177  *              dnsHostName:            <dns_host_name>
178  */
179
180 /*
181  * LDAP search 1st LDAP connection:
182  *
183  * see: becomeDC_ldap1_infrastructure_fsmo()
184  * 
185  * Request:
186  *      basedn: <WKGUID=2fbac1870ade11d297c400c04fd8d5cd,domain_partition>
187  *      scope:  base
188  *      filter: (objectClass=*)
189  *      attrs:  1.1
190  * Result:
191  *      CN=Infrastructure,<domain_partition>
192  */
193
194 /*
195  * LDAP search 1st LDAP connection:
196  *
197  * see: becomeDC_ldap1_w2k3_update_revision()
198  *
199  * Request:
200  *      basedn: CN=Windows2003Update,CN=DomainUpdates,CN=System,<domain_partition>
201  *      scope:  base
202  *      filter: (objectClass=*)
203  *      attrs:  revision
204  * Result:
205  *      CN=Windows2003Update,CN=DomainUpdates,CN=System,<domain_partition>
206  *              revision:       8
207  */
208
209 /*
210  * LDAP search 1st LDAP connection:
211  *
212  * see: becomeDC_ldap1_infrastructure_fsmo()
213  *
214  * Request:
215  *      basedn: CN=Infrastructure,<domain_partition>
216  *      scope:  base
217  *      filter: (objectClass=*)
218  *      attrs:  fSMORoleOwner
219  * Result:
220  *      CN=Infrastructure,<domain_partition>
221  *              fSMORoleOwner:  CN=NTDS Settings,<infrastructure_fsmo_server_object>
222  */
223
224 /*
225  * LDAP search 1st LDAP connection:
226  *
227  * see: becomeDC_ldap1_infrastructure_fsmo()
228  *
229  * Request:
230  *      basedn: <infrastructure_fsmo_server_object>
231  *      scope:  base
232  *      filter: (objectClass=*)
233  *      attrs:  dnsHostName
234  * Result:
235  *      <infrastructure_fsmo_server_object>
236  *              dnsHostName:    <dns_host_name>
237  */
238
239 /*
240  * LDAP search 1st LDAP connection:
241  *
242  * see: becomeDC_ldap1_infrastructure_fsmo()
243  *
244  * Request:
245  *      basedn: CN=NTDS Settings,<infrastructure_fsmo_server_object>
246  *      scope:  base
247  *      filter: (objectClass=*)
248  *      attrs:  objectGUID
249  * Result:
250  *      CN=NTDS Settings,<infrastructure_fsmo_server_object>
251  *              objectGUID:     <object_guid>
252  */
253
254 /*
255  * LDAP search 1st LDAP connection:
256  * 
257  * see: becomeDC_ldap1_rid_manager_fsmo()
258  *
259  * Request:
260  *      basedn: <domain_partition>
261  *      scope:  base
262  *      filter: (objectClass=*)
263  *      attrs:  rIDManagerReference
264  * Result:
265  *      <domain_partition>
266  *              rIDManagerReference:    CN=RID Manager$,CN=System,<domain_partition>
267  */
268
269 /*
270  * LDAP search 1st LDAP connection:
271  * 
272  * see: becomeDC_ldap1_rid_manager_fsmo()
273  *
274  * Request:
275  *      basedn: CN=RID Manager$,CN=System,<domain_partition>
276  *      scope:  base
277  *      filter: (objectClass=*)
278  *      attrs:  fSMORoleOwner
279  * Result:
280  *      CN=Infrastructure,<domain_partition>
281  *              fSMORoleOwner:  CN=NTDS Settings,<rid_manager_fsmo_server_object>
282  */
283
284 /*
285  * LDAP search 1st LDAP connection:
286  *
287  * see: becomeDC_ldap1_rid_manager_fsmo()
288  *
289  * Request:
290  *      basedn: <rid_manager_fsmo_server_object>
291  *      scope:  base
292  *      filter: (objectClass=*)
293  *      attrs:  dnsHostName
294  * Result:
295  *      <rid_manager_fsmo_server_object>
296  *              dnsHostName:    <dns_host_name>
297  */
298
299 /*
300  * LDAP search 1st LDAP connection:
301  *
302  * see: becomeDC_ldap1_rid_manager_fsmo()
303  *
304  * Request:
305  *      basedn: CN=NTDS Settings,<rid_manager_fsmo_server_object>
306  *      scope:  base
307  *      filter: (objectClass=*)
308  *      attrs:  msDs-ReplicationEpoch
309  * Result:
310  *      CN=NTDS Settings,<rid_manager_fsmo_server_object>
311  */
312
313 /*
314  * LDAP search 1st LDAP connection:
315  *
316  * see: becomeDC_ldap1_site_object()
317  *
318  * Request:
319  *      basedn: CN=<new_dc_site_name>,CN=Sites,CN=Configuration,<domain_partition>
320  *      scope:  base
321  *      filter: (objectClass=*)
322  *      attrs:
323  * Result:
324  *      CN=<new_dc_site_name>,CN=Sites,CN=Configuration,<domain_partition>
325  *              objectClass:    top
326  *                              site
327  *              cn:             <new_dc_site_name>
328  *              distinguishedName:CN=<new_dc_site_name>,CN=Sites,CN=Configuration,<domain_partition>
329  *              instanceType:   4
330  *              whenCreated:    ...
331  *              whenChanged:    ...
332  *              uSNCreated:     ...
333  *              uSNChanged:     ...
334  *              showInAdvancedViewOnly: TRUE
335  *              name:           <new_dc_site_name>
336  *              objectGUID:     <object_guid>
337  *              systemFlags:    1107296256 <0x42000000>
338  *              objectCategory: CN=Site,C=Schema,CN=Configuration,<domain_partition>
339  */
340
341 /***************************************************************
342  * Add this stage we call the check_options() callback function
343  * of the caller, to see if he wants us to continue
344  *
345  * see: becomeDC_check_options()
346  ***************************************************************/
347
348 /*
349  * LDAP search 1st LDAP connection:
350  *
351  * see: becomeDC_ldap1_computer_object()
352  *
353  * Request:
354  *      basedn: <domain_partition>
355  *      scope:  sub
356  *      filter: (&(|(objectClass=user)(objectClass=computer))(sAMAccountName=<new_dc_account_name>))
357  *      attrs:  distinguishedName
358  *              userAccountControl
359  * Result:
360  *      CN=<new_dc_netbios_name>,CN=Computers,<domain_partition>
361  *              distinguishedName:      CN=<new_dc_netbios_name>,CN=Computers,<domain_partition>
362  *              userAccoountControl:    4096 <0x1000>
363  */
364
365 /*
366  * LDAP search 1st LDAP connection:
367  *
368  * see: becomeDC_ldap1_server_object_1()
369  *
370  * Request:
371  *      basedn: CN=<new_dc_netbios_name>,CN=Servers,CN=<new_dc_site_name>,CN=Sites,CN=Configuration,<domain_partition>
372  *      scope:  base
373  *      filter: (objectClass=*)
374  *      attrs:
375  * Result:
376  *      <noSuchObject>
377  *      <matchedDN:CN=Servers,CN=<new_dc_site_name>,CN=Sites,CN=Configuration,<domain_partition>>
378  */
379
380 /*
381  * LDAP search 1st LDAP connection:
382  *
383  * see: becomeDC_ldap1_server_object_2()
384  * 
385  * Request:
386  *      basedn: CN=<new_dc_netbios_name>,CN=Computers,<domain_partition>
387  *      scope:  base
388  *      filter: (objectClass=*)
389  *      attrs:  serverReferenceBL
390  *      typesOnly: TRUE!!!
391  * Result:
392  *      CN=<new_dc_netbios_name>,CN=Computers,<domain_partition>
393  */
394
395 /*
396  * LDAP add 1st LDAP connection:
397  * 
398  * see: becomeDC_ldap1_server_object_add()
399  *
400  * Request:
401  *      CN=<new_dc_netbios_name>,CN=Computers,<domain_partition>
402  *      objectClass:    server
403  *      systemFlags:    50000000 <0x2FAF080>
404  *      serverReference:CN=<new_dc_netbios_name>,CN=Computers,<domain_partition>
405  * Result:
406  *      <success>
407  */
408
409 /*
410  * LDAP search 1st LDAP connection:
411  *
412  * not implemented, maybe we can add that later
413  *
414  * Request:
415  *      basedn: CN=NTDS Settings,CN=<new_dc_netbios_name>,CN=Servers,CN=<new_dc_site_name>,CN=Sites,CN=Configuration,<domain_partition>
416  *      scope:  base
417  *      filter: (objectClass=*)
418  *      attrs:
419  * Result:
420  *      <noSuchObject>
421  *      <matchedDN:CN=<new_dc_netbios_name>,CN=Servers,CN=<new_dc_site_name>,CN=Sites,CN=Configuration,<domain_partition>>
422  */
423
424 /*
425  * LDAP search 1st LDAP connection:
426  *
427  * not implemented because it gives no new information
428  * 
429  * Request:
430  *      basedn: CN=Partitions,CN=Configuration,<domain_partition>
431  *      scope:  sub
432  *      filter: (nCName=<domain_partition>)
433  *      attrs:  nCName
434  *              dnsRoot
435  *      controls: LDAP_SERVER_EXTENDED_DN_OID:critical=false
436  * Result:
437  *      <GUID=<hex_guid>>;CN=<domain_netbios_name>,CN=Partitions,<domain_partition>>
438  *              nCName:         <GUID=<hex_guid>>;<SID=<hex_sid>>;<domain_partition>>
439  *              dnsRoot:        <domain_dns_name>
440  */
441
442 /*
443  * LDAP modify 1st LDAP connection:
444  *
445  * see: becomeDC_ldap1_server_object_modify()
446  * 
447  * Request (add):
448  *      CN=<new_dc_netbios_name>,CN=Servers,CN=<new_dc_site_name>,CN=Sites,CN=Configuration,<domain_partition>>
449  *      serverReference:CN=<new_dc_netbios_name>,CN=Computers,<domain_partition>
450  * Result:
451  *      <attributeOrValueExist>
452  */
453
454 /*
455  * LDAP modify 1st LDAP connection:
456  *
457  * see: becomeDC_ldap1_server_object_modify()
458  *
459  * Request (replace):
460  *      CN=<new_dc_netbios_name>,CN=Servers,CN=<new_dc_site_name>,CN=Sites,CN=Configuration,<domain_partition>>
461  *      serverReference:CN=<new_dc_netbios_name>,CN=Computers,<domain_partition>
462  * Result:
463  *      <success>
464  */
465
466 /*
467  * Open 1st DRSUAPI connection to the DC using admin credentials
468  * DsBind with DRSUAPI_DS_BIND_GUID_W2K3 ("6afab99c-6e26-464a-975f-f58f105218bc")
469  * (w2k3 does 2 DsBind() calls here..., where is first is unused and contains garbage at the end)
470  *
471  * see: becomeDC_drsuapi_connect_send(), becomeDC_drsuapi1_connect_recv(),
472  *      becomeDC_drsuapi_bind_send(), becomeDC_drsuapi_bind_recv() and becomeDC_drsuapi1_bind_recv()
473  */
474
475 /*
476  * DsAddEntry to create the CN=NTDS Settings,CN=<machine_name>,CN=Servers,CN=Default-First-Site-Name, ...
477  * on the 1st DRSUAPI connection
478  *
479  * see: becomeDC_drsuapi1_add_entry_send() and becomeDC_drsuapi1_add_entry_recv()
480  */
481
482 /***************************************************************
483  * Add this stage we call the prepare_db() callback function
484  * of the caller, to see if he wants us to continue
485  *
486  * see: becomeDC_prepare_db()
487  ***************************************************************/
488
489 /*
490  * Open 2nd and 3rd DRSUAPI connection to the DC using admin credentials
491  * - a DsBind with DRSUAPI_DS_BIND_GUID_W2K3 ("6afab99c-6e26-464a-975f-f58f105218bc")
492  *   on the 2nd connection
493  *
494  * see: becomeDC_drsuapi_connect_send(), becomeDC_drsuapi2_connect_recv(),
495  *      becomeDC_drsuapi_bind_send(), becomeDC_drsuapi_bind_recv(), becomeDC_drsuapi2_bind_recv()
496  *      and becomeDC_drsuapi3_connect_recv()
497  */
498
499 /*
500  * replicate CN=Schema,CN=Configuration,...
501  * on the 3rd DRSUAPI connection and the bind_handle from the 2nd connection
502  *
503  * see: becomeDC_drsuapi_pull_partition_send(), becomeDC_drsuapi_pull_partition_recv(),
504  *      becomeDC_drsuapi3_pull_schema_send() and becomeDC_drsuapi3_pull_schema_recv()
505  *
506  ***************************************************************
507  * Add this stage we call the schema_chunk() callback function
508  * for each replication message
509  ***************************************************************/
510
511 /*
512  * replicate CN=Configuration,...
513  * on the 3rd DRSUAPI connection and the bind_handle from the 2nd connection
514  *
515  * see: becomeDC_drsuapi_pull_partition_send(), becomeDC_drsuapi_pull_partition_recv(),
516  *      becomeDC_drsuapi3_pull_config_send() and becomeDC_drsuapi3_pull_config_recv()
517  *
518  ***************************************************************
519  * Add this stage we call the config_chunk() callback function
520  * for each replication message
521  ***************************************************************/
522
523 /*
524  * LDAP unbind on the 1st LDAP connection
525  *
526  * not implemented, because it's not needed...
527  */
528
529 /*
530  * Open 2nd LDAP connection to the DC using admin credentials
531  *
532  * see: becomeDC_connect_ldap2() and becomeDC_ldap_connect()
533  */
534
535 /*
536  * LDAP search 2nd LDAP connection:
537  * 
538  * not implemented because it gives no new information
539  * same as becomeDC_ldap1_computer_object()
540  *
541  * Request:
542  *      basedn: <domain_partition>
543  *      scope:  sub
544  *      filter: (&(|(objectClass=user)(objectClass=computer))(sAMAccountName=<new_dc_account_name>))
545  *      attrs:  distinguishedName
546  *              userAccountControl
547  * Result:
548  *      CN=<new_dc_netbios_name>,CN=Computers,<domain_partition>
549  *              distinguishedName:      CN=<new_dc_netbios_name>,CN=Computers,<domain_partition>
550  *              userAccoountControl:    4096 <0x00001000>
551  */
552
553 /*
554  * LDAP search 2nd LDAP connection:
555  * 
556  * not implemented because it gives no new information
557  * same as becomeDC_ldap1_computer_object()
558  *
559  * Request:
560  *      basedn: CN=<new_dc_netbios_name>,CN=Computers,<domain_partition>
561  *      scope:  base
562  *      filter: (objectClass=*)
563  *      attrs:  userAccountControl
564  * Result:
565  *      CN=<new_dc_netbios_name>,CN=Computers,<domain_partition>
566  *              userAccoountControl:    4096 <0x00001000>
567  */
568
569 /*
570  * LDAP modify 2nd LDAP connection:
571  *
572  * see: becomeDC_ldap2_modify_computer()
573  *
574  * Request (replace):
575  *      CN=<new_dc_netbios_name>,CN=Computers,<domain_partition>
576  *      userAccoountControl:    532480 <0x82000>
577  * Result:
578  *      <success>
579  */
580
581 /*
582  * LDAP search 2nd LDAP connection:
583  *
584  * see: becomeDC_ldap2_move_computer()
585  * 
586  * Request:
587  *      basedn: <WKGUID=2fbac1870ade11d297c400c04fd8d5cd,<domain_partition>>
588  *      scope:  base
589  *      filter: (objectClass=*)
590  *      attrs:  1.1
591  * Result:
592  *      CN=Domain Controllers,<domain_partition>
593  */
594
595 /*
596  * LDAP search 2nd LDAP connection:
597  *
598  * not implemented because it gives no new information
599  * 
600  * Request:
601  *      basedn: CN=Domain Controllers,<domain_partition>
602  *      scope:  base
603  *      filter: (objectClass=*)
604  *      attrs:  distinguishedName
605  * Result:
606  *      CN=Domain Controller,<domain_partition>
607  *              distinguishedName:      CN=Domain Controllers,<domain_partition>
608  */
609
610 /*
611  * LDAP modifyRDN 2nd LDAP connection:
612  *
613  * see: becomeDC_ldap2_move_computer()
614  * 
615  * Request:
616  *      entry:          CN=<new_dc_netbios_name>,CN=Computers,<domain_partition>
617  *      newrdn:         CN=<new_dc_netbios_name>
618  *      deleteoldrdn:   TRUE
619  *      newparent:      CN=Domain Controllers,<domain_partition>
620  * Result:
621  *      <success>
622  */
623
624 /*
625  * LDAP unbind on the 2nd LDAP connection
626  *
627  * not implemented, because it's not needed...
628  */
629
630 /*
631  * replicate Domain Partition
632  * on the 3rd DRSUAPI connection and the bind_handle from the 2nd connection
633  *
634  * see: becomeDC_drsuapi_pull_partition_send(), becomeDC_drsuapi_pull_partition_recv(),
635  *      becomeDC_drsuapi3_pull_domain_send() and becomeDC_drsuapi3_pull_domain_recv()
636  *
637  ***************************************************************
638  * Add this stage we call the domain_chunk() callback function
639  * for each replication message
640  ***************************************************************/
641
642 /* call DsReplicaUpdateRefs() for all partitions like this:
643  *     req1: struct drsuapi_DsReplicaUpdateRefsRequest1
644  *
645  *                 naming_context: struct drsuapi_DsReplicaObjectIdentifier
646  *                     __ndr_size               : 0x000000ae (174)
647  *                     __ndr_size_sid           : 0x00000000 (0)
648  *                     guid                     : 00000000-0000-0000-0000-000000000000
649  *                     sid                      : S-0-0
650  *                     dn                       : 'CN=Schema,CN=Configuration,DC=w2k3,DC=vmnet1,DC=vm,DC=base'
651  *
652  *                 dest_dsa_dns_name        : '4a0df188-a0b8-47ea-bbe5-e614723f16dd._msdcs.w2k3.vmnet1.vm.base'
653  *           dest_dsa_guid            : 4a0df188-a0b8-47ea-bbe5-e614723f16dd
654  *           options                  : 0x0000001c (28)
655  *                 0: DRSUAPI_DS_REPLICA_UPDATE_ASYNCHRONOUS_OPERATION
656  *                 0: DRSUAPI_DS_REPLICA_UPDATE_WRITEABLE
657  *                 1: DRSUAPI_DS_REPLICA_UPDATE_ADD_REFERENCE
658  *                 1: DRSUAPI_DS_REPLICA_UPDATE_DELETE_REFERENCE
659  *                 1: DRSUAPI_DS_REPLICA_UPDATE_0x00000010
660  *
661  * 4a0df188-a0b8-47ea-bbe5-e614723f16dd is the objectGUID the DsAddEntry() returned for the
662  * CN=NTDS Settings,CN=<machine_name>,CN=Servers,CN=Default-First-Site-Name, ...
663  * on the 2nd!!! DRSUAPI connection
664  *
665  * see: becomeDC_drsuapi_update_refs_send(), becomeDC_drsuapi2_update_refs_schema_recv(),
666  *      becomeDC_drsuapi2_update_refs_config_recv() and becomeDC_drsuapi2_update_refs_domain_recv()
667  */
668
669 /*
670  * Windows does opens the 4th and 5th DRSUAPI connection...
671  * and does a DsBind() with the objectGUID from DsAddEntry() as bind_guid
672  * on the 4th connection
673  *
674  * and then 2 full replications of the domain partition on the 5th connection
675  * with the bind_handle from the 4th connection
676  *
677  * not implemented because it gives no new information
678  */
679
680 struct libnet_BecomeDC_state {
681         struct composite_context *creq;
682
683         struct libnet_context *libnet;
684
685         struct dom_sid zero_sid;
686
687         struct {
688                 struct cldap_socket *sock;
689                 struct cldap_netlogon io;
690                 struct nbt_cldap_netlogon_5 netlogon5;
691         } cldap;
692
693         struct becomeDC_ldap {
694                 struct ldb_context *ldb;
695                 const struct ldb_message *rootdse;
696         } ldap1, ldap2;
697
698         struct becomeDC_drsuapi {
699                 struct libnet_BecomeDC_state *s;
700                 struct dcerpc_binding *binding;
701                 struct dcerpc_pipe *pipe;
702                 DATA_BLOB gensec_skey;
703                 struct drsuapi_DsBind bind_r;
704                 struct GUID bind_guid;
705                 struct drsuapi_DsBindInfoCtr bind_info_ctr;
706                 struct drsuapi_DsBindInfo28 local_info28;
707                 struct drsuapi_DsBindInfo28 remote_info28;
708                 struct policy_handle bind_handle;
709         } drsuapi1, drsuapi2, drsuapi3;
710
711         struct libnet_BecomeDC_Domain domain;
712         struct libnet_BecomeDC_Forest forest;
713         struct libnet_BecomeDC_SourceDSA source_dsa;
714         struct libnet_BecomeDC_DestDSA dest_dsa;
715
716         struct libnet_BecomeDC_Partition schema_part, config_part, domain_part;
717
718         struct becomeDC_fsmo {
719                 const char *dns_name;
720                 const char *server_dn_str;
721                 const char *ntds_dn_str;
722                 struct GUID ntds_guid;
723         } infrastructure_fsmo;
724
725         struct becomeDC_fsmo rid_manager_fsmo;
726
727         struct libnet_BecomeDC_CheckOptions _co;
728         struct libnet_BecomeDC_PrepareDB _pp;
729         struct libnet_BecomeDC_StoreChunk _sc;
730         struct libnet_BecomeDC_Callbacks callbacks;
731 };
732
733 static void becomeDC_recv_cldap(struct cldap_request *req);
734
735 static void becomeDC_send_cldap(struct libnet_BecomeDC_state *s)
736 {
737         struct composite_context *c = s->creq;
738         struct cldap_request *req;
739
740         s->cldap.io.in.dest_address     = s->source_dsa.address;
741         s->cldap.io.in.realm            = s->domain.dns_name;
742         s->cldap.io.in.host             = s->dest_dsa.netbios_name;
743         s->cldap.io.in.user             = NULL;
744         s->cldap.io.in.domain_guid      = NULL;
745         s->cldap.io.in.domain_sid       = NULL;
746         s->cldap.io.in.acct_control     = -1;
747         s->cldap.io.in.version          = 6;
748
749         s->cldap.sock = cldap_socket_init(s, s->libnet->event_ctx);
750         if (composite_nomem(s->cldap.sock, c)) return;
751
752         req = cldap_netlogon_send(s->cldap.sock, &s->cldap.io);
753         if (composite_nomem(req, c)) return;
754         req->async.fn           = becomeDC_recv_cldap;
755         req->async.private      = s;
756 }
757
758 static void becomeDC_connect_ldap1(struct libnet_BecomeDC_state *s);
759
760 static void becomeDC_recv_cldap(struct cldap_request *req)
761 {
762         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private,
763                                           struct libnet_BecomeDC_state);
764         struct composite_context *c = s->creq;
765
766         c->status = cldap_netlogon_recv(req, s, &s->cldap.io);
767         if (!composite_is_ok(c)) return;
768
769         s->cldap.netlogon5 = s->cldap.io.out.netlogon.logon5;
770
771         s->domain.dns_name              = s->cldap.netlogon5.dns_domain;
772         s->domain.netbios_name          = s->cldap.netlogon5.domain;
773         s->domain.guid                  = s->cldap.netlogon5.domain_uuid;
774
775         s->forest.dns_name              = s->cldap.netlogon5.forest;
776
777         s->source_dsa.dns_name          = s->cldap.netlogon5.pdc_dns_name;
778         s->source_dsa.netbios_name      = s->cldap.netlogon5.pdc_name;
779         s->source_dsa.site_name         = s->cldap.netlogon5.server_site;
780
781         s->dest_dsa.site_name           = s->cldap.netlogon5.client_site;
782
783         becomeDC_connect_ldap1(s);
784 }
785
786 static NTSTATUS becomeDC_ldap_connect(struct libnet_BecomeDC_state *s, struct becomeDC_ldap *ldap)
787 {
788         char *url;
789
790         url = talloc_asprintf(s, "ldap://%s/", s->source_dsa.dns_name);
791         NT_STATUS_HAVE_NO_MEMORY(url);
792
793         ldap->ldb = ldb_wrap_connect(s, global_loadparm, url,
794                                      NULL,
795                                      s->libnet->cred,
796                                      0, NULL);
797         talloc_free(url);
798         if (ldap->ldb == NULL) {
799                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
800         }
801
802         return NT_STATUS_OK;
803 }
804
805 static NTSTATUS becomeDC_ldap1_rootdse(struct libnet_BecomeDC_state *s)
806 {
807         int ret;
808         struct ldb_result *r;
809         struct ldb_dn *basedn;
810         static const char *attrs[] = {
811                 "*",
812                 NULL
813         };
814
815         basedn = ldb_dn_new(s, s->ldap1.ldb, NULL);
816         NT_STATUS_HAVE_NO_MEMORY(basedn);
817
818         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, 
819                          "(objectClass=*)", attrs, &r);
820         talloc_free(basedn);
821         if (ret != LDB_SUCCESS) {
822                 return NT_STATUS_LDAP(ret);
823         } else if (r->count != 1) {
824                 talloc_free(r);
825                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
826         }
827         talloc_steal(s, r);
828
829         s->ldap1.rootdse = r->msgs[0];
830
831         s->domain.dn_str        = ldb_msg_find_attr_as_string(s->ldap1.rootdse, "defaultNamingContext", NULL);
832         if (!s->domain.dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
833
834         s->forest.root_dn_str   = ldb_msg_find_attr_as_string(s->ldap1.rootdse, "rootDomainNamingContext", NULL);
835         if (!s->forest.root_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
836         s->forest.config_dn_str = ldb_msg_find_attr_as_string(s->ldap1.rootdse, "configurationNamingContext", NULL);
837         if (!s->forest.config_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
838         s->forest.schema_dn_str = ldb_msg_find_attr_as_string(s->ldap1.rootdse, "schemaNamingContext", NULL);
839         if (!s->forest.schema_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
840
841         s->source_dsa.server_dn_str     = ldb_msg_find_attr_as_string(s->ldap1.rootdse, "serverName", NULL);
842         if (!s->source_dsa.server_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
843         s->source_dsa.ntds_dn_str       = ldb_msg_find_attr_as_string(s->ldap1.rootdse, "dsServiceName", NULL);
844         if (!s->source_dsa.ntds_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
845
846         return NT_STATUS_OK;
847 }
848
849 static NTSTATUS becomeDC_ldap1_crossref_behavior_version(struct libnet_BecomeDC_state *s)
850 {
851         int ret;
852         struct ldb_result *r;
853         struct ldb_dn *basedn;
854         static const char *attrs[] = {
855                 "msDs-Behavior-Version",
856                 NULL
857         };
858
859         basedn = ldb_dn_new(s, s->ldap1.ldb, s->forest.config_dn_str);
860         NT_STATUS_HAVE_NO_MEMORY(basedn);
861
862         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_ONELEVEL,
863                          "(cn=Partitions)", attrs, &r);
864         talloc_free(basedn);
865         if (ret != LDB_SUCCESS) {
866                 return NT_STATUS_LDAP(ret);
867         } else if (r->count != 1) {
868                 talloc_free(r);
869                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
870         }
871
872         s->forest.crossref_behavior_version = ldb_msg_find_attr_as_uint(r->msgs[0], "msDs-Behavior-Version", 0);
873
874         talloc_free(r);
875         return NT_STATUS_OK;
876 }
877
878 static NTSTATUS becomeDC_ldap1_domain_behavior_version(struct libnet_BecomeDC_state *s)
879 {
880         int ret;
881         struct ldb_result *r;
882         struct ldb_dn *basedn;
883         static const char *attrs[] = {
884                 "msDs-Behavior-Version",
885                 NULL
886         };
887
888         basedn = ldb_dn_new(s, s->ldap1.ldb, s->domain.dn_str);
889         NT_STATUS_HAVE_NO_MEMORY(basedn);
890
891         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE,
892                          "(objectClass=*)", attrs, &r);
893         talloc_free(basedn);
894         if (ret != LDB_SUCCESS) {
895                 return NT_STATUS_LDAP(ret);
896         } else if (r->count != 1) {
897                 talloc_free(r);
898                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
899         }
900
901         s->domain.behavior_version = ldb_msg_find_attr_as_uint(r->msgs[0], "msDs-Behavior-Version", 0);
902
903         talloc_free(r);
904         return NT_STATUS_OK;
905 }
906
907 static NTSTATUS becomeDC_ldap1_schema_object_version(struct libnet_BecomeDC_state *s)
908 {
909         int ret;
910         struct ldb_result *r;
911         struct ldb_dn *basedn;
912         static const char *attrs[] = {
913                 "objectVersion",
914                 NULL
915         };
916
917         basedn = ldb_dn_new(s, s->ldap1.ldb, s->forest.schema_dn_str);
918         NT_STATUS_HAVE_NO_MEMORY(basedn);
919
920         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE,
921                          "(objectClass=*)", attrs, &r);
922         talloc_free(basedn);
923         if (ret != LDB_SUCCESS) {
924                 return NT_STATUS_LDAP(ret);
925         } else if (r->count != 1) {
926                 talloc_free(r);
927                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
928         }
929
930         s->forest.schema_object_version = ldb_msg_find_attr_as_uint(r->msgs[0], "objectVersion", 0);
931
932         talloc_free(r);
933         return NT_STATUS_OK;
934 }
935
936 static NTSTATUS becomeDC_ldap1_w2k3_update_revision(struct libnet_BecomeDC_state *s)
937 {
938         int ret;
939         struct ldb_result *r;
940         struct ldb_dn *basedn;
941         static const char *attrs[] = {
942                 "revision",
943                 NULL
944         };
945
946         basedn = ldb_dn_new_fmt(s, s->ldap1.ldb, "CN=Windows2003Update,CN=DomainUpdates,CN=System,%s",
947                                 s->domain.dn_str);
948         NT_STATUS_HAVE_NO_MEMORY(basedn);
949
950         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE,
951                          "(objectClass=*)", attrs, &r);
952         talloc_free(basedn);
953         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
954                 /* w2k doesn't have this object */
955                 s->domain.w2k3_update_revision = 0;
956                 return NT_STATUS_OK;
957         } else if (ret != LDB_SUCCESS) {
958                 return NT_STATUS_LDAP(ret);
959         } else if (r->count != 1) {
960                 talloc_free(r);
961                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
962         }
963
964         s->domain.w2k3_update_revision = ldb_msg_find_attr_as_uint(r->msgs[0], "revision", 0);
965
966         talloc_free(r);
967         return NT_STATUS_OK;
968 }
969
970 static NTSTATUS becomeDC_ldap1_infrastructure_fsmo(struct libnet_BecomeDC_state *s)
971 {
972         int ret;
973         struct ldb_result *r;
974         struct ldb_dn *basedn;
975         struct ldb_dn *ntds_dn;
976         struct ldb_dn *server_dn;
977         static const char *_1_1_attrs[] = {
978                 "1.1",
979                 NULL
980         };
981         static const char *fsmo_attrs[] = {
982                 "fSMORoleOwner",
983                 NULL
984         };
985         static const char *dns_attrs[] = {
986                 "dnsHostName",
987                 NULL
988         };
989         static const char *guid_attrs[] = {
990                 "objectGUID",
991                 NULL
992         };
993
994         basedn = ldb_dn_new_fmt(s, s->ldap1.ldb, "<WKGUID=2fbac1870ade11d297c400c04fd8d5cd,%s>",
995                                 s->domain.dn_str);
996         NT_STATUS_HAVE_NO_MEMORY(basedn);
997
998         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE,
999                          "(objectClass=*)", _1_1_attrs, &r);
1000         talloc_free(basedn);
1001         if (ret != LDB_SUCCESS) {
1002                 return NT_STATUS_LDAP(ret);
1003         } else if (r->count != 1) {
1004                 talloc_free(r);
1005                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1006         }
1007
1008         basedn = talloc_steal(s, r->msgs[0]->dn);
1009         talloc_free(r);
1010
1011         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE,
1012                          "(objectClass=*)", fsmo_attrs, &r);
1013         talloc_free(basedn);
1014         if (ret != LDB_SUCCESS) {
1015                 return NT_STATUS_LDAP(ret);
1016         } else if (r->count != 1) {
1017                 talloc_free(r);
1018                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1019         }
1020
1021         s->infrastructure_fsmo.ntds_dn_str      = samdb_result_string(r->msgs[0], "fSMORoleOwner", NULL);
1022         if (!s->infrastructure_fsmo.ntds_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
1023         talloc_steal(s, s->infrastructure_fsmo.ntds_dn_str);
1024
1025         talloc_free(r);
1026
1027         ntds_dn = ldb_dn_new(s, s->ldap1.ldb, s->infrastructure_fsmo.ntds_dn_str);
1028         NT_STATUS_HAVE_NO_MEMORY(ntds_dn);
1029
1030         server_dn = ldb_dn_get_parent(s, ntds_dn);
1031         NT_STATUS_HAVE_NO_MEMORY(server_dn);
1032
1033         s->infrastructure_fsmo.server_dn_str = ldb_dn_alloc_linearized(s, server_dn);
1034         NT_STATUS_HAVE_NO_MEMORY(s->infrastructure_fsmo.server_dn_str);
1035
1036         ret = ldb_search(s->ldap1.ldb, server_dn, LDB_SCOPE_BASE,
1037                          "(objectClass=*)", dns_attrs, &r);
1038         if (ret != LDB_SUCCESS) {
1039                 return NT_STATUS_LDAP(ret);
1040         } else if (r->count != 1) {
1041                 talloc_free(r);
1042                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1043         }
1044
1045         s->infrastructure_fsmo.dns_name = samdb_result_string(r->msgs[0], "dnsHostName", NULL);
1046         if (!s->infrastructure_fsmo.dns_name) return NT_STATUS_INVALID_NETWORK_RESPONSE;
1047         talloc_steal(s, s->infrastructure_fsmo.dns_name);
1048
1049         talloc_free(r);
1050
1051         ret = ldb_search(s->ldap1.ldb, ntds_dn, LDB_SCOPE_BASE,
1052                          "(objectClass=*)", guid_attrs, &r);
1053         if (ret != LDB_SUCCESS) {
1054                 return NT_STATUS_LDAP(ret);
1055         } else if (r->count != 1) {
1056                 talloc_free(r);
1057                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1058         }
1059
1060         s->infrastructure_fsmo.ntds_guid = samdb_result_guid(r->msgs[0], "objectGUID");
1061
1062         talloc_free(r);
1063
1064         return NT_STATUS_OK;
1065 }
1066
1067 static NTSTATUS becomeDC_ldap1_rid_manager_fsmo(struct libnet_BecomeDC_state *s)
1068 {
1069         int ret;
1070         struct ldb_result *r;
1071         struct ldb_dn *basedn;
1072         const char *reference_dn_str;
1073         struct ldb_dn *ntds_dn;
1074         struct ldb_dn *server_dn;
1075         static const char *rid_attrs[] = {
1076                 "rIDManagerReference",
1077                 NULL
1078         };
1079         static const char *fsmo_attrs[] = {
1080                 "fSMORoleOwner",
1081                 NULL
1082         };
1083         static const char *dns_attrs[] = {
1084                 "dnsHostName",
1085                 NULL
1086         };
1087         static const char *guid_attrs[] = {
1088                 "objectGUID",
1089                 NULL
1090         };
1091
1092         basedn = ldb_dn_new(s, s->ldap1.ldb, s->domain.dn_str);
1093         NT_STATUS_HAVE_NO_MEMORY(basedn);
1094
1095         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE,
1096                          "(objectClass=*)", rid_attrs, &r);
1097         talloc_free(basedn);
1098         if (ret != LDB_SUCCESS) {
1099                 return NT_STATUS_LDAP(ret);
1100         } else if (r->count != 1) {
1101                 talloc_free(r);
1102                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1103         }
1104
1105         reference_dn_str        = samdb_result_string(r->msgs[0], "rIDManagerReference", NULL);
1106         if (!reference_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
1107
1108         basedn = ldb_dn_new(s, s->ldap1.ldb, reference_dn_str);
1109         NT_STATUS_HAVE_NO_MEMORY(basedn);
1110
1111         talloc_free(r);
1112
1113         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE,
1114                          "(objectClass=*)", fsmo_attrs, &r);
1115         talloc_free(basedn);
1116         if (ret != LDB_SUCCESS) {
1117                 return NT_STATUS_LDAP(ret);
1118         } else if (r->count != 1) {
1119                 talloc_free(r);
1120                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1121         }
1122
1123         s->rid_manager_fsmo.ntds_dn_str = samdb_result_string(r->msgs[0], "fSMORoleOwner", NULL);
1124         if (!s->rid_manager_fsmo.ntds_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
1125         talloc_steal(s, s->rid_manager_fsmo.ntds_dn_str);
1126
1127         talloc_free(r);
1128
1129         ntds_dn = ldb_dn_new(s, s->ldap1.ldb, s->rid_manager_fsmo.ntds_dn_str);
1130         NT_STATUS_HAVE_NO_MEMORY(ntds_dn);
1131
1132         server_dn = ldb_dn_get_parent(s, ntds_dn);
1133         NT_STATUS_HAVE_NO_MEMORY(server_dn);
1134
1135         s->rid_manager_fsmo.server_dn_str = ldb_dn_alloc_linearized(s, server_dn);
1136         NT_STATUS_HAVE_NO_MEMORY(s->rid_manager_fsmo.server_dn_str);
1137
1138         ret = ldb_search(s->ldap1.ldb, server_dn, LDB_SCOPE_BASE,
1139                          "(objectClass=*)", dns_attrs, &r);
1140         if (ret != LDB_SUCCESS) {
1141                 return NT_STATUS_LDAP(ret);
1142         } else if (r->count != 1) {
1143                 talloc_free(r);
1144                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1145         }
1146
1147         s->rid_manager_fsmo.dns_name    = samdb_result_string(r->msgs[0], "dnsHostName", NULL);
1148         if (!s->rid_manager_fsmo.dns_name) return NT_STATUS_INVALID_NETWORK_RESPONSE;
1149         talloc_steal(s, s->rid_manager_fsmo.dns_name);
1150
1151         talloc_free(r);
1152
1153         ret = ldb_search(s->ldap1.ldb, ntds_dn, LDB_SCOPE_BASE,
1154                          "(objectClass=*)", guid_attrs, &r);
1155         if (ret != LDB_SUCCESS) {
1156                 return NT_STATUS_LDAP(ret);
1157         } else if (r->count != 1) {
1158                 talloc_free(r);
1159                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1160         }
1161
1162         s->rid_manager_fsmo.ntds_guid = samdb_result_guid(r->msgs[0], "objectGUID");
1163
1164         talloc_free(r);
1165
1166         return NT_STATUS_OK;
1167 }
1168
1169 static NTSTATUS becomeDC_ldap1_site_object(struct libnet_BecomeDC_state *s)
1170 {
1171         int ret;
1172         struct ldb_result *r;
1173         struct ldb_dn *basedn;
1174
1175         basedn = ldb_dn_new_fmt(s, s->ldap1.ldb, "CN=%s,CN=Sites,%s",
1176                                 s->dest_dsa.site_name,
1177                                 s->forest.config_dn_str);
1178         NT_STATUS_HAVE_NO_MEMORY(basedn);
1179
1180         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, 
1181                          "(objectClass=*)", NULL, &r);
1182         talloc_free(basedn);
1183         if (ret != LDB_SUCCESS) {
1184                 return NT_STATUS_LDAP(ret);
1185         } else if (r->count != 1) {
1186                 talloc_free(r);
1187                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1188         }
1189
1190         s->dest_dsa.site_guid = samdb_result_guid(r->msgs[0], "objectGUID");
1191
1192         talloc_free(r);
1193         return NT_STATUS_OK;
1194 }
1195
1196 static NTSTATUS becomeDC_check_options(struct libnet_BecomeDC_state *s)
1197 {
1198         if (!s->callbacks.check_options) return NT_STATUS_OK;
1199
1200         s->_co.domain           = &s->domain;
1201         s->_co.forest           = &s->forest;
1202         s->_co.source_dsa       = &s->source_dsa;
1203
1204         return s->callbacks.check_options(s->callbacks.private_data, &s->_co);
1205 }
1206
1207 static NTSTATUS becomeDC_ldap1_computer_object(struct libnet_BecomeDC_state *s)
1208 {
1209         int ret;
1210         struct ldb_result *r;
1211         struct ldb_dn *basedn;
1212         char *filter;
1213         static const char *attrs[] = {
1214                 "distinguishedName",
1215                 "userAccountControl",
1216                 NULL
1217         };
1218
1219         basedn = ldb_dn_new(s, s->ldap1.ldb, s->domain.dn_str);
1220         NT_STATUS_HAVE_NO_MEMORY(basedn);
1221
1222         filter = talloc_asprintf(basedn, "(&(|(objectClass=user)(objectClass=computer))(sAMAccountName=%s$))",
1223                                  s->dest_dsa.netbios_name);
1224         NT_STATUS_HAVE_NO_MEMORY(filter);
1225
1226         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_SUBTREE, 
1227                          filter, attrs, &r);
1228         talloc_free(basedn);
1229         if (ret != LDB_SUCCESS) {
1230                 return NT_STATUS_LDAP(ret);
1231         } else if (r->count != 1) {
1232                 talloc_free(r);
1233                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1234         }
1235
1236         s->dest_dsa.computer_dn_str     = samdb_result_string(r->msgs[0], "distinguishedName", NULL);
1237         if (!s->dest_dsa.computer_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
1238         talloc_steal(s, s->dest_dsa.computer_dn_str);
1239
1240         s->dest_dsa.user_account_control = samdb_result_uint(r->msgs[0], "userAccountControl", 0);
1241
1242         talloc_free(r);
1243         return NT_STATUS_OK;
1244 }
1245
1246 static NTSTATUS becomeDC_ldap1_server_object_1(struct libnet_BecomeDC_state *s)
1247 {
1248         int ret;
1249         struct ldb_result *r;
1250         struct ldb_dn *basedn;
1251         const char *server_reference_dn_str;
1252         struct ldb_dn *server_reference_dn;
1253         struct ldb_dn *computer_dn;
1254
1255         basedn = ldb_dn_new_fmt(s, s->ldap1.ldb, "CN=%s,CN=Servers,CN=%s,CN=Sites,%s",
1256                                 s->dest_dsa.netbios_name,
1257                                 s->dest_dsa.site_name,
1258                                 s->forest.config_dn_str);
1259         NT_STATUS_HAVE_NO_MEMORY(basedn);
1260
1261         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, 
1262                          "(objectClass=*)", NULL, &r);
1263         talloc_free(basedn);
1264         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1265                 /* if the object doesn't exist, we'll create it later */
1266                 return NT_STATUS_OK;
1267         } else if (ret != LDB_SUCCESS) {
1268                 return NT_STATUS_LDAP(ret);
1269         } else if (r->count != 1) {
1270                 talloc_free(r);
1271                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1272         }
1273
1274         server_reference_dn_str = samdb_result_string(r->msgs[0], "serverReference", NULL);
1275         if (server_reference_dn_str) {
1276                 server_reference_dn     = ldb_dn_new(r, s->ldap1.ldb, server_reference_dn_str);
1277                 NT_STATUS_HAVE_NO_MEMORY(server_reference_dn);
1278
1279                 computer_dn             = ldb_dn_new(r, s->ldap1.ldb, s->dest_dsa.computer_dn_str);
1280                 NT_STATUS_HAVE_NO_MEMORY(computer_dn);
1281
1282                 /*
1283                  * if the server object belongs to another DC in another domain in the forest,
1284                  * we should not touch this object!
1285                  */
1286                 if (ldb_dn_compare(computer_dn, server_reference_dn) != 0) {
1287                         talloc_free(r);
1288                         return NT_STATUS_OBJECT_NAME_COLLISION;
1289                 }
1290         }
1291
1292         /* if the server object is already for the dest_dsa, then we don't need to create it */
1293         s->dest_dsa.server_dn_str       = samdb_result_string(r->msgs[0], "distinguishedName", NULL);
1294         if (!s->dest_dsa.server_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
1295         talloc_steal(s, s->dest_dsa.server_dn_str);
1296
1297         talloc_free(r);
1298         return NT_STATUS_OK;
1299 }
1300
1301 static NTSTATUS becomeDC_ldap1_server_object_2(struct libnet_BecomeDC_state *s)
1302 {
1303         int ret;
1304         struct ldb_result *r;
1305         struct ldb_dn *basedn;
1306         const char *server_reference_bl_dn_str;
1307         static const char *attrs[] = {
1308                 "serverReferenceBL",
1309                 NULL
1310         };
1311
1312         /* if the server_dn_str has a valid value, we skip this lookup */
1313         if (s->dest_dsa.server_dn_str) return NT_STATUS_OK;
1314
1315         basedn = ldb_dn_new(s, s->ldap1.ldb, s->dest_dsa.computer_dn_str);
1316         NT_STATUS_HAVE_NO_MEMORY(basedn);
1317
1318         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, 
1319                          "(objectClass=*)", attrs, &r);
1320         talloc_free(basedn);
1321         if (ret != LDB_SUCCESS) {
1322                 return NT_STATUS_LDAP(ret);
1323         } else if (r->count != 1) {
1324                 talloc_free(r);
1325                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1326         }
1327
1328         server_reference_bl_dn_str = samdb_result_string(r->msgs[0], "serverReferenceBL", NULL);
1329         if (!server_reference_bl_dn_str) {
1330                 /* if no back link is present, we're done for this function */
1331                 talloc_free(r);
1332                 return NT_STATUS_OK;
1333         }
1334
1335         /* if the server object is already for the dest_dsa, then we don't need to create it */
1336         s->dest_dsa.server_dn_str       = samdb_result_string(r->msgs[0], "serverReferenceBL", NULL);
1337         if (s->dest_dsa.server_dn_str) {
1338                 /* if a back link is present, we know that the server object is present */
1339                 talloc_steal(s, s->dest_dsa.server_dn_str);
1340         }
1341
1342         talloc_free(r);
1343         return NT_STATUS_OK;
1344 }
1345
1346 static NTSTATUS becomeDC_ldap1_server_object_add(struct libnet_BecomeDC_state *s)
1347 {
1348         int ret;
1349         struct ldb_message *msg;
1350         char *server_dn_str;
1351
1352         /* if the server_dn_str has a valid value, we skip this lookup */
1353         if (s->dest_dsa.server_dn_str) return NT_STATUS_OK;
1354
1355         msg = ldb_msg_new(s);
1356         NT_STATUS_HAVE_NO_MEMORY(msg);
1357
1358         msg->dn = ldb_dn_new_fmt(msg, s->ldap1.ldb, "CN=%s,CN=Servers,CN=%s,CN=Sites,%s",
1359                                  s->dest_dsa.netbios_name,
1360                                  s->dest_dsa.site_name,
1361                                  s->forest.config_dn_str);
1362         NT_STATUS_HAVE_NO_MEMORY(msg->dn);
1363
1364         ret = ldb_msg_add_string(msg, "objectClass", "server");
1365         if (ret != 0) {
1366                 talloc_free(msg);
1367                 return NT_STATUS_NO_MEMORY;
1368         }
1369         ret = ldb_msg_add_string(msg, "systemFlags", "50000000");
1370         if (ret != 0) {
1371                 talloc_free(msg);
1372                 return NT_STATUS_NO_MEMORY;
1373         }
1374         ret = ldb_msg_add_string(msg, "serverReference", s->dest_dsa.computer_dn_str);
1375         if (ret != 0) {
1376                 talloc_free(msg);
1377                 return NT_STATUS_NO_MEMORY;
1378         }
1379
1380         server_dn_str = ldb_dn_alloc_linearized(s, msg->dn);
1381         NT_STATUS_HAVE_NO_MEMORY(server_dn_str);
1382
1383         ret = ldb_add(s->ldap1.ldb, msg);
1384         talloc_free(msg);
1385         if (ret != LDB_SUCCESS) {
1386                 talloc_free(server_dn_str);
1387                 return NT_STATUS_LDAP(ret);
1388         }
1389
1390         s->dest_dsa.server_dn_str = server_dn_str;
1391
1392         return NT_STATUS_OK;
1393 }
1394
1395 static NTSTATUS becomeDC_ldap1_server_object_modify(struct libnet_BecomeDC_state *s)
1396 {
1397         int ret;
1398         struct ldb_message *msg;
1399         uint32_t i;
1400
1401         /* make a 'modify' msg, and only for serverReference */
1402         msg = ldb_msg_new(s);
1403         NT_STATUS_HAVE_NO_MEMORY(msg);
1404         msg->dn = ldb_dn_new(msg, s->ldap1.ldb, s->dest_dsa.server_dn_str);
1405         NT_STATUS_HAVE_NO_MEMORY(msg->dn);
1406
1407         ret = ldb_msg_add_string(msg, "serverReference", s->dest_dsa.computer_dn_str);
1408         if (ret != 0) {
1409                 talloc_free(msg);
1410                 return NT_STATUS_NO_MEMORY;
1411         }
1412
1413         /* mark all the message elements (should be just one)
1414            as LDB_FLAG_MOD_ADD */
1415         for (i=0;i<msg->num_elements;i++) {
1416                 msg->elements[i].flags = LDB_FLAG_MOD_ADD;
1417         }
1418
1419         ret = ldb_modify(s->ldap1.ldb, msg);
1420         if (ret == LDB_SUCCESS) {
1421                 talloc_free(msg);
1422                 return NT_STATUS_OK;
1423         } else if (ret == LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS) {
1424                 /* retry with LDB_FLAG_MOD_REPLACE */
1425         } else {
1426                 talloc_free(msg);
1427                 return NT_STATUS_LDAP(ret);
1428         }
1429
1430         /* mark all the message elements (should be just one)
1431            as LDB_FLAG_MOD_REPLACE */
1432         for (i=0;i<msg->num_elements;i++) {
1433                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
1434         }
1435
1436         ret = ldb_modify(s->ldap1.ldb, msg);
1437         talloc_free(msg);
1438         if (ret != LDB_SUCCESS) {
1439                 return NT_STATUS_LDAP(ret);
1440         }
1441
1442         return NT_STATUS_OK;
1443 }
1444
1445 static void becomeDC_drsuapi_connect_send(struct libnet_BecomeDC_state *s,
1446                                           struct becomeDC_drsuapi *drsuapi,
1447                                           void (*recv_fn)(struct composite_context *req));
1448 static void becomeDC_drsuapi1_connect_recv(struct composite_context *req);
1449 static void becomeDC_connect_ldap2(struct libnet_BecomeDC_state *s);
1450
1451 static void becomeDC_connect_ldap1(struct libnet_BecomeDC_state *s)
1452 {
1453         struct composite_context *c = s->creq;
1454
1455         c->status = becomeDC_ldap_connect(s, &s->ldap1);
1456         if (!composite_is_ok(c)) return;
1457
1458         c->status = becomeDC_ldap1_rootdse(s);
1459         if (!composite_is_ok(c)) return;
1460
1461         c->status = becomeDC_ldap1_crossref_behavior_version(s);
1462         if (!composite_is_ok(c)) return;
1463
1464         c->status = becomeDC_ldap1_domain_behavior_version(s);
1465         if (!composite_is_ok(c)) return;
1466
1467         c->status = becomeDC_ldap1_schema_object_version(s);
1468         if (!composite_is_ok(c)) return;
1469
1470         c->status = becomeDC_ldap1_w2k3_update_revision(s);
1471         if (!composite_is_ok(c)) return;
1472
1473         c->status = becomeDC_ldap1_infrastructure_fsmo(s);
1474         if (!composite_is_ok(c)) return;
1475
1476         c->status = becomeDC_ldap1_rid_manager_fsmo(s);
1477         if (!composite_is_ok(c)) return;
1478
1479         c->status = becomeDC_ldap1_site_object(s);
1480         if (!composite_is_ok(c)) return;
1481
1482         c->status = becomeDC_check_options(s);
1483         if (!composite_is_ok(c)) return;
1484
1485         c->status = becomeDC_ldap1_computer_object(s);
1486         if (!composite_is_ok(c)) return;
1487
1488         c->status = becomeDC_ldap1_server_object_1(s);
1489         if (!composite_is_ok(c)) return;
1490
1491         c->status = becomeDC_ldap1_server_object_2(s);
1492         if (!composite_is_ok(c)) return;
1493
1494         c->status = becomeDC_ldap1_server_object_add(s);
1495         if (!composite_is_ok(c)) return;
1496
1497         c->status = becomeDC_ldap1_server_object_modify(s);
1498         if (!composite_is_ok(c)) return;
1499
1500         becomeDC_drsuapi_connect_send(s, &s->drsuapi1, becomeDC_drsuapi1_connect_recv);
1501 }
1502
1503 static void becomeDC_drsuapi_connect_send(struct libnet_BecomeDC_state *s,
1504                                           struct becomeDC_drsuapi *drsuapi,
1505                                           void (*recv_fn)(struct composite_context *req))
1506 {
1507         struct composite_context *c = s->creq;
1508         struct composite_context *creq;
1509         char *binding_str;
1510
1511         drsuapi->s = s;
1512
1513         if (!drsuapi->binding) {
1514                 if (lp_parm_bool(global_loadparm, NULL, "become_dc", "print", false)) {
1515                         binding_str = talloc_asprintf(s, "ncacn_ip_tcp:%s[krb5,print,seal]", s->source_dsa.dns_name);
1516                         if (composite_nomem(binding_str, c)) return;
1517                 } else {
1518                         binding_str = talloc_asprintf(s, "ncacn_ip_tcp:%s[krb5,seal]", s->source_dsa.dns_name);
1519                         if (composite_nomem(binding_str, c)) return;
1520                 }
1521                 c->status = dcerpc_parse_binding(s, binding_str, &drsuapi->binding);
1522                 talloc_free(binding_str);
1523                 if (!composite_is_ok(c)) return;
1524         }
1525
1526         creq = dcerpc_pipe_connect_b_send(s, drsuapi->binding, &ndr_table_drsuapi,
1527                                           s->libnet->cred, s->libnet->event_ctx);
1528         composite_continue(c, creq, recv_fn, s);
1529 }
1530
1531 static void becomeDC_drsuapi_bind_send(struct libnet_BecomeDC_state *s,
1532                                        struct becomeDC_drsuapi *drsuapi,
1533                                        void (*recv_fn)(struct rpc_request *req));
1534 static void becomeDC_drsuapi1_bind_recv(struct rpc_request *req);
1535
1536 static void becomeDC_drsuapi1_connect_recv(struct composite_context *req)
1537 {
1538         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
1539                                           struct libnet_BecomeDC_state);
1540         struct composite_context *c = s->creq;
1541
1542         c->status = dcerpc_pipe_connect_b_recv(req, s, &s->drsuapi1.pipe);
1543         if (!composite_is_ok(c)) return;
1544
1545         c->status = gensec_session_key(s->drsuapi1.pipe->conn->security_state.generic_state,
1546                                        &s->drsuapi1.gensec_skey);
1547         if (!composite_is_ok(c)) return;
1548
1549         becomeDC_drsuapi_bind_send(s, &s->drsuapi1, becomeDC_drsuapi1_bind_recv);
1550 }
1551
1552 static void becomeDC_drsuapi_bind_send(struct libnet_BecomeDC_state *s,
1553                                        struct becomeDC_drsuapi *drsuapi,
1554                                        void (*recv_fn)(struct rpc_request *req))
1555 {
1556         struct composite_context *c = s->creq;
1557         struct rpc_request *req;
1558         struct drsuapi_DsBindInfo28 *bind_info28;
1559
1560         GUID_from_string(DRSUAPI_DS_BIND_GUID_W2K3, &drsuapi->bind_guid);
1561
1562         bind_info28                             = &drsuapi->local_info28;
1563         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_BASE;
1564         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION;
1565         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI;
1566         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2;
1567         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS;
1568         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1;
1569         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION;
1570         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE;
1571         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2;
1572         if (s->domain.behavior_version == 2) {
1573                 /* TODO: find out how this is really triggered! */
1574                 bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION;
1575         }
1576         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2;
1577         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD;
1578         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND;
1579         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO;
1580         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION;
1581         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01;
1582         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP;
1583         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY;
1584         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3;
1585         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_00100000;
1586         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2;
1587         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6;
1588         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS;
1589         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8;
1590         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5;
1591         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6;
1592         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3;
1593         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7;
1594         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT;
1595 #if 0 /* we don't support XPRESS compression yet */
1596         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_XPRESS_COMPRESS;
1597 #endif
1598         bind_info28->site_guid                  = s->dest_dsa.site_guid;
1599         if (s->domain.behavior_version == 2) {
1600                 /* TODO: find out how this is really triggered! */
1601                 bind_info28->u1                         = 528;
1602         } else {
1603                 bind_info28->u1                         = 516;
1604         }
1605         bind_info28->repl_epoch                 = 0;
1606
1607         drsuapi->bind_info_ctr.length           = 28;
1608         drsuapi->bind_info_ctr.info.info28      = *bind_info28;
1609
1610         drsuapi->bind_r.in.bind_guid = &drsuapi->bind_guid;
1611         drsuapi->bind_r.in.bind_info = &drsuapi->bind_info_ctr;
1612         drsuapi->bind_r.out.bind_handle = &drsuapi->bind_handle;
1613
1614         req = dcerpc_drsuapi_DsBind_send(drsuapi->pipe, s, &drsuapi->bind_r);
1615         composite_continue_rpc(c, req, recv_fn, s);
1616 }
1617
1618 static WERROR becomeDC_drsuapi_bind_recv(struct libnet_BecomeDC_state *s,
1619                                          struct becomeDC_drsuapi *drsuapi)
1620 {
1621         if (!W_ERROR_IS_OK(drsuapi->bind_r.out.result)) {
1622                 return drsuapi->bind_r.out.result;
1623         }
1624
1625         ZERO_STRUCT(drsuapi->remote_info28);
1626         if (drsuapi->bind_r.out.bind_info) {
1627                 switch (drsuapi->bind_r.out.bind_info->length) {
1628                 case 24: {
1629                         struct drsuapi_DsBindInfo24 *info24;
1630                         info24 = &drsuapi->bind_r.out.bind_info->info.info24;
1631                         drsuapi->remote_info28.supported_extensions     = info24->supported_extensions;
1632                         drsuapi->remote_info28.site_guid                = info24->site_guid;
1633                         drsuapi->remote_info28.u1                       = info24->u1;
1634                         drsuapi->remote_info28.repl_epoch               = 0;
1635                         break;
1636                 }
1637                 case 28:
1638                         drsuapi->remote_info28 = drsuapi->bind_r.out.bind_info->info.info28;
1639                         break;
1640                 }
1641         }
1642
1643         return WERR_OK;
1644 }
1645
1646 static void becomeDC_drsuapi1_add_entry_send(struct libnet_BecomeDC_state *s);
1647
1648 static void becomeDC_drsuapi1_bind_recv(struct rpc_request *req)
1649 {
1650         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
1651                                           struct libnet_BecomeDC_state);
1652         struct composite_context *c = s->creq;
1653         WERROR status;
1654
1655         bool print = false;
1656
1657         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
1658                 print = true;
1659         }
1660
1661         c->status = dcerpc_ndr_request_recv(req);
1662         if (!composite_is_ok(c)) return;
1663
1664         if (print) {
1665                 NDR_PRINT_OUT_DEBUG(drsuapi_DsBind, &s->drsuapi1.bind_r);
1666         }
1667
1668         status = becomeDC_drsuapi_bind_recv(s, &s->drsuapi1);
1669         if (!W_ERROR_IS_OK(status)) {
1670                 composite_error(c, werror_to_ntstatus(status));
1671                 return;
1672         }
1673
1674         becomeDC_drsuapi1_add_entry_send(s);
1675 }
1676
1677 static void becomeDC_drsuapi1_add_entry_recv(struct rpc_request *req);
1678
1679 static void becomeDC_drsuapi1_add_entry_send(struct libnet_BecomeDC_state *s)
1680 {
1681         struct composite_context *c = s->creq;
1682         struct rpc_request *req;
1683         struct drsuapi_DsAddEntry *r;
1684         struct drsuapi_DsReplicaObjectIdentifier *identifier;
1685         uint32_t num_attrs, i = 0;
1686         struct drsuapi_DsReplicaAttribute *attrs;
1687         enum ndr_err_code ndr_err;
1688         bool w2k3;
1689
1690         /* choose a random invocationId */
1691         s->dest_dsa.invocation_id = GUID_random();
1692
1693         /*
1694          * if the schema version indicates w2k3, then
1695          * also send some w2k3 specific attributes
1696          */
1697         if (s->forest.schema_object_version >= 30) {
1698                 w2k3 = true;
1699         } else {
1700                 w2k3 = false;
1701         }
1702
1703         r = talloc_zero(s, struct drsuapi_DsAddEntry);
1704         if (composite_nomem(r, c)) return;
1705
1706         /* setup identifier */
1707         identifier              = talloc(r, struct drsuapi_DsReplicaObjectIdentifier);
1708         if (composite_nomem(identifier, c)) return;
1709         identifier->guid        = GUID_zero();
1710         identifier->sid         = s->zero_sid;
1711         identifier->dn          = talloc_asprintf(identifier, "CN=NTDS Settings,%s",
1712                                                   s->dest_dsa.server_dn_str);
1713         if (composite_nomem(identifier->dn, c)) return;
1714
1715         /* allocate attribute array */
1716         num_attrs       = 11;
1717         attrs           = talloc_array(r, struct drsuapi_DsReplicaAttribute, num_attrs);
1718         if (composite_nomem(attrs, c)) return;
1719
1720         /* ntSecurityDescriptor */
1721         {
1722                 struct drsuapi_DsAttributeValue *vs;
1723                 DATA_BLOB *vd;
1724                 struct security_descriptor *v;
1725                 struct dom_sid *domain_admins_sid;
1726                 const char *domain_admins_sid_str;
1727
1728                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
1729                 if (composite_nomem(vs, c)) return;
1730
1731                 vd = talloc_array(vs, DATA_BLOB, 1);
1732                 if (composite_nomem(vd, c)) return;
1733
1734                 domain_admins_sid = dom_sid_add_rid(vs, s->domain.sid, DOMAIN_RID_ADMINS);
1735                 if (composite_nomem(domain_admins_sid, c)) return;
1736
1737                 domain_admins_sid_str = dom_sid_string(domain_admins_sid, domain_admins_sid);
1738                 if (composite_nomem(domain_admins_sid_str, c)) return;
1739
1740                 v = security_descriptor_dacl_create(vd,
1741                                                0,
1742                                                /* owner: domain admins */
1743                                                domain_admins_sid_str,
1744                                                /* owner group: domain admins */
1745                                                domain_admins_sid_str,
1746                                                /* authenticated users */
1747                                                SID_NT_AUTHENTICATED_USERS,
1748                                                SEC_ACE_TYPE_ACCESS_ALLOWED,
1749                                                SEC_STD_READ_CONTROL |
1750                                                SEC_ADS_LIST |
1751                                                SEC_ADS_READ_PROP |
1752                                                SEC_ADS_LIST_OBJECT,
1753                                                0,
1754                                                /* domain admins */
1755                                                domain_admins_sid_str,
1756                                                SEC_ACE_TYPE_ACCESS_ALLOWED,
1757                                                SEC_STD_REQUIRED |
1758                                                SEC_ADS_CREATE_CHILD |
1759                                                SEC_ADS_LIST |
1760                                                SEC_ADS_SELF_WRITE |
1761                                                SEC_ADS_READ_PROP |
1762                                                SEC_ADS_WRITE_PROP |
1763                                                SEC_ADS_DELETE_TREE |
1764                                                SEC_ADS_LIST_OBJECT |
1765                                                SEC_ADS_CONTROL_ACCESS,
1766                                                0,
1767                                                /* system */
1768                                                SID_NT_SYSTEM,
1769                                                SEC_ACE_TYPE_ACCESS_ALLOWED,
1770                                                SEC_STD_REQUIRED |
1771                                                SEC_ADS_CREATE_CHILD |
1772                                                SEC_ADS_DELETE_CHILD |
1773                                                SEC_ADS_LIST |
1774                                                SEC_ADS_SELF_WRITE |
1775                                                SEC_ADS_READ_PROP |
1776                                                SEC_ADS_WRITE_PROP |
1777                                                SEC_ADS_DELETE_TREE |
1778                                                SEC_ADS_LIST_OBJECT |
1779                                                SEC_ADS_CONTROL_ACCESS,
1780                                                0,
1781                                                /* end */
1782                                                NULL);
1783                 if (composite_nomem(v, c)) return;
1784
1785                 ndr_err = ndr_push_struct_blob(&vd[0], vd, v,(ndr_push_flags_fn_t)ndr_push_security_descriptor);
1786                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1787                         c->status = ndr_map_error2ntstatus(ndr_err);
1788                         if (!composite_is_ok(c)) return;
1789                 }
1790
1791                 vs[0].blob              = &vd[0];
1792
1793                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_ntSecurityDescriptor;
1794                 attrs[i].value_ctr.num_values   = 1;
1795                 attrs[i].value_ctr.values       = vs;
1796
1797                 i++;
1798         }
1799
1800         /* objectClass: nTDSDSA */
1801         {
1802                 struct drsuapi_DsAttributeValue *vs;
1803                 DATA_BLOB *vd;
1804
1805                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
1806                 if (composite_nomem(vs, c)) return;
1807
1808                 vd = talloc_array(vs, DATA_BLOB, 1);
1809                 if (composite_nomem(vd, c)) return;
1810
1811                 vd[0] = data_blob_talloc(vd, NULL, 4);
1812                 if (composite_nomem(vd[0].data, c)) return;
1813
1814                 /* value for nTDSDSA */
1815                 SIVAL(vd[0].data, 0, 0x0017002F);
1816
1817                 vs[0].blob              = &vd[0];
1818
1819                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_objectClass;
1820                 attrs[i].value_ctr.num_values   = 1;
1821                 attrs[i].value_ctr.values       = vs;
1822
1823                 i++;
1824         }
1825
1826         /* objectCategory: CN=NTDS-DSA,CN=Schema,... */
1827         {
1828                 struct drsuapi_DsAttributeValue *vs;
1829                 DATA_BLOB *vd;
1830                 struct drsuapi_DsReplicaObjectIdentifier3 v[1];
1831
1832                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
1833                 if (composite_nomem(vs, c)) return;
1834
1835                 vd = talloc_array(vs, DATA_BLOB, 1);
1836                 if (composite_nomem(vd, c)) return;
1837
1838                 v[0].guid               = GUID_zero();
1839                 v[0].sid                = s->zero_sid;
1840                 v[0].dn                 = talloc_asprintf(vd, "CN=NTDS-DSA,%s",
1841                                                           s->forest.schema_dn_str);
1842                 if (composite_nomem(v[0].dn, c)) return;
1843
1844                 ndr_err = ndr_push_struct_blob(&vd[0], vd, &v[0],
1845                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1846                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1847                         c->status = ndr_map_error2ntstatus(ndr_err);
1848                         if (!composite_is_ok(c)) return;
1849                 }
1850
1851                 vs[0].blob              = &vd[0];
1852
1853                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_objectCategory;
1854                 attrs[i].value_ctr.num_values   = 1;
1855                 attrs[i].value_ctr.values       = vs;
1856
1857                 i++;
1858         }
1859
1860         /* invocationId: random guid */
1861         {
1862                 struct drsuapi_DsAttributeValue *vs;
1863                 DATA_BLOB *vd;
1864                 const struct GUID *v;
1865
1866                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
1867                 if (composite_nomem(vs, c)) return;
1868
1869                 vd = talloc_array(vs, DATA_BLOB, 1);
1870                 if (composite_nomem(vd, c)) return;
1871
1872                 v = &s->dest_dsa.invocation_id;
1873
1874                 ndr_err = ndr_push_struct_blob(&vd[0], vd, v, (ndr_push_flags_fn_t)ndr_push_GUID);
1875                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1876                         c->status = ndr_map_error2ntstatus(ndr_err);
1877                         if (!composite_is_ok(c)) return;
1878                 }
1879
1880                 vs[0].blob              = &vd[0];
1881
1882                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_invocationId;
1883                 attrs[i].value_ctr.num_values   = 1;
1884                 attrs[i].value_ctr.values       = vs;
1885
1886                 i++;
1887         }
1888
1889         /* hasMasterNCs: ... */
1890         {
1891                 struct drsuapi_DsAttributeValue *vs;
1892                 DATA_BLOB *vd;
1893                 struct drsuapi_DsReplicaObjectIdentifier3 v[3];
1894
1895                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 3);
1896                 if (composite_nomem(vs, c)) return;
1897
1898                 vd = talloc_array(vs, DATA_BLOB, 3);
1899                 if (composite_nomem(vd, c)) return;
1900
1901                 v[0].guid               = GUID_zero();
1902                 v[0].sid                = s->zero_sid;
1903                 v[0].dn                 = s->forest.config_dn_str;
1904
1905                 v[1].guid               = GUID_zero();
1906                 v[1].sid                = s->zero_sid;
1907                 v[1].dn                 = s->domain.dn_str;
1908
1909                 v[2].guid               = GUID_zero();
1910                 v[2].sid                = s->zero_sid;
1911                 v[2].dn                 = s->forest.schema_dn_str;
1912
1913                 ndr_err = ndr_push_struct_blob(&vd[0], vd, &v[0],
1914                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1915                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1916                         c->status = ndr_map_error2ntstatus(ndr_err);
1917                         if (!composite_is_ok(c)) return;
1918                 }
1919
1920                 ndr_err = ndr_push_struct_blob(&vd[1], vd, &v[1],
1921                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1922                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1923                         c->status = ndr_map_error2ntstatus(ndr_err);
1924                         if (!composite_is_ok(c)) return;
1925                 }
1926
1927                 ndr_err = ndr_push_struct_blob(&vd[2], vd, &v[2],
1928                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1929                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1930                         c->status = ndr_map_error2ntstatus(ndr_err);
1931                         if (!composite_is_ok(c)) return;
1932                 }
1933
1934                 vs[0].blob              = &vd[0];
1935                 vs[1].blob              = &vd[1];
1936                 vs[2].blob              = &vd[2];
1937
1938                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_hasMasterNCs;
1939                 attrs[i].value_ctr.num_values   = 3;
1940                 attrs[i].value_ctr.values       = vs;
1941
1942                 i++;
1943         }
1944
1945         /* msDS-hasMasterNCs: ... */
1946         if (w2k3) {
1947                 struct drsuapi_DsAttributeValue *vs;
1948                 DATA_BLOB *vd;
1949                 struct drsuapi_DsReplicaObjectIdentifier3 v[3];
1950
1951                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 3);
1952                 if (composite_nomem(vs, c)) return;
1953
1954                 vd = talloc_array(vs, DATA_BLOB, 3);
1955                 if (composite_nomem(vd, c)) return;
1956
1957                 v[0].guid               = GUID_zero();
1958                 v[0].sid                = s->zero_sid;
1959                 v[0].dn                 = s->forest.config_dn_str;
1960
1961                 v[1].guid               = GUID_zero();
1962                 v[1].sid                = s->zero_sid;
1963                 v[1].dn                 = s->domain.dn_str;
1964
1965                 v[2].guid               = GUID_zero();
1966                 v[2].sid                = s->zero_sid;
1967                 v[2].dn                 = s->forest.schema_dn_str;
1968
1969                 ndr_err = ndr_push_struct_blob(&vd[0], vd, &v[0],
1970                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1971                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1972                         c->status = ndr_map_error2ntstatus(ndr_err);
1973                         if (!composite_is_ok(c)) return;
1974                 }
1975
1976                 ndr_err = ndr_push_struct_blob(&vd[1], vd, &v[1],
1977                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1978                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1979                         c->status = ndr_map_error2ntstatus(ndr_err);
1980                         if (!composite_is_ok(c)) return;
1981                 }
1982
1983                 ndr_err = ndr_push_struct_blob(&vd[2], vd, &v[2],
1984                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1985                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1986                         c->status = ndr_map_error2ntstatus(ndr_err);
1987                         if (!composite_is_ok(c)) return;
1988                 }
1989
1990                 vs[0].blob              = &vd[0];
1991                 vs[1].blob              = &vd[1];
1992                 vs[2].blob              = &vd[2];
1993
1994                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_msDS_hasMasterNCs;
1995                 attrs[i].value_ctr.num_values   = 3;
1996                 attrs[i].value_ctr.values       = vs;
1997
1998                 i++;
1999         }
2000
2001         /* dMDLocation: CN=Schema,... */
2002         {
2003                 struct drsuapi_DsAttributeValue *vs;
2004                 DATA_BLOB *vd;
2005                 struct drsuapi_DsReplicaObjectIdentifier3 v[1];
2006
2007                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
2008                 if (composite_nomem(vs, c)) return;
2009
2010                 vd = talloc_array(vs, DATA_BLOB, 1);
2011                 if (composite_nomem(vd, c)) return;
2012
2013                 v[0].guid               = GUID_zero();
2014                 v[0].sid                = s->zero_sid;
2015                 v[0].dn                 = s->forest.schema_dn_str;
2016
2017                 ndr_err = ndr_push_struct_blob(&vd[0], vd, &v[0],
2018                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
2019                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2020                         c->status = ndr_map_error2ntstatus(ndr_err);
2021                         if (!composite_is_ok(c)) return;
2022                 }
2023
2024                 vs[0].blob              = &vd[0];
2025
2026                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_dMDLocation;
2027                 attrs[i].value_ctr.num_values   = 1;
2028                 attrs[i].value_ctr.values       = vs;
2029
2030                 i++;
2031         }
2032
2033         /* msDS-HasDomainNCs: <domain_partition> */
2034         if (w2k3) {
2035                 struct drsuapi_DsAttributeValue *vs;
2036                 DATA_BLOB *vd;
2037                 struct drsuapi_DsReplicaObjectIdentifier3 v[1];
2038
2039                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
2040                 if (composite_nomem(vs, c)) return;
2041
2042                 vd = talloc_array(vs, DATA_BLOB, 1);
2043                 if (composite_nomem(vd, c)) return;
2044
2045                 v[0].guid               = GUID_zero();
2046                 v[0].sid                = s->zero_sid;
2047                 v[0].dn                 = s->domain.dn_str;
2048
2049                 ndr_err = ndr_push_struct_blob(&vd[0], vd, &v[0],
2050                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
2051                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2052                         c->status = ndr_map_error2ntstatus(ndr_err);
2053                         if (!composite_is_ok(c)) return;
2054                 }
2055
2056                 vs[0].blob              = &vd[0];
2057
2058                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_msDS_HasDomainNCs;
2059                 attrs[i].value_ctr.num_values   = 1;
2060                 attrs[i].value_ctr.values       = vs;
2061
2062                 i++;
2063         }
2064
2065         /* msDS-Behavior-Version */
2066         if (w2k3) {
2067                 struct drsuapi_DsAttributeValue *vs;
2068                 DATA_BLOB *vd;
2069
2070                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
2071                 if (composite_nomem(vs, c)) return;
2072
2073                 vd = talloc_array(vs, DATA_BLOB, 1);
2074                 if (composite_nomem(vd, c)) return;
2075
2076                 vd[0] = data_blob_talloc(vd, NULL, 4);
2077                 if (composite_nomem(vd[0].data, c)) return;
2078
2079                 SIVAL(vd[0].data, 0, DS_BEHAVIOR_WIN2003);
2080
2081                 vs[0].blob              = &vd[0];
2082
2083                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_msDS_Behavior_Version;
2084                 attrs[i].value_ctr.num_values   = 1;
2085                 attrs[i].value_ctr.values       = vs;
2086
2087                 i++;
2088         }
2089
2090         /* systemFlags */
2091         {
2092                 struct drsuapi_DsAttributeValue *vs;
2093                 DATA_BLOB *vd;
2094
2095                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
2096                 if (composite_nomem(vs, c)) return;
2097
2098                 vd = talloc_array(vs, DATA_BLOB, 1);
2099                 if (composite_nomem(vd, c)) return;
2100
2101                 vd[0] = data_blob_talloc(vd, NULL, 4);
2102                 if (composite_nomem(vd[0].data, c)) return;
2103
2104                 SIVAL(vd[0].data, 0, SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE);
2105
2106                 vs[0].blob              = &vd[0];
2107
2108                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_systemFlags;
2109                 attrs[i].value_ctr.num_values   = 1;
2110                 attrs[i].value_ctr.values       = vs;
2111
2112                 i++;
2113         }
2114
2115         /* serverReference: ... */
2116         {
2117                 struct drsuapi_DsAttributeValue *vs;
2118                 DATA_BLOB *vd;
2119                 struct drsuapi_DsReplicaObjectIdentifier3 v[1];
2120
2121                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
2122                 if (composite_nomem(vs, c)) return;
2123
2124                 vd = talloc_array(vs, DATA_BLOB, 1);
2125                 if (composite_nomem(vd, c)) return;
2126
2127                 v[0].guid               = GUID_zero();
2128                 v[0].sid                = s->zero_sid;
2129                 v[0].dn                 = s->dest_dsa.computer_dn_str;
2130
2131                 ndr_err = ndr_push_struct_blob(&vd[0], vd, &v[0],
2132                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
2133                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2134                         c->status = ndr_map_error2ntstatus(ndr_err);
2135                         if (!composite_is_ok(c)) return;
2136                 }
2137
2138                 vs[0].blob              = &vd[0];
2139
2140                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_serverReference;
2141                 attrs[i].value_ctr.num_values   = 1;
2142                 attrs[i].value_ctr.values       = vs;
2143
2144                 i++;
2145         }
2146
2147         /* truncate the attribute list to the attribute count we have filled in */
2148         num_attrs = i;
2149
2150         /* setup request structure */
2151         r->in.bind_handle                                               = &s->drsuapi1.bind_handle;
2152         r->in.level                                                     = 2;
2153         r->in.req.req2.first_object.next_object                         = NULL;
2154         r->in.req.req2.first_object.object.identifier                   = identifier;
2155         r->in.req.req2.first_object.object.unknown1                     = 0x00000000;   
2156         r->in.req.req2.first_object.object.attribute_ctr.num_attributes = num_attrs;
2157         r->in.req.req2.first_object.object.attribute_ctr.attributes     = attrs;
2158
2159         req = dcerpc_drsuapi_DsAddEntry_send(s->drsuapi1.pipe, r, r);
2160         composite_continue_rpc(c, req, becomeDC_drsuapi1_add_entry_recv, s);
2161 }
2162
2163 static void becomeDC_drsuapi2_connect_recv(struct composite_context *req);
2164 static NTSTATUS becomeDC_prepare_db(struct libnet_BecomeDC_state *s);
2165
2166 static void becomeDC_drsuapi1_add_entry_recv(struct rpc_request *req)
2167 {
2168         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2169                                           struct libnet_BecomeDC_state);
2170         struct composite_context *c = s->creq;
2171         struct drsuapi_DsAddEntry *r = talloc_get_type(req->ndr.struct_ptr,
2172                                        struct drsuapi_DsAddEntry);
2173         char *binding_str;
2174         bool print = false;
2175
2176         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2177                 print = true;
2178         }
2179
2180         c->status = dcerpc_ndr_request_recv(req);
2181         if (!composite_is_ok(c)) return;
2182
2183         if (print) {
2184                 NDR_PRINT_OUT_DEBUG(drsuapi_DsAddEntry, r);
2185         }
2186
2187         if (!W_ERROR_IS_OK(r->out.result)) {
2188                 composite_error(c, werror_to_ntstatus(r->out.result));
2189                 return;
2190         }
2191
2192         if (r->out.level == 3) {
2193                 if (r->out.ctr.ctr3.count != 1) {
2194                         WERROR status;
2195
2196                         if (r->out.ctr.ctr3.level != 1) {
2197                                 composite_error(c, NT_STATUS_INVALID_NETWORK_RESPONSE);
2198                                 return;
2199                         }
2200
2201                         if (!r->out.ctr.ctr3.error) {
2202                                 composite_error(c, NT_STATUS_INVALID_NETWORK_RESPONSE);
2203                                 return;
2204                         }
2205
2206                         status = r->out.ctr.ctr3.error->info1.status;
2207
2208                         if (!r->out.ctr.ctr3.error->info1.info) {
2209                                 composite_error(c, werror_to_ntstatus(status));
2210                                 return;
2211                         }
2212
2213                         /* see if we can get a more detailed error */
2214                         switch (r->out.ctr.ctr3.error->info1.level) {
2215                         case 1:
2216                                 status = r->out.ctr.ctr3.error->info1.info->error1.status;
2217                                 break;
2218                         case 4:
2219                         case 5:
2220                         case 6:
2221                         case 7:
2222                                 status = r->out.ctr.ctr3.error->info1.info->errorX.status;
2223                                 break;
2224                         }
2225
2226                         composite_error(c, werror_to_ntstatus(status));
2227                         return;
2228                 }
2229
2230                 s->dest_dsa.ntds_guid   = r->out.ctr.ctr3.objects[0].guid;
2231         } else if (r->out.level == 2) {
2232                 if (r->out.ctr.ctr2.count != 1) {
2233                         composite_error(c, werror_to_ntstatus(r->out.ctr.ctr2.error.status));
2234                         return;
2235                 }
2236
2237                 s->dest_dsa.ntds_guid   = r->out.ctr.ctr2.objects[0].guid;
2238         } else {
2239                 composite_error(c, NT_STATUS_INVALID_NETWORK_RESPONSE);
2240                 return;
2241         }
2242
2243         talloc_free(r);
2244
2245         s->dest_dsa.ntds_dn_str = talloc_asprintf(s, "CN=NTDS Settings,%s",
2246                                                   s->dest_dsa.server_dn_str);
2247         if (composite_nomem(s->dest_dsa.ntds_dn_str, c)) return;
2248
2249         c->status = becomeDC_prepare_db(s);
2250         if (!composite_is_ok(c)) return;
2251
2252         /* this avoids the epmapper lookup on the 2nd connection */
2253         binding_str = dcerpc_binding_string(s, s->drsuapi1.binding);
2254         if (composite_nomem(binding_str, c)) return;
2255
2256         c->status = dcerpc_parse_binding(s, binding_str, &s->drsuapi2.binding);
2257         talloc_free(binding_str);
2258         if (!composite_is_ok(c)) return;
2259
2260         /* w2k3 uses the same assoc_group_id as on the first connection, so we do */
2261         s->drsuapi2.binding->assoc_group_id     = s->drsuapi1.pipe->assoc_group_id;
2262
2263         becomeDC_drsuapi_connect_send(s, &s->drsuapi2, becomeDC_drsuapi2_connect_recv);
2264 }
2265
2266 static NTSTATUS becomeDC_prepare_db(struct libnet_BecomeDC_state *s)
2267 {
2268         if (!s->callbacks.prepare_db) return NT_STATUS_OK;
2269
2270         s->_pp.domain           = &s->domain;
2271         s->_pp.forest           = &s->forest;
2272         s->_pp.source_dsa       = &s->source_dsa;
2273         s->_pp.dest_dsa         = &s->dest_dsa;
2274
2275         return s->callbacks.prepare_db(s->callbacks.private_data, &s->_pp);
2276 }
2277
2278 static void becomeDC_drsuapi2_bind_recv(struct rpc_request *req);
2279
2280 static void becomeDC_drsuapi2_connect_recv(struct composite_context *req)
2281 {
2282         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2283                                           struct libnet_BecomeDC_state);
2284         struct composite_context *c = s->creq;
2285
2286         c->status = dcerpc_pipe_connect_b_recv(req, s, &s->drsuapi2.pipe);
2287         if (!composite_is_ok(c)) return;
2288
2289         c->status = gensec_session_key(s->drsuapi2.pipe->conn->security_state.generic_state,
2290                                        &s->drsuapi2.gensec_skey);
2291         if (!composite_is_ok(c)) return;
2292
2293         becomeDC_drsuapi_bind_send(s, &s->drsuapi2, becomeDC_drsuapi2_bind_recv);
2294 }
2295
2296 static void becomeDC_drsuapi3_connect_recv(struct composite_context *req);
2297
2298 static void becomeDC_drsuapi2_bind_recv(struct rpc_request *req)
2299 {
2300         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2301                                           struct libnet_BecomeDC_state);
2302         struct composite_context *c = s->creq;
2303         char *binding_str;
2304         WERROR status;
2305
2306         bool print = false;
2307
2308         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2309                 print = true;
2310         }
2311
2312         c->status = dcerpc_ndr_request_recv(req);
2313         if (!composite_is_ok(c)) return;
2314
2315         if (print) {
2316                 NDR_PRINT_OUT_DEBUG(drsuapi_DsBind, &s->drsuapi2.bind_r);
2317         }
2318
2319         status = becomeDC_drsuapi_bind_recv(s, &s->drsuapi2);
2320         if (!W_ERROR_IS_OK(status)) {
2321                 composite_error(c, werror_to_ntstatus(status));
2322                 return;
2323         }
2324
2325         /* this avoids the epmapper lookup on the 3rd connection */
2326         binding_str = dcerpc_binding_string(s, s->drsuapi1.binding);
2327         if (composite_nomem(binding_str, c)) return;
2328
2329         c->status = dcerpc_parse_binding(s, binding_str, &s->drsuapi3.binding);
2330         talloc_free(binding_str);
2331         if (!composite_is_ok(c)) return;
2332
2333         /* w2k3 uses the same assoc_group_id as on the first connection, so we do */
2334         s->drsuapi3.binding->assoc_group_id     = s->drsuapi1.pipe->assoc_group_id;
2335         /* w2k3 uses the concurrent multiplex feature on the 3rd connection, so we do */
2336         s->drsuapi3.binding->flags              |= DCERPC_CONCURRENT_MULTIPLEX;
2337
2338         becomeDC_drsuapi_connect_send(s, &s->drsuapi3, becomeDC_drsuapi3_connect_recv);
2339 }
2340
2341 static void becomeDC_drsuapi3_pull_schema_send(struct libnet_BecomeDC_state *s);
2342
2343 static void becomeDC_drsuapi3_connect_recv(struct composite_context *req)
2344 {
2345         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2346                                           struct libnet_BecomeDC_state);
2347         struct composite_context *c = s->creq;
2348
2349         c->status = dcerpc_pipe_connect_b_recv(req, s, &s->drsuapi3.pipe);
2350         if (!composite_is_ok(c)) return;
2351
2352         c->status = gensec_session_key(s->drsuapi3.pipe->conn->security_state.generic_state,
2353                                        &s->drsuapi3.gensec_skey);
2354         if (!composite_is_ok(c)) return;
2355
2356         becomeDC_drsuapi3_pull_schema_send(s);
2357 }
2358
2359 static void becomeDC_drsuapi_pull_partition_send(struct libnet_BecomeDC_state *s,
2360                                                  struct becomeDC_drsuapi *drsuapi_h,
2361                                                  struct becomeDC_drsuapi *drsuapi_p,
2362                                                  struct libnet_BecomeDC_Partition *partition,
2363                                                  void (*recv_fn)(struct rpc_request *req))
2364 {
2365         struct composite_context *c = s->creq;
2366         struct rpc_request *req;
2367         struct drsuapi_DsGetNCChanges *r;
2368
2369         r = talloc(s, struct drsuapi_DsGetNCChanges);
2370         if (composite_nomem(r, c)) return;
2371
2372         r->in.level = talloc(r, int32_t);
2373         if (composite_nomem(r->in.level, c)) return;
2374         r->out.level = talloc(r, int32_t);
2375         if (composite_nomem(r->out.level, c)) return;
2376
2377         r->in.bind_handle       = &drsuapi_h->bind_handle;
2378         if (drsuapi_h->remote_info28.supported_extensions & DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8) {
2379                 *r->in.level                            = 8;
2380                 r->in.req.req8.destination_dsa_guid     = partition->destination_dsa_guid;
2381                 r->in.req.req8.source_dsa_invocation_id = partition->source_dsa_invocation_id;
2382                 r->in.req.req8.naming_context           = &partition->nc;
2383                 r->in.req.req8.highwatermark            = partition->highwatermark;
2384                 r->in.req.req8.uptodateness_vector      = NULL;
2385                 r->in.req.req8.replica_flags            = partition->replica_flags;
2386                 r->in.req.req8.max_object_count         = 133;
2387                 r->in.req.req8.max_ndr_size             = 1336811;
2388                 r->in.req.req8.unknown4                 = 0;
2389                 r->in.req.req8.h1                       = 0;
2390                 r->in.req.req8.unique_ptr1              = 0;
2391                 r->in.req.req8.unique_ptr2              = 0;
2392                 r->in.req.req8.mapping_ctr.num_mappings = 0;
2393                 r->in.req.req8.mapping_ctr.mappings     = NULL;
2394         } else {
2395                 *r->in.level                            = 5;
2396                 r->in.req.req5.destination_dsa_guid     = partition->destination_dsa_guid;
2397                 r->in.req.req5.source_dsa_invocation_id = partition->source_dsa_invocation_id;
2398                 r->in.req.req5.naming_context           = &partition->nc;
2399                 r->in.req.req5.highwatermark            = partition->highwatermark;
2400                 r->in.req.req5.uptodateness_vector      = NULL;
2401                 r->in.req.req5.replica_flags            = partition->replica_flags;
2402                 r->in.req.req5.max_object_count         = 133;
2403                 r->in.req.req5.max_ndr_size             = 1336770;
2404                 r->in.req.req5.unknown4                 = 0;
2405                 r->in.req.req5.h1                       = 0;
2406         }
2407
2408         /* 
2409          * we should try to use the drsuapi_p->pipe here, as w2k3 does
2410          * but it seems that some extra flags in the DCERPC Bind call
2411          * are needed for it. Or the same KRB5 TGS is needed on both
2412          * connections.
2413          */
2414         req = dcerpc_drsuapi_DsGetNCChanges_send(drsuapi_p->pipe, r, r);
2415         composite_continue_rpc(c, req, recv_fn, s);
2416 }
2417
2418 static WERROR becomeDC_drsuapi_pull_partition_recv(struct libnet_BecomeDC_state *s,
2419                                                    struct becomeDC_drsuapi *drsuapi_h,
2420                                                    struct becomeDC_drsuapi *drsuapi_p,
2421                                                    struct libnet_BecomeDC_Partition *partition,
2422                                                    struct drsuapi_DsGetNCChanges *r)
2423 {
2424         uint32_t ctr_level = 0;
2425         struct drsuapi_DsGetNCChangesCtr1 *ctr1 = NULL;
2426         struct drsuapi_DsGetNCChangesCtr6 *ctr6 = NULL;
2427         struct GUID *source_dsa_guid;
2428         struct GUID *source_dsa_invocation_id;
2429         struct drsuapi_DsReplicaHighWaterMark *new_highwatermark;
2430         NTSTATUS nt_status;
2431
2432         if (!W_ERROR_IS_OK(r->out.result)) {
2433                 return r->out.result;
2434         }
2435
2436         if (*r->out.level == 1) {
2437                 ctr_level = 1;
2438                 ctr1 = &r->out.ctr.ctr1;
2439         } else if (*r->out.level == 2) {
2440                 ctr_level = 1;
2441                 ctr1 = r->out.ctr.ctr2.ctr.mszip1.ctr1;
2442         } else if (*r->out.level == 6) {
2443                 ctr_level = 6;
2444                 ctr6 = &r->out.ctr.ctr6;
2445         } else if (*r->out.level == 7 &&
2446                    r->out.ctr.ctr7.level == 6 &&
2447                    r->out.ctr.ctr7.type == DRSUAPI_COMPRESSION_TYPE_MSZIP) {
2448                 ctr_level = 6;
2449                 ctr6 = r->out.ctr.ctr7.ctr.mszip6.ctr6;
2450         } else {
2451                 return WERR_BAD_NET_RESP;
2452         }
2453
2454         switch (ctr_level) {
2455         case 1:
2456                 source_dsa_guid                 = &ctr1->source_dsa_guid;
2457                 source_dsa_invocation_id        = &ctr1->source_dsa_invocation_id;
2458                 new_highwatermark               = &ctr1->new_highwatermark;
2459                 break;
2460         case 6:
2461                 source_dsa_guid                 = &ctr6->source_dsa_guid;
2462                 source_dsa_invocation_id        = &ctr6->source_dsa_invocation_id;
2463                 new_highwatermark               = &ctr6->new_highwatermark;
2464                 break;
2465         }
2466
2467         partition->highwatermark                = *new_highwatermark;
2468         partition->source_dsa_guid              = *source_dsa_guid;
2469         partition->source_dsa_invocation_id     = *source_dsa_invocation_id;
2470
2471         if (!partition->store_chunk) return WERR_OK;
2472
2473         s->_sc.domain           = &s->domain;
2474         s->_sc.forest           = &s->forest;
2475         s->_sc.source_dsa       = &s->source_dsa;
2476         s->_sc.dest_dsa         = &s->dest_dsa;
2477         s->_sc.partition        = partition;
2478         s->_sc.ctr_level        = ctr_level;
2479         s->_sc.ctr1             = ctr1;
2480         s->_sc.ctr6             = ctr6;
2481         /* 
2482          * we need to use the drsuapi_p->gensec_skey here,
2483          * when we use drsuapi_p->pipe in the for this request
2484          */
2485         s->_sc.gensec_skey      = &drsuapi_p->gensec_skey;
2486
2487         nt_status = partition->store_chunk(s->callbacks.private_data, &s->_sc);
2488         if (!NT_STATUS_IS_OK(nt_status)) {
2489                 return ntstatus_to_werror(nt_status);
2490         }
2491
2492         return WERR_OK;
2493 }
2494
2495 static void becomeDC_drsuapi3_pull_schema_recv(struct rpc_request *req);
2496
2497 static void becomeDC_drsuapi3_pull_schema_send(struct libnet_BecomeDC_state *s)
2498 {
2499         s->schema_part.nc.guid  = GUID_zero();
2500         s->schema_part.nc.sid   = s->zero_sid;
2501         s->schema_part.nc.dn    = s->forest.schema_dn_str;
2502
2503         s->schema_part.destination_dsa_guid     = s->drsuapi2.bind_guid;
2504
2505         s->schema_part.replica_flags    = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
2506                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
2507                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS
2508                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_FULL_IN_PROGRESS
2509                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_NEVER_SYNCED
2510                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_COMPRESS_CHANGES;
2511
2512         s->schema_part.store_chunk      = s->callbacks.schema_chunk;
2513
2514         becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->schema_part,
2515                                              becomeDC_drsuapi3_pull_schema_recv);
2516 }
2517
2518 static void becomeDC_drsuapi3_pull_config_send(struct libnet_BecomeDC_state *s);
2519
2520 static void becomeDC_drsuapi3_pull_schema_recv(struct rpc_request *req)
2521 {
2522         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2523                                           struct libnet_BecomeDC_state);
2524         struct composite_context *c = s->creq;
2525         struct drsuapi_DsGetNCChanges *r = talloc_get_type(req->ndr.struct_ptr,
2526                                            struct drsuapi_DsGetNCChanges);
2527         WERROR status;
2528
2529         bool print = false;
2530
2531         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2532                 print = true;
2533         }
2534
2535         c->status = dcerpc_ndr_request_recv(req);
2536         if (!composite_is_ok(c)) return;
2537
2538         if (print) {
2539                 NDR_PRINT_OUT_DEBUG(drsuapi_DsGetNCChanges, r);
2540         }
2541
2542         status = becomeDC_drsuapi_pull_partition_recv(s, &s->drsuapi2, &s->drsuapi3, &s->schema_part, r);
2543         if (!W_ERROR_IS_OK(status)) {
2544                 composite_error(c, werror_to_ntstatus(status));
2545                 return;
2546         }
2547
2548         talloc_free(r);
2549
2550         if (s->schema_part.highwatermark.tmp_highest_usn > s->schema_part.highwatermark.highest_usn) {
2551                 becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->schema_part,
2552                                                      becomeDC_drsuapi3_pull_schema_recv);
2553                 return;
2554         }
2555
2556         becomeDC_drsuapi3_pull_config_send(s);
2557 }
2558
2559 static void becomeDC_drsuapi3_pull_config_recv(struct rpc_request *req);
2560
2561 static void becomeDC_drsuapi3_pull_config_send(struct libnet_BecomeDC_state *s)
2562 {
2563         s->config_part.nc.guid  = GUID_zero();
2564         s->config_part.nc.sid   = s->zero_sid;
2565         s->config_part.nc.dn    = s->forest.config_dn_str;
2566
2567         s->config_part.destination_dsa_guid     = s->drsuapi2.bind_guid;
2568
2569         s->config_part.replica_flags    = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
2570                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
2571                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS
2572                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_FULL_IN_PROGRESS
2573                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_NEVER_SYNCED
2574                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_COMPRESS_CHANGES;
2575
2576         s->config_part.store_chunk      = s->callbacks.config_chunk;
2577
2578         becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->config_part,
2579                                              becomeDC_drsuapi3_pull_config_recv);
2580 }
2581
2582 static void becomeDC_drsuapi3_pull_config_recv(struct rpc_request *req)
2583 {
2584         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2585                                           struct libnet_BecomeDC_state);
2586         struct composite_context *c = s->creq;
2587         struct drsuapi_DsGetNCChanges *r = talloc_get_type(req->ndr.struct_ptr,
2588                                            struct drsuapi_DsGetNCChanges);
2589         WERROR status;
2590
2591         bool print = false;
2592
2593         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2594                 print = true;
2595         }
2596
2597         c->status = dcerpc_ndr_request_recv(req);
2598         if (!composite_is_ok(c)) return;
2599
2600         if (print) {
2601                 NDR_PRINT_OUT_DEBUG(drsuapi_DsGetNCChanges, r);
2602         }
2603
2604         status = becomeDC_drsuapi_pull_partition_recv(s, &s->drsuapi2, &s->drsuapi3, &s->config_part, r);
2605         if (!W_ERROR_IS_OK(status)) {
2606                 composite_error(c, werror_to_ntstatus(status));
2607                 return;
2608         }
2609
2610         talloc_free(r);
2611
2612         if (s->config_part.highwatermark.tmp_highest_usn > s->config_part.highwatermark.highest_usn) {
2613                 becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->config_part,
2614                                                      becomeDC_drsuapi3_pull_config_recv);
2615                 return;
2616         }
2617
2618         becomeDC_connect_ldap2(s);
2619 }
2620
2621 static void becomeDC_drsuapi3_pull_domain_recv(struct rpc_request *req);
2622
2623 static void becomeDC_drsuapi3_pull_domain_send(struct libnet_BecomeDC_state *s)
2624 {
2625         s->domain_part.nc.guid  = GUID_zero();
2626         s->domain_part.nc.sid   = s->zero_sid;
2627         s->domain_part.nc.dn    = s->domain.dn_str;
2628
2629         s->domain_part.destination_dsa_guid     = s->drsuapi2.bind_guid;
2630
2631         s->domain_part.replica_flags    = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
2632                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
2633                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS
2634                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_FULL_IN_PROGRESS
2635                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_NEVER_SYNCED
2636                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_COMPRESS_CHANGES;
2637
2638         s->domain_part.store_chunk      = s->callbacks.domain_chunk;
2639
2640         becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->domain_part,
2641                                              becomeDC_drsuapi3_pull_domain_recv);
2642 }
2643
2644 static void becomeDC_drsuapi_update_refs_send(struct libnet_BecomeDC_state *s,
2645                                               struct becomeDC_drsuapi *drsuapi,
2646                                               struct libnet_BecomeDC_Partition *partition,
2647                                               void (*recv_fn)(struct rpc_request *req));
2648 static void becomeDC_drsuapi2_update_refs_schema_recv(struct rpc_request *req);
2649
2650 static void becomeDC_drsuapi3_pull_domain_recv(struct rpc_request *req)
2651 {
2652         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2653                                           struct libnet_BecomeDC_state);
2654         struct composite_context *c = s->creq;
2655         struct drsuapi_DsGetNCChanges *r = talloc_get_type(req->ndr.struct_ptr,
2656                                            struct drsuapi_DsGetNCChanges);
2657         WERROR status;
2658         bool print = false;
2659
2660         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2661                 print = true;
2662         }
2663
2664         c->status = dcerpc_ndr_request_recv(req);
2665         if (!composite_is_ok(c)) return;
2666
2667         if (print) {
2668                 NDR_PRINT_OUT_DEBUG(drsuapi_DsGetNCChanges, r);
2669         }
2670
2671         status = becomeDC_drsuapi_pull_partition_recv(s, &s->drsuapi2, &s->drsuapi3, &s->domain_part, r);
2672         if (!W_ERROR_IS_OK(status)) {
2673                 composite_error(c, werror_to_ntstatus(status));
2674                 return;
2675         }
2676
2677         talloc_free(r);
2678
2679         if (s->domain_part.highwatermark.tmp_highest_usn > s->domain_part.highwatermark.highest_usn) {
2680                 becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->domain_part,
2681                                                      becomeDC_drsuapi3_pull_domain_recv);
2682                 return;
2683         }
2684
2685         becomeDC_drsuapi_update_refs_send(s, &s->drsuapi2, &s->schema_part,
2686                                           becomeDC_drsuapi2_update_refs_schema_recv);
2687 }
2688
2689 static void becomeDC_drsuapi_update_refs_send(struct libnet_BecomeDC_state *s,
2690                                               struct becomeDC_drsuapi *drsuapi,
2691                                               struct libnet_BecomeDC_Partition *partition,
2692                                               void (*recv_fn)(struct rpc_request *req))
2693 {
2694         struct composite_context *c = s->creq;
2695         struct rpc_request *req;
2696         struct drsuapi_DsReplicaUpdateRefs *r;
2697         const char *ntds_guid_str;
2698         const char *ntds_dns_name;
2699
2700         r = talloc(s, struct drsuapi_DsReplicaUpdateRefs);
2701         if (composite_nomem(r, c)) return;
2702
2703         ntds_guid_str = GUID_string(r, &s->dest_dsa.ntds_guid);
2704         if (composite_nomem(ntds_guid_str, c)) return;
2705
2706         ntds_dns_name = talloc_asprintf(r, "%s._msdcs.%s",
2707                                         ntds_guid_str,
2708                                         s->domain.dns_name);
2709         if (composite_nomem(ntds_dns_name, c)) return;
2710
2711         r->in.bind_handle               = &drsuapi->bind_handle;
2712         r->in.level                     = 1;
2713         r->in.req.req1.naming_context   = &partition->nc;
2714         r->in.req.req1.dest_dsa_dns_name= ntds_dns_name;
2715         r->in.req.req1.dest_dsa_guid    = s->dest_dsa.ntds_guid;
2716         r->in.req.req1.options          = DRSUAPI_DS_REPLICA_UPDATE_ADD_REFERENCE
2717                                         | DRSUAPI_DS_REPLICA_UPDATE_DELETE_REFERENCE
2718                                         | DRSUAPI_DS_REPLICA_UPDATE_0x00000010;
2719
2720         req = dcerpc_drsuapi_DsReplicaUpdateRefs_send(drsuapi->pipe, r, r);
2721         composite_continue_rpc(c, req, recv_fn, s);
2722 }
2723
2724 static void becomeDC_drsuapi2_update_refs_config_recv(struct rpc_request *req);
2725
2726 static void becomeDC_drsuapi2_update_refs_schema_recv(struct rpc_request *req)
2727 {
2728         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2729                                           struct libnet_BecomeDC_state);
2730         struct composite_context *c = s->creq;
2731         struct drsuapi_DsReplicaUpdateRefs *r = talloc_get_type(req->ndr.struct_ptr,
2732                                            struct drsuapi_DsReplicaUpdateRefs);
2733         bool print = false;
2734
2735         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2736                 print = true;
2737         }
2738
2739         c->status = dcerpc_ndr_request_recv(req);
2740         if (!composite_is_ok(c)) return;
2741
2742         if (print) {
2743                 NDR_PRINT_OUT_DEBUG(drsuapi_DsReplicaUpdateRefs, r);
2744         }
2745
2746         if (!W_ERROR_IS_OK(r->out.result)) {
2747                 composite_error(c, werror_to_ntstatus(r->out.result));
2748                 return;
2749         }
2750
2751         talloc_free(r);
2752
2753         becomeDC_drsuapi_update_refs_send(s, &s->drsuapi2, &s->config_part,
2754                                           becomeDC_drsuapi2_update_refs_config_recv);
2755 }
2756
2757 static void becomeDC_drsuapi2_update_refs_domain_recv(struct rpc_request *req);
2758
2759 static void becomeDC_drsuapi2_update_refs_config_recv(struct rpc_request *req)
2760 {
2761         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2762                                           struct libnet_BecomeDC_state);
2763         struct composite_context *c = s->creq;
2764         struct drsuapi_DsReplicaUpdateRefs *r = talloc_get_type(req->ndr.struct_ptr,
2765                                            struct drsuapi_DsReplicaUpdateRefs);
2766
2767         c->status = dcerpc_ndr_request_recv(req);
2768         if (!composite_is_ok(c)) return;
2769
2770         if (!W_ERROR_IS_OK(r->out.result)) {
2771                 composite_error(c, werror_to_ntstatus(r->out.result));
2772                 return;
2773         }
2774
2775         talloc_free(r);
2776
2777         becomeDC_drsuapi_update_refs_send(s, &s->drsuapi2, &s->domain_part,
2778                                           becomeDC_drsuapi2_update_refs_domain_recv);
2779 }
2780
2781 static void becomeDC_drsuapi2_update_refs_domain_recv(struct rpc_request *req)
2782 {
2783         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2784                                           struct libnet_BecomeDC_state);
2785         struct composite_context *c = s->creq;
2786         struct drsuapi_DsReplicaUpdateRefs *r = talloc_get_type(req->ndr.struct_ptr,
2787                                            struct drsuapi_DsReplicaUpdateRefs);
2788
2789         c->status = dcerpc_ndr_request_recv(req);
2790         if (!composite_is_ok(c)) return;
2791
2792         if (!W_ERROR_IS_OK(r->out.result)) {
2793                 composite_error(c, werror_to_ntstatus(r->out.result));
2794                 return;
2795         }
2796
2797         talloc_free(r);
2798
2799         /* TODO: use DDNS updates and register dns names */
2800         composite_done(c);
2801 }
2802
2803 static NTSTATUS becomeDC_ldap2_modify_computer(struct libnet_BecomeDC_state *s)
2804 {
2805         int ret;
2806         struct ldb_message *msg;
2807         uint32_t i;
2808         uint32_t user_account_control = UF_SERVER_TRUST_ACCOUNT |
2809                                         UF_TRUSTED_FOR_DELEGATION;
2810
2811         /* as the value is already as we want it to be, we're done */
2812         if (s->dest_dsa.user_account_control == user_account_control) {
2813                 return NT_STATUS_OK;
2814         }
2815
2816         /* make a 'modify' msg, and only for serverReference */
2817         msg = ldb_msg_new(s);
2818         NT_STATUS_HAVE_NO_MEMORY(msg);
2819         msg->dn = ldb_dn_new(msg, s->ldap2.ldb, s->dest_dsa.computer_dn_str);
2820         NT_STATUS_HAVE_NO_MEMORY(msg->dn);
2821
2822         ret = ldb_msg_add_fmt(msg, "userAccountControl", "%u", user_account_control);
2823         if (ret != 0) {
2824                 talloc_free(msg);
2825                 return NT_STATUS_NO_MEMORY;
2826         }
2827
2828         /* mark all the message elements (should be just one)
2829            as LDB_FLAG_MOD_REPLACE */
2830         for (i=0;i<msg->num_elements;i++) {
2831                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
2832         }
2833
2834         ret = ldb_modify(s->ldap2.ldb, msg);
2835         talloc_free(msg);
2836         if (ret != LDB_SUCCESS) {
2837                 return NT_STATUS_LDAP(ret);
2838         }
2839
2840         s->dest_dsa.user_account_control = user_account_control;
2841
2842         return NT_STATUS_OK;
2843 }
2844
2845 static NTSTATUS becomeDC_ldap2_move_computer(struct libnet_BecomeDC_state *s)
2846 {
2847         int ret;
2848         struct ldb_result *r;
2849         struct ldb_dn *basedn;
2850         struct ldb_dn *old_dn;
2851         struct ldb_dn *new_dn;
2852         static const char *_1_1_attrs[] = {
2853                 "1.1",
2854                 NULL
2855         };
2856
2857         basedn = ldb_dn_new_fmt(s, s->ldap2.ldb, "<WKGUID=a361b2ffffd211d1aa4b00c04fd7d83a,%s>",
2858                                 s->domain.dn_str);
2859         NT_STATUS_HAVE_NO_MEMORY(basedn);
2860
2861         ret = ldb_search(s->ldap2.ldb, basedn, LDB_SCOPE_BASE,
2862                          "(objectClass=*)", _1_1_attrs, &r);
2863         talloc_free(basedn);
2864         if (ret != LDB_SUCCESS) {
2865                 return NT_STATUS_LDAP(ret);
2866         } else if (r->count != 1) {
2867                 talloc_free(r);
2868                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
2869         }
2870
2871         old_dn = ldb_dn_new(r, s->ldap2.ldb, s->dest_dsa.computer_dn_str);
2872         NT_STATUS_HAVE_NO_MEMORY(old_dn);
2873
2874         new_dn = r->msgs[0]->dn;
2875
2876         if (!ldb_dn_add_child_fmt(new_dn, "CN=%s", s->dest_dsa.netbios_name)) {
2877                 talloc_free(r);
2878                 return NT_STATUS_NO_MEMORY;
2879         }
2880
2881         if (ldb_dn_compare(old_dn, new_dn) == 0) {
2882                 /* we don't need to rename if the old and new dn match */
2883                 talloc_free(r);
2884                 return NT_STATUS_OK;
2885         }
2886
2887         ret = ldb_rename(s->ldap2.ldb, old_dn, new_dn);
2888         if (ret != LDB_SUCCESS) {
2889                 talloc_free(r);
2890                 return NT_STATUS_LDAP(ret);
2891         }
2892
2893         s->dest_dsa.computer_dn_str = ldb_dn_alloc_linearized(s, new_dn);
2894         NT_STATUS_HAVE_NO_MEMORY(s->dest_dsa.computer_dn_str);
2895
2896         talloc_free(r);
2897
2898         return NT_STATUS_OK;
2899 }
2900
2901 static void becomeDC_connect_ldap2(struct libnet_BecomeDC_state *s)
2902 {
2903         struct composite_context *c = s->creq;
2904
2905         c->status = becomeDC_ldap_connect(s, &s->ldap2);
2906         if (!composite_is_ok(c)) return;
2907
2908         c->status = becomeDC_ldap2_modify_computer(s);
2909         if (!composite_is_ok(c)) return;
2910
2911         c->status = becomeDC_ldap2_move_computer(s);
2912         if (!composite_is_ok(c)) return;
2913
2914         becomeDC_drsuapi3_pull_domain_send(s);
2915 }
2916
2917 struct composite_context *libnet_BecomeDC_send(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_BecomeDC *r)
2918 {
2919         struct composite_context *c;
2920         struct libnet_BecomeDC_state *s;
2921         char *tmp_name;
2922
2923         c = composite_create(mem_ctx, ctx->event_ctx);
2924         if (c == NULL) return NULL;
2925
2926         s = talloc_zero(c, struct libnet_BecomeDC_state);
2927         if (composite_nomem(s, c)) return c;
2928         c->private_data = s;
2929         s->creq         = c;
2930         s->libnet       = ctx;
2931
2932         /* Domain input */
2933         s->domain.dns_name      = talloc_strdup(s, r->in.domain_dns_name);
2934         if (composite_nomem(s->domain.dns_name, c)) return c;
2935         s->domain.netbios_name  = talloc_strdup(s, r->in.domain_netbios_name);
2936         if (composite_nomem(s->domain.netbios_name, c)) return c;
2937         s->domain.sid           = dom_sid_dup(s, r->in.domain_sid);
2938         if (composite_nomem(s->domain.sid, c)) return c;
2939
2940         /* Source DSA input */
2941         s->source_dsa.address   = talloc_strdup(s, r->in.source_dsa_address);
2942         if (composite_nomem(s->source_dsa.address, c)) return c;
2943
2944         /* Destination DSA input */
2945         s->dest_dsa.netbios_name= talloc_strdup(s, r->in.dest_dsa_netbios_name);
2946         if (composite_nomem(s->dest_dsa.netbios_name, c)) return c;
2947
2948         /* Destination DSA dns_name construction */
2949         tmp_name        = strlower_talloc(s, s->dest_dsa.netbios_name);
2950         if (composite_nomem(tmp_name, c)) return c;
2951         tmp_name        = talloc_asprintf_append_buffer(tmp_name, ".%s",s->domain.dns_name);
2952         if (composite_nomem(tmp_name, c)) return c;
2953         s->dest_dsa.dns_name    = tmp_name;
2954
2955         /* Callback function pointers */
2956         s->callbacks = r->in.callbacks;
2957
2958         becomeDC_send_cldap(s);
2959         return c;
2960 }
2961
2962 NTSTATUS libnet_BecomeDC_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, struct libnet_BecomeDC *r)
2963 {
2964         NTSTATUS status;
2965
2966         status = composite_wait(c);
2967
2968         ZERO_STRUCT(r->out);
2969
2970         talloc_free(c);
2971         return status;
2972 }
2973
2974 NTSTATUS libnet_BecomeDC(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_BecomeDC *r)
2975 {
2976         NTSTATUS status;
2977         struct composite_context *c;
2978         c = libnet_BecomeDC_send(ctx, mem_ctx, r);
2979         status = libnet_BecomeDC_recv(c, mem_ctx, r);
2980         return status;
2981 }