r25446: Merge some changes I made on the way home from SFO:
[jelmer/samba4-debian.git] / source / 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         bool w2k3;
1688
1689         /* choose a random invocationId */
1690         s->dest_dsa.invocation_id = GUID_random();
1691
1692         /*
1693          * if the schema version indicates w2k3, then
1694          * also send some w2k3 specific attributes
1695          */
1696         if (s->forest.schema_object_version >= 30) {
1697                 w2k3 = true;
1698         } else {
1699                 w2k3 = false;
1700         }
1701
1702         r = talloc_zero(s, struct drsuapi_DsAddEntry);
1703         if (composite_nomem(r, c)) return;
1704
1705         /* setup identifier */
1706         identifier              = talloc(r, struct drsuapi_DsReplicaObjectIdentifier);
1707         if (composite_nomem(identifier, c)) return;
1708         identifier->guid        = GUID_zero();
1709         identifier->sid         = s->zero_sid;
1710         identifier->dn          = talloc_asprintf(identifier, "CN=NTDS Settings,%s",
1711                                                   s->dest_dsa.server_dn_str);
1712         if (composite_nomem(identifier->dn, c)) return;
1713
1714         /* allocate attribute array */
1715         num_attrs       = 11;
1716         attrs           = talloc_array(r, struct drsuapi_DsReplicaAttribute, num_attrs);
1717         if (composite_nomem(attrs, c)) return;
1718
1719         /* ntSecurityDescriptor */
1720         {
1721                 struct drsuapi_DsAttributeValue *vs;
1722                 DATA_BLOB *vd;
1723                 struct security_descriptor *v;
1724                 struct dom_sid *domain_admins_sid;
1725                 const char *domain_admins_sid_str;
1726
1727                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
1728                 if (composite_nomem(vs, c)) return;
1729
1730                 vd = talloc_array(vs, DATA_BLOB, 1);
1731                 if (composite_nomem(vd, c)) return;
1732
1733                 domain_admins_sid = dom_sid_add_rid(vs, s->domain.sid, DOMAIN_RID_ADMINS);
1734                 if (composite_nomem(domain_admins_sid, c)) return;
1735
1736                 domain_admins_sid_str = dom_sid_string(domain_admins_sid, domain_admins_sid);
1737                 if (composite_nomem(domain_admins_sid_str, c)) return;
1738
1739                 v = security_descriptor_create(vd,
1740                                                /* owner: domain admins */
1741                                                domain_admins_sid_str,
1742                                                /* owner group: domain admins */
1743                                                domain_admins_sid_str,
1744                                                /* authenticated users */
1745                                                SID_NT_AUTHENTICATED_USERS,
1746                                                SEC_ACE_TYPE_ACCESS_ALLOWED,
1747                                                SEC_STD_READ_CONTROL |
1748                                                SEC_ADS_LIST |
1749                                                SEC_ADS_READ_PROP |
1750                                                SEC_ADS_LIST_OBJECT,
1751                                                0,
1752                                                /* domain admins */
1753                                                domain_admins_sid_str,
1754                                                SEC_ACE_TYPE_ACCESS_ALLOWED,
1755                                                SEC_STD_REQUIRED |
1756                                                SEC_ADS_CREATE_CHILD |
1757                                                SEC_ADS_LIST |
1758                                                SEC_ADS_SELF_WRITE |
1759                                                SEC_ADS_READ_PROP |
1760                                                SEC_ADS_WRITE_PROP |
1761                                                SEC_ADS_DELETE_TREE |
1762                                                SEC_ADS_LIST_OBJECT |
1763                                                SEC_ADS_CONTROL_ACCESS,
1764                                                0,
1765                                                /* system */
1766                                                SID_NT_SYSTEM,
1767                                                SEC_ACE_TYPE_ACCESS_ALLOWED,
1768                                                SEC_STD_REQUIRED |
1769                                                SEC_ADS_CREATE_CHILD |
1770                                                SEC_ADS_DELETE_CHILD |
1771                                                SEC_ADS_LIST |
1772                                                SEC_ADS_SELF_WRITE |
1773                                                SEC_ADS_READ_PROP |
1774                                                SEC_ADS_WRITE_PROP |
1775                                                SEC_ADS_DELETE_TREE |
1776                                                SEC_ADS_LIST_OBJECT |
1777                                                SEC_ADS_CONTROL_ACCESS,
1778                                                0,
1779                                                /* end */
1780                                                NULL);
1781                 if (composite_nomem(v, c)) return;
1782
1783                 c->status = ndr_push_struct_blob(&vd[0], vd, v,(ndr_push_flags_fn_t)ndr_push_security_descriptor);
1784                 if (!composite_is_ok(c)) return;
1785
1786                 vs[0].blob              = &vd[0];
1787
1788                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_ntSecurityDescriptor;
1789                 attrs[i].value_ctr.num_values   = 1;
1790                 attrs[i].value_ctr.values       = vs;
1791
1792                 i++;
1793         }
1794
1795         /* objectClass: nTDSDSA */
1796         {
1797                 struct drsuapi_DsAttributeValue *vs;
1798                 DATA_BLOB *vd;
1799
1800                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
1801                 if (composite_nomem(vs, c)) return;
1802
1803                 vd = talloc_array(vs, DATA_BLOB, 1);
1804                 if (composite_nomem(vd, c)) return;
1805
1806                 vd[0] = data_blob_talloc(vd, NULL, 4);
1807                 if (composite_nomem(vd[0].data, c)) return;
1808
1809                 /* value for nTDSDSA */
1810                 SIVAL(vd[0].data, 0, 0x0017002F);
1811
1812                 vs[0].blob              = &vd[0];
1813
1814                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_objectClass;
1815                 attrs[i].value_ctr.num_values   = 1;
1816                 attrs[i].value_ctr.values       = vs;
1817
1818                 i++;
1819         }
1820
1821         /* objectCategory: CN=NTDS-DSA,CN=Schema,... */
1822         {
1823                 struct drsuapi_DsAttributeValue *vs;
1824                 DATA_BLOB *vd;
1825                 struct drsuapi_DsReplicaObjectIdentifier3 v[1];
1826
1827                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
1828                 if (composite_nomem(vs, c)) return;
1829
1830                 vd = talloc_array(vs, DATA_BLOB, 1);
1831                 if (composite_nomem(vd, c)) return;
1832
1833                 v[0].guid               = GUID_zero();
1834                 v[0].sid                = s->zero_sid;
1835                 v[0].dn                 = talloc_asprintf(vd, "CN=NTDS-DSA,%s",
1836                                                           s->forest.schema_dn_str);
1837                 if (composite_nomem(v[0].dn, c)) return;
1838
1839                 c->status = ndr_push_struct_blob(&vd[0], vd, &v[0],
1840                                                  (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1841                 if (!composite_is_ok(c)) return;
1842
1843                 vs[0].blob              = &vd[0];
1844
1845                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_objectCategory;
1846                 attrs[i].value_ctr.num_values   = 1;
1847                 attrs[i].value_ctr.values       = vs;
1848
1849                 i++;
1850         }
1851
1852         /* invocationId: random guid */
1853         {
1854                 struct drsuapi_DsAttributeValue *vs;
1855                 DATA_BLOB *vd;
1856                 const struct GUID *v;
1857
1858                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
1859                 if (composite_nomem(vs, c)) return;
1860
1861                 vd = talloc_array(vs, DATA_BLOB, 1);
1862                 if (composite_nomem(vd, c)) return;
1863
1864                 v = &s->dest_dsa.invocation_id;
1865
1866                 c->status = ndr_push_struct_blob(&vd[0], vd, v, (ndr_push_flags_fn_t)ndr_push_GUID);
1867                 if (!composite_is_ok(c)) return;
1868
1869                 vs[0].blob              = &vd[0];
1870
1871                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_invocationId;
1872                 attrs[i].value_ctr.num_values   = 1;
1873                 attrs[i].value_ctr.values       = vs;
1874
1875                 i++;
1876         }
1877
1878         /* hasMasterNCs: ... */
1879         {
1880                 struct drsuapi_DsAttributeValue *vs;
1881                 DATA_BLOB *vd;
1882                 struct drsuapi_DsReplicaObjectIdentifier3 v[3];
1883
1884                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 3);
1885                 if (composite_nomem(vs, c)) return;
1886
1887                 vd = talloc_array(vs, DATA_BLOB, 3);
1888                 if (composite_nomem(vd, c)) return;
1889
1890                 v[0].guid               = GUID_zero();
1891                 v[0].sid                = s->zero_sid;
1892                 v[0].dn                 = s->forest.config_dn_str;
1893
1894                 v[1].guid               = GUID_zero();
1895                 v[1].sid                = s->zero_sid;
1896                 v[1].dn                 = s->domain.dn_str;
1897
1898                 v[2].guid               = GUID_zero();
1899                 v[2].sid                = s->zero_sid;
1900                 v[2].dn                 = s->forest.schema_dn_str;
1901
1902                 c->status = ndr_push_struct_blob(&vd[0], vd, &v[0],
1903                                                  (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1904                 if (!composite_is_ok(c)) return;
1905
1906                 c->status = ndr_push_struct_blob(&vd[1], vd, &v[1],
1907                                                  (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1908                 if (!composite_is_ok(c)) return;
1909
1910                 c->status = ndr_push_struct_blob(&vd[2], vd, &v[2],
1911                                                  (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1912                 if (!composite_is_ok(c)) return;
1913
1914                 vs[0].blob              = &vd[0];
1915                 vs[1].blob              = &vd[1];
1916                 vs[2].blob              = &vd[2];
1917
1918                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_hasMasterNCs;
1919                 attrs[i].value_ctr.num_values   = 3;
1920                 attrs[i].value_ctr.values       = vs;
1921
1922                 i++;
1923         }
1924
1925         /* msDS-hasMasterNCs: ... */
1926         if (w2k3) {
1927                 struct drsuapi_DsAttributeValue *vs;
1928                 DATA_BLOB *vd;
1929                 struct drsuapi_DsReplicaObjectIdentifier3 v[3];
1930
1931                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 3);
1932                 if (composite_nomem(vs, c)) return;
1933
1934                 vd = talloc_array(vs, DATA_BLOB, 3);
1935                 if (composite_nomem(vd, c)) return;
1936
1937                 v[0].guid               = GUID_zero();
1938                 v[0].sid                = s->zero_sid;
1939                 v[0].dn                 = s->forest.config_dn_str;
1940
1941                 v[1].guid               = GUID_zero();
1942                 v[1].sid                = s->zero_sid;
1943                 v[1].dn                 = s->domain.dn_str;
1944
1945                 v[2].guid               = GUID_zero();
1946                 v[2].sid                = s->zero_sid;
1947                 v[2].dn                 = s->forest.schema_dn_str;
1948
1949                 c->status = ndr_push_struct_blob(&vd[0], vd, &v[0],
1950                                                  (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1951                 if (!composite_is_ok(c)) return;
1952
1953                 c->status = ndr_push_struct_blob(&vd[1], vd, &v[1],
1954                                                  (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1955                 if (!composite_is_ok(c)) return;
1956
1957                 c->status = ndr_push_struct_blob(&vd[2], vd, &v[2],
1958                                                  (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1959                 if (!composite_is_ok(c)) return;
1960
1961                 vs[0].blob              = &vd[0];
1962                 vs[1].blob              = &vd[1];
1963                 vs[2].blob              = &vd[2];
1964
1965                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_msDS_hasMasterNCs;
1966                 attrs[i].value_ctr.num_values   = 3;
1967                 attrs[i].value_ctr.values       = vs;
1968
1969                 i++;
1970         }
1971
1972         /* dMDLocation: CN=Schema,... */
1973         {
1974                 struct drsuapi_DsAttributeValue *vs;
1975                 DATA_BLOB *vd;
1976                 struct drsuapi_DsReplicaObjectIdentifier3 v[1];
1977
1978                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
1979                 if (composite_nomem(vs, c)) return;
1980
1981                 vd = talloc_array(vs, DATA_BLOB, 1);
1982                 if (composite_nomem(vd, c)) return;
1983
1984                 v[0].guid               = GUID_zero();
1985                 v[0].sid                = s->zero_sid;
1986                 v[0].dn                 = s->forest.schema_dn_str;
1987
1988                 c->status = ndr_push_struct_blob(&vd[0], vd, &v[0],
1989                                                  (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1990                 if (!composite_is_ok(c)) return;
1991
1992                 vs[0].blob              = &vd[0];
1993
1994                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_dMDLocation;
1995                 attrs[i].value_ctr.num_values   = 1;
1996                 attrs[i].value_ctr.values       = vs;
1997
1998                 i++;
1999         }
2000
2001         /* msDS-HasDomainNCs: <domain_partition> */
2002         if (w2k3) {
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->domain.dn_str;
2016
2017                 c->status = ndr_push_struct_blob(&vd[0], vd, &v[0],
2018                                                  (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
2019                 if (!composite_is_ok(c)) return;
2020
2021                 vs[0].blob              = &vd[0];
2022
2023                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_msDS_HasDomainNCs;
2024                 attrs[i].value_ctr.num_values   = 1;
2025                 attrs[i].value_ctr.values       = vs;
2026
2027                 i++;
2028         }
2029
2030         /* msDS-Behavior-Version */
2031         if (w2k3) {
2032                 struct drsuapi_DsAttributeValue *vs;
2033                 DATA_BLOB *vd;
2034
2035                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
2036                 if (composite_nomem(vs, c)) return;
2037
2038                 vd = talloc_array(vs, DATA_BLOB, 1);
2039                 if (composite_nomem(vd, c)) return;
2040
2041                 vd[0] = data_blob_talloc(vd, NULL, 4);
2042                 if (composite_nomem(vd[0].data, c)) return;
2043
2044                 SIVAL(vd[0].data, 0, DS_BEHAVIOR_WIN2003);
2045
2046                 vs[0].blob              = &vd[0];
2047
2048                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_msDS_Behavior_Version;
2049                 attrs[i].value_ctr.num_values   = 1;
2050                 attrs[i].value_ctr.values       = vs;
2051
2052                 i++;
2053         }
2054
2055         /* systemFlags */
2056         {
2057                 struct drsuapi_DsAttributeValue *vs;
2058                 DATA_BLOB *vd;
2059
2060                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
2061                 if (composite_nomem(vs, c)) return;
2062
2063                 vd = talloc_array(vs, DATA_BLOB, 1);
2064                 if (composite_nomem(vd, c)) return;
2065
2066                 vd[0] = data_blob_talloc(vd, NULL, 4);
2067                 if (composite_nomem(vd[0].data, c)) return;
2068
2069                 SIVAL(vd[0].data, 0, SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE);
2070
2071                 vs[0].blob              = &vd[0];
2072
2073                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_systemFlags;
2074                 attrs[i].value_ctr.num_values   = 1;
2075                 attrs[i].value_ctr.values       = vs;
2076
2077                 i++;
2078         }
2079
2080         /* serverReference: ... */
2081         {
2082                 struct drsuapi_DsAttributeValue *vs;
2083                 DATA_BLOB *vd;
2084                 struct drsuapi_DsReplicaObjectIdentifier3 v[1];
2085
2086                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
2087                 if (composite_nomem(vs, c)) return;
2088
2089                 vd = talloc_array(vs, DATA_BLOB, 1);
2090                 if (composite_nomem(vd, c)) return;
2091
2092                 v[0].guid               = GUID_zero();
2093                 v[0].sid                = s->zero_sid;
2094                 v[0].dn                 = s->dest_dsa.computer_dn_str;
2095
2096                 c->status = ndr_push_struct_blob(&vd[0], vd, &v[0],
2097                                                  (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
2098                 if (!composite_is_ok(c)) return;
2099
2100                 vs[0].blob              = &vd[0];
2101
2102                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_serverReference;
2103                 attrs[i].value_ctr.num_values   = 1;
2104                 attrs[i].value_ctr.values       = vs;
2105
2106                 i++;
2107         }
2108
2109         /* truncate the attribute list to the attribute count we have filled in */
2110         num_attrs = i;
2111
2112         /* setup request structure */
2113         r->in.bind_handle                                               = &s->drsuapi1.bind_handle;
2114         r->in.level                                                     = 2;
2115         r->in.req.req2.first_object.next_object                         = NULL;
2116         r->in.req.req2.first_object.object.identifier                   = identifier;
2117         r->in.req.req2.first_object.object.unknown1                     = 0x00000000;   
2118         r->in.req.req2.first_object.object.attribute_ctr.num_attributes = num_attrs;
2119         r->in.req.req2.first_object.object.attribute_ctr.attributes     = attrs;
2120
2121         req = dcerpc_drsuapi_DsAddEntry_send(s->drsuapi1.pipe, r, r);
2122         composite_continue_rpc(c, req, becomeDC_drsuapi1_add_entry_recv, s);
2123 }
2124
2125 static void becomeDC_drsuapi2_connect_recv(struct composite_context *req);
2126 static NTSTATUS becomeDC_prepare_db(struct libnet_BecomeDC_state *s);
2127
2128 static void becomeDC_drsuapi1_add_entry_recv(struct rpc_request *req)
2129 {
2130         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2131                                           struct libnet_BecomeDC_state);
2132         struct composite_context *c = s->creq;
2133         struct drsuapi_DsAddEntry *r = talloc_get_type(req->ndr.struct_ptr,
2134                                        struct drsuapi_DsAddEntry);
2135         char *binding_str;
2136         bool print = false;
2137
2138         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2139                 print = true;
2140         }
2141
2142         c->status = dcerpc_ndr_request_recv(req);
2143         if (!composite_is_ok(c)) return;
2144
2145         if (print) {
2146                 NDR_PRINT_OUT_DEBUG(drsuapi_DsAddEntry, r);
2147         }
2148
2149         if (!W_ERROR_IS_OK(r->out.result)) {
2150                 composite_error(c, werror_to_ntstatus(r->out.result));
2151                 return;
2152         }
2153
2154         if (r->out.level == 3) {
2155                 if (r->out.ctr.ctr3.count != 1) {
2156                         WERROR status;
2157
2158                         if (r->out.ctr.ctr3.level != 1) {
2159                                 composite_error(c, NT_STATUS_INVALID_NETWORK_RESPONSE);
2160                                 return;
2161                         }
2162
2163                         if (!r->out.ctr.ctr3.error) {
2164                                 composite_error(c, NT_STATUS_INVALID_NETWORK_RESPONSE);
2165                                 return;
2166                         }
2167
2168                         status = r->out.ctr.ctr3.error->info1.status;
2169
2170                         if (!r->out.ctr.ctr3.error->info1.info) {
2171                                 composite_error(c, werror_to_ntstatus(status));
2172                                 return;
2173                         }
2174
2175                         /* see if we can get a more detailed error */
2176                         switch (r->out.ctr.ctr3.error->info1.level) {
2177                         case 1:
2178                                 status = r->out.ctr.ctr3.error->info1.info->error1.status;
2179                                 break;
2180                         case 4:
2181                         case 5:
2182                         case 6:
2183                         case 7:
2184                                 status = r->out.ctr.ctr3.error->info1.info->errorX.status;
2185                                 break;
2186                         }
2187
2188                         composite_error(c, werror_to_ntstatus(status));
2189                         return;
2190                 }
2191
2192                 s->dest_dsa.ntds_guid   = r->out.ctr.ctr3.objects[0].guid;
2193         } else if (r->out.level == 2) {
2194                 if (r->out.ctr.ctr2.count != 1) {
2195                         composite_error(c, werror_to_ntstatus(r->out.ctr.ctr2.error.status));
2196                         return;
2197                 }
2198
2199                 s->dest_dsa.ntds_guid   = r->out.ctr.ctr2.objects[0].guid;
2200         } else {
2201                 composite_error(c, NT_STATUS_INVALID_NETWORK_RESPONSE);
2202                 return;
2203         }
2204
2205         talloc_free(r);
2206
2207         s->dest_dsa.ntds_dn_str = talloc_asprintf(s, "CN=NTDS Settings,%s",
2208                                                   s->dest_dsa.server_dn_str);
2209         if (composite_nomem(s->dest_dsa.ntds_dn_str, c)) return;
2210
2211         c->status = becomeDC_prepare_db(s);
2212         if (!composite_is_ok(c)) return;
2213
2214         /* this avoids the epmapper lookup on the 2nd connection */
2215         binding_str = dcerpc_binding_string(s, s->drsuapi1.binding);
2216         if (composite_nomem(binding_str, c)) return;
2217
2218         c->status = dcerpc_parse_binding(s, binding_str, &s->drsuapi2.binding);
2219         talloc_free(binding_str);
2220         if (!composite_is_ok(c)) return;
2221
2222         /* w2k3 uses the same assoc_group_id as on the first connection, so we do */
2223         s->drsuapi2.binding->assoc_group_id     = s->drsuapi1.pipe->assoc_group_id;
2224
2225         becomeDC_drsuapi_connect_send(s, &s->drsuapi2, becomeDC_drsuapi2_connect_recv);
2226 }
2227
2228 static NTSTATUS becomeDC_prepare_db(struct libnet_BecomeDC_state *s)
2229 {
2230         if (!s->callbacks.prepare_db) return NT_STATUS_OK;
2231
2232         s->_pp.domain           = &s->domain;
2233         s->_pp.forest           = &s->forest;
2234         s->_pp.source_dsa       = &s->source_dsa;
2235         s->_pp.dest_dsa         = &s->dest_dsa;
2236
2237         return s->callbacks.prepare_db(s->callbacks.private_data, &s->_pp);
2238 }
2239
2240 static void becomeDC_drsuapi2_bind_recv(struct rpc_request *req);
2241
2242 static void becomeDC_drsuapi2_connect_recv(struct composite_context *req)
2243 {
2244         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2245                                           struct libnet_BecomeDC_state);
2246         struct composite_context *c = s->creq;
2247
2248         c->status = dcerpc_pipe_connect_b_recv(req, s, &s->drsuapi2.pipe);
2249         if (!composite_is_ok(c)) return;
2250
2251         c->status = gensec_session_key(s->drsuapi2.pipe->conn->security_state.generic_state,
2252                                        &s->drsuapi2.gensec_skey);
2253         if (!composite_is_ok(c)) return;
2254
2255         becomeDC_drsuapi_bind_send(s, &s->drsuapi2, becomeDC_drsuapi2_bind_recv);
2256 }
2257
2258 static void becomeDC_drsuapi3_connect_recv(struct composite_context *req);
2259
2260 static void becomeDC_drsuapi2_bind_recv(struct rpc_request *req)
2261 {
2262         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2263                                           struct libnet_BecomeDC_state);
2264         struct composite_context *c = s->creq;
2265         char *binding_str;
2266         WERROR status;
2267
2268         bool print = false;
2269
2270         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2271                 print = true;
2272         }
2273
2274         c->status = dcerpc_ndr_request_recv(req);
2275         if (!composite_is_ok(c)) return;
2276
2277         if (print) {
2278                 NDR_PRINT_OUT_DEBUG(drsuapi_DsBind, &s->drsuapi2.bind_r);
2279         }
2280
2281         status = becomeDC_drsuapi_bind_recv(s, &s->drsuapi2);
2282         if (!W_ERROR_IS_OK(status)) {
2283                 composite_error(c, werror_to_ntstatus(status));
2284                 return;
2285         }
2286
2287         /* this avoids the epmapper lookup on the 3rd connection */
2288         binding_str = dcerpc_binding_string(s, s->drsuapi1.binding);
2289         if (composite_nomem(binding_str, c)) return;
2290
2291         c->status = dcerpc_parse_binding(s, binding_str, &s->drsuapi3.binding);
2292         talloc_free(binding_str);
2293         if (!composite_is_ok(c)) return;
2294
2295         /* w2k3 uses the same assoc_group_id as on the first connection, so we do */
2296         s->drsuapi3.binding->assoc_group_id     = s->drsuapi1.pipe->assoc_group_id;
2297         /* w2k3 uses the concurrent multiplex feature on the 3rd connection, so we do */
2298         s->drsuapi3.binding->flags              |= DCERPC_CONCURRENT_MULTIPLEX;
2299
2300         becomeDC_drsuapi_connect_send(s, &s->drsuapi3, becomeDC_drsuapi3_connect_recv);
2301 }
2302
2303 static void becomeDC_drsuapi3_pull_schema_send(struct libnet_BecomeDC_state *s);
2304
2305 static void becomeDC_drsuapi3_connect_recv(struct composite_context *req)
2306 {
2307         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2308                                           struct libnet_BecomeDC_state);
2309         struct composite_context *c = s->creq;
2310
2311         c->status = dcerpc_pipe_connect_b_recv(req, s, &s->drsuapi3.pipe);
2312         if (!composite_is_ok(c)) return;
2313
2314         c->status = gensec_session_key(s->drsuapi3.pipe->conn->security_state.generic_state,
2315                                        &s->drsuapi3.gensec_skey);
2316         if (!composite_is_ok(c)) return;
2317
2318         becomeDC_drsuapi3_pull_schema_send(s);
2319 }
2320
2321 static void becomeDC_drsuapi_pull_partition_send(struct libnet_BecomeDC_state *s,
2322                                                  struct becomeDC_drsuapi *drsuapi_h,
2323                                                  struct becomeDC_drsuapi *drsuapi_p,
2324                                                  struct libnet_BecomeDC_Partition *partition,
2325                                                  void (*recv_fn)(struct rpc_request *req))
2326 {
2327         struct composite_context *c = s->creq;
2328         struct rpc_request *req;
2329         struct drsuapi_DsGetNCChanges *r;
2330
2331         r = talloc(s, struct drsuapi_DsGetNCChanges);
2332         if (composite_nomem(r, c)) return;
2333
2334         r->in.level = talloc(r, int32_t);
2335         if (composite_nomem(r->in.level, c)) return;
2336         r->out.level = talloc(r, int32_t);
2337         if (composite_nomem(r->out.level, c)) return;
2338
2339         r->in.bind_handle       = &drsuapi_h->bind_handle;
2340         if (drsuapi_h->remote_info28.supported_extensions & DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8) {
2341                 *r->in.level                            = 8;
2342                 r->in.req.req8.destination_dsa_guid     = partition->destination_dsa_guid;
2343                 r->in.req.req8.source_dsa_invocation_id = partition->source_dsa_invocation_id;
2344                 r->in.req.req8.naming_context           = &partition->nc;
2345                 r->in.req.req8.highwatermark            = partition->highwatermark;
2346                 r->in.req.req8.uptodateness_vector      = NULL;
2347                 r->in.req.req8.replica_flags            = partition->replica_flags;
2348                 r->in.req.req8.max_object_count         = 133;
2349                 r->in.req.req8.max_ndr_size             = 1336811;
2350                 r->in.req.req8.unknown4                 = 0;
2351                 r->in.req.req8.h1                       = 0;
2352                 r->in.req.req8.unique_ptr1              = 0;
2353                 r->in.req.req8.unique_ptr2              = 0;
2354                 r->in.req.req8.mapping_ctr.num_mappings = 0;
2355                 r->in.req.req8.mapping_ctr.mappings     = NULL;
2356         } else {
2357                 *r->in.level                            = 5;
2358                 r->in.req.req5.destination_dsa_guid     = partition->destination_dsa_guid;
2359                 r->in.req.req5.source_dsa_invocation_id = partition->source_dsa_invocation_id;
2360                 r->in.req.req5.naming_context           = &partition->nc;
2361                 r->in.req.req5.highwatermark            = partition->highwatermark;
2362                 r->in.req.req5.uptodateness_vector      = NULL;
2363                 r->in.req.req5.replica_flags            = partition->replica_flags;
2364                 r->in.req.req5.max_object_count         = 133;
2365                 r->in.req.req5.max_ndr_size             = 1336770;
2366                 r->in.req.req5.unknown4                 = 0;
2367                 r->in.req.req5.h1                       = 0;
2368         }
2369
2370         /* 
2371          * we should try to use the drsuapi_p->pipe here, as w2k3 does
2372          * but it seems that some extra flags in the DCERPC Bind call
2373          * are needed for it. Or the same KRB5 TGS is needed on both
2374          * connections.
2375          */
2376         req = dcerpc_drsuapi_DsGetNCChanges_send(drsuapi_p->pipe, r, r);
2377         composite_continue_rpc(c, req, recv_fn, s);
2378 }
2379
2380 static WERROR becomeDC_drsuapi_pull_partition_recv(struct libnet_BecomeDC_state *s,
2381                                                    struct becomeDC_drsuapi *drsuapi_h,
2382                                                    struct becomeDC_drsuapi *drsuapi_p,
2383                                                    struct libnet_BecomeDC_Partition *partition,
2384                                                    struct drsuapi_DsGetNCChanges *r)
2385 {
2386         uint32_t ctr_level = 0;
2387         struct drsuapi_DsGetNCChangesCtr1 *ctr1 = NULL;
2388         struct drsuapi_DsGetNCChangesCtr6 *ctr6 = NULL;
2389         struct GUID *source_dsa_guid;
2390         struct GUID *source_dsa_invocation_id;
2391         struct drsuapi_DsReplicaHighWaterMark *new_highwatermark;
2392         NTSTATUS nt_status;
2393
2394         if (!W_ERROR_IS_OK(r->out.result)) {
2395                 return r->out.result;
2396         }
2397
2398         if (*r->out.level == 1) {
2399                 ctr_level = 1;
2400                 ctr1 = &r->out.ctr.ctr1;
2401         } else if (*r->out.level == 2) {
2402                 ctr_level = 1;
2403                 ctr1 = r->out.ctr.ctr2.ctr.mszip1.ctr1;
2404         } else if (*r->out.level == 6) {
2405                 ctr_level = 6;
2406                 ctr6 = &r->out.ctr.ctr6;
2407         } else if (*r->out.level == 7 &&
2408                    r->out.ctr.ctr7.level == 6 &&
2409                    r->out.ctr.ctr7.type == DRSUAPI_COMPRESSION_TYPE_MSZIP) {
2410                 ctr_level = 6;
2411                 ctr6 = r->out.ctr.ctr7.ctr.mszip6.ctr6;
2412         } else {
2413                 return WERR_BAD_NET_RESP;
2414         }
2415
2416         switch (ctr_level) {
2417         case 1:
2418                 source_dsa_guid                 = &ctr1->source_dsa_guid;
2419                 source_dsa_invocation_id        = &ctr1->source_dsa_invocation_id;
2420                 new_highwatermark               = &ctr1->new_highwatermark;
2421                 break;
2422         case 6:
2423                 source_dsa_guid                 = &ctr6->source_dsa_guid;
2424                 source_dsa_invocation_id        = &ctr6->source_dsa_invocation_id;
2425                 new_highwatermark               = &ctr6->new_highwatermark;
2426                 break;
2427         }
2428
2429         partition->highwatermark                = *new_highwatermark;
2430         partition->source_dsa_guid              = *source_dsa_guid;
2431         partition->source_dsa_invocation_id     = *source_dsa_invocation_id;
2432
2433         if (!partition->store_chunk) return WERR_OK;
2434
2435         s->_sc.domain           = &s->domain;
2436         s->_sc.forest           = &s->forest;
2437         s->_sc.source_dsa       = &s->source_dsa;
2438         s->_sc.dest_dsa         = &s->dest_dsa;
2439         s->_sc.partition        = partition;
2440         s->_sc.ctr_level        = ctr_level;
2441         s->_sc.ctr1             = ctr1;
2442         s->_sc.ctr6             = ctr6;
2443         /* 
2444          * we need to use the drsuapi_p->gensec_skey here,
2445          * when we use drsuapi_p->pipe in the for this request
2446          */
2447         s->_sc.gensec_skey      = &drsuapi_p->gensec_skey;
2448
2449         nt_status = partition->store_chunk(s->callbacks.private_data, &s->_sc);
2450         if (!NT_STATUS_IS_OK(nt_status)) {
2451                 return ntstatus_to_werror(nt_status);
2452         }
2453
2454         return WERR_OK;
2455 }
2456
2457 static void becomeDC_drsuapi3_pull_schema_recv(struct rpc_request *req);
2458
2459 static void becomeDC_drsuapi3_pull_schema_send(struct libnet_BecomeDC_state *s)
2460 {
2461         s->schema_part.nc.guid  = GUID_zero();
2462         s->schema_part.nc.sid   = s->zero_sid;
2463         s->schema_part.nc.dn    = s->forest.schema_dn_str;
2464
2465         s->schema_part.destination_dsa_guid     = s->drsuapi2.bind_guid;
2466
2467         s->schema_part.replica_flags    = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
2468                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
2469                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS
2470                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_FULL_IN_PROGRESS
2471                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_NEVER_SYNCED
2472                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_COMPRESS_CHANGES;
2473
2474         s->schema_part.store_chunk      = s->callbacks.schema_chunk;
2475
2476         becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->schema_part,
2477                                              becomeDC_drsuapi3_pull_schema_recv);
2478 }
2479
2480 static void becomeDC_drsuapi3_pull_config_send(struct libnet_BecomeDC_state *s);
2481
2482 static void becomeDC_drsuapi3_pull_schema_recv(struct rpc_request *req)
2483 {
2484         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2485                                           struct libnet_BecomeDC_state);
2486         struct composite_context *c = s->creq;
2487         struct drsuapi_DsGetNCChanges *r = talloc_get_type(req->ndr.struct_ptr,
2488                                            struct drsuapi_DsGetNCChanges);
2489         WERROR status;
2490
2491         bool print = false;
2492
2493         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2494                 print = true;
2495         }
2496
2497         c->status = dcerpc_ndr_request_recv(req);
2498         if (!composite_is_ok(c)) return;
2499
2500         if (print) {
2501                 NDR_PRINT_OUT_DEBUG(drsuapi_DsGetNCChanges, r);
2502         }
2503
2504         status = becomeDC_drsuapi_pull_partition_recv(s, &s->drsuapi2, &s->drsuapi3, &s->schema_part, r);
2505         if (!W_ERROR_IS_OK(status)) {
2506                 composite_error(c, werror_to_ntstatus(status));
2507                 return;
2508         }
2509
2510         talloc_free(r);
2511
2512         if (s->schema_part.highwatermark.tmp_highest_usn > s->schema_part.highwatermark.highest_usn) {
2513                 becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->schema_part,
2514                                                      becomeDC_drsuapi3_pull_schema_recv);
2515                 return;
2516         }
2517
2518         becomeDC_drsuapi3_pull_config_send(s);
2519 }
2520
2521 static void becomeDC_drsuapi3_pull_config_recv(struct rpc_request *req);
2522
2523 static void becomeDC_drsuapi3_pull_config_send(struct libnet_BecomeDC_state *s)
2524 {
2525         s->config_part.nc.guid  = GUID_zero();
2526         s->config_part.nc.sid   = s->zero_sid;
2527         s->config_part.nc.dn    = s->forest.config_dn_str;
2528
2529         s->config_part.destination_dsa_guid     = s->drsuapi2.bind_guid;
2530
2531         s->config_part.replica_flags    = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
2532                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
2533                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS
2534                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_FULL_IN_PROGRESS
2535                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_NEVER_SYNCED
2536                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_COMPRESS_CHANGES;
2537
2538         s->config_part.store_chunk      = s->callbacks.config_chunk;
2539
2540         becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->config_part,
2541                                              becomeDC_drsuapi3_pull_config_recv);
2542 }
2543
2544 static void becomeDC_drsuapi3_pull_config_recv(struct rpc_request *req)
2545 {
2546         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2547                                           struct libnet_BecomeDC_state);
2548         struct composite_context *c = s->creq;
2549         struct drsuapi_DsGetNCChanges *r = talloc_get_type(req->ndr.struct_ptr,
2550                                            struct drsuapi_DsGetNCChanges);
2551         WERROR status;
2552
2553         bool print = false;
2554
2555         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2556                 print = true;
2557         }
2558
2559         c->status = dcerpc_ndr_request_recv(req);
2560         if (!composite_is_ok(c)) return;
2561
2562         if (print) {
2563                 NDR_PRINT_OUT_DEBUG(drsuapi_DsGetNCChanges, r);
2564         }
2565
2566         status = becomeDC_drsuapi_pull_partition_recv(s, &s->drsuapi2, &s->drsuapi3, &s->config_part, r);
2567         if (!W_ERROR_IS_OK(status)) {
2568                 composite_error(c, werror_to_ntstatus(status));
2569                 return;
2570         }
2571
2572         talloc_free(r);
2573
2574         if (s->config_part.highwatermark.tmp_highest_usn > s->config_part.highwatermark.highest_usn) {
2575                 becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->config_part,
2576                                                      becomeDC_drsuapi3_pull_config_recv);
2577                 return;
2578         }
2579
2580         becomeDC_connect_ldap2(s);
2581 }
2582
2583 static void becomeDC_drsuapi3_pull_domain_recv(struct rpc_request *req);
2584
2585 static void becomeDC_drsuapi3_pull_domain_send(struct libnet_BecomeDC_state *s)
2586 {
2587         s->domain_part.nc.guid  = GUID_zero();
2588         s->domain_part.nc.sid   = s->zero_sid;
2589         s->domain_part.nc.dn    = s->domain.dn_str;
2590
2591         s->domain_part.destination_dsa_guid     = s->drsuapi2.bind_guid;
2592
2593         s->domain_part.replica_flags    = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
2594                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
2595                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS
2596                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_FULL_IN_PROGRESS
2597                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_NEVER_SYNCED
2598                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_COMPRESS_CHANGES;
2599
2600         s->domain_part.store_chunk      = s->callbacks.domain_chunk;
2601
2602         becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->domain_part,
2603                                              becomeDC_drsuapi3_pull_domain_recv);
2604 }
2605
2606 static void becomeDC_drsuapi_update_refs_send(struct libnet_BecomeDC_state *s,
2607                                               struct becomeDC_drsuapi *drsuapi,
2608                                               struct libnet_BecomeDC_Partition *partition,
2609                                               void (*recv_fn)(struct rpc_request *req));
2610 static void becomeDC_drsuapi2_update_refs_schema_recv(struct rpc_request *req);
2611
2612 static void becomeDC_drsuapi3_pull_domain_recv(struct rpc_request *req)
2613 {
2614         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2615                                           struct libnet_BecomeDC_state);
2616         struct composite_context *c = s->creq;
2617         struct drsuapi_DsGetNCChanges *r = talloc_get_type(req->ndr.struct_ptr,
2618                                            struct drsuapi_DsGetNCChanges);
2619         WERROR status;
2620         bool print = false;
2621
2622         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2623                 print = true;
2624         }
2625
2626         c->status = dcerpc_ndr_request_recv(req);
2627         if (!composite_is_ok(c)) return;
2628
2629         if (print) {
2630                 NDR_PRINT_OUT_DEBUG(drsuapi_DsGetNCChanges, r);
2631         }
2632
2633         status = becomeDC_drsuapi_pull_partition_recv(s, &s->drsuapi2, &s->drsuapi3, &s->domain_part, r);
2634         if (!W_ERROR_IS_OK(status)) {
2635                 composite_error(c, werror_to_ntstatus(status));
2636                 return;
2637         }
2638
2639         talloc_free(r);
2640
2641         if (s->domain_part.highwatermark.tmp_highest_usn > s->domain_part.highwatermark.highest_usn) {
2642                 becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->domain_part,
2643                                                      becomeDC_drsuapi3_pull_domain_recv);
2644                 return;
2645         }
2646
2647         becomeDC_drsuapi_update_refs_send(s, &s->drsuapi2, &s->schema_part,
2648                                           becomeDC_drsuapi2_update_refs_schema_recv);
2649 }
2650
2651 static void becomeDC_drsuapi_update_refs_send(struct libnet_BecomeDC_state *s,
2652                                               struct becomeDC_drsuapi *drsuapi,
2653                                               struct libnet_BecomeDC_Partition *partition,
2654                                               void (*recv_fn)(struct rpc_request *req))
2655 {
2656         struct composite_context *c = s->creq;
2657         struct rpc_request *req;
2658         struct drsuapi_DsReplicaUpdateRefs *r;
2659         const char *ntds_guid_str;
2660         const char *ntds_dns_name;
2661
2662         r = talloc(s, struct drsuapi_DsReplicaUpdateRefs);
2663         if (composite_nomem(r, c)) return;
2664
2665         ntds_guid_str = GUID_string(r, &s->dest_dsa.ntds_guid);
2666         if (composite_nomem(ntds_guid_str, c)) return;
2667
2668         ntds_dns_name = talloc_asprintf(r, "%s._msdcs.%s",
2669                                         ntds_guid_str,
2670                                         s->domain.dns_name);
2671         if (composite_nomem(ntds_dns_name, c)) return;
2672
2673         r->in.bind_handle               = &drsuapi->bind_handle;
2674         r->in.level                     = 1;
2675         r->in.req.req1.naming_context   = &partition->nc;
2676         r->in.req.req1.dest_dsa_dns_name= ntds_dns_name;
2677         r->in.req.req1.dest_dsa_guid    = s->dest_dsa.ntds_guid;
2678         r->in.req.req1.options          = DRSUAPI_DS_REPLICA_UPDATE_ADD_REFERENCE
2679                                         | DRSUAPI_DS_REPLICA_UPDATE_DELETE_REFERENCE
2680                                         | DRSUAPI_DS_REPLICA_UPDATE_0x00000010;
2681
2682         req = dcerpc_drsuapi_DsReplicaUpdateRefs_send(drsuapi->pipe, r, r);
2683         composite_continue_rpc(c, req, recv_fn, s);
2684 }
2685
2686 static void becomeDC_drsuapi2_update_refs_config_recv(struct rpc_request *req);
2687
2688 static void becomeDC_drsuapi2_update_refs_schema_recv(struct rpc_request *req)
2689 {
2690         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2691                                           struct libnet_BecomeDC_state);
2692         struct composite_context *c = s->creq;
2693         struct drsuapi_DsReplicaUpdateRefs *r = talloc_get_type(req->ndr.struct_ptr,
2694                                            struct drsuapi_DsReplicaUpdateRefs);
2695         bool print = false;
2696
2697         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2698                 print = true;
2699         }
2700
2701         c->status = dcerpc_ndr_request_recv(req);
2702         if (!composite_is_ok(c)) return;
2703
2704         if (print) {
2705                 NDR_PRINT_OUT_DEBUG(drsuapi_DsReplicaUpdateRefs, r);
2706         }
2707
2708         if (!W_ERROR_IS_OK(r->out.result)) {
2709                 composite_error(c, werror_to_ntstatus(r->out.result));
2710                 return;
2711         }
2712
2713         talloc_free(r);
2714
2715         becomeDC_drsuapi_update_refs_send(s, &s->drsuapi2, &s->config_part,
2716                                           becomeDC_drsuapi2_update_refs_config_recv);
2717 }
2718
2719 static void becomeDC_drsuapi2_update_refs_domain_recv(struct rpc_request *req);
2720
2721 static void becomeDC_drsuapi2_update_refs_config_recv(struct rpc_request *req)
2722 {
2723         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2724                                           struct libnet_BecomeDC_state);
2725         struct composite_context *c = s->creq;
2726         struct drsuapi_DsReplicaUpdateRefs *r = talloc_get_type(req->ndr.struct_ptr,
2727                                            struct drsuapi_DsReplicaUpdateRefs);
2728
2729         c->status = dcerpc_ndr_request_recv(req);
2730         if (!composite_is_ok(c)) return;
2731
2732         if (!W_ERROR_IS_OK(r->out.result)) {
2733                 composite_error(c, werror_to_ntstatus(r->out.result));
2734                 return;
2735         }
2736
2737         talloc_free(r);
2738
2739         becomeDC_drsuapi_update_refs_send(s, &s->drsuapi2, &s->domain_part,
2740                                           becomeDC_drsuapi2_update_refs_domain_recv);
2741 }
2742
2743 static void becomeDC_drsuapi2_update_refs_domain_recv(struct rpc_request *req)
2744 {
2745         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2746                                           struct libnet_BecomeDC_state);
2747         struct composite_context *c = s->creq;
2748         struct drsuapi_DsReplicaUpdateRefs *r = talloc_get_type(req->ndr.struct_ptr,
2749                                            struct drsuapi_DsReplicaUpdateRefs);
2750
2751         c->status = dcerpc_ndr_request_recv(req);
2752         if (!composite_is_ok(c)) return;
2753
2754         if (!W_ERROR_IS_OK(r->out.result)) {
2755                 composite_error(c, werror_to_ntstatus(r->out.result));
2756                 return;
2757         }
2758
2759         talloc_free(r);
2760
2761         /* TODO: use DDNS updates and register dns names */
2762         composite_done(c);
2763 }
2764
2765 static NTSTATUS becomeDC_ldap2_modify_computer(struct libnet_BecomeDC_state *s)
2766 {
2767         int ret;
2768         struct ldb_message *msg;
2769         uint32_t i;
2770         uint32_t user_account_control = UF_SERVER_TRUST_ACCOUNT |
2771                                         UF_TRUSTED_FOR_DELEGATION;
2772
2773         /* as the value is already as we want it to be, we're done */
2774         if (s->dest_dsa.user_account_control == user_account_control) {
2775                 return NT_STATUS_OK;
2776         }
2777
2778         /* make a 'modify' msg, and only for serverReference */
2779         msg = ldb_msg_new(s);
2780         NT_STATUS_HAVE_NO_MEMORY(msg);
2781         msg->dn = ldb_dn_new(msg, s->ldap2.ldb, s->dest_dsa.computer_dn_str);
2782         NT_STATUS_HAVE_NO_MEMORY(msg->dn);
2783
2784         ret = ldb_msg_add_fmt(msg, "userAccountControl", "%u", user_account_control);
2785         if (ret != 0) {
2786                 talloc_free(msg);
2787                 return NT_STATUS_NO_MEMORY;
2788         }
2789
2790         /* mark all the message elements (should be just one)
2791            as LDB_FLAG_MOD_REPLACE */
2792         for (i=0;i<msg->num_elements;i++) {
2793                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
2794         }
2795
2796         ret = ldb_modify(s->ldap2.ldb, msg);
2797         talloc_free(msg);
2798         if (ret != LDB_SUCCESS) {
2799                 return NT_STATUS_LDAP(ret);
2800         }
2801
2802         s->dest_dsa.user_account_control = user_account_control;
2803
2804         return NT_STATUS_OK;
2805 }
2806
2807 static NTSTATUS becomeDC_ldap2_move_computer(struct libnet_BecomeDC_state *s)
2808 {
2809         int ret;
2810         struct ldb_result *r;
2811         struct ldb_dn *basedn;
2812         struct ldb_dn *old_dn;
2813         struct ldb_dn *new_dn;
2814         static const char *_1_1_attrs[] = {
2815                 "1.1",
2816                 NULL
2817         };
2818
2819         basedn = ldb_dn_new_fmt(s, s->ldap2.ldb, "<WKGUID=a361b2ffffd211d1aa4b00c04fd7d83a,%s>",
2820                                 s->domain.dn_str);
2821         NT_STATUS_HAVE_NO_MEMORY(basedn);
2822
2823         ret = ldb_search(s->ldap2.ldb, basedn, LDB_SCOPE_BASE,
2824                          "(objectClass=*)", _1_1_attrs, &r);
2825         talloc_free(basedn);
2826         if (ret != LDB_SUCCESS) {
2827                 return NT_STATUS_LDAP(ret);
2828         } else if (r->count != 1) {
2829                 talloc_free(r);
2830                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
2831         }
2832
2833         old_dn = ldb_dn_new(r, s->ldap2.ldb, s->dest_dsa.computer_dn_str);
2834         NT_STATUS_HAVE_NO_MEMORY(old_dn);
2835
2836         new_dn = r->msgs[0]->dn;
2837
2838         if (!ldb_dn_add_child_fmt(new_dn, "CN=%s", s->dest_dsa.netbios_name)) {
2839                 talloc_free(r);
2840                 return NT_STATUS_NO_MEMORY;
2841         }
2842
2843         if (ldb_dn_compare(old_dn, new_dn) == 0) {
2844                 /* we don't need to rename if the old and new dn match */
2845                 talloc_free(r);
2846                 return NT_STATUS_OK;
2847         }
2848
2849         ret = ldb_rename(s->ldap2.ldb, old_dn, new_dn);
2850         if (ret != LDB_SUCCESS) {
2851                 talloc_free(r);
2852                 return NT_STATUS_LDAP(ret);
2853         }
2854
2855         s->dest_dsa.computer_dn_str = ldb_dn_alloc_linearized(s, new_dn);
2856         NT_STATUS_HAVE_NO_MEMORY(s->dest_dsa.computer_dn_str);
2857
2858         talloc_free(r);
2859
2860         return NT_STATUS_OK;
2861 }
2862
2863 static void becomeDC_connect_ldap2(struct libnet_BecomeDC_state *s)
2864 {
2865         struct composite_context *c = s->creq;
2866
2867         c->status = becomeDC_ldap_connect(s, &s->ldap2);
2868         if (!composite_is_ok(c)) return;
2869
2870         c->status = becomeDC_ldap2_modify_computer(s);
2871         if (!composite_is_ok(c)) return;
2872
2873         c->status = becomeDC_ldap2_move_computer(s);
2874         if (!composite_is_ok(c)) return;
2875
2876         becomeDC_drsuapi3_pull_domain_send(s);
2877 }
2878
2879 struct composite_context *libnet_BecomeDC_send(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_BecomeDC *r)
2880 {
2881         struct composite_context *c;
2882         struct libnet_BecomeDC_state *s;
2883         char *tmp_name;
2884
2885         c = composite_create(mem_ctx, ctx->event_ctx);
2886         if (c == NULL) return NULL;
2887
2888         s = talloc_zero(c, struct libnet_BecomeDC_state);
2889         if (composite_nomem(s, c)) return c;
2890         c->private_data = s;
2891         s->creq         = c;
2892         s->libnet       = ctx;
2893
2894         /* Domain input */
2895         s->domain.dns_name      = talloc_strdup(s, r->in.domain_dns_name);
2896         if (composite_nomem(s->domain.dns_name, c)) return c;
2897         s->domain.netbios_name  = talloc_strdup(s, r->in.domain_netbios_name);
2898         if (composite_nomem(s->domain.netbios_name, c)) return c;
2899         s->domain.sid           = dom_sid_dup(s, r->in.domain_sid);
2900         if (composite_nomem(s->domain.sid, c)) return c;
2901
2902         /* Source DSA input */
2903         s->source_dsa.address   = talloc_strdup(s, r->in.source_dsa_address);
2904         if (composite_nomem(s->source_dsa.address, c)) return c;
2905
2906         /* Destination DSA input */
2907         s->dest_dsa.netbios_name= talloc_strdup(s, r->in.dest_dsa_netbios_name);
2908         if (composite_nomem(s->dest_dsa.netbios_name, c)) return c;
2909
2910         /* Destination DSA dns_name construction */
2911         tmp_name        = strlower_talloc(s, s->dest_dsa.netbios_name);
2912         if (composite_nomem(tmp_name, c)) return c;
2913         tmp_name        = talloc_asprintf_append_buffer(tmp_name, ".%s",s->domain.dns_name);
2914         if (composite_nomem(tmp_name, c)) return c;
2915         s->dest_dsa.dns_name    = tmp_name;
2916
2917         /* Callback function pointers */
2918         s->callbacks = r->in.callbacks;
2919
2920         becomeDC_send_cldap(s);
2921         return c;
2922 }
2923
2924 NTSTATUS libnet_BecomeDC_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, struct libnet_BecomeDC *r)
2925 {
2926         NTSTATUS status;
2927
2928         status = composite_wait(c);
2929
2930         ZERO_STRUCT(r->out);
2931
2932         talloc_free(c);
2933         return status;
2934 }
2935
2936 NTSTATUS libnet_BecomeDC(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_BecomeDC *r)
2937 {
2938         NTSTATUS status;
2939         struct composite_context *c;
2940         c = libnet_BecomeDC_send(ctx, mem_ctx, r);
2941         status = libnet_BecomeDC_recv(c, mem_ctx, r);
2942         return status;
2943 }