r19299: Fix possible memleaks
[ira/wip.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 "passdb/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 "librpc/gen_ndr/ndr_samr_c.h"
34
35 /*
36  * complete a domain join, when joining to a AD domain:
37  * 1.) connect and bind to the DRSUAPI pipe
38  * 2.) do a DsCrackNames() to find the machine account dn
39  * 3.) connect to LDAP
40  * 4.) do an ldap search to find the "msDS-KeyVersionNumber" of the machine account
41  * 5.) set the servicePrincipalName's of the machine account via LDAP, (maybe we should use DsWriteAccountSpn()...)
42  * 6.) do a DsCrackNames() to find the domain dn
43  * 7.) find out Site specific stuff, look at libnet_JoinSite() for details
44  */
45 static NTSTATUS libnet_JoinADSDomain(struct libnet_context *ctx, struct libnet_JoinDomain *r)
46 {
47         NTSTATUS status;
48
49         TALLOC_CTX *tmp_ctx;
50
51         const char *realm = r->out.realm;
52
53         struct dcerpc_binding *samr_binding = r->out.samr_binding;
54
55         struct dcerpc_pipe *drsuapi_pipe;
56         struct dcerpc_binding *drsuapi_binding;
57         struct drsuapi_DsBind r_drsuapi_bind;
58         struct drsuapi_DsCrackNames r_crack_names;
59         struct drsuapi_DsNameString names[1];
60         struct policy_handle drsuapi_bind_handle;
61         struct GUID drsuapi_bind_guid;
62
63         struct ldb_context *remote_ldb;
64         const struct ldb_dn *account_dn;
65         const char *account_dn_str;
66         const char *remote_ldb_url;
67         struct ldb_result *res;
68         struct ldb_message *msg;
69
70         int ret, rtn;
71
72         unsigned int kvno;
73         
74         const char * const attrs[] = {
75                 "msDS-KeyVersionNumber",
76                 "servicePrincipalName",
77                 "dNSHostName",
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.unknown1      = 0x000004e4;
164         r_crack_names.in.req.req1.unknown2      = 0x00000407;
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         account_dn = ldb_dn_explode(tmp_ctx, account_dn_str);
222         if (!account_dn) {
223                 r->out.error_string = talloc_asprintf(r, "Invalid account dn: %s",
224                                                       account_dn_str);
225                 talloc_free(tmp_ctx);
226                 return NT_STATUS_UNSUCCESSFUL;
227         }
228
229         /* Now we know the user's DN, open with LDAP, read and modify a few things */
230
231         remote_ldb_url = talloc_asprintf(tmp_ctx, "ldap://%s", 
232                                          drsuapi_binding->target_hostname);
233         if (!remote_ldb_url) {
234                 r->out.error_string = NULL;
235                 talloc_free(tmp_ctx);
236                 return NT_STATUS_NO_MEMORY;
237         }
238
239         remote_ldb = ldb_wrap_connect(tmp_ctx, remote_ldb_url, 
240                                       NULL, ctx->cred, 0, NULL);
241         if (!remote_ldb) {
242                 r->out.error_string = NULL;
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         talloc_steal(tmp_ctx, res);
251         if (ret != LDB_SUCCESS || res->count != 1) {
252                 r->out.error_string = talloc_asprintf(r, "ldb_search for %s failed - %s",
253                                                       account_dn_str, ldb_errstring(remote_ldb));
254                 talloc_free(tmp_ctx);
255                 return NT_STATUS_UNSUCCESSFUL;
256         }
257
258         /* If we have a kvno recorded in AD, we need it locally as well */
259         kvno = ldb_msg_find_attr_as_uint(res->msgs[0], "msDS-KeyVersionNumber", 0);
260
261         /* Prepare a new message, for the modify */
262         msg = ldb_msg_new(tmp_ctx);
263         if (!msg) {
264                 r->out.error_string = NULL;
265                 talloc_free(tmp_ctx);
266                 return NT_STATUS_NO_MEMORY;
267         }
268         msg->dn = res->msgs[0]->dn;
269
270         {
271                 int i;
272                 const char *service_principal_name[6];
273                 const char *dns_host_name = strlower_talloc(tmp_ctx, 
274                                                             talloc_asprintf(tmp_ctx, 
275                                                                             "%s.%s", 
276                                                                             r->in.netbios_name, 
277                                                                             realm));
278
279                 if (!dns_host_name) {
280                         r->out.error_string = NULL;
281                         talloc_free(tmp_ctx);
282                         return NT_STATUS_NO_MEMORY;
283                 }
284
285                 service_principal_name[0] = talloc_asprintf(tmp_ctx, "host/%s", dns_host_name);
286                 service_principal_name[1] = talloc_asprintf(tmp_ctx, "host/%s", strlower_talloc(tmp_ctx, r->in.netbios_name));
287                 service_principal_name[2] = talloc_asprintf(tmp_ctx, "host/%s/%s", dns_host_name, realm);
288                 service_principal_name[3] = talloc_asprintf(tmp_ctx, "host/%s/%s", strlower_talloc(tmp_ctx, r->in.netbios_name), realm);
289                 service_principal_name[4] = talloc_asprintf(tmp_ctx, "host/%s/%s", dns_host_name, r->out.domain_name);
290                 service_principal_name[5] = talloc_asprintf(tmp_ctx, "host/%s/%s", strlower_talloc(tmp_ctx, r->in.netbios_name), r->out.domain_name);
291                 
292                 for (i=0; i < ARRAY_SIZE(service_principal_name); i++) {
293                         if (!service_principal_name[i]) {
294                                 r->out.error_string = NULL;
295                                 talloc_free(tmp_ctx);
296                                 return NT_STATUS_NO_MEMORY;
297                         }
298                         rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "servicePrincipalName", service_principal_name[i]);
299                         if (rtn == -1) {
300                                 r->out.error_string = NULL;
301                                 talloc_free(tmp_ctx);
302                                 return NT_STATUS_NO_MEMORY;
303                         }
304                 }
305
306                 rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "dNSHostName", dns_host_name);
307                 if (rtn == -1) {
308                         r->out.error_string = NULL;
309                         talloc_free(tmp_ctx);
310                         return NT_STATUS_NO_MEMORY;
311                 }
312
313                 rtn = samdb_replace(remote_ldb, tmp_ctx, msg);
314                 if (rtn != 0) {
315                         r->out.error_string
316                                 = talloc_asprintf(r, 
317                                                   "Failed to replace entries on %s", 
318                                                   ldb_dn_linearize(tmp_ctx, msg->dn));
319                         talloc_free(tmp_ctx);
320                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
321                 }
322         }
323                                 
324         /* DsCrackNames to find out the DN of the domain. */
325         r_crack_names.in.req.req1.format_offered = DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT;
326         r_crack_names.in.req.req1.format_desired = DRSUAPI_DS_NAME_FORMAT_FQDN_1779;
327         names[0].str = talloc_asprintf(tmp_ctx, "%s\\", r->out.domain_name);
328         if (!names[0].str) {
329                 r->out.error_string = NULL;
330                 talloc_free(tmp_ctx);
331                 return NT_STATUS_NO_MEMORY;
332         }
333
334         status = dcerpc_drsuapi_DsCrackNames(drsuapi_pipe, tmp_ctx, &r_crack_names);
335         if (!NT_STATUS_IS_OK(status)) {
336                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
337                         r->out.error_string
338                                 = talloc_asprintf(r,
339                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s", 
340                                                   r->in.domain_name, 
341                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
342                         talloc_free(tmp_ctx);
343                         return status;
344                 } else {
345                         r->out.error_string
346                                 = talloc_asprintf(r,
347                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s", 
348                                                   r->in.domain_name, 
349                                                   nt_errstr(status));
350                         talloc_free(tmp_ctx);
351                         return status;
352                 }
353         } else if (!W_ERROR_IS_OK(r_crack_names.out.result)) {
354                 r->out.error_string
355                         = talloc_asprintf(r,
356                                           "DsCrackNames failed - %s", win_errstr(r_crack_names.out.result));
357                 talloc_free(tmp_ctx);
358                 return NT_STATUS_UNSUCCESSFUL;
359         } else if (r_crack_names.out.level != 1 
360                    || !r_crack_names.out.ctr.ctr1 
361                    || r_crack_names.out.ctr.ctr1->count != 1
362                    || !r_crack_names.out.ctr.ctr1->array[0].result_name           
363                    || r_crack_names.out.ctr.ctr1->array[0].status != DRSUAPI_DS_NAME_STATUS_OK) {
364                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed");
365                 talloc_free(tmp_ctx);
366                 return NT_STATUS_UNSUCCESSFUL;
367         }
368
369         /* Store the account DN. */
370         r->out.account_dn_str = account_dn_str;
371         talloc_steal(r, account_dn_str);
372
373         /* Store the domain DN. */
374         r->out.domain_dn_str = r_crack_names.out.ctr.ctr1->array[0].result_name;
375         talloc_steal(r, r_crack_names.out.ctr.ctr1->array[0].result_name);
376
377         r->out.kvno = kvno;
378
379         if (r->in.acct_type == ACB_SVRTRUST) {
380                 status = libnet_JoinSite(remote_ldb, r);
381         }
382         talloc_free(tmp_ctx);
383
384         return status;
385 }
386
387 /*
388  * do a domain join using DCERPC/SAMR calls
389  * - connect to the LSA pipe, to try and find out information about the domain
390  * - create a secondary connection to SAMR pipe
391  * - do a samr_Connect to get a policy handle
392  * - do a samr_LookupDomain to get the domain sid
393  * - do a samr_OpenDomain to get a domain handle
394  * - do a samr_CreateAccount to try and get a new account 
395  * 
396  * If that fails, do:
397  * - do a samr_LookupNames to get the users rid
398  * - do a samr_OpenUser to get a user handle
399  * - potentially delete and recreate the user
400  * - assert the account is of the right type with samrQueryUserInfo
401  * 
402  * - call libnet_SetPassword_samr_handle to set the password
403  *
404  * - do a samrSetUserInfo to set the account flags
405  * - do some ADS specific things when we join as Domain Controller,
406  *    look at libnet_joinADSDomain() for the details
407  */
408 NTSTATUS libnet_JoinDomain(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_JoinDomain *r)
409 {
410         TALLOC_CTX *tmp_ctx;
411
412         NTSTATUS status, cu_status;
413
414         struct libnet_RpcConnect *connect_with_info;
415         struct dcerpc_pipe *samr_pipe;
416
417         struct samr_Connect sc;
418         struct policy_handle p_handle;
419         struct samr_OpenDomain od;
420         struct policy_handle d_handle;
421         struct samr_LookupNames ln;
422         struct samr_OpenUser ou;
423         struct samr_CreateUser2 cu;
424         struct policy_handle *u_handle = NULL;
425         struct samr_QueryUserInfo qui;
426         struct samr_SetUserInfo sui;
427         union samr_UserInfo u_info;
428         union libnet_SetPassword r2;
429         struct samr_GetUserPwInfo pwp;
430         struct lsa_String samr_account_name;
431         
432         uint32_t acct_flags, old_acct_flags;
433         uint32_t rid, access_granted;
434         int policy_min_pw_len = 0;
435
436         struct dom_sid *account_sid = NULL;
437         const char *password_str = NULL;
438         
439         r->out.error_string = NULL;
440         r2.samr_handle.out.error_string = NULL;
441         
442         tmp_ctx = talloc_named(mem_ctx, 0, "libnet_Join temp context");
443         if (!tmp_ctx) {
444                 r->out.error_string = NULL;
445                 return NT_STATUS_NO_MEMORY;
446         }
447         
448         u_handle = talloc(tmp_ctx, struct policy_handle);
449         if (!u_handle) {
450                 r->out.error_string = NULL;
451                 talloc_free(tmp_ctx);
452                 return NT_STATUS_NO_MEMORY;
453         }
454         
455         connect_with_info = talloc(tmp_ctx, struct libnet_RpcConnect);
456         if (!connect_with_info) {
457                 r->out.error_string = NULL;
458                 talloc_free(tmp_ctx);
459                 return NT_STATUS_NO_MEMORY;
460         }
461
462         /* prepare connect to the LSA pipe of PDC */
463         if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
464                 connect_with_info->in.binding = NULL;
465                 connect_with_info->in.name    = r->in.domain_name;
466         } else {
467                 connect_with_info->in.binding = r->in.binding;
468                 connect_with_info->in.name    = NULL;
469         }
470
471         connect_with_info->level              = LIBNET_RPC_CONNECT_DC_INFO;
472         connect_with_info->in.dcerpc_iface    = &dcerpc_table_samr;
473
474         /*
475           establish a SAMR connection, on the same CIFS transport
476         */
477         status = libnet_RpcConnect(ctx, tmp_ctx, connect_with_info);
478         if (!NT_STATUS_IS_OK(status)) {
479                 if (r->in.binding) {
480                         r->out.error_string = talloc_asprintf(mem_ctx,
481                                                               "Connection to SAMR pipe of DC %s failed: %s",
482                                                               r->in.binding, connect_with_info->out.error_string);
483                 } else {
484                         r->out.error_string = talloc_asprintf(mem_ctx,
485                                                               "Connection to SAMR pipe of PDC for %s failed: %s",
486                                                               r->in.domain_name, connect_with_info->out.error_string);
487                 }
488                 talloc_free(tmp_ctx);
489                 return status;
490         }
491
492         samr_pipe = connect_with_info->out.dcerpc_pipe;
493
494         status = dcerpc_pipe_auth(tmp_ctx, &samr_pipe,
495                                   connect_with_info->out.dcerpc_pipe->binding, 
496                                   &dcerpc_table_samr, ctx->cred);
497         if (!NT_STATUS_IS_OK(status)) {
498                 r->out.error_string = talloc_asprintf(mem_ctx,
499                                                 "SAMR bind failed: %s",
500                                                 nt_errstr(status));
501                 talloc_free(tmp_ctx);
502                 return status;
503         }
504
505         /* prepare samr_Connect */
506         ZERO_STRUCT(p_handle);
507         sc.in.system_name = NULL;
508         sc.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
509         sc.out.connect_handle = &p_handle;
510
511         /* 2. do a samr_Connect to get a policy handle */
512         status = dcerpc_samr_Connect(samr_pipe, tmp_ctx, &sc);
513         if (!NT_STATUS_IS_OK(status)) {
514                 r->out.error_string = talloc_asprintf(mem_ctx,
515                                                 "samr_Connect failed: %s",
516                                                 nt_errstr(status));
517                 talloc_free(tmp_ctx);
518                 return status;
519         }
520
521         /* If this is a connection on ncacn_ip_tcp to Win2k3 SP1, we don't get back this useful info */
522         if (!connect_with_info->out.domain_name) {
523                 if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
524                         connect_with_info->out.domain_name = talloc_strdup(tmp_ctx, r->in.domain_name);
525                 } else {
526                         /* Bugger, we just lost our way to automaticly find the domain name */
527                         connect_with_info->out.domain_name = talloc_strdup(tmp_ctx, lp_workgroup());
528                 }
529         }
530
531         /* Perhaps we didn't get a SID above, because we are against ncacn_ip_tcp */
532         if (!connect_with_info->out.domain_sid) {
533                 struct lsa_String name;
534                 struct samr_LookupDomain l;
535                 name.string = connect_with_info->out.domain_name;
536                 l.in.connect_handle = &p_handle;
537                 l.in.domain_name = &name;
538                 
539                 status = dcerpc_samr_LookupDomain(samr_pipe, tmp_ctx, &l);
540                 if (!NT_STATUS_IS_OK(status)) {
541                         r->out.error_string = talloc_asprintf(mem_ctx,
542                                                               "SAMR LookupDomain failed: %s",
543                                                               nt_errstr(status));
544                         talloc_free(tmp_ctx);
545                         return status;
546                 }
547                 connect_with_info->out.domain_sid = l.out.sid;
548         }
549
550         /* prepare samr_OpenDomain */
551         ZERO_STRUCT(d_handle);
552         od.in.connect_handle = &p_handle;
553         od.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
554         od.in.sid = connect_with_info->out.domain_sid;
555         od.out.domain_handle = &d_handle;
556
557         /* do a samr_OpenDomain to get a domain handle */
558         status = dcerpc_samr_OpenDomain(samr_pipe, tmp_ctx, &od);                       
559         if (!NT_STATUS_IS_OK(status)) {
560                 r->out.error_string = talloc_asprintf(mem_ctx,
561                                                       "samr_OpenDomain for [%s] failed: %s",
562                                                       dom_sid_string(tmp_ctx, connect_with_info->out.domain_sid),
563                                                       nt_errstr(status));
564                 talloc_free(tmp_ctx);
565                 return status;
566         }
567         
568         /* prepare samr_CreateUser2 */
569         ZERO_STRUCTP(u_handle);
570         cu.in.domain_handle  = &d_handle;
571         cu.in.access_mask     = SEC_FLAG_MAXIMUM_ALLOWED;
572         samr_account_name.string = r->in.account_name;
573         cu.in.account_name    = &samr_account_name;
574         cu.in.acct_flags      = r->in.acct_type;
575         cu.out.user_handle    = u_handle;
576         cu.out.rid            = &rid;
577         cu.out.access_granted = &access_granted;
578
579         /* do a samr_CreateUser2 to get an account handle, or an error */
580         cu_status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                   
581         status = cu_status;
582         if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
583                 /* prepare samr_LookupNames */
584                 ln.in.domain_handle = &d_handle;
585                 ln.in.num_names = 1;
586                 ln.in.names = talloc_array(tmp_ctx, struct lsa_String, 1);
587                 if (!ln.in.names) {
588                         r->out.error_string = NULL;
589                         talloc_free(tmp_ctx);
590                         return NT_STATUS_NO_MEMORY;
591                 }
592                 ln.in.names[0].string = r->in.account_name;
593                 
594                 /* 5. do a samr_LookupNames to get the users rid */
595                 status = dcerpc_samr_LookupNames(samr_pipe, tmp_ctx, &ln);
596                 if (!NT_STATUS_IS_OK(status)) {
597                         r->out.error_string = talloc_asprintf(mem_ctx,
598                                                 "samr_LookupNames for [%s] failed: %s",
599                                                 r->in.account_name,
600                                                 nt_errstr(status));
601                         talloc_free(tmp_ctx);
602                         return status;
603                 }
604                 
605                 /* check if we got one RID for the user */
606                 if (ln.out.rids.count != 1) {
607                         r->out.error_string = talloc_asprintf(mem_ctx,
608                                                               "samr_LookupNames for [%s] returns %d RIDs",
609                                                               r->in.account_name, ln.out.rids.count);
610                         talloc_free(tmp_ctx);
611                         return NT_STATUS_INVALID_PARAMETER;
612                 }
613                 
614                 /* prepare samr_OpenUser */
615                 ZERO_STRUCTP(u_handle);
616                 ou.in.domain_handle = &d_handle;
617                 ou.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
618                 ou.in.rid = ln.out.rids.ids[0];
619                 rid = ou.in.rid;
620                 ou.out.user_handle = u_handle;
621                 
622                 /* 6. do a samr_OpenUser to get a user handle */
623                 status = dcerpc_samr_OpenUser(samr_pipe, tmp_ctx, &ou); 
624                 if (!NT_STATUS_IS_OK(status)) {
625                         r->out.error_string = talloc_asprintf(mem_ctx,
626                                                         "samr_OpenUser for [%s] failed: %s",
627                                                         r->in.account_name,
628                                                         nt_errstr(status));
629                         talloc_free(tmp_ctx);
630                         return status;
631                 }
632
633                 if (r->in.recreate_account) {
634                         struct samr_DeleteUser d;
635                         d.in.user_handle = u_handle;
636                         d.out.user_handle = u_handle;
637                         status = dcerpc_samr_DeleteUser(samr_pipe, mem_ctx, &d);
638                         if (!NT_STATUS_IS_OK(status)) {
639                                 r->out.error_string = talloc_asprintf(mem_ctx,
640                                                                       "samr_DeleteUser (for recreate) of [%s] failed: %s",
641                                                                       r->in.account_name,
642                                                                       nt_errstr(status));
643                                 talloc_free(tmp_ctx);
644                                 return status;
645                         }
646
647                         /* We want to recreate, so delete and another samr_CreateUser2 */
648                         
649                         /* &cu filled in above */
650                         status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                      
651                         if (!NT_STATUS_IS_OK(status)) {
652                                 r->out.error_string = talloc_asprintf(mem_ctx,
653                                                                       "samr_CreateUser2 (recreate) for [%s] failed: %s",
654                                                                       r->in.account_name, nt_errstr(status));
655                                 talloc_free(tmp_ctx);
656                                 return status;
657                         }
658                 }
659         } else if (!NT_STATUS_IS_OK(status)) {
660                 r->out.error_string = talloc_asprintf(mem_ctx,
661                                                       "samr_CreateUser2 for [%s] failed: %s",
662                                                       r->in.account_name, nt_errstr(status));
663                 talloc_free(tmp_ctx);
664                 return status;
665         }
666
667         /* prepare samr_QueryUserInfo (get flags) */
668         qui.in.user_handle = u_handle;
669         qui.in.level = 16;
670         
671         status = dcerpc_samr_QueryUserInfo(samr_pipe, tmp_ctx, &qui);
672         if (!NT_STATUS_IS_OK(status)) {
673                 r->out.error_string = talloc_asprintf(mem_ctx,
674                                                 "samr_QueryUserInfo for [%s] failed: %s",
675                                                 r->in.account_name,
676                                                 nt_errstr(status));
677                 talloc_free(tmp_ctx);
678                 return status;
679         }
680         
681         if (!qui.out.info) {
682                 status = NT_STATUS_INVALID_PARAMETER;
683                 r->out.error_string
684                         = talloc_asprintf(mem_ctx,
685                                           "samr_QueryUserInfo failed to return qui.out.info for [%s]: %s",
686                                           r->in.account_name, nt_errstr(status));
687                 talloc_free(tmp_ctx);
688                 return status;
689         }
690
691         old_acct_flags = (qui.out.info->info16.acct_flags & (ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST));
692         /* Possibly bail if the account is of the wrong type */
693         if (old_acct_flags
694             != r->in.acct_type) {
695                 const char *old_account_type, *new_account_type;
696                 switch (old_acct_flags) {
697                 case ACB_WSTRUST:
698                         old_account_type = "domain member (member)";
699                         break;
700                 case ACB_SVRTRUST:
701                         old_account_type = "domain controller (bdc)";
702                         break;
703                 case ACB_DOMTRUST:
704                         old_account_type = "trusted domain";
705                         break;
706                 default:
707                         return NT_STATUS_INVALID_PARAMETER;
708                 }
709                 switch (r->in.acct_type) {
710                 case ACB_WSTRUST:
711                         new_account_type = "domain member (member)";
712                         break;
713                 case ACB_SVRTRUST:
714                         new_account_type = "domain controller (bdc)";
715                         break;
716                 case ACB_DOMTRUST:
717                         new_account_type = "trusted domain";
718                         break;
719                 default:
720                         return NT_STATUS_INVALID_PARAMETER;
721                 }
722
723                 if (!NT_STATUS_EQUAL(cu_status, NT_STATUS_USER_EXISTS)) {
724                         /* We created a new user, but they didn't come out the right type?!? */
725                         r->out.error_string
726                                 = talloc_asprintf(mem_ctx,
727                                                   "We asked to create a new machine account (%s) of type %s, "
728                                                   "but we got an account of type %s.  This is unexpected.  "
729                                                   "Perhaps delete the account and try again.",
730                                                   r->in.account_name, new_account_type, old_account_type);
731                         talloc_free(tmp_ctx);
732                         return NT_STATUS_INVALID_PARAMETER;
733                 } else {
734                         /* The account is of the wrong type, so bail */
735
736                         /* TODO: We should allow a --force option to override, and redo this from the top setting r.in.recreate_account */
737                         r->out.error_string
738                                 = talloc_asprintf(mem_ctx,
739                                                   "The machine account (%s) already exists in the domain %s, "
740                                                   "but is a %s.  You asked to join as a %s.  Please delete "
741                                                   "the account and try again.",
742                                                   r->in.account_name, connect_with_info->out.domain_name, old_account_type, new_account_type);
743                         talloc_free(tmp_ctx);
744                         return NT_STATUS_USER_EXISTS;
745                 }
746         } else {
747                 acct_flags = qui.out.info->info16.acct_flags;
748         }
749         
750         acct_flags = (acct_flags & ~ACB_DISABLED);
751
752         /* Find out what password policy this user has */
753         pwp.in.user_handle = u_handle;
754
755         status = dcerpc_samr_GetUserPwInfo(samr_pipe, tmp_ctx, &pwp);                           
756         if (NT_STATUS_IS_OK(status)) {
757                 policy_min_pw_len = pwp.out.info.min_password_length;
758         }
759         
760         /* Grab a password of that minimum length */
761         
762         password_str = generate_random_str(tmp_ctx, MAX(8, policy_min_pw_len)); 
763
764         r2.samr_handle.level            = LIBNET_SET_PASSWORD_SAMR_HANDLE;
765         r2.samr_handle.in.account_name  = r->in.account_name;
766         r2.samr_handle.in.newpassword   = password_str;
767         r2.samr_handle.in.user_handle   = u_handle;
768         r2.samr_handle.in.dcerpc_pipe   = samr_pipe;
769
770         status = libnet_SetPassword(ctx, tmp_ctx, &r2); 
771         if (!NT_STATUS_IS_OK(status)) {
772                 r->out.error_string = talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
773                 talloc_free(tmp_ctx);
774                 return status;
775         }
776
777         /* reset flags (if required) */
778         if (acct_flags != qui.out.info->info16.acct_flags) {
779                 ZERO_STRUCT(u_info);
780                 u_info.info16.acct_flags = acct_flags;
781
782                 sui.in.user_handle = u_handle;
783                 sui.in.info = &u_info;
784                 sui.in.level = 16;
785                 
786                 dcerpc_samr_SetUserInfo(samr_pipe, tmp_ctx, &sui);
787                 if (!NT_STATUS_IS_OK(status)) {
788                         r->out.error_string = talloc_asprintf(mem_ctx,
789                                                         "samr_SetUserInfo for [%s] failed to remove ACB_DISABLED flag: %s",
790                                                         r->in.account_name,
791                                                         nt_errstr(status));
792                         talloc_free(tmp_ctx);
793                         return status;
794                 }
795         }
796
797         account_sid = dom_sid_add_rid(mem_ctx, connect_with_info->out.domain_sid, rid);
798         if (!account_sid) {
799                 r->out.error_string = NULL;
800                 talloc_free(tmp_ctx);
801                 return NT_STATUS_NO_MEMORY;
802         }
803
804         /* Finish out by pushing various bits of status data out for the caller to use */
805         r->out.join_password = password_str;
806         talloc_steal(mem_ctx, r->out.join_password);
807
808         r->out.domain_sid = connect_with_info->out.domain_sid;
809         talloc_steal(mem_ctx, r->out.domain_sid);
810
811         r->out.account_sid = account_sid;
812         talloc_steal(mem_ctx, r->out.account_sid);
813
814         r->out.domain_name = connect_with_info->out.domain_name;
815         talloc_steal(mem_ctx, r->out.domain_name);
816         r->out.realm = connect_with_info->out.realm;
817         talloc_steal(mem_ctx, r->out.realm);
818         r->out.samr_pipe = samr_pipe;
819         talloc_steal(mem_ctx, samr_pipe);
820         r->out.samr_binding = samr_pipe->binding;
821         talloc_steal(mem_ctx, r->out.samr_binding);
822         r->out.user_handle = u_handle;
823         talloc_steal(mem_ctx, u_handle);
824         r->out.error_string = r2.samr_handle.out.error_string;
825         talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
826         r->out.kvno = 0;
827         r->out.server_dn_str = NULL;
828         talloc_free(tmp_ctx); 
829
830         /* Now, if it was AD, then we want to start looking changing a
831          * few more things.  Otherwise, we are done. */
832         if (r->out.realm) {
833                 status = libnet_JoinADSDomain(ctx, r);
834                 return status;
835         }
836
837         return status;
838 }
839
840 static NTSTATUS libnet_Join_primary_domain(struct libnet_context *ctx, 
841                                            TALLOC_CTX *mem_ctx, 
842                                            struct libnet_Join *r)
843 {
844         NTSTATUS status;
845         TALLOC_CTX *tmp_mem;
846         struct libnet_JoinDomain *r2;
847         int ret, rtn;
848         struct ldb_context *ldb;
849         const struct ldb_dn *base_dn;
850         struct ldb_message **msgs, *msg;
851         const char *sct;
852         const char * const attrs[] = {
853                 "whenChanged",
854                 "secret",
855                 "priorSecret",
856                 "priorChanged",
857                 "krb5Keytab",
858                 "privateKeytab",
859                 NULL
860         };
861         uint32_t acct_type = 0;
862         const char *account_name;
863         const char *netbios_name;
864         char *filter;
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());
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);
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_explode(tmp_mem, "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_build_child(tmp_mem, "flatname", r2->out.domain_name, base_dn);
963         if (!msg->dn) {
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 = samdb_add(ldb, tmp_mem, msg);
1140         if (ret != 0) {
1141                 r->out.error_string = talloc_asprintf(mem_ctx, "Failed to create secret record %s", 
1142                                                       ldb_dn_linearize(ldb, msg->dn));
1143                 talloc_free(tmp_mem);
1144                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1145         }
1146
1147         if (r2->out.realm) {
1148                 struct cli_credentials *creds;
1149                 /* Make a credentials structure from it */
1150                 creds = cli_credentials_init(mem_ctx);
1151                 if (!creds) {
1152                         r->out.error_string = NULL;
1153                         talloc_free(tmp_mem);
1154                         return NT_STATUS_NO_MEMORY;
1155                 }
1156                 cli_credentials_set_conf(creds);
1157                 filter = talloc_asprintf(mem_ctx, "dn=%s", ldb_dn_linearize(mem_ctx, msg->dn));
1158                 status = cli_credentials_set_secrets(creds, NULL, filter);
1159                 if (!NT_STATUS_IS_OK(status)) {
1160                         r->out.error_string = talloc_asprintf(mem_ctx, "Failed to read secrets for keytab update for %s", 
1161                                                               filter);
1162                         talloc_free(tmp_mem);
1163                         return status;
1164                 } 
1165                 ret = cli_credentials_update_keytab(creds);
1166                 if (ret != 0) {
1167                         r->out.error_string = talloc_asprintf(mem_ctx, "Failed to update keytab for %s", 
1168                                                               filter);
1169                         talloc_free(tmp_mem);
1170                         return NT_STATUS_UNSUCCESSFUL;
1171                 }
1172         }
1173
1174         /* move all out parameter to the callers TALLOC_CTX */
1175         r->out.error_string     = NULL;
1176         r->out.join_password    = r2->out.join_password;
1177         talloc_steal(mem_ctx, r2->out.join_password);
1178         r->out.domain_sid       = r2->out.domain_sid;
1179         talloc_steal(mem_ctx, r2->out.domain_sid);
1180         r->out.domain_name      = r2->out.domain_name;
1181         talloc_steal(mem_ctx, r2->out.domain_name);
1182         talloc_free(tmp_mem);
1183         return NT_STATUS_OK;
1184 }
1185
1186 NTSTATUS libnet_Join(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_Join *r)
1187 {
1188         switch (r->in.join_type) {
1189                 case SEC_CHAN_WKSTA:
1190                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1191                 case SEC_CHAN_BDC:
1192                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1193                 case SEC_CHAN_DOMAIN:
1194                         break;
1195         }
1196
1197         r->out.error_string = talloc_asprintf(mem_ctx,
1198                                               "Invalid join type specified (%08X) attempting to join domain %s",
1199                                               r->in.join_type, r->in.domain_name);
1200         return NT_STATUS_INVALID_PARAMETER;
1201 }