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