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