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