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