r10486: This is a merge of Brad Henry's 'net join' rework, to better perform
[ira/wip.git] / source / 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(remote_ldb, 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(remote_ldb, 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(remote_ldb, 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         drsuapi_binding->transport = NCACN_IP_TCP;
231         drsuapi_binding->endpoint = NULL;
232         drsuapi_binding->flags |= DCERPC_SEAL;
233
234         status = dcerpc_pipe_connect_b(tmp_ctx, 
235                                        &drsuapi_pipe,
236                                        drsuapi_binding,
237                                        DCERPC_DRSUAPI_UUID,
238                                        DCERPC_DRSUAPI_VERSION, 
239                                        ctx->cred, 
240                                        ctx->event_ctx);
241         if (!NT_STATUS_IS_OK(status)) {
242                 r->out.error_string = talloc_asprintf(r,
243                                         "Connection to DRSUAPI pipe of PDC of domain '%s' failed: %s",
244                                         r->in.domain_name,
245                                         nt_errstr(status));
246                 talloc_free(tmp_ctx);
247                 return status;
248         }
249
250         /* get a DRSUAPI pipe handle */
251         GUID_from_string(DRSUAPI_DS_BIND_GUID, &drsuapi_bind_guid);
252
253         r_drsuapi_bind.in.bind_guid = &drsuapi_bind_guid;
254         r_drsuapi_bind.in.bind_info = NULL;
255         r_drsuapi_bind.out.bind_handle = &drsuapi_bind_handle;
256
257         status = dcerpc_drsuapi_DsBind(drsuapi_pipe, tmp_ctx, &r_drsuapi_bind);
258         if (!NT_STATUS_IS_OK(status)) {
259                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
260                         r->out.error_string
261                                 = talloc_asprintf(r,
262                                                   "dcerpc_drsuapi_DsBind for [%s\\%s] failed - %s\n", 
263                                                   r->in.domain_name, r->in.account_name, 
264                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
265                         talloc_free(tmp_ctx);
266                         return status;
267                 } else {
268                         r->out.error_string
269                                 = talloc_asprintf(r,
270                                                   "dcerpc_drsuapi_DsBind for [%s\\%s] failed - %s\n", 
271                                                   r->in.domain_name, r->in.account_name, 
272                                                   nt_errstr(status));
273                         talloc_free(tmp_ctx);
274                         return status;
275                 }
276         } else if (!W_ERROR_IS_OK(r_drsuapi_bind.out.result)) {
277                 r->out.error_string
278                                 = talloc_asprintf(r,
279                                                   "DsBind failed - %s\n", 
280                                                   win_errstr(r_drsuapi_bind.out.result));
281                         talloc_free(tmp_ctx);
282                 return NT_STATUS_UNSUCCESSFUL;
283         }
284
285         /* Actually 'crack' the names */
286         ZERO_STRUCT(r_crack_names);
287         r_crack_names.in.bind_handle            = &drsuapi_bind_handle;
288         r_crack_names.in.level                  = 1;
289         r_crack_names.in.req.req1.unknown1      = 0x000004e4;
290         r_crack_names.in.req.req1.unknown2      = 0x00000407;
291         r_crack_names.in.req.req1.count         = 1;
292         r_crack_names.in.req.req1.names         = names;
293         r_crack_names.in.req.req1.format_flags  = DRSUAPI_DS_NAME_FLAG_NO_FLAGS;
294         r_crack_names.in.req.req1.format_offered= DRSUAPI_DS_NAME_FORMAT_SID_OR_SID_HISTORY;
295         r_crack_names.in.req.req1.format_desired= DRSUAPI_DS_NAME_FORMAT_FQDN_1779;
296         names[0].str = dom_sid_string(tmp_ctx, r->out.account_sid);
297         if (!names[0].str) {
298                 r->out.error_string = NULL;
299                 talloc_free(tmp_ctx);
300                 return NT_STATUS_NO_MEMORY;
301         }
302
303         status = dcerpc_drsuapi_DsCrackNames(drsuapi_pipe, tmp_ctx, &r_crack_names);
304         if (!NT_STATUS_IS_OK(status)) {
305                 if (NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
306                         r->out.error_string
307                                 = talloc_asprintf(r,
308                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s\n", 
309                                                   names[0].str,
310                                                   dcerpc_errstr(tmp_ctx, drsuapi_pipe->last_fault_code));
311                         talloc_free(tmp_ctx);
312                         return status;
313                 } else {
314                         r->out.error_string
315                                 = talloc_asprintf(r,
316                                                   "dcerpc_drsuapi_DsCrackNames for [%s] failed - %s\n", 
317                                                   names[0].str,
318                                                   nt_errstr(status));
319                         talloc_free(tmp_ctx);
320                         return status;
321                 }
322         } else if (!W_ERROR_IS_OK(r_crack_names.out.result)) {
323                 r->out.error_string
324                                 = talloc_asprintf(r,
325                                                   "DsCrackNames failed - %s\n", win_errstr(r_crack_names.out.result));
326                 talloc_free(tmp_ctx);
327                 return NT_STATUS_UNSUCCESSFUL;
328         } else if (r_crack_names.out.level != 1 
329                    || !r_crack_names.out.ctr.ctr1 
330                    || r_crack_names.out.ctr.ctr1->count != 1 
331                    || !r_crack_names.out.ctr.ctr1->array[0].result_name
332                    || r_crack_names.out.ctr.ctr1->array[0].status != DRSUAPI_DS_NAME_STATUS_OK) {
333                 r->out.error_string = talloc_asprintf(r, "DsCrackNames failed\n");
334                 talloc_free(tmp_ctx);
335                 return NT_STATUS_UNSUCCESSFUL;
336         }
337
338         /* Store the DN of our machine account. */
339         account_dn_str = r_crack_names.out.ctr.ctr1->array[0].result_name;
340
341         account_dn = ldb_dn_explode(tmp_ctx, account_dn_str);
342         if (!account_dn) {
343                 r->out.error_string = talloc_asprintf(r, "Invalid account dn: %s",
344                                                       account_dn_str);
345                 talloc_free(tmp_ctx);
346                 return NT_STATUS_UNSUCCESSFUL;
347         }
348
349         /* Now we know the user's DN, open with LDAP, read and modify a few things */
350
351         remote_ldb_url = talloc_asprintf(tmp_ctx, "ldap://%s", 
352                                          drsuapi_binding->host);
353         if (!remote_ldb_url) {
354                 r->out.error_string = NULL;
355                 talloc_free(tmp_ctx);
356                 return NT_STATUS_NO_MEMORY;
357         }
358
359         remote_ldb = ldb_wrap_connect(tmp_ctx, remote_ldb_url, 0, NULL);
360         if (!remote_ldb) {
361                 r->out.error_string = NULL;
362                 talloc_free(tmp_ctx);
363                 return NT_STATUS_UNSUCCESSFUL;
364         }
365
366         /* search for the user's record */
367         rtn = ldb_search(remote_ldb, account_dn, LDB_SCOPE_BASE, 
368                              NULL, attrs, &msgs);
369         if (rtn != 1) {
370                 r->out.error_string = talloc_asprintf(r, "ldb_search for %s failed - %s\n",
371                                                       account_dn_str, ldb_errstring(remote_ldb));
372                 talloc_free(tmp_ctx);
373                 return NT_STATUS_UNSUCCESSFUL;
374         }
375
376         /* If we have a kvno recorded in AD, we need it locally as well */
377         kvno = ldb_msg_find_uint(msgs[0], "msDS-KeyVersionNumber", 0);
378
379         /* Prepare a new message, for the modify */
380         msg = ldb_msg_new(tmp_ctx);
381         if (!msg) {
382                 r->out.error_string = NULL;
383                 talloc_free(tmp_ctx);
384                 return NT_STATUS_NO_MEMORY;
385         }
386         msg->dn = msgs[0]->dn;
387
388         {
389                 const char *service_principal_name[2];
390                 const char *dns_host_name = strlower_talloc(tmp_ctx, 
391                                                             talloc_asprintf(tmp_ctx, 
392                                                                             "%s.%s", 
393                                                                             r->in.netbios_name, 
394                                                                             realm));
395
396                 if (!dns_host_name) {
397                         r->out.error_string = NULL;
398                         talloc_free(tmp_ctx);
399                         return NT_STATUS_NO_MEMORY;
400                 }
401
402                 service_principal_name[0] = talloc_asprintf(tmp_ctx, "host/%s", dns_host_name);
403                 if (!service_principal_name[0]) {
404                         r->out.error_string = NULL;
405                         talloc_free(tmp_ctx);
406                         return NT_STATUS_NO_MEMORY;
407                 }
408
409                 service_principal_name[1] = talloc_asprintf(tmp_ctx, "host/%s", strlower_talloc(tmp_ctx, r->in.netbios_name));
410                 if (!service_principal_name[1]) {
411                         r->out.error_string = NULL;
412                         talloc_free(tmp_ctx);
413                         return NT_STATUS_NO_MEMORY;
414                 }
415
416                 rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "dNSHostName", dns_host_name);
417                 if (rtn == -1) {
418                         r->out.error_string = NULL;
419                         talloc_free(tmp_ctx);
420                         return NT_STATUS_NO_MEMORY;
421                 }
422                 rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "servicePrincipalName", service_principal_name[0]);
423                 if (rtn == -1) {
424                         r->out.error_string = NULL;
425                         talloc_free(tmp_ctx);
426                         return NT_STATUS_NO_MEMORY;
427                 }
428                 rtn = samdb_msg_add_string(remote_ldb, tmp_ctx, msg, "servicePrincipalName", service_principal_name[1]);
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         status = libnet_JoinSite(ctx,
502                                  drsuapi_pipe, drsuapi_bind_handle,
503                                  remote_ldb, r);
504         talloc_free(tmp_ctx);
505
506         return status;
507 }
508
509 /*
510  * do a domain join using DCERPC/SAMR calls
511  * 1. connect to the SAMR pipe of users domain PDC (maybe a standalone server or workstation)
512  *    is it correct to contact the the pdc of the domain of the user who's password should be set?
513  * 2. do a samr_Connect to get a policy handle
514  * 3. do a samr_LookupDomain to get the domain sid
515  * 4. do a samr_OpenDomain to get a domain handle
516  * 5. do a samr_CreateAccount to try and get a new account 
517  * 
518  * If that fails, do:
519  * 5.1. do a samr_LookupNames to get the users rid
520  * 5.2. do a samr_OpenUser to get a user handle
521  * 
522  * 6. call libnet_SetPassword_samr_handle to set the password
523  *
524  * 7. do a samrSetUserInfo to set the account flags
525  * 8. do some ADS specific things when we join as Domain Controller,
526  *    look at libnet_joinADSDomain() for the details
527  */
528 NTSTATUS libnet_JoinDomain(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_JoinDomain *r)
529 {
530         TALLOC_CTX *tmp_ctx;
531
532         NTSTATUS status, cu_status;
533         struct libnet_RpcConnect *c;
534         struct lsa_ObjectAttribute attr;
535         struct lsa_QosInfo qos;
536         struct lsa_OpenPolicy2 lsa_open_policy;
537         struct policy_handle lsa_p_handle;
538         struct lsa_QueryInfoPolicy2 lsa_query_info2;
539         struct lsa_QueryInfoPolicy lsa_query_info;
540
541         struct dcerpc_binding *samr_binding;
542         struct dcerpc_pipe *samr_pipe;
543         struct dcerpc_pipe *lsa_pipe;
544         struct samr_Connect sc;
545         struct policy_handle p_handle;
546         struct samr_OpenDomain od;
547         struct policy_handle d_handle;
548         struct samr_LookupNames ln;
549         struct samr_OpenUser ou;
550         struct samr_CreateUser2 cu;
551         struct policy_handle *u_handle = NULL;
552         struct samr_QueryUserInfo qui;
553         struct samr_SetUserInfo sui;
554         union samr_UserInfo u_info;
555         union libnet_SetPassword r2;
556         struct samr_GetUserPwInfo pwp;
557         struct lsa_String samr_account_name;
558         
559         uint32_t acct_flags;
560         uint32_t rid, access_granted;
561         int policy_min_pw_len = 0;
562
563         struct dom_sid *domain_sid = NULL;
564         struct dom_sid *account_sid = NULL;
565         const char *domain_name = NULL;
566         const char *password_str = NULL;
567         const char *realm = NULL; /* Also flag for remote being AD */
568         
569         
570         r->out.error_string = NULL;
571         r2.samr_handle.out.error_string = NULL;
572         
573         tmp_ctx = talloc_named(mem_ctx, 0, "libnet_Join temp context");
574         if (!tmp_ctx) {
575                 r->out.error_string = NULL;
576                 return NT_STATUS_NO_MEMORY;
577         }
578         
579         u_handle = talloc(tmp_ctx, struct policy_handle);
580         if (!u_handle) {
581                 r->out.error_string = NULL;
582                 talloc_free(tmp_ctx);
583                 return NT_STATUS_NO_MEMORY;
584         }
585         
586         samr_pipe = talloc(tmp_ctx, struct dcerpc_pipe);
587         if (!samr_pipe) {
588                 r->out.error_string = NULL;
589                 talloc_free(tmp_ctx);
590                 return NT_STATUS_NO_MEMORY;
591         }
592         
593         c = talloc(tmp_ctx, struct libnet_RpcConnect);
594         if (!c) {
595                 r->out.error_string = NULL;
596                 talloc_free(tmp_ctx);
597                 return NT_STATUS_NO_MEMORY;
598         }
599         
600         /* prepare connect to the LSA pipe of PDC */
601         if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
602                 c->level             = LIBNET_RPC_CONNECT_PDC;
603                 c->in.domain_name    = r->in.domain_name;
604         } else {
605                 c->level             = LIBNET_RPC_CONNECT_BINDING;
606                 c->in.binding        = r->in.binding;
607         }
608         c->in.dcerpc_iface_name      = DCERPC_LSARPC_NAME;
609         c->in.dcerpc_iface_uuid      = DCERPC_LSARPC_UUID;
610         c->in.dcerpc_iface_version   = DCERPC_LSARPC_VERSION;
611         
612         /* connect to the LSA pipe of the PDC */
613
614         status = libnet_RpcConnect(ctx, c, c);
615         if (!NT_STATUS_IS_OK(status)) {
616                 r->out.error_string = talloc_asprintf(mem_ctx,
617                                                 "Connection to LSA pipe of PDC of domain '%s' failed: %s",
618                                                 r->in.domain_name, nt_errstr(status));
619                 talloc_free(tmp_ctx);
620                 return status;
621         }                       
622         lsa_pipe = c->out.dcerpc_pipe;
623         
624         /* Get an LSA policy handle */
625
626         ZERO_STRUCT(lsa_p_handle);
627         qos.len = 0;
628         qos.impersonation_level = 2;
629         qos.context_mode = 1;
630         qos.effective_only = 0;
631
632         attr.len = 0;
633         attr.root_dir = NULL;
634         attr.object_name = NULL;
635         attr.attributes = 0;
636         attr.sec_desc = NULL;
637         attr.sec_qos = &qos;
638
639         lsa_open_policy.in.attr = &attr;
640         
641         lsa_open_policy.in.system_name = talloc_asprintf(tmp_ctx, "\\"); 
642         if (!lsa_open_policy.in.system_name) {
643                 r->out.error_string = NULL;
644                 talloc_free(tmp_ctx);
645                 return NT_STATUS_NO_MEMORY;
646         }
647
648         lsa_open_policy.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
649         lsa_open_policy.out.handle = &lsa_p_handle;
650
651         status = dcerpc_lsa_OpenPolicy2(lsa_pipe, tmp_ctx, &lsa_open_policy); 
652         if (!NT_STATUS_IS_OK(status)) {
653                 r->out.error_string = talloc_asprintf(mem_ctx,
654                                                 "lsa_OpenPolicy2 failed: %s",
655                                                 nt_errstr(status));
656                 talloc_free(tmp_ctx);
657                 return status;
658         }
659         
660         /* Look to see if this is ADS (a fault indicates NT4 or Samba 3.0) */
661
662         lsa_query_info2.in.handle = &lsa_p_handle;
663         lsa_query_info2.in.level = LSA_POLICY_INFO_DNS;
664
665         status = dcerpc_lsa_QueryInfoPolicy2(lsa_pipe, tmp_ctx,                 
666                                              &lsa_query_info2);
667         
668         if (!NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
669                 if (!NT_STATUS_IS_OK(status)) {
670                         r->out.error_string = talloc_asprintf(mem_ctx,
671                                                         "lsa_QueryInfoPolicy2 failed: %s",
672                                                         nt_errstr(status));
673                         talloc_free(tmp_ctx);
674                         return status;
675                 }
676                 realm = lsa_query_info2.out.info->dns.dns_domain.string;
677         }
678
679         /* Grab the domain SID (regardless of the result of the previous call */
680
681         lsa_query_info.in.handle = &lsa_p_handle;
682         lsa_query_info.in.level = LSA_POLICY_INFO_DOMAIN;
683
684         status = dcerpc_lsa_QueryInfoPolicy(lsa_pipe, tmp_ctx, 
685                                              &lsa_query_info);
686
687         if (!NT_STATUS_IS_OK(status)) {
688                 r->out.error_string = talloc_asprintf(mem_ctx,
689                                                 "lsa_QueryInfoPolicy2 failed: %s",
690                                                 nt_errstr(status));
691                 talloc_free(tmp_ctx);
692                 return status;
693         }
694
695         domain_sid = lsa_query_info.out.info->domain.sid;
696         domain_name = lsa_query_info.out.info->domain.name.string;
697
698         /*
699           establish a SAMR connection, on the same CIFS transport
700         */
701
702         /* Find the original binding string */
703         status = dcerpc_parse_binding(tmp_ctx, lsa_pipe->conn->binding_string, &samr_binding);  
704         if (!NT_STATUS_IS_OK(status)) {
705                 r->out.error_string = talloc_asprintf(mem_ctx,
706                                                 "Failed to parse lsa binding '%s'",
707                                                 lsa_pipe->conn->binding_string);
708                 talloc_free(tmp_ctx);
709                 return status;
710         }
711
712         /* Make binding string for samr, not the other pipe */
713         status = dcerpc_epm_map_binding(tmp_ctx, samr_binding,                                  
714                                         DCERPC_SAMR_UUID, DCERPC_SAMR_VERSION,
715                                         lsa_pipe->conn->event_ctx);
716         if (!NT_STATUS_IS_OK(status)) {
717                 r->out.error_string = talloc_asprintf(mem_ctx,
718                                                 "Failed to map DCERPC/TCP NCACN_NP pipe for '%s' - %s",
719                                                 DCERPC_NETLOGON_UUID,
720                                                 nt_errstr(status));
721                 talloc_free(tmp_ctx);
722                 return status;
723         }
724
725         /* Setup a SAMR connection */
726         status = dcerpc_secondary_connection(lsa_pipe, &samr_pipe, samr_binding);
727         if (!NT_STATUS_IS_OK(status)) {
728                 r->out.error_string = talloc_asprintf(mem_ctx,
729                                                 "SAMR secondary connection failed: %s",
730                                                 nt_errstr(status));
731                 talloc_free(tmp_ctx);
732                 return status;
733         }
734
735         status = dcerpc_pipe_auth(samr_pipe, samr_binding, DCERPC_SAMR_UUID, 
736                                   DCERPC_SAMR_VERSION, ctx->cred);
737         if (!NT_STATUS_IS_OK(status)) {
738                 r->out.error_string = talloc_asprintf(mem_ctx,
739                                                 "SAMR bind failed: %s",
740                                                 nt_errstr(status));
741                 talloc_free(tmp_ctx);
742                 return status;
743         }
744
745         /* prepare samr_Connect */
746         ZERO_STRUCT(p_handle);
747         sc.in.system_name = NULL;
748         sc.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
749         sc.out.connect_handle = &p_handle;
750
751         /* 2. do a samr_Connect to get a policy handle */
752         status = dcerpc_samr_Connect(samr_pipe, tmp_ctx, &sc);
753         if (!NT_STATUS_IS_OK(status)) {
754                 r->out.error_string = talloc_asprintf(mem_ctx,
755                                                 "samr_Connect failed: %s",
756                                                 nt_errstr(status));
757                 talloc_free(tmp_ctx);
758                 return status;
759         }
760
761         /* check result of samr_Connect */
762         if (!NT_STATUS_IS_OK(sc.out.result)) {
763                 r->out.error_string = talloc_asprintf(mem_ctx,
764                                                 "samr_Connect failed: %s",
765                                                 nt_errstr(sc.out.result));
766                 status = sc.out.result;
767                 talloc_free(tmp_ctx);
768                 return status;
769         }
770         
771         /* prepare samr_OpenDomain */
772         ZERO_STRUCT(d_handle);
773         od.in.connect_handle = &p_handle;
774         od.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
775         od.in.sid = domain_sid;
776         od.out.domain_handle = &d_handle;
777
778         /* 4. do a samr_OpenDomain to get a domain handle */
779         status = dcerpc_samr_OpenDomain(samr_pipe, tmp_ctx, &od);                       
780         if (!NT_STATUS_IS_OK(status)) {
781                 r->out.error_string = talloc_asprintf(mem_ctx,
782                                         "samr_OpenDomain for [%s] failed: %s",
783                                         r->in.domain_name,
784                                         nt_errstr(status));
785                 talloc_free(tmp_ctx);
786                 return status;
787         }
788         
789         /* prepare samr_CreateUser2 */
790         ZERO_STRUCTP(u_handle);
791         cu.in.domain_handle  = &d_handle;
792         cu.in.access_mask     = SEC_FLAG_MAXIMUM_ALLOWED;
793         samr_account_name.string = r->in.account_name;
794         cu.in.account_name    = &samr_account_name;
795         cu.in.acct_flags      = r->in.acct_type;
796         cu.out.user_handle    = u_handle;
797         cu.out.rid            = &rid;
798         cu.out.access_granted = &access_granted;
799
800         /* 4. do a samr_CreateUser2 to get an account handle, or an error */
801         cu_status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                   
802         status = cu_status;
803         if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
804                         r->out.error_string = talloc_asprintf(mem_ctx,
805                                                                 "samr_CreateUser2 for [%s] failed: %s\n",
806                                                                 r->in.domain_name, nt_errstr(status));
807                         talloc_free(tmp_ctx);
808                         return status;
809
810         } else if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
811                 /* prepare samr_LookupNames */
812                 ln.in.domain_handle = &d_handle;
813                 ln.in.num_names = 1;
814                 ln.in.names = talloc_array(tmp_ctx, struct lsa_String, 1);
815                 if (!ln.in.names) {
816                         r->out.error_string = NULL;
817                         talloc_free(tmp_ctx);
818                         return NT_STATUS_NO_MEMORY;
819                 }
820                 ln.in.names[0].string = r->in.account_name;
821                 
822                 /* 5. do a samr_LookupNames to get the users rid */
823                 status = dcerpc_samr_LookupNames(samr_pipe, tmp_ctx, &ln);
824                 if (!NT_STATUS_IS_OK(status)) {
825                         r->out.error_string = talloc_asprintf(mem_ctx,
826                                                 "samr_LookupNames for [%s] failed: %s",
827                                                 r->in.account_name,
828                                                 nt_errstr(status));
829                         talloc_free(tmp_ctx);
830                         return status;
831                 }
832                 
833                 /* check if we got one RID for the user */
834                 if (ln.out.rids.count != 1) {
835                         r->out.error_string = talloc_asprintf(mem_ctx,
836                                                               "samr_LookupNames for [%s] returns %d RIDs\n",
837                                                               r->in.account_name, ln.out.rids.count);
838                         status = NT_STATUS_INVALID_PARAMETER;
839                         talloc_free(tmp_ctx);
840                         return status;  
841                 }
842                 
843                 /* prepare samr_OpenUser */
844                 ZERO_STRUCTP(u_handle);
845                 ou.in.domain_handle = &d_handle;
846                 ou.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
847                 ou.in.rid = ln.out.rids.ids[0];
848                 rid = ou.in.rid;
849                 ou.out.user_handle = u_handle;
850                 
851                 /* 6. do a samr_OpenUser to get a user handle */
852                 status = dcerpc_samr_OpenUser(samr_pipe, tmp_ctx, &ou); 
853                 if (!NT_STATUS_IS_OK(status)) {
854                         r->out.error_string = talloc_asprintf(mem_ctx,
855                                                         "samr_OpenUser for [%s] failed: %s",
856                                                         r->in.account_name,
857                                                         nt_errstr(status));
858                         talloc_free(tmp_ctx);
859                         return status;
860                 }
861         }
862         /* Find out what password policy this user has */
863         pwp.in.user_handle = u_handle;
864
865         status = dcerpc_samr_GetUserPwInfo(samr_pipe, tmp_ctx, &pwp);                           
866         if (NT_STATUS_IS_OK(status)) {
867                 policy_min_pw_len = pwp.out.info.min_password_length;
868         }
869         
870         /* Grab a password of that minimum length */
871         
872         password_str = generate_random_str(tmp_ctx, MAX(8, policy_min_pw_len)); 
873
874         r2.samr_handle.level            = LIBNET_SET_PASSWORD_SAMR_HANDLE;
875         r2.samr_handle.in.account_name  = r->in.account_name;
876         r2.samr_handle.in.newpassword   = password_str;
877         r2.samr_handle.in.user_handle   = u_handle;
878         r2.samr_handle.in.dcerpc_pipe   = samr_pipe;
879
880         status = libnet_SetPassword(ctx, tmp_ctx, &r2); 
881         if (!NT_STATUS_IS_OK(status)) {
882                 r->out.error_string = talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
883                 talloc_free(tmp_ctx);
884                 return status;
885         }
886
887         /* prepare samr_QueryUserInfo (get flags) */
888         qui.in.user_handle = u_handle;
889         qui.in.level = 16;
890         
891         status = dcerpc_samr_QueryUserInfo(samr_pipe, tmp_ctx, &qui);
892         if (!NT_STATUS_IS_OK(status)) {
893                 r->out.error_string = talloc_asprintf(mem_ctx,
894                                                 "samr_QueryUserInfo for [%s] failed: %s",
895                                                 r->in.account_name,
896                                                 nt_errstr(status));
897                 talloc_free(tmp_ctx);
898                 return status;
899         }
900         
901         if (!qui.out.info) {
902                 status = NT_STATUS_INVALID_PARAMETER;
903                 r->out.error_string
904                         = talloc_asprintf(mem_ctx,
905                                           "samr_QueryUserInfo failed to return qui.out.info for [%s]: %s\n",
906                                           r->in.account_name, nt_errstr(status));
907                 talloc_free(tmp_ctx);
908                 return status;
909         }
910
911         /* Possibly change account type (if we are creating a new account) */
912         if (((qui.out.info->info16.acct_flags & (ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST)) 
913             != r->in.acct_type) && (!NT_STATUS_EQUAL(cu_status, NT_STATUS_USER_EXISTS))) {
914                 acct_flags = (qui.out.info->info16.acct_flags & ~(ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST))
915                               | r->in.acct_type;
916         } else {
917                 acct_flags = qui.out.info->info16.acct_flags;
918         }
919         
920         acct_flags = (acct_flags & ~ACB_DISABLED);
921
922         /* reset flags (if required) */
923         if (acct_flags != qui.out.info->info16.acct_flags) {    
924                 ZERO_STRUCT(u_info);
925                 u_info.info16.acct_flags = acct_flags;
926
927                 sui.in.user_handle = u_handle;
928                 sui.in.info = &u_info;
929                 sui.in.level = 16;
930                 
931                 dcerpc_samr_SetUserInfo(samr_pipe, tmp_ctx, &sui);
932                 if (!NT_STATUS_IS_OK(status)) {
933                         r->out.error_string = talloc_asprintf(mem_ctx,
934                                                         "samr_SetUserInfo for [%s] failed to remove ACB_DISABLED flag: %s",
935                                                         r->in.account_name,
936                                                         nt_errstr(status));
937                         talloc_free(tmp_ctx);
938                         return status;
939                 }
940         }
941
942         account_sid = dom_sid_add_rid(mem_ctx, domain_sid, rid);
943         if (!account_sid) {
944                 r->out.error_string = NULL;
945                 talloc_free(tmp_ctx);
946                 return NT_STATUS_NO_MEMORY;
947         }
948
949         r->out.join_password = password_str;
950         talloc_steal(mem_ctx, password_str);
951
952         r->out.domain_sid = domain_sid;
953         talloc_steal(mem_ctx, domain_sid);
954
955         r->out.account_sid = account_sid;
956         talloc_steal(mem_ctx, account_sid);
957
958         r->out.domain_name = domain_name;
959         talloc_steal(mem_ctx, domain_name);
960         r->out.realm = realm;
961         talloc_steal(mem_ctx, realm);
962         r->out.lsa_pipe = lsa_pipe;
963         talloc_steal(mem_ctx, lsa_pipe);
964         r->out.samr_pipe = samr_pipe;
965         talloc_steal(mem_ctx, samr_pipe);
966         r->out.samr_binding = samr_binding;
967         talloc_steal(mem_ctx, samr_binding);
968         r->out.user_handle = cu.out.user_handle;
969         talloc_steal(mem_ctx, cu.out.user_handle);
970         r->out.error_string = r2.samr_handle.out.error_string;
971         talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
972         r->out.realm = NULL;
973         r->out.kvno = 0;
974         r->out.server_dn_str = NULL;
975         talloc_free(tmp_ctx); 
976
977         /* Now, if it was AD, then we want to start looking changing a
978          * few more things.  Otherwise, we are done. */
979         if (realm 
980             && (r->in.acct_type ==  ACB_SVRTRUST) 
981             && (!NT_STATUS_EQUAL(cu_status, NT_STATUS_USER_EXISTS))) {
982                 
983                 status = libnet_JoinADSDomain(ctx, r);
984                 return status;
985         }
986
987         return NT_STATUS_OK;
988 }
989
990 static NTSTATUS libnet_Join_primary_domain(struct libnet_context *ctx, 
991                                            TALLOC_CTX *mem_ctx, 
992                                            struct libnet_Join *r)
993 {
994         NTSTATUS status;
995         TALLOC_CTX *tmp_mem;
996         struct libnet_JoinDomain *r2;
997         int ret, rtn;
998         struct ldb_context *ldb;
999         const struct ldb_dn *base_dn;
1000         struct ldb_message **msgs, *msg;
1001         const char *sct;
1002         const char * const attrs[] = {
1003                 "whenChanged",
1004                 "secret",
1005                 "priorSecret",
1006                 "priorChanged",
1007                 NULL
1008         };
1009         uint32_t acct_type = 0;
1010         const char *account_name;
1011         const char *netbios_name;
1012         
1013         r->out.error_string = NULL;
1014
1015         tmp_mem = talloc_new(mem_ctx);
1016         if (!tmp_mem) {
1017                 return NT_STATUS_NO_MEMORY;
1018         }
1019
1020         r2 = talloc(tmp_mem, struct libnet_JoinDomain);
1021         if (!r2) {
1022                 r->out.error_string = NULL;
1023                 talloc_free(tmp_mem);
1024                 return NT_STATUS_NO_MEMORY;
1025         }
1026         
1027         if (r->in.secure_channel_type == SEC_CHAN_BDC) {
1028                 acct_type = ACB_SVRTRUST;
1029         } else if (r->in.secure_channel_type == SEC_CHAN_WKSTA) {
1030                 acct_type = ACB_WSTRUST;
1031         } else {
1032                 r->out.error_string = NULL;
1033                 talloc_free(tmp_mem);   
1034                 return NT_STATUS_INVALID_PARAMETER;
1035         }
1036
1037         if ((r->in.netbios_name != NULL) && (r->in.level != LIBNET_JOIN_AUTOMATIC)) {
1038                 netbios_name = r->in.netbios_name;
1039         } else {
1040                 netbios_name = talloc_asprintf(tmp_mem, "%s", lp_netbios_name());
1041                 if (!netbios_name) {
1042                         r->out.error_string = NULL;
1043                         talloc_free(tmp_mem);
1044                         return NT_STATUS_NO_MEMORY;
1045                 }
1046         }
1047
1048         account_name = talloc_asprintf(tmp_mem, "%s$", netbios_name);                   
1049         if (!account_name) {
1050                 r->out.error_string = NULL;
1051                 talloc_free(tmp_mem);
1052                 return NT_STATUS_NO_MEMORY;
1053         }
1054         
1055         /*
1056          * Local secrets are stored in secrets.ldb 
1057          * open it to make sure we can write the info into it after the join
1058          */
1059         ldb = secrets_db_connect(tmp_mem);                                              
1060         if (!ldb) {
1061                 r->out.error_string
1062                         = talloc_asprintf(mem_ctx, 
1063                                           "Could not open secrets database\n");
1064                 talloc_free(tmp_mem);
1065                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1066         }
1067
1068         /*
1069          * join the domain
1070          */
1071         ZERO_STRUCTP(r2);
1072         r2->in.domain_name      = r->in.domain_name;
1073         r2->in.account_name     = account_name;
1074         r2->in.netbios_name     = netbios_name;
1075         r2->in.level            = LIBNET_JOINDOMAIN_AUTOMATIC;
1076         r2->in.acct_type        = acct_type;
1077         status = libnet_JoinDomain(ctx, r2, r2);
1078         if (!NT_STATUS_IS_OK(status)) {
1079                 r->out.error_string = talloc_steal(mem_ctx, r2->out.error_string);
1080                 talloc_free(tmp_mem);
1081                 return status;
1082         }
1083         
1084         /*
1085          * now prepare the record for secrets.ldb
1086          */
1087         sct = talloc_asprintf(tmp_mem, "%d", r->in.secure_channel_type); 
1088         if (!sct) {
1089                 r->out.error_string = NULL;
1090                 talloc_free(tmp_mem);
1091                 return NT_STATUS_NO_MEMORY;
1092         }
1093         
1094         msg = ldb_msg_new(tmp_mem);
1095         if (!msg) {
1096                 r->out.error_string = NULL;
1097                 talloc_free(tmp_mem);
1098                 return NT_STATUS_NO_MEMORY;
1099         }
1100
1101         base_dn = ldb_dn_explode(tmp_mem, "cn=Primary Domains");
1102         if (!base_dn) {
1103                 r->out.error_string = NULL;
1104                 talloc_free(tmp_mem);
1105                 return NT_STATUS_NO_MEMORY;
1106         }
1107
1108         msg->dn = ldb_dn_build_child(tmp_mem, "flatname", r2->out.domain_name, base_dn);
1109         if (!msg->dn) {
1110                 r->out.error_string = NULL;
1111                 talloc_free(tmp_mem);
1112                 return NT_STATUS_NO_MEMORY;
1113         }
1114         
1115         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "flatname", r2->out.domain_name);
1116         if (rtn == -1) {
1117                 r->out.error_string = NULL;
1118                 talloc_free(tmp_mem);
1119                 return NT_STATUS_NO_MEMORY;
1120         }
1121
1122         if (r2->out.realm) {
1123                 rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "realm", r2->out.realm);
1124                 if (rtn == -1) {
1125                         r->out.error_string = NULL;
1126                         talloc_free(tmp_mem);
1127                         return NT_STATUS_NO_MEMORY;
1128                 }
1129         }
1130
1131         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "objectClass", "primaryDomain");
1132         if (rtn == -1) {
1133                 r->out.error_string = NULL;
1134                 talloc_free(tmp_mem);
1135                 return NT_STATUS_NO_MEMORY;
1136         }
1137
1138         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secret", r2->out.join_password);
1139         if (rtn == -1) {
1140                 r->out.error_string = NULL;
1141                 talloc_free(tmp_mem);
1142                 return NT_STATUS_NO_MEMORY;
1143         }
1144
1145         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "samAccountName", r2->in.account_name);
1146         if (rtn == -1) {
1147                 r->out.error_string = NULL;
1148                 talloc_free(tmp_mem);
1149                 return NT_STATUS_NO_MEMORY;
1150         }
1151
1152         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secureChannelType", sct);
1153         if (rtn == -1) {
1154                 r->out.error_string = NULL;
1155                 talloc_free(tmp_mem);
1156                 return NT_STATUS_NO_MEMORY;
1157         }
1158
1159         if (r2->out.kvno) {
1160                 rtn = samdb_msg_add_uint(ldb, tmp_mem, msg, "msDS-KeyVersionNumber",
1161                                          r2->out.kvno);
1162                 if (rtn == -1) {
1163                         r->out.error_string = NULL;
1164                         talloc_free(tmp_mem);
1165                         return NT_STATUS_NO_MEMORY;
1166                 }
1167         }
1168
1169         if (r2->out.domain_sid) {
1170                 rtn = samdb_msg_add_dom_sid(ldb, tmp_mem, msg, "objectSid",
1171                                             r2->out.domain_sid);
1172                 if (rtn == -1) {
1173                         r->out.error_string = NULL;
1174                         talloc_free(tmp_mem);
1175                         return NT_STATUS_NO_MEMORY;
1176                 }
1177         }
1178
1179         /* 
1180          * search for the secret record
1181          * - remove the records we find
1182          * - and fetch the old secret and store it under priorSecret
1183          */
1184         ret = gendb_search(ldb,
1185                            tmp_mem, base_dn,
1186                            &msgs, attrs,
1187                            "(|" SECRETS_PRIMARY_DOMAIN_FILTER "(realm=%s))",
1188                            r2->out.domain_name, r2->out.realm);
1189         if (ret == 0) {
1190         } else if (ret == -1) {
1191                 r->out.error_string
1192                         = talloc_asprintf(mem_ctx, 
1193                                           "Search for domain: %s and realm: %s failed: %s", 
1194                                           r2->out.domain_name, r2->out.realm, ldb_errstring(ldb));
1195                 talloc_free(tmp_mem);
1196                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1197         } else {
1198                 const struct ldb_val *prior_secret;
1199                 const struct ldb_val *prior_modified_time;
1200                 int i;
1201
1202                 for (i = 0; i < ret; i++) {
1203                         ldb_delete(ldb, msgs[i]->dn);
1204                 }
1205
1206                 prior_secret = ldb_msg_find_ldb_val(msgs[0], "secret");
1207                 if (prior_secret) {
1208                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorSecret", prior_secret);
1209                         if (rtn == -1) {
1210                                 r->out.error_string = NULL;
1211                                 talloc_free(tmp_mem);
1212                                 return NT_STATUS_NO_MEMORY;
1213                         }
1214                 }
1215                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secret", r2->out.join_password);
1216                 if (rtn == -1) {
1217                         r->out.error_string = NULL;
1218                         talloc_free(tmp_mem);
1219                         return NT_STATUS_NO_MEMORY;
1220                 }
1221
1222                 prior_modified_time = ldb_msg_find_ldb_val(msgs[0], 
1223                                                            "whenChanged");
1224                 if (prior_modified_time) {
1225                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorWhenChanged", 
1226                                                   prior_modified_time);
1227                         if (rtn == -1) {
1228                                 r->out.error_string = NULL;
1229                                 talloc_free(tmp_mem);
1230                                 return NT_STATUS_NO_MEMORY;
1231                         }
1232                 }
1233
1234                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "samAccountName", r2->in.account_name);
1235                 if (rtn == -1) {
1236                         r->out.error_string = NULL;
1237                         talloc_free(tmp_mem);
1238                         return NT_STATUS_NO_MEMORY;
1239                 }
1240
1241                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secureChannelType", sct);
1242                 if (rtn == -1) {
1243                         r->out.error_string = NULL;
1244                         talloc_free(tmp_mem);
1245                         return NT_STATUS_NO_MEMORY;
1246                 }
1247         }
1248
1249         /* create the secret */
1250         ret = samdb_add(ldb, tmp_mem, msg);
1251         if (ret != 0) {
1252                 r->out.error_string = talloc_asprintf(mem_ctx, "Failed to create secret record %s\n", 
1253                                                       ldb_dn_linearize(ldb, msg->dn));
1254                 talloc_free(tmp_mem);
1255                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1256         }
1257
1258         /* move all out parameter to the callers TALLOC_CTX */
1259         r->out.error_string     = NULL;
1260         r->out.join_password    = r2->out.join_password;
1261         talloc_steal(mem_ctx, r2->out.join_password);
1262         r->out.domain_sid       = r2->out.domain_sid;
1263         talloc_steal(mem_ctx, r2->out.domain_sid);
1264         talloc_free(tmp_mem);
1265         return NT_STATUS_OK;
1266 }
1267
1268 NTSTATUS libnet_Join(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_Join *r)
1269 {
1270         switch (r->in.secure_channel_type) {
1271                 case SEC_CHAN_WKSTA:
1272                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1273                 case SEC_CHAN_BDC:
1274                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1275                 case SEC_CHAN_DOMAIN:
1276                         break;
1277         }
1278
1279         r->out.error_string = talloc_asprintf(mem_ctx,
1280                                 "Invalid secure channel type specified (%08X) attempting to join domain %s",
1281                                 r->in.secure_channel_type, r->in.domain_name);
1282         return NT_STATUS_INVALID_PARAMETER;
1283 }
1284
1285