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