r11410: Fix rejoin as a BDC by modifying, rather than trying to recreate, the
[ira/wip.git] / source / libnet / libnet_join.c
1 /* 
2    Unix SMB/CIFS implementation.
3    
4    Copyright (C) Stefan Metzmacher      2004
5    Copyright (C) Andrew Bartlett <abartlet@samba.org> 2005
6    Copyright (C) Brad Henry 2005
7  
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12    
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17    
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21 */
22
23 #include "includes.h"
24 #include "libnet/libnet.h"
25 #include "librpc/gen_ndr/ndr_samr.h"
26 #include "librpc/gen_ndr/ndr_lsa.h"
27 #include "librpc/gen_ndr/ndr_drsuapi.h"
28 #include "lib/ldb/include/ldb.h"
29 #include "lib/ldb/include/ldb_errors.h"
30 #include "libcli/cldap/cldap.h"
31 #include "include/secrets.h"
32 #include "librpc/gen_ndr/drsuapi.h"
33
34 /*
35  * find out Site specific stuff:
36  * 1.) setup an CLDAP socket
37  * 2.) lookup the Site name
38  * 3.) Add entry CN=<netbios name>,CN=Servers,CN=<site name>,CN=Sites,CN=Configuration,<domain dn>.
39  * TODO: 4.) use DsAddEntry() to create CN=NTDS Settings,CN=<netbios name>,CN=Servers,CN=<site name>...
40  */
41 static NTSTATUS libnet_JoinSite(struct libnet_context *ctx,
42                                 struct dcerpc_pipe *drsuapi_pipe,
43                                 struct policy_handle drsuapi_bind_handle,
44                                 struct ldb_context *remote_ldb,
45                                 struct libnet_JoinDomain *libnet_r)
46 {
47         NTSTATUS status;
48         TALLOC_CTX *tmp_ctx;
49
50         struct cldap_socket *cldap = NULL;
51         struct cldap_netlogon search;
52
53         struct ldb_dn *server_dn;
54         struct ldb_message *msg;
55         int rtn;
56
57         const char *site_name;
58         const char *server_dn_str;
59         const char *config_dn_str;
60
61         tmp_ctx = talloc_named(libnet_r, 0, "libnet_JoinSite temp context");
62         if (!tmp_ctx) {
63                 libnet_r->out.error_string = NULL;
64                 return NT_STATUS_NO_MEMORY;
65         }
66
67         /* Resolve the site name. */
68
69         ZERO_STRUCT(search);
70         search.in.dest_address = libnet_r->out.samr_binding->host;
71         search.in.acct_control = -1;
72         search.in.version = 6;
73
74         cldap = cldap_socket_init(tmp_ctx, NULL);
75         status = cldap_netlogon(cldap, tmp_ctx, &search);
76         if (!NT_STATUS_IS_OK(status)) {
77                 /* Default to using Default-First-Site-Name rather than returning status at this point. */
78                 site_name = talloc_asprintf(tmp_ctx, "%s", "Default-First-Site-Name");
79                 if (!site_name) {
80                         libnet_r->out.error_string = NULL;
81                         talloc_free(tmp_ctx);
82                         return NT_STATUS_NO_MEMORY;
83                 }
84         } else {
85                 site_name = search.out.netlogon.logon5.site_name;
86         }
87
88         config_dn_str = talloc_asprintf(tmp_ctx, "CN=Configuration,%s", libnet_r->out.domain_dn_str);
89         if (!config_dn_str) {
90                 libnet_r->out.error_string = NULL;
91                 talloc_free(tmp_ctx);
92                 return NT_STATUS_NO_MEMORY;
93         }
94
95         server_dn_str = talloc_asprintf(tmp_ctx, "CN=%s,CN=Servers,CN=%s,CN=Sites,%s",
96                                                  libnet_r->in.netbios_name, site_name, config_dn_str);
97         if (!server_dn_str) {
98                 libnet_r->out.error_string = NULL;
99                 talloc_free(tmp_ctx);
100                 return NT_STATUS_NO_MEMORY;
101         }
102
103         /*
104          Add entry CN=<netbios name>,CN=Servers,CN=<site name>,CN=Sites,CN=Configuration,<domain dn>.
105         */
106         msg = ldb_msg_new(tmp_ctx);
107         if (!msg) {
108                 libnet_r->out.error_string = NULL;
109                 talloc_free(tmp_ctx);
110                 return NT_STATUS_NO_MEMORY;
111         }
112
113         rtn = ldb_msg_add_string(msg, "objectClass", "server");
114         if (rtn != 0) {
115                 libnet_r->out.error_string = NULL;
116                 talloc_free(tmp_ctx);
117                 return NT_STATUS_NO_MEMORY;
118         }
119         rtn = ldb_msg_add_string(msg, "systemFlags", "50000000");
120         if (rtn != 0) {
121                 libnet_r->out.error_string = NULL;
122                 talloc_free(tmp_ctx);
123                 return NT_STATUS_NO_MEMORY;
124         }
125         rtn = ldb_msg_add_string(msg, "serverReference",libnet_r->out.account_dn_str);
126         if (rtn != 0) {
127                 libnet_r->out.error_string = NULL;
128                 talloc_free(tmp_ctx);
129                 return NT_STATUS_NO_MEMORY;
130         }
131
132         server_dn = ldb_dn_explode(tmp_ctx, server_dn_str);
133         if (server_dn == NULL) {
134                 libnet_r->out.error_string = talloc_asprintf(libnet_r, 
135                                         "Invalid server dn: %s",
136                                         server_dn_str);
137                 talloc_free(tmp_ctx);
138                 return NT_STATUS_UNSUCCESSFUL;
139         }
140
141         msg->dn = server_dn; 
142
143         rtn = ldb_add(remote_ldb, msg);
144         if (rtn == LDB_ERR_ENTRY_ALREADY_EXISTS) {
145                 int i;
146                 
147                 /* make a 'modify' msg, and only for serverReference */
148                 msg = ldb_msg_new(tmp_ctx);
149                 if (!msg) {
150                         libnet_r->out.error_string = NULL;
151                         talloc_free(tmp_ctx);
152                         return NT_STATUS_NO_MEMORY;
153                 }
154                 msg->dn = server_dn; 
155
156                 rtn = ldb_msg_add_string(msg, "serverReference",libnet_r->out.account_dn_str);
157                 if (rtn != 0) {
158                         libnet_r->out.error_string = NULL;
159                         talloc_free(tmp_ctx);
160                         return NT_STATUS_NO_MEMORY;
161                 }
162                 
163                 /* mark all the message elements (should be just one)
164                    as LDB_FLAG_MOD_REPLACE */
165                 for (i=0;i<msg->num_elements;i++) {
166                         msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
167                 }
168
169                 rtn = ldb_modify(remote_ldb, msg);
170                 if (rtn != 0) {
171                         libnet_r->out.error_string
172                                 = talloc_asprintf(libnet_r,
173                                                   "Failed to modify server entry %s: %s: %d",
174                                                   server_dn_str,
175                                                   ldb_errstring(remote_ldb), rtn);
176                         talloc_free(tmp_ctx);
177                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
178                 }
179         } else if (rtn != 0) {
180                 libnet_r->out.error_string
181                         = talloc_asprintf(libnet_r,
182                                 "Failed to add server entry %s: %s: %d",
183                                 server_dn_str,
184                                           ldb_errstring(remote_ldb), rtn);
185                 talloc_free(tmp_ctx);
186                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
187         }
188         DEBUG(0, ("We still need to perform a DsAddEntry() so that we can create the CN=NTDS Settings container.\n"));
189
190         /* Store the server DN in libnet_r */
191         libnet_r->out.server_dn_str = server_dn_str;
192         talloc_steal(libnet_r, server_dn_str);
193         
194         talloc_free(tmp_ctx);
195         return NT_STATUS_OK;
196 }
197
198 /*
199  * complete a domain join, when joining to a AD domain:
200  * 1.) connect and bind to the DRSUAPI pipe
201  * 2.) do a DsCrackNames() to find the machine account dn
202  * 3.) connect to LDAP
203  * 4.) do an ldap search to find the "msDS-KeyVersionNumber" of the machine account
204  * 5.) set the servicePrincipalName's of the machine account via LDAP, (maybe we should use DsWriteAccountSpn()...)
205  * 6.) do a DsCrackNames() to find the domain dn
206  * 7.) find out Site specific stuff, look at libnet_JoinSite() for details
207  */
208 static NTSTATUS libnet_JoinADSDomain(struct libnet_context *ctx, struct libnet_JoinDomain *r)
209 {
210         NTSTATUS status;
211
212         TALLOC_CTX *tmp_ctx;
213
214         const char *realm = r->out.realm;
215
216         struct dcerpc_binding *samr_binding = r->out.samr_binding;
217
218         struct dcerpc_pipe *drsuapi_pipe;
219         struct dcerpc_binding *drsuapi_binding;
220         struct drsuapi_DsBind r_drsuapi_bind;
221         struct drsuapi_DsCrackNames r_crack_names;
222         struct drsuapi_DsNameString names[1];
223         struct policy_handle drsuapi_bind_handle;
224         struct GUID drsuapi_bind_guid;
225
226         struct ldb_context *remote_ldb;
227         const struct ldb_dn *account_dn;
228         const char *account_dn_str;
229         const char *remote_ldb_url;
230         struct ldb_message **msgs, *msg;
231
232         int rtn;
233
234         unsigned int kvno;
235         
236         const char * const attrs[] = {
237                 "msDS-KeyVersionNumber",
238                 "servicePrincipalName",
239                 "dNSHostName",
240                 NULL,
241         };
242
243         r->out.error_string = NULL;
244         
245         /* We need to convert between a samAccountName and domain to a
246          * DN in the directory.  The correct way to do this is with
247          * DRSUAPI CrackNames */
248
249         /* Fiddle with the bindings, so get to DRSUAPI on
250          * NCACN_IP_TCP, sealed */
251         tmp_ctx = talloc_named(r, 0, "libnet_JoinADSDomain temp context");  
252         if (!tmp_ctx) {
253                 r->out.error_string = NULL;
254                 return NT_STATUS_NO_MEMORY;
255         }
256                                                    
257         drsuapi_binding = talloc(tmp_ctx, struct dcerpc_binding);
258         if (!drsuapi_binding) {
259                 r->out.error_string = NULL;
260                 talloc_free(tmp_ctx);
261                 return NT_STATUS_NO_MEMORY;
262         }
263         
264         *drsuapi_binding = *samr_binding;
265
266         /* DRSUAPI is only available on IP_TCP, and locally on NCALRPC */
267         if (drsuapi_binding->transport != NCALRPC) {
268                 drsuapi_binding->transport = NCACN_IP_TCP;
269         }
270         drsuapi_binding->endpoint = NULL;
271         drsuapi_binding->flags |= DCERPC_SEAL;
272
273         status = dcerpc_pipe_connect_b(tmp_ctx, 
274                                        &drsuapi_pipe,
275                                        drsuapi_binding,
276                                        DCERPC_DRSUAPI_UUID,
277                                        DCERPC_DRSUAPI_VERSION, 
278                                        ctx->cred, 
279                                        ctx->event_ctx);
280         if (!NT_STATUS_IS_OK(status)) {
281                 r->out.error_string = talloc_asprintf(r,
282                                         "Connection to DRSUAPI pipe of PDC of domain '%s' failed: %s",
283                                         r->in.domain_name,
284                                         nt_errstr(status));
285                 talloc_free(tmp_ctx);
286                 return status;
287         }
288
289         /* get a DRSUAPI pipe handle */
290         GUID_from_string(DRSUAPI_DS_BIND_GUID, &drsuapi_bind_guid);
291
292         r_drsuapi_bind.in.bind_guid = &drsuapi_bind_guid;
293         r_drsuapi_bind.in.bind_info = NULL;
294         r_drsuapi_bind.out.bind_handle = &drsuapi_bind_handle;
295
296         status = dcerpc_drsuapi_DsBind(drsuapi_pipe, tmp_ctx, &r_drsuapi_bind);
297         if (!NT_STATUS_IS_OK(status)) {
298                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
299                         r->out.error_string
300                                 = talloc_asprintf(r,
301                                                   "dcerpc_drsuapi_DsBind for [%s\\%s] failed - %s\n", 
302                                                   r->in.domain_name, r->in.account_name, 
303                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
304                         talloc_free(tmp_ctx);
305                         return status;
306                 } else {
307                         r->out.error_string
308                                 = talloc_asprintf(r,
309                                                   "dcerpc_drsuapi_DsBind for [%s\\%s] failed - %s\n", 
310                                                   r->in.domain_name, r->in.account_name, 
311                                                   nt_errstr(status));
312                         talloc_free(tmp_ctx);
313                         return status;
314                 }
315         } else if (!W_ERROR_IS_OK(r_drsuapi_bind.out.result)) {
316                 r->out.error_string
317                                 = talloc_asprintf(r,
318                                                   "DsBind failed - %s\n", 
319                                                   win_errstr(r_drsuapi_bind.out.result));
320                         talloc_free(tmp_ctx);
321                 return NT_STATUS_UNSUCCESSFUL;
322         }
323
324         /* Actually 'crack' the names */
325         ZERO_STRUCT(r_crack_names);
326         r_crack_names.in.bind_handle            = &drsuapi_bind_handle;
327         r_crack_names.in.level                  = 1;
328         r_crack_names.in.req.req1.unknown1      = 0x000004e4;
329         r_crack_names.in.req.req1.unknown2      = 0x00000407;
330         r_crack_names.in.req.req1.count         = 1;
331         r_crack_names.in.req.req1.names         = names;
332         r_crack_names.in.req.req1.format_flags  = DRSUAPI_DS_NAME_FLAG_NO_FLAGS;
333         r_crack_names.in.req.req1.format_offered= DRSUAPI_DS_NAME_FORMAT_SID_OR_SID_HISTORY;
334         r_crack_names.in.req.req1.format_desired= DRSUAPI_DS_NAME_FORMAT_FQDN_1779;
335         names[0].str = dom_sid_string(tmp_ctx, r->out.account_sid);
336         if (!names[0].str) {
337                 r->out.error_string = NULL;
338                 talloc_free(tmp_ctx);
339                 return NT_STATUS_NO_MEMORY;
340         }
341
342         status = dcerpc_drsuapi_DsCrackNames(drsuapi_pipe, tmp_ctx, &r_crack_names);
343         if (!NT_STATUS_IS_OK(status)) {
344                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
345                         r->out.error_string
346                                 = talloc_asprintf(r,
347                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s\n", 
348                                                   names[0].str,
349                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
350                         talloc_free(tmp_ctx);
351                         return status;
352                 } else {
353                         r->out.error_string
354                                 = talloc_asprintf(r,
355                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s\n", 
356                                                   names[0].str,
357                                                   nt_errstr(status));
358                         talloc_free(tmp_ctx);
359                         return status;
360                 }
361         } else if (!W_ERROR_IS_OK(r_crack_names.out.result)) {
362                 r->out.error_string
363                                 = talloc_asprintf(r,
364                                                   "DsCrackNames failed - %s\n", win_errstr(r_crack_names.out.result));
365                 talloc_free(tmp_ctx);
366                 return NT_STATUS_UNSUCCESSFUL;
367         } else if (r_crack_names.out.level != 1 
368                    || !r_crack_names.out.ctr.ctr1 
369                    || r_crack_names.out.ctr.ctr1->count != 1 
370                    || !r_crack_names.out.ctr.ctr1->array[0].result_name
371                    || r_crack_names.out.ctr.ctr1->array[0].status != DRSUAPI_DS_NAME_STATUS_OK) {
372                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed\n");
373                 talloc_free(tmp_ctx);
374                 return NT_STATUS_UNSUCCESSFUL;
375         }
376
377         /* Store the DN of our machine account. */
378         account_dn_str = r_crack_names.out.ctr.ctr1->array[0].result_name;
379
380         account_dn = ldb_dn_explode(tmp_ctx, account_dn_str);
381         if (!account_dn) {
382                 r->out.error_string = talloc_asprintf(r, "Invalid account dn: %s",
383                                                       account_dn_str);
384                 talloc_free(tmp_ctx);
385                 return NT_STATUS_UNSUCCESSFUL;
386         }
387
388         /* Now we know the user's DN, open with LDAP, read and modify a few things */
389
390         remote_ldb_url = talloc_asprintf(tmp_ctx, "ldap://%s", 
391                                          drsuapi_binding->host);
392         if (!remote_ldb_url) {
393                 r->out.error_string = NULL;
394                 talloc_free(tmp_ctx);
395                 return NT_STATUS_NO_MEMORY;
396         }
397
398         remote_ldb = ldb_wrap_connect(tmp_ctx, remote_ldb_url, 0, NULL);
399         if (!remote_ldb) {
400                 r->out.error_string = NULL;
401                 talloc_free(tmp_ctx);
402                 return NT_STATUS_UNSUCCESSFUL;
403         }
404
405         /* search for the user's record */
406         rtn = ldb_search(remote_ldb, account_dn, LDB_SCOPE_BASE, 
407                              NULL, attrs, &msgs);
408         if (rtn != 1) {
409                 r->out.error_string = talloc_asprintf(r, "ldb_search for %s failed - %s\n",
410                                                       account_dn_str, ldb_errstring(remote_ldb));
411                 talloc_free(tmp_ctx);
412                 return NT_STATUS_UNSUCCESSFUL;
413         }
414
415         /* If we have a kvno recorded in AD, we need it locally as well */
416         kvno = ldb_msg_find_uint(msgs[0], "msDS-KeyVersionNumber", 0);
417
418         /* Prepare a new message, for the modify */
419         msg = ldb_msg_new(tmp_ctx);
420         if (!msg) {
421                 r->out.error_string = NULL;
422                 talloc_free(tmp_ctx);
423                 return NT_STATUS_NO_MEMORY;
424         }
425         msg->dn = msgs[0]->dn;
426
427         {
428                 int i;
429                 const char *service_principal_name[6];
430                 const char *dns_host_name = strlower_talloc(tmp_ctx, 
431                                                             talloc_asprintf(tmp_ctx, 
432                                                                             "%s.%s", 
433                                                                             r->in.netbios_name, 
434                                                                             realm));
435
436                 if (!dns_host_name) {
437                         r->out.error_string = NULL;
438                         talloc_free(tmp_ctx);
439                         return NT_STATUS_NO_MEMORY;
440                 }
441
442                 service_principal_name[0] = talloc_asprintf(tmp_ctx, "host/%s", dns_host_name);
443                 service_principal_name[1] = talloc_asprintf(tmp_ctx, "host/%s", strlower_talloc(tmp_ctx, r->in.netbios_name));
444                 service_principal_name[2] = talloc_asprintf(tmp_ctx, "host/%s/%s", dns_host_name, realm);
445                 service_principal_name[3] = talloc_asprintf(tmp_ctx, "host/%s/%s", strlower_talloc(tmp_ctx, r->in.netbios_name), realm);
446                 service_principal_name[4] = talloc_asprintf(tmp_ctx, "host/%s/%s", dns_host_name, r->out.domain_name);
447                 service_principal_name[5] = talloc_asprintf(tmp_ctx, "host/%s/%s", strlower_talloc(tmp_ctx, r->in.netbios_name), r->out.domain_name);
448                 
449                 for (i=0; i < ARRAY_SIZE(service_principal_name); i++) {
450                         if (!service_principal_name[i]) {
451                                 r->out.error_string = NULL;
452                                 talloc_free(tmp_ctx);
453                                 return NT_STATUS_NO_MEMORY;
454                         }
455                         rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "servicePrincipalName", service_principal_name[i]);
456                         if (rtn == -1) {
457                                 r->out.error_string = NULL;
458                                 talloc_free(tmp_ctx);
459                                 return NT_STATUS_NO_MEMORY;
460                         }
461                 }
462
463                 rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "dNSHostName", dns_host_name);
464                 if (rtn == -1) {
465                         r->out.error_string = NULL;
466                         talloc_free(tmp_ctx);
467                         return NT_STATUS_NO_MEMORY;
468                 }
469
470                 rtn = samdb_replace(remote_ldb, tmp_ctx, msg);
471                 if (rtn != 0) {
472                         r->out.error_string
473                                 = talloc_asprintf(r, 
474                                                   "Failed to replace entries on %s\n", 
475                                                   ldb_dn_linearize(tmp_ctx, msg->dn));
476                         talloc_free(tmp_ctx);
477                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
478                 }
479         }
480                                 
481         /* DsCrackNames to find out the DN of the domain. */
482         r_crack_names.in.req.req1.format_offered = DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT;
483         r_crack_names.in.req.req1.format_desired = DRSUAPI_DS_NAME_FORMAT_FQDN_1779;
484         names[0].str = talloc_asprintf(tmp_ctx, "%s\\", r->out.domain_name);
485         if (!names[0].str) {
486                 r->out.error_string = NULL;
487                 talloc_free(tmp_ctx);
488                 return NT_STATUS_NO_MEMORY;
489         }
490
491         status = dcerpc_drsuapi_DsCrackNames(drsuapi_pipe, tmp_ctx, &r_crack_names);
492         if (!NT_STATUS_IS_OK(status)) {
493                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
494                         r->out.error_string
495                                 = talloc_asprintf(r,
496                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s\n", 
497                                                   r->in.domain_name, 
498                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
499                         talloc_free(tmp_ctx);
500                         return status;
501                 } else {
502                         r->out.error_string
503                                 = talloc_asprintf(r,
504                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s\n", 
505                                                   r->in.domain_name, 
506                                                   nt_errstr(status));
507                         talloc_free(tmp_ctx);
508                         return status;
509                 }
510         } else if (!W_ERROR_IS_OK(r_crack_names.out.result)) {
511                 r->out.error_string
512                         = talloc_asprintf(r,
513                                           "DsCrackNames failed - %s\n", win_errstr(r_crack_names.out.result));
514                 talloc_free(tmp_ctx);
515                 return NT_STATUS_UNSUCCESSFUL;
516         } else if (r_crack_names.out.level != 1 
517                    || !r_crack_names.out.ctr.ctr1 
518                    || r_crack_names.out.ctr.ctr1->count != 1
519                    || !r_crack_names.out.ctr.ctr1->array[0].result_name           
520                    || r_crack_names.out.ctr.ctr1->array[0].status != DRSUAPI_DS_NAME_STATUS_OK) {
521                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed\n");
522                 talloc_free(tmp_ctx);
523                 return NT_STATUS_UNSUCCESSFUL;
524         }
525
526         /* Store the account DN. */
527         r->out.account_dn_str = account_dn_str;
528         talloc_steal(r, account_dn_str);
529
530         /* Store the domain DN. */
531         r->out.domain_dn_str = r_crack_names.out.ctr.ctr1->array[0].result_name;
532         talloc_steal(r, r_crack_names.out.ctr.ctr1->array[0].result_name);
533
534         r->out.kvno = kvno;
535
536         if (r->in.acct_type ==  ACB_SVRTRUST) {
537                 status = libnet_JoinSite(ctx,
538                                          drsuapi_pipe, drsuapi_bind_handle,
539                                          remote_ldb, r);
540         }
541         talloc_free(tmp_ctx);
542
543         return status;
544 }
545
546 /*
547  * do a domain join using DCERPC/SAMR calls
548  * 1. connect to the SAMR pipe of users domain PDC (maybe a standalone server or workstation)
549  *    is it correct to contact the the pdc of the domain of the user who's password should be set?
550  * 2. do a samr_Connect to get a policy handle
551  * 3. do a samr_LookupDomain to get the domain sid
552  * 4. do a samr_OpenDomain to get a domain handle
553  * 5. do a samr_CreateAccount to try and get a new account 
554  * 
555  * If that fails, do:
556  * 5.1. do a samr_LookupNames to get the users rid
557  * 5.2. do a samr_OpenUser to get a user handle
558  * 
559  * 6. call libnet_SetPassword_samr_handle to set the password
560  *
561  * 7. do a samrSetUserInfo to set the account flags
562  * 8. do some ADS specific things when we join as Domain Controller,
563  *    look at libnet_joinADSDomain() for the details
564  */
565 NTSTATUS libnet_JoinDomain(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_JoinDomain *r)
566 {
567         TALLOC_CTX *tmp_ctx;
568
569         NTSTATUS status, cu_status;
570         struct libnet_RpcConnect *c;
571         struct lsa_ObjectAttribute attr;
572         struct lsa_QosInfo qos;
573         struct lsa_OpenPolicy2 lsa_open_policy;
574         struct policy_handle lsa_p_handle;
575         struct lsa_QueryInfoPolicy2 lsa_query_info2;
576         struct lsa_QueryInfoPolicy lsa_query_info;
577
578         struct dcerpc_binding *samr_binding;
579         struct dcerpc_pipe *samr_pipe;
580         struct dcerpc_pipe *lsa_pipe;
581         struct samr_Connect sc;
582         struct policy_handle p_handle;
583         struct samr_OpenDomain od;
584         struct policy_handle d_handle;
585         struct samr_LookupNames ln;
586         struct samr_OpenUser ou;
587         struct samr_CreateUser2 cu;
588         struct policy_handle *u_handle = NULL;
589         struct samr_QueryUserInfo qui;
590         struct samr_SetUserInfo sui;
591         union samr_UserInfo u_info;
592         union libnet_SetPassword r2;
593         struct samr_GetUserPwInfo pwp;
594         struct lsa_String samr_account_name;
595         
596         uint32_t acct_flags;
597         uint32_t rid, access_granted;
598         int policy_min_pw_len = 0;
599
600         struct dom_sid *domain_sid = NULL;
601         struct dom_sid *account_sid = NULL;
602         const char *domain_name = NULL;
603         const char *password_str = NULL;
604         const char *realm = NULL; /* Also flag for remote being AD */
605         
606         
607         r->out.error_string = NULL;
608         r2.samr_handle.out.error_string = NULL;
609         
610         tmp_ctx = talloc_named(mem_ctx, 0, "libnet_Join temp context");
611         if (!tmp_ctx) {
612                 r->out.error_string = NULL;
613                 return NT_STATUS_NO_MEMORY;
614         }
615         
616         u_handle = talloc(tmp_ctx, struct policy_handle);
617         if (!u_handle) {
618                 r->out.error_string = NULL;
619                 talloc_free(tmp_ctx);
620                 return NT_STATUS_NO_MEMORY;
621         }
622         
623         samr_pipe = talloc(tmp_ctx, struct dcerpc_pipe);
624         if (!samr_pipe) {
625                 r->out.error_string = NULL;
626                 talloc_free(tmp_ctx);
627                 return NT_STATUS_NO_MEMORY;
628         }
629         
630         c = talloc(tmp_ctx, struct libnet_RpcConnect);
631         if (!c) {
632                 r->out.error_string = NULL;
633                 talloc_free(tmp_ctx);
634                 return NT_STATUS_NO_MEMORY;
635         }
636         
637         /* prepare connect to the LSA pipe of PDC */
638         if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
639                 c->level             = LIBNET_RPC_CONNECT_PDC;
640                 c->in.domain_name    = r->in.domain_name;
641         } else {
642                 c->level             = LIBNET_RPC_CONNECT_BINDING;
643                 c->in.binding        = r->in.binding;
644         }
645         c->in.dcerpc_iface_name      = DCERPC_LSARPC_NAME;
646         c->in.dcerpc_iface_uuid      = DCERPC_LSARPC_UUID;
647         c->in.dcerpc_iface_version   = DCERPC_LSARPC_VERSION;
648         
649         /* connect to the LSA pipe of the PDC */
650
651         status = libnet_RpcConnect(ctx, c, c);
652         if (!NT_STATUS_IS_OK(status)) {
653                 if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
654                         r->out.error_string = talloc_asprintf(mem_ctx,
655                                                               "Connection to LSA pipe of PDC of domain '%s' failed: %s",
656                                                               r->in.domain_name, nt_errstr(status));
657                 } else {
658                         r->out.error_string = talloc_asprintf(mem_ctx,
659                                                               "Connection to LSA pipe with binding '%s' failed: %s",
660                                                               r->in.binding, nt_errstr(status));
661                 }
662                 talloc_free(tmp_ctx);
663                 return status;
664         }                       
665         lsa_pipe = c->out.dcerpc_pipe;
666         
667         /* Get an LSA policy handle */
668
669         ZERO_STRUCT(lsa_p_handle);
670         qos.len = 0;
671         qos.impersonation_level = 2;
672         qos.context_mode = 1;
673         qos.effective_only = 0;
674
675         attr.len = 0;
676         attr.root_dir = NULL;
677         attr.object_name = NULL;
678         attr.attributes = 0;
679         attr.sec_desc = NULL;
680         attr.sec_qos = &qos;
681
682         lsa_open_policy.in.attr = &attr;
683         
684         lsa_open_policy.in.system_name = talloc_asprintf(tmp_ctx, "\\"); 
685         if (!lsa_open_policy.in.system_name) {
686                 r->out.error_string = NULL;
687                 talloc_free(tmp_ctx);
688                 return NT_STATUS_NO_MEMORY;
689         }
690
691         lsa_open_policy.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
692         lsa_open_policy.out.handle = &lsa_p_handle;
693
694         status = dcerpc_lsa_OpenPolicy2(lsa_pipe, tmp_ctx, &lsa_open_policy); 
695
696         /* This now fails on ncacn_ip_tcp against Win2k3 SP1 */
697         if (NT_STATUS_IS_OK(status)) {
698                 /* Look to see if this is ADS (a fault indicates NT4 or Samba 3.0) */
699                 
700                 lsa_query_info2.in.handle = &lsa_p_handle;
701                 lsa_query_info2.in.level = LSA_POLICY_INFO_DNS;
702                 
703                 status = dcerpc_lsa_QueryInfoPolicy2(lsa_pipe, tmp_ctx,                 
704                                                      &lsa_query_info2);
705                 
706                 if (!NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
707                         if (!NT_STATUS_IS_OK(status)) {
708                                 r->out.error_string = talloc_asprintf(mem_ctx,
709                                                                       "lsa_QueryInfoPolicy2 failed: %s",
710                                                                       nt_errstr(status));
711                                 talloc_free(tmp_ctx);
712                                 return status;
713                         }
714                         realm = lsa_query_info2.out.info->dns.dns_domain.string;
715                 }
716                 
717                 /* Grab the domain SID (regardless of the result of the previous call */
718                 
719                 lsa_query_info.in.handle = &lsa_p_handle;
720                 lsa_query_info.in.level = LSA_POLICY_INFO_DOMAIN;
721                 
722                 status = dcerpc_lsa_QueryInfoPolicy(lsa_pipe, tmp_ctx, 
723                                                     &lsa_query_info);
724                 
725                 if (!NT_STATUS_IS_OK(status)) {
726                         r->out.error_string = talloc_asprintf(mem_ctx,
727                                                               "lsa_QueryInfoPolicy2 failed: %s",
728                                                               nt_errstr(status));
729                         talloc_free(tmp_ctx);
730                         return status;
731                 }
732                 
733                 domain_sid = lsa_query_info.out.info->domain.sid;
734                 domain_name = lsa_query_info.out.info->domain.name.string;
735         } else {
736                 /* Cause the code further down to try this with just SAMR */
737                 domain_sid = NULL;
738                 if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
739                         domain_name = talloc_strdup(tmp_ctx, r->in.domain_name);
740                 } else {
741                         /* Bugger, we just lost our way to automaticly find the domain name */
742                         domain_name = talloc_strdup(tmp_ctx, lp_workgroup());
743                 }
744         }
745
746         DEBUG(0, ("Joining domain %s\n", domain_name));
747
748         /*
749           establish a SAMR connection, on the same CIFS transport
750         */
751
752         /* Find the original binding string */
753         status = dcerpc_parse_binding(tmp_ctx, lsa_pipe->conn->binding_string, &samr_binding);  
754         if (!NT_STATUS_IS_OK(status)) {
755                 r->out.error_string = talloc_asprintf(mem_ctx,
756                                                 "Failed to parse lsa binding '%s'",
757                                                 lsa_pipe->conn->binding_string);
758                 talloc_free(tmp_ctx);
759                 return status;
760         }
761
762         /* Make binding string for samr, not the other pipe */
763         status = dcerpc_epm_map_binding(tmp_ctx, samr_binding,                                  
764                                         DCERPC_SAMR_UUID, DCERPC_SAMR_VERSION,
765                                         lsa_pipe->conn->event_ctx);
766         if (!NT_STATUS_IS_OK(status)) {
767                 r->out.error_string = talloc_asprintf(mem_ctx,
768                                                 "Failed to map DCERPC/TCP NCACN_NP pipe for '%s' - %s",
769                                                 DCERPC_NETLOGON_UUID,
770                                                 nt_errstr(status));
771                 talloc_free(tmp_ctx);
772                 return status;
773         }
774
775         /* Setup a SAMR connection */
776         status = dcerpc_secondary_connection(lsa_pipe, &samr_pipe, samr_binding);
777         if (!NT_STATUS_IS_OK(status)) {
778                 r->out.error_string = talloc_asprintf(mem_ctx,
779                                                 "SAMR secondary connection failed: %s",
780                                                 nt_errstr(status));
781                 talloc_free(tmp_ctx);
782                 return status;
783         }
784
785         status = dcerpc_pipe_auth(samr_pipe, samr_binding, DCERPC_SAMR_UUID, 
786                                   DCERPC_SAMR_VERSION, ctx->cred);
787         if (!NT_STATUS_IS_OK(status)) {
788                 r->out.error_string = talloc_asprintf(mem_ctx,
789                                                 "SAMR bind failed: %s",
790                                                 nt_errstr(status));
791                 talloc_free(tmp_ctx);
792                 return status;
793         }
794
795         /* prepare samr_Connect */
796         ZERO_STRUCT(p_handle);
797         sc.in.system_name = NULL;
798         sc.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
799         sc.out.connect_handle = &p_handle;
800
801         /* 2. do a samr_Connect to get a policy handle */
802         status = dcerpc_samr_Connect(samr_pipe, tmp_ctx, &sc);
803         if (!NT_STATUS_IS_OK(status)) {
804                 r->out.error_string = talloc_asprintf(mem_ctx,
805                                                 "samr_Connect failed: %s",
806                                                 nt_errstr(status));
807                 talloc_free(tmp_ctx);
808                 return status;
809         }
810
811         /* Perhaps we didn't get a SID above, because we are against ncacn_ip_tcp */
812         if (!domain_sid) {
813                 struct lsa_String name;
814                 struct samr_LookupDomain l;
815                 name.string = domain_name;
816                 l.in.connect_handle = &p_handle;
817                 l.in.domain_name = &name;
818                 
819                 status = dcerpc_samr_LookupDomain(samr_pipe, tmp_ctx, &l);
820                 if (!NT_STATUS_IS_OK(status)) {
821                         r->out.error_string = talloc_asprintf(mem_ctx,
822                                                               "SAMR LookupDomain failed: %s",
823                                                               nt_errstr(status));
824                         talloc_free(tmp_ctx);
825                         return status;
826                 }
827                 domain_sid = l.out.sid;
828         }
829
830         /* prepare samr_OpenDomain */
831         ZERO_STRUCT(d_handle);
832         od.in.connect_handle = &p_handle;
833         od.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
834         od.in.sid = domain_sid;
835         od.out.domain_handle = &d_handle;
836
837         /* 4. do a samr_OpenDomain to get a domain handle */
838         status = dcerpc_samr_OpenDomain(samr_pipe, tmp_ctx, &od);                       
839         if (!NT_STATUS_IS_OK(status)) {
840                 r->out.error_string = talloc_asprintf(mem_ctx,
841                                         "samr_OpenDomain for [%s] failed: %s",
842                                         r->in.domain_name,
843                                         nt_errstr(status));
844                 talloc_free(tmp_ctx);
845                 return status;
846         }
847         
848         /* prepare samr_CreateUser2 */
849         ZERO_STRUCTP(u_handle);
850         cu.in.domain_handle  = &d_handle;
851         cu.in.access_mask     = SEC_FLAG_MAXIMUM_ALLOWED;
852         samr_account_name.string = r->in.account_name;
853         cu.in.account_name    = &samr_account_name;
854         cu.in.acct_flags      = r->in.acct_type;
855         cu.out.user_handle    = u_handle;
856         cu.out.rid            = &rid;
857         cu.out.access_granted = &access_granted;
858
859         /* 4. do a samr_CreateUser2 to get an account handle, or an error */
860         cu_status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                   
861         status = cu_status;
862         if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
863                         r->out.error_string = talloc_asprintf(mem_ctx,
864                                                                 "samr_CreateUser2 for [%s] failed: %s\n",
865                                                                 r->in.domain_name, nt_errstr(status));
866                         talloc_free(tmp_ctx);
867                         return status;
868
869         } else if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
870                 /* prepare samr_LookupNames */
871                 ln.in.domain_handle = &d_handle;
872                 ln.in.num_names = 1;
873                 ln.in.names = talloc_array(tmp_ctx, struct lsa_String, 1);
874                 if (!ln.in.names) {
875                         r->out.error_string = NULL;
876                         talloc_free(tmp_ctx);
877                         return NT_STATUS_NO_MEMORY;
878                 }
879                 ln.in.names[0].string = r->in.account_name;
880                 
881                 /* 5. do a samr_LookupNames to get the users rid */
882                 status = dcerpc_samr_LookupNames(samr_pipe, tmp_ctx, &ln);
883                 if (!NT_STATUS_IS_OK(status)) {
884                         r->out.error_string = talloc_asprintf(mem_ctx,
885                                                 "samr_LookupNames for [%s] failed: %s",
886                                                 r->in.account_name,
887                                                 nt_errstr(status));
888                         talloc_free(tmp_ctx);
889                         return status;
890                 }
891                 
892                 /* check if we got one RID for the user */
893                 if (ln.out.rids.count != 1) {
894                         r->out.error_string = talloc_asprintf(mem_ctx,
895                                                               "samr_LookupNames for [%s] returns %d RIDs\n",
896                                                               r->in.account_name, ln.out.rids.count);
897                         talloc_free(tmp_ctx);
898                         return NT_STATUS_INVALID_PARAMETER;
899                 }
900                 
901                 /* prepare samr_OpenUser */
902                 ZERO_STRUCTP(u_handle);
903                 ou.in.domain_handle = &d_handle;
904                 ou.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
905                 ou.in.rid = ln.out.rids.ids[0];
906                 rid = ou.in.rid;
907                 ou.out.user_handle = u_handle;
908                 
909                 /* 6. do a samr_OpenUser to get a user handle */
910                 status = dcerpc_samr_OpenUser(samr_pipe, tmp_ctx, &ou); 
911                 if (!NT_STATUS_IS_OK(status)) {
912                         r->out.error_string = talloc_asprintf(mem_ctx,
913                                                         "samr_OpenUser for [%s] failed: %s",
914                                                         r->in.account_name,
915                                                         nt_errstr(status));
916                         talloc_free(tmp_ctx);
917                         return status;
918                 }
919
920                 if (r->in.recreate_account) {
921                         struct samr_DeleteUser d;
922                         d.in.user_handle = u_handle;
923                         d.out.user_handle = u_handle;
924                         status = dcerpc_samr_DeleteUser(samr_pipe, mem_ctx, &d);
925                         if (!NT_STATUS_IS_OK(status)) {
926                                 r->out.error_string = talloc_asprintf(mem_ctx,
927                                                                       "samr_DeleteUser (for recreate) of [%s] failed: %s",
928                                                                       r->in.account_name,
929                                                                       nt_errstr(status));
930                                 talloc_free(tmp_ctx);
931                                 return status;
932                         }
933
934                         /* We want to recreate, so delete and another samr_CreateUser2 */
935                         
936                         /* &cu filled in above */
937                         cu_status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                   
938                         status = cu_status;
939                         if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
940                                 r->out.error_string = talloc_asprintf(mem_ctx,
941                                                                       "samr_CreateUser2 (recreate) for [%s] failed: %s\n",
942                                                                       r->in.domain_name, nt_errstr(status));
943                                 talloc_free(tmp_ctx);
944                                 return status;
945                         }
946                         DEBUG(0, ("Recreated account in domain %s\n", domain_name));
947
948                 }
949         }
950         /* Find out what password policy this user has */
951         pwp.in.user_handle = u_handle;
952
953         status = dcerpc_samr_GetUserPwInfo(samr_pipe, tmp_ctx, &pwp);                           
954         if (NT_STATUS_IS_OK(status)) {
955                 policy_min_pw_len = pwp.out.info.min_password_length;
956         }
957         
958         /* Grab a password of that minimum length */
959         
960         password_str = generate_random_str(tmp_ctx, MAX(8, policy_min_pw_len)); 
961
962         r2.samr_handle.level            = LIBNET_SET_PASSWORD_SAMR_HANDLE;
963         r2.samr_handle.in.account_name  = r->in.account_name;
964         r2.samr_handle.in.newpassword   = password_str;
965         r2.samr_handle.in.user_handle   = u_handle;
966         r2.samr_handle.in.dcerpc_pipe   = samr_pipe;
967
968         status = libnet_SetPassword(ctx, tmp_ctx, &r2); 
969         if (!NT_STATUS_IS_OK(status)) {
970                 r->out.error_string = talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
971                 talloc_free(tmp_ctx);
972                 return status;
973         }
974
975         /* prepare samr_QueryUserInfo (get flags) */
976         qui.in.user_handle = u_handle;
977         qui.in.level = 16;
978         
979         status = dcerpc_samr_QueryUserInfo(samr_pipe, tmp_ctx, &qui);
980         if (!NT_STATUS_IS_OK(status)) {
981                 r->out.error_string = talloc_asprintf(mem_ctx,
982                                                 "samr_QueryUserInfo for [%s] failed: %s",
983                                                 r->in.account_name,
984                                                 nt_errstr(status));
985                 talloc_free(tmp_ctx);
986                 return status;
987         }
988         
989         if (!qui.out.info) {
990                 status = NT_STATUS_INVALID_PARAMETER;
991                 r->out.error_string
992                         = talloc_asprintf(mem_ctx,
993                                           "samr_QueryUserInfo failed to return qui.out.info for [%s]: %s\n",
994                                           r->in.account_name, nt_errstr(status));
995                 talloc_free(tmp_ctx);
996                 return status;
997         }
998
999         /* Possibly change account type (if we are creating a new account) */
1000         if (((qui.out.info->info16.acct_flags & (ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST)) 
1001             != r->in.acct_type) && (!NT_STATUS_EQUAL(cu_status, NT_STATUS_USER_EXISTS))) {
1002                 acct_flags = (qui.out.info->info16.acct_flags & ~(ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST))
1003                               | r->in.acct_type;
1004         } else {
1005                 acct_flags = qui.out.info->info16.acct_flags;
1006         }
1007         
1008         acct_flags = (acct_flags & ~ACB_DISABLED);
1009
1010         /* reset flags (if required) */
1011         if (acct_flags != qui.out.info->info16.acct_flags) {    
1012                 ZERO_STRUCT(u_info);
1013                 u_info.info16.acct_flags = acct_flags;
1014
1015                 sui.in.user_handle = u_handle;
1016                 sui.in.info = &u_info;
1017                 sui.in.level = 16;
1018                 
1019                 dcerpc_samr_SetUserInfo(samr_pipe, tmp_ctx, &sui);
1020                 if (!NT_STATUS_IS_OK(status)) {
1021                         r->out.error_string = talloc_asprintf(mem_ctx,
1022                                                         "samr_SetUserInfo for [%s] failed to remove ACB_DISABLED flag: %s",
1023                                                         r->in.account_name,
1024                                                         nt_errstr(status));
1025                         talloc_free(tmp_ctx);
1026                         return status;
1027                 }
1028         }
1029
1030         account_sid = dom_sid_add_rid(mem_ctx, domain_sid, rid);
1031         if (!account_sid) {
1032                 r->out.error_string = NULL;
1033                 talloc_free(tmp_ctx);
1034                 return NT_STATUS_NO_MEMORY;
1035         }
1036
1037         r->out.join_password = password_str;
1038         talloc_steal(mem_ctx, password_str);
1039
1040         r->out.domain_sid = domain_sid;
1041         talloc_steal(mem_ctx, domain_sid);
1042
1043         r->out.account_sid = account_sid;
1044         talloc_steal(mem_ctx, account_sid);
1045
1046         r->out.domain_name = domain_name;
1047         talloc_steal(mem_ctx, domain_name);
1048         r->out.realm = realm;
1049         talloc_steal(mem_ctx, realm);
1050         r->out.lsa_pipe = lsa_pipe;
1051         talloc_steal(mem_ctx, lsa_pipe);
1052         r->out.samr_pipe = samr_pipe;
1053         talloc_steal(mem_ctx, samr_pipe);
1054         r->out.samr_binding = samr_binding;
1055         talloc_steal(mem_ctx, samr_binding);
1056         r->out.user_handle = u_handle;
1057         talloc_steal(mem_ctx, u_handle);
1058         r->out.error_string = r2.samr_handle.out.error_string;
1059         talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
1060         r->out.kvno = 0;
1061         r->out.server_dn_str = NULL;
1062         talloc_free(tmp_ctx); 
1063
1064         /* Now, if it was AD, then we want to start looking changing a
1065          * few more things.  Otherwise, we are done. */
1066         if (realm) {
1067                 status = libnet_JoinADSDomain(ctx, r);
1068                 return status;
1069         }
1070
1071         return status;
1072 }
1073
1074 static NTSTATUS libnet_Join_primary_domain(struct libnet_context *ctx, 
1075                                            TALLOC_CTX *mem_ctx, 
1076                                            struct libnet_Join *r)
1077 {
1078         NTSTATUS status;
1079         TALLOC_CTX *tmp_mem;
1080         struct libnet_JoinDomain *r2;
1081         int ret, rtn;
1082         struct ldb_context *ldb;
1083         const struct ldb_dn *base_dn;
1084         struct ldb_message **msgs, *msg;
1085         const char *sct;
1086         const char * const attrs[] = {
1087                 "whenChanged",
1088                 "secret",
1089                 "priorSecret",
1090                 "priorChanged",
1091                 NULL
1092         };
1093         uint32_t acct_type = 0;
1094         const char *account_name;
1095         const char *netbios_name;
1096         
1097         r->out.error_string = NULL;
1098
1099         tmp_mem = talloc_new(mem_ctx);
1100         if (!tmp_mem) {
1101                 return NT_STATUS_NO_MEMORY;
1102         }
1103
1104         r2 = talloc(tmp_mem, struct libnet_JoinDomain);
1105         if (!r2) {
1106                 r->out.error_string = NULL;
1107                 talloc_free(tmp_mem);
1108                 return NT_STATUS_NO_MEMORY;
1109         }
1110         
1111         if (r->in.secure_channel_type == SEC_CHAN_BDC) {
1112                 acct_type = ACB_SVRTRUST;
1113         } else if (r->in.secure_channel_type == SEC_CHAN_WKSTA) {
1114                 acct_type = ACB_WSTRUST;
1115         } else {
1116                 r->out.error_string = NULL;
1117                 talloc_free(tmp_mem);   
1118                 return NT_STATUS_INVALID_PARAMETER;
1119         }
1120
1121         if ((r->in.netbios_name != NULL) && (r->in.level != LIBNET_JOIN_AUTOMATIC)) {
1122                 netbios_name = r->in.netbios_name;
1123         } else {
1124                 netbios_name = talloc_asprintf(tmp_mem, "%s", lp_netbios_name());
1125                 if (!netbios_name) {
1126                         r->out.error_string = NULL;
1127                         talloc_free(tmp_mem);
1128                         return NT_STATUS_NO_MEMORY;
1129                 }
1130         }
1131
1132         account_name = talloc_asprintf(tmp_mem, "%s$", netbios_name);                   
1133         if (!account_name) {
1134                 r->out.error_string = NULL;
1135                 talloc_free(tmp_mem);
1136                 return NT_STATUS_NO_MEMORY;
1137         }
1138         
1139         /*
1140          * Local secrets are stored in secrets.ldb 
1141          * open it to make sure we can write the info into it after the join
1142          */
1143         ldb = secrets_db_connect(tmp_mem);                                              
1144         if (!ldb) {
1145                 r->out.error_string
1146                         = talloc_asprintf(mem_ctx, 
1147                                           "Could not open secrets database\n");
1148                 talloc_free(tmp_mem);
1149                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1150         }
1151
1152         /*
1153          * join the domain
1154          */
1155         ZERO_STRUCTP(r2);
1156         r2->in.domain_name      = r->in.domain_name;
1157         r2->in.account_name     = account_name;
1158         r2->in.netbios_name     = netbios_name;
1159         r2->in.level            = LIBNET_JOINDOMAIN_AUTOMATIC;
1160         r2->in.acct_type        = acct_type;
1161         r2->in.recreate_account = False;
1162         status = libnet_JoinDomain(ctx, r2, r2);
1163         if (!NT_STATUS_IS_OK(status)) {
1164                 r->out.error_string = talloc_steal(mem_ctx, r2->out.error_string);
1165                 talloc_free(tmp_mem);
1166                 return status;
1167         }
1168         
1169         /*
1170          * now prepare the record for secrets.ldb
1171          */
1172         sct = talloc_asprintf(tmp_mem, "%d", r->in.secure_channel_type); 
1173         if (!sct) {
1174                 r->out.error_string = NULL;
1175                 talloc_free(tmp_mem);
1176                 return NT_STATUS_NO_MEMORY;
1177         }
1178         
1179         msg = ldb_msg_new(tmp_mem);
1180         if (!msg) {
1181                 r->out.error_string = NULL;
1182                 talloc_free(tmp_mem);
1183                 return NT_STATUS_NO_MEMORY;
1184         }
1185
1186         base_dn = ldb_dn_explode(tmp_mem, "cn=Primary Domains");
1187         if (!base_dn) {
1188                 r->out.error_string = NULL;
1189                 talloc_free(tmp_mem);
1190                 return NT_STATUS_NO_MEMORY;
1191         }
1192
1193         msg->dn = ldb_dn_build_child(tmp_mem, "flatname", r2->out.domain_name, base_dn);
1194         if (!msg->dn) {
1195                 r->out.error_string = NULL;
1196                 talloc_free(tmp_mem);
1197                 return NT_STATUS_NO_MEMORY;
1198         }
1199         
1200         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "flatname", r2->out.domain_name);
1201         if (rtn == -1) {
1202                 r->out.error_string = NULL;
1203                 talloc_free(tmp_mem);
1204                 return NT_STATUS_NO_MEMORY;
1205         }
1206
1207         if (r2->out.realm) {
1208                 rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "realm", r2->out.realm);
1209                 if (rtn == -1) {
1210                         r->out.error_string = NULL;
1211                         talloc_free(tmp_mem);
1212                         return NT_STATUS_NO_MEMORY;
1213                 }
1214         }
1215
1216         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "objectClass", "primaryDomain");
1217         if (rtn == -1) {
1218                 r->out.error_string = NULL;
1219                 talloc_free(tmp_mem);
1220                 return NT_STATUS_NO_MEMORY;
1221         }
1222
1223         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secret", r2->out.join_password);
1224         if (rtn == -1) {
1225                 r->out.error_string = NULL;
1226                 talloc_free(tmp_mem);
1227                 return NT_STATUS_NO_MEMORY;
1228         }
1229
1230         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "samAccountName", r2->in.account_name);
1231         if (rtn == -1) {
1232                 r->out.error_string = NULL;
1233                 talloc_free(tmp_mem);
1234                 return NT_STATUS_NO_MEMORY;
1235         }
1236
1237         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secureChannelType", sct);
1238         if (rtn == -1) {
1239                 r->out.error_string = NULL;
1240                 talloc_free(tmp_mem);
1241                 return NT_STATUS_NO_MEMORY;
1242         }
1243
1244         if (r2->out.kvno) {
1245                 rtn = samdb_msg_add_uint(ldb, tmp_mem, msg, "msDS-KeyVersionNumber",
1246                                          r2->out.kvno);
1247                 if (rtn == -1) {
1248                         r->out.error_string = NULL;
1249                         talloc_free(tmp_mem);
1250                         return NT_STATUS_NO_MEMORY;
1251                 }
1252         }
1253
1254         if (r2->out.domain_sid) {
1255                 rtn = samdb_msg_add_dom_sid(ldb, tmp_mem, msg, "objectSid",
1256                                             r2->out.domain_sid);
1257                 if (rtn == -1) {
1258                         r->out.error_string = NULL;
1259                         talloc_free(tmp_mem);
1260                         return NT_STATUS_NO_MEMORY;
1261                 }
1262         }
1263
1264         /* 
1265          * search for the secret record
1266          * - remove the records we find
1267          * - and fetch the old secret and store it under priorSecret
1268          */
1269         ret = gendb_search(ldb,
1270                            tmp_mem, base_dn,
1271                            &msgs, attrs,
1272                            "(|" SECRETS_PRIMARY_DOMAIN_FILTER "(realm=%s))",
1273                            r2->out.domain_name, r2->out.realm);
1274         if (ret == 0) {
1275         } else if (ret == -1) {
1276                 r->out.error_string
1277                         = talloc_asprintf(mem_ctx, 
1278                                           "Search for domain: %s and realm: %s failed: %s", 
1279                                           r2->out.domain_name, r2->out.realm, ldb_errstring(ldb));
1280                 talloc_free(tmp_mem);
1281                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1282         } else {
1283                 const struct ldb_val *prior_secret;
1284                 const struct ldb_val *prior_modified_time;
1285                 int i;
1286
1287                 for (i = 0; i < ret; i++) {
1288                         ldb_delete(ldb, msgs[i]->dn);
1289                 }
1290
1291                 prior_secret = ldb_msg_find_ldb_val(msgs[0], "secret");
1292                 if (prior_secret) {
1293                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorSecret", prior_secret);
1294                         if (rtn == -1) {
1295                                 r->out.error_string = NULL;
1296                                 talloc_free(tmp_mem);
1297                                 return NT_STATUS_NO_MEMORY;
1298                         }
1299                 }
1300                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secret", r2->out.join_password);
1301                 if (rtn == -1) {
1302                         r->out.error_string = NULL;
1303                         talloc_free(tmp_mem);
1304                         return NT_STATUS_NO_MEMORY;
1305                 }
1306
1307                 prior_modified_time = ldb_msg_find_ldb_val(msgs[0], 
1308                                                            "whenChanged");
1309                 if (prior_modified_time) {
1310                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorWhenChanged", 
1311                                                   prior_modified_time);
1312                         if (rtn == -1) {
1313                                 r->out.error_string = NULL;
1314                                 talloc_free(tmp_mem);
1315                                 return NT_STATUS_NO_MEMORY;
1316                         }
1317                 }
1318
1319                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "samAccountName", r2->in.account_name);
1320                 if (rtn == -1) {
1321                         r->out.error_string = NULL;
1322                         talloc_free(tmp_mem);
1323                         return NT_STATUS_NO_MEMORY;
1324                 }
1325
1326                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secureChannelType", sct);
1327                 if (rtn == -1) {
1328                         r->out.error_string = NULL;
1329                         talloc_free(tmp_mem);
1330                         return NT_STATUS_NO_MEMORY;
1331                 }
1332         }
1333
1334         /* create the secret */
1335         ret = samdb_add(ldb, tmp_mem, msg);
1336         if (ret != 0) {
1337                 r->out.error_string = talloc_asprintf(mem_ctx, "Failed to create secret record %s\n", 
1338                                                       ldb_dn_linearize(ldb, msg->dn));
1339                 talloc_free(tmp_mem);
1340                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1341         }
1342
1343         /* move all out parameter to the callers TALLOC_CTX */
1344         r->out.error_string     = NULL;
1345         r->out.join_password    = r2->out.join_password;
1346         talloc_steal(mem_ctx, r2->out.join_password);
1347         r->out.domain_sid       = r2->out.domain_sid;
1348         talloc_steal(mem_ctx, r2->out.domain_sid);
1349         talloc_free(tmp_mem);
1350         return NT_STATUS_OK;
1351 }
1352
1353 NTSTATUS libnet_Join(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_Join *r)
1354 {
1355         switch (r->in.secure_channel_type) {
1356                 case SEC_CHAN_WKSTA:
1357                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1358                 case SEC_CHAN_BDC:
1359                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1360                 case SEC_CHAN_DOMAIN:
1361                         break;
1362         }
1363
1364         r->out.error_string = talloc_asprintf(mem_ctx,
1365                                 "Invalid secure channel type specified (%08X) attempting to join domain %s",
1366                                 r->in.secure_channel_type, r->in.domain_name);
1367         return NT_STATUS_INVALID_PARAMETER;
1368 }
1369
1370