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