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