r12413: do some testing with 0x1E names
[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_samr.h"
26 #include "librpc/gen_ndr/ndr_lsa.h"
27 #include "librpc/gen_ndr/ndr_drsuapi.h"
28 #include "lib/ldb/include/ldb.h"
29 #include "lib/ldb/include/ldb_errors.h"
30 #include "libcli/cldap/cldap.h"
31 #include "include/secrets.h"
32 #include "librpc/gen_ndr/drsuapi.h"
33
34 /*
35  * find out Site specific stuff:
36  * 1.) setup an CLDAP socket
37  * 2.) lookup the Site name
38  * 3.) Add entry CN=<netbios name>,CN=Servers,CN=<site name>,CN=Sites,CN=Configuration,<domain dn>.
39  * TODO: 4.) use DsAddEntry() to create CN=NTDS Settings,CN=<netbios name>,CN=Servers,CN=<site name>...
40  */
41 static NTSTATUS libnet_JoinSite(struct libnet_context *ctx,
42                                 struct dcerpc_pipe *drsuapi_pipe,
43                                 struct policy_handle drsuapi_bind_handle,
44                                 struct ldb_context *remote_ldb,
45                                 struct libnet_JoinDomain *libnet_r)
46 {
47         NTSTATUS status;
48         TALLOC_CTX *tmp_ctx;
49
50         struct cldap_socket *cldap = NULL;
51         struct cldap_netlogon search;
52
53         struct ldb_dn *server_dn;
54         struct ldb_message *msg;
55         int rtn;
56
57         const char *site_name;
58         const char *server_dn_str;
59         const char *config_dn_str;
60
61         tmp_ctx = talloc_named(libnet_r, 0, "libnet_JoinSite temp context");
62         if (!tmp_ctx) {
63                 libnet_r->out.error_string = NULL;
64                 return NT_STATUS_NO_MEMORY;
65         }
66
67         /* Resolve the site name. */
68
69         ZERO_STRUCT(search);
70         search.in.dest_address = libnet_r->out.samr_binding->host;
71         search.in.acct_control = -1;
72         search.in.version = 6;
73
74         cldap = cldap_socket_init(tmp_ctx, NULL);
75         status = cldap_netlogon(cldap, tmp_ctx, &search);
76         if (!NT_STATUS_IS_OK(status)) {
77                 /* Default to using Default-First-Site-Name rather than returning status at this point. */
78                 site_name = talloc_asprintf(tmp_ctx, "%s", "Default-First-Site-Name");
79                 if (!site_name) {
80                         libnet_r->out.error_string = NULL;
81                         talloc_free(tmp_ctx);
82                         return NT_STATUS_NO_MEMORY;
83                 }
84         } else {
85                 site_name = search.out.netlogon.logon5.site_name;
86         }
87
88         config_dn_str = talloc_asprintf(tmp_ctx, "CN=Configuration,%s", libnet_r->out.domain_dn_str);
89         if (!config_dn_str) {
90                 libnet_r->out.error_string = NULL;
91                 talloc_free(tmp_ctx);
92                 return NT_STATUS_NO_MEMORY;
93         }
94
95         server_dn_str = talloc_asprintf(tmp_ctx, "CN=%s,CN=Servers,CN=%s,CN=Sites,%s",
96                                                  libnet_r->in.netbios_name, site_name, config_dn_str);
97         if (!server_dn_str) {
98                 libnet_r->out.error_string = NULL;
99                 talloc_free(tmp_ctx);
100                 return NT_STATUS_NO_MEMORY;
101         }
102
103         /*
104          Add entry CN=<netbios name>,CN=Servers,CN=<site name>,CN=Sites,CN=Configuration,<domain dn>.
105         */
106         msg = ldb_msg_new(tmp_ctx);
107         if (!msg) {
108                 libnet_r->out.error_string = NULL;
109                 talloc_free(tmp_ctx);
110                 return NT_STATUS_NO_MEMORY;
111         }
112
113         rtn = ldb_msg_add_string(msg, "objectClass", "server");
114         if (rtn != 0) {
115                 libnet_r->out.error_string = NULL;
116                 talloc_free(tmp_ctx);
117                 return NT_STATUS_NO_MEMORY;
118         }
119         rtn = ldb_msg_add_string(msg, "systemFlags", "50000000");
120         if (rtn != 0) {
121                 libnet_r->out.error_string = NULL;
122                 talloc_free(tmp_ctx);
123                 return NT_STATUS_NO_MEMORY;
124         }
125         rtn = ldb_msg_add_string(msg, "serverReference",libnet_r->out.account_dn_str);
126         if (rtn != 0) {
127                 libnet_r->out.error_string = NULL;
128                 talloc_free(tmp_ctx);
129                 return NT_STATUS_NO_MEMORY;
130         }
131
132         server_dn = ldb_dn_explode(tmp_ctx, server_dn_str);
133         if (server_dn == NULL) {
134                 libnet_r->out.error_string = talloc_asprintf(libnet_r, 
135                                         "Invalid server dn: %s",
136                                         server_dn_str);
137                 talloc_free(tmp_ctx);
138                 return NT_STATUS_UNSUCCESSFUL;
139         }
140
141         msg->dn = server_dn; 
142
143         rtn = ldb_add(remote_ldb, msg);
144         if (rtn == LDB_ERR_ENTRY_ALREADY_EXISTS) {
145                 int i;
146                 
147                 /* make a 'modify' msg, and only for serverReference */
148                 msg = ldb_msg_new(tmp_ctx);
149                 if (!msg) {
150                         libnet_r->out.error_string = NULL;
151                         talloc_free(tmp_ctx);
152                         return NT_STATUS_NO_MEMORY;
153                 }
154                 msg->dn = server_dn; 
155
156                 rtn = ldb_msg_add_string(msg, "serverReference",libnet_r->out.account_dn_str);
157                 if (rtn != 0) {
158                         libnet_r->out.error_string = NULL;
159                         talloc_free(tmp_ctx);
160                         return NT_STATUS_NO_MEMORY;
161                 }
162                 
163                 /* mark all the message elements (should be just one)
164                    as LDB_FLAG_MOD_REPLACE */
165                 for (i=0;i<msg->num_elements;i++) {
166                         msg->elements[i].flags = LDB_FLAG_MOD_REPLACE;
167                 }
168
169                 rtn = ldb_modify(remote_ldb, msg);
170                 if (rtn != 0) {
171                         libnet_r->out.error_string
172                                 = talloc_asprintf(libnet_r,
173                                                   "Failed to modify server entry %s: %s: %d",
174                                                   server_dn_str,
175                                                   ldb_errstring(remote_ldb), rtn);
176                         talloc_free(tmp_ctx);
177                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
178                 }
179         } else if (rtn != 0) {
180                 libnet_r->out.error_string
181                         = talloc_asprintf(libnet_r,
182                                 "Failed to add server entry %s: %s: %d",
183                                 server_dn_str,
184                                           ldb_errstring(remote_ldb), rtn);
185                 talloc_free(tmp_ctx);
186                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
187         }
188         DEBUG(0, ("We still need to perform a DsAddEntry() so that we can create the CN=NTDS Settings container.\n"));
189
190         /* Store the server DN in libnet_r */
191         libnet_r->out.server_dn_str = server_dn_str;
192         talloc_steal(libnet_r, server_dn_str);
193         
194         talloc_free(tmp_ctx);
195         return NT_STATUS_OK;
196 }
197
198 /*
199  * complete a domain join, when joining to a AD domain:
200  * 1.) connect and bind to the DRSUAPI pipe
201  * 2.) do a DsCrackNames() to find the machine account dn
202  * 3.) connect to LDAP
203  * 4.) do an ldap search to find the "msDS-KeyVersionNumber" of the machine account
204  * 5.) set the servicePrincipalName's of the machine account via LDAP, (maybe we should use DsWriteAccountSpn()...)
205  * 6.) do a DsCrackNames() to find the domain dn
206  * 7.) find out Site specific stuff, look at libnet_JoinSite() for details
207  */
208 static NTSTATUS libnet_JoinADSDomain(struct libnet_context *ctx, struct libnet_JoinDomain *r)
209 {
210         NTSTATUS status;
211
212         TALLOC_CTX *tmp_ctx;
213
214         const char *realm = r->out.realm;
215
216         struct dcerpc_binding *samr_binding = r->out.samr_binding;
217
218         struct dcerpc_pipe *drsuapi_pipe;
219         struct dcerpc_binding *drsuapi_binding;
220         struct drsuapi_DsBind r_drsuapi_bind;
221         struct drsuapi_DsCrackNames r_crack_names;
222         struct drsuapi_DsNameString names[1];
223         struct policy_handle drsuapi_bind_handle;
224         struct GUID drsuapi_bind_guid;
225
226         struct ldb_context *remote_ldb;
227         const struct ldb_dn *account_dn;
228         const char *account_dn_str;
229         const char *remote_ldb_url;
230         struct ldb_result *res;
231         struct ldb_message *msg;
232
233         int ret, rtn;
234
235         unsigned int kvno;
236         
237         const char * const attrs[] = {
238                 "msDS-KeyVersionNumber",
239                 "servicePrincipalName",
240                 "dNSHostName",
241                 NULL,
242         };
243
244         r->out.error_string = NULL;
245         
246         /* We need to convert between a samAccountName and domain to a
247          * DN in the directory.  The correct way to do this is with
248          * DRSUAPI CrackNames */
249
250         /* Fiddle with the bindings, so get to DRSUAPI on
251          * NCACN_IP_TCP, sealed */
252         tmp_ctx = talloc_named(r, 0, "libnet_JoinADSDomain temp context");  
253         if (!tmp_ctx) {
254                 r->out.error_string = NULL;
255                 return NT_STATUS_NO_MEMORY;
256         }
257                                                    
258         drsuapi_binding = talloc(tmp_ctx, struct dcerpc_binding);
259         if (!drsuapi_binding) {
260                 r->out.error_string = NULL;
261                 talloc_free(tmp_ctx);
262                 return NT_STATUS_NO_MEMORY;
263         }
264         
265         *drsuapi_binding = *samr_binding;
266
267         /* DRSUAPI is only available on IP_TCP, and locally on NCALRPC */
268         if (drsuapi_binding->transport != NCALRPC) {
269                 drsuapi_binding->transport = NCACN_IP_TCP;
270         }
271         drsuapi_binding->endpoint = NULL;
272         drsuapi_binding->flags |= DCERPC_SEAL;
273
274         status = dcerpc_pipe_connect_b(tmp_ctx, 
275                                        &drsuapi_pipe,
276                                        drsuapi_binding,
277                                        DCERPC_DRSUAPI_UUID,
278                                        DCERPC_DRSUAPI_VERSION, 
279                                        ctx->cred, 
280                                        ctx->event_ctx);
281         if (!NT_STATUS_IS_OK(status)) {
282                 r->out.error_string = talloc_asprintf(r,
283                                         "Connection to DRSUAPI pipe of PDC of domain '%s' failed: %s",
284                                         r->in.domain_name,
285                                         nt_errstr(status));
286                 talloc_free(tmp_ctx);
287                 return status;
288         }
289
290         /* get a DRSUAPI pipe handle */
291         GUID_from_string(DRSUAPI_DS_BIND_GUID, &drsuapi_bind_guid);
292
293         r_drsuapi_bind.in.bind_guid = &drsuapi_bind_guid;
294         r_drsuapi_bind.in.bind_info = NULL;
295         r_drsuapi_bind.out.bind_handle = &drsuapi_bind_handle;
296
297         status = dcerpc_drsuapi_DsBind(drsuapi_pipe, tmp_ctx, &r_drsuapi_bind);
298         if (!NT_STATUS_IS_OK(status)) {
299                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
300                         r->out.error_string
301                                 = talloc_asprintf(r,
302                                                   "dcerpc_drsuapi_DsBind for [%s\\%s] failed - %s\n", 
303                                                   r->in.domain_name, r->in.account_name, 
304                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
305                         talloc_free(tmp_ctx);
306                         return status;
307                 } else {
308                         r->out.error_string
309                                 = talloc_asprintf(r,
310                                                   "dcerpc_drsuapi_DsBind for [%s\\%s] failed - %s\n", 
311                                                   r->in.domain_name, r->in.account_name, 
312                                                   nt_errstr(status));
313                         talloc_free(tmp_ctx);
314                         return status;
315                 }
316         } else if (!W_ERROR_IS_OK(r_drsuapi_bind.out.result)) {
317                 r->out.error_string
318                                 = talloc_asprintf(r,
319                                                   "DsBind failed - %s\n", 
320                                                   win_errstr(r_drsuapi_bind.out.result));
321                         talloc_free(tmp_ctx);
322                 return NT_STATUS_UNSUCCESSFUL;
323         }
324
325         /* Actually 'crack' the names */
326         ZERO_STRUCT(r_crack_names);
327         r_crack_names.in.bind_handle            = &drsuapi_bind_handle;
328         r_crack_names.in.level                  = 1;
329         r_crack_names.in.req.req1.unknown1      = 0x000004e4;
330         r_crack_names.in.req.req1.unknown2      = 0x00000407;
331         r_crack_names.in.req.req1.count         = 1;
332         r_crack_names.in.req.req1.names         = names;
333         r_crack_names.in.req.req1.format_flags  = DRSUAPI_DS_NAME_FLAG_NO_FLAGS;
334         r_crack_names.in.req.req1.format_offered= DRSUAPI_DS_NAME_FORMAT_SID_OR_SID_HISTORY;
335         r_crack_names.in.req.req1.format_desired= DRSUAPI_DS_NAME_FORMAT_FQDN_1779;
336         names[0].str = dom_sid_string(tmp_ctx, r->out.account_sid);
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\n", 
349                                                   names[0].str,
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\n", 
357                                                   names[0].str,
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\n", 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\n");
374                 talloc_free(tmp_ctx);
375                 return NT_STATUS_UNSUCCESSFUL;
376         }
377
378         /* Store the DN of our machine account. */
379         account_dn_str = r_crack_names.out.ctr.ctr1->array[0].result_name;
380
381         account_dn = ldb_dn_explode(tmp_ctx, account_dn_str);
382         if (!account_dn) {
383                 r->out.error_string = talloc_asprintf(r, "Invalid account dn: %s",
384                                                       account_dn_str);
385                 talloc_free(tmp_ctx);
386                 return NT_STATUS_UNSUCCESSFUL;
387         }
388
389         /* Now we know the user's DN, open with LDAP, read and modify a few things */
390
391         remote_ldb_url = talloc_asprintf(tmp_ctx, "ldap://%s", 
392                                          drsuapi_binding->host);
393         if (!remote_ldb_url) {
394                 r->out.error_string = NULL;
395                 talloc_free(tmp_ctx);
396                 return NT_STATUS_NO_MEMORY;
397         }
398
399         remote_ldb = ldb_wrap_connect(tmp_ctx, remote_ldb_url, 
400                                       NULL, ctx->cred, 0, NULL);
401         if (!remote_ldb) {
402                 r->out.error_string = NULL;
403                 talloc_free(tmp_ctx);
404                 return NT_STATUS_UNSUCCESSFUL;
405         }
406
407         /* search for the user's record */
408         ret = ldb_search(remote_ldb, account_dn, LDB_SCOPE_BASE, 
409                              NULL, attrs, &res);
410         if (ret != LDB_SUCCESS || res->count != 1) {
411                 r->out.error_string = talloc_asprintf(r, "ldb_search for %s failed - %s\n",
412                                                       account_dn_str, ldb_errstring(remote_ldb));
413                 talloc_free(tmp_ctx);
414                 return NT_STATUS_UNSUCCESSFUL;
415         }
416
417         /* If we have a kvno recorded in AD, we need it locally as well */
418         kvno = ldb_msg_find_uint(res->msgs[0], "msDS-KeyVersionNumber", 0);
419
420         /* Prepare a new message, for the modify */
421         msg = ldb_msg_new(tmp_ctx);
422         if (!msg) {
423                 r->out.error_string = NULL;
424                 talloc_free(tmp_ctx);
425                 return NT_STATUS_NO_MEMORY;
426         }
427         msg->dn = res->msgs[0]->dn;
428
429         {
430                 int i;
431                 const char *service_principal_name[6];
432                 const char *dns_host_name = strlower_talloc(tmp_ctx, 
433                                                             talloc_asprintf(tmp_ctx, 
434                                                                             "%s.%s", 
435                                                                             r->in.netbios_name, 
436                                                                             realm));
437
438                 if (!dns_host_name) {
439                         r->out.error_string = NULL;
440                         talloc_free(tmp_ctx);
441                         return NT_STATUS_NO_MEMORY;
442                 }
443
444                 service_principal_name[0] = talloc_asprintf(tmp_ctx, "host/%s", dns_host_name);
445                 service_principal_name[1] = talloc_asprintf(tmp_ctx, "host/%s", strlower_talloc(tmp_ctx, r->in.netbios_name));
446                 service_principal_name[2] = talloc_asprintf(tmp_ctx, "host/%s/%s", dns_host_name, realm);
447                 service_principal_name[3] = talloc_asprintf(tmp_ctx, "host/%s/%s", strlower_talloc(tmp_ctx, r->in.netbios_name), realm);
448                 service_principal_name[4] = talloc_asprintf(tmp_ctx, "host/%s/%s", dns_host_name, r->out.domain_name);
449                 service_principal_name[5] = talloc_asprintf(tmp_ctx, "host/%s/%s", strlower_talloc(tmp_ctx, r->in.netbios_name), r->out.domain_name);
450                 
451                 for (i=0; i < ARRAY_SIZE(service_principal_name); i++) {
452                         if (!service_principal_name[i]) {
453                                 r->out.error_string = NULL;
454                                 talloc_free(tmp_ctx);
455                                 return NT_STATUS_NO_MEMORY;
456                         }
457                         rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "servicePrincipalName", service_principal_name[i]);
458                         if (rtn == -1) {
459                                 r->out.error_string = NULL;
460                                 talloc_free(tmp_ctx);
461                                 return NT_STATUS_NO_MEMORY;
462                         }
463                 }
464
465                 rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "dNSHostName", dns_host_name);
466                 if (rtn == -1) {
467                         r->out.error_string = NULL;
468                         talloc_free(tmp_ctx);
469                         return NT_STATUS_NO_MEMORY;
470                 }
471
472                 rtn = samdb_replace(remote_ldb, tmp_ctx, msg);
473                 if (rtn != 0) {
474                         r->out.error_string
475                                 = talloc_asprintf(r, 
476                                                   "Failed to replace entries on %s\n", 
477                                                   ldb_dn_linearize(tmp_ctx, msg->dn));
478                         talloc_free(tmp_ctx);
479                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
480                 }
481         }
482                                 
483         /* DsCrackNames to find out the DN of the domain. */
484         r_crack_names.in.req.req1.format_offered = DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT;
485         r_crack_names.in.req.req1.format_desired = DRSUAPI_DS_NAME_FORMAT_FQDN_1779;
486         names[0].str = talloc_asprintf(tmp_ctx, "%s\\", r->out.domain_name);
487         if (!names[0].str) {
488                 r->out.error_string = NULL;
489                 talloc_free(tmp_ctx);
490                 return NT_STATUS_NO_MEMORY;
491         }
492
493         status = dcerpc_drsuapi_DsCrackNames(drsuapi_pipe, tmp_ctx, &r_crack_names);
494         if (!NT_STATUS_IS_OK(status)) {
495                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
496                         r->out.error_string
497                                 = talloc_asprintf(r,
498                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s\n", 
499                                                   r->in.domain_name, 
500                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
501                         talloc_free(tmp_ctx);
502                         return status;
503                 } else {
504                         r->out.error_string
505                                 = talloc_asprintf(r,
506                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s\n", 
507                                                   r->in.domain_name, 
508                                                   nt_errstr(status));
509                         talloc_free(tmp_ctx);
510                         return status;
511                 }
512         } else if (!W_ERROR_IS_OK(r_crack_names.out.result)) {
513                 r->out.error_string
514                         = talloc_asprintf(r,
515                                           "DsCrackNames failed - %s\n", win_errstr(r_crack_names.out.result));
516                 talloc_free(tmp_ctx);
517                 return NT_STATUS_UNSUCCESSFUL;
518         } else if (r_crack_names.out.level != 1 
519                    || !r_crack_names.out.ctr.ctr1 
520                    || r_crack_names.out.ctr.ctr1->count != 1
521                    || !r_crack_names.out.ctr.ctr1->array[0].result_name           
522                    || r_crack_names.out.ctr.ctr1->array[0].status != DRSUAPI_DS_NAME_STATUS_OK) {
523                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed\n");
524                 talloc_free(tmp_ctx);
525                 return NT_STATUS_UNSUCCESSFUL;
526         }
527
528         /* Store the account DN. */
529         r->out.account_dn_str = account_dn_str;
530         talloc_steal(r, account_dn_str);
531
532         /* Store the domain DN. */
533         r->out.domain_dn_str = r_crack_names.out.ctr.ctr1->array[0].result_name;
534         talloc_steal(r, r_crack_names.out.ctr.ctr1->array[0].result_name);
535
536         r->out.kvno = kvno;
537
538         if (r->in.acct_type ==  ACB_SVRTRUST) {
539                 status = libnet_JoinSite(ctx,
540                                          drsuapi_pipe, drsuapi_bind_handle,
541                                          remote_ldb, r);
542         }
543         talloc_free(tmp_ctx);
544
545         return status;
546 }
547
548 /*
549  * do a domain join using DCERPC/SAMR calls
550  * 1. connect to the SAMR pipe of users domain PDC (maybe a standalone server or workstation)
551  *    is it correct to contact the the pdc of the domain of the user who's password should be set?
552  * 2. do a samr_Connect to get a policy handle
553  * 3. do a samr_LookupDomain to get the domain sid
554  * 4. do a samr_OpenDomain to get a domain handle
555  * 5. do a samr_CreateAccount to try and get a new account 
556  * 
557  * If that fails, do:
558  * 5.1. do a samr_LookupNames to get the users rid
559  * 5.2. do a samr_OpenUser to get a user handle
560  * 
561  * 6. call libnet_SetPassword_samr_handle to set the password
562  *
563  * 7. do a samrSetUserInfo to set the account flags
564  * 8. do some ADS specific things when we join as Domain Controller,
565  *    look at libnet_joinADSDomain() for the details
566  */
567 NTSTATUS libnet_JoinDomain(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_JoinDomain *r)
568 {
569         TALLOC_CTX *tmp_ctx;
570
571         NTSTATUS status, cu_status;
572         struct libnet_RpcConnect *c;
573         struct lsa_ObjectAttribute attr;
574         struct lsa_QosInfo qos;
575         struct lsa_OpenPolicy2 lsa_open_policy;
576         struct policy_handle lsa_p_handle;
577         struct lsa_QueryInfoPolicy2 lsa_query_info2;
578         struct lsa_QueryInfoPolicy lsa_query_info;
579
580         struct dcerpc_binding *samr_binding;
581         struct dcerpc_pipe *samr_pipe;
582         struct dcerpc_pipe *lsa_pipe;
583         struct samr_Connect sc;
584         struct policy_handle p_handle;
585         struct samr_OpenDomain od;
586         struct policy_handle d_handle;
587         struct samr_LookupNames ln;
588         struct samr_OpenUser ou;
589         struct samr_CreateUser2 cu;
590         struct policy_handle *u_handle = NULL;
591         struct samr_QueryUserInfo qui;
592         struct samr_SetUserInfo sui;
593         union samr_UserInfo u_info;
594         union libnet_SetPassword r2;
595         struct samr_GetUserPwInfo pwp;
596         struct lsa_String samr_account_name;
597         
598         uint32_t acct_flags;
599         uint32_t rid, access_granted;
600         int policy_min_pw_len = 0;
601
602         struct dom_sid *domain_sid = NULL;
603         struct dom_sid *account_sid = NULL;
604         const char *domain_name = NULL;
605         const char *password_str = NULL;
606         const char *realm = NULL; /* Also flag for remote being AD */
607         
608         
609         r->out.error_string = NULL;
610         r2.samr_handle.out.error_string = NULL;
611         
612         tmp_ctx = talloc_named(mem_ctx, 0, "libnet_Join temp context");
613         if (!tmp_ctx) {
614                 r->out.error_string = NULL;
615                 return NT_STATUS_NO_MEMORY;
616         }
617         
618         u_handle = talloc(tmp_ctx, struct policy_handle);
619         if (!u_handle) {
620                 r->out.error_string = NULL;
621                 talloc_free(tmp_ctx);
622                 return NT_STATUS_NO_MEMORY;
623         }
624         
625         samr_pipe = talloc(tmp_ctx, struct dcerpc_pipe);
626         if (!samr_pipe) {
627                 r->out.error_string = NULL;
628                 talloc_free(tmp_ctx);
629                 return NT_STATUS_NO_MEMORY;
630         }
631         
632         c = talloc(tmp_ctx, struct libnet_RpcConnect);
633         if (!c) {
634                 r->out.error_string = NULL;
635                 talloc_free(tmp_ctx);
636                 return NT_STATUS_NO_MEMORY;
637         }
638         
639         /* prepare connect to the LSA pipe of PDC */
640         if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
641                 c->level             = LIBNET_RPC_CONNECT_PDC;
642                 c->in.domain_name    = r->in.domain_name;
643         } else {
644                 c->level             = LIBNET_RPC_CONNECT_BINDING;
645                 c->in.binding        = r->in.binding;
646         }
647         c->in.dcerpc_iface_name      = DCERPC_LSARPC_NAME;
648         c->in.dcerpc_iface_uuid      = DCERPC_LSARPC_UUID;
649         c->in.dcerpc_iface_version   = DCERPC_LSARPC_VERSION;
650         
651         /* connect to the LSA pipe of the PDC */
652
653         status = libnet_RpcConnect(ctx, c, c);
654         if (!NT_STATUS_IS_OK(status)) {
655                 if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
656                         r->out.error_string = talloc_asprintf(mem_ctx,
657                                                               "Connection to LSA pipe of PDC of domain '%s' failed: %s",
658                                                               r->in.domain_name, nt_errstr(status));
659                 } else {
660                         r->out.error_string = talloc_asprintf(mem_ctx,
661                                                               "Connection to LSA pipe with binding '%s' failed: %s",
662                                                               r->in.binding, nt_errstr(status));
663                 }
664                 talloc_free(tmp_ctx);
665                 return status;
666         }                       
667         lsa_pipe = c->out.dcerpc_pipe;
668         
669         /* Get an LSA policy handle */
670
671         ZERO_STRUCT(lsa_p_handle);
672         qos.len = 0;
673         qos.impersonation_level = 2;
674         qos.context_mode = 1;
675         qos.effective_only = 0;
676
677         attr.len = 0;
678         attr.root_dir = NULL;
679         attr.object_name = NULL;
680         attr.attributes = 0;
681         attr.sec_desc = NULL;
682         attr.sec_qos = &qos;
683
684         lsa_open_policy.in.attr = &attr;
685         
686         lsa_open_policy.in.system_name = talloc_asprintf(tmp_ctx, "\\"); 
687         if (!lsa_open_policy.in.system_name) {
688                 r->out.error_string = NULL;
689                 talloc_free(tmp_ctx);
690                 return NT_STATUS_NO_MEMORY;
691         }
692
693         lsa_open_policy.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
694         lsa_open_policy.out.handle = &lsa_p_handle;
695
696         status = dcerpc_lsa_OpenPolicy2(lsa_pipe, tmp_ctx, &lsa_open_policy); 
697
698         /* This now fails on ncacn_ip_tcp against Win2k3 SP1 */
699         if (NT_STATUS_IS_OK(status)) {
700                 /* Look to see if this is ADS (a fault indicates NT4 or Samba 3.0) */
701                 
702                 lsa_query_info2.in.handle = &lsa_p_handle;
703                 lsa_query_info2.in.level = LSA_POLICY_INFO_DNS;
704                 
705                 status = dcerpc_lsa_QueryInfoPolicy2(lsa_pipe, tmp_ctx,                 
706                                                      &lsa_query_info2);
707                 
708                 if (!NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
709                         if (!NT_STATUS_IS_OK(status)) {
710                                 r->out.error_string = talloc_asprintf(mem_ctx,
711                                                                       "lsa_QueryInfoPolicy2 failed: %s",
712                                                                       nt_errstr(status));
713                                 talloc_free(tmp_ctx);
714                                 return status;
715                         }
716                         realm = lsa_query_info2.out.info->dns.dns_domain.string;
717                 }
718                 
719                 /* Grab the domain SID (regardless of the result of the previous call */
720                 
721                 lsa_query_info.in.handle = &lsa_p_handle;
722                 lsa_query_info.in.level = LSA_POLICY_INFO_DOMAIN;
723                 
724                 status = dcerpc_lsa_QueryInfoPolicy(lsa_pipe, tmp_ctx, 
725                                                     &lsa_query_info);
726                 
727                 if (!NT_STATUS_IS_OK(status)) {
728                         r->out.error_string = talloc_asprintf(mem_ctx,
729                                                               "lsa_QueryInfoPolicy2 failed: %s",
730                                                               nt_errstr(status));
731                         talloc_free(tmp_ctx);
732                         return status;
733                 }
734                 
735                 domain_sid = lsa_query_info.out.info->domain.sid;
736                 domain_name = lsa_query_info.out.info->domain.name.string;
737         } else {
738                 /* Cause the code further down to try this with just SAMR */
739                 domain_sid = NULL;
740                 if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
741                         domain_name = talloc_strdup(tmp_ctx, r->in.domain_name);
742                 } else {
743                         /* Bugger, we just lost our way to automaticly find the domain name */
744                         domain_name = talloc_strdup(tmp_ctx, lp_workgroup());
745                 }
746         }
747
748         DEBUG(0, ("Joining domain %s\n", domain_name));
749
750         /*
751           establish a SAMR connection, on the same CIFS transport
752         */
753
754         /* Find the original binding string */
755         status = dcerpc_parse_binding(tmp_ctx, lsa_pipe->conn->binding_string, &samr_binding);  
756         if (!NT_STATUS_IS_OK(status)) {
757                 r->out.error_string = talloc_asprintf(mem_ctx,
758                                                 "Failed to parse lsa binding '%s'",
759                                                 lsa_pipe->conn->binding_string);
760                 talloc_free(tmp_ctx);
761                 return status;
762         }
763
764         /* Make binding string for samr, not the other pipe */
765         status = dcerpc_epm_map_binding(tmp_ctx, samr_binding,                                  
766                                         DCERPC_SAMR_UUID, DCERPC_SAMR_VERSION,
767                                         lsa_pipe->conn->event_ctx);
768         if (!NT_STATUS_IS_OK(status)) {
769                 r->out.error_string = talloc_asprintf(mem_ctx,
770                                                 "Failed to map DCERPC/TCP NCACN_NP pipe for '%s' - %s",
771                                                 DCERPC_NETLOGON_UUID,
772                                                 nt_errstr(status));
773                 talloc_free(tmp_ctx);
774                 return status;
775         }
776
777         /* Setup a SAMR connection */
778         status = dcerpc_secondary_connection(lsa_pipe, &samr_pipe, samr_binding);
779         if (!NT_STATUS_IS_OK(status)) {
780                 r->out.error_string = talloc_asprintf(mem_ctx,
781                                                 "SAMR secondary connection failed: %s",
782                                                 nt_errstr(status));
783                 talloc_free(tmp_ctx);
784                 return status;
785         }
786
787         status = dcerpc_pipe_auth(samr_pipe, samr_binding, DCERPC_SAMR_UUID, 
788                                   DCERPC_SAMR_VERSION, ctx->cred);
789         if (!NT_STATUS_IS_OK(status)) {
790                 r->out.error_string = talloc_asprintf(mem_ctx,
791                                                 "SAMR bind failed: %s",
792                                                 nt_errstr(status));
793                 talloc_free(tmp_ctx);
794                 return status;
795         }
796
797         /* prepare samr_Connect */
798         ZERO_STRUCT(p_handle);
799         sc.in.system_name = NULL;
800         sc.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
801         sc.out.connect_handle = &p_handle;
802
803         /* 2. do a samr_Connect to get a policy handle */
804         status = dcerpc_samr_Connect(samr_pipe, tmp_ctx, &sc);
805         if (!NT_STATUS_IS_OK(status)) {
806                 r->out.error_string = talloc_asprintf(mem_ctx,
807                                                 "samr_Connect failed: %s",
808                                                 nt_errstr(status));
809                 talloc_free(tmp_ctx);
810                 return status;
811         }
812
813         /* Perhaps we didn't get a SID above, because we are against ncacn_ip_tcp */
814         if (!domain_sid) {
815                 struct lsa_String name;
816                 struct samr_LookupDomain l;
817                 name.string = domain_name;
818                 l.in.connect_handle = &p_handle;
819                 l.in.domain_name = &name;
820                 
821                 status = dcerpc_samr_LookupDomain(samr_pipe, tmp_ctx, &l);
822                 if (!NT_STATUS_IS_OK(status)) {
823                         r->out.error_string = talloc_asprintf(mem_ctx,
824                                                               "SAMR LookupDomain failed: %s",
825                                                               nt_errstr(status));
826                         talloc_free(tmp_ctx);
827                         return status;
828                 }
829                 domain_sid = l.out.sid;
830         }
831
832         /* prepare samr_OpenDomain */
833         ZERO_STRUCT(d_handle);
834         od.in.connect_handle = &p_handle;
835         od.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
836         od.in.sid = domain_sid;
837         od.out.domain_handle = &d_handle;
838
839         /* 4. do a samr_OpenDomain to get a domain handle */
840         status = dcerpc_samr_OpenDomain(samr_pipe, tmp_ctx, &od);                       
841         if (!NT_STATUS_IS_OK(status)) {
842                 r->out.error_string = talloc_asprintf(mem_ctx,
843                                         "samr_OpenDomain for [%s] failed: %s",
844                                         r->in.domain_name,
845                                         nt_errstr(status));
846                 talloc_free(tmp_ctx);
847                 return status;
848         }
849         
850         /* prepare samr_CreateUser2 */
851         ZERO_STRUCTP(u_handle);
852         cu.in.domain_handle  = &d_handle;
853         cu.in.access_mask     = SEC_FLAG_MAXIMUM_ALLOWED;
854         samr_account_name.string = r->in.account_name;
855         cu.in.account_name    = &samr_account_name;
856         cu.in.acct_flags      = r->in.acct_type;
857         cu.out.user_handle    = u_handle;
858         cu.out.rid            = &rid;
859         cu.out.access_granted = &access_granted;
860
861         /* 4. do a samr_CreateUser2 to get an account handle, or an error */
862         cu_status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                   
863         status = cu_status;
864         if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
865                         r->out.error_string = talloc_asprintf(mem_ctx,
866                                                                 "samr_CreateUser2 for [%s] failed: %s\n",
867                                                                 r->in.domain_name, nt_errstr(status));
868                         talloc_free(tmp_ctx);
869                         return status;
870
871         } else if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
872                 /* prepare samr_LookupNames */
873                 ln.in.domain_handle = &d_handle;
874                 ln.in.num_names = 1;
875                 ln.in.names = talloc_array(tmp_ctx, struct lsa_String, 1);
876                 if (!ln.in.names) {
877                         r->out.error_string = NULL;
878                         talloc_free(tmp_ctx);
879                         return NT_STATUS_NO_MEMORY;
880                 }
881                 ln.in.names[0].string = r->in.account_name;
882                 
883                 /* 5. do a samr_LookupNames to get the users rid */
884                 status = dcerpc_samr_LookupNames(samr_pipe, tmp_ctx, &ln);
885                 if (!NT_STATUS_IS_OK(status)) {
886                         r->out.error_string = talloc_asprintf(mem_ctx,
887                                                 "samr_LookupNames for [%s] failed: %s",
888                                                 r->in.account_name,
889                                                 nt_errstr(status));
890                         talloc_free(tmp_ctx);
891                         return status;
892                 }
893                 
894                 /* check if we got one RID for the user */
895                 if (ln.out.rids.count != 1) {
896                         r->out.error_string = talloc_asprintf(mem_ctx,
897                                                               "samr_LookupNames for [%s] returns %d RIDs\n",
898                                                               r->in.account_name, ln.out.rids.count);
899                         talloc_free(tmp_ctx);
900                         return NT_STATUS_INVALID_PARAMETER;
901                 }
902                 
903                 /* prepare samr_OpenUser */
904                 ZERO_STRUCTP(u_handle);
905                 ou.in.domain_handle = &d_handle;
906                 ou.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
907                 ou.in.rid = ln.out.rids.ids[0];
908                 rid = ou.in.rid;
909                 ou.out.user_handle = u_handle;
910                 
911                 /* 6. do a samr_OpenUser to get a user handle */
912                 status = dcerpc_samr_OpenUser(samr_pipe, tmp_ctx, &ou); 
913                 if (!NT_STATUS_IS_OK(status)) {
914                         r->out.error_string = talloc_asprintf(mem_ctx,
915                                                         "samr_OpenUser for [%s] failed: %s",
916                                                         r->in.account_name,
917                                                         nt_errstr(status));
918                         talloc_free(tmp_ctx);
919                         return status;
920                 }
921
922                 if (r->in.recreate_account) {
923                         struct samr_DeleteUser d;
924                         d.in.user_handle = u_handle;
925                         d.out.user_handle = u_handle;
926                         status = dcerpc_samr_DeleteUser(samr_pipe, mem_ctx, &d);
927                         if (!NT_STATUS_IS_OK(status)) {
928                                 r->out.error_string = talloc_asprintf(mem_ctx,
929                                                                       "samr_DeleteUser (for recreate) of [%s] failed: %s",
930                                                                       r->in.account_name,
931                                                                       nt_errstr(status));
932                                 talloc_free(tmp_ctx);
933                                 return status;
934                         }
935
936                         /* We want to recreate, so delete and another samr_CreateUser2 */
937                         
938                         /* &cu filled in above */
939                         cu_status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                   
940                         status = cu_status;
941                         if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
942                                 r->out.error_string = talloc_asprintf(mem_ctx,
943                                                                       "samr_CreateUser2 (recreate) for [%s] failed: %s\n",
944                                                                       r->in.domain_name, nt_errstr(status));
945                                 talloc_free(tmp_ctx);
946                                 return status;
947                         }
948                         DEBUG(0, ("Recreated account in domain %s\n", domain_name));
949
950                 }
951         }
952         /* Find out what password policy this user has */
953         pwp.in.user_handle = u_handle;
954
955         status = dcerpc_samr_GetUserPwInfo(samr_pipe, tmp_ctx, &pwp);                           
956         if (NT_STATUS_IS_OK(status)) {
957                 policy_min_pw_len = pwp.out.info.min_password_length;
958         }
959         
960         /* Grab a password of that minimum length */
961         
962         password_str = generate_random_str(tmp_ctx, MAX(8, policy_min_pw_len)); 
963
964         r2.samr_handle.level            = LIBNET_SET_PASSWORD_SAMR_HANDLE;
965         r2.samr_handle.in.account_name  = r->in.account_name;
966         r2.samr_handle.in.newpassword   = password_str;
967         r2.samr_handle.in.user_handle   = u_handle;
968         r2.samr_handle.in.dcerpc_pipe   = samr_pipe;
969
970         status = libnet_SetPassword(ctx, tmp_ctx, &r2); 
971         if (!NT_STATUS_IS_OK(status)) {
972                 r->out.error_string = talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
973                 talloc_free(tmp_ctx);
974                 return status;
975         }
976
977         /* prepare samr_QueryUserInfo (get flags) */
978         qui.in.user_handle = u_handle;
979         qui.in.level = 16;
980         
981         status = dcerpc_samr_QueryUserInfo(samr_pipe, tmp_ctx, &qui);
982         if (!NT_STATUS_IS_OK(status)) {
983                 r->out.error_string = talloc_asprintf(mem_ctx,
984                                                 "samr_QueryUserInfo for [%s] failed: %s",
985                                                 r->in.account_name,
986                                                 nt_errstr(status));
987                 talloc_free(tmp_ctx);
988                 return status;
989         }
990         
991         if (!qui.out.info) {
992                 status = NT_STATUS_INVALID_PARAMETER;
993                 r->out.error_string
994                         = talloc_asprintf(mem_ctx,
995                                           "samr_QueryUserInfo failed to return qui.out.info for [%s]: %s\n",
996                                           r->in.account_name, nt_errstr(status));
997                 talloc_free(tmp_ctx);
998                 return status;
999         }
1000
1001         /* Possibly change account type (if we are creating a new account) */
1002         if (((qui.out.info->info16.acct_flags & (ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST)) 
1003             != r->in.acct_type) && (!NT_STATUS_EQUAL(cu_status, NT_STATUS_USER_EXISTS))) {
1004                 acct_flags = (qui.out.info->info16.acct_flags & ~(ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST))
1005                               | r->in.acct_type;
1006         } else {
1007                 acct_flags = qui.out.info->info16.acct_flags;
1008         }
1009         
1010         acct_flags = (acct_flags & ~ACB_DISABLED);
1011
1012         /* reset flags (if required) */
1013         if (acct_flags != qui.out.info->info16.acct_flags) {    
1014                 ZERO_STRUCT(u_info);
1015                 u_info.info16.acct_flags = acct_flags;
1016
1017                 sui.in.user_handle = u_handle;
1018                 sui.in.info = &u_info;
1019                 sui.in.level = 16;
1020                 
1021                 dcerpc_samr_SetUserInfo(samr_pipe, tmp_ctx, &sui);
1022                 if (!NT_STATUS_IS_OK(status)) {
1023                         r->out.error_string = talloc_asprintf(mem_ctx,
1024                                                         "samr_SetUserInfo for [%s] failed to remove ACB_DISABLED flag: %s",
1025                                                         r->in.account_name,
1026                                                         nt_errstr(status));
1027                         talloc_free(tmp_ctx);
1028                         return status;
1029                 }
1030         }
1031
1032         account_sid = dom_sid_add_rid(mem_ctx, domain_sid, rid);
1033         if (!account_sid) {
1034                 r->out.error_string = NULL;
1035                 talloc_free(tmp_ctx);
1036                 return NT_STATUS_NO_MEMORY;
1037         }
1038
1039         r->out.join_password = password_str;
1040         talloc_steal(mem_ctx, password_str);
1041
1042         r->out.domain_sid = domain_sid;
1043         talloc_steal(mem_ctx, domain_sid);
1044
1045         r->out.account_sid = account_sid;
1046         talloc_steal(mem_ctx, account_sid);
1047
1048         r->out.domain_name = domain_name;
1049         talloc_steal(mem_ctx, domain_name);
1050         r->out.realm = realm;
1051         talloc_steal(mem_ctx, realm);
1052         r->out.lsa_pipe = lsa_pipe;
1053         talloc_steal(mem_ctx, lsa_pipe);
1054         r->out.samr_pipe = samr_pipe;
1055         talloc_steal(mem_ctx, samr_pipe);
1056         r->out.samr_binding = samr_binding;
1057         talloc_steal(mem_ctx, samr_binding);
1058         r->out.user_handle = u_handle;
1059         talloc_steal(mem_ctx, u_handle);
1060         r->out.error_string = r2.samr_handle.out.error_string;
1061         talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
1062         r->out.kvno = 0;
1063         r->out.server_dn_str = NULL;
1064         talloc_free(tmp_ctx); 
1065
1066         /* Now, if it was AD, then we want to start looking changing a
1067          * few more things.  Otherwise, we are done. */
1068         if (realm) {
1069                 status = libnet_JoinADSDomain(ctx, r);
1070                 return status;
1071         }
1072
1073         return status;
1074 }
1075
1076 static NTSTATUS libnet_Join_primary_domain(struct libnet_context *ctx, 
1077                                            TALLOC_CTX *mem_ctx, 
1078                                            struct libnet_Join *r)
1079 {
1080         NTSTATUS status;
1081         TALLOC_CTX *tmp_mem;
1082         struct libnet_JoinDomain *r2;
1083         int ret, rtn;
1084         struct ldb_context *ldb;
1085         const struct ldb_dn *base_dn;
1086         struct ldb_message **msgs, *msg;
1087         const char *sct;
1088         const char * const attrs[] = {
1089                 "whenChanged",
1090                 "secret",
1091                 "priorSecret",
1092                 "priorChanged",
1093                 NULL
1094         };
1095         uint32_t acct_type = 0;
1096         const char *account_name;
1097         const char *netbios_name;
1098         char *filter;
1099         
1100         r->out.error_string = NULL;
1101
1102         tmp_mem = talloc_new(mem_ctx);
1103         if (!tmp_mem) {
1104                 return NT_STATUS_NO_MEMORY;
1105         }
1106
1107         r2 = talloc(tmp_mem, struct libnet_JoinDomain);
1108         if (!r2) {
1109                 r->out.error_string = NULL;
1110                 talloc_free(tmp_mem);
1111                 return NT_STATUS_NO_MEMORY;
1112         }
1113         
1114         if (r->in.secure_channel_type == SEC_CHAN_BDC) {
1115                 acct_type = ACB_SVRTRUST;
1116         } else if (r->in.secure_channel_type == SEC_CHAN_WKSTA) {
1117                 acct_type = ACB_WSTRUST;
1118         } else {
1119                 r->out.error_string = NULL;
1120                 talloc_free(tmp_mem);   
1121                 return NT_STATUS_INVALID_PARAMETER;
1122         }
1123
1124         if ((r->in.netbios_name != NULL) && (r->in.level != LIBNET_JOIN_AUTOMATIC)) {
1125                 netbios_name = r->in.netbios_name;
1126         } else {
1127                 netbios_name = talloc_asprintf(tmp_mem, "%s", lp_netbios_name());
1128                 if (!netbios_name) {
1129                         r->out.error_string = NULL;
1130                         talloc_free(tmp_mem);
1131                         return NT_STATUS_NO_MEMORY;
1132                 }
1133         }
1134
1135         account_name = talloc_asprintf(tmp_mem, "%s$", netbios_name);
1136         if (!account_name) {
1137                 r->out.error_string = NULL;
1138                 talloc_free(tmp_mem);
1139                 return NT_STATUS_NO_MEMORY;
1140         }
1141         
1142         /*
1143          * Local secrets are stored in secrets.ldb 
1144          * open it to make sure we can write the info into it after the join
1145          */
1146         ldb = secrets_db_connect(tmp_mem);
1147         if (!ldb) {
1148                 r->out.error_string
1149                         = talloc_asprintf(mem_ctx, 
1150                                           "Could not open secrets database\n");
1151                 talloc_free(tmp_mem);
1152                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1153         }
1154
1155         /*
1156          * join the domain
1157          */
1158         ZERO_STRUCTP(r2);
1159         r2->in.domain_name      = r->in.domain_name;
1160         r2->in.account_name     = account_name;
1161         r2->in.netbios_name     = netbios_name;
1162         r2->in.level            = LIBNET_JOINDOMAIN_AUTOMATIC;
1163         r2->in.acct_type        = acct_type;
1164         r2->in.recreate_account = False;
1165         status = libnet_JoinDomain(ctx, r2, r2);
1166         if (!NT_STATUS_IS_OK(status)) {
1167                 r->out.error_string = talloc_steal(mem_ctx, r2->out.error_string);
1168                 talloc_free(tmp_mem);
1169                 return status;
1170         }
1171         
1172         /*
1173          * now prepare the record for secrets.ldb
1174          */
1175         sct = talloc_asprintf(tmp_mem, "%d", r->in.secure_channel_type); 
1176         if (!sct) {
1177                 r->out.error_string = NULL;
1178                 talloc_free(tmp_mem);
1179                 return NT_STATUS_NO_MEMORY;
1180         }
1181         
1182         msg = ldb_msg_new(tmp_mem);
1183         if (!msg) {
1184                 r->out.error_string = NULL;
1185                 talloc_free(tmp_mem);
1186                 return NT_STATUS_NO_MEMORY;
1187         }
1188
1189         base_dn = ldb_dn_explode(tmp_mem, "cn=Primary Domains");
1190         if (!base_dn) {
1191                 r->out.error_string = NULL;
1192                 talloc_free(tmp_mem);
1193                 return NT_STATUS_NO_MEMORY;
1194         }
1195
1196         msg->dn = ldb_dn_build_child(tmp_mem, "flatname", r2->out.domain_name, base_dn);
1197         if (!msg->dn) {
1198                 r->out.error_string = NULL;
1199                 talloc_free(tmp_mem);
1200                 return NT_STATUS_NO_MEMORY;
1201         }
1202         
1203         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "flatname", r2->out.domain_name);
1204         if (rtn == -1) {
1205                 r->out.error_string = NULL;
1206                 talloc_free(tmp_mem);
1207                 return NT_STATUS_NO_MEMORY;
1208         }
1209
1210         if (r2->out.realm) {
1211                 rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "realm", r2->out.realm);
1212                 if (rtn == -1) {
1213                         r->out.error_string = NULL;
1214                         talloc_free(tmp_mem);
1215                         return NT_STATUS_NO_MEMORY;
1216                 }
1217
1218                 rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "objectClass", "primaryDomain");
1219                 if (rtn == -1) {
1220                         r->out.error_string = NULL;
1221                         talloc_free(tmp_mem);
1222                         return NT_STATUS_NO_MEMORY;
1223                 }
1224         }
1225
1226         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "objectClass", "primaryDomain");
1227         if (rtn == -1) {
1228                 r->out.error_string = NULL;
1229                 talloc_free(tmp_mem);
1230                 return NT_STATUS_NO_MEMORY;
1231         }
1232
1233         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secret", r2->out.join_password);
1234         if (rtn == -1) {
1235                 r->out.error_string = NULL;
1236                 talloc_free(tmp_mem);
1237                 return NT_STATUS_NO_MEMORY;
1238         }
1239
1240         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "samAccountName", r2->in.account_name);
1241         if (rtn == -1) {
1242                 r->out.error_string = NULL;
1243                 talloc_free(tmp_mem);
1244                 return NT_STATUS_NO_MEMORY;
1245         }
1246
1247         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secureChannelType", sct);
1248         if (rtn == -1) {
1249                 r->out.error_string = NULL;
1250                 talloc_free(tmp_mem);
1251                 return NT_STATUS_NO_MEMORY;
1252         }
1253
1254         if (r2->out.kvno) {
1255                 rtn = samdb_msg_add_uint(ldb, tmp_mem, msg, "msDS-KeyVersionNumber",
1256                                          r2->out.kvno);
1257                 if (rtn == -1) {
1258                         r->out.error_string = NULL;
1259                         talloc_free(tmp_mem);
1260                         return NT_STATUS_NO_MEMORY;
1261                 }
1262         }
1263
1264         if (r2->out.domain_sid) {
1265                 rtn = samdb_msg_add_dom_sid(ldb, tmp_mem, msg, "objectSid",
1266                                             r2->out.domain_sid);
1267                 if (rtn == -1) {
1268                         r->out.error_string = NULL;
1269                         talloc_free(tmp_mem);
1270                         return NT_STATUS_NO_MEMORY;
1271                 }
1272         }
1273
1274         /* 
1275          * search for the secret record
1276          * - remove the records we find
1277          * - and fetch the old secret and store it under priorSecret
1278          */
1279         ret = gendb_search(ldb,
1280                            tmp_mem, base_dn,
1281                            &msgs, attrs,
1282                            "(|" SECRETS_PRIMARY_DOMAIN_FILTER "(realm=%s))",
1283                            r2->out.domain_name, r2->out.realm);
1284         if (ret == 0) {
1285         } else if (ret == -1) {
1286                 r->out.error_string
1287                         = talloc_asprintf(mem_ctx, 
1288                                           "Search for domain: %s and realm: %s failed: %s", 
1289                                           r2->out.domain_name, r2->out.realm, ldb_errstring(ldb));
1290                 talloc_free(tmp_mem);
1291                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1292         } else {
1293                 const struct ldb_val *prior_secret;
1294                 const struct ldb_val *prior_modified_time;
1295                 int i;
1296
1297                 for (i = 0; i < ret; i++) {
1298                         ldb_delete(ldb, msgs[i]->dn);
1299                 }
1300
1301                 prior_secret = ldb_msg_find_ldb_val(msgs[0], "secret");
1302                 if (prior_secret) {
1303                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorSecret", prior_secret);
1304                         if (rtn == -1) {
1305                                 r->out.error_string = NULL;
1306                                 talloc_free(tmp_mem);
1307                                 return NT_STATUS_NO_MEMORY;
1308                         }
1309                 }
1310                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secret", r2->out.join_password);
1311                 if (rtn == -1) {
1312                         r->out.error_string = NULL;
1313                         talloc_free(tmp_mem);
1314                         return NT_STATUS_NO_MEMORY;
1315                 }
1316
1317                 prior_modified_time = ldb_msg_find_ldb_val(msgs[0], 
1318                                                            "whenChanged");
1319                 if (prior_modified_time) {
1320                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorWhenChanged", 
1321                                                   prior_modified_time);
1322                         if (rtn == -1) {
1323                                 r->out.error_string = NULL;
1324                                 talloc_free(tmp_mem);
1325                                 return NT_STATUS_NO_MEMORY;
1326                         }
1327                 }
1328
1329                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "samAccountName", r2->in.account_name);
1330                 if (rtn == -1) {
1331                         r->out.error_string = NULL;
1332                         talloc_free(tmp_mem);
1333                         return NT_STATUS_NO_MEMORY;
1334                 }
1335
1336                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secureChannelType", sct);
1337                 if (rtn == -1) {
1338                         r->out.error_string = NULL;
1339                         talloc_free(tmp_mem);
1340                         return NT_STATUS_NO_MEMORY;
1341                 }
1342         }
1343
1344         /* create the secret */
1345         ret = samdb_add(ldb, tmp_mem, msg);
1346         if (ret != 0) {
1347                 r->out.error_string = talloc_asprintf(mem_ctx, "Failed to create secret record %s\n", 
1348                                                       ldb_dn_linearize(ldb, msg->dn));
1349                 talloc_free(tmp_mem);
1350                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1351         }
1352
1353         if (r2->out.realm) {
1354                 struct cli_credentials *creds;
1355                 /* Make a credentials structure from it */
1356                 creds = cli_credentials_init(mem_ctx);
1357                 if (!creds) {
1358                         r->out.error_string = NULL;
1359                         talloc_free(tmp_mem);
1360                         return NT_STATUS_NO_MEMORY;
1361                 }
1362                 cli_credentials_set_conf(creds);
1363                 filter = talloc_asprintf(mem_ctx, "dn=%s", ldb_dn_linearize(mem_ctx, msg->dn));
1364                 status = cli_credentials_set_secrets(creds, NULL, filter);
1365                 if (!NT_STATUS_IS_OK(status)) {
1366                         r->out.error_string = talloc_asprintf(mem_ctx, "Failed to read secrets for keytab update for %s\n", 
1367                                                               filter);
1368                         talloc_free(tmp_mem);
1369                         return status;
1370                 } 
1371                 ret = cli_credentials_update_keytab(creds);
1372                 if (ret != 0) {
1373                         r->out.error_string = talloc_asprintf(mem_ctx, "Failed to update keytab for %s\n", 
1374                                                               filter);
1375                         talloc_free(tmp_mem);
1376                         return NT_STATUS_UNSUCCESSFUL;
1377                 }
1378         }
1379
1380         /* move all out parameter to the callers TALLOC_CTX */
1381         r->out.error_string     = NULL;
1382         r->out.join_password    = r2->out.join_password;
1383         talloc_steal(mem_ctx, r2->out.join_password);
1384         r->out.domain_sid       = r2->out.domain_sid;
1385         talloc_steal(mem_ctx, r2->out.domain_sid);
1386         talloc_free(tmp_mem);
1387         return NT_STATUS_OK;
1388 }
1389
1390 NTSTATUS libnet_Join(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_Join *r)
1391 {
1392         switch (r->in.secure_channel_type) {
1393                 case SEC_CHAN_WKSTA:
1394                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1395                 case SEC_CHAN_BDC:
1396                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1397                 case SEC_CHAN_DOMAIN:
1398                         break;
1399         }
1400
1401         r->out.error_string = talloc_asprintf(mem_ctx,
1402                                 "Invalid secure channel type specified (%08X) attempting to join domain %s",
1403                                 r->in.secure_channel_type, r->in.domain_name);
1404         return NT_STATUS_INVALID_PARAMETER;
1405 }
1406
1407