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