Fix include paths to new location of libutil.
[tprouty/samba.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 3 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, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "includes.h"
23 #include "libnet/libnet.h"
24 #include "librpc/gen_ndr/ndr_drsuapi_c.h"
25 #include "lib/ldb/include/ldb.h"
26 #include "lib/ldb/include/ldb_errors.h"
27 #include "param/secrets.h"
28 #include "dsdb/samdb/samdb.h"
29 #include "ldb_wrap.h"
30 #include "../lib/util/util_ldb.h"
31 #include "libcli/security/security.h"
32 #include "auth/credentials/credentials.h"
33 #include "auth/credentials/credentials_krb5.h"
34 #include "librpc/gen_ndr/ndr_samr_c.h"
35 #include "param/param.h"
36
37 /*
38  * complete a domain join, when joining to a AD domain:
39  * 1.) connect and bind to the DRSUAPI pipe
40  * 2.) do a DsCrackNames() to find the machine account dn
41  * 3.) connect to LDAP
42  * 4.) do an ldap search to find the "msDS-KeyVersionNumber" of the machine account
43  * 5.) set the servicePrincipalName's of the machine account via LDAP, (maybe we should use DsWriteAccountSpn()...)
44  * 6.) do a DsCrackNames() to find the domain dn
45  * 7.) find out Site specific stuff, look at libnet_JoinSite() for details
46  */
47 static NTSTATUS libnet_JoinADSDomain(struct libnet_context *ctx, struct libnet_JoinDomain *r)
48 {
49         NTSTATUS status;
50
51         TALLOC_CTX *tmp_ctx;
52
53         const char *realm = r->out.realm;
54
55         struct dcerpc_binding *samr_binding = r->out.samr_binding;
56
57         struct dcerpc_pipe *drsuapi_pipe;
58         struct dcerpc_binding *drsuapi_binding;
59         struct drsuapi_DsBind r_drsuapi_bind;
60         struct drsuapi_DsCrackNames r_crack_names;
61         struct drsuapi_DsNameString names[1];
62         struct policy_handle drsuapi_bind_handle;
63         struct GUID drsuapi_bind_guid;
64
65         struct ldb_context *remote_ldb;
66         struct ldb_dn *account_dn;
67         const char *account_dn_str;
68         const char *remote_ldb_url;
69         struct ldb_result *res;
70         struct ldb_message *msg;
71
72         int ret, rtn;
73
74         const char * const attrs[] = {
75                 "msDS-KeyVersionNumber",
76                 "servicePrincipalName",
77                 "dNSHostName",
78                 "objectGUID",
79                 NULL,
80         };
81
82         r->out.error_string = NULL;
83         
84         /* We need to convert between a samAccountName and domain to a
85          * DN in the directory.  The correct way to do this is with
86          * DRSUAPI CrackNames */
87
88         /* Fiddle with the bindings, so get to DRSUAPI on
89          * NCACN_IP_TCP, sealed */
90         tmp_ctx = talloc_named(r, 0, "libnet_JoinADSDomain temp context");  
91         if (!tmp_ctx) {
92                 r->out.error_string = NULL;
93                 return NT_STATUS_NO_MEMORY;
94         }
95                                                    
96         drsuapi_binding = talloc(tmp_ctx, struct dcerpc_binding);
97         if (!drsuapi_binding) {
98                 r->out.error_string = NULL;
99                 talloc_free(tmp_ctx);
100                 return NT_STATUS_NO_MEMORY;
101         }
102         
103         *drsuapi_binding = *samr_binding;
104
105         /* DRSUAPI is only available on IP_TCP, and locally on NCALRPC */
106         if (drsuapi_binding->transport != NCALRPC) {
107                 drsuapi_binding->transport = NCACN_IP_TCP;
108         }
109         drsuapi_binding->endpoint = NULL;
110         drsuapi_binding->flags |= DCERPC_SEAL;
111
112         status = dcerpc_pipe_connect_b(tmp_ctx, 
113                                        &drsuapi_pipe,
114                                        drsuapi_binding,
115                                        &ndr_table_drsuapi,
116                                        ctx->cred, 
117                                        ctx->event_ctx,
118                                        ctx->lp_ctx);
119         if (!NT_STATUS_IS_OK(status)) {
120                 r->out.error_string = talloc_asprintf(r,
121                                         "Connection to DRSUAPI pipe of PDC of domain '%s' failed: %s",
122                                         r->out.domain_name,
123                                         nt_errstr(status));
124                 talloc_free(tmp_ctx);
125                 return status;
126         }
127
128         /* get a DRSUAPI pipe handle */
129         GUID_from_string(DRSUAPI_DS_BIND_GUID, &drsuapi_bind_guid);
130
131         r_drsuapi_bind.in.bind_guid = &drsuapi_bind_guid;
132         r_drsuapi_bind.in.bind_info = NULL;
133         r_drsuapi_bind.out.bind_handle = &drsuapi_bind_handle;
134
135         status = dcerpc_drsuapi_DsBind(drsuapi_pipe, tmp_ctx, &r_drsuapi_bind);
136         if (!NT_STATUS_IS_OK(status)) {
137                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
138                         r->out.error_string
139                                 = talloc_asprintf(r,
140                                                   "dcerpc_drsuapi_DsBind failed - %s", 
141                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
142                         talloc_free(tmp_ctx);
143                         return status;
144                 } else {
145                         r->out.error_string
146                                 = talloc_asprintf(r,
147                                                   "dcerpc_drsuapi_DsBind failed - %s", 
148                                                   nt_errstr(status));
149                         talloc_free(tmp_ctx);
150                         return status;
151                 }
152         } else if (!W_ERROR_IS_OK(r_drsuapi_bind.out.result)) {
153                 r->out.error_string
154                                 = talloc_asprintf(r,
155                                                   "DsBind failed - %s", 
156                                                   win_errstr(r_drsuapi_bind.out.result));
157                         talloc_free(tmp_ctx);
158                 return NT_STATUS_UNSUCCESSFUL;
159         }
160
161         /* Actually 'crack' the names */
162         ZERO_STRUCT(r_crack_names);
163         r_crack_names.in.bind_handle            = &drsuapi_bind_handle;
164         r_crack_names.in.level                  = 1;
165         r_crack_names.in.req.req1.codepage      = 1252; /* western european */
166         r_crack_names.in.req.req1.language      = 0x00000407; /* german */
167         r_crack_names.in.req.req1.count         = 1;
168         r_crack_names.in.req.req1.names         = names;
169         r_crack_names.in.req.req1.format_flags  = DRSUAPI_DS_NAME_FLAG_NO_FLAGS;
170         r_crack_names.in.req.req1.format_offered= DRSUAPI_DS_NAME_FORMAT_SID_OR_SID_HISTORY;
171         r_crack_names.in.req.req1.format_desired= DRSUAPI_DS_NAME_FORMAT_FQDN_1779;
172         names[0].str = dom_sid_string(tmp_ctx, r->out.account_sid);
173         if (!names[0].str) {
174                 r->out.error_string = NULL;
175                 talloc_free(tmp_ctx);
176                 return NT_STATUS_NO_MEMORY;
177         }
178
179         status = dcerpc_drsuapi_DsCrackNames(drsuapi_pipe, tmp_ctx, &r_crack_names);
180         if (!NT_STATUS_IS_OK(status)) {
181                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
182                         r->out.error_string
183                                 = talloc_asprintf(r,
184                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s", 
185                                                   names[0].str,
186                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
187                         talloc_free(tmp_ctx);
188                         return status;
189                 } else {
190                         r->out.error_string
191                                 = talloc_asprintf(r,
192                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s", 
193                                                   names[0].str,
194                                                   nt_errstr(status));
195                         talloc_free(tmp_ctx);
196                         return status;
197                 }
198         } else if (!W_ERROR_IS_OK(r_crack_names.out.result)) {
199                 r->out.error_string
200                                 = talloc_asprintf(r,
201                                                   "DsCrackNames failed - %s", win_errstr(r_crack_names.out.result));
202                 talloc_free(tmp_ctx);
203                 return NT_STATUS_UNSUCCESSFUL;
204         } else if (r_crack_names.out.level != 1 
205                    || !r_crack_names.out.ctr.ctr1 
206                    || r_crack_names.out.ctr.ctr1->count != 1) {
207                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed");
208                 talloc_free(tmp_ctx);
209                 return NT_STATUS_INVALID_PARAMETER;
210         } else if (r_crack_names.out.ctr.ctr1->array[0].status != DRSUAPI_DS_NAME_STATUS_OK) {
211                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed: %d", r_crack_names.out.ctr.ctr1->array[0].status);
212                 talloc_free(tmp_ctx);
213                 return NT_STATUS_UNSUCCESSFUL;
214         } else if (r_crack_names.out.ctr.ctr1->array[0].result_name == NULL) {
215                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed: no result name");
216                 talloc_free(tmp_ctx);
217                 return NT_STATUS_INVALID_PARAMETER;
218         }
219
220         /* Store the DN of our machine account. */
221         account_dn_str = r_crack_names.out.ctr.ctr1->array[0].result_name;
222
223         /* Now we know the user's DN, open with LDAP, read and modify a few things */
224
225         remote_ldb_url = talloc_asprintf(tmp_ctx, "ldap://%s", 
226                                          drsuapi_binding->target_hostname);
227         if (!remote_ldb_url) {
228                 r->out.error_string = NULL;
229                 talloc_free(tmp_ctx);
230                 return NT_STATUS_NO_MEMORY;
231         }
232
233         remote_ldb = ldb_wrap_connect(tmp_ctx, ctx->event_ctx, ctx->lp_ctx, 
234                                       remote_ldb_url, 
235                                       NULL, ctx->cred, 0, NULL);
236         if (!remote_ldb) {
237                 r->out.error_string = NULL;
238                 talloc_free(tmp_ctx);
239                 return NT_STATUS_UNSUCCESSFUL;
240         }
241
242         account_dn = ldb_dn_new(tmp_ctx, remote_ldb, account_dn_str);
243         if (! ldb_dn_validate(account_dn)) {
244                 r->out.error_string = talloc_asprintf(r, "Invalid account dn: %s",
245                                                       account_dn_str);
246                 talloc_free(tmp_ctx);
247                 return NT_STATUS_UNSUCCESSFUL;
248         }
249
250         /* search for the user's record */
251         ret = ldb_search(remote_ldb, tmp_ctx, &res,
252                          account_dn, LDB_SCOPE_BASE, attrs, NULL);
253         if (ret != LDB_SUCCESS) {
254                 r->out.error_string = talloc_asprintf(r, "ldb_search for %s failed - %s",
255                                                       account_dn_str, ldb_errstring(remote_ldb));
256                 talloc_free(tmp_ctx);
257                 return NT_STATUS_UNSUCCESSFUL;
258         }
259
260         if (res->count != 1) {
261                 r->out.error_string = talloc_asprintf(r, "ldb_search for %s failed - found %d entries",
262                                                       account_dn_str, res->count);
263                 talloc_free(tmp_ctx);
264                 return NT_STATUS_UNSUCCESSFUL;
265         }
266
267         /* Prepare a new message, for the modify */
268         msg = ldb_msg_new(tmp_ctx);
269         if (!msg) {
270                 r->out.error_string = NULL;
271                 talloc_free(tmp_ctx);
272                 return NT_STATUS_NO_MEMORY;
273         }
274         msg->dn = res->msgs[0]->dn;
275
276         {
277                 int i;
278                 const char *service_principal_name[6];
279                 const char *dns_host_name = strlower_talloc(tmp_ctx, 
280                                                             talloc_asprintf(tmp_ctx, 
281                                                                             "%s.%s", 
282                                                                             r->in.netbios_name, 
283                                                                             realm));
284
285                 if (!dns_host_name) {
286                         r->out.error_string = NULL;
287                         talloc_free(tmp_ctx);
288                         return NT_STATUS_NO_MEMORY;
289                 }
290
291                 service_principal_name[0] = talloc_asprintf(tmp_ctx, "host/%s", dns_host_name);
292                 service_principal_name[1] = talloc_asprintf(tmp_ctx, "host/%s", strlower_talloc(tmp_ctx, r->in.netbios_name));
293                 service_principal_name[2] = talloc_asprintf(tmp_ctx, "host/%s/%s", dns_host_name, realm);
294                 service_principal_name[3] = talloc_asprintf(tmp_ctx, "host/%s/%s", strlower_talloc(tmp_ctx, r->in.netbios_name), realm);
295                 service_principal_name[4] = talloc_asprintf(tmp_ctx, "host/%s/%s", dns_host_name, r->out.domain_name);
296                 service_principal_name[5] = talloc_asprintf(tmp_ctx, "host/%s/%s", strlower_talloc(tmp_ctx, r->in.netbios_name), r->out.domain_name);
297                 
298                 for (i=0; i < ARRAY_SIZE(service_principal_name); i++) {
299                         if (!service_principal_name[i]) {
300                                 r->out.error_string = NULL;
301                                 talloc_free(tmp_ctx);
302                                 return NT_STATUS_NO_MEMORY;
303                         }
304                         rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "servicePrincipalName", service_principal_name[i]);
305                         if (rtn == -1) {
306                                 r->out.error_string = NULL;
307                                 talloc_free(tmp_ctx);
308                                 return NT_STATUS_NO_MEMORY;
309                         }
310                 }
311
312                 rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "dNSHostName", dns_host_name);
313                 if (rtn == -1) {
314                         r->out.error_string = NULL;
315                         talloc_free(tmp_ctx);
316                         return NT_STATUS_NO_MEMORY;
317                 }
318
319                 rtn = samdb_replace(remote_ldb, tmp_ctx, msg);
320                 if (rtn != 0) {
321                         r->out.error_string
322                                 = talloc_asprintf(r, 
323                                                   "Failed to replace entries on %s", 
324                                                   ldb_dn_get_linearized(msg->dn));
325                         talloc_free(tmp_ctx);
326                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
327                 }
328         }
329                                 
330         /* DsCrackNames to find out the DN of the domain. */
331         r_crack_names.in.req.req1.format_offered = DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT;
332         r_crack_names.in.req.req1.format_desired = DRSUAPI_DS_NAME_FORMAT_FQDN_1779;
333         names[0].str = talloc_asprintf(tmp_ctx, "%s\\", r->out.domain_name);
334         if (!names[0].str) {
335                 r->out.error_string = NULL;
336                 talloc_free(tmp_ctx);
337                 return NT_STATUS_NO_MEMORY;
338         }
339
340         status = dcerpc_drsuapi_DsCrackNames(drsuapi_pipe, tmp_ctx, &r_crack_names);
341         if (!NT_STATUS_IS_OK(status)) {
342                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
343                         r->out.error_string
344                                 = talloc_asprintf(r,
345                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s", 
346                                                   r->in.domain_name, 
347                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
348                         talloc_free(tmp_ctx);
349                         return status;
350                 } else {
351                         r->out.error_string
352                                 = talloc_asprintf(r,
353                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s", 
354                                                   r->in.domain_name, 
355                                                   nt_errstr(status));
356                         talloc_free(tmp_ctx);
357                         return status;
358                 }
359         } else if (!W_ERROR_IS_OK(r_crack_names.out.result)) {
360                 r->out.error_string
361                         = talloc_asprintf(r,
362                                           "DsCrackNames failed - %s", win_errstr(r_crack_names.out.result));
363                 talloc_free(tmp_ctx);
364                 return NT_STATUS_UNSUCCESSFUL;
365         } else if (r_crack_names.out.level != 1 
366                    || !r_crack_names.out.ctr.ctr1 
367                    || r_crack_names.out.ctr.ctr1->count != 1
368                    || !r_crack_names.out.ctr.ctr1->array[0].result_name           
369                    || r_crack_names.out.ctr.ctr1->array[0].status != DRSUAPI_DS_NAME_STATUS_OK) {
370                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed");
371                 talloc_free(tmp_ctx);
372                 return NT_STATUS_UNSUCCESSFUL;
373         }
374
375         /* Store the account DN. */
376         r->out.account_dn_str = account_dn_str;
377         talloc_steal(r, account_dn_str);
378
379         /* Store the domain DN. */
380         r->out.domain_dn_str = r_crack_names.out.ctr.ctr1->array[0].result_name;
381         talloc_steal(r, r_crack_names.out.ctr.ctr1->array[0].result_name);
382
383         /* Store the KVNO of the account, critical for some kerberos
384          * operations */
385         r->out.kvno = ldb_msg_find_attr_as_uint(res->msgs[0], "msDS-KeyVersionNumber", 0);
386
387         /* Store the account GUID. */
388         r->out.account_guid = samdb_result_guid(res->msgs[0], "objectGUID");
389
390         if (r->in.acct_type == ACB_SVRTRUST) {
391                 status = libnet_JoinSite(ctx, remote_ldb, r);
392         }
393         talloc_free(tmp_ctx);
394
395         return status;
396 }
397
398 /*
399  * do a domain join using DCERPC/SAMR calls
400  * - connect to the LSA pipe, to try and find out information about the domain
401  * - create a secondary connection to SAMR pipe
402  * - do a samr_Connect to get a policy handle
403  * - do a samr_LookupDomain to get the domain sid
404  * - do a samr_OpenDomain to get a domain handle
405  * - do a samr_CreateAccount to try and get a new account 
406  * 
407  * If that fails, do:
408  * - do a samr_LookupNames to get the users rid
409  * - do a samr_OpenUser to get a user handle
410  * - potentially delete and recreate the user
411  * - assert the account is of the right type with samrQueryUserInfo
412  * 
413  * - call libnet_SetPassword_samr_handle to set the password,
414  *   and pass a samr_UserInfo21 struct to set full_name and the account flags
415  *
416  * - do some ADS specific things when we join as Domain Controller,
417  *    look at libnet_joinADSDomain() for the details
418  */
419 NTSTATUS libnet_JoinDomain(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_JoinDomain *r)
420 {
421         TALLOC_CTX *tmp_ctx;
422
423         NTSTATUS status, cu_status;
424
425         struct libnet_RpcConnect *connect_with_info;
426         struct dcerpc_pipe *samr_pipe;
427
428         struct samr_Connect sc;
429         struct policy_handle p_handle;
430         struct samr_OpenDomain od;
431         struct policy_handle d_handle;
432         struct samr_LookupNames ln;
433         struct samr_OpenUser ou;
434         struct samr_CreateUser2 cu;
435         struct policy_handle *u_handle = NULL;
436         struct samr_QueryUserInfo qui;
437         struct samr_UserInfo21 u_info21;
438         union libnet_SetPassword r2;
439         struct samr_GetUserPwInfo pwp;
440         struct lsa_String samr_account_name;
441         
442         uint32_t acct_flags, old_acct_flags;
443         uint32_t rid, access_granted;
444         int policy_min_pw_len = 0;
445
446         struct dom_sid *account_sid = NULL;
447         const char *password_str = NULL;
448         
449         r->out.error_string = NULL;
450         r2.samr_handle.out.error_string = NULL;
451         
452         tmp_ctx = talloc_named(mem_ctx, 0, "libnet_Join temp context");
453         if (!tmp_ctx) {
454                 r->out.error_string = NULL;
455                 return NT_STATUS_NO_MEMORY;
456         }
457         
458         u_handle = talloc(tmp_ctx, struct policy_handle);
459         if (!u_handle) {
460                 r->out.error_string = NULL;
461                 talloc_free(tmp_ctx);
462                 return NT_STATUS_NO_MEMORY;
463         }
464         
465         connect_with_info = talloc(tmp_ctx, struct libnet_RpcConnect);
466         if (!connect_with_info) {
467                 r->out.error_string = NULL;
468                 talloc_free(tmp_ctx);
469                 return NT_STATUS_NO_MEMORY;
470         }
471
472         /* prepare connect to the SAMR pipe of PDC */
473         if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
474                 connect_with_info->in.binding = NULL;
475                 connect_with_info->in.name    = r->in.domain_name;
476         } else {
477                 connect_with_info->in.binding = r->in.binding;
478                 connect_with_info->in.name    = NULL;
479         }
480
481         /* This level makes a connection to the LSA pipe on the way,
482          * to get some useful bits of information about the domain */
483         connect_with_info->level              = LIBNET_RPC_CONNECT_DC_INFO;
484         connect_with_info->in.dcerpc_iface    = &ndr_table_samr;
485
486         /*
487           establish the SAMR connection
488         */
489         status = libnet_RpcConnect(ctx, tmp_ctx, connect_with_info);
490         if (!NT_STATUS_IS_OK(status)) {
491                 if (r->in.binding) {
492                         r->out.error_string = talloc_asprintf(mem_ctx,
493                                                               "Connection to SAMR pipe of DC %s failed: %s",
494                                                               r->in.binding, connect_with_info->out.error_string);
495                 } else {
496                         r->out.error_string = talloc_asprintf(mem_ctx,
497                                                               "Connection to SAMR pipe of PDC for %s failed: %s",
498                                                               r->in.domain_name, connect_with_info->out.error_string);
499                 }
500                 talloc_free(tmp_ctx);
501                 return status;
502         }
503
504         samr_pipe = connect_with_info->out.dcerpc_pipe;
505
506         status = dcerpc_pipe_auth(tmp_ctx, &samr_pipe,
507                                   connect_with_info->out.dcerpc_pipe->binding, 
508                                   &ndr_table_samr, ctx->cred, ctx->lp_ctx);
509         if (!NT_STATUS_IS_OK(status)) {
510                 r->out.error_string = talloc_asprintf(mem_ctx,
511                                                 "SAMR bind failed: %s",
512                                                 nt_errstr(status));
513                 talloc_free(tmp_ctx);
514                 return status;
515         }
516
517         /* prepare samr_Connect */
518         ZERO_STRUCT(p_handle);
519         sc.in.system_name = NULL;
520         sc.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
521         sc.out.connect_handle = &p_handle;
522
523         /* 2. do a samr_Connect to get a policy handle */
524         status = dcerpc_samr_Connect(samr_pipe, tmp_ctx, &sc);
525         if (!NT_STATUS_IS_OK(status)) {
526                 r->out.error_string = talloc_asprintf(mem_ctx,
527                                                 "samr_Connect failed: %s",
528                                                 nt_errstr(status));
529                 talloc_free(tmp_ctx);
530                 return status;
531         }
532
533         /* If this is a connection on ncacn_ip_tcp to Win2k3 SP1, we don't get back this useful info */
534         if (!connect_with_info->out.domain_name) {
535                 if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
536                         connect_with_info->out.domain_name = talloc_strdup(tmp_ctx, r->in.domain_name);
537                 } else {
538                         /* Bugger, we just lost our way to automaticly find the domain name */
539                         connect_with_info->out.domain_name = talloc_strdup(tmp_ctx, lp_workgroup(ctx->lp_ctx));
540                         connect_with_info->out.realm = talloc_strdup(tmp_ctx, lp_realm(ctx->lp_ctx));
541                 }
542         }
543
544         /* Perhaps we didn't get a SID above, because we are against ncacn_ip_tcp */
545         if (!connect_with_info->out.domain_sid) {
546                 struct lsa_String name;
547                 struct samr_LookupDomain l;
548                 name.string = connect_with_info->out.domain_name;
549                 l.in.connect_handle = &p_handle;
550                 l.in.domain_name = &name;
551                 
552                 status = dcerpc_samr_LookupDomain(samr_pipe, tmp_ctx, &l);
553                 if (!NT_STATUS_IS_OK(status)) {
554                         r->out.error_string = talloc_asprintf(mem_ctx,
555                                                               "SAMR LookupDomain failed: %s",
556                                                               nt_errstr(status));
557                         talloc_free(tmp_ctx);
558                         return status;
559                 }
560                 connect_with_info->out.domain_sid = l.out.sid;
561         }
562
563         /* prepare samr_OpenDomain */
564         ZERO_STRUCT(d_handle);
565         od.in.connect_handle = &p_handle;
566         od.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
567         od.in.sid = connect_with_info->out.domain_sid;
568         od.out.domain_handle = &d_handle;
569
570         /* do a samr_OpenDomain to get a domain handle */
571         status = dcerpc_samr_OpenDomain(samr_pipe, tmp_ctx, &od);                       
572         if (!NT_STATUS_IS_OK(status)) {
573                 r->out.error_string = talloc_asprintf(mem_ctx,
574                                                       "samr_OpenDomain for [%s] failed: %s",
575                                                       dom_sid_string(tmp_ctx, connect_with_info->out.domain_sid),
576                                                       nt_errstr(status));
577                 talloc_free(tmp_ctx);
578                 return status;
579         }
580         
581         /* prepare samr_CreateUser2 */
582         ZERO_STRUCTP(u_handle);
583         cu.in.domain_handle  = &d_handle;
584         cu.in.access_mask     = SEC_FLAG_MAXIMUM_ALLOWED;
585         samr_account_name.string = r->in.account_name;
586         cu.in.account_name    = &samr_account_name;
587         cu.in.acct_flags      = r->in.acct_type;
588         cu.out.user_handle    = u_handle;
589         cu.out.rid            = &rid;
590         cu.out.access_granted = &access_granted;
591
592         /* do a samr_CreateUser2 to get an account handle, or an error */
593         cu_status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                   
594         status = cu_status;
595         if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
596                 /* prepare samr_LookupNames */
597                 ln.in.domain_handle = &d_handle;
598                 ln.in.num_names = 1;
599                 ln.in.names = talloc_array(tmp_ctx, struct lsa_String, 1);
600                 if (!ln.in.names) {
601                         r->out.error_string = NULL;
602                         talloc_free(tmp_ctx);
603                         return NT_STATUS_NO_MEMORY;
604                 }
605                 ln.in.names[0].string = r->in.account_name;
606                 
607                 /* 5. do a samr_LookupNames to get the users rid */
608                 status = dcerpc_samr_LookupNames(samr_pipe, tmp_ctx, &ln);
609                 if (!NT_STATUS_IS_OK(status)) {
610                         r->out.error_string = talloc_asprintf(mem_ctx,
611                                                 "samr_LookupNames for [%s] failed: %s",
612                                                 r->in.account_name,
613                                                 nt_errstr(status));
614                         talloc_free(tmp_ctx);
615                         return status;
616                 }
617                 
618                 /* check if we got one RID for the user */
619                 if (ln.out.rids.count != 1) {
620                         r->out.error_string = talloc_asprintf(mem_ctx,
621                                                               "samr_LookupNames for [%s] returns %d RIDs",
622                                                               r->in.account_name, ln.out.rids.count);
623                         talloc_free(tmp_ctx);
624                         return NT_STATUS_INVALID_PARAMETER;
625                 }
626                 
627                 /* prepare samr_OpenUser */
628                 ZERO_STRUCTP(u_handle);
629                 ou.in.domain_handle = &d_handle;
630                 ou.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
631                 ou.in.rid = ln.out.rids.ids[0];
632                 rid = ou.in.rid;
633                 ou.out.user_handle = u_handle;
634                 
635                 /* 6. do a samr_OpenUser to get a user handle */
636                 status = dcerpc_samr_OpenUser(samr_pipe, tmp_ctx, &ou); 
637                 if (!NT_STATUS_IS_OK(status)) {
638                         r->out.error_string = talloc_asprintf(mem_ctx,
639                                                         "samr_OpenUser for [%s] failed: %s",
640                                                         r->in.account_name,
641                                                         nt_errstr(status));
642                         talloc_free(tmp_ctx);
643                         return status;
644                 }
645
646                 if (r->in.recreate_account) {
647                         struct samr_DeleteUser d;
648                         d.in.user_handle = u_handle;
649                         d.out.user_handle = u_handle;
650                         status = dcerpc_samr_DeleteUser(samr_pipe, mem_ctx, &d);
651                         if (!NT_STATUS_IS_OK(status)) {
652                                 r->out.error_string = talloc_asprintf(mem_ctx,
653                                                                       "samr_DeleteUser (for recreate) of [%s] failed: %s",
654                                                                       r->in.account_name,
655                                                                       nt_errstr(status));
656                                 talloc_free(tmp_ctx);
657                                 return status;
658                         }
659
660                         /* We want to recreate, so delete and another samr_CreateUser2 */
661                         
662                         /* &cu filled in above */
663                         status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                      
664                         if (!NT_STATUS_IS_OK(status)) {
665                                 r->out.error_string = talloc_asprintf(mem_ctx,
666                                                                       "samr_CreateUser2 (recreate) for [%s] failed: %s",
667                                                                       r->in.account_name, nt_errstr(status));
668                                 talloc_free(tmp_ctx);
669                                 return status;
670                         }
671                 }
672         } else if (!NT_STATUS_IS_OK(status)) {
673                 r->out.error_string = talloc_asprintf(mem_ctx,
674                                                       "samr_CreateUser2 for [%s] failed: %s",
675                                                       r->in.account_name, nt_errstr(status));
676                 talloc_free(tmp_ctx);
677                 return status;
678         }
679
680         /* prepare samr_QueryUserInfo (get flags) */
681         qui.in.user_handle = u_handle;
682         qui.in.level = 16;
683         
684         status = dcerpc_samr_QueryUserInfo(samr_pipe, tmp_ctx, &qui);
685         if (!NT_STATUS_IS_OK(status)) {
686                 r->out.error_string = talloc_asprintf(mem_ctx,
687                                                 "samr_QueryUserInfo for [%s] failed: %s",
688                                                 r->in.account_name,
689                                                 nt_errstr(status));
690                 talloc_free(tmp_ctx);
691                 return status;
692         }
693         
694         if (!qui.out.info) {
695                 status = NT_STATUS_INVALID_PARAMETER;
696                 r->out.error_string
697                         = talloc_asprintf(mem_ctx,
698                                           "samr_QueryUserInfo failed to return qui.out.info for [%s]: %s",
699                                           r->in.account_name, nt_errstr(status));
700                 talloc_free(tmp_ctx);
701                 return status;
702         }
703
704         old_acct_flags = (qui.out.info->info16.acct_flags & (ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST));
705         /* Possibly bail if the account is of the wrong type */
706         if (old_acct_flags
707             != r->in.acct_type) {
708                 const char *old_account_type, *new_account_type;
709                 switch (old_acct_flags) {
710                 case ACB_WSTRUST:
711                         old_account_type = "domain member (member)";
712                         break;
713                 case ACB_SVRTRUST:
714                         old_account_type = "domain controller (bdc)";
715                         break;
716                 case ACB_DOMTRUST:
717                         old_account_type = "trusted domain";
718                         break;
719                 default:
720                         return NT_STATUS_INVALID_PARAMETER;
721                 }
722                 switch (r->in.acct_type) {
723                 case ACB_WSTRUST:
724                         new_account_type = "domain member (member)";
725                         break;
726                 case ACB_SVRTRUST:
727                         new_account_type = "domain controller (bdc)";
728                         break;
729                 case ACB_DOMTRUST:
730                         new_account_type = "trusted domain";
731                         break;
732                 default:
733                         return NT_STATUS_INVALID_PARAMETER;
734                 }
735
736                 if (!NT_STATUS_EQUAL(cu_status, NT_STATUS_USER_EXISTS)) {
737                         /* We created a new user, but they didn't come out the right type?!? */
738                         r->out.error_string
739                                 = talloc_asprintf(mem_ctx,
740                                                   "We asked to create a new machine account (%s) of type %s, "
741                                                   "but we got an account of type %s.  This is unexpected.  "
742                                                   "Perhaps delete the account and try again.",
743                                                   r->in.account_name, new_account_type, old_account_type);
744                         talloc_free(tmp_ctx);
745                         return NT_STATUS_INVALID_PARAMETER;
746                 } else {
747                         /* The account is of the wrong type, so bail */
748
749                         /* TODO: We should allow a --force option to override, and redo this from the top setting r.in.recreate_account */
750                         r->out.error_string
751                                 = talloc_asprintf(mem_ctx,
752                                                   "The machine account (%s) already exists in the domain %s, "
753                                                   "but is a %s.  You asked to join as a %s.  Please delete "
754                                                   "the account and try again.",
755                                                   r->in.account_name, connect_with_info->out.domain_name, old_account_type, new_account_type);
756                         talloc_free(tmp_ctx);
757                         return NT_STATUS_USER_EXISTS;
758                 }
759         } else {
760                 acct_flags = qui.out.info->info16.acct_flags;
761         }
762         
763         acct_flags = (acct_flags & ~(ACB_DISABLED|ACB_PWNOTREQ));
764
765         /* Find out what password policy this user has */
766         pwp.in.user_handle = u_handle;
767
768         status = dcerpc_samr_GetUserPwInfo(samr_pipe, tmp_ctx, &pwp);                           
769         if (NT_STATUS_IS_OK(status)) {
770                 policy_min_pw_len = pwp.out.info.min_password_length;
771         }
772         
773         /* Grab a password of that minimum length */
774         
775         password_str = generate_random_str(tmp_ctx, MAX(8, policy_min_pw_len)); 
776
777         /* set full_name and reset flags */
778         ZERO_STRUCT(u_info21);
779         u_info21.full_name.string       = r->in.account_name;
780         u_info21.acct_flags             = acct_flags;
781         u_info21.fields_present         = SAMR_FIELD_FULL_NAME | SAMR_FIELD_ACCT_FLAGS;
782
783         r2.samr_handle.level            = LIBNET_SET_PASSWORD_SAMR_HANDLE;
784         r2.samr_handle.in.account_name  = r->in.account_name;
785         r2.samr_handle.in.newpassword   = password_str;
786         r2.samr_handle.in.user_handle   = u_handle;
787         r2.samr_handle.in.dcerpc_pipe   = samr_pipe;
788         r2.samr_handle.in.info21        = &u_info21;
789
790         status = libnet_SetPassword(ctx, tmp_ctx, &r2); 
791         if (!NT_STATUS_IS_OK(status)) {
792                 r->out.error_string = talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
793                 talloc_free(tmp_ctx);
794                 return status;
795         }
796
797         account_sid = dom_sid_add_rid(mem_ctx, connect_with_info->out.domain_sid, rid);
798         if (!account_sid) {
799                 r->out.error_string = NULL;
800                 talloc_free(tmp_ctx);
801                 return NT_STATUS_NO_MEMORY;
802         }
803
804         /* Finish out by pushing various bits of status data out for the caller to use */
805         r->out.join_password = password_str;
806         talloc_steal(mem_ctx, r->out.join_password);
807
808         r->out.domain_sid = connect_with_info->out.domain_sid;
809         talloc_steal(mem_ctx, r->out.domain_sid);
810
811         r->out.account_sid = account_sid;
812         talloc_steal(mem_ctx, r->out.account_sid);
813
814         r->out.domain_name = connect_with_info->out.domain_name;
815         talloc_steal(mem_ctx, r->out.domain_name);
816         r->out.realm = connect_with_info->out.realm;
817         talloc_steal(mem_ctx, r->out.realm);
818         r->out.samr_pipe = samr_pipe;
819         talloc_steal(mem_ctx, samr_pipe);
820         r->out.samr_binding = samr_pipe->binding;
821         talloc_steal(mem_ctx, r->out.samr_binding);
822         r->out.user_handle = u_handle;
823         talloc_steal(mem_ctx, u_handle);
824         r->out.error_string = r2.samr_handle.out.error_string;
825         talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
826         r->out.kvno = 0;
827         r->out.server_dn_str = NULL;
828         talloc_free(tmp_ctx); 
829
830         /* Now, if it was AD, then we want to start looking changing a
831          * few more things.  Otherwise, we are done. */
832         if (r->out.realm) {
833                 status = libnet_JoinADSDomain(ctx, r);
834                 return status;
835         }
836
837         return status;
838 }
839
840 NTSTATUS libnet_set_join_secrets(struct libnet_context *ctx, 
841                                  TALLOC_CTX *mem_ctx, 
842                                  struct libnet_set_join_secrets *r)
843 {
844         TALLOC_CTX *tmp_mem;
845         int ret, rtn;
846         struct ldb_context *ldb;
847         struct ldb_dn *base_dn;
848         struct ldb_message **msgs, *msg;
849         const char *sct;
850         const char * const attrs[] = {
851                 "whenChanged",
852                 "secret",
853                 "priorSecret",
854                 "priorChanged",
855                 "krb5Keytab",
856                 "privateKeytab",
857                 NULL
858         };
859
860         tmp_mem = talloc_new(mem_ctx);
861         if (!tmp_mem) {
862                 return NT_STATUS_NO_MEMORY;
863         }
864
865         /* Open the secrets database */
866         ldb = secrets_db_connect(tmp_mem, ctx->event_ctx, ctx->lp_ctx);
867         if (!ldb) {
868                 r->out.error_string
869                         = talloc_asprintf(mem_ctx, 
870                                           "Could not open secrets database");
871                 talloc_free(tmp_mem);
872                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
873         }
874
875         /*
876          * now prepare the record for secrets.ldb
877          */
878         sct = talloc_asprintf(tmp_mem, "%d", r->in.join_type); 
879         if (!sct) {
880                 r->out.error_string = NULL;
881                 talloc_free(tmp_mem);
882                 return NT_STATUS_NO_MEMORY;
883         }
884         
885         msg = ldb_msg_new(tmp_mem);
886         if (!msg) {
887                 r->out.error_string = NULL;
888                 talloc_free(tmp_mem);
889                 return NT_STATUS_NO_MEMORY;
890         }
891
892         base_dn = ldb_dn_new(tmp_mem, ldb, "cn=Primary Domains");
893         if (!base_dn) {
894                 r->out.error_string = NULL;
895                 talloc_free(tmp_mem);
896                 return NT_STATUS_NO_MEMORY;
897         }
898
899         msg->dn = ldb_dn_copy(tmp_mem, base_dn);
900         if ( ! ldb_dn_add_child_fmt(msg->dn, "flatname=%s", r->in.domain_name)) {
901                 r->out.error_string = NULL;
902                 talloc_free(tmp_mem);
903                 return NT_STATUS_NO_MEMORY;
904         }
905         
906         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "flatname", r->in.domain_name);
907         if (rtn == -1) {
908                 r->out.error_string = NULL;
909                 talloc_free(tmp_mem);
910                 return NT_STATUS_NO_MEMORY;
911         }
912
913         if (r->in.realm) {
914                 rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "realm", r->in.realm);
915                 if (rtn == -1) {
916                         r->out.error_string = NULL;
917                         talloc_free(tmp_mem);
918                         return NT_STATUS_NO_MEMORY;
919                 }
920
921                 rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "objectClass", "primaryDomain");
922                 if (rtn == -1) {
923                         r->out.error_string = NULL;
924                         talloc_free(tmp_mem);
925                         return NT_STATUS_NO_MEMORY;
926                 }
927         }
928
929         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "objectClass", "primaryDomain");
930         if (rtn == -1) {
931                 r->out.error_string = NULL;
932                 talloc_free(tmp_mem);
933                 return NT_STATUS_NO_MEMORY;
934         }
935
936         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secret", r->in.join_password);
937         if (rtn == -1) {
938                 r->out.error_string = NULL;
939                 talloc_free(tmp_mem);
940                 return NT_STATUS_NO_MEMORY;
941         }
942
943         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "samAccountName", r->in.account_name);
944         if (rtn == -1) {
945                 r->out.error_string = NULL;
946                 talloc_free(tmp_mem);
947                 return NT_STATUS_NO_MEMORY;
948         }
949
950         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secureChannelType", sct);
951         if (rtn == -1) {
952                 r->out.error_string = NULL;
953                 talloc_free(tmp_mem);
954                 return NT_STATUS_NO_MEMORY;
955         }
956
957         if (r->in.kvno) {
958                 rtn = samdb_msg_add_uint(ldb, tmp_mem, msg, "msDS-KeyVersionNumber",
959                                          r->in.kvno);
960                 if (rtn == -1) {
961                         r->out.error_string = NULL;
962                         talloc_free(tmp_mem);
963                         return NT_STATUS_NO_MEMORY;
964                 }
965         }
966
967         if (r->in.domain_sid) {
968                 rtn = samdb_msg_add_dom_sid(ldb, tmp_mem, msg, "objectSid",
969                                             r->in.domain_sid);
970                 if (rtn == -1) {
971                         r->out.error_string = NULL;
972                         talloc_free(tmp_mem);
973                         return NT_STATUS_NO_MEMORY;
974                 }
975         }
976
977         /* 
978          * search for the secret record
979          * - remove the records we find
980          * - and fetch the old secret and store it under priorSecret
981          */
982         ret = gendb_search(ldb,
983                            tmp_mem, base_dn,
984                            &msgs, attrs,
985                            "(|" SECRETS_PRIMARY_DOMAIN_FILTER "(realm=%s))",
986                            r->in.domain_name, r->in.realm);
987         if (ret == 0) {
988                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secretsKeytab", "secrets.keytab");
989                 if (rtn == -1) {
990                         r->out.error_string = NULL;
991                         talloc_free(tmp_mem);
992                         return NT_STATUS_NO_MEMORY;
993                 }
994         } else if (ret == -1) {
995                 r->out.error_string
996                         = talloc_asprintf(mem_ctx, 
997                                           "Search for domain: %s and realm: %s failed: %s", 
998                                           r->in.domain_name, r->in.realm, ldb_errstring(ldb));
999                 talloc_free(tmp_mem);
1000                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1001         } else {
1002                 const struct ldb_val *private_keytab;
1003                 const struct ldb_val *krb5_main_keytab;
1004                 const struct ldb_val *prior_secret;
1005                 const struct ldb_val *prior_modified_time;
1006                 int i;
1007
1008                 for (i = 0; i < ret; i++) {
1009                         ldb_delete(ldb, msgs[i]->dn);
1010                 }
1011
1012                 prior_secret = ldb_msg_find_ldb_val(msgs[0], "secret");
1013                 if (prior_secret) {
1014                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorSecret", prior_secret);
1015                         if (rtn == -1) {
1016                                 r->out.error_string = NULL;
1017                                 talloc_free(tmp_mem);
1018                                 return NT_STATUS_NO_MEMORY;
1019                         }
1020                 }
1021                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secret", r->in.join_password);
1022                 if (rtn == -1) {
1023                         r->out.error_string = NULL;
1024                         talloc_free(tmp_mem);
1025                         return NT_STATUS_NO_MEMORY;
1026                 }
1027
1028                 prior_modified_time = ldb_msg_find_ldb_val(msgs[0], 
1029                                                            "whenChanged");
1030                 if (prior_modified_time) {
1031                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorWhenChanged", 
1032                                                   prior_modified_time);
1033                         if (rtn == -1) {
1034                                 r->out.error_string = NULL;
1035                                 talloc_free(tmp_mem);
1036                                 return NT_STATUS_NO_MEMORY;
1037                         }
1038                 }
1039
1040                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "samAccountName", r->in.account_name);
1041                 if (rtn == -1) {
1042                         r->out.error_string = NULL;
1043                         talloc_free(tmp_mem);
1044                         return NT_STATUS_NO_MEMORY;
1045                 }
1046
1047                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secureChannelType", sct);
1048                 if (rtn == -1) {
1049                         r->out.error_string = NULL;
1050                         talloc_free(tmp_mem);
1051                         return NT_STATUS_NO_MEMORY;
1052                 }
1053
1054                 /* We will want to keep the keytab names */
1055                 private_keytab = ldb_msg_find_ldb_val(msgs[0], "privateKeytab");
1056                 if (private_keytab) {
1057                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "privateKeytab", private_keytab);
1058                         if (rtn == -1) {
1059                                 r->out.error_string = NULL;
1060                                 talloc_free(tmp_mem);
1061                                 return NT_STATUS_NO_MEMORY;
1062                         }
1063                 }
1064                 krb5_main_keytab = ldb_msg_find_ldb_val(msgs[0], "krb5Keytab");
1065                 if (krb5_main_keytab) {
1066                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg,
1067                                         "krb5Keytab", krb5_main_keytab);
1068                         if (rtn == -1) {
1069                                 r->out.error_string = NULL;
1070                                 talloc_free(tmp_mem);
1071                                 return NT_STATUS_NO_MEMORY;
1072                         }
1073                 }
1074         }
1075
1076         /* create the secret */
1077         ret = ldb_add(ldb, msg);
1078         if (ret != 0) {
1079                 r->out.error_string = talloc_asprintf(mem_ctx, "Failed to create secret record %s", 
1080                                                       ldb_dn_get_linearized(msg->dn));
1081                 talloc_free(tmp_mem);
1082                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1083         }
1084
1085         return NT_STATUS_OK;
1086 }
1087
1088 static NTSTATUS libnet_Join_primary_domain(struct libnet_context *ctx, 
1089                                            TALLOC_CTX *mem_ctx, 
1090                                            struct libnet_Join *r)
1091 {
1092         NTSTATUS status;
1093         TALLOC_CTX *tmp_mem;
1094         struct libnet_JoinDomain *r2;
1095         struct libnet_set_join_secrets *r3;
1096         uint32_t acct_type = 0;
1097         const char *account_name;
1098         const char *netbios_name;
1099         
1100         r->out.error_string = NULL;
1101
1102         tmp_mem = talloc_new(mem_ctx);
1103         if (!tmp_mem) {
1104                 return NT_STATUS_NO_MEMORY;
1105         }
1106
1107         r2 = talloc(tmp_mem, struct libnet_JoinDomain);
1108         if (!r2) {
1109                 r->out.error_string = NULL;
1110                 talloc_free(tmp_mem);
1111                 return NT_STATUS_NO_MEMORY;
1112         }
1113         
1114         if (r->in.join_type == SEC_CHAN_BDC) {
1115                 acct_type = ACB_SVRTRUST;
1116         } else if (r->in.join_type == SEC_CHAN_WKSTA) {
1117                 acct_type = ACB_WSTRUST;
1118         } else {
1119                 r->out.error_string = NULL;
1120                 talloc_free(tmp_mem);   
1121                 return NT_STATUS_INVALID_PARAMETER;
1122         }
1123
1124         if (r->in.netbios_name != NULL) {
1125                 netbios_name = r->in.netbios_name;
1126         } else {
1127                 netbios_name = talloc_reference(tmp_mem, lp_netbios_name(ctx->lp_ctx));
1128                 if (!netbios_name) {
1129                         r->out.error_string = NULL;
1130                         talloc_free(tmp_mem);
1131                         return NT_STATUS_NO_MEMORY;
1132                 }
1133         }
1134
1135         account_name = talloc_asprintf(tmp_mem, "%s$", netbios_name);
1136         if (!account_name) {
1137                 r->out.error_string = NULL;
1138                 talloc_free(tmp_mem);
1139                 return NT_STATUS_NO_MEMORY;
1140         }
1141         
1142         /*
1143          * join the domain
1144          */
1145         ZERO_STRUCTP(r2);
1146         r2->in.domain_name      = r->in.domain_name;
1147         r2->in.account_name     = account_name;
1148         r2->in.netbios_name     = netbios_name;
1149         r2->in.level            = LIBNET_JOINDOMAIN_AUTOMATIC;
1150         r2->in.acct_type        = acct_type;
1151         r2->in.recreate_account = false;
1152         status = libnet_JoinDomain(ctx, r2, r2);
1153         if (!NT_STATUS_IS_OK(status)) {
1154                 r->out.error_string = talloc_steal(mem_ctx, r2->out.error_string);
1155                 talloc_free(tmp_mem);
1156                 return status;
1157         }
1158
1159         r3 = talloc(tmp_mem, struct libnet_set_join_secrets);
1160         if (!r3) {
1161                 r->out.error_string = NULL;
1162                 talloc_free(tmp_mem);
1163                 return NT_STATUS_NO_MEMORY;
1164         }
1165         
1166         ZERO_STRUCTP(r3);
1167         r3->in.domain_name = r2->out.domain_name;
1168         r3->in.realm = r2->out.realm;
1169         r3->in.account_name = account_name;
1170         r3->in.netbios_name = netbios_name;
1171         r3->in.join_type = r->in.join_type;
1172         r3->in.join_password = r2->out.join_password;
1173         r3->in.kvno = r2->out.kvno;
1174         r3->in.domain_sid = r2->out.domain_sid;
1175         
1176         status = libnet_set_join_secrets(ctx, r3, r3);
1177         if (!NT_STATUS_IS_OK(status)) {
1178                 r->out.error_string = talloc_steal(mem_ctx, r3->out.error_string);
1179                 talloc_free(tmp_mem);
1180                 return status;
1181         }
1182
1183         /* move all out parameter to the callers TALLOC_CTX */
1184         r->out.error_string     = NULL;
1185         r->out.join_password    = r2->out.join_password;
1186         talloc_steal(mem_ctx, r2->out.join_password);
1187         r->out.domain_sid       = r2->out.domain_sid;
1188         talloc_steal(mem_ctx, r2->out.domain_sid);
1189         r->out.domain_name      = r2->out.domain_name;
1190         talloc_steal(mem_ctx, r2->out.domain_name);
1191         talloc_free(tmp_mem);
1192         return NT_STATUS_OK;
1193 }
1194
1195 NTSTATUS libnet_Join(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_Join *r)
1196 {
1197         switch (r->in.join_type) {
1198                 case SEC_CHAN_WKSTA:
1199                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1200                 case SEC_CHAN_BDC:
1201                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1202                 case SEC_CHAN_DOMAIN:
1203                         break;
1204         }
1205
1206         r->out.error_string = talloc_asprintf(mem_ctx,
1207                                               "Invalid join type specified (%08X) attempting to join domain %s",
1208                                               r->in.join_type, r->in.domain_name);
1209         return NT_STATUS_INVALID_PARAMETER;
1210 }