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