Merge branch 'v4-0-test' of git://git.samba.org/samba into 4-0-abartlet
[sfrench/samba-autobuild/.git] / source4 / libnet / libnet_become_dc.c
1 /*
2    Unix SMB/CIFS implementation.
3
4    Copyright (C) Stefan Metzmacher <metze@samba.org> 2006
5
6    This program is free software; you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 */
19
20 #include "includes.h"
21 #include "libnet/libnet.h"
22 #include "libcli/composite/composite.h"
23 #include "libcli/cldap/cldap.h"
24 #include "lib/ldb/include/ldb.h"
25 #include "lib/ldb/include/ldb_errors.h"
26 #include "lib/ldb_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.dest_port        = lp_cldap_port(s->libnet->lp_ctx);
742         s->cldap.io.in.realm            = s->domain.dns_name;
743         s->cldap.io.in.host             = s->dest_dsa.netbios_name;
744         s->cldap.io.in.user             = NULL;
745         s->cldap.io.in.domain_guid      = NULL;
746         s->cldap.io.in.domain_sid       = NULL;
747         s->cldap.io.in.acct_control     = -1;
748         s->cldap.io.in.version          = 6;
749
750         s->cldap.sock = cldap_socket_init(s, s->libnet->event_ctx);
751         if (composite_nomem(s->cldap.sock, c)) return;
752
753         req = cldap_netlogon_send(s->cldap.sock, &s->cldap.io);
754         if (composite_nomem(req, c)) return;
755         req->async.fn           = becomeDC_recv_cldap;
756         req->async.private      = s;
757 }
758
759 static void becomeDC_connect_ldap1(struct libnet_BecomeDC_state *s);
760
761 static void becomeDC_recv_cldap(struct cldap_request *req)
762 {
763         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private,
764                                           struct libnet_BecomeDC_state);
765         struct composite_context *c = s->creq;
766
767         c->status = cldap_netlogon_recv(req, s, &s->cldap.io);
768         if (!composite_is_ok(c)) return;
769
770         s->cldap.netlogon5 = s->cldap.io.out.netlogon.logon5;
771
772         s->domain.dns_name              = s->cldap.netlogon5.dns_domain;
773         s->domain.netbios_name          = s->cldap.netlogon5.domain;
774         s->domain.guid                  = s->cldap.netlogon5.domain_uuid;
775
776         s->forest.dns_name              = s->cldap.netlogon5.forest;
777
778         s->source_dsa.dns_name          = s->cldap.netlogon5.pdc_dns_name;
779         s->source_dsa.netbios_name      = s->cldap.netlogon5.pdc_name;
780         s->source_dsa.site_name         = s->cldap.netlogon5.server_site;
781
782         s->dest_dsa.site_name           = s->cldap.netlogon5.client_site;
783
784         becomeDC_connect_ldap1(s);
785 }
786
787 static NTSTATUS becomeDC_ldap_connect(struct libnet_BecomeDC_state *s, 
788                                       struct becomeDC_ldap *ldap)
789 {
790         char *url;
791
792         url = talloc_asprintf(s, "ldap://%s/", s->source_dsa.dns_name);
793         NT_STATUS_HAVE_NO_MEMORY(url);
794
795         ldap->ldb = ldb_wrap_connect(s, s->libnet->lp_ctx, url,
796                                      NULL,
797                                      s->libnet->cred,
798                                      0, NULL);
799         talloc_free(url);
800         if (ldap->ldb == NULL) {
801                 return NT_STATUS_UNEXPECTED_NETWORK_ERROR;
802         }
803
804         return NT_STATUS_OK;
805 }
806
807 static NTSTATUS becomeDC_ldap1_rootdse(struct libnet_BecomeDC_state *s)
808 {
809         int ret;
810         struct ldb_result *r;
811         struct ldb_dn *basedn;
812         static const char *attrs[] = {
813                 "*",
814                 NULL
815         };
816
817         basedn = ldb_dn_new(s, s->ldap1.ldb, NULL);
818         NT_STATUS_HAVE_NO_MEMORY(basedn);
819
820         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, 
821                          "(objectClass=*)", attrs, &r);
822         talloc_free(basedn);
823         if (ret != LDB_SUCCESS) {
824                 return NT_STATUS_LDAP(ret);
825         } else if (r->count != 1) {
826                 talloc_free(r);
827                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
828         }
829         talloc_steal(s, r);
830
831         s->ldap1.rootdse = r->msgs[0];
832
833         s->domain.dn_str        = ldb_msg_find_attr_as_string(s->ldap1.rootdse, "defaultNamingContext", NULL);
834         if (!s->domain.dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
835
836         s->forest.root_dn_str   = ldb_msg_find_attr_as_string(s->ldap1.rootdse, "rootDomainNamingContext", NULL);
837         if (!s->forest.root_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
838         s->forest.config_dn_str = ldb_msg_find_attr_as_string(s->ldap1.rootdse, "configurationNamingContext", NULL);
839         if (!s->forest.config_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
840         s->forest.schema_dn_str = ldb_msg_find_attr_as_string(s->ldap1.rootdse, "schemaNamingContext", NULL);
841         if (!s->forest.schema_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
842
843         s->source_dsa.server_dn_str     = ldb_msg_find_attr_as_string(s->ldap1.rootdse, "serverName", NULL);
844         if (!s->source_dsa.server_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
845         s->source_dsa.ntds_dn_str       = ldb_msg_find_attr_as_string(s->ldap1.rootdse, "dsServiceName", NULL);
846         if (!s->source_dsa.ntds_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
847
848         return NT_STATUS_OK;
849 }
850
851 static NTSTATUS becomeDC_ldap1_crossref_behavior_version(struct libnet_BecomeDC_state *s)
852 {
853         int ret;
854         struct ldb_result *r;
855         struct ldb_dn *basedn;
856         static const char *attrs[] = {
857                 "msDs-Behavior-Version",
858                 NULL
859         };
860
861         basedn = ldb_dn_new(s, s->ldap1.ldb, s->forest.config_dn_str);
862         NT_STATUS_HAVE_NO_MEMORY(basedn);
863
864         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_ONELEVEL,
865                          "(cn=Partitions)", attrs, &r);
866         talloc_free(basedn);
867         if (ret != LDB_SUCCESS) {
868                 return NT_STATUS_LDAP(ret);
869         } else if (r->count != 1) {
870                 talloc_free(r);
871                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
872         }
873
874         s->forest.crossref_behavior_version = ldb_msg_find_attr_as_uint(r->msgs[0], "msDs-Behavior-Version", 0);
875
876         talloc_free(r);
877         return NT_STATUS_OK;
878 }
879
880 static NTSTATUS becomeDC_ldap1_domain_behavior_version(struct libnet_BecomeDC_state *s)
881 {
882         int ret;
883         struct ldb_result *r;
884         struct ldb_dn *basedn;
885         static const char *attrs[] = {
886                 "msDs-Behavior-Version",
887                 NULL
888         };
889
890         basedn = ldb_dn_new(s, s->ldap1.ldb, s->domain.dn_str);
891         NT_STATUS_HAVE_NO_MEMORY(basedn);
892
893         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE,
894                          "(objectClass=*)", attrs, &r);
895         talloc_free(basedn);
896         if (ret != LDB_SUCCESS) {
897                 return NT_STATUS_LDAP(ret);
898         } else if (r->count != 1) {
899                 talloc_free(r);
900                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
901         }
902
903         s->domain.behavior_version = ldb_msg_find_attr_as_uint(r->msgs[0], "msDs-Behavior-Version", 0);
904
905         talloc_free(r);
906         return NT_STATUS_OK;
907 }
908
909 static NTSTATUS becomeDC_ldap1_schema_object_version(struct libnet_BecomeDC_state *s)
910 {
911         int ret;
912         struct ldb_result *r;
913         struct ldb_dn *basedn;
914         static const char *attrs[] = {
915                 "objectVersion",
916                 NULL
917         };
918
919         basedn = ldb_dn_new(s, s->ldap1.ldb, s->forest.schema_dn_str);
920         NT_STATUS_HAVE_NO_MEMORY(basedn);
921
922         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE,
923                          "(objectClass=*)", attrs, &r);
924         talloc_free(basedn);
925         if (ret != LDB_SUCCESS) {
926                 return NT_STATUS_LDAP(ret);
927         } else if (r->count != 1) {
928                 talloc_free(r);
929                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
930         }
931
932         s->forest.schema_object_version = ldb_msg_find_attr_as_uint(r->msgs[0], "objectVersion", 0);
933
934         talloc_free(r);
935         return NT_STATUS_OK;
936 }
937
938 static NTSTATUS becomeDC_ldap1_w2k3_update_revision(struct libnet_BecomeDC_state *s)
939 {
940         int ret;
941         struct ldb_result *r;
942         struct ldb_dn *basedn;
943         static const char *attrs[] = {
944                 "revision",
945                 NULL
946         };
947
948         basedn = ldb_dn_new_fmt(s, s->ldap1.ldb, "CN=Windows2003Update,CN=DomainUpdates,CN=System,%s",
949                                 s->domain.dn_str);
950         NT_STATUS_HAVE_NO_MEMORY(basedn);
951
952         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE,
953                          "(objectClass=*)", attrs, &r);
954         talloc_free(basedn);
955         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
956                 /* w2k doesn't have this object */
957                 s->domain.w2k3_update_revision = 0;
958                 return NT_STATUS_OK;
959         } else if (ret != LDB_SUCCESS) {
960                 return NT_STATUS_LDAP(ret);
961         } else if (r->count != 1) {
962                 talloc_free(r);
963                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
964         }
965
966         s->domain.w2k3_update_revision = ldb_msg_find_attr_as_uint(r->msgs[0], "revision", 0);
967
968         talloc_free(r);
969         return NT_STATUS_OK;
970 }
971
972 static NTSTATUS becomeDC_ldap1_infrastructure_fsmo(struct libnet_BecomeDC_state *s)
973 {
974         int ret;
975         struct ldb_result *r;
976         struct ldb_dn *basedn;
977         struct ldb_dn *ntds_dn;
978         struct ldb_dn *server_dn;
979         static const char *_1_1_attrs[] = {
980                 "1.1",
981                 NULL
982         };
983         static const char *fsmo_attrs[] = {
984                 "fSMORoleOwner",
985                 NULL
986         };
987         static const char *dns_attrs[] = {
988                 "dnsHostName",
989                 NULL
990         };
991         static const char *guid_attrs[] = {
992                 "objectGUID",
993                 NULL
994         };
995
996         basedn = ldb_dn_new_fmt(s, s->ldap1.ldb, "<WKGUID=2fbac1870ade11d297c400c04fd8d5cd,%s>",
997                                 s->domain.dn_str);
998         NT_STATUS_HAVE_NO_MEMORY(basedn);
999
1000         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE,
1001                          "(objectClass=*)", _1_1_attrs, &r);
1002         talloc_free(basedn);
1003         if (ret != LDB_SUCCESS) {
1004                 return NT_STATUS_LDAP(ret);
1005         } else if (r->count != 1) {
1006                 talloc_free(r);
1007                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1008         }
1009
1010         basedn = talloc_steal(s, r->msgs[0]->dn);
1011         talloc_free(r);
1012
1013         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE,
1014                          "(objectClass=*)", fsmo_attrs, &r);
1015         talloc_free(basedn);
1016         if (ret != LDB_SUCCESS) {
1017                 return NT_STATUS_LDAP(ret);
1018         } else if (r->count != 1) {
1019                 talloc_free(r);
1020                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1021         }
1022
1023         s->infrastructure_fsmo.ntds_dn_str      = samdb_result_string(r->msgs[0], "fSMORoleOwner", NULL);
1024         if (!s->infrastructure_fsmo.ntds_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
1025         talloc_steal(s, s->infrastructure_fsmo.ntds_dn_str);
1026
1027         talloc_free(r);
1028
1029         ntds_dn = ldb_dn_new(s, s->ldap1.ldb, s->infrastructure_fsmo.ntds_dn_str);
1030         NT_STATUS_HAVE_NO_MEMORY(ntds_dn);
1031
1032         server_dn = ldb_dn_get_parent(s, ntds_dn);
1033         NT_STATUS_HAVE_NO_MEMORY(server_dn);
1034
1035         s->infrastructure_fsmo.server_dn_str = ldb_dn_alloc_linearized(s, server_dn);
1036         NT_STATUS_HAVE_NO_MEMORY(s->infrastructure_fsmo.server_dn_str);
1037
1038         ret = ldb_search(s->ldap1.ldb, server_dn, LDB_SCOPE_BASE,
1039                          "(objectClass=*)", dns_attrs, &r);
1040         if (ret != LDB_SUCCESS) {
1041                 return NT_STATUS_LDAP(ret);
1042         } else if (r->count != 1) {
1043                 talloc_free(r);
1044                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1045         }
1046
1047         s->infrastructure_fsmo.dns_name = samdb_result_string(r->msgs[0], "dnsHostName", NULL);
1048         if (!s->infrastructure_fsmo.dns_name) return NT_STATUS_INVALID_NETWORK_RESPONSE;
1049         talloc_steal(s, s->infrastructure_fsmo.dns_name);
1050
1051         talloc_free(r);
1052
1053         ret = ldb_search(s->ldap1.ldb, ntds_dn, LDB_SCOPE_BASE,
1054                          "(objectClass=*)", guid_attrs, &r);
1055         if (ret != LDB_SUCCESS) {
1056                 return NT_STATUS_LDAP(ret);
1057         } else if (r->count != 1) {
1058                 talloc_free(r);
1059                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1060         }
1061
1062         s->infrastructure_fsmo.ntds_guid = samdb_result_guid(r->msgs[0], "objectGUID");
1063
1064         talloc_free(r);
1065
1066         return NT_STATUS_OK;
1067 }
1068
1069 static NTSTATUS becomeDC_ldap1_rid_manager_fsmo(struct libnet_BecomeDC_state *s)
1070 {
1071         int ret;
1072         struct ldb_result *r;
1073         struct ldb_dn *basedn;
1074         const char *reference_dn_str;
1075         struct ldb_dn *ntds_dn;
1076         struct ldb_dn *server_dn;
1077         static const char *rid_attrs[] = {
1078                 "rIDManagerReference",
1079                 NULL
1080         };
1081         static const char *fsmo_attrs[] = {
1082                 "fSMORoleOwner",
1083                 NULL
1084         };
1085         static const char *dns_attrs[] = {
1086                 "dnsHostName",
1087                 NULL
1088         };
1089         static const char *guid_attrs[] = {
1090                 "objectGUID",
1091                 NULL
1092         };
1093
1094         basedn = ldb_dn_new(s, s->ldap1.ldb, s->domain.dn_str);
1095         NT_STATUS_HAVE_NO_MEMORY(basedn);
1096
1097         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE,
1098                          "(objectClass=*)", rid_attrs, &r);
1099         talloc_free(basedn);
1100         if (ret != LDB_SUCCESS) {
1101                 return NT_STATUS_LDAP(ret);
1102         } else if (r->count != 1) {
1103                 talloc_free(r);
1104                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1105         }
1106
1107         reference_dn_str        = samdb_result_string(r->msgs[0], "rIDManagerReference", NULL);
1108         if (!reference_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
1109
1110         basedn = ldb_dn_new(s, s->ldap1.ldb, reference_dn_str);
1111         NT_STATUS_HAVE_NO_MEMORY(basedn);
1112
1113         talloc_free(r);
1114
1115         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE,
1116                          "(objectClass=*)", fsmo_attrs, &r);
1117         talloc_free(basedn);
1118         if (ret != LDB_SUCCESS) {
1119                 return NT_STATUS_LDAP(ret);
1120         } else if (r->count != 1) {
1121                 talloc_free(r);
1122                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1123         }
1124
1125         s->rid_manager_fsmo.ntds_dn_str = samdb_result_string(r->msgs[0], "fSMORoleOwner", NULL);
1126         if (!s->rid_manager_fsmo.ntds_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
1127         talloc_steal(s, s->rid_manager_fsmo.ntds_dn_str);
1128
1129         talloc_free(r);
1130
1131         ntds_dn = ldb_dn_new(s, s->ldap1.ldb, s->rid_manager_fsmo.ntds_dn_str);
1132         NT_STATUS_HAVE_NO_MEMORY(ntds_dn);
1133
1134         server_dn = ldb_dn_get_parent(s, ntds_dn);
1135         NT_STATUS_HAVE_NO_MEMORY(server_dn);
1136
1137         s->rid_manager_fsmo.server_dn_str = ldb_dn_alloc_linearized(s, server_dn);
1138         NT_STATUS_HAVE_NO_MEMORY(s->rid_manager_fsmo.server_dn_str);
1139
1140         ret = ldb_search(s->ldap1.ldb, server_dn, LDB_SCOPE_BASE,
1141                          "(objectClass=*)", dns_attrs, &r);
1142         if (ret != LDB_SUCCESS) {
1143                 return NT_STATUS_LDAP(ret);
1144         } else if (r->count != 1) {
1145                 talloc_free(r);
1146                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1147         }
1148
1149         s->rid_manager_fsmo.dns_name    = samdb_result_string(r->msgs[0], "dnsHostName", NULL);
1150         if (!s->rid_manager_fsmo.dns_name) return NT_STATUS_INVALID_NETWORK_RESPONSE;
1151         talloc_steal(s, s->rid_manager_fsmo.dns_name);
1152
1153         talloc_free(r);
1154
1155         ret = ldb_search(s->ldap1.ldb, ntds_dn, LDB_SCOPE_BASE,
1156                          "(objectClass=*)", guid_attrs, &r);
1157         if (ret != LDB_SUCCESS) {
1158                 return NT_STATUS_LDAP(ret);
1159         } else if (r->count != 1) {
1160                 talloc_free(r);
1161                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1162         }
1163
1164         s->rid_manager_fsmo.ntds_guid = samdb_result_guid(r->msgs[0], "objectGUID");
1165
1166         talloc_free(r);
1167
1168         return NT_STATUS_OK;
1169 }
1170
1171 static NTSTATUS becomeDC_ldap1_site_object(struct libnet_BecomeDC_state *s)
1172 {
1173         int ret;
1174         struct ldb_result *r;
1175         struct ldb_dn *basedn;
1176
1177         basedn = ldb_dn_new_fmt(s, s->ldap1.ldb, "CN=%s,CN=Sites,%s",
1178                                 s->dest_dsa.site_name,
1179                                 s->forest.config_dn_str);
1180         NT_STATUS_HAVE_NO_MEMORY(basedn);
1181
1182         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, 
1183                          "(objectClass=*)", NULL, &r);
1184         talloc_free(basedn);
1185         if (ret != LDB_SUCCESS) {
1186                 return NT_STATUS_LDAP(ret);
1187         } else if (r->count != 1) {
1188                 talloc_free(r);
1189                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1190         }
1191
1192         s->dest_dsa.site_guid = samdb_result_guid(r->msgs[0], "objectGUID");
1193
1194         talloc_free(r);
1195         return NT_STATUS_OK;
1196 }
1197
1198 static NTSTATUS becomeDC_check_options(struct libnet_BecomeDC_state *s)
1199 {
1200         if (!s->callbacks.check_options) return NT_STATUS_OK;
1201
1202         s->_co.domain           = &s->domain;
1203         s->_co.forest           = &s->forest;
1204         s->_co.source_dsa       = &s->source_dsa;
1205
1206         return s->callbacks.check_options(s->callbacks.private_data, &s->_co);
1207 }
1208
1209 static NTSTATUS becomeDC_ldap1_computer_object(struct libnet_BecomeDC_state *s)
1210 {
1211         int ret;
1212         struct ldb_result *r;
1213         struct ldb_dn *basedn;
1214         char *filter;
1215         static const char *attrs[] = {
1216                 "distinguishedName",
1217                 "userAccountControl",
1218                 NULL
1219         };
1220
1221         basedn = ldb_dn_new(s, s->ldap1.ldb, s->domain.dn_str);
1222         NT_STATUS_HAVE_NO_MEMORY(basedn);
1223
1224         filter = talloc_asprintf(basedn, "(&(|(objectClass=user)(objectClass=computer))(sAMAccountName=%s$))",
1225                                  s->dest_dsa.netbios_name);
1226         NT_STATUS_HAVE_NO_MEMORY(filter);
1227
1228         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_SUBTREE, 
1229                          filter, attrs, &r);
1230         talloc_free(basedn);
1231         if (ret != LDB_SUCCESS) {
1232                 return NT_STATUS_LDAP(ret);
1233         } else if (r->count != 1) {
1234                 talloc_free(r);
1235                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1236         }
1237
1238         s->dest_dsa.computer_dn_str     = samdb_result_string(r->msgs[0], "distinguishedName", NULL);
1239         if (!s->dest_dsa.computer_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
1240         talloc_steal(s, s->dest_dsa.computer_dn_str);
1241
1242         s->dest_dsa.user_account_control = samdb_result_uint(r->msgs[0], "userAccountControl", 0);
1243
1244         talloc_free(r);
1245         return NT_STATUS_OK;
1246 }
1247
1248 static NTSTATUS becomeDC_ldap1_server_object_1(struct libnet_BecomeDC_state *s)
1249 {
1250         int ret;
1251         struct ldb_result *r;
1252         struct ldb_dn *basedn;
1253         const char *server_reference_dn_str;
1254         struct ldb_dn *server_reference_dn;
1255         struct ldb_dn *computer_dn;
1256
1257         basedn = ldb_dn_new_fmt(s, s->ldap1.ldb, "CN=%s,CN=Servers,CN=%s,CN=Sites,%s",
1258                                 s->dest_dsa.netbios_name,
1259                                 s->dest_dsa.site_name,
1260                                 s->forest.config_dn_str);
1261         NT_STATUS_HAVE_NO_MEMORY(basedn);
1262
1263         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, 
1264                          "(objectClass=*)", NULL, &r);
1265         talloc_free(basedn);
1266         if (ret == LDB_ERR_NO_SUCH_OBJECT) {
1267                 /* if the object doesn't exist, we'll create it later */
1268                 return NT_STATUS_OK;
1269         } else if (ret != LDB_SUCCESS) {
1270                 return NT_STATUS_LDAP(ret);
1271         } else if (r->count != 1) {
1272                 talloc_free(r);
1273                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1274         }
1275
1276         server_reference_dn_str = samdb_result_string(r->msgs[0], "serverReference", NULL);
1277         if (server_reference_dn_str) {
1278                 server_reference_dn     = ldb_dn_new(r, s->ldap1.ldb, server_reference_dn_str);
1279                 NT_STATUS_HAVE_NO_MEMORY(server_reference_dn);
1280
1281                 computer_dn             = ldb_dn_new(r, s->ldap1.ldb, s->dest_dsa.computer_dn_str);
1282                 NT_STATUS_HAVE_NO_MEMORY(computer_dn);
1283
1284                 /*
1285                  * if the server object belongs to another DC in another domain in the forest,
1286                  * we should not touch this object!
1287                  */
1288                 if (ldb_dn_compare(computer_dn, server_reference_dn) != 0) {
1289                         talloc_free(r);
1290                         return NT_STATUS_OBJECT_NAME_COLLISION;
1291                 }
1292         }
1293
1294         /* if the server object is already for the dest_dsa, then we don't need to create it */
1295         s->dest_dsa.server_dn_str       = samdb_result_string(r->msgs[0], "distinguishedName", NULL);
1296         if (!s->dest_dsa.server_dn_str) return NT_STATUS_INVALID_NETWORK_RESPONSE;
1297         talloc_steal(s, s->dest_dsa.server_dn_str);
1298
1299         talloc_free(r);
1300         return NT_STATUS_OK;
1301 }
1302
1303 static NTSTATUS becomeDC_ldap1_server_object_2(struct libnet_BecomeDC_state *s)
1304 {
1305         int ret;
1306         struct ldb_result *r;
1307         struct ldb_dn *basedn;
1308         const char *server_reference_bl_dn_str;
1309         static const char *attrs[] = {
1310                 "serverReferenceBL",
1311                 NULL
1312         };
1313
1314         /* if the server_dn_str has a valid value, we skip this lookup */
1315         if (s->dest_dsa.server_dn_str) return NT_STATUS_OK;
1316
1317         basedn = ldb_dn_new(s, s->ldap1.ldb, s->dest_dsa.computer_dn_str);
1318         NT_STATUS_HAVE_NO_MEMORY(basedn);
1319
1320         ret = ldb_search(s->ldap1.ldb, basedn, LDB_SCOPE_BASE, 
1321                          "(objectClass=*)", attrs, &r);
1322         talloc_free(basedn);
1323         if (ret != LDB_SUCCESS) {
1324                 return NT_STATUS_LDAP(ret);
1325         } else if (r->count != 1) {
1326                 talloc_free(r);
1327                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
1328         }
1329
1330         server_reference_bl_dn_str = samdb_result_string(r->msgs[0], "serverReferenceBL", NULL);
1331         if (!server_reference_bl_dn_str) {
1332                 /* if no back link is present, we're done for this function */
1333                 talloc_free(r);
1334                 return NT_STATUS_OK;
1335         }
1336
1337         /* if the server object is already for the dest_dsa, then we don't need to create it */
1338         s->dest_dsa.server_dn_str       = samdb_result_string(r->msgs[0], "serverReferenceBL", NULL);
1339         if (s->dest_dsa.server_dn_str) {
1340                 /* if a back link is present, we know that the server object is present */
1341                 talloc_steal(s, s->dest_dsa.server_dn_str);
1342         }
1343
1344         talloc_free(r);
1345         return NT_STATUS_OK;
1346 }
1347
1348 static NTSTATUS becomeDC_ldap1_server_object_add(struct libnet_BecomeDC_state *s)
1349 {
1350         int ret;
1351         struct ldb_message *msg;
1352         char *server_dn_str;
1353
1354         /* if the server_dn_str has a valid value, we skip this lookup */
1355         if (s->dest_dsa.server_dn_str) return NT_STATUS_OK;
1356
1357         msg = ldb_msg_new(s);
1358         NT_STATUS_HAVE_NO_MEMORY(msg);
1359
1360         msg->dn = ldb_dn_new_fmt(msg, s->ldap1.ldb, "CN=%s,CN=Servers,CN=%s,CN=Sites,%s",
1361                                  s->dest_dsa.netbios_name,
1362                                  s->dest_dsa.site_name,
1363                                  s->forest.config_dn_str);
1364         NT_STATUS_HAVE_NO_MEMORY(msg->dn);
1365
1366         ret = ldb_msg_add_string(msg, "objectClass", "server");
1367         if (ret != 0) {
1368                 talloc_free(msg);
1369                 return NT_STATUS_NO_MEMORY;
1370         }
1371         ret = ldb_msg_add_string(msg, "systemFlags", "50000000");
1372         if (ret != 0) {
1373                 talloc_free(msg);
1374                 return NT_STATUS_NO_MEMORY;
1375         }
1376         ret = ldb_msg_add_string(msg, "serverReference", s->dest_dsa.computer_dn_str);
1377         if (ret != 0) {
1378                 talloc_free(msg);
1379                 return NT_STATUS_NO_MEMORY;
1380         }
1381
1382         server_dn_str = ldb_dn_alloc_linearized(s, msg->dn);
1383         NT_STATUS_HAVE_NO_MEMORY(server_dn_str);
1384
1385         ret = ldb_add(s->ldap1.ldb, msg);
1386         talloc_free(msg);
1387         if (ret != LDB_SUCCESS) {
1388                 talloc_free(server_dn_str);
1389                 return NT_STATUS_LDAP(ret);
1390         }
1391
1392         s->dest_dsa.server_dn_str = server_dn_str;
1393
1394         return NT_STATUS_OK;
1395 }
1396
1397 static NTSTATUS becomeDC_ldap1_server_object_modify(struct libnet_BecomeDC_state *s)
1398 {
1399         int ret;
1400         struct ldb_message *msg;
1401         uint32_t i;
1402
1403         /* make a 'modify' msg, and only for serverReference */
1404         msg = ldb_msg_new(s);
1405         NT_STATUS_HAVE_NO_MEMORY(msg);
1406         msg->dn = ldb_dn_new(msg, s->ldap1.ldb, s->dest_dsa.server_dn_str);
1407         NT_STATUS_HAVE_NO_MEMORY(msg->dn);
1408
1409         ret = ldb_msg_add_string(msg, "serverReference", s->dest_dsa.computer_dn_str);
1410         if (ret != 0) {
1411                 talloc_free(msg);
1412                 return NT_STATUS_NO_MEMORY;
1413         }
1414
1415         /* mark all the message elements (should be just one)
1416            as LDB_FLAG_MOD_ADD */
1417         for (i=0;i<msg->num_elements;i++) {
1418                 msg->elements[i].flags = LDB_FLAG_MOD_ADD;
1419         }
1420
1421         ret = ldb_modify(s->ldap1.ldb, msg);
1422         if (ret == LDB_SUCCESS) {
1423                 talloc_free(msg);
1424                 return NT_STATUS_OK;
1425         } else if (ret == LDB_ERR_ATTRIBUTE_OR_VALUE_EXISTS) {
1426                 /* retry with LDB_FLAG_MOD_REPLACE */
1427         } else {
1428                 talloc_free(msg);
1429                 return NT_STATUS_LDAP(ret);
1430         }
1431
1432         /* mark all the message elements (should be just one)
1433            as LDB_FLAG_MOD_REPLACE */
1434         for (i=0;i<msg->num_elements;i++) {
1435                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
1436         }
1437
1438         ret = ldb_modify(s->ldap1.ldb, msg);
1439         talloc_free(msg);
1440         if (ret != LDB_SUCCESS) {
1441                 return NT_STATUS_LDAP(ret);
1442         }
1443
1444         return NT_STATUS_OK;
1445 }
1446
1447 static void becomeDC_drsuapi_connect_send(struct libnet_BecomeDC_state *s,
1448                                           struct becomeDC_drsuapi *drsuapi,
1449                                           void (*recv_fn)(struct composite_context *req));
1450 static void becomeDC_drsuapi1_connect_recv(struct composite_context *req);
1451 static void becomeDC_connect_ldap2(struct libnet_BecomeDC_state *s);
1452
1453 static void becomeDC_connect_ldap1(struct libnet_BecomeDC_state *s)
1454 {
1455         struct composite_context *c = s->creq;
1456
1457         c->status = becomeDC_ldap_connect(s, &s->ldap1);
1458         if (!composite_is_ok(c)) return;
1459
1460         c->status = becomeDC_ldap1_rootdse(s);
1461         if (!composite_is_ok(c)) return;
1462
1463         c->status = becomeDC_ldap1_crossref_behavior_version(s);
1464         if (!composite_is_ok(c)) return;
1465
1466         c->status = becomeDC_ldap1_domain_behavior_version(s);
1467         if (!composite_is_ok(c)) return;
1468
1469         c->status = becomeDC_ldap1_schema_object_version(s);
1470         if (!composite_is_ok(c)) return;
1471
1472         c->status = becomeDC_ldap1_w2k3_update_revision(s);
1473         if (!composite_is_ok(c)) return;
1474
1475         c->status = becomeDC_ldap1_infrastructure_fsmo(s);
1476         if (!composite_is_ok(c)) return;
1477
1478         c->status = becomeDC_ldap1_rid_manager_fsmo(s);
1479         if (!composite_is_ok(c)) return;
1480
1481         c->status = becomeDC_ldap1_site_object(s);
1482         if (!composite_is_ok(c)) return;
1483
1484         c->status = becomeDC_check_options(s);
1485         if (!composite_is_ok(c)) return;
1486
1487         c->status = becomeDC_ldap1_computer_object(s);
1488         if (!composite_is_ok(c)) return;
1489
1490         c->status = becomeDC_ldap1_server_object_1(s);
1491         if (!composite_is_ok(c)) return;
1492
1493         c->status = becomeDC_ldap1_server_object_2(s);
1494         if (!composite_is_ok(c)) return;
1495
1496         c->status = becomeDC_ldap1_server_object_add(s);
1497         if (!composite_is_ok(c)) return;
1498
1499         c->status = becomeDC_ldap1_server_object_modify(s);
1500         if (!composite_is_ok(c)) return;
1501
1502         becomeDC_drsuapi_connect_send(s, &s->drsuapi1, becomeDC_drsuapi1_connect_recv);
1503 }
1504
1505 static void becomeDC_drsuapi_connect_send(struct libnet_BecomeDC_state *s,
1506                                           struct becomeDC_drsuapi *drsuapi,
1507                                           void (*recv_fn)(struct composite_context *req))
1508 {
1509         struct composite_context *c = s->creq;
1510         struct composite_context *creq;
1511         char *binding_str;
1512
1513         drsuapi->s = s;
1514
1515         if (!drsuapi->binding) {
1516                 if (lp_parm_bool(s->libnet->lp_ctx, NULL, "become_dc", "print", false)) {
1517                         binding_str = talloc_asprintf(s, "ncacn_ip_tcp:%s[krb5,print,seal]", s->source_dsa.dns_name);
1518                         if (composite_nomem(binding_str, c)) return;
1519                 } else {
1520                         binding_str = talloc_asprintf(s, "ncacn_ip_tcp:%s[krb5,seal]", s->source_dsa.dns_name);
1521                         if (composite_nomem(binding_str, c)) return;
1522                 }
1523                 c->status = dcerpc_parse_binding(s, binding_str, &drsuapi->binding);
1524                 talloc_free(binding_str);
1525                 if (!composite_is_ok(c)) return;
1526         }
1527
1528         creq = dcerpc_pipe_connect_b_send(s, drsuapi->binding, &ndr_table_drsuapi,
1529                                           s->libnet->cred, s->libnet->event_ctx,
1530                                           s->libnet->lp_ctx);
1531         composite_continue(c, creq, recv_fn, s);
1532 }
1533
1534 static void becomeDC_drsuapi_bind_send(struct libnet_BecomeDC_state *s,
1535                                        struct becomeDC_drsuapi *drsuapi,
1536                                        void (*recv_fn)(struct rpc_request *req));
1537 static void becomeDC_drsuapi1_bind_recv(struct rpc_request *req);
1538
1539 static void becomeDC_drsuapi1_connect_recv(struct composite_context *req)
1540 {
1541         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
1542                                           struct libnet_BecomeDC_state);
1543         struct composite_context *c = s->creq;
1544
1545         c->status = dcerpc_pipe_connect_b_recv(req, s, &s->drsuapi1.pipe);
1546         if (!composite_is_ok(c)) return;
1547
1548         c->status = gensec_session_key(s->drsuapi1.pipe->conn->security_state.generic_state,
1549                                        &s->drsuapi1.gensec_skey);
1550         if (!composite_is_ok(c)) return;
1551
1552         becomeDC_drsuapi_bind_send(s, &s->drsuapi1, becomeDC_drsuapi1_bind_recv);
1553 }
1554
1555 static void becomeDC_drsuapi_bind_send(struct libnet_BecomeDC_state *s,
1556                                        struct becomeDC_drsuapi *drsuapi,
1557                                        void (*recv_fn)(struct rpc_request *req))
1558 {
1559         struct composite_context *c = s->creq;
1560         struct rpc_request *req;
1561         struct drsuapi_DsBindInfo28 *bind_info28;
1562
1563         GUID_from_string(DRSUAPI_DS_BIND_GUID_W2K3, &drsuapi->bind_guid);
1564
1565         bind_info28                             = &drsuapi->local_info28;
1566         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_BASE;
1567         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_ASYNC_REPLICATION;
1568         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_REMOVEAPI;
1569         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_MOVEREQ_V2;
1570         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GETCHG_COMPRESS;
1571         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V1;
1572         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_RESTORE_USN_OPTIMIZATION;
1573         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_KCC_EXECUTE;
1574         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_ADDENTRY_V2;
1575         if (s->domain.behavior_version == 2) {
1576                 /* TODO: find out how this is really triggered! */
1577                 bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_LINKED_VALUE_REPLICATION;
1578         }
1579         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V2;
1580         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_INSTANCE_TYPE_NOT_REQ_ON_MOD;
1581         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_CRYPTO_BIND;
1582         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GET_REPL_INFO;
1583         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_STRONG_ENCRYPTION;
1584         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_DCINFO_V01;
1585         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_TRANSITIVE_MEMBERSHIP;
1586         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_ADD_SID_HISTORY;
1587         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_POST_BETA3;
1588         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_00100000;
1589         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GET_MEMBERSHIPS2;
1590         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V6;
1591         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_NONDOMAIN_NCS;
1592         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8;
1593         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V5;
1594         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V6;
1595         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_ADDENTRYREPLY_V3;
1596         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_GETCHGREPLY_V7;
1597         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_VERIFY_OBJECT;
1598 #if 0 /* we don't support XPRESS compression yet */
1599         bind_info28->supported_extensions       |= DRSUAPI_SUPPORTED_EXTENSION_XPRESS_COMPRESS;
1600 #endif
1601         bind_info28->site_guid                  = s->dest_dsa.site_guid;
1602         if (s->domain.behavior_version == 2) {
1603                 /* TODO: find out how this is really triggered! */
1604                 bind_info28->u1                         = 528;
1605         } else {
1606                 bind_info28->u1                         = 516;
1607         }
1608         bind_info28->repl_epoch                 = 0;
1609
1610         drsuapi->bind_info_ctr.length           = 28;
1611         drsuapi->bind_info_ctr.info.info28      = *bind_info28;
1612
1613         drsuapi->bind_r.in.bind_guid = &drsuapi->bind_guid;
1614         drsuapi->bind_r.in.bind_info = &drsuapi->bind_info_ctr;
1615         drsuapi->bind_r.out.bind_handle = &drsuapi->bind_handle;
1616
1617         req = dcerpc_drsuapi_DsBind_send(drsuapi->pipe, s, &drsuapi->bind_r);
1618         composite_continue_rpc(c, req, recv_fn, s);
1619 }
1620
1621 static WERROR becomeDC_drsuapi_bind_recv(struct libnet_BecomeDC_state *s,
1622                                          struct becomeDC_drsuapi *drsuapi)
1623 {
1624         if (!W_ERROR_IS_OK(drsuapi->bind_r.out.result)) {
1625                 return drsuapi->bind_r.out.result;
1626         }
1627
1628         ZERO_STRUCT(drsuapi->remote_info28);
1629         if (drsuapi->bind_r.out.bind_info) {
1630                 switch (drsuapi->bind_r.out.bind_info->length) {
1631                 case 24: {
1632                         struct drsuapi_DsBindInfo24 *info24;
1633                         info24 = &drsuapi->bind_r.out.bind_info->info.info24;
1634                         drsuapi->remote_info28.supported_extensions     = info24->supported_extensions;
1635                         drsuapi->remote_info28.site_guid                = info24->site_guid;
1636                         drsuapi->remote_info28.u1                       = info24->u1;
1637                         drsuapi->remote_info28.repl_epoch               = 0;
1638                         break;
1639                 }
1640                 case 28:
1641                         drsuapi->remote_info28 = drsuapi->bind_r.out.bind_info->info.info28;
1642                         break;
1643                 }
1644         }
1645
1646         return WERR_OK;
1647 }
1648
1649 static void becomeDC_drsuapi1_add_entry_send(struct libnet_BecomeDC_state *s);
1650
1651 static void becomeDC_drsuapi1_bind_recv(struct rpc_request *req)
1652 {
1653         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
1654                                           struct libnet_BecomeDC_state);
1655         struct composite_context *c = s->creq;
1656         WERROR status;
1657
1658         bool print = false;
1659
1660         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
1661                 print = true;
1662         }
1663
1664         c->status = dcerpc_ndr_request_recv(req);
1665         if (!composite_is_ok(c)) return;
1666
1667         if (print) {
1668                 NDR_PRINT_OUT_DEBUG(drsuapi_DsBind, &s->drsuapi1.bind_r);
1669         }
1670
1671         status = becomeDC_drsuapi_bind_recv(s, &s->drsuapi1);
1672         if (!W_ERROR_IS_OK(status)) {
1673                 composite_error(c, werror_to_ntstatus(status));
1674                 return;
1675         }
1676
1677         becomeDC_drsuapi1_add_entry_send(s);
1678 }
1679
1680 static void becomeDC_drsuapi1_add_entry_recv(struct rpc_request *req);
1681
1682 static void becomeDC_drsuapi1_add_entry_send(struct libnet_BecomeDC_state *s)
1683 {
1684         struct composite_context *c = s->creq;
1685         struct rpc_request *req;
1686         struct drsuapi_DsAddEntry *r;
1687         struct drsuapi_DsReplicaObjectIdentifier *identifier;
1688         uint32_t num_attrs, i = 0;
1689         struct drsuapi_DsReplicaAttribute *attrs;
1690         struct smb_iconv_convenience *iconv_convenience = lp_iconv_convenience(s->libnet->lp_ctx);
1691         enum ndr_err_code ndr_err;
1692         bool w2k3;
1693
1694         /* choose a random invocationId */
1695         s->dest_dsa.invocation_id = GUID_random();
1696
1697         /*
1698          * if the schema version indicates w2k3, then
1699          * also send some w2k3 specific attributes
1700          */
1701         if (s->forest.schema_object_version >= 30) {
1702                 w2k3 = true;
1703         } else {
1704                 w2k3 = false;
1705         }
1706
1707         r = talloc_zero(s, struct drsuapi_DsAddEntry);
1708         if (composite_nomem(r, c)) return;
1709
1710         /* setup identifier */
1711         identifier              = talloc(r, struct drsuapi_DsReplicaObjectIdentifier);
1712         if (composite_nomem(identifier, c)) return;
1713         identifier->guid        = GUID_zero();
1714         identifier->sid         = s->zero_sid;
1715         identifier->dn          = talloc_asprintf(identifier, "CN=NTDS Settings,%s",
1716                                                   s->dest_dsa.server_dn_str);
1717         if (composite_nomem(identifier->dn, c)) return;
1718
1719         /* allocate attribute array */
1720         num_attrs       = 11;
1721         attrs           = talloc_array(r, struct drsuapi_DsReplicaAttribute, num_attrs);
1722         if (composite_nomem(attrs, c)) return;
1723
1724         /* ntSecurityDescriptor */
1725         {
1726                 struct drsuapi_DsAttributeValue *vs;
1727                 DATA_BLOB *vd;
1728                 struct security_descriptor *v;
1729                 struct dom_sid *domain_admins_sid;
1730                 const char *domain_admins_sid_str;
1731
1732                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
1733                 if (composite_nomem(vs, c)) return;
1734
1735                 vd = talloc_array(vs, DATA_BLOB, 1);
1736                 if (composite_nomem(vd, c)) return;
1737
1738                 domain_admins_sid = dom_sid_add_rid(vs, s->domain.sid, DOMAIN_RID_ADMINS);
1739                 if (composite_nomem(domain_admins_sid, c)) return;
1740
1741                 domain_admins_sid_str = dom_sid_string(domain_admins_sid, domain_admins_sid);
1742                 if (composite_nomem(domain_admins_sid_str, c)) return;
1743
1744                 v = security_descriptor_dacl_create(vd,
1745                                                0,
1746                                                /* owner: domain admins */
1747                                                domain_admins_sid_str,
1748                                                /* owner group: domain admins */
1749                                                domain_admins_sid_str,
1750                                                /* authenticated users */
1751                                                SID_NT_AUTHENTICATED_USERS,
1752                                                SEC_ACE_TYPE_ACCESS_ALLOWED,
1753                                                SEC_STD_READ_CONTROL |
1754                                                SEC_ADS_LIST |
1755                                                SEC_ADS_READ_PROP |
1756                                                SEC_ADS_LIST_OBJECT,
1757                                                0,
1758                                                /* domain admins */
1759                                                domain_admins_sid_str,
1760                                                SEC_ACE_TYPE_ACCESS_ALLOWED,
1761                                                SEC_STD_REQUIRED |
1762                                                SEC_ADS_CREATE_CHILD |
1763                                                SEC_ADS_LIST |
1764                                                SEC_ADS_SELF_WRITE |
1765                                                SEC_ADS_READ_PROP |
1766                                                SEC_ADS_WRITE_PROP |
1767                                                SEC_ADS_DELETE_TREE |
1768                                                SEC_ADS_LIST_OBJECT |
1769                                                SEC_ADS_CONTROL_ACCESS,
1770                                                0,
1771                                                /* system */
1772                                                SID_NT_SYSTEM,
1773                                                SEC_ACE_TYPE_ACCESS_ALLOWED,
1774                                                SEC_STD_REQUIRED |
1775                                                SEC_ADS_CREATE_CHILD |
1776                                                SEC_ADS_DELETE_CHILD |
1777                                                SEC_ADS_LIST |
1778                                                SEC_ADS_SELF_WRITE |
1779                                                SEC_ADS_READ_PROP |
1780                                                SEC_ADS_WRITE_PROP |
1781                                                SEC_ADS_DELETE_TREE |
1782                                                SEC_ADS_LIST_OBJECT |
1783                                                SEC_ADS_CONTROL_ACCESS,
1784                                                0,
1785                                                /* end */
1786                                                NULL);
1787                 if (composite_nomem(v, c)) return;
1788
1789                 ndr_err = ndr_push_struct_blob(&vd[0], vd, iconv_convenience, v,(ndr_push_flags_fn_t)ndr_push_security_descriptor);
1790                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1791                         c->status = ndr_map_error2ntstatus(ndr_err);
1792                         if (!composite_is_ok(c)) return;
1793                 }
1794
1795                 vs[0].blob              = &vd[0];
1796
1797                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_ntSecurityDescriptor;
1798                 attrs[i].value_ctr.num_values   = 1;
1799                 attrs[i].value_ctr.values       = vs;
1800
1801                 i++;
1802         }
1803
1804         /* objectClass: nTDSDSA */
1805         {
1806                 struct drsuapi_DsAttributeValue *vs;
1807                 DATA_BLOB *vd;
1808
1809                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
1810                 if (composite_nomem(vs, c)) return;
1811
1812                 vd = talloc_array(vs, DATA_BLOB, 1);
1813                 if (composite_nomem(vd, c)) return;
1814
1815                 vd[0] = data_blob_talloc(vd, NULL, 4);
1816                 if (composite_nomem(vd[0].data, c)) return;
1817
1818                 /* value for nTDSDSA */
1819                 SIVAL(vd[0].data, 0, 0x0017002F);
1820
1821                 vs[0].blob              = &vd[0];
1822
1823                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_objectClass;
1824                 attrs[i].value_ctr.num_values   = 1;
1825                 attrs[i].value_ctr.values       = vs;
1826
1827                 i++;
1828         }
1829
1830         /* objectCategory: CN=NTDS-DSA,CN=Schema,... */
1831         {
1832                 struct drsuapi_DsAttributeValue *vs;
1833                 DATA_BLOB *vd;
1834                 struct drsuapi_DsReplicaObjectIdentifier3 v[1];
1835
1836                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
1837                 if (composite_nomem(vs, c)) return;
1838
1839                 vd = talloc_array(vs, DATA_BLOB, 1);
1840                 if (composite_nomem(vd, c)) return;
1841
1842                 v[0].guid               = GUID_zero();
1843                 v[0].sid                = s->zero_sid;
1844                 v[0].dn                 = talloc_asprintf(vd, "CN=NTDS-DSA,%s",
1845                                                           s->forest.schema_dn_str);
1846                 if (composite_nomem(v[0].dn, c)) return;
1847
1848                 ndr_err = ndr_push_struct_blob(&vd[0], vd, iconv_convenience, &v[0], 
1849                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1850                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1851                         c->status = ndr_map_error2ntstatus(ndr_err);
1852                         if (!composite_is_ok(c)) return;
1853                 }
1854
1855                 vs[0].blob              = &vd[0];
1856
1857                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_objectCategory;
1858                 attrs[i].value_ctr.num_values   = 1;
1859                 attrs[i].value_ctr.values       = vs;
1860
1861                 i++;
1862         }
1863
1864         /* invocationId: random guid */
1865         {
1866                 struct drsuapi_DsAttributeValue *vs;
1867                 DATA_BLOB *vd;
1868                 const struct GUID *v;
1869
1870                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
1871                 if (composite_nomem(vs, c)) return;
1872
1873                 vd = talloc_array(vs, DATA_BLOB, 1);
1874                 if (composite_nomem(vd, c)) return;
1875
1876                 v = &s->dest_dsa.invocation_id;
1877
1878                 ndr_err = ndr_push_struct_blob(&vd[0], vd, iconv_convenience, v, (ndr_push_flags_fn_t)ndr_push_GUID);
1879                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1880                         c->status = ndr_map_error2ntstatus(ndr_err);
1881                         if (!composite_is_ok(c)) return;
1882                 }
1883
1884                 vs[0].blob              = &vd[0];
1885
1886                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_invocationId;
1887                 attrs[i].value_ctr.num_values   = 1;
1888                 attrs[i].value_ctr.values       = vs;
1889
1890                 i++;
1891         }
1892
1893         /* hasMasterNCs: ... */
1894         {
1895                 struct drsuapi_DsAttributeValue *vs;
1896                 DATA_BLOB *vd;
1897                 struct drsuapi_DsReplicaObjectIdentifier3 v[3];
1898
1899                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 3);
1900                 if (composite_nomem(vs, c)) return;
1901
1902                 vd = talloc_array(vs, DATA_BLOB, 3);
1903                 if (composite_nomem(vd, c)) return;
1904
1905                 v[0].guid               = GUID_zero();
1906                 v[0].sid                = s->zero_sid;
1907                 v[0].dn                 = s->forest.config_dn_str;
1908
1909                 v[1].guid               = GUID_zero();
1910                 v[1].sid                = s->zero_sid;
1911                 v[1].dn                 = s->domain.dn_str;
1912
1913                 v[2].guid               = GUID_zero();
1914                 v[2].sid                = s->zero_sid;
1915                 v[2].dn                 = s->forest.schema_dn_str;
1916
1917                 ndr_err = ndr_push_struct_blob(&vd[0], vd, iconv_convenience, &v[0],
1918                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1919                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1920                         c->status = ndr_map_error2ntstatus(ndr_err);
1921                         if (!composite_is_ok(c)) return;
1922                 }
1923
1924                 ndr_err = ndr_push_struct_blob(&vd[1], vd, iconv_convenience, &v[1],
1925                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1926                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1927                         c->status = ndr_map_error2ntstatus(ndr_err);
1928                         if (!composite_is_ok(c)) return;
1929                 }
1930
1931                 ndr_err = ndr_push_struct_blob(&vd[2], vd, iconv_convenience, &v[2],
1932                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1933                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1934                         c->status = ndr_map_error2ntstatus(ndr_err);
1935                         if (!composite_is_ok(c)) return;
1936                 }
1937
1938                 vs[0].blob              = &vd[0];
1939                 vs[1].blob              = &vd[1];
1940                 vs[2].blob              = &vd[2];
1941
1942                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_hasMasterNCs;
1943                 attrs[i].value_ctr.num_values   = 3;
1944                 attrs[i].value_ctr.values       = vs;
1945
1946                 i++;
1947         }
1948
1949         /* msDS-hasMasterNCs: ... */
1950         if (w2k3) {
1951                 struct drsuapi_DsAttributeValue *vs;
1952                 DATA_BLOB *vd;
1953                 struct drsuapi_DsReplicaObjectIdentifier3 v[3];
1954
1955                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 3);
1956                 if (composite_nomem(vs, c)) return;
1957
1958                 vd = talloc_array(vs, DATA_BLOB, 3);
1959                 if (composite_nomem(vd, c)) return;
1960
1961                 v[0].guid               = GUID_zero();
1962                 v[0].sid                = s->zero_sid;
1963                 v[0].dn                 = s->forest.config_dn_str;
1964
1965                 v[1].guid               = GUID_zero();
1966                 v[1].sid                = s->zero_sid;
1967                 v[1].dn                 = s->domain.dn_str;
1968
1969                 v[2].guid               = GUID_zero();
1970                 v[2].sid                = s->zero_sid;
1971                 v[2].dn                 = s->forest.schema_dn_str;
1972
1973                 ndr_err = ndr_push_struct_blob(&vd[0], vd, iconv_convenience, &v[0],
1974                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1975                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1976                         c->status = ndr_map_error2ntstatus(ndr_err);
1977                         if (!composite_is_ok(c)) return;
1978                 }
1979
1980                 ndr_err = ndr_push_struct_blob(&vd[1], vd, iconv_convenience, &v[1],
1981                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1982                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1983                         c->status = ndr_map_error2ntstatus(ndr_err);
1984                         if (!composite_is_ok(c)) return;
1985                 }
1986
1987                 ndr_err = ndr_push_struct_blob(&vd[2], vd, iconv_convenience, &v[2],
1988                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
1989                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
1990                         c->status = ndr_map_error2ntstatus(ndr_err);
1991                         if (!composite_is_ok(c)) return;
1992                 }
1993
1994                 vs[0].blob              = &vd[0];
1995                 vs[1].blob              = &vd[1];
1996                 vs[2].blob              = &vd[2];
1997
1998                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_msDS_hasMasterNCs;
1999                 attrs[i].value_ctr.num_values   = 3;
2000                 attrs[i].value_ctr.values       = vs;
2001
2002                 i++;
2003         }
2004
2005         /* dMDLocation: CN=Schema,... */
2006         {
2007                 struct drsuapi_DsAttributeValue *vs;
2008                 DATA_BLOB *vd;
2009                 struct drsuapi_DsReplicaObjectIdentifier3 v[1];
2010
2011                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
2012                 if (composite_nomem(vs, c)) return;
2013
2014                 vd = talloc_array(vs, DATA_BLOB, 1);
2015                 if (composite_nomem(vd, c)) return;
2016
2017                 v[0].guid               = GUID_zero();
2018                 v[0].sid                = s->zero_sid;
2019                 v[0].dn                 = s->forest.schema_dn_str;
2020
2021                 ndr_err = ndr_push_struct_blob(&vd[0], vd, iconv_convenience, &v[0],
2022                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
2023                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2024                         c->status = ndr_map_error2ntstatus(ndr_err);
2025                         if (!composite_is_ok(c)) return;
2026                 }
2027
2028                 vs[0].blob              = &vd[0];
2029
2030                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_dMDLocation;
2031                 attrs[i].value_ctr.num_values   = 1;
2032                 attrs[i].value_ctr.values       = vs;
2033
2034                 i++;
2035         }
2036
2037         /* msDS-HasDomainNCs: <domain_partition> */
2038         if (w2k3) {
2039                 struct drsuapi_DsAttributeValue *vs;
2040                 DATA_BLOB *vd;
2041                 struct drsuapi_DsReplicaObjectIdentifier3 v[1];
2042
2043                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
2044                 if (composite_nomem(vs, c)) return;
2045
2046                 vd = talloc_array(vs, DATA_BLOB, 1);
2047                 if (composite_nomem(vd, c)) return;
2048
2049                 v[0].guid               = GUID_zero();
2050                 v[0].sid                = s->zero_sid;
2051                 v[0].dn                 = s->domain.dn_str;
2052
2053                 ndr_err = ndr_push_struct_blob(&vd[0], vd, iconv_convenience, &v[0],
2054                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
2055                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2056                         c->status = ndr_map_error2ntstatus(ndr_err);
2057                         if (!composite_is_ok(c)) return;
2058                 }
2059
2060                 vs[0].blob              = &vd[0];
2061
2062                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_msDS_HasDomainNCs;
2063                 attrs[i].value_ctr.num_values   = 1;
2064                 attrs[i].value_ctr.values       = vs;
2065
2066                 i++;
2067         }
2068
2069         /* msDS-Behavior-Version */
2070         if (w2k3) {
2071                 struct drsuapi_DsAttributeValue *vs;
2072                 DATA_BLOB *vd;
2073
2074                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
2075                 if (composite_nomem(vs, c)) return;
2076
2077                 vd = talloc_array(vs, DATA_BLOB, 1);
2078                 if (composite_nomem(vd, c)) return;
2079
2080                 vd[0] = data_blob_talloc(vd, NULL, 4);
2081                 if (composite_nomem(vd[0].data, c)) return;
2082
2083                 SIVAL(vd[0].data, 0, DS_BEHAVIOR_WIN2003);
2084
2085                 vs[0].blob              = &vd[0];
2086
2087                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_msDS_Behavior_Version;
2088                 attrs[i].value_ctr.num_values   = 1;
2089                 attrs[i].value_ctr.values       = vs;
2090
2091                 i++;
2092         }
2093
2094         /* systemFlags */
2095         {
2096                 struct drsuapi_DsAttributeValue *vs;
2097                 DATA_BLOB *vd;
2098
2099                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
2100                 if (composite_nomem(vs, c)) return;
2101
2102                 vd = talloc_array(vs, DATA_BLOB, 1);
2103                 if (composite_nomem(vd, c)) return;
2104
2105                 vd[0] = data_blob_talloc(vd, NULL, 4);
2106                 if (composite_nomem(vd[0].data, c)) return;
2107
2108                 SIVAL(vd[0].data, 0, SYSTEM_FLAG_DISALLOW_MOVE_ON_DELETE);
2109
2110                 vs[0].blob              = &vd[0];
2111
2112                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_systemFlags;
2113                 attrs[i].value_ctr.num_values   = 1;
2114                 attrs[i].value_ctr.values       = vs;
2115
2116                 i++;
2117         }
2118
2119         /* serverReference: ... */
2120         {
2121                 struct drsuapi_DsAttributeValue *vs;
2122                 DATA_BLOB *vd;
2123                 struct drsuapi_DsReplicaObjectIdentifier3 v[1];
2124
2125                 vs = talloc_array(attrs, struct drsuapi_DsAttributeValue, 1);
2126                 if (composite_nomem(vs, c)) return;
2127
2128                 vd = talloc_array(vs, DATA_BLOB, 1);
2129                 if (composite_nomem(vd, c)) return;
2130
2131                 v[0].guid               = GUID_zero();
2132                 v[0].sid                = s->zero_sid;
2133                 v[0].dn                 = s->dest_dsa.computer_dn_str;
2134
2135                 ndr_err = ndr_push_struct_blob(&vd[0], vd, iconv_convenience, &v[0],
2136                                                (ndr_push_flags_fn_t)ndr_push_drsuapi_DsReplicaObjectIdentifier3);
2137                 if (!NDR_ERR_CODE_IS_SUCCESS(ndr_err)) {
2138                         c->status = ndr_map_error2ntstatus(ndr_err);
2139                         if (!composite_is_ok(c)) return;
2140                 }
2141
2142                 vs[0].blob              = &vd[0];
2143
2144                 attrs[i].attid                  = DRSUAPI_ATTRIBUTE_serverReference;
2145                 attrs[i].value_ctr.num_values   = 1;
2146                 attrs[i].value_ctr.values       = vs;
2147
2148                 i++;
2149         }
2150
2151         /* truncate the attribute list to the attribute count we have filled in */
2152         num_attrs = i;
2153
2154         /* setup request structure */
2155         r->in.bind_handle                                               = &s->drsuapi1.bind_handle;
2156         r->in.level                                                     = 2;
2157         r->in.req.req2.first_object.next_object                         = NULL;
2158         r->in.req.req2.first_object.object.identifier                   = identifier;
2159         r->in.req.req2.first_object.object.unknown1                     = 0x00000000;   
2160         r->in.req.req2.first_object.object.attribute_ctr.num_attributes = num_attrs;
2161         r->in.req.req2.first_object.object.attribute_ctr.attributes     = attrs;
2162
2163         req = dcerpc_drsuapi_DsAddEntry_send(s->drsuapi1.pipe, r, r);
2164         composite_continue_rpc(c, req, becomeDC_drsuapi1_add_entry_recv, s);
2165 }
2166
2167 static void becomeDC_drsuapi2_connect_recv(struct composite_context *req);
2168 static NTSTATUS becomeDC_prepare_db(struct libnet_BecomeDC_state *s);
2169
2170 static void becomeDC_drsuapi1_add_entry_recv(struct rpc_request *req)
2171 {
2172         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2173                                           struct libnet_BecomeDC_state);
2174         struct composite_context *c = s->creq;
2175         struct drsuapi_DsAddEntry *r = talloc_get_type(req->ndr.struct_ptr,
2176                                        struct drsuapi_DsAddEntry);
2177         char *binding_str;
2178         bool print = false;
2179
2180         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2181                 print = true;
2182         }
2183
2184         c->status = dcerpc_ndr_request_recv(req);
2185         if (!composite_is_ok(c)) return;
2186
2187         if (print) {
2188                 NDR_PRINT_OUT_DEBUG(drsuapi_DsAddEntry, r);
2189         }
2190
2191         if (!W_ERROR_IS_OK(r->out.result)) {
2192                 composite_error(c, werror_to_ntstatus(r->out.result));
2193                 return;
2194         }
2195
2196         if (r->out.level == 3) {
2197                 if (r->out.ctr.ctr3.count != 1) {
2198                         WERROR status;
2199
2200                         if (r->out.ctr.ctr3.level != 1) {
2201                                 composite_error(c, NT_STATUS_INVALID_NETWORK_RESPONSE);
2202                                 return;
2203                         }
2204
2205                         if (!r->out.ctr.ctr3.error) {
2206                                 composite_error(c, NT_STATUS_INVALID_NETWORK_RESPONSE);
2207                                 return;
2208                         }
2209
2210                         status = r->out.ctr.ctr3.error->info1.status;
2211
2212                         if (!r->out.ctr.ctr3.error->info1.info) {
2213                                 composite_error(c, werror_to_ntstatus(status));
2214                                 return;
2215                         }
2216
2217                         /* see if we can get a more detailed error */
2218                         switch (r->out.ctr.ctr3.error->info1.level) {
2219                         case 1:
2220                                 status = r->out.ctr.ctr3.error->info1.info->error1.status;
2221                                 break;
2222                         case 4:
2223                         case 5:
2224                         case 6:
2225                         case 7:
2226                                 status = r->out.ctr.ctr3.error->info1.info->errorX.status;
2227                                 break;
2228                         }
2229
2230                         composite_error(c, werror_to_ntstatus(status));
2231                         return;
2232                 }
2233
2234                 s->dest_dsa.ntds_guid   = r->out.ctr.ctr3.objects[0].guid;
2235         } else if (r->out.level == 2) {
2236                 if (r->out.ctr.ctr2.count != 1) {
2237                         composite_error(c, werror_to_ntstatus(r->out.ctr.ctr2.error.status));
2238                         return;
2239                 }
2240
2241                 s->dest_dsa.ntds_guid   = r->out.ctr.ctr2.objects[0].guid;
2242         } else {
2243                 composite_error(c, NT_STATUS_INVALID_NETWORK_RESPONSE);
2244                 return;
2245         }
2246
2247         talloc_free(r);
2248
2249         s->dest_dsa.ntds_dn_str = talloc_asprintf(s, "CN=NTDS Settings,%s",
2250                                                   s->dest_dsa.server_dn_str);
2251         if (composite_nomem(s->dest_dsa.ntds_dn_str, c)) return;
2252
2253         c->status = becomeDC_prepare_db(s);
2254         if (!composite_is_ok(c)) return;
2255
2256         /* this avoids the epmapper lookup on the 2nd connection */
2257         binding_str = dcerpc_binding_string(s, s->drsuapi1.binding);
2258         if (composite_nomem(binding_str, c)) return;
2259
2260         c->status = dcerpc_parse_binding(s, binding_str, &s->drsuapi2.binding);
2261         talloc_free(binding_str);
2262         if (!composite_is_ok(c)) return;
2263
2264         /* w2k3 uses the same assoc_group_id as on the first connection, so we do */
2265         s->drsuapi2.binding->assoc_group_id     = s->drsuapi1.pipe->assoc_group_id;
2266
2267         becomeDC_drsuapi_connect_send(s, &s->drsuapi2, becomeDC_drsuapi2_connect_recv);
2268 }
2269
2270 static NTSTATUS becomeDC_prepare_db(struct libnet_BecomeDC_state *s)
2271 {
2272         if (!s->callbacks.prepare_db) return NT_STATUS_OK;
2273
2274         s->_pp.domain           = &s->domain;
2275         s->_pp.forest           = &s->forest;
2276         s->_pp.source_dsa       = &s->source_dsa;
2277         s->_pp.dest_dsa         = &s->dest_dsa;
2278
2279         return s->callbacks.prepare_db(s->callbacks.private_data, &s->_pp);
2280 }
2281
2282 static void becomeDC_drsuapi2_bind_recv(struct rpc_request *req);
2283
2284 static void becomeDC_drsuapi2_connect_recv(struct composite_context *req)
2285 {
2286         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2287                                           struct libnet_BecomeDC_state);
2288         struct composite_context *c = s->creq;
2289
2290         c->status = dcerpc_pipe_connect_b_recv(req, s, &s->drsuapi2.pipe);
2291         if (!composite_is_ok(c)) return;
2292
2293         c->status = gensec_session_key(s->drsuapi2.pipe->conn->security_state.generic_state,
2294                                        &s->drsuapi2.gensec_skey);
2295         if (!composite_is_ok(c)) return;
2296
2297         becomeDC_drsuapi_bind_send(s, &s->drsuapi2, becomeDC_drsuapi2_bind_recv);
2298 }
2299
2300 static void becomeDC_drsuapi3_connect_recv(struct composite_context *req);
2301
2302 static void becomeDC_drsuapi2_bind_recv(struct rpc_request *req)
2303 {
2304         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2305                                           struct libnet_BecomeDC_state);
2306         struct composite_context *c = s->creq;
2307         char *binding_str;
2308         WERROR status;
2309
2310         bool print = false;
2311
2312         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2313                 print = true;
2314         }
2315
2316         c->status = dcerpc_ndr_request_recv(req);
2317         if (!composite_is_ok(c)) return;
2318
2319         if (print) {
2320                 NDR_PRINT_OUT_DEBUG(drsuapi_DsBind, &s->drsuapi2.bind_r);
2321         }
2322
2323         status = becomeDC_drsuapi_bind_recv(s, &s->drsuapi2);
2324         if (!W_ERROR_IS_OK(status)) {
2325                 composite_error(c, werror_to_ntstatus(status));
2326                 return;
2327         }
2328
2329         /* this avoids the epmapper lookup on the 3rd connection */
2330         binding_str = dcerpc_binding_string(s, s->drsuapi1.binding);
2331         if (composite_nomem(binding_str, c)) return;
2332
2333         c->status = dcerpc_parse_binding(s, binding_str, &s->drsuapi3.binding);
2334         talloc_free(binding_str);
2335         if (!composite_is_ok(c)) return;
2336
2337         /* w2k3 uses the same assoc_group_id as on the first connection, so we do */
2338         s->drsuapi3.binding->assoc_group_id     = s->drsuapi1.pipe->assoc_group_id;
2339         /* w2k3 uses the concurrent multiplex feature on the 3rd connection, so we do */
2340         s->drsuapi3.binding->flags              |= DCERPC_CONCURRENT_MULTIPLEX;
2341
2342         becomeDC_drsuapi_connect_send(s, &s->drsuapi3, becomeDC_drsuapi3_connect_recv);
2343 }
2344
2345 static void becomeDC_drsuapi3_pull_schema_send(struct libnet_BecomeDC_state *s);
2346
2347 static void becomeDC_drsuapi3_connect_recv(struct composite_context *req)
2348 {
2349         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2350                                           struct libnet_BecomeDC_state);
2351         struct composite_context *c = s->creq;
2352
2353         c->status = dcerpc_pipe_connect_b_recv(req, s, &s->drsuapi3.pipe);
2354         if (!composite_is_ok(c)) return;
2355
2356         c->status = gensec_session_key(s->drsuapi3.pipe->conn->security_state.generic_state,
2357                                        &s->drsuapi3.gensec_skey);
2358         if (!composite_is_ok(c)) return;
2359
2360         becomeDC_drsuapi3_pull_schema_send(s);
2361 }
2362
2363 static void becomeDC_drsuapi_pull_partition_send(struct libnet_BecomeDC_state *s,
2364                                                  struct becomeDC_drsuapi *drsuapi_h,
2365                                                  struct becomeDC_drsuapi *drsuapi_p,
2366                                                  struct libnet_BecomeDC_Partition *partition,
2367                                                  void (*recv_fn)(struct rpc_request *req))
2368 {
2369         struct composite_context *c = s->creq;
2370         struct rpc_request *req;
2371         struct drsuapi_DsGetNCChanges *r;
2372
2373         r = talloc(s, struct drsuapi_DsGetNCChanges);
2374         if (composite_nomem(r, c)) return;
2375
2376         r->in.level = talloc(r, int32_t);
2377         if (composite_nomem(r->in.level, c)) return;
2378         r->out.level = talloc(r, int32_t);
2379         if (composite_nomem(r->out.level, c)) return;
2380
2381         r->in.bind_handle       = &drsuapi_h->bind_handle;
2382         if (drsuapi_h->remote_info28.supported_extensions & DRSUAPI_SUPPORTED_EXTENSION_GETCHGREQ_V8) {
2383                 *r->in.level                            = 8;
2384                 r->in.req.req8.destination_dsa_guid     = partition->destination_dsa_guid;
2385                 r->in.req.req8.source_dsa_invocation_id = partition->source_dsa_invocation_id;
2386                 r->in.req.req8.naming_context           = &partition->nc;
2387                 r->in.req.req8.highwatermark            = partition->highwatermark;
2388                 r->in.req.req8.uptodateness_vector      = NULL;
2389                 r->in.req.req8.replica_flags            = partition->replica_flags;
2390                 r->in.req.req8.max_object_count         = 133;
2391                 r->in.req.req8.max_ndr_size             = 1336811;
2392                 r->in.req.req8.unknown4                 = 0;
2393                 r->in.req.req8.h1                       = 0;
2394                 r->in.req.req8.unique_ptr1              = 0;
2395                 r->in.req.req8.unique_ptr2              = 0;
2396                 r->in.req.req8.mapping_ctr.num_mappings = 0;
2397                 r->in.req.req8.mapping_ctr.mappings     = NULL;
2398         } else {
2399                 *r->in.level                            = 5;
2400                 r->in.req.req5.destination_dsa_guid     = partition->destination_dsa_guid;
2401                 r->in.req.req5.source_dsa_invocation_id = partition->source_dsa_invocation_id;
2402                 r->in.req.req5.naming_context           = &partition->nc;
2403                 r->in.req.req5.highwatermark            = partition->highwatermark;
2404                 r->in.req.req5.uptodateness_vector      = NULL;
2405                 r->in.req.req5.replica_flags            = partition->replica_flags;
2406                 r->in.req.req5.max_object_count         = 133;
2407                 r->in.req.req5.max_ndr_size             = 1336770;
2408                 r->in.req.req5.unknown4                 = 0;
2409                 r->in.req.req5.h1                       = 0;
2410         }
2411
2412         /* 
2413          * we should try to use the drsuapi_p->pipe here, as w2k3 does
2414          * but it seems that some extra flags in the DCERPC Bind call
2415          * are needed for it. Or the same KRB5 TGS is needed on both
2416          * connections.
2417          */
2418         req = dcerpc_drsuapi_DsGetNCChanges_send(drsuapi_p->pipe, r, r);
2419         composite_continue_rpc(c, req, recv_fn, s);
2420 }
2421
2422 static WERROR becomeDC_drsuapi_pull_partition_recv(struct libnet_BecomeDC_state *s,
2423                                                    struct becomeDC_drsuapi *drsuapi_h,
2424                                                    struct becomeDC_drsuapi *drsuapi_p,
2425                                                    struct libnet_BecomeDC_Partition *partition,
2426                                                    struct drsuapi_DsGetNCChanges *r)
2427 {
2428         uint32_t ctr_level = 0;
2429         struct drsuapi_DsGetNCChangesCtr1 *ctr1 = NULL;
2430         struct drsuapi_DsGetNCChangesCtr6 *ctr6 = NULL;
2431         struct GUID *source_dsa_guid;
2432         struct GUID *source_dsa_invocation_id;
2433         struct drsuapi_DsReplicaHighWaterMark *new_highwatermark;
2434         NTSTATUS nt_status;
2435
2436         if (!W_ERROR_IS_OK(r->out.result)) {
2437                 return r->out.result;
2438         }
2439
2440         if (*r->out.level == 1) {
2441                 ctr_level = 1;
2442                 ctr1 = &r->out.ctr.ctr1;
2443         } else if (*r->out.level == 2) {
2444                 ctr_level = 1;
2445                 ctr1 = r->out.ctr.ctr2.ctr.mszip1.ctr1;
2446         } else if (*r->out.level == 6) {
2447                 ctr_level = 6;
2448                 ctr6 = &r->out.ctr.ctr6;
2449         } else if (*r->out.level == 7 &&
2450                    r->out.ctr.ctr7.level == 6 &&
2451                    r->out.ctr.ctr7.type == DRSUAPI_COMPRESSION_TYPE_MSZIP) {
2452                 ctr_level = 6;
2453                 ctr6 = r->out.ctr.ctr7.ctr.mszip6.ctr6;
2454         } else {
2455                 return WERR_BAD_NET_RESP;
2456         }
2457
2458         switch (ctr_level) {
2459         case 1:
2460                 source_dsa_guid                 = &ctr1->source_dsa_guid;
2461                 source_dsa_invocation_id        = &ctr1->source_dsa_invocation_id;
2462                 new_highwatermark               = &ctr1->new_highwatermark;
2463                 break;
2464         case 6:
2465                 source_dsa_guid                 = &ctr6->source_dsa_guid;
2466                 source_dsa_invocation_id        = &ctr6->source_dsa_invocation_id;
2467                 new_highwatermark               = &ctr6->new_highwatermark;
2468                 break;
2469         }
2470
2471         partition->highwatermark                = *new_highwatermark;
2472         partition->source_dsa_guid              = *source_dsa_guid;
2473         partition->source_dsa_invocation_id     = *source_dsa_invocation_id;
2474
2475         if (!partition->store_chunk) return WERR_OK;
2476
2477         s->_sc.domain           = &s->domain;
2478         s->_sc.forest           = &s->forest;
2479         s->_sc.source_dsa       = &s->source_dsa;
2480         s->_sc.dest_dsa         = &s->dest_dsa;
2481         s->_sc.partition        = partition;
2482         s->_sc.ctr_level        = ctr_level;
2483         s->_sc.ctr1             = ctr1;
2484         s->_sc.ctr6             = ctr6;
2485         /* 
2486          * we need to use the drsuapi_p->gensec_skey here,
2487          * when we use drsuapi_p->pipe in the for this request
2488          */
2489         s->_sc.gensec_skey      = &drsuapi_p->gensec_skey;
2490
2491         nt_status = partition->store_chunk(s->callbacks.private_data, &s->_sc);
2492         if (!NT_STATUS_IS_OK(nt_status)) {
2493                 return ntstatus_to_werror(nt_status);
2494         }
2495
2496         return WERR_OK;
2497 }
2498
2499 static void becomeDC_drsuapi3_pull_schema_recv(struct rpc_request *req);
2500
2501 static void becomeDC_drsuapi3_pull_schema_send(struct libnet_BecomeDC_state *s)
2502 {
2503         s->schema_part.nc.guid  = GUID_zero();
2504         s->schema_part.nc.sid   = s->zero_sid;
2505         s->schema_part.nc.dn    = s->forest.schema_dn_str;
2506
2507         s->schema_part.destination_dsa_guid     = s->drsuapi2.bind_guid;
2508
2509         s->schema_part.replica_flags    = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
2510                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
2511                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS
2512                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_FULL_IN_PROGRESS
2513                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_NEVER_SYNCED
2514                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_COMPRESS_CHANGES;
2515
2516         s->schema_part.store_chunk      = s->callbacks.schema_chunk;
2517
2518         becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->schema_part,
2519                                              becomeDC_drsuapi3_pull_schema_recv);
2520 }
2521
2522 static void becomeDC_drsuapi3_pull_config_send(struct libnet_BecomeDC_state *s);
2523
2524 static void becomeDC_drsuapi3_pull_schema_recv(struct rpc_request *req)
2525 {
2526         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2527                                           struct libnet_BecomeDC_state);
2528         struct composite_context *c = s->creq;
2529         struct drsuapi_DsGetNCChanges *r = talloc_get_type(req->ndr.struct_ptr,
2530                                            struct drsuapi_DsGetNCChanges);
2531         WERROR status;
2532
2533         bool print = false;
2534
2535         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2536                 print = true;
2537         }
2538
2539         c->status = dcerpc_ndr_request_recv(req);
2540         if (!composite_is_ok(c)) return;
2541
2542         if (print) {
2543                 NDR_PRINT_OUT_DEBUG(drsuapi_DsGetNCChanges, r);
2544         }
2545
2546         status = becomeDC_drsuapi_pull_partition_recv(s, &s->drsuapi2, &s->drsuapi3, &s->schema_part, r);
2547         if (!W_ERROR_IS_OK(status)) {
2548                 composite_error(c, werror_to_ntstatus(status));
2549                 return;
2550         }
2551
2552         talloc_free(r);
2553
2554         if (s->schema_part.highwatermark.tmp_highest_usn > s->schema_part.highwatermark.highest_usn) {
2555                 becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->schema_part,
2556                                                      becomeDC_drsuapi3_pull_schema_recv);
2557                 return;
2558         }
2559
2560         becomeDC_drsuapi3_pull_config_send(s);
2561 }
2562
2563 static void becomeDC_drsuapi3_pull_config_recv(struct rpc_request *req);
2564
2565 static void becomeDC_drsuapi3_pull_config_send(struct libnet_BecomeDC_state *s)
2566 {
2567         s->config_part.nc.guid  = GUID_zero();
2568         s->config_part.nc.sid   = s->zero_sid;
2569         s->config_part.nc.dn    = s->forest.config_dn_str;
2570
2571         s->config_part.destination_dsa_guid     = s->drsuapi2.bind_guid;
2572
2573         s->config_part.replica_flags    = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
2574                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
2575                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS
2576                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_FULL_IN_PROGRESS
2577                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_NEVER_SYNCED
2578                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_COMPRESS_CHANGES;
2579
2580         s->config_part.store_chunk      = s->callbacks.config_chunk;
2581
2582         becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->config_part,
2583                                              becomeDC_drsuapi3_pull_config_recv);
2584 }
2585
2586 static void becomeDC_drsuapi3_pull_config_recv(struct rpc_request *req)
2587 {
2588         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2589                                           struct libnet_BecomeDC_state);
2590         struct composite_context *c = s->creq;
2591         struct drsuapi_DsGetNCChanges *r = talloc_get_type(req->ndr.struct_ptr,
2592                                            struct drsuapi_DsGetNCChanges);
2593         WERROR status;
2594
2595         bool print = false;
2596
2597         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2598                 print = true;
2599         }
2600
2601         c->status = dcerpc_ndr_request_recv(req);
2602         if (!composite_is_ok(c)) return;
2603
2604         if (print) {
2605                 NDR_PRINT_OUT_DEBUG(drsuapi_DsGetNCChanges, r);
2606         }
2607
2608         status = becomeDC_drsuapi_pull_partition_recv(s, &s->drsuapi2, &s->drsuapi3, &s->config_part, r);
2609         if (!W_ERROR_IS_OK(status)) {
2610                 composite_error(c, werror_to_ntstatus(status));
2611                 return;
2612         }
2613
2614         talloc_free(r);
2615
2616         if (s->config_part.highwatermark.tmp_highest_usn > s->config_part.highwatermark.highest_usn) {
2617                 becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->config_part,
2618                                                      becomeDC_drsuapi3_pull_config_recv);
2619                 return;
2620         }
2621
2622         becomeDC_connect_ldap2(s);
2623 }
2624
2625 static void becomeDC_drsuapi3_pull_domain_recv(struct rpc_request *req);
2626
2627 static void becomeDC_drsuapi3_pull_domain_send(struct libnet_BecomeDC_state *s)
2628 {
2629         s->domain_part.nc.guid  = GUID_zero();
2630         s->domain_part.nc.sid   = s->zero_sid;
2631         s->domain_part.nc.dn    = s->domain.dn_str;
2632
2633         s->domain_part.destination_dsa_guid     = s->drsuapi2.bind_guid;
2634
2635         s->domain_part.replica_flags    = DRSUAPI_DS_REPLICA_NEIGHBOUR_WRITEABLE
2636                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_SYNC_ON_STARTUP
2637                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_DO_SCHEDULED_SYNCS
2638                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_FULL_IN_PROGRESS
2639                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_NEVER_SYNCED
2640                                         | DRSUAPI_DS_REPLICA_NEIGHBOUR_COMPRESS_CHANGES;
2641
2642         s->domain_part.store_chunk      = s->callbacks.domain_chunk;
2643
2644         becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->domain_part,
2645                                              becomeDC_drsuapi3_pull_domain_recv);
2646 }
2647
2648 static void becomeDC_drsuapi_update_refs_send(struct libnet_BecomeDC_state *s,
2649                                               struct becomeDC_drsuapi *drsuapi,
2650                                               struct libnet_BecomeDC_Partition *partition,
2651                                               void (*recv_fn)(struct rpc_request *req));
2652 static void becomeDC_drsuapi2_update_refs_schema_recv(struct rpc_request *req);
2653
2654 static void becomeDC_drsuapi3_pull_domain_recv(struct rpc_request *req)
2655 {
2656         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2657                                           struct libnet_BecomeDC_state);
2658         struct composite_context *c = s->creq;
2659         struct drsuapi_DsGetNCChanges *r = talloc_get_type(req->ndr.struct_ptr,
2660                                            struct drsuapi_DsGetNCChanges);
2661         WERROR status;
2662         bool print = false;
2663
2664         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2665                 print = true;
2666         }
2667
2668         c->status = dcerpc_ndr_request_recv(req);
2669         if (!composite_is_ok(c)) return;
2670
2671         if (print) {
2672                 NDR_PRINT_OUT_DEBUG(drsuapi_DsGetNCChanges, r);
2673         }
2674
2675         status = becomeDC_drsuapi_pull_partition_recv(s, &s->drsuapi2, &s->drsuapi3, &s->domain_part, r);
2676         if (!W_ERROR_IS_OK(status)) {
2677                 composite_error(c, werror_to_ntstatus(status));
2678                 return;
2679         }
2680
2681         talloc_free(r);
2682
2683         if (s->domain_part.highwatermark.tmp_highest_usn > s->domain_part.highwatermark.highest_usn) {
2684                 becomeDC_drsuapi_pull_partition_send(s, &s->drsuapi2, &s->drsuapi3, &s->domain_part,
2685                                                      becomeDC_drsuapi3_pull_domain_recv);
2686                 return;
2687         }
2688
2689         becomeDC_drsuapi_update_refs_send(s, &s->drsuapi2, &s->schema_part,
2690                                           becomeDC_drsuapi2_update_refs_schema_recv);
2691 }
2692
2693 static void becomeDC_drsuapi_update_refs_send(struct libnet_BecomeDC_state *s,
2694                                               struct becomeDC_drsuapi *drsuapi,
2695                                               struct libnet_BecomeDC_Partition *partition,
2696                                               void (*recv_fn)(struct rpc_request *req))
2697 {
2698         struct composite_context *c = s->creq;
2699         struct rpc_request *req;
2700         struct drsuapi_DsReplicaUpdateRefs *r;
2701         const char *ntds_guid_str;
2702         const char *ntds_dns_name;
2703
2704         r = talloc(s, struct drsuapi_DsReplicaUpdateRefs);
2705         if (composite_nomem(r, c)) return;
2706
2707         ntds_guid_str = GUID_string(r, &s->dest_dsa.ntds_guid);
2708         if (composite_nomem(ntds_guid_str, c)) return;
2709
2710         ntds_dns_name = talloc_asprintf(r, "%s._msdcs.%s",
2711                                         ntds_guid_str,
2712                                         s->domain.dns_name);
2713         if (composite_nomem(ntds_dns_name, c)) return;
2714
2715         r->in.bind_handle               = &drsuapi->bind_handle;
2716         r->in.level                     = 1;
2717         r->in.req.req1.naming_context   = &partition->nc;
2718         r->in.req.req1.dest_dsa_dns_name= ntds_dns_name;
2719         r->in.req.req1.dest_dsa_guid    = s->dest_dsa.ntds_guid;
2720         r->in.req.req1.options          = DRSUAPI_DS_REPLICA_UPDATE_ADD_REFERENCE
2721                                         | DRSUAPI_DS_REPLICA_UPDATE_DELETE_REFERENCE
2722                                         | DRSUAPI_DS_REPLICA_UPDATE_0x00000010;
2723
2724         req = dcerpc_drsuapi_DsReplicaUpdateRefs_send(drsuapi->pipe, r, r);
2725         composite_continue_rpc(c, req, recv_fn, s);
2726 }
2727
2728 static void becomeDC_drsuapi2_update_refs_config_recv(struct rpc_request *req);
2729
2730 static void becomeDC_drsuapi2_update_refs_schema_recv(struct rpc_request *req)
2731 {
2732         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2733                                           struct libnet_BecomeDC_state);
2734         struct composite_context *c = s->creq;
2735         struct drsuapi_DsReplicaUpdateRefs *r = talloc_get_type(req->ndr.struct_ptr,
2736                                            struct drsuapi_DsReplicaUpdateRefs);
2737         bool print = false;
2738
2739         if (req->p->conn->flags & DCERPC_DEBUG_PRINT_OUT) {
2740                 print = true;
2741         }
2742
2743         c->status = dcerpc_ndr_request_recv(req);
2744         if (!composite_is_ok(c)) return;
2745
2746         if (print) {
2747                 NDR_PRINT_OUT_DEBUG(drsuapi_DsReplicaUpdateRefs, r);
2748         }
2749
2750         if (!W_ERROR_IS_OK(r->out.result)) {
2751                 composite_error(c, werror_to_ntstatus(r->out.result));
2752                 return;
2753         }
2754
2755         talloc_free(r);
2756
2757         becomeDC_drsuapi_update_refs_send(s, &s->drsuapi2, &s->config_part,
2758                                           becomeDC_drsuapi2_update_refs_config_recv);
2759 }
2760
2761 static void becomeDC_drsuapi2_update_refs_domain_recv(struct rpc_request *req);
2762
2763 static void becomeDC_drsuapi2_update_refs_config_recv(struct rpc_request *req)
2764 {
2765         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2766                                           struct libnet_BecomeDC_state);
2767         struct composite_context *c = s->creq;
2768         struct drsuapi_DsReplicaUpdateRefs *r = talloc_get_type(req->ndr.struct_ptr,
2769                                            struct drsuapi_DsReplicaUpdateRefs);
2770
2771         c->status = dcerpc_ndr_request_recv(req);
2772         if (!composite_is_ok(c)) return;
2773
2774         if (!W_ERROR_IS_OK(r->out.result)) {
2775                 composite_error(c, werror_to_ntstatus(r->out.result));
2776                 return;
2777         }
2778
2779         talloc_free(r);
2780
2781         becomeDC_drsuapi_update_refs_send(s, &s->drsuapi2, &s->domain_part,
2782                                           becomeDC_drsuapi2_update_refs_domain_recv);
2783 }
2784
2785 static void becomeDC_drsuapi2_update_refs_domain_recv(struct rpc_request *req)
2786 {
2787         struct libnet_BecomeDC_state *s = talloc_get_type(req->async.private_data,
2788                                           struct libnet_BecomeDC_state);
2789         struct composite_context *c = s->creq;
2790         struct drsuapi_DsReplicaUpdateRefs *r = talloc_get_type(req->ndr.struct_ptr,
2791                                            struct drsuapi_DsReplicaUpdateRefs);
2792
2793         c->status = dcerpc_ndr_request_recv(req);
2794         if (!composite_is_ok(c)) return;
2795
2796         if (!W_ERROR_IS_OK(r->out.result)) {
2797                 composite_error(c, werror_to_ntstatus(r->out.result));
2798                 return;
2799         }
2800
2801         talloc_free(r);
2802
2803         /* TODO: use DDNS updates and register dns names */
2804         composite_done(c);
2805 }
2806
2807 static NTSTATUS becomeDC_ldap2_modify_computer(struct libnet_BecomeDC_state *s)
2808 {
2809         int ret;
2810         struct ldb_message *msg;
2811         uint32_t i;
2812         uint32_t user_account_control = UF_SERVER_TRUST_ACCOUNT |
2813                                         UF_TRUSTED_FOR_DELEGATION;
2814
2815         /* as the value is already as we want it to be, we're done */
2816         if (s->dest_dsa.user_account_control == user_account_control) {
2817                 return NT_STATUS_OK;
2818         }
2819
2820         /* make a 'modify' msg, and only for serverReference */
2821         msg = ldb_msg_new(s);
2822         NT_STATUS_HAVE_NO_MEMORY(msg);
2823         msg->dn = ldb_dn_new(msg, s->ldap2.ldb, s->dest_dsa.computer_dn_str);
2824         NT_STATUS_HAVE_NO_MEMORY(msg->dn);
2825
2826         ret = ldb_msg_add_fmt(msg, "userAccountControl", "%u", user_account_control);
2827         if (ret != 0) {
2828                 talloc_free(msg);
2829                 return NT_STATUS_NO_MEMORY;
2830         }
2831
2832         /* mark all the message elements (should be just one)
2833            as LDB_FLAG_MOD_REPLACE */
2834         for (i=0;i<msg->num_elements;i++) {
2835                 msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
2836         }
2837
2838         ret = ldb_modify(s->ldap2.ldb, msg);
2839         talloc_free(msg);
2840         if (ret != LDB_SUCCESS) {
2841                 return NT_STATUS_LDAP(ret);
2842         }
2843
2844         s->dest_dsa.user_account_control = user_account_control;
2845
2846         return NT_STATUS_OK;
2847 }
2848
2849 static NTSTATUS becomeDC_ldap2_move_computer(struct libnet_BecomeDC_state *s)
2850 {
2851         int ret;
2852         struct ldb_result *r;
2853         struct ldb_dn *basedn;
2854         struct ldb_dn *old_dn;
2855         struct ldb_dn *new_dn;
2856         static const char *_1_1_attrs[] = {
2857                 "1.1",
2858                 NULL
2859         };
2860
2861         basedn = ldb_dn_new_fmt(s, s->ldap2.ldb, "<WKGUID=a361b2ffffd211d1aa4b00c04fd7d83a,%s>",
2862                                 s->domain.dn_str);
2863         NT_STATUS_HAVE_NO_MEMORY(basedn);
2864
2865         ret = ldb_search(s->ldap2.ldb, basedn, LDB_SCOPE_BASE,
2866                          "(objectClass=*)", _1_1_attrs, &r);
2867         talloc_free(basedn);
2868         if (ret != LDB_SUCCESS) {
2869                 return NT_STATUS_LDAP(ret);
2870         } else if (r->count != 1) {
2871                 talloc_free(r);
2872                 return NT_STATUS_INVALID_NETWORK_RESPONSE;
2873         }
2874
2875         old_dn = ldb_dn_new(r, s->ldap2.ldb, s->dest_dsa.computer_dn_str);
2876         NT_STATUS_HAVE_NO_MEMORY(old_dn);
2877
2878         new_dn = r->msgs[0]->dn;
2879
2880         if (!ldb_dn_add_child_fmt(new_dn, "CN=%s", s->dest_dsa.netbios_name)) {
2881                 talloc_free(r);
2882                 return NT_STATUS_NO_MEMORY;
2883         }
2884
2885         if (ldb_dn_compare(old_dn, new_dn) == 0) {
2886                 /* we don't need to rename if the old and new dn match */
2887                 talloc_free(r);
2888                 return NT_STATUS_OK;
2889         }
2890
2891         ret = ldb_rename(s->ldap2.ldb, old_dn, new_dn);
2892         if (ret != LDB_SUCCESS) {
2893                 talloc_free(r);
2894                 return NT_STATUS_LDAP(ret);
2895         }
2896
2897         s->dest_dsa.computer_dn_str = ldb_dn_alloc_linearized(s, new_dn);
2898         NT_STATUS_HAVE_NO_MEMORY(s->dest_dsa.computer_dn_str);
2899
2900         talloc_free(r);
2901
2902         return NT_STATUS_OK;
2903 }
2904
2905 static void becomeDC_connect_ldap2(struct libnet_BecomeDC_state *s)
2906 {
2907         struct composite_context *c = s->creq;
2908
2909         c->status = becomeDC_ldap_connect(s, &s->ldap2);
2910         if (!composite_is_ok(c)) return;
2911
2912         c->status = becomeDC_ldap2_modify_computer(s);
2913         if (!composite_is_ok(c)) return;
2914
2915         c->status = becomeDC_ldap2_move_computer(s);
2916         if (!composite_is_ok(c)) return;
2917
2918         becomeDC_drsuapi3_pull_domain_send(s);
2919 }
2920
2921 struct composite_context *libnet_BecomeDC_send(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_BecomeDC *r)
2922 {
2923         struct composite_context *c;
2924         struct libnet_BecomeDC_state *s;
2925         char *tmp_name;
2926
2927         c = composite_create(mem_ctx, ctx->event_ctx);
2928         if (c == NULL) return NULL;
2929
2930         s = talloc_zero(c, struct libnet_BecomeDC_state);
2931         if (composite_nomem(s, c)) return c;
2932         c->private_data = s;
2933         s->creq         = c;
2934         s->libnet       = ctx;
2935
2936         /* Domain input */
2937         s->domain.dns_name      = talloc_strdup(s, r->in.domain_dns_name);
2938         if (composite_nomem(s->domain.dns_name, c)) return c;
2939         s->domain.netbios_name  = talloc_strdup(s, r->in.domain_netbios_name);
2940         if (composite_nomem(s->domain.netbios_name, c)) return c;
2941         s->domain.sid           = dom_sid_dup(s, r->in.domain_sid);
2942         if (composite_nomem(s->domain.sid, c)) return c;
2943
2944         /* Source DSA input */
2945         s->source_dsa.address   = talloc_strdup(s, r->in.source_dsa_address);
2946         if (composite_nomem(s->source_dsa.address, c)) return c;
2947
2948         /* Destination DSA input */
2949         s->dest_dsa.netbios_name= talloc_strdup(s, r->in.dest_dsa_netbios_name);
2950         if (composite_nomem(s->dest_dsa.netbios_name, c)) return c;
2951
2952         /* Destination DSA dns_name construction */
2953         tmp_name        = strlower_talloc(s, s->dest_dsa.netbios_name);
2954         if (composite_nomem(tmp_name, c)) return c;
2955         tmp_name        = talloc_asprintf_append_buffer(tmp_name, ".%s",s->domain.dns_name);
2956         if (composite_nomem(tmp_name, c)) return c;
2957         s->dest_dsa.dns_name    = tmp_name;
2958
2959         /* Callback function pointers */
2960         s->callbacks = r->in.callbacks;
2961
2962         becomeDC_send_cldap(s);
2963         return c;
2964 }
2965
2966 NTSTATUS libnet_BecomeDC_recv(struct composite_context *c, TALLOC_CTX *mem_ctx, struct libnet_BecomeDC *r)
2967 {
2968         NTSTATUS status;
2969
2970         status = composite_wait(c);
2971
2972         ZERO_STRUCT(r->out);
2973
2974         talloc_free(c);
2975         return status;
2976 }
2977
2978 NTSTATUS libnet_BecomeDC(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_BecomeDC *r)
2979 {
2980         NTSTATUS status;
2981         struct composite_context *c;
2982         c = libnet_BecomeDC_send(ctx, mem_ctx, r);
2983         status = libnet_BecomeDC_recv(c, mem_ctx, r);
2984         return status;
2985 }