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