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