r12903: Factor out a new routine libnet_RpcConnectDCInfo, to both connect to
[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_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 "passdb/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  * - connect to the LSA pipe, to try and find out information about the domain
548  * - create a secondary connection to SAMR pipe
549  * - do a samr_Connect to get a policy handle
550  * - do a samr_LookupDomain to get the domain sid
551  * - do a samr_OpenDomain to get a domain handle
552  * - do a samr_CreateAccount to try and get a new account 
553  * 
554  * If that fails, do:
555  * - do a samr_LookupNames to get the users rid
556  * - do a samr_OpenUser to get a user handle
557  * - potentially delete and recreate the user
558  * - assert the account is of the right type with samrQueryUserInfo
559  * 
560  * - call libnet_SetPassword_samr_handle to set the password
561  *
562  * - do a samrSetUserInfo to set the account flags
563  * - 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
572         struct libnet_RpcConnectDCInfo *connect_with_info;
573         struct dcerpc_pipe *samr_pipe;
574
575         struct samr_Connect sc;
576         struct policy_handle p_handle;
577         struct samr_OpenDomain od;
578         struct policy_handle d_handle;
579         struct samr_LookupNames ln;
580         struct samr_OpenUser ou;
581         struct samr_CreateUser2 cu;
582         struct policy_handle *u_handle = NULL;
583         struct samr_QueryUserInfo qui;
584         struct samr_SetUserInfo sui;
585         union samr_UserInfo u_info;
586         union libnet_SetPassword r2;
587         struct samr_GetUserPwInfo pwp;
588         struct lsa_String samr_account_name;
589         
590         uint32_t acct_flags, old_acct_flags;
591         uint32_t rid, access_granted;
592         int policy_min_pw_len = 0;
593
594         struct dom_sid *account_sid = NULL;
595         const char *password_str = NULL;
596         const char *realm = NULL; /* Also flag for remote being AD */
597         
598         
599         r->out.error_string = NULL;
600         r2.samr_handle.out.error_string = NULL;
601         
602         tmp_ctx = talloc_named(mem_ctx, 0, "libnet_Join temp context");
603         if (!tmp_ctx) {
604                 r->out.error_string = NULL;
605                 return NT_STATUS_NO_MEMORY;
606         }
607         
608         u_handle = talloc(tmp_ctx, struct policy_handle);
609         if (!u_handle) {
610                 r->out.error_string = NULL;
611                 talloc_free(tmp_ctx);
612                 return NT_STATUS_NO_MEMORY;
613         }
614         
615         connect_with_info = talloc(tmp_ctx, struct libnet_RpcConnectDCInfo);
616         if (!connect_with_info) {
617                 r->out.error_string = NULL;
618                 talloc_free(tmp_ctx);
619                 return NT_STATUS_NO_MEMORY;
620         }
621
622         /* prepare connect to the LSA pipe of PDC */
623         if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
624                 connect_with_info->level      = LIBNET_RPC_CONNECT_PDC;
625                 connect_with_info->in.name    = r->in.domain_name;
626         } else {
627                 connect_with_info->level      = LIBNET_RPC_CONNECT_BINDING;
628                 connect_with_info->in.binding = r->in.binding;
629         }
630
631         connect_with_info->in.dcerpc_iface    = &dcerpc_table_samr;
632         /*
633           establish a SAMR connection, on the same CIFS transport
634         */
635         
636         status = libnet_RpcConnectDCInfo(ctx, connect_with_info);
637         if (!NT_STATUS_IS_OK(status)) {
638                 if (r->in.binding) {
639                         r->out.error_string = talloc_asprintf(mem_ctx,
640                                                               "Connection to SAMR pipe of DC %s failed: %s",
641                                                               r->in.binding, connect_with_info->out.error_string);
642                 } else {
643                         r->out.error_string = talloc_asprintf(mem_ctx,
644                                                               "Connection to SAMR pipe of PDC for %s failed: %s",
645                                                               r->in.domain_name, connect_with_info->out.error_string);
646                 }
647                 talloc_free(tmp_ctx);
648                 return status;
649         }
650
651         samr_pipe = connect_with_info->out.dcerpc_pipe, 
652
653         status = dcerpc_pipe_auth(samr_pipe,
654                                   connect_with_info->out.dcerpc_pipe->binding, 
655                                   &dcerpc_table_samr, ctx->cred);
656         if (!NT_STATUS_IS_OK(status)) {
657                 r->out.error_string = talloc_asprintf(mem_ctx,
658                                                 "SAMR bind failed: %s",
659                                                 nt_errstr(status));
660                 talloc_free(tmp_ctx);
661                 return status;
662         }
663
664         /* prepare samr_Connect */
665         ZERO_STRUCT(p_handle);
666         sc.in.system_name = NULL;
667         sc.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
668         sc.out.connect_handle = &p_handle;
669
670         /* 2. do a samr_Connect to get a policy handle */
671         status = dcerpc_samr_Connect(samr_pipe, tmp_ctx, &sc);
672         if (!NT_STATUS_IS_OK(status)) {
673                 r->out.error_string = talloc_asprintf(mem_ctx,
674                                                 "samr_Connect failed: %s",
675                                                 nt_errstr(status));
676                 talloc_free(tmp_ctx);
677                 return status;
678         }
679
680         /* If this is a connection on ncacn_ip_tcp to Win2k3 SP1, we don't get back this useful info */
681         if (!connect_with_info->out.domain_name) {
682                 if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
683                         connect_with_info->out.domain_name = talloc_strdup(tmp_ctx, r->in.domain_name);
684                 } else {
685                         /* Bugger, we just lost our way to automaticly find the domain name */
686                         connect_with_info->out.domain_name = talloc_strdup(tmp_ctx, lp_workgroup());
687                 }
688         }
689
690         /* Perhaps we didn't get a SID above, because we are against ncacn_ip_tcp */
691         if (!connect_with_info->out.domain_sid) {
692                 struct lsa_String name;
693                 struct samr_LookupDomain l;
694                 name.string = connect_with_info->out.domain_name;
695                 l.in.connect_handle = &p_handle;
696                 l.in.domain_name = &name;
697                 
698                 status = dcerpc_samr_LookupDomain(samr_pipe, tmp_ctx, &l);
699                 if (!NT_STATUS_IS_OK(status)) {
700                         r->out.error_string = talloc_asprintf(mem_ctx,
701                                                               "SAMR LookupDomain failed: %s",
702                                                               nt_errstr(status));
703                         talloc_free(tmp_ctx);
704                         return status;
705                 }
706                 connect_with_info->out.domain_sid = l.out.sid;
707         }
708
709         /* prepare samr_OpenDomain */
710         ZERO_STRUCT(d_handle);
711         od.in.connect_handle = &p_handle;
712         od.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
713         od.in.sid = connect_with_info->out.domain_sid;
714         od.out.domain_handle = &d_handle;
715
716         /* do a samr_OpenDomain to get a domain handle */
717         status = dcerpc_samr_OpenDomain(samr_pipe, tmp_ctx, &od);                       
718         if (!NT_STATUS_IS_OK(status)) {
719                 r->out.error_string = talloc_asprintf(mem_ctx,
720                                                       "samr_OpenDomain for [%s] failed: %s",
721                                                       dom_sid_string(tmp_ctx, connect_with_info->out.domain_sid),
722                                                       nt_errstr(status));
723                 talloc_free(tmp_ctx);
724                 return status;
725         }
726         
727         /* prepare samr_CreateUser2 */
728         ZERO_STRUCTP(u_handle);
729         cu.in.domain_handle  = &d_handle;
730         cu.in.access_mask     = SEC_FLAG_MAXIMUM_ALLOWED;
731         samr_account_name.string = r->in.account_name;
732         cu.in.account_name    = &samr_account_name;
733         cu.in.acct_flags      = r->in.acct_type;
734         cu.out.user_handle    = u_handle;
735         cu.out.rid            = &rid;
736         cu.out.access_granted = &access_granted;
737
738         /* do a samr_CreateUser2 to get an account handle, or an error */
739         cu_status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                   
740         status = cu_status;
741         if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
742                 /* prepare samr_LookupNames */
743                 ln.in.domain_handle = &d_handle;
744                 ln.in.num_names = 1;
745                 ln.in.names = talloc_array(tmp_ctx, struct lsa_String, 1);
746                 if (!ln.in.names) {
747                         r->out.error_string = NULL;
748                         talloc_free(tmp_ctx);
749                         return NT_STATUS_NO_MEMORY;
750                 }
751                 ln.in.names[0].string = r->in.account_name;
752                 
753                 /* 5. do a samr_LookupNames to get the users rid */
754                 status = dcerpc_samr_LookupNames(samr_pipe, tmp_ctx, &ln);
755                 if (!NT_STATUS_IS_OK(status)) {
756                         r->out.error_string = talloc_asprintf(mem_ctx,
757                                                 "samr_LookupNames for [%s] failed: %s",
758                                                 r->in.account_name,
759                                                 nt_errstr(status));
760                         talloc_free(tmp_ctx);
761                         return status;
762                 }
763                 
764                 /* check if we got one RID for the user */
765                 if (ln.out.rids.count != 1) {
766                         r->out.error_string = talloc_asprintf(mem_ctx,
767                                                               "samr_LookupNames for [%s] returns %d RIDs\n",
768                                                               r->in.account_name, ln.out.rids.count);
769                         talloc_free(tmp_ctx);
770                         return NT_STATUS_INVALID_PARAMETER;
771                 }
772                 
773                 /* prepare samr_OpenUser */
774                 ZERO_STRUCTP(u_handle);
775                 ou.in.domain_handle = &d_handle;
776                 ou.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
777                 ou.in.rid = ln.out.rids.ids[0];
778                 rid = ou.in.rid;
779                 ou.out.user_handle = u_handle;
780                 
781                 /* 6. do a samr_OpenUser to get a user handle */
782                 status = dcerpc_samr_OpenUser(samr_pipe, tmp_ctx, &ou); 
783                 if (!NT_STATUS_IS_OK(status)) {
784                         r->out.error_string = talloc_asprintf(mem_ctx,
785                                                         "samr_OpenUser for [%s] failed: %s",
786                                                         r->in.account_name,
787                                                         nt_errstr(status));
788                         talloc_free(tmp_ctx);
789                         return status;
790                 }
791
792                 if (r->in.recreate_account) {
793                         struct samr_DeleteUser d;
794                         d.in.user_handle = u_handle;
795                         d.out.user_handle = u_handle;
796                         status = dcerpc_samr_DeleteUser(samr_pipe, mem_ctx, &d);
797                         if (!NT_STATUS_IS_OK(status)) {
798                                 r->out.error_string = talloc_asprintf(mem_ctx,
799                                                                       "samr_DeleteUser (for recreate) of [%s] failed: %s",
800                                                                       r->in.account_name,
801                                                                       nt_errstr(status));
802                                 talloc_free(tmp_ctx);
803                                 return status;
804                         }
805
806                         /* We want to recreate, so delete and another samr_CreateUser2 */
807                         
808                         /* &cu filled in above */
809                         status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                      
810                         if (!NT_STATUS_IS_OK(status)) {
811                                 r->out.error_string = talloc_asprintf(mem_ctx,
812                                                                       "samr_CreateUser2 (recreate) for [%s] failed: %s\n",
813                                                                       r->in.domain_name, nt_errstr(status));
814                                 talloc_free(tmp_ctx);
815                                 return status;
816                         }
817                 }
818         } else if (!NT_STATUS_IS_OK(status)) {
819                 r->out.error_string = talloc_asprintf(mem_ctx,
820                                                       "samr_CreateUser2 for [%s] failed: %s\n",
821                                                       r->in.domain_name, nt_errstr(status));
822                 talloc_free(tmp_ctx);
823                 return status;
824         }
825
826         /* prepare samr_QueryUserInfo (get flags) */
827         qui.in.user_handle = u_handle;
828         qui.in.level = 16;
829         
830         status = dcerpc_samr_QueryUserInfo(samr_pipe, tmp_ctx, &qui);
831         if (!NT_STATUS_IS_OK(status)) {
832                 r->out.error_string = talloc_asprintf(mem_ctx,
833                                                 "samr_QueryUserInfo for [%s] failed: %s",
834                                                 r->in.account_name,
835                                                 nt_errstr(status));
836                 talloc_free(tmp_ctx);
837                 return status;
838         }
839         
840         if (!qui.out.info) {
841                 status = NT_STATUS_INVALID_PARAMETER;
842                 r->out.error_string
843                         = talloc_asprintf(mem_ctx,
844                                           "samr_QueryUserInfo failed to return qui.out.info for [%s]: %s\n",
845                                           r->in.account_name, nt_errstr(status));
846                 talloc_free(tmp_ctx);
847                 return status;
848         }
849
850         old_acct_flags = (qui.out.info->info16.acct_flags & (ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST));
851         /* Possibly bail if the account is of the wrong type */
852         if (old_acct_flags
853             != r->in.acct_type) {
854                 const char *old_account_type, *new_account_type;
855                 switch (old_acct_flags) {
856                 case ACB_WSTRUST:
857                         old_account_type = "domain member (member)";
858                         break;
859                 case ACB_SVRTRUST:
860                         old_account_type = "domain controller (bdc)";
861                         break;
862                 case ACB_DOMTRUST:
863                         old_account_type = "trusted domain";
864                         break;
865                 default:
866                         return NT_STATUS_INVALID_PARAMETER;
867                 }
868                 switch (r->in.acct_type) {
869                 case ACB_WSTRUST:
870                         new_account_type = "domain member (member)";
871                         break;
872                 case ACB_SVRTRUST:
873                         new_account_type = "domain controller (bdc)";
874                         break;
875                 case ACB_DOMTRUST:
876                         new_account_type = "trusted domain";
877                         break;
878                 default:
879                         return NT_STATUS_INVALID_PARAMETER;
880                 }
881
882                 if (!NT_STATUS_EQUAL(cu_status, NT_STATUS_USER_EXISTS)) {
883                         /* We created a new user, but they didn't come out the right type?!? */
884                         r->out.error_string
885                                 = talloc_asprintf(mem_ctx,
886                                                   "We asked to create a new machine account (%s) of type %s, "
887                                                   "but we got an account of type %s.  This is unexpected.  "
888                                                   "Perhaps delete the account and try again.\n",
889                                                   r->in.account_name, new_account_type, old_account_type);
890                         talloc_free(tmp_ctx);
891                         return NT_STATUS_INVALID_PARAMETER;
892                 } else {
893                         /* The account is of the wrong type, so bail */
894
895                         /* TODO: We should allow a --force option to override, and redo this from the top setting r.in.recreate_account */
896                         r->out.error_string
897                                 = talloc_asprintf(mem_ctx,
898                                                   "The machine account (%s) already exists in the domain %s, "
899                                                   "but is a %s.  You asked to join as a %s.  Please delete "
900                                                   "the account and try again.\n",
901                                                   r->in.account_name, connect_with_info->out.domain_name, old_account_type, new_account_type);
902                         talloc_free(tmp_ctx);
903                         return NT_STATUS_USER_EXISTS;
904                 }
905         } else {
906                 acct_flags = qui.out.info->info16.acct_flags;
907         }
908         
909         acct_flags = (acct_flags & ~ACB_DISABLED);
910
911         /* Find out what password policy this user has */
912         pwp.in.user_handle = u_handle;
913
914         status = dcerpc_samr_GetUserPwInfo(samr_pipe, tmp_ctx, &pwp);                           
915         if (NT_STATUS_IS_OK(status)) {
916                 policy_min_pw_len = pwp.out.info.min_password_length;
917         }
918         
919         /* Grab a password of that minimum length */
920         
921         password_str = generate_random_str(tmp_ctx, MAX(8, policy_min_pw_len)); 
922
923         r2.samr_handle.level            = LIBNET_SET_PASSWORD_SAMR_HANDLE;
924         r2.samr_handle.in.account_name  = r->in.account_name;
925         r2.samr_handle.in.newpassword   = password_str;
926         r2.samr_handle.in.user_handle   = u_handle;
927         r2.samr_handle.in.dcerpc_pipe   = samr_pipe;
928
929         status = libnet_SetPassword(ctx, tmp_ctx, &r2); 
930         if (!NT_STATUS_IS_OK(status)) {
931                 r->out.error_string = talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
932                 talloc_free(tmp_ctx);
933                 return status;
934         }
935
936         /* reset flags (if required) */
937         if (acct_flags != qui.out.info->info16.acct_flags) {
938                 ZERO_STRUCT(u_info);
939                 u_info.info16.acct_flags = acct_flags;
940
941                 sui.in.user_handle = u_handle;
942                 sui.in.info = &u_info;
943                 sui.in.level = 16;
944                 
945                 dcerpc_samr_SetUserInfo(samr_pipe, tmp_ctx, &sui);
946                 if (!NT_STATUS_IS_OK(status)) {
947                         r->out.error_string = talloc_asprintf(mem_ctx,
948                                                         "samr_SetUserInfo for [%s] failed to remove ACB_DISABLED flag: %s",
949                                                         r->in.account_name,
950                                                         nt_errstr(status));
951                         talloc_free(tmp_ctx);
952                         return status;
953                 }
954         }
955
956         account_sid = dom_sid_add_rid(mem_ctx, connect_with_info->out.domain_sid, rid);
957         if (!account_sid) {
958                 r->out.error_string = NULL;
959                 talloc_free(tmp_ctx);
960                 return NT_STATUS_NO_MEMORY;
961         }
962
963         /* Finish out by pushing various bits of status data out for the caller to use */
964         r->out.join_password = password_str;
965         talloc_steal(mem_ctx, r->out.join_password);
966
967         r->out.domain_sid = connect_with_info->out.domain_sid;
968         talloc_steal(mem_ctx, r->out.domain_sid);
969
970         r->out.account_sid = account_sid;
971         talloc_steal(mem_ctx, r->out.account_sid);
972
973         r->out.domain_name = connect_with_info->out.domain_name;
974         talloc_steal(mem_ctx, r->out.domain_name);
975         r->out.realm = connect_with_info->out.realm;
976         talloc_steal(mem_ctx, r->out.realm);
977         r->out.samr_pipe = samr_pipe;
978         talloc_steal(mem_ctx, samr_pipe);
979         r->out.samr_binding = samr_pipe->binding;
980         talloc_steal(mem_ctx, r->out.samr_binding);
981         r->out.user_handle = u_handle;
982         talloc_steal(mem_ctx, u_handle);
983         r->out.error_string = r2.samr_handle.out.error_string;
984         talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
985         r->out.kvno = 0;
986         r->out.server_dn_str = NULL;
987         talloc_free(tmp_ctx); 
988
989         /* Now, if it was AD, then we want to start looking changing a
990          * few more things.  Otherwise, we are done. */
991         if (realm) {
992                 status = libnet_JoinADSDomain(ctx, r);
993                 return status;
994         }
995
996         return status;
997 }
998
999 static NTSTATUS libnet_Join_primary_domain(struct libnet_context *ctx, 
1000                                            TALLOC_CTX *mem_ctx, 
1001                                            struct libnet_Join *r)
1002 {
1003         NTSTATUS status;
1004         TALLOC_CTX *tmp_mem;
1005         struct libnet_JoinDomain *r2;
1006         int ret, rtn;
1007         struct ldb_context *ldb;
1008         const struct ldb_dn *base_dn;
1009         struct ldb_message **msgs, *msg;
1010         const char *sct;
1011         const char * const attrs[] = {
1012                 "whenChanged",
1013                 "secret",
1014                 "priorSecret",
1015                 "priorChanged",
1016                 NULL
1017         };
1018         uint32_t acct_type = 0;
1019         const char *account_name;
1020         const char *netbios_name;
1021         char *filter;
1022         
1023         r->out.error_string = NULL;
1024
1025         tmp_mem = talloc_new(mem_ctx);
1026         if (!tmp_mem) {
1027                 return NT_STATUS_NO_MEMORY;
1028         }
1029
1030         r2 = talloc(tmp_mem, struct libnet_JoinDomain);
1031         if (!r2) {
1032                 r->out.error_string = NULL;
1033                 talloc_free(tmp_mem);
1034                 return NT_STATUS_NO_MEMORY;
1035         }
1036         
1037         if (r->in.join_type == SEC_CHAN_BDC) {
1038                 acct_type = ACB_SVRTRUST;
1039         } else if (r->in.join_type == SEC_CHAN_WKSTA) {
1040                 acct_type = ACB_WSTRUST;
1041         } else {
1042                 r->out.error_string = NULL;
1043                 talloc_free(tmp_mem);   
1044                 return NT_STATUS_INVALID_PARAMETER;
1045         }
1046
1047         if (r->in.netbios_name != NULL) {
1048                 netbios_name = r->in.netbios_name;
1049         } else {
1050                 netbios_name = talloc_reference(tmp_mem, lp_netbios_name());
1051                 if (!netbios_name) {
1052                         r->out.error_string = NULL;
1053                         talloc_free(tmp_mem);
1054                         return NT_STATUS_NO_MEMORY;
1055                 }
1056         }
1057
1058         account_name = talloc_asprintf(tmp_mem, "%s$", netbios_name);
1059         if (!account_name) {
1060                 r->out.error_string = NULL;
1061                 talloc_free(tmp_mem);
1062                 return NT_STATUS_NO_MEMORY;
1063         }
1064         
1065         /*
1066          * Local secrets are stored in secrets.ldb 
1067          * open it to make sure we can write the info into it after the join
1068          */
1069         ldb = secrets_db_connect(tmp_mem);
1070         if (!ldb) {
1071                 r->out.error_string
1072                         = talloc_asprintf(mem_ctx, 
1073                                           "Could not open secrets database\n");
1074                 talloc_free(tmp_mem);
1075                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1076         }
1077
1078         /*
1079          * join the domain
1080          */
1081         ZERO_STRUCTP(r2);
1082         r2->in.domain_name      = r->in.domain_name;
1083         r2->in.account_name     = account_name;
1084         r2->in.netbios_name     = netbios_name;
1085         r2->in.level            = LIBNET_JOINDOMAIN_AUTOMATIC;
1086         r2->in.acct_type        = acct_type;
1087         r2->in.recreate_account = False;
1088         status = libnet_JoinDomain(ctx, r2, r2);
1089         if (!NT_STATUS_IS_OK(status)) {
1090                 r->out.error_string = talloc_steal(mem_ctx, r2->out.error_string);
1091                 talloc_free(tmp_mem);
1092                 return status;
1093         }
1094         
1095         /*
1096          * now prepare the record for secrets.ldb
1097          */
1098         sct = talloc_asprintf(tmp_mem, "%d", r->in.join_type); 
1099         if (!sct) {
1100                 r->out.error_string = NULL;
1101                 talloc_free(tmp_mem);
1102                 return NT_STATUS_NO_MEMORY;
1103         }
1104         
1105         msg = ldb_msg_new(tmp_mem);
1106         if (!msg) {
1107                 r->out.error_string = NULL;
1108                 talloc_free(tmp_mem);
1109                 return NT_STATUS_NO_MEMORY;
1110         }
1111
1112         base_dn = ldb_dn_explode(tmp_mem, "cn=Primary Domains");
1113         if (!base_dn) {
1114                 r->out.error_string = NULL;
1115                 talloc_free(tmp_mem);
1116                 return NT_STATUS_NO_MEMORY;
1117         }
1118
1119         msg->dn = ldb_dn_build_child(tmp_mem, "flatname", r2->out.domain_name, base_dn);
1120         if (!msg->dn) {
1121                 r->out.error_string = NULL;
1122                 talloc_free(tmp_mem);
1123                 return NT_STATUS_NO_MEMORY;
1124         }
1125         
1126         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "flatname", r2->out.domain_name);
1127         if (rtn == -1) {
1128                 r->out.error_string = NULL;
1129                 talloc_free(tmp_mem);
1130                 return NT_STATUS_NO_MEMORY;
1131         }
1132
1133         if (r2->out.realm) {
1134                 rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "realm", r2->out.realm);
1135                 if (rtn == -1) {
1136                         r->out.error_string = NULL;
1137                         talloc_free(tmp_mem);
1138                         return NT_STATUS_NO_MEMORY;
1139                 }
1140
1141                 rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "objectClass", "primaryDomain");
1142                 if (rtn == -1) {
1143                         r->out.error_string = NULL;
1144                         talloc_free(tmp_mem);
1145                         return NT_STATUS_NO_MEMORY;
1146                 }
1147         }
1148
1149         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "objectClass", "primaryDomain");
1150         if (rtn == -1) {
1151                 r->out.error_string = NULL;
1152                 talloc_free(tmp_mem);
1153                 return NT_STATUS_NO_MEMORY;
1154         }
1155
1156         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secret", r2->out.join_password);
1157         if (rtn == -1) {
1158                 r->out.error_string = NULL;
1159                 talloc_free(tmp_mem);
1160                 return NT_STATUS_NO_MEMORY;
1161         }
1162
1163         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "samAccountName", r2->in.account_name);
1164         if (rtn == -1) {
1165                 r->out.error_string = NULL;
1166                 talloc_free(tmp_mem);
1167                 return NT_STATUS_NO_MEMORY;
1168         }
1169
1170         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secureChannelType", sct);
1171         if (rtn == -1) {
1172                 r->out.error_string = NULL;
1173                 talloc_free(tmp_mem);
1174                 return NT_STATUS_NO_MEMORY;
1175         }
1176
1177         if (r2->out.kvno) {
1178                 rtn = samdb_msg_add_uint(ldb, tmp_mem, msg, "msDS-KeyVersionNumber",
1179                                          r2->out.kvno);
1180                 if (rtn == -1) {
1181                         r->out.error_string = NULL;
1182                         talloc_free(tmp_mem);
1183                         return NT_STATUS_NO_MEMORY;
1184                 }
1185         }
1186
1187         if (r2->out.domain_sid) {
1188                 rtn = samdb_msg_add_dom_sid(ldb, tmp_mem, msg, "objectSid",
1189                                             r2->out.domain_sid);
1190                 if (rtn == -1) {
1191                         r->out.error_string = NULL;
1192                         talloc_free(tmp_mem);
1193                         return NT_STATUS_NO_MEMORY;
1194                 }
1195         }
1196
1197         /* 
1198          * search for the secret record
1199          * - remove the records we find
1200          * - and fetch the old secret and store it under priorSecret
1201          */
1202         ret = gendb_search(ldb,
1203                            tmp_mem, base_dn,
1204                            &msgs, attrs,
1205                            "(|" SECRETS_PRIMARY_DOMAIN_FILTER "(realm=%s))",
1206                            r2->out.domain_name, r2->out.realm);
1207         if (ret == 0) {
1208         } else if (ret == -1) {
1209                 r->out.error_string
1210                         = talloc_asprintf(mem_ctx, 
1211                                           "Search for domain: %s and realm: %s failed: %s", 
1212                                           r2->out.domain_name, r2->out.realm, ldb_errstring(ldb));
1213                 talloc_free(tmp_mem);
1214                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1215         } else {
1216                 const struct ldb_val *prior_secret;
1217                 const struct ldb_val *prior_modified_time;
1218                 int i;
1219
1220                 for (i = 0; i < ret; i++) {
1221                         ldb_delete(ldb, msgs[i]->dn);
1222                 }
1223
1224                 prior_secret = ldb_msg_find_ldb_val(msgs[0], "secret");
1225                 if (prior_secret) {
1226                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorSecret", prior_secret);
1227                         if (rtn == -1) {
1228                                 r->out.error_string = NULL;
1229                                 talloc_free(tmp_mem);
1230                                 return NT_STATUS_NO_MEMORY;
1231                         }
1232                 }
1233                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secret", r2->out.join_password);
1234                 if (rtn == -1) {
1235                         r->out.error_string = NULL;
1236                         talloc_free(tmp_mem);
1237                         return NT_STATUS_NO_MEMORY;
1238                 }
1239
1240                 prior_modified_time = ldb_msg_find_ldb_val(msgs[0], 
1241                                                            "whenChanged");
1242                 if (prior_modified_time) {
1243                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorWhenChanged", 
1244                                                   prior_modified_time);
1245                         if (rtn == -1) {
1246                                 r->out.error_string = NULL;
1247                                 talloc_free(tmp_mem);
1248                                 return NT_STATUS_NO_MEMORY;
1249                         }
1250                 }
1251
1252                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "samAccountName", r2->in.account_name);
1253                 if (rtn == -1) {
1254                         r->out.error_string = NULL;
1255                         talloc_free(tmp_mem);
1256                         return NT_STATUS_NO_MEMORY;
1257                 }
1258
1259                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secureChannelType", sct);
1260                 if (rtn == -1) {
1261                         r->out.error_string = NULL;
1262                         talloc_free(tmp_mem);
1263                         return NT_STATUS_NO_MEMORY;
1264                 }
1265         }
1266
1267         /* create the secret */
1268         ret = samdb_add(ldb, tmp_mem, msg);
1269         if (ret != 0) {
1270                 r->out.error_string = talloc_asprintf(mem_ctx, "Failed to create secret record %s\n", 
1271                                                       ldb_dn_linearize(ldb, msg->dn));
1272                 talloc_free(tmp_mem);
1273                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1274         }
1275
1276         if (r2->out.realm) {
1277                 struct cli_credentials *creds;
1278                 /* Make a credentials structure from it */
1279                 creds = cli_credentials_init(mem_ctx);
1280                 if (!creds) {
1281                         r->out.error_string = NULL;
1282                         talloc_free(tmp_mem);
1283                         return NT_STATUS_NO_MEMORY;
1284                 }
1285                 cli_credentials_set_conf(creds);
1286                 filter = talloc_asprintf(mem_ctx, "dn=%s", ldb_dn_linearize(mem_ctx, msg->dn));
1287                 status = cli_credentials_set_secrets(creds, NULL, filter);
1288                 if (!NT_STATUS_IS_OK(status)) {
1289                         r->out.error_string = talloc_asprintf(mem_ctx, "Failed to read secrets for keytab update for %s\n", 
1290                                                               filter);
1291                         talloc_free(tmp_mem);
1292                         return status;
1293                 } 
1294                 ret = cli_credentials_update_keytab(creds);
1295                 if (ret != 0) {
1296                         r->out.error_string = talloc_asprintf(mem_ctx, "Failed to update keytab for %s\n", 
1297                                                               filter);
1298                         talloc_free(tmp_mem);
1299                         return NT_STATUS_UNSUCCESSFUL;
1300                 }
1301         }
1302
1303         /* move all out parameter to the callers TALLOC_CTX */
1304         r->out.error_string     = NULL;
1305         r->out.join_password    = r2->out.join_password;
1306         talloc_steal(mem_ctx, r2->out.join_password);
1307         r->out.domain_sid       = r2->out.domain_sid;
1308         talloc_steal(mem_ctx, r2->out.domain_sid);
1309         r->out.domain_name      = r2->out.domain_name;
1310         talloc_steal(mem_ctx, r2->out.domain_name);
1311         talloc_free(tmp_mem);
1312         return NT_STATUS_OK;
1313 }
1314
1315 NTSTATUS libnet_Join(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_Join *r)
1316 {
1317         switch (r->in.join_type) {
1318                 case SEC_CHAN_WKSTA:
1319                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1320                 case SEC_CHAN_BDC:
1321                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1322                 case SEC_CHAN_DOMAIN:
1323                         break;
1324         }
1325
1326         r->out.error_string = talloc_asprintf(mem_ctx,
1327                                               "Invalid join type specified (%08X) attempting to join domain %s",
1328                                               r->in.join_type, r->in.domain_name);
1329         return NT_STATUS_INVALID_PARAMETER;
1330 }