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