r11995: A big kerberos-related update.
[ira/wip.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, 0, NULL);
400         if (!remote_ldb) {
401                 r->out.error_string = NULL;
402                 talloc_free(tmp_ctx);
403                 return NT_STATUS_UNSUCCESSFUL;
404         }
405
406         /* search for the user's record */
407         ret = ldb_search(remote_ldb, account_dn, LDB_SCOPE_BASE, 
408                              NULL, attrs, &res);
409         if (ret != LDB_SUCCESS || res->count != 1) {
410                 r->out.error_string = talloc_asprintf(r, "ldb_search for %s failed - %s\n",
411                                                       account_dn_str, ldb_errstring(remote_ldb));
412                 talloc_free(tmp_ctx);
413                 return NT_STATUS_UNSUCCESSFUL;
414         }
415
416         /* If we have a kvno recorded in AD, we need it locally as well */
417         kvno = ldb_msg_find_uint(res->msgs[0], "msDS-KeyVersionNumber", 0);
418
419         /* Prepare a new message, for the modify */
420         msg = ldb_msg_new(tmp_ctx);
421         if (!msg) {
422                 r->out.error_string = NULL;
423                 talloc_free(tmp_ctx);
424                 return NT_STATUS_NO_MEMORY;
425         }
426         msg->dn = res->msgs[0]->dn;
427
428         {
429                 int i;
430                 const char *service_principal_name[6];
431                 const char *dns_host_name = strlower_talloc(tmp_ctx, 
432                                                             talloc_asprintf(tmp_ctx, 
433                                                                             "%s.%s", 
434                                                                             r->in.netbios_name, 
435                                                                             realm));
436
437                 if (!dns_host_name) {
438                         r->out.error_string = NULL;
439                         talloc_free(tmp_ctx);
440                         return NT_STATUS_NO_MEMORY;
441                 }
442
443                 service_principal_name[0] = talloc_asprintf(tmp_ctx, "host/%s", dns_host_name);
444                 service_principal_name[1] = talloc_asprintf(tmp_ctx, "host/%s", strlower_talloc(tmp_ctx, r->in.netbios_name));
445                 service_principal_name[2] = talloc_asprintf(tmp_ctx, "host/%s/%s", dns_host_name, realm);
446                 service_principal_name[3] = talloc_asprintf(tmp_ctx, "host/%s/%s", strlower_talloc(tmp_ctx, r->in.netbios_name), realm);
447                 service_principal_name[4] = talloc_asprintf(tmp_ctx, "host/%s/%s", dns_host_name, r->out.domain_name);
448                 service_principal_name[5] = talloc_asprintf(tmp_ctx, "host/%s/%s", strlower_talloc(tmp_ctx, r->in.netbios_name), r->out.domain_name);
449                 
450                 for (i=0; i < ARRAY_SIZE(service_principal_name); i++) {
451                         if (!service_principal_name[i]) {
452                                 r->out.error_string = NULL;
453                                 talloc_free(tmp_ctx);
454                                 return NT_STATUS_NO_MEMORY;
455                         }
456                         rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "servicePrincipalName", service_principal_name[i]);
457                         if (rtn == -1) {
458                                 r->out.error_string = NULL;
459                                 talloc_free(tmp_ctx);
460                                 return NT_STATUS_NO_MEMORY;
461                         }
462                 }
463
464                 rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "dNSHostName", dns_host_name);
465                 if (rtn == -1) {
466                         r->out.error_string = NULL;
467                         talloc_free(tmp_ctx);
468                         return NT_STATUS_NO_MEMORY;
469                 }
470
471                 rtn = samdb_replace(remote_ldb, tmp_ctx, msg);
472                 if (rtn != 0) {
473                         r->out.error_string
474                                 = talloc_asprintf(r, 
475                                                   "Failed to replace entries on %s\n", 
476                                                   ldb_dn_linearize(tmp_ctx, msg->dn));
477                         talloc_free(tmp_ctx);
478                         return NT_STATUS_INTERNAL_DB_CORRUPTION;
479                 }
480         }
481                                 
482         /* DsCrackNames to find out the DN of the domain. */
483         r_crack_names.in.req.req1.format_offered = DRSUAPI_DS_NAME_FORMAT_NT4_ACCOUNT;
484         r_crack_names.in.req.req1.format_desired = DRSUAPI_DS_NAME_FORMAT_FQDN_1779;
485         names[0].str = talloc_asprintf(tmp_ctx, "%s\\", r->out.domain_name);
486         if (!names[0].str) {
487                 r->out.error_string = NULL;
488                 talloc_free(tmp_ctx);
489                 return NT_STATUS_NO_MEMORY;
490         }
491
492         status = dcerpc_drsuapi_DsCrackNames(drsuapi_pipe, tmp_ctx, &r_crack_names);
493         if (!NT_STATUS_IS_OK(status)) {
494                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
495                         r->out.error_string
496                                 = talloc_asprintf(r,
497                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s\n", 
498                                                   r->in.domain_name, 
499                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
500                         talloc_free(tmp_ctx);
501                         return status;
502                 } else {
503                         r->out.error_string
504                                 = talloc_asprintf(r,
505                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s\n", 
506                                                   r->in.domain_name, 
507                                                   nt_errstr(status));
508                         talloc_free(tmp_ctx);
509                         return status;
510                 }
511         } else if (!W_ERROR_IS_OK(r_crack_names.out.result)) {
512                 r->out.error_string
513                         = talloc_asprintf(r,
514                                           "DsCrackNames failed - %s\n", win_errstr(r_crack_names.out.result));
515                 talloc_free(tmp_ctx);
516                 return NT_STATUS_UNSUCCESSFUL;
517         } else if (r_crack_names.out.level != 1 
518                    || !r_crack_names.out.ctr.ctr1 
519                    || r_crack_names.out.ctr.ctr1->count != 1
520                    || !r_crack_names.out.ctr.ctr1->array[0].result_name           
521                    || r_crack_names.out.ctr.ctr1->array[0].status != DRSUAPI_DS_NAME_STATUS_OK) {
522                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed\n");
523                 talloc_free(tmp_ctx);
524                 return NT_STATUS_UNSUCCESSFUL;
525         }
526
527         /* Store the account DN. */
528         r->out.account_dn_str = account_dn_str;
529         talloc_steal(r, account_dn_str);
530
531         /* Store the domain DN. */
532         r->out.domain_dn_str = r_crack_names.out.ctr.ctr1->array[0].result_name;
533         talloc_steal(r, r_crack_names.out.ctr.ctr1->array[0].result_name);
534
535         r->out.kvno = kvno;
536
537         if (r->in.acct_type ==  ACB_SVRTRUST) {
538                 status = libnet_JoinSite(ctx,
539                                          drsuapi_pipe, drsuapi_bind_handle,
540                                          remote_ldb, r);
541         }
542         talloc_free(tmp_ctx);
543
544         return status;
545 }
546
547 /*
548  * do a domain join using DCERPC/SAMR calls
549  * 1. connect to the SAMR pipe of users domain PDC (maybe a standalone server or workstation)
550  *    is it correct to contact the the pdc of the domain of the user who's password should be set?
551  * 2. do a samr_Connect to get a policy handle
552  * 3. do a samr_LookupDomain to get the domain sid
553  * 4. do a samr_OpenDomain to get a domain handle
554  * 5. do a samr_CreateAccount to try and get a new account 
555  * 
556  * If that fails, do:
557  * 5.1. do a samr_LookupNames to get the users rid
558  * 5.2. do a samr_OpenUser to get a user handle
559  * 
560  * 6. call libnet_SetPassword_samr_handle to set the password
561  *
562  * 7. do a samrSetUserInfo to set the account flags
563  * 8. do some ADS specific things when we join as Domain Controller,
564  *    look at libnet_joinADSDomain() for the details
565  */
566 NTSTATUS libnet_JoinDomain(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_JoinDomain *r)
567 {
568         TALLOC_CTX *tmp_ctx;
569
570         NTSTATUS status, cu_status;
571         struct libnet_RpcConnect *c;
572         struct lsa_ObjectAttribute attr;
573         struct lsa_QosInfo qos;
574         struct lsa_OpenPolicy2 lsa_open_policy;
575         struct policy_handle lsa_p_handle;
576         struct lsa_QueryInfoPolicy2 lsa_query_info2;
577         struct lsa_QueryInfoPolicy lsa_query_info;
578
579         struct dcerpc_binding *samr_binding;
580         struct dcerpc_pipe *samr_pipe;
581         struct dcerpc_pipe *lsa_pipe;
582         struct samr_Connect sc;
583         struct policy_handle p_handle;
584         struct samr_OpenDomain od;
585         struct policy_handle d_handle;
586         struct samr_LookupNames ln;
587         struct samr_OpenUser ou;
588         struct samr_CreateUser2 cu;
589         struct policy_handle *u_handle = NULL;
590         struct samr_QueryUserInfo qui;
591         struct samr_SetUserInfo sui;
592         union samr_UserInfo u_info;
593         union libnet_SetPassword r2;
594         struct samr_GetUserPwInfo pwp;
595         struct lsa_String samr_account_name;
596         
597         uint32_t acct_flags;
598         uint32_t rid, access_granted;
599         int policy_min_pw_len = 0;
600
601         struct dom_sid *domain_sid = NULL;
602         struct dom_sid *account_sid = NULL;
603         const char *domain_name = NULL;
604         const char *password_str = NULL;
605         const char *realm = NULL; /* Also flag for remote being AD */
606         
607         
608         r->out.error_string = NULL;
609         r2.samr_handle.out.error_string = NULL;
610         
611         tmp_ctx = talloc_named(mem_ctx, 0, "libnet_Join temp context");
612         if (!tmp_ctx) {
613                 r->out.error_string = NULL;
614                 return NT_STATUS_NO_MEMORY;
615         }
616         
617         u_handle = talloc(tmp_ctx, struct policy_handle);
618         if (!u_handle) {
619                 r->out.error_string = NULL;
620                 talloc_free(tmp_ctx);
621                 return NT_STATUS_NO_MEMORY;
622         }
623         
624         samr_pipe = talloc(tmp_ctx, struct dcerpc_pipe);
625         if (!samr_pipe) {
626                 r->out.error_string = NULL;
627                 talloc_free(tmp_ctx);
628                 return NT_STATUS_NO_MEMORY;
629         }
630         
631         c = talloc(tmp_ctx, struct libnet_RpcConnect);
632         if (!c) {
633                 r->out.error_string = NULL;
634                 talloc_free(tmp_ctx);
635                 return NT_STATUS_NO_MEMORY;
636         }
637         
638         /* prepare connect to the LSA pipe of PDC */
639         if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
640                 c->level             = LIBNET_RPC_CONNECT_PDC;
641                 c->in.domain_name    = r->in.domain_name;
642         } else {
643                 c->level             = LIBNET_RPC_CONNECT_BINDING;
644                 c->in.binding        = r->in.binding;
645         }
646         c->in.dcerpc_iface_name      = DCERPC_LSARPC_NAME;
647         c->in.dcerpc_iface_uuid      = DCERPC_LSARPC_UUID;
648         c->in.dcerpc_iface_version   = DCERPC_LSARPC_VERSION;
649         
650         /* connect to the LSA pipe of the PDC */
651
652         status = libnet_RpcConnect(ctx, c, c);
653         if (!NT_STATUS_IS_OK(status)) {
654                 if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
655                         r->out.error_string = talloc_asprintf(mem_ctx,
656                                                               "Connection to LSA pipe of PDC of domain '%s' failed: %s",
657                                                               r->in.domain_name, nt_errstr(status));
658                 } else {
659                         r->out.error_string = talloc_asprintf(mem_ctx,
660                                                               "Connection to LSA pipe with binding '%s' failed: %s",
661                                                               r->in.binding, nt_errstr(status));
662                 }
663                 talloc_free(tmp_ctx);
664                 return status;
665         }                       
666         lsa_pipe = c->out.dcerpc_pipe;
667         
668         /* Get an LSA policy handle */
669
670         ZERO_STRUCT(lsa_p_handle);
671         qos.len = 0;
672         qos.impersonation_level = 2;
673         qos.context_mode = 1;
674         qos.effective_only = 0;
675
676         attr.len = 0;
677         attr.root_dir = NULL;
678         attr.object_name = NULL;
679         attr.attributes = 0;
680         attr.sec_desc = NULL;
681         attr.sec_qos = &qos;
682
683         lsa_open_policy.in.attr = &attr;
684         
685         lsa_open_policy.in.system_name = talloc_asprintf(tmp_ctx, "\\"); 
686         if (!lsa_open_policy.in.system_name) {
687                 r->out.error_string = NULL;
688                 talloc_free(tmp_ctx);
689                 return NT_STATUS_NO_MEMORY;
690         }
691
692         lsa_open_policy.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
693         lsa_open_policy.out.handle = &lsa_p_handle;
694
695         status = dcerpc_lsa_OpenPolicy2(lsa_pipe, tmp_ctx, &lsa_open_policy); 
696
697         /* This now fails on ncacn_ip_tcp against Win2k3 SP1 */
698         if (NT_STATUS_IS_OK(status)) {
699                 /* Look to see if this is ADS (a fault indicates NT4 or Samba 3.0) */
700                 
701                 lsa_query_info2.in.handle = &lsa_p_handle;
702                 lsa_query_info2.in.level = LSA_POLICY_INFO_DNS;
703                 
704                 status = dcerpc_lsa_QueryInfoPolicy2(lsa_pipe, tmp_ctx,                 
705                                                      &lsa_query_info2);
706                 
707                 if (!NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
708                         if (!NT_STATUS_IS_OK(status)) {
709                                 r->out.error_string = talloc_asprintf(mem_ctx,
710                                                                       "lsa_QueryInfoPolicy2 failed: %s",
711                                                                       nt_errstr(status));
712                                 talloc_free(tmp_ctx);
713                                 return status;
714                         }
715                         realm = lsa_query_info2.out.info->dns.dns_domain.string;
716                 }
717                 
718                 /* Grab the domain SID (regardless of the result of the previous call */
719                 
720                 lsa_query_info.in.handle = &lsa_p_handle;
721                 lsa_query_info.in.level = LSA_POLICY_INFO_DOMAIN;
722                 
723                 status = dcerpc_lsa_QueryInfoPolicy(lsa_pipe, tmp_ctx, 
724                                                     &lsa_query_info);
725                 
726                 if (!NT_STATUS_IS_OK(status)) {
727                         r->out.error_string = talloc_asprintf(mem_ctx,
728                                                               "lsa_QueryInfoPolicy2 failed: %s",
729                                                               nt_errstr(status));
730                         talloc_free(tmp_ctx);
731                         return status;
732                 }
733                 
734                 domain_sid = lsa_query_info.out.info->domain.sid;
735                 domain_name = lsa_query_info.out.info->domain.name.string;
736         } else {
737                 /* Cause the code further down to try this with just SAMR */
738                 domain_sid = NULL;
739                 if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
740                         domain_name = talloc_strdup(tmp_ctx, r->in.domain_name);
741                 } else {
742                         /* Bugger, we just lost our way to automaticly find the domain name */
743                         domain_name = talloc_strdup(tmp_ctx, lp_workgroup());
744                 }
745         }
746
747         DEBUG(0, ("Joining domain %s\n", domain_name));
748
749         /*
750           establish a SAMR connection, on the same CIFS transport
751         */
752
753         /* Find the original binding string */
754         status = dcerpc_parse_binding(tmp_ctx, lsa_pipe->conn->binding_string, &samr_binding);  
755         if (!NT_STATUS_IS_OK(status)) {
756                 r->out.error_string = talloc_asprintf(mem_ctx,
757                                                 "Failed to parse lsa binding '%s'",
758                                                 lsa_pipe->conn->binding_string);
759                 talloc_free(tmp_ctx);
760                 return status;
761         }
762
763         /* Make binding string for samr, not the other pipe */
764         status = dcerpc_epm_map_binding(tmp_ctx, samr_binding,                                  
765                                         DCERPC_SAMR_UUID, DCERPC_SAMR_VERSION,
766                                         lsa_pipe->conn->event_ctx);
767         if (!NT_STATUS_IS_OK(status)) {
768                 r->out.error_string = talloc_asprintf(mem_ctx,
769                                                 "Failed to map DCERPC/TCP NCACN_NP pipe for '%s' - %s",
770                                                 DCERPC_NETLOGON_UUID,
771                                                 nt_errstr(status));
772                 talloc_free(tmp_ctx);
773                 return status;
774         }
775
776         /* Setup a SAMR connection */
777         status = dcerpc_secondary_connection(lsa_pipe, &samr_pipe, samr_binding);
778         if (!NT_STATUS_IS_OK(status)) {
779                 r->out.error_string = talloc_asprintf(mem_ctx,
780                                                 "SAMR secondary connection failed: %s",
781                                                 nt_errstr(status));
782                 talloc_free(tmp_ctx);
783                 return status;
784         }
785
786         status = dcerpc_pipe_auth(samr_pipe, samr_binding, DCERPC_SAMR_UUID, 
787                                   DCERPC_SAMR_VERSION, ctx->cred);
788         if (!NT_STATUS_IS_OK(status)) {
789                 r->out.error_string = talloc_asprintf(mem_ctx,
790                                                 "SAMR bind failed: %s",
791                                                 nt_errstr(status));
792                 talloc_free(tmp_ctx);
793                 return status;
794         }
795
796         /* prepare samr_Connect */
797         ZERO_STRUCT(p_handle);
798         sc.in.system_name = NULL;
799         sc.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
800         sc.out.connect_handle = &p_handle;
801
802         /* 2. do a samr_Connect to get a policy handle */
803         status = dcerpc_samr_Connect(samr_pipe, tmp_ctx, &sc);
804         if (!NT_STATUS_IS_OK(status)) {
805                 r->out.error_string = talloc_asprintf(mem_ctx,
806                                                 "samr_Connect failed: %s",
807                                                 nt_errstr(status));
808                 talloc_free(tmp_ctx);
809                 return status;
810         }
811
812         /* Perhaps we didn't get a SID above, because we are against ncacn_ip_tcp */
813         if (!domain_sid) {
814                 struct lsa_String name;
815                 struct samr_LookupDomain l;
816                 name.string = domain_name;
817                 l.in.connect_handle = &p_handle;
818                 l.in.domain_name = &name;
819                 
820                 status = dcerpc_samr_LookupDomain(samr_pipe, tmp_ctx, &l);
821                 if (!NT_STATUS_IS_OK(status)) {
822                         r->out.error_string = talloc_asprintf(mem_ctx,
823                                                               "SAMR LookupDomain failed: %s",
824                                                               nt_errstr(status));
825                         talloc_free(tmp_ctx);
826                         return status;
827                 }
828                 domain_sid = l.out.sid;
829         }
830
831         /* prepare samr_OpenDomain */
832         ZERO_STRUCT(d_handle);
833         od.in.connect_handle = &p_handle;
834         od.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
835         od.in.sid = domain_sid;
836         od.out.domain_handle = &d_handle;
837
838         /* 4. do a samr_OpenDomain to get a domain handle */
839         status = dcerpc_samr_OpenDomain(samr_pipe, tmp_ctx, &od);                       
840         if (!NT_STATUS_IS_OK(status)) {
841                 r->out.error_string = talloc_asprintf(mem_ctx,
842                                         "samr_OpenDomain for [%s] failed: %s",
843                                         r->in.domain_name,
844                                         nt_errstr(status));
845                 talloc_free(tmp_ctx);
846                 return status;
847         }
848         
849         /* prepare samr_CreateUser2 */
850         ZERO_STRUCTP(u_handle);
851         cu.in.domain_handle  = &d_handle;
852         cu.in.access_mask     = SEC_FLAG_MAXIMUM_ALLOWED;
853         samr_account_name.string = r->in.account_name;
854         cu.in.account_name    = &samr_account_name;
855         cu.in.acct_flags      = r->in.acct_type;
856         cu.out.user_handle    = u_handle;
857         cu.out.rid            = &rid;
858         cu.out.access_granted = &access_granted;
859
860         /* 4. do a samr_CreateUser2 to get an account handle, or an error */
861         cu_status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                   
862         status = cu_status;
863         if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
864                         r->out.error_string = talloc_asprintf(mem_ctx,
865                                                                 "samr_CreateUser2 for [%s] failed: %s\n",
866                                                                 r->in.domain_name, nt_errstr(status));
867                         talloc_free(tmp_ctx);
868                         return status;
869
870         } else if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
871                 /* prepare samr_LookupNames */
872                 ln.in.domain_handle = &d_handle;
873                 ln.in.num_names = 1;
874                 ln.in.names = talloc_array(tmp_ctx, struct lsa_String, 1);
875                 if (!ln.in.names) {
876                         r->out.error_string = NULL;
877                         talloc_free(tmp_ctx);
878                         return NT_STATUS_NO_MEMORY;
879                 }
880                 ln.in.names[0].string = r->in.account_name;
881                 
882                 /* 5. do a samr_LookupNames to get the users rid */
883                 status = dcerpc_samr_LookupNames(samr_pipe, tmp_ctx, &ln);
884                 if (!NT_STATUS_IS_OK(status)) {
885                         r->out.error_string = talloc_asprintf(mem_ctx,
886                                                 "samr_LookupNames for [%s] failed: %s",
887                                                 r->in.account_name,
888                                                 nt_errstr(status));
889                         talloc_free(tmp_ctx);
890                         return status;
891                 }
892                 
893                 /* check if we got one RID for the user */
894                 if (ln.out.rids.count != 1) {
895                         r->out.error_string = talloc_asprintf(mem_ctx,
896                                                               "samr_LookupNames for [%s] returns %d RIDs\n",
897                                                               r->in.account_name, ln.out.rids.count);
898                         talloc_free(tmp_ctx);
899                         return NT_STATUS_INVALID_PARAMETER;
900                 }
901                 
902                 /* prepare samr_OpenUser */
903                 ZERO_STRUCTP(u_handle);
904                 ou.in.domain_handle = &d_handle;
905                 ou.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
906                 ou.in.rid = ln.out.rids.ids[0];
907                 rid = ou.in.rid;
908                 ou.out.user_handle = u_handle;
909                 
910                 /* 6. do a samr_OpenUser to get a user handle */
911                 status = dcerpc_samr_OpenUser(samr_pipe, tmp_ctx, &ou); 
912                 if (!NT_STATUS_IS_OK(status)) {
913                         r->out.error_string = talloc_asprintf(mem_ctx,
914                                                         "samr_OpenUser for [%s] failed: %s",
915                                                         r->in.account_name,
916                                                         nt_errstr(status));
917                         talloc_free(tmp_ctx);
918                         return status;
919                 }
920
921                 if (r->in.recreate_account) {
922                         struct samr_DeleteUser d;
923                         d.in.user_handle = u_handle;
924                         d.out.user_handle = u_handle;
925                         status = dcerpc_samr_DeleteUser(samr_pipe, mem_ctx, &d);
926                         if (!NT_STATUS_IS_OK(status)) {
927                                 r->out.error_string = talloc_asprintf(mem_ctx,
928                                                                       "samr_DeleteUser (for recreate) of [%s] failed: %s",
929                                                                       r->in.account_name,
930                                                                       nt_errstr(status));
931                                 talloc_free(tmp_ctx);
932                                 return status;
933                         }
934
935                         /* We want to recreate, so delete and another samr_CreateUser2 */
936                         
937                         /* &cu filled in above */
938                         cu_status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                   
939                         status = cu_status;
940                         if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
941                                 r->out.error_string = talloc_asprintf(mem_ctx,
942                                                                       "samr_CreateUser2 (recreate) for [%s] failed: %s\n",
943                                                                       r->in.domain_name, nt_errstr(status));
944                                 talloc_free(tmp_ctx);
945                                 return status;
946                         }
947                         DEBUG(0, ("Recreated account in domain %s\n", domain_name));
948
949                 }
950         }
951         /* Find out what password policy this user has */
952         pwp.in.user_handle = u_handle;
953
954         status = dcerpc_samr_GetUserPwInfo(samr_pipe, tmp_ctx, &pwp);                           
955         if (NT_STATUS_IS_OK(status)) {
956                 policy_min_pw_len = pwp.out.info.min_password_length;
957         }
958         
959         /* Grab a password of that minimum length */
960         
961         password_str = generate_random_str(tmp_ctx, MAX(8, policy_min_pw_len)); 
962
963         r2.samr_handle.level            = LIBNET_SET_PASSWORD_SAMR_HANDLE;
964         r2.samr_handle.in.account_name  = r->in.account_name;
965         r2.samr_handle.in.newpassword   = password_str;
966         r2.samr_handle.in.user_handle   = u_handle;
967         r2.samr_handle.in.dcerpc_pipe   = samr_pipe;
968
969         status = libnet_SetPassword(ctx, tmp_ctx, &r2); 
970         if (!NT_STATUS_IS_OK(status)) {
971                 r->out.error_string = talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
972                 talloc_free(tmp_ctx);
973                 return status;
974         }
975
976         /* prepare samr_QueryUserInfo (get flags) */
977         qui.in.user_handle = u_handle;
978         qui.in.level = 16;
979         
980         status = dcerpc_samr_QueryUserInfo(samr_pipe, tmp_ctx, &qui);
981         if (!NT_STATUS_IS_OK(status)) {
982                 r->out.error_string = talloc_asprintf(mem_ctx,
983                                                 "samr_QueryUserInfo for [%s] failed: %s",
984                                                 r->in.account_name,
985                                                 nt_errstr(status));
986                 talloc_free(tmp_ctx);
987                 return status;
988         }
989         
990         if (!qui.out.info) {
991                 status = NT_STATUS_INVALID_PARAMETER;
992                 r->out.error_string
993                         = talloc_asprintf(mem_ctx,
994                                           "samr_QueryUserInfo failed to return qui.out.info for [%s]: %s\n",
995                                           r->in.account_name, nt_errstr(status));
996                 talloc_free(tmp_ctx);
997                 return status;
998         }
999
1000         /* Possibly change account type (if we are creating a new account) */
1001         if (((qui.out.info->info16.acct_flags & (ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST)) 
1002             != r->in.acct_type) && (!NT_STATUS_EQUAL(cu_status, NT_STATUS_USER_EXISTS))) {
1003                 acct_flags = (qui.out.info->info16.acct_flags & ~(ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST))
1004                               | r->in.acct_type;
1005         } else {
1006                 acct_flags = qui.out.info->info16.acct_flags;
1007         }
1008         
1009         acct_flags = (acct_flags & ~ACB_DISABLED);
1010
1011         /* reset flags (if required) */
1012         if (acct_flags != qui.out.info->info16.acct_flags) {    
1013                 ZERO_STRUCT(u_info);
1014                 u_info.info16.acct_flags = acct_flags;
1015
1016                 sui.in.user_handle = u_handle;
1017                 sui.in.info = &u_info;
1018                 sui.in.level = 16;
1019                 
1020                 dcerpc_samr_SetUserInfo(samr_pipe, tmp_ctx, &sui);
1021                 if (!NT_STATUS_IS_OK(status)) {
1022                         r->out.error_string = talloc_asprintf(mem_ctx,
1023                                                         "samr_SetUserInfo for [%s] failed to remove ACB_DISABLED flag: %s",
1024                                                         r->in.account_name,
1025                                                         nt_errstr(status));
1026                         talloc_free(tmp_ctx);
1027                         return status;
1028                 }
1029         }
1030
1031         account_sid = dom_sid_add_rid(mem_ctx, domain_sid, rid);
1032         if (!account_sid) {
1033                 r->out.error_string = NULL;
1034                 talloc_free(tmp_ctx);
1035                 return NT_STATUS_NO_MEMORY;
1036         }
1037
1038         r->out.join_password = password_str;
1039         talloc_steal(mem_ctx, password_str);
1040
1041         r->out.domain_sid = domain_sid;
1042         talloc_steal(mem_ctx, domain_sid);
1043
1044         r->out.account_sid = account_sid;
1045         talloc_steal(mem_ctx, account_sid);
1046
1047         r->out.domain_name = domain_name;
1048         talloc_steal(mem_ctx, domain_name);
1049         r->out.realm = realm;
1050         talloc_steal(mem_ctx, realm);
1051         r->out.lsa_pipe = lsa_pipe;
1052         talloc_steal(mem_ctx, lsa_pipe);
1053         r->out.samr_pipe = samr_pipe;
1054         talloc_steal(mem_ctx, samr_pipe);
1055         r->out.samr_binding = samr_binding;
1056         talloc_steal(mem_ctx, samr_binding);
1057         r->out.user_handle = u_handle;
1058         talloc_steal(mem_ctx, u_handle);
1059         r->out.error_string = r2.samr_handle.out.error_string;
1060         talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
1061         r->out.kvno = 0;
1062         r->out.server_dn_str = NULL;
1063         talloc_free(tmp_ctx); 
1064
1065         /* Now, if it was AD, then we want to start looking changing a
1066          * few more things.  Otherwise, we are done. */
1067         if (realm) {
1068                 status = libnet_JoinADSDomain(ctx, r);
1069                 return status;
1070         }
1071
1072         return status;
1073 }
1074
1075 static NTSTATUS libnet_Join_primary_domain(struct libnet_context *ctx, 
1076                                            TALLOC_CTX *mem_ctx, 
1077                                            struct libnet_Join *r)
1078 {
1079         NTSTATUS status;
1080         TALLOC_CTX *tmp_mem;
1081         struct libnet_JoinDomain *r2;
1082         int ret, rtn;
1083         struct ldb_context *ldb;
1084         const struct ldb_dn *base_dn;
1085         struct ldb_message **msgs, *msg;
1086         const char *sct;
1087         const char * const attrs[] = {
1088                 "whenChanged",
1089                 "secret",
1090                 "priorSecret",
1091                 "priorChanged",
1092                 NULL
1093         };
1094         uint32_t acct_type = 0;
1095         const char *account_name;
1096         const char *netbios_name;
1097         char *filter;
1098         
1099         r->out.error_string = NULL;
1100
1101         tmp_mem = talloc_new(mem_ctx);
1102         if (!tmp_mem) {
1103                 return NT_STATUS_NO_MEMORY;
1104         }
1105
1106         r2 = talloc(tmp_mem, struct libnet_JoinDomain);
1107         if (!r2) {
1108                 r->out.error_string = NULL;
1109                 talloc_free(tmp_mem);
1110                 return NT_STATUS_NO_MEMORY;
1111         }
1112         
1113         if (r->in.secure_channel_type == SEC_CHAN_BDC) {
1114                 acct_type = ACB_SVRTRUST;
1115         } else if (r->in.secure_channel_type == SEC_CHAN_WKSTA) {
1116                 acct_type = ACB_WSTRUST;
1117         } else {
1118                 r->out.error_string = NULL;
1119                 talloc_free(tmp_mem);   
1120                 return NT_STATUS_INVALID_PARAMETER;
1121         }
1122
1123         if ((r->in.netbios_name != NULL) && (r->in.level != LIBNET_JOIN_AUTOMATIC)) {
1124                 netbios_name = r->in.netbios_name;
1125         } else {
1126                 netbios_name = talloc_asprintf(tmp_mem, "%s", lp_netbios_name());
1127                 if (!netbios_name) {
1128                         r->out.error_string = NULL;
1129                         talloc_free(tmp_mem);
1130                         return NT_STATUS_NO_MEMORY;
1131                 }
1132         }
1133
1134         account_name = talloc_asprintf(tmp_mem, "%s$", netbios_name);                   
1135         if (!account_name) {
1136                 r->out.error_string = NULL;
1137                 talloc_free(tmp_mem);
1138                 return NT_STATUS_NO_MEMORY;
1139         }
1140         
1141         /*
1142          * Local secrets are stored in secrets.ldb 
1143          * open it to make sure we can write the info into it after the join
1144          */
1145         ldb = secrets_db_connect(tmp_mem);                                              
1146         if (!ldb) {
1147                 r->out.error_string
1148                         = talloc_asprintf(mem_ctx, 
1149                                           "Could not open secrets database\n");
1150                 talloc_free(tmp_mem);
1151                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1152         }
1153
1154         /*
1155          * join the domain
1156          */
1157         ZERO_STRUCTP(r2);
1158         r2->in.domain_name      = r->in.domain_name;
1159         r2->in.account_name     = account_name;
1160         r2->in.netbios_name     = netbios_name;
1161         r2->in.level            = LIBNET_JOINDOMAIN_AUTOMATIC;
1162         r2->in.acct_type        = acct_type;
1163         r2->in.recreate_account = False;
1164         status = libnet_JoinDomain(ctx, r2, r2);
1165         if (!NT_STATUS_IS_OK(status)) {
1166                 r->out.error_string = talloc_steal(mem_ctx, r2->out.error_string);
1167                 talloc_free(tmp_mem);
1168                 return status;
1169         }
1170         
1171         /*
1172          * now prepare the record for secrets.ldb
1173          */
1174         sct = talloc_asprintf(tmp_mem, "%d", r->in.secure_channel_type); 
1175         if (!sct) {
1176                 r->out.error_string = NULL;
1177                 talloc_free(tmp_mem);
1178                 return NT_STATUS_NO_MEMORY;
1179         }
1180         
1181         msg = ldb_msg_new(tmp_mem);
1182         if (!msg) {
1183                 r->out.error_string = NULL;
1184                 talloc_free(tmp_mem);
1185                 return NT_STATUS_NO_MEMORY;
1186         }
1187
1188         base_dn = ldb_dn_explode(tmp_mem, "cn=Primary Domains");
1189         if (!base_dn) {
1190                 r->out.error_string = NULL;
1191                 talloc_free(tmp_mem);
1192                 return NT_STATUS_NO_MEMORY;
1193         }
1194
1195         msg->dn = ldb_dn_build_child(tmp_mem, "flatname", r2->out.domain_name, base_dn);
1196         if (!msg->dn) {
1197                 r->out.error_string = NULL;
1198                 talloc_free(tmp_mem);
1199                 return NT_STATUS_NO_MEMORY;
1200         }
1201         
1202         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "flatname", r2->out.domain_name);
1203         if (rtn == -1) {
1204                 r->out.error_string = NULL;
1205                 talloc_free(tmp_mem);
1206                 return NT_STATUS_NO_MEMORY;
1207         }
1208
1209         if (r2->out.realm) {
1210                 rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "realm", r2->out.realm);
1211                 if (rtn == -1) {
1212                         r->out.error_string = NULL;
1213                         talloc_free(tmp_mem);
1214                         return NT_STATUS_NO_MEMORY;
1215                 }
1216
1217                 rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "objectClass", "primaryDomain");
1218                 if (rtn == -1) {
1219                         r->out.error_string = NULL;
1220                         talloc_free(tmp_mem);
1221                         return NT_STATUS_NO_MEMORY;
1222                 }
1223         }
1224
1225         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "objectClass", "primaryDomain");
1226         if (rtn == -1) {
1227                 r->out.error_string = NULL;
1228                 talloc_free(tmp_mem);
1229                 return NT_STATUS_NO_MEMORY;
1230         }
1231
1232         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secret", r2->out.join_password);
1233         if (rtn == -1) {
1234                 r->out.error_string = NULL;
1235                 talloc_free(tmp_mem);
1236                 return NT_STATUS_NO_MEMORY;
1237         }
1238
1239         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "samAccountName", r2->in.account_name);
1240         if (rtn == -1) {
1241                 r->out.error_string = NULL;
1242                 talloc_free(tmp_mem);
1243                 return NT_STATUS_NO_MEMORY;
1244         }
1245
1246         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secureChannelType", sct);
1247         if (rtn == -1) {
1248                 r->out.error_string = NULL;
1249                 talloc_free(tmp_mem);
1250                 return NT_STATUS_NO_MEMORY;
1251         }
1252
1253         if (r2->out.kvno) {
1254                 rtn = samdb_msg_add_uint(ldb, tmp_mem, msg, "msDS-KeyVersionNumber",
1255                                          r2->out.kvno);
1256                 if (rtn == -1) {
1257                         r->out.error_string = NULL;
1258                         talloc_free(tmp_mem);
1259                         return NT_STATUS_NO_MEMORY;
1260                 }
1261         }
1262
1263         if (r2->out.domain_sid) {
1264                 rtn = samdb_msg_add_dom_sid(ldb, tmp_mem, msg, "objectSid",
1265                                             r2->out.domain_sid);
1266                 if (rtn == -1) {
1267                         r->out.error_string = NULL;
1268                         talloc_free(tmp_mem);
1269                         return NT_STATUS_NO_MEMORY;
1270                 }
1271         }
1272
1273         /* 
1274          * search for the secret record
1275          * - remove the records we find
1276          * - and fetch the old secret and store it under priorSecret
1277          */
1278         ret = gendb_search(ldb,
1279                            tmp_mem, base_dn,
1280                            &msgs, attrs,
1281                            "(|" SECRETS_PRIMARY_DOMAIN_FILTER "(realm=%s))",
1282                            r2->out.domain_name, r2->out.realm);
1283         if (ret == 0) {
1284         } else if (ret == -1) {
1285                 r->out.error_string
1286                         = talloc_asprintf(mem_ctx, 
1287                                           "Search for domain: %s and realm: %s failed: %s", 
1288                                           r2->out.domain_name, r2->out.realm, ldb_errstring(ldb));
1289                 talloc_free(tmp_mem);
1290                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1291         } else {
1292                 const struct ldb_val *prior_secret;
1293                 const struct ldb_val *prior_modified_time;
1294                 int i;
1295
1296                 for (i = 0; i < ret; i++) {
1297                         ldb_delete(ldb, msgs[i]->dn);
1298                 }
1299
1300                 prior_secret = ldb_msg_find_ldb_val(msgs[0], "secret");
1301                 if (prior_secret) {
1302                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorSecret", prior_secret);
1303                         if (rtn == -1) {
1304                                 r->out.error_string = NULL;
1305                                 talloc_free(tmp_mem);
1306                                 return NT_STATUS_NO_MEMORY;
1307                         }
1308                 }
1309                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secret", r2->out.join_password);
1310                 if (rtn == -1) {
1311                         r->out.error_string = NULL;
1312                         talloc_free(tmp_mem);
1313                         return NT_STATUS_NO_MEMORY;
1314                 }
1315
1316                 prior_modified_time = ldb_msg_find_ldb_val(msgs[0], 
1317                                                            "whenChanged");
1318                 if (prior_modified_time) {
1319                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorWhenChanged", 
1320                                                   prior_modified_time);
1321                         if (rtn == -1) {
1322                                 r->out.error_string = NULL;
1323                                 talloc_free(tmp_mem);
1324                                 return NT_STATUS_NO_MEMORY;
1325                         }
1326                 }
1327
1328                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "samAccountName", r2->in.account_name);
1329                 if (rtn == -1) {
1330                         r->out.error_string = NULL;
1331                         talloc_free(tmp_mem);
1332                         return NT_STATUS_NO_MEMORY;
1333                 }
1334
1335                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secureChannelType", sct);
1336                 if (rtn == -1) {
1337                         r->out.error_string = NULL;
1338                         talloc_free(tmp_mem);
1339                         return NT_STATUS_NO_MEMORY;
1340                 }
1341         }
1342
1343         /* create the secret */
1344         ret = samdb_add(ldb, tmp_mem, msg);
1345         if (ret != 0) {
1346                 r->out.error_string = talloc_asprintf(mem_ctx, "Failed to create secret record %s\n", 
1347                                                       ldb_dn_linearize(ldb, msg->dn));
1348                 talloc_free(tmp_mem);
1349                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1350         }
1351
1352         if (r2->out.realm) {
1353                 struct cli_credentials *creds;
1354                 /* Make a credentials structure from it */
1355                 creds = cli_credentials_init(mem_ctx);
1356                 if (!creds) {
1357                         r->out.error_string = NULL;
1358                         talloc_free(tmp_mem);
1359                         return NT_STATUS_NO_MEMORY;
1360                 }
1361                 cli_credentials_set_conf(creds);
1362                 filter = talloc_asprintf(mem_ctx, "dn=%s", ldb_dn_linearize(mem_ctx, msg->dn));
1363                 status = cli_credentials_set_secrets(creds, NULL, filter);
1364                 if (!NT_STATUS_IS_OK(status)) {
1365                         r->out.error_string = talloc_asprintf(mem_ctx, "Failed to read secrets for keytab update for %s\n", 
1366                                                               filter);
1367                         talloc_free(tmp_mem);
1368                         return status;
1369                 } 
1370                 ret = cli_credentials_update_keytab(creds);
1371                 if (ret != 0) {
1372                         r->out.error_string = talloc_asprintf(mem_ctx, "Failed to update keytab for %s\n", 
1373                                                               filter);
1374                         talloc_free(tmp_mem);
1375                         return NT_STATUS_UNSUCCESSFUL;
1376                 }
1377         }
1378
1379         /* move all out parameter to the callers TALLOC_CTX */
1380         r->out.error_string     = NULL;
1381         r->out.join_password    = r2->out.join_password;
1382         talloc_steal(mem_ctx, r2->out.join_password);
1383         r->out.domain_sid       = r2->out.domain_sid;
1384         talloc_steal(mem_ctx, r2->out.domain_sid);
1385         talloc_free(tmp_mem);
1386         return NT_STATUS_OK;
1387 }
1388
1389 NTSTATUS libnet_Join(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_Join *r)
1390 {
1391         switch (r->in.secure_channel_type) {
1392                 case SEC_CHAN_WKSTA:
1393                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1394                 case SEC_CHAN_BDC:
1395                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1396                 case SEC_CHAN_DOMAIN:
1397                         break;
1398         }
1399
1400         r->out.error_string = talloc_asprintf(mem_ctx,
1401                                 "Invalid secure channel type specified (%08X) attempting to join domain %s",
1402                                 r->in.secure_channel_type, r->in.domain_name);
1403         return NT_STATUS_INVALID_PARAMETER;
1404 }
1405
1406