r12510: Change the DCE/RPC interfaces to take a pointer to a
[kai/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_table_drsuapi,
278                                        ctx->cred, 
279                                        ctx->event_ctx);
280         if (!NT_STATUS_IS_OK(status)) {
281                 r->out.error_string = talloc_asprintf(r,
282                                         "Connection to DRSUAPI pipe of PDC of domain '%s' failed: %s",
283                                         r->in.domain_name,
284                                         nt_errstr(status));
285                 talloc_free(tmp_ctx);
286                 return status;
287         }
288
289         /* get a DRSUAPI pipe handle */
290         GUID_from_string(DRSUAPI_DS_BIND_GUID, &drsuapi_bind_guid);
291
292         r_drsuapi_bind.in.bind_guid = &drsuapi_bind_guid;
293         r_drsuapi_bind.in.bind_info = NULL;
294         r_drsuapi_bind.out.bind_handle = &drsuapi_bind_handle;
295
296         status = dcerpc_drsuapi_DsBind(drsuapi_pipe, tmp_ctx, &r_drsuapi_bind);
297         if (!NT_STATUS_IS_OK(status)) {
298                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
299                         r->out.error_string
300                                 = talloc_asprintf(r,
301                                                   "dcerpc_drsuapi_DsBind for [%s\\%s] failed - %s\n", 
302                                                   r->in.domain_name, r->in.account_name, 
303                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
304                         talloc_free(tmp_ctx);
305                         return status;
306                 } else {
307                         r->out.error_string
308                                 = talloc_asprintf(r,
309                                                   "dcerpc_drsuapi_DsBind for [%s\\%s] failed - %s\n", 
310                                                   r->in.domain_name, r->in.account_name, 
311                                                   nt_errstr(status));
312                         talloc_free(tmp_ctx);
313                         return status;
314                 }
315         } else if (!W_ERROR_IS_OK(r_drsuapi_bind.out.result)) {
316                 r->out.error_string
317                                 = talloc_asprintf(r,
318                                                   "DsBind failed - %s\n", 
319                                                   win_errstr(r_drsuapi_bind.out.result));
320                         talloc_free(tmp_ctx);
321                 return NT_STATUS_UNSUCCESSFUL;
322         }
323
324         /* Actually 'crack' the names */
325         ZERO_STRUCT(r_crack_names);
326         r_crack_names.in.bind_handle            = &drsuapi_bind_handle;
327         r_crack_names.in.level                  = 1;
328         r_crack_names.in.req.req1.unknown1      = 0x000004e4;
329         r_crack_names.in.req.req1.unknown2      = 0x00000407;
330         r_crack_names.in.req.req1.count         = 1;
331         r_crack_names.in.req.req1.names         = names;
332         r_crack_names.in.req.req1.format_flags  = DRSUAPI_DS_NAME_FLAG_NO_FLAGS;
333         r_crack_names.in.req.req1.format_offered= DRSUAPI_DS_NAME_FORMAT_SID_OR_SID_HISTORY;
334         r_crack_names.in.req.req1.format_desired= DRSUAPI_DS_NAME_FORMAT_FQDN_1779;
335         names[0].str = dom_sid_string(tmp_ctx, r->out.account_sid);
336         if (!names[0].str) {
337                 r->out.error_string = NULL;
338                 talloc_free(tmp_ctx);
339                 return NT_STATUS_NO_MEMORY;
340         }
341
342         status = dcerpc_drsuapi_DsCrackNames(drsuapi_pipe, tmp_ctx, &r_crack_names);
343         if (!NT_STATUS_IS_OK(status)) {
344                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
345                         r->out.error_string
346                                 = talloc_asprintf(r,
347                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s\n", 
348                                                   names[0].str,
349                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
350                         talloc_free(tmp_ctx);
351                         return status;
352                 } else {
353                         r->out.error_string
354                                 = talloc_asprintf(r,
355                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s\n", 
356                                                   names[0].str,
357                                                   nt_errstr(status));
358                         talloc_free(tmp_ctx);
359                         return status;
360                 }
361         } else if (!W_ERROR_IS_OK(r_crack_names.out.result)) {
362                 r->out.error_string
363                                 = talloc_asprintf(r,
364                                                   "DsCrackNames failed - %s\n", win_errstr(r_crack_names.out.result));
365                 talloc_free(tmp_ctx);
366                 return NT_STATUS_UNSUCCESSFUL;
367         } else if (r_crack_names.out.level != 1 
368                    || !r_crack_names.out.ctr.ctr1 
369                    || r_crack_names.out.ctr.ctr1->count != 1 
370                    || !r_crack_names.out.ctr.ctr1->array[0].result_name
371                    || r_crack_names.out.ctr.ctr1->array[0].status != DRSUAPI_DS_NAME_STATUS_OK) {
372                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed\n");
373                 talloc_free(tmp_ctx);
374                 return NT_STATUS_UNSUCCESSFUL;
375         }
376
377         /* Store the DN of our machine account. */
378         account_dn_str = r_crack_names.out.ctr.ctr1->array[0].result_name;
379
380         account_dn = ldb_dn_explode(tmp_ctx, account_dn_str);
381         if (!account_dn) {
382                 r->out.error_string = talloc_asprintf(r, "Invalid account dn: %s",
383                                                       account_dn_str);
384                 talloc_free(tmp_ctx);
385                 return NT_STATUS_UNSUCCESSFUL;
386         }
387
388         /* Now we know the user's DN, open with LDAP, read and modify a few things */
389
390         remote_ldb_url = talloc_asprintf(tmp_ctx, "ldap://%s", 
391                                          drsuapi_binding->host);
392         if (!remote_ldb_url) {
393                 r->out.error_string = NULL;
394                 talloc_free(tmp_ctx);
395                 return NT_STATUS_NO_MEMORY;
396         }
397
398         remote_ldb = ldb_wrap_connect(tmp_ctx, remote_ldb_url, 
399                                       NULL, ctx->cred, 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, old_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      = &dcerpc_table_lsarpc;
647         
648         /* connect to the LSA pipe of the PDC */
649
650         status = libnet_RpcConnect(ctx, c, c);
651         if (!NT_STATUS_IS_OK(status)) {
652                 if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
653                         r->out.error_string = talloc_asprintf(mem_ctx,
654                                                               "Connection to LSA pipe of PDC of domain '%s' failed: %s",
655                                                               r->in.domain_name, nt_errstr(status));
656                 } else {
657                         r->out.error_string = talloc_asprintf(mem_ctx,
658                                                               "Connection to LSA pipe with binding '%s' failed: %s",
659                                                               r->in.binding, nt_errstr(status));
660                 }
661                 talloc_free(tmp_ctx);
662                 return status;
663         }                       
664         lsa_pipe = c->out.dcerpc_pipe;
665         
666         /* Get an LSA policy handle */
667
668         ZERO_STRUCT(lsa_p_handle);
669         qos.len = 0;
670         qos.impersonation_level = 2;
671         qos.context_mode = 1;
672         qos.effective_only = 0;
673
674         attr.len = 0;
675         attr.root_dir = NULL;
676         attr.object_name = NULL;
677         attr.attributes = 0;
678         attr.sec_desc = NULL;
679         attr.sec_qos = &qos;
680
681         lsa_open_policy.in.attr = &attr;
682         
683         lsa_open_policy.in.system_name = talloc_asprintf(tmp_ctx, "\\"); 
684         if (!lsa_open_policy.in.system_name) {
685                 r->out.error_string = NULL;
686                 talloc_free(tmp_ctx);
687                 return NT_STATUS_NO_MEMORY;
688         }
689
690         lsa_open_policy.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
691         lsa_open_policy.out.handle = &lsa_p_handle;
692
693         status = dcerpc_lsa_OpenPolicy2(lsa_pipe, tmp_ctx, &lsa_open_policy); 
694
695         /* This now fails on ncacn_ip_tcp against Win2k3 SP1 */
696         if (NT_STATUS_IS_OK(status)) {
697                 /* Look to see if this is ADS (a fault indicates NT4 or Samba 3.0) */
698                 
699                 lsa_query_info2.in.handle = &lsa_p_handle;
700                 lsa_query_info2.in.level = LSA_POLICY_INFO_DNS;
701                 
702                 status = dcerpc_lsa_QueryInfoPolicy2(lsa_pipe, tmp_ctx,                 
703                                                      &lsa_query_info2);
704                 
705                 if (!NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
706                         if (!NT_STATUS_IS_OK(status)) {
707                                 r->out.error_string = talloc_asprintf(mem_ctx,
708                                                                       "lsa_QueryInfoPolicy2 failed: %s",
709                                                                       nt_errstr(status));
710                                 talloc_free(tmp_ctx);
711                                 return status;
712                         }
713                         realm = lsa_query_info2.out.info->dns.dns_domain.string;
714                 }
715                 
716                 /* Grab the domain SID (regardless of the result of the previous call */
717                 
718                 lsa_query_info.in.handle = &lsa_p_handle;
719                 lsa_query_info.in.level = LSA_POLICY_INFO_DOMAIN;
720                 
721                 status = dcerpc_lsa_QueryInfoPolicy(lsa_pipe, tmp_ctx, 
722                                                     &lsa_query_info);
723                 
724                 if (!NT_STATUS_IS_OK(status)) {
725                         r->out.error_string = talloc_asprintf(mem_ctx,
726                                                               "lsa_QueryInfoPolicy2 failed: %s",
727                                                               nt_errstr(status));
728                         talloc_free(tmp_ctx);
729                         return status;
730                 }
731                 
732                 domain_sid = lsa_query_info.out.info->domain.sid;
733                 domain_name = lsa_query_info.out.info->domain.name.string;
734         } else {
735                 /* Cause the code further down to try this with just SAMR */
736                 domain_sid = NULL;
737                 if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
738                         domain_name = talloc_strdup(tmp_ctx, r->in.domain_name);
739                 } else {
740                         /* Bugger, we just lost our way to automaticly find the domain name */
741                         domain_name = talloc_strdup(tmp_ctx, lp_workgroup());
742                 }
743         }
744
745         /*
746           establish a SAMR connection, on the same CIFS transport
747         */
748
749         /* Find the original binding string */
750         status = dcerpc_parse_binding(tmp_ctx, lsa_pipe->conn->binding_string, &samr_binding);  
751         if (!NT_STATUS_IS_OK(status)) {
752                 r->out.error_string = talloc_asprintf(mem_ctx,
753                                                 "Failed to parse lsa binding '%s'",
754                                                 lsa_pipe->conn->binding_string);
755                 talloc_free(tmp_ctx);
756                 return status;
757         }
758
759         /* Make binding string for samr, not the other pipe */
760         status = dcerpc_epm_map_binding(tmp_ctx, samr_binding,                                  
761                                         &dcerpc_table_samr,
762                                         lsa_pipe->conn->event_ctx);
763         if (!NT_STATUS_IS_OK(status)) {
764                 r->out.error_string = talloc_asprintf(mem_ctx,
765                                                 "Failed to map DCERPC/TCP NCACN_NP pipe for '%s' - %s",
766                                                 DCERPC_NETLOGON_UUID,
767                                                 nt_errstr(status));
768                 talloc_free(tmp_ctx);
769                 return status;
770         }
771
772         /* Setup a SAMR connection */
773         status = dcerpc_secondary_connection(lsa_pipe, &samr_pipe, samr_binding);
774         if (!NT_STATUS_IS_OK(status)) {
775                 r->out.error_string = talloc_asprintf(mem_ctx,
776                                                 "SAMR secondary connection failed: %s",
777                                                 nt_errstr(status));
778                 talloc_free(tmp_ctx);
779                 return status;
780         }
781
782         status = dcerpc_pipe_auth(samr_pipe, samr_binding, &dcerpc_table_samr, ctx->cred);
783         if (!NT_STATUS_IS_OK(status)) {
784                 r->out.error_string = talloc_asprintf(mem_ctx,
785                                                 "SAMR bind failed: %s",
786                                                 nt_errstr(status));
787                 talloc_free(tmp_ctx);
788                 return status;
789         }
790
791         /* prepare samr_Connect */
792         ZERO_STRUCT(p_handle);
793         sc.in.system_name = NULL;
794         sc.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
795         sc.out.connect_handle = &p_handle;
796
797         /* 2. do a samr_Connect to get a policy handle */
798         status = dcerpc_samr_Connect(samr_pipe, tmp_ctx, &sc);
799         if (!NT_STATUS_IS_OK(status)) {
800                 r->out.error_string = talloc_asprintf(mem_ctx,
801                                                 "samr_Connect failed: %s",
802                                                 nt_errstr(status));
803                 talloc_free(tmp_ctx);
804                 return status;
805         }
806
807         /* Perhaps we didn't get a SID above, because we are against ncacn_ip_tcp */
808         if (!domain_sid) {
809                 struct lsa_String name;
810                 struct samr_LookupDomain l;
811                 name.string = domain_name;
812                 l.in.connect_handle = &p_handle;
813                 l.in.domain_name = &name;
814                 
815                 status = dcerpc_samr_LookupDomain(samr_pipe, tmp_ctx, &l);
816                 if (!NT_STATUS_IS_OK(status)) {
817                         r->out.error_string = talloc_asprintf(mem_ctx,
818                                                               "SAMR LookupDomain failed: %s",
819                                                               nt_errstr(status));
820                         talloc_free(tmp_ctx);
821                         return status;
822                 }
823                 domain_sid = l.out.sid;
824         }
825
826         /* prepare samr_OpenDomain */
827         ZERO_STRUCT(d_handle);
828         od.in.connect_handle = &p_handle;
829         od.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
830         od.in.sid = domain_sid;
831         od.out.domain_handle = &d_handle;
832
833         /* do a samr_OpenDomain to get a domain handle */
834         status = dcerpc_samr_OpenDomain(samr_pipe, tmp_ctx, &od);                       
835         if (!NT_STATUS_IS_OK(status)) {
836                 r->out.error_string = talloc_asprintf(mem_ctx,
837                                         "samr_OpenDomain for [%s] failed: %s",
838                                         r->in.domain_name,
839                                         nt_errstr(status));
840                 talloc_free(tmp_ctx);
841                 return status;
842         }
843         
844         /* prepare samr_CreateUser2 */
845         ZERO_STRUCTP(u_handle);
846         cu.in.domain_handle  = &d_handle;
847         cu.in.access_mask     = SEC_FLAG_MAXIMUM_ALLOWED;
848         samr_account_name.string = r->in.account_name;
849         cu.in.account_name    = &samr_account_name;
850         cu.in.acct_flags      = r->in.acct_type;
851         cu.out.user_handle    = u_handle;
852         cu.out.rid            = &rid;
853         cu.out.access_granted = &access_granted;
854
855         /* do a samr_CreateUser2 to get an account handle, or an error */
856         cu_status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                   
857         status = cu_status;
858         if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
859                 /* prepare samr_LookupNames */
860                 ln.in.domain_handle = &d_handle;
861                 ln.in.num_names = 1;
862                 ln.in.names = talloc_array(tmp_ctx, struct lsa_String, 1);
863                 if (!ln.in.names) {
864                         r->out.error_string = NULL;
865                         talloc_free(tmp_ctx);
866                         return NT_STATUS_NO_MEMORY;
867                 }
868                 ln.in.names[0].string = r->in.account_name;
869                 
870                 /* 5. do a samr_LookupNames to get the users rid */
871                 status = dcerpc_samr_LookupNames(samr_pipe, tmp_ctx, &ln);
872                 if (!NT_STATUS_IS_OK(status)) {
873                         r->out.error_string = talloc_asprintf(mem_ctx,
874                                                 "samr_LookupNames for [%s] failed: %s",
875                                                 r->in.account_name,
876                                                 nt_errstr(status));
877                         talloc_free(tmp_ctx);
878                         return status;
879                 }
880                 
881                 /* check if we got one RID for the user */
882                 if (ln.out.rids.count != 1) {
883                         r->out.error_string = talloc_asprintf(mem_ctx,
884                                                               "samr_LookupNames for [%s] returns %d RIDs\n",
885                                                               r->in.account_name, ln.out.rids.count);
886                         talloc_free(tmp_ctx);
887                         return NT_STATUS_INVALID_PARAMETER;
888                 }
889                 
890                 /* prepare samr_OpenUser */
891                 ZERO_STRUCTP(u_handle);
892                 ou.in.domain_handle = &d_handle;
893                 ou.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
894                 ou.in.rid = ln.out.rids.ids[0];
895                 rid = ou.in.rid;
896                 ou.out.user_handle = u_handle;
897                 
898                 /* 6. do a samr_OpenUser to get a user handle */
899                 status = dcerpc_samr_OpenUser(samr_pipe, tmp_ctx, &ou); 
900                 if (!NT_STATUS_IS_OK(status)) {
901                         r->out.error_string = talloc_asprintf(mem_ctx,
902                                                         "samr_OpenUser for [%s] failed: %s",
903                                                         r->in.account_name,
904                                                         nt_errstr(status));
905                         talloc_free(tmp_ctx);
906                         return status;
907                 }
908
909                 if (r->in.recreate_account) {
910                         struct samr_DeleteUser d;
911                         d.in.user_handle = u_handle;
912                         d.out.user_handle = u_handle;
913                         status = dcerpc_samr_DeleteUser(samr_pipe, mem_ctx, &d);
914                         if (!NT_STATUS_IS_OK(status)) {
915                                 r->out.error_string = talloc_asprintf(mem_ctx,
916                                                                       "samr_DeleteUser (for recreate) of [%s] failed: %s",
917                                                                       r->in.account_name,
918                                                                       nt_errstr(status));
919                                 talloc_free(tmp_ctx);
920                                 return status;
921                         }
922
923                         /* We want to recreate, so delete and another samr_CreateUser2 */
924                         
925                         /* &cu filled in above */
926                         status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                      
927                         if (!NT_STATUS_IS_OK(status)) {
928                                 r->out.error_string = talloc_asprintf(mem_ctx,
929                                                                       "samr_CreateUser2 (recreate) for [%s] failed: %s\n",
930                                                                       r->in.domain_name, nt_errstr(status));
931                                 talloc_free(tmp_ctx);
932                                 return status;
933                         }
934                 }
935         } else if (!NT_STATUS_IS_OK(status)) {
936                 r->out.error_string = talloc_asprintf(mem_ctx,
937                                                       "samr_CreateUser2 for [%s] failed: %s\n",
938                                                       r->in.domain_name, nt_errstr(status));
939                 talloc_free(tmp_ctx);
940                 return status;
941         }
942
943         /* prepare samr_QueryUserInfo (get flags) */
944         qui.in.user_handle = u_handle;
945         qui.in.level = 16;
946         
947         status = dcerpc_samr_QueryUserInfo(samr_pipe, tmp_ctx, &qui);
948         if (!NT_STATUS_IS_OK(status)) {
949                 r->out.error_string = talloc_asprintf(mem_ctx,
950                                                 "samr_QueryUserInfo for [%s] failed: %s",
951                                                 r->in.account_name,
952                                                 nt_errstr(status));
953                 talloc_free(tmp_ctx);
954                 return status;
955         }
956         
957         if (!qui.out.info) {
958                 status = NT_STATUS_INVALID_PARAMETER;
959                 r->out.error_string
960                         = talloc_asprintf(mem_ctx,
961                                           "samr_QueryUserInfo failed to return qui.out.info for [%s]: %s\n",
962                                           r->in.account_name, nt_errstr(status));
963                 talloc_free(tmp_ctx);
964                 return status;
965         }
966
967         old_acct_flags = (qui.out.info->info16.acct_flags & (ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST));
968         /* Possibly bail if the account is of the wrong type */
969         if (old_acct_flags
970             != r->in.acct_type) {
971                 const char *old_account_type, *new_account_type;
972                 switch (old_acct_flags) {
973                 case ACB_WSTRUST:
974                         old_account_type = "domain member (member)";
975                         break;
976                 case ACB_SVRTRUST:
977                         old_account_type = "domain controller (bdc)";
978                         break;
979                 case ACB_DOMTRUST:
980                         old_account_type = "trusted domain";
981                         break;
982                 default:
983                         return NT_STATUS_INVALID_PARAMETER;
984                 }
985                 switch (r->in.acct_type) {
986                 case ACB_WSTRUST:
987                         new_account_type = "domain member (member)";
988                         break;
989                 case ACB_SVRTRUST:
990                         new_account_type = "domain controller (bdc)";
991                         break;
992                 case ACB_DOMTRUST:
993                         new_account_type = "trusted domain";
994                         break;
995                 default:
996                         return NT_STATUS_INVALID_PARAMETER;
997                 }
998
999                 if (!NT_STATUS_EQUAL(cu_status, NT_STATUS_USER_EXISTS)) {
1000                         /* We created a new user, but they didn't come out the right type?!? */
1001                         r->out.error_string
1002                                 = talloc_asprintf(mem_ctx,
1003                                                   "We asked to create a new machine account (%s) of type %s, but we got an account of type %s.  This is unexpected.  Perhaps delete the account and try again.\n",
1004                                                   r->in.account_name, new_account_type, old_account_type);
1005                         talloc_free(tmp_ctx);
1006                         return NT_STATUS_INVALID_PARAMETER;
1007                 } else {
1008                         /* The account is of the wrong type, so bail */
1009
1010                         /* TODO: We should allow a --force option to override, and redo this from the top setting r.in.recreate_account */
1011                         r->out.error_string
1012                                 = talloc_asprintf(mem_ctx,
1013                                                   "The machine account (%s) already exists in the domain %s, but is a %s.  You asked to join as a %s.  Please delete the account and try again.\n",
1014                                                   r->in.account_name, domain_name, old_account_type, new_account_type);
1015                         talloc_free(tmp_ctx);
1016                         return NT_STATUS_USER_EXISTS;
1017                 }
1018         } else {
1019                 acct_flags = qui.out.info->info16.acct_flags;
1020         }
1021         
1022         acct_flags = (acct_flags & ~ACB_DISABLED);
1023
1024         /* Find out what password policy this user has */
1025         pwp.in.user_handle = u_handle;
1026
1027         status = dcerpc_samr_GetUserPwInfo(samr_pipe, tmp_ctx, &pwp);                           
1028         if (NT_STATUS_IS_OK(status)) {
1029                 policy_min_pw_len = pwp.out.info.min_password_length;
1030         }
1031         
1032         /* Grab a password of that minimum length */
1033         
1034         password_str = generate_random_str(tmp_ctx, MAX(8, policy_min_pw_len)); 
1035
1036         r2.samr_handle.level            = LIBNET_SET_PASSWORD_SAMR_HANDLE;
1037         r2.samr_handle.in.account_name  = r->in.account_name;
1038         r2.samr_handle.in.newpassword   = password_str;
1039         r2.samr_handle.in.user_handle   = u_handle;
1040         r2.samr_handle.in.dcerpc_pipe   = samr_pipe;
1041
1042         status = libnet_SetPassword(ctx, tmp_ctx, &r2); 
1043         if (!NT_STATUS_IS_OK(status)) {
1044                 r->out.error_string = talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
1045                 talloc_free(tmp_ctx);
1046                 return status;
1047         }
1048
1049         /* reset flags (if required) */
1050         if (acct_flags != qui.out.info->info16.acct_flags) {    
1051                 ZERO_STRUCT(u_info);
1052                 u_info.info16.acct_flags = acct_flags;
1053
1054                 sui.in.user_handle = u_handle;
1055                 sui.in.info = &u_info;
1056                 sui.in.level = 16;
1057                 
1058                 dcerpc_samr_SetUserInfo(samr_pipe, tmp_ctx, &sui);
1059                 if (!NT_STATUS_IS_OK(status)) {
1060                         r->out.error_string = talloc_asprintf(mem_ctx,
1061                                                         "samr_SetUserInfo for [%s] failed to remove ACB_DISABLED flag: %s",
1062                                                         r->in.account_name,
1063                                                         nt_errstr(status));
1064                         talloc_free(tmp_ctx);
1065                         return status;
1066                 }
1067         }
1068
1069         account_sid = dom_sid_add_rid(mem_ctx, domain_sid, rid);
1070         if (!account_sid) {
1071                 r->out.error_string = NULL;
1072                 talloc_free(tmp_ctx);
1073                 return NT_STATUS_NO_MEMORY;
1074         }
1075
1076         /* Finish out by pushing various bits of status data out for the caller to use */
1077         r->out.join_password = password_str;
1078         talloc_steal(mem_ctx, password_str);
1079
1080         r->out.domain_sid = domain_sid;
1081         talloc_steal(mem_ctx, domain_sid);
1082
1083         r->out.account_sid = account_sid;
1084         talloc_steal(mem_ctx, account_sid);
1085
1086         r->out.domain_name = domain_name;
1087         talloc_steal(mem_ctx, domain_name);
1088         r->out.realm = realm;
1089         talloc_steal(mem_ctx, realm);
1090         r->out.lsa_pipe = lsa_pipe;
1091         talloc_steal(mem_ctx, lsa_pipe);
1092         r->out.samr_pipe = samr_pipe;
1093         talloc_steal(mem_ctx, samr_pipe);
1094         r->out.samr_binding = samr_binding;
1095         talloc_steal(mem_ctx, samr_binding);
1096         r->out.user_handle = u_handle;
1097         talloc_steal(mem_ctx, u_handle);
1098         r->out.error_string = r2.samr_handle.out.error_string;
1099         talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
1100         r->out.kvno = 0;
1101         r->out.server_dn_str = NULL;
1102         talloc_free(tmp_ctx); 
1103
1104         /* Now, if it was AD, then we want to start looking changing a
1105          * few more things.  Otherwise, we are done. */
1106         if (realm) {
1107                 status = libnet_JoinADSDomain(ctx, r);
1108                 return status;
1109         }
1110
1111         return status;
1112 }
1113
1114 static NTSTATUS libnet_Join_primary_domain(struct libnet_context *ctx, 
1115                                            TALLOC_CTX *mem_ctx, 
1116                                            struct libnet_Join *r)
1117 {
1118         NTSTATUS status;
1119         TALLOC_CTX *tmp_mem;
1120         struct libnet_JoinDomain *r2;
1121         int ret, rtn;
1122         struct ldb_context *ldb;
1123         const struct ldb_dn *base_dn;
1124         struct ldb_message **msgs, *msg;
1125         const char *sct;
1126         const char * const attrs[] = {
1127                 "whenChanged",
1128                 "secret",
1129                 "priorSecret",
1130                 "priorChanged",
1131                 NULL
1132         };
1133         uint32_t acct_type = 0;
1134         const char *account_name;
1135         const char *netbios_name;
1136         char *filter;
1137         
1138         r->out.error_string = NULL;
1139
1140         tmp_mem = talloc_new(mem_ctx);
1141         if (!tmp_mem) {
1142                 return NT_STATUS_NO_MEMORY;
1143         }
1144
1145         r2 = talloc(tmp_mem, struct libnet_JoinDomain);
1146         if (!r2) {
1147                 r->out.error_string = NULL;
1148                 talloc_free(tmp_mem);
1149                 return NT_STATUS_NO_MEMORY;
1150         }
1151         
1152         if (r->in.secure_channel_type == SEC_CHAN_BDC) {
1153                 acct_type = ACB_SVRTRUST;
1154         } else if (r->in.secure_channel_type == SEC_CHAN_WKSTA) {
1155                 acct_type = ACB_WSTRUST;
1156         } else {
1157                 r->out.error_string = NULL;
1158                 talloc_free(tmp_mem);   
1159                 return NT_STATUS_INVALID_PARAMETER;
1160         }
1161
1162         if ((r->in.netbios_name != NULL) && (r->in.level != LIBNET_JOIN_AUTOMATIC)) {
1163                 netbios_name = r->in.netbios_name;
1164         } else {
1165                 netbios_name = talloc_asprintf(tmp_mem, "%s", lp_netbios_name());
1166                 if (!netbios_name) {
1167                         r->out.error_string = NULL;
1168                         talloc_free(tmp_mem);
1169                         return NT_STATUS_NO_MEMORY;
1170                 }
1171         }
1172
1173         account_name = talloc_asprintf(tmp_mem, "%s$", netbios_name);
1174         if (!account_name) {
1175                 r->out.error_string = NULL;
1176                 talloc_free(tmp_mem);
1177                 return NT_STATUS_NO_MEMORY;
1178         }
1179         
1180         /*
1181          * Local secrets are stored in secrets.ldb 
1182          * open it to make sure we can write the info into it after the join
1183          */
1184         ldb = secrets_db_connect(tmp_mem);
1185         if (!ldb) {
1186                 r->out.error_string
1187                         = talloc_asprintf(mem_ctx, 
1188                                           "Could not open secrets database\n");
1189                 talloc_free(tmp_mem);
1190                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1191         }
1192
1193         /*
1194          * join the domain
1195          */
1196         ZERO_STRUCTP(r2);
1197         r2->in.domain_name      = r->in.domain_name;
1198         r2->in.account_name     = account_name;
1199         r2->in.netbios_name     = netbios_name;
1200         r2->in.level            = LIBNET_JOINDOMAIN_AUTOMATIC;
1201         r2->in.acct_type        = acct_type;
1202         r2->in.recreate_account = False;
1203         status = libnet_JoinDomain(ctx, r2, r2);
1204         if (!NT_STATUS_IS_OK(status)) {
1205                 r->out.error_string = talloc_steal(mem_ctx, r2->out.error_string);
1206                 talloc_free(tmp_mem);
1207                 return status;
1208         }
1209         
1210         /*
1211          * now prepare the record for secrets.ldb
1212          */
1213         sct = talloc_asprintf(tmp_mem, "%d", r->in.secure_channel_type); 
1214         if (!sct) {
1215                 r->out.error_string = NULL;
1216                 talloc_free(tmp_mem);
1217                 return NT_STATUS_NO_MEMORY;
1218         }
1219         
1220         msg = ldb_msg_new(tmp_mem);
1221         if (!msg) {
1222                 r->out.error_string = NULL;
1223                 talloc_free(tmp_mem);
1224                 return NT_STATUS_NO_MEMORY;
1225         }
1226
1227         base_dn = ldb_dn_explode(tmp_mem, "cn=Primary Domains");
1228         if (!base_dn) {
1229                 r->out.error_string = NULL;
1230                 talloc_free(tmp_mem);
1231                 return NT_STATUS_NO_MEMORY;
1232         }
1233
1234         msg->dn = ldb_dn_build_child(tmp_mem, "flatname", r2->out.domain_name, base_dn);
1235         if (!msg->dn) {
1236                 r->out.error_string = NULL;
1237                 talloc_free(tmp_mem);
1238                 return NT_STATUS_NO_MEMORY;
1239         }
1240         
1241         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "flatname", r2->out.domain_name);
1242         if (rtn == -1) {
1243                 r->out.error_string = NULL;
1244                 talloc_free(tmp_mem);
1245                 return NT_STATUS_NO_MEMORY;
1246         }
1247
1248         if (r2->out.realm) {
1249                 rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "realm", r2->out.realm);
1250                 if (rtn == -1) {
1251                         r->out.error_string = NULL;
1252                         talloc_free(tmp_mem);
1253                         return NT_STATUS_NO_MEMORY;
1254                 }
1255
1256                 rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "objectClass", "primaryDomain");
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         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "objectClass", "primaryDomain");
1265         if (rtn == -1) {
1266                 r->out.error_string = NULL;
1267                 talloc_free(tmp_mem);
1268                 return NT_STATUS_NO_MEMORY;
1269         }
1270
1271         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secret", r2->out.join_password);
1272         if (rtn == -1) {
1273                 r->out.error_string = NULL;
1274                 talloc_free(tmp_mem);
1275                 return NT_STATUS_NO_MEMORY;
1276         }
1277
1278         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "samAccountName", r2->in.account_name);
1279         if (rtn == -1) {
1280                 r->out.error_string = NULL;
1281                 talloc_free(tmp_mem);
1282                 return NT_STATUS_NO_MEMORY;
1283         }
1284
1285         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secureChannelType", sct);
1286         if (rtn == -1) {
1287                 r->out.error_string = NULL;
1288                 talloc_free(tmp_mem);
1289                 return NT_STATUS_NO_MEMORY;
1290         }
1291
1292         if (r2->out.kvno) {
1293                 rtn = samdb_msg_add_uint(ldb, tmp_mem, msg, "msDS-KeyVersionNumber",
1294                                          r2->out.kvno);
1295                 if (rtn == -1) {
1296                         r->out.error_string = NULL;
1297                         talloc_free(tmp_mem);
1298                         return NT_STATUS_NO_MEMORY;
1299                 }
1300         }
1301
1302         if (r2->out.domain_sid) {
1303                 rtn = samdb_msg_add_dom_sid(ldb, tmp_mem, msg, "objectSid",
1304                                             r2->out.domain_sid);
1305                 if (rtn == -1) {
1306                         r->out.error_string = NULL;
1307                         talloc_free(tmp_mem);
1308                         return NT_STATUS_NO_MEMORY;
1309                 }
1310         }
1311
1312         /* 
1313          * search for the secret record
1314          * - remove the records we find
1315          * - and fetch the old secret and store it under priorSecret
1316          */
1317         ret = gendb_search(ldb,
1318                            tmp_mem, base_dn,
1319                            &msgs, attrs,
1320                            "(|" SECRETS_PRIMARY_DOMAIN_FILTER "(realm=%s))",
1321                            r2->out.domain_name, r2->out.realm);
1322         if (ret == 0) {
1323         } else if (ret == -1) {
1324                 r->out.error_string
1325                         = talloc_asprintf(mem_ctx, 
1326                                           "Search for domain: %s and realm: %s failed: %s", 
1327                                           r2->out.domain_name, r2->out.realm, ldb_errstring(ldb));
1328                 talloc_free(tmp_mem);
1329                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1330         } else {
1331                 const struct ldb_val *prior_secret;
1332                 const struct ldb_val *prior_modified_time;
1333                 int i;
1334
1335                 for (i = 0; i < ret; i++) {
1336                         ldb_delete(ldb, msgs[i]->dn);
1337                 }
1338
1339                 prior_secret = ldb_msg_find_ldb_val(msgs[0], "secret");
1340                 if (prior_secret) {
1341                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorSecret", prior_secret);
1342                         if (rtn == -1) {
1343                                 r->out.error_string = NULL;
1344                                 talloc_free(tmp_mem);
1345                                 return NT_STATUS_NO_MEMORY;
1346                         }
1347                 }
1348                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secret", r2->out.join_password);
1349                 if (rtn == -1) {
1350                         r->out.error_string = NULL;
1351                         talloc_free(tmp_mem);
1352                         return NT_STATUS_NO_MEMORY;
1353                 }
1354
1355                 prior_modified_time = ldb_msg_find_ldb_val(msgs[0], 
1356                                                            "whenChanged");
1357                 if (prior_modified_time) {
1358                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorWhenChanged", 
1359                                                   prior_modified_time);
1360                         if (rtn == -1) {
1361                                 r->out.error_string = NULL;
1362                                 talloc_free(tmp_mem);
1363                                 return NT_STATUS_NO_MEMORY;
1364                         }
1365                 }
1366
1367                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "samAccountName", r2->in.account_name);
1368                 if (rtn == -1) {
1369                         r->out.error_string = NULL;
1370                         talloc_free(tmp_mem);
1371                         return NT_STATUS_NO_MEMORY;
1372                 }
1373
1374                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secureChannelType", sct);
1375                 if (rtn == -1) {
1376                         r->out.error_string = NULL;
1377                         talloc_free(tmp_mem);
1378                         return NT_STATUS_NO_MEMORY;
1379                 }
1380         }
1381
1382         /* create the secret */
1383         ret = samdb_add(ldb, tmp_mem, msg);
1384         if (ret != 0) {
1385                 r->out.error_string = talloc_asprintf(mem_ctx, "Failed to create secret record %s\n", 
1386                                                       ldb_dn_linearize(ldb, msg->dn));
1387                 talloc_free(tmp_mem);
1388                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1389         }
1390
1391         if (r2->out.realm) {
1392                 struct cli_credentials *creds;
1393                 /* Make a credentials structure from it */
1394                 creds = cli_credentials_init(mem_ctx);
1395                 if (!creds) {
1396                         r->out.error_string = NULL;
1397                         talloc_free(tmp_mem);
1398                         return NT_STATUS_NO_MEMORY;
1399                 }
1400                 cli_credentials_set_conf(creds);
1401                 filter = talloc_asprintf(mem_ctx, "dn=%s", ldb_dn_linearize(mem_ctx, msg->dn));
1402                 status = cli_credentials_set_secrets(creds, NULL, filter);
1403                 if (!NT_STATUS_IS_OK(status)) {
1404                         r->out.error_string = talloc_asprintf(mem_ctx, "Failed to read secrets for keytab update for %s\n", 
1405                                                               filter);
1406                         talloc_free(tmp_mem);
1407                         return status;
1408                 } 
1409                 ret = cli_credentials_update_keytab(creds);
1410                 if (ret != 0) {
1411                         r->out.error_string = talloc_asprintf(mem_ctx, "Failed to update keytab for %s\n", 
1412                                                               filter);
1413                         talloc_free(tmp_mem);
1414                         return NT_STATUS_UNSUCCESSFUL;
1415                 }
1416         }
1417
1418         /* move all out parameter to the callers TALLOC_CTX */
1419         r->out.error_string     = NULL;
1420         r->out.join_password    = r2->out.join_password;
1421         talloc_steal(mem_ctx, r2->out.join_password);
1422         r->out.domain_sid       = r2->out.domain_sid;
1423         talloc_steal(mem_ctx, r2->out.domain_sid);
1424         r->out.domain_name      = r2->out.domain_name;
1425         talloc_steal(mem_ctx, r2->out.domain_name);
1426         talloc_free(tmp_mem);
1427         return NT_STATUS_OK;
1428 }
1429
1430 NTSTATUS libnet_Join(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_Join *r)
1431 {
1432         switch (r->in.secure_channel_type) {
1433                 case SEC_CHAN_WKSTA:
1434                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1435                 case SEC_CHAN_BDC:
1436                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1437                 case SEC_CHAN_DOMAIN:
1438                         break;
1439         }
1440
1441         r->out.error_string = talloc_asprintf(mem_ctx,
1442                                 "Invalid secure channel type specified (%08X) attempting to join domain %s",
1443                                 r->in.secure_channel_type, r->in.domain_name);
1444         return NT_STATUS_INVALID_PARAMETER;
1445 }
1446
1447