r10696: Return the realm to the caller, not NULL...
[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                 if (r->in.level == LIBNET_JOINDOMAIN_AUTOMATIC) {
617                         r->out.error_string = talloc_asprintf(mem_ctx,
618                                                               "Connection to LSA pipe of PDC of domain '%s' failed: %s",
619                                                               r->in.domain_name, nt_errstr(status));
620                 } else {
621                         r->out.error_string = talloc_asprintf(mem_ctx,
622                                                               "Connection to LSA pipe with binding '%s' failed: %s",
623                                                               r->in.binding, nt_errstr(status));
624                 }
625                 talloc_free(tmp_ctx);
626                 return status;
627         }                       
628         lsa_pipe = c->out.dcerpc_pipe;
629         
630         /* Get an LSA policy handle */
631
632         ZERO_STRUCT(lsa_p_handle);
633         qos.len = 0;
634         qos.impersonation_level = 2;
635         qos.context_mode = 1;
636         qos.effective_only = 0;
637
638         attr.len = 0;
639         attr.root_dir = NULL;
640         attr.object_name = NULL;
641         attr.attributes = 0;
642         attr.sec_desc = NULL;
643         attr.sec_qos = &qos;
644
645         lsa_open_policy.in.attr = &attr;
646         
647         lsa_open_policy.in.system_name = talloc_asprintf(tmp_ctx, "\\"); 
648         if (!lsa_open_policy.in.system_name) {
649                 r->out.error_string = NULL;
650                 talloc_free(tmp_ctx);
651                 return NT_STATUS_NO_MEMORY;
652         }
653
654         lsa_open_policy.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
655         lsa_open_policy.out.handle = &lsa_p_handle;
656
657         status = dcerpc_lsa_OpenPolicy2(lsa_pipe, tmp_ctx, &lsa_open_policy); 
658         if (!NT_STATUS_IS_OK(status)) {
659                 r->out.error_string = talloc_asprintf(mem_ctx,
660                                                 "lsa_OpenPolicy2 failed: %s",
661                                                 nt_errstr(status));
662                 talloc_free(tmp_ctx);
663                 return status;
664         }
665         
666         /* Look to see if this is ADS (a fault indicates NT4 or Samba 3.0) */
667
668         lsa_query_info2.in.handle = &lsa_p_handle;
669         lsa_query_info2.in.level = LSA_POLICY_INFO_DNS;
670
671         status = dcerpc_lsa_QueryInfoPolicy2(lsa_pipe, tmp_ctx,                 
672                                              &lsa_query_info2);
673         
674         if (!NT_STATUS_EQUAL(status, NT_STATUS_NET_WRITE_FAULT)) {
675                 if (!NT_STATUS_IS_OK(status)) {
676                         r->out.error_string = talloc_asprintf(mem_ctx,
677                                                         "lsa_QueryInfoPolicy2 failed: %s",
678                                                         nt_errstr(status));
679                         talloc_free(tmp_ctx);
680                         return status;
681                 }
682                 realm = lsa_query_info2.out.info->dns.dns_domain.string;
683         }
684
685         /* Grab the domain SID (regardless of the result of the previous call */
686
687         lsa_query_info.in.handle = &lsa_p_handle;
688         lsa_query_info.in.level = LSA_POLICY_INFO_DOMAIN;
689
690         status = dcerpc_lsa_QueryInfoPolicy(lsa_pipe, tmp_ctx, 
691                                              &lsa_query_info);
692
693         if (!NT_STATUS_IS_OK(status)) {
694                 r->out.error_string = talloc_asprintf(mem_ctx,
695                                                 "lsa_QueryInfoPolicy2 failed: %s",
696                                                 nt_errstr(status));
697                 talloc_free(tmp_ctx);
698                 return status;
699         }
700
701         domain_sid = lsa_query_info.out.info->domain.sid;
702         domain_name = lsa_query_info.out.info->domain.name.string;
703
704         /*
705           establish a SAMR connection, on the same CIFS transport
706         */
707
708         /* Find the original binding string */
709         status = dcerpc_parse_binding(tmp_ctx, lsa_pipe->conn->binding_string, &samr_binding);  
710         if (!NT_STATUS_IS_OK(status)) {
711                 r->out.error_string = talloc_asprintf(mem_ctx,
712                                                 "Failed to parse lsa binding '%s'",
713                                                 lsa_pipe->conn->binding_string);
714                 talloc_free(tmp_ctx);
715                 return status;
716         }
717
718         /* Make binding string for samr, not the other pipe */
719         status = dcerpc_epm_map_binding(tmp_ctx, samr_binding,                                  
720                                         DCERPC_SAMR_UUID, DCERPC_SAMR_VERSION,
721                                         lsa_pipe->conn->event_ctx);
722         if (!NT_STATUS_IS_OK(status)) {
723                 r->out.error_string = talloc_asprintf(mem_ctx,
724                                                 "Failed to map DCERPC/TCP NCACN_NP pipe for '%s' - %s",
725                                                 DCERPC_NETLOGON_UUID,
726                                                 nt_errstr(status));
727                 talloc_free(tmp_ctx);
728                 return status;
729         }
730
731         /* Setup a SAMR connection */
732         status = dcerpc_secondary_connection(lsa_pipe, &samr_pipe, samr_binding);
733         if (!NT_STATUS_IS_OK(status)) {
734                 r->out.error_string = talloc_asprintf(mem_ctx,
735                                                 "SAMR secondary connection failed: %s",
736                                                 nt_errstr(status));
737                 talloc_free(tmp_ctx);
738                 return status;
739         }
740
741         status = dcerpc_pipe_auth(samr_pipe, samr_binding, DCERPC_SAMR_UUID, 
742                                   DCERPC_SAMR_VERSION, ctx->cred);
743         if (!NT_STATUS_IS_OK(status)) {
744                 r->out.error_string = talloc_asprintf(mem_ctx,
745                                                 "SAMR bind failed: %s",
746                                                 nt_errstr(status));
747                 talloc_free(tmp_ctx);
748                 return status;
749         }
750
751         /* prepare samr_Connect */
752         ZERO_STRUCT(p_handle);
753         sc.in.system_name = NULL;
754         sc.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
755         sc.out.connect_handle = &p_handle;
756
757         /* 2. do a samr_Connect to get a policy handle */
758         status = dcerpc_samr_Connect(samr_pipe, tmp_ctx, &sc);
759         if (!NT_STATUS_IS_OK(status)) {
760                 r->out.error_string = talloc_asprintf(mem_ctx,
761                                                 "samr_Connect failed: %s",
762                                                 nt_errstr(status));
763                 talloc_free(tmp_ctx);
764                 return status;
765         }
766
767         /* check result of samr_Connect */
768         if (!NT_STATUS_IS_OK(sc.out.result)) {
769                 r->out.error_string = talloc_asprintf(mem_ctx,
770                                                 "samr_Connect failed: %s",
771                                                 nt_errstr(sc.out.result));
772                 status = sc.out.result;
773                 talloc_free(tmp_ctx);
774                 return status;
775         }
776         
777         /* prepare samr_OpenDomain */
778         ZERO_STRUCT(d_handle);
779         od.in.connect_handle = &p_handle;
780         od.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
781         od.in.sid = domain_sid;
782         od.out.domain_handle = &d_handle;
783
784         /* 4. do a samr_OpenDomain to get a domain handle */
785         status = dcerpc_samr_OpenDomain(samr_pipe, tmp_ctx, &od);                       
786         if (!NT_STATUS_IS_OK(status)) {
787                 r->out.error_string = talloc_asprintf(mem_ctx,
788                                         "samr_OpenDomain for [%s] failed: %s",
789                                         r->in.domain_name,
790                                         nt_errstr(status));
791                 talloc_free(tmp_ctx);
792                 return status;
793         }
794         
795         /* prepare samr_CreateUser2 */
796         ZERO_STRUCTP(u_handle);
797         cu.in.domain_handle  = &d_handle;
798         cu.in.access_mask     = SEC_FLAG_MAXIMUM_ALLOWED;
799         samr_account_name.string = r->in.account_name;
800         cu.in.account_name    = &samr_account_name;
801         cu.in.acct_flags      = r->in.acct_type;
802         cu.out.user_handle    = u_handle;
803         cu.out.rid            = &rid;
804         cu.out.access_granted = &access_granted;
805
806         /* 4. do a samr_CreateUser2 to get an account handle, or an error */
807         cu_status = dcerpc_samr_CreateUser2(samr_pipe, tmp_ctx, &cu);                   
808         status = cu_status;
809         if (!NT_STATUS_IS_OK(status) && !NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
810                         r->out.error_string = talloc_asprintf(mem_ctx,
811                                                                 "samr_CreateUser2 for [%s] failed: %s\n",
812                                                                 r->in.domain_name, nt_errstr(status));
813                         talloc_free(tmp_ctx);
814                         return status;
815
816         } else if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
817                 /* prepare samr_LookupNames */
818                 ln.in.domain_handle = &d_handle;
819                 ln.in.num_names = 1;
820                 ln.in.names = talloc_array(tmp_ctx, struct lsa_String, 1);
821                 if (!ln.in.names) {
822                         r->out.error_string = NULL;
823                         talloc_free(tmp_ctx);
824                         return NT_STATUS_NO_MEMORY;
825                 }
826                 ln.in.names[0].string = r->in.account_name;
827                 
828                 /* 5. do a samr_LookupNames to get the users rid */
829                 status = dcerpc_samr_LookupNames(samr_pipe, tmp_ctx, &ln);
830                 if (!NT_STATUS_IS_OK(status)) {
831                         r->out.error_string = talloc_asprintf(mem_ctx,
832                                                 "samr_LookupNames for [%s] failed: %s",
833                                                 r->in.account_name,
834                                                 nt_errstr(status));
835                         talloc_free(tmp_ctx);
836                         return status;
837                 }
838                 
839                 /* check if we got one RID for the user */
840                 if (ln.out.rids.count != 1) {
841                         r->out.error_string = talloc_asprintf(mem_ctx,
842                                                               "samr_LookupNames for [%s] returns %d RIDs\n",
843                                                               r->in.account_name, ln.out.rids.count);
844                         talloc_free(tmp_ctx);
845                         return NT_STATUS_INVALID_PARAMETER;
846                 }
847                 
848                 /* prepare samr_OpenUser */
849                 ZERO_STRUCTP(u_handle);
850                 ou.in.domain_handle = &d_handle;
851                 ou.in.access_mask = SEC_FLAG_MAXIMUM_ALLOWED;
852                 ou.in.rid = ln.out.rids.ids[0];
853                 rid = ou.in.rid;
854                 ou.out.user_handle = u_handle;
855                 
856                 /* 6. do a samr_OpenUser to get a user handle */
857                 status = dcerpc_samr_OpenUser(samr_pipe, tmp_ctx, &ou); 
858                 if (!NT_STATUS_IS_OK(status)) {
859                         r->out.error_string = talloc_asprintf(mem_ctx,
860                                                         "samr_OpenUser for [%s] failed: %s",
861                                                         r->in.account_name,
862                                                         nt_errstr(status));
863                         talloc_free(tmp_ctx);
864                         return status;
865                 }
866         }
867         /* Find out what password policy this user has */
868         pwp.in.user_handle = u_handle;
869
870         status = dcerpc_samr_GetUserPwInfo(samr_pipe, tmp_ctx, &pwp);                           
871         if (NT_STATUS_IS_OK(status)) {
872                 policy_min_pw_len = pwp.out.info.min_password_length;
873         }
874         
875         /* Grab a password of that minimum length */
876         
877         password_str = generate_random_str(tmp_ctx, MAX(8, policy_min_pw_len)); 
878
879         r2.samr_handle.level            = LIBNET_SET_PASSWORD_SAMR_HANDLE;
880         r2.samr_handle.in.account_name  = r->in.account_name;
881         r2.samr_handle.in.newpassword   = password_str;
882         r2.samr_handle.in.user_handle   = u_handle;
883         r2.samr_handle.in.dcerpc_pipe   = samr_pipe;
884
885         status = libnet_SetPassword(ctx, tmp_ctx, &r2); 
886         if (!NT_STATUS_IS_OK(status)) {
887                 r->out.error_string = talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
888                 talloc_free(tmp_ctx);
889                 return status;
890         }
891
892         /* prepare samr_QueryUserInfo (get flags) */
893         qui.in.user_handle = u_handle;
894         qui.in.level = 16;
895         
896         status = dcerpc_samr_QueryUserInfo(samr_pipe, tmp_ctx, &qui);
897         if (!NT_STATUS_IS_OK(status)) {
898                 r->out.error_string = talloc_asprintf(mem_ctx,
899                                                 "samr_QueryUserInfo for [%s] failed: %s",
900                                                 r->in.account_name,
901                                                 nt_errstr(status));
902                 talloc_free(tmp_ctx);
903                 return status;
904         }
905         
906         if (!qui.out.info) {
907                 status = NT_STATUS_INVALID_PARAMETER;
908                 r->out.error_string
909                         = talloc_asprintf(mem_ctx,
910                                           "samr_QueryUserInfo failed to return qui.out.info for [%s]: %s\n",
911                                           r->in.account_name, nt_errstr(status));
912                 talloc_free(tmp_ctx);
913                 return status;
914         }
915
916         /* Possibly change account type (if we are creating a new account) */
917         if (((qui.out.info->info16.acct_flags & (ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST)) 
918             != r->in.acct_type) && (!NT_STATUS_EQUAL(cu_status, NT_STATUS_USER_EXISTS))) {
919                 acct_flags = (qui.out.info->info16.acct_flags & ~(ACB_WSTRUST | ACB_SVRTRUST | ACB_DOMTRUST))
920                               | r->in.acct_type;
921         } else {
922                 acct_flags = qui.out.info->info16.acct_flags;
923         }
924         
925         acct_flags = (acct_flags & ~ACB_DISABLED);
926
927         /* reset flags (if required) */
928         if (acct_flags != qui.out.info->info16.acct_flags) {    
929                 ZERO_STRUCT(u_info);
930                 u_info.info16.acct_flags = acct_flags;
931
932                 sui.in.user_handle = u_handle;
933                 sui.in.info = &u_info;
934                 sui.in.level = 16;
935                 
936                 dcerpc_samr_SetUserInfo(samr_pipe, tmp_ctx, &sui);
937                 if (!NT_STATUS_IS_OK(status)) {
938                         r->out.error_string = talloc_asprintf(mem_ctx,
939                                                         "samr_SetUserInfo for [%s] failed to remove ACB_DISABLED flag: %s",
940                                                         r->in.account_name,
941                                                         nt_errstr(status));
942                         talloc_free(tmp_ctx);
943                         return status;
944                 }
945         }
946
947         account_sid = dom_sid_add_rid(mem_ctx, domain_sid, rid);
948         if (!account_sid) {
949                 r->out.error_string = NULL;
950                 talloc_free(tmp_ctx);
951                 return NT_STATUS_NO_MEMORY;
952         }
953
954         r->out.join_password = password_str;
955         talloc_steal(mem_ctx, password_str);
956
957         r->out.domain_sid = domain_sid;
958         talloc_steal(mem_ctx, domain_sid);
959
960         r->out.account_sid = account_sid;
961         talloc_steal(mem_ctx, account_sid);
962
963         r->out.domain_name = domain_name;
964         talloc_steal(mem_ctx, domain_name);
965         r->out.realm = realm;
966         talloc_steal(mem_ctx, realm);
967         r->out.lsa_pipe = lsa_pipe;
968         talloc_steal(mem_ctx, lsa_pipe);
969         r->out.samr_pipe = samr_pipe;
970         talloc_steal(mem_ctx, samr_pipe);
971         r->out.samr_binding = samr_binding;
972         talloc_steal(mem_ctx, samr_binding);
973         r->out.user_handle = cu.out.user_handle;
974         talloc_steal(mem_ctx, cu.out.user_handle);
975         r->out.error_string = r2.samr_handle.out.error_string;
976         talloc_steal(mem_ctx, r2.samr_handle.out.error_string);
977         r->out.kvno = 0;
978         r->out.server_dn_str = NULL;
979         talloc_free(tmp_ctx); 
980
981         /* Now, if it was AD, then we want to start looking changing a
982          * few more things.  Otherwise, we are done. */
983         if (realm 
984             && (r->in.acct_type ==  ACB_SVRTRUST) 
985             && (!NT_STATUS_EQUAL(cu_status, NT_STATUS_USER_EXISTS))) {
986                 
987                 status = libnet_JoinADSDomain(ctx, r);
988                 return status;
989         }
990
991         return cu_status;
992 }
993
994 static NTSTATUS libnet_Join_primary_domain(struct libnet_context *ctx, 
995                                            TALLOC_CTX *mem_ctx, 
996                                            struct libnet_Join *r)
997 {
998         NTSTATUS status;
999         TALLOC_CTX *tmp_mem;
1000         struct libnet_JoinDomain *r2;
1001         int ret, rtn;
1002         struct ldb_context *ldb;
1003         const struct ldb_dn *base_dn;
1004         struct ldb_message **msgs, *msg;
1005         const char *sct;
1006         const char * const attrs[] = {
1007                 "whenChanged",
1008                 "secret",
1009                 "priorSecret",
1010                 "priorChanged",
1011                 NULL
1012         };
1013         uint32_t acct_type = 0;
1014         const char *account_name;
1015         const char *netbios_name;
1016         
1017         r->out.error_string = NULL;
1018
1019         tmp_mem = talloc_new(mem_ctx);
1020         if (!tmp_mem) {
1021                 return NT_STATUS_NO_MEMORY;
1022         }
1023
1024         r2 = talloc(tmp_mem, struct libnet_JoinDomain);
1025         if (!r2) {
1026                 r->out.error_string = NULL;
1027                 talloc_free(tmp_mem);
1028                 return NT_STATUS_NO_MEMORY;
1029         }
1030         
1031         if (r->in.secure_channel_type == SEC_CHAN_BDC) {
1032                 acct_type = ACB_SVRTRUST;
1033         } else if (r->in.secure_channel_type == SEC_CHAN_WKSTA) {
1034                 acct_type = ACB_WSTRUST;
1035         } else {
1036                 r->out.error_string = NULL;
1037                 talloc_free(tmp_mem);   
1038                 return NT_STATUS_INVALID_PARAMETER;
1039         }
1040
1041         if ((r->in.netbios_name != NULL) && (r->in.level != LIBNET_JOIN_AUTOMATIC)) {
1042                 netbios_name = r->in.netbios_name;
1043         } else {
1044                 netbios_name = talloc_asprintf(tmp_mem, "%s", lp_netbios_name());
1045                 if (!netbios_name) {
1046                         r->out.error_string = NULL;
1047                         talloc_free(tmp_mem);
1048                         return NT_STATUS_NO_MEMORY;
1049                 }
1050         }
1051
1052         account_name = talloc_asprintf(tmp_mem, "%s$", netbios_name);                   
1053         if (!account_name) {
1054                 r->out.error_string = NULL;
1055                 talloc_free(tmp_mem);
1056                 return NT_STATUS_NO_MEMORY;
1057         }
1058         
1059         /*
1060          * Local secrets are stored in secrets.ldb 
1061          * open it to make sure we can write the info into it after the join
1062          */
1063         ldb = secrets_db_connect(tmp_mem);                                              
1064         if (!ldb) {
1065                 r->out.error_string
1066                         = talloc_asprintf(mem_ctx, 
1067                                           "Could not open secrets database\n");
1068                 talloc_free(tmp_mem);
1069                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1070         }
1071
1072         /*
1073          * join the domain
1074          */
1075         ZERO_STRUCTP(r2);
1076         r2->in.domain_name      = r->in.domain_name;
1077         r2->in.account_name     = account_name;
1078         r2->in.netbios_name     = netbios_name;
1079         r2->in.level            = LIBNET_JOINDOMAIN_AUTOMATIC;
1080         r2->in.acct_type        = acct_type;
1081         status = libnet_JoinDomain(ctx, r2, r2);
1082         if (!NT_STATUS_IS_OK(status)) {
1083                 r->out.error_string = talloc_steal(mem_ctx, r2->out.error_string);
1084                 talloc_free(tmp_mem);
1085                 return status;
1086         }
1087         
1088         /*
1089          * now prepare the record for secrets.ldb
1090          */
1091         sct = talloc_asprintf(tmp_mem, "%d", r->in.secure_channel_type); 
1092         if (!sct) {
1093                 r->out.error_string = NULL;
1094                 talloc_free(tmp_mem);
1095                 return NT_STATUS_NO_MEMORY;
1096         }
1097         
1098         msg = ldb_msg_new(tmp_mem);
1099         if (!msg) {
1100                 r->out.error_string = NULL;
1101                 talloc_free(tmp_mem);
1102                 return NT_STATUS_NO_MEMORY;
1103         }
1104
1105         base_dn = ldb_dn_explode(tmp_mem, "cn=Primary Domains");
1106         if (!base_dn) {
1107                 r->out.error_string = NULL;
1108                 talloc_free(tmp_mem);
1109                 return NT_STATUS_NO_MEMORY;
1110         }
1111
1112         msg->dn = ldb_dn_build_child(tmp_mem, "flatname", r2->out.domain_name, base_dn);
1113         if (!msg->dn) {
1114                 r->out.error_string = NULL;
1115                 talloc_free(tmp_mem);
1116                 return NT_STATUS_NO_MEMORY;
1117         }
1118         
1119         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "flatname", r2->out.domain_name);
1120         if (rtn == -1) {
1121                 r->out.error_string = NULL;
1122                 talloc_free(tmp_mem);
1123                 return NT_STATUS_NO_MEMORY;
1124         }
1125
1126         if (r2->out.realm) {
1127                 rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "realm", r2->out.realm);
1128                 if (rtn == -1) {
1129                         r->out.error_string = NULL;
1130                         talloc_free(tmp_mem);
1131                         return NT_STATUS_NO_MEMORY;
1132                 }
1133         }
1134
1135         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "objectClass", "primaryDomain");
1136         if (rtn == -1) {
1137                 r->out.error_string = NULL;
1138                 talloc_free(tmp_mem);
1139                 return NT_STATUS_NO_MEMORY;
1140         }
1141
1142         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secret", r2->out.join_password);
1143         if (rtn == -1) {
1144                 r->out.error_string = NULL;
1145                 talloc_free(tmp_mem);
1146                 return NT_STATUS_NO_MEMORY;
1147         }
1148
1149         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "samAccountName", r2->in.account_name);
1150         if (rtn == -1) {
1151                 r->out.error_string = NULL;
1152                 talloc_free(tmp_mem);
1153                 return NT_STATUS_NO_MEMORY;
1154         }
1155
1156         rtn = samdb_msg_add_string(ldb, tmp_mem, msg, "secureChannelType", sct);
1157         if (rtn == -1) {
1158                 r->out.error_string = NULL;
1159                 talloc_free(tmp_mem);
1160                 return NT_STATUS_NO_MEMORY;
1161         }
1162
1163         if (r2->out.kvno) {
1164                 rtn = samdb_msg_add_uint(ldb, tmp_mem, msg, "msDS-KeyVersionNumber",
1165                                          r2->out.kvno);
1166                 if (rtn == -1) {
1167                         r->out.error_string = NULL;
1168                         talloc_free(tmp_mem);
1169                         return NT_STATUS_NO_MEMORY;
1170                 }
1171         }
1172
1173         if (r2->out.domain_sid) {
1174                 rtn = samdb_msg_add_dom_sid(ldb, tmp_mem, msg, "objectSid",
1175                                             r2->out.domain_sid);
1176                 if (rtn == -1) {
1177                         r->out.error_string = NULL;
1178                         talloc_free(tmp_mem);
1179                         return NT_STATUS_NO_MEMORY;
1180                 }
1181         }
1182
1183         /* 
1184          * search for the secret record
1185          * - remove the records we find
1186          * - and fetch the old secret and store it under priorSecret
1187          */
1188         ret = gendb_search(ldb,
1189                            tmp_mem, base_dn,
1190                            &msgs, attrs,
1191                            "(|" SECRETS_PRIMARY_DOMAIN_FILTER "(realm=%s))",
1192                            r2->out.domain_name, r2->out.realm);
1193         if (ret == 0) {
1194         } else if (ret == -1) {
1195                 r->out.error_string
1196                         = talloc_asprintf(mem_ctx, 
1197                                           "Search for domain: %s and realm: %s failed: %s", 
1198                                           r2->out.domain_name, r2->out.realm, ldb_errstring(ldb));
1199                 talloc_free(tmp_mem);
1200                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1201         } else {
1202                 const struct ldb_val *prior_secret;
1203                 const struct ldb_val *prior_modified_time;
1204                 int i;
1205
1206                 for (i = 0; i < ret; i++) {
1207                         ldb_delete(ldb, msgs[i]->dn);
1208                 }
1209
1210                 prior_secret = ldb_msg_find_ldb_val(msgs[0], "secret");
1211                 if (prior_secret) {
1212                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorSecret", prior_secret);
1213                         if (rtn == -1) {
1214                                 r->out.error_string = NULL;
1215                                 talloc_free(tmp_mem);
1216                                 return NT_STATUS_NO_MEMORY;
1217                         }
1218                 }
1219                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secret", r2->out.join_password);
1220                 if (rtn == -1) {
1221                         r->out.error_string = NULL;
1222                         talloc_free(tmp_mem);
1223                         return NT_STATUS_NO_MEMORY;
1224                 }
1225
1226                 prior_modified_time = ldb_msg_find_ldb_val(msgs[0], 
1227                                                            "whenChanged");
1228                 if (prior_modified_time) {
1229                         rtn = samdb_msg_set_value(ldb, tmp_mem, msg, "priorWhenChanged", 
1230                                                   prior_modified_time);
1231                         if (rtn == -1) {
1232                                 r->out.error_string = NULL;
1233                                 talloc_free(tmp_mem);
1234                                 return NT_STATUS_NO_MEMORY;
1235                         }
1236                 }
1237
1238                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "samAccountName", r2->in.account_name);
1239                 if (rtn == -1) {
1240                         r->out.error_string = NULL;
1241                         talloc_free(tmp_mem);
1242                         return NT_STATUS_NO_MEMORY;
1243                 }
1244
1245                 rtn = samdb_msg_set_string(ldb, tmp_mem, msg, "secureChannelType", sct);
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         /* create the secret */
1254         ret = samdb_add(ldb, tmp_mem, msg);
1255         if (ret != 0) {
1256                 r->out.error_string = talloc_asprintf(mem_ctx, "Failed to create secret record %s\n", 
1257                                                       ldb_dn_linearize(ldb, msg->dn));
1258                 talloc_free(tmp_mem);
1259                 return NT_STATUS_INTERNAL_DB_CORRUPTION;
1260         }
1261
1262         /* move all out parameter to the callers TALLOC_CTX */
1263         r->out.error_string     = NULL;
1264         r->out.join_password    = r2->out.join_password;
1265         talloc_steal(mem_ctx, r2->out.join_password);
1266         r->out.domain_sid       = r2->out.domain_sid;
1267         talloc_steal(mem_ctx, r2->out.domain_sid);
1268         talloc_free(tmp_mem);
1269         return NT_STATUS_OK;
1270 }
1271
1272 NTSTATUS libnet_Join(struct libnet_context *ctx, TALLOC_CTX *mem_ctx, struct libnet_Join *r)
1273 {
1274         switch (r->in.secure_channel_type) {
1275                 case SEC_CHAN_WKSTA:
1276                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1277                 case SEC_CHAN_BDC:
1278                         return libnet_Join_primary_domain(ctx, mem_ctx, r);
1279                 case SEC_CHAN_DOMAIN:
1280                         break;
1281         }
1282
1283         r->out.error_string = talloc_asprintf(mem_ctx,
1284                                 "Invalid secure channel type specified (%08X) attempting to join domain %s",
1285                                 r->in.secure_channel_type, r->in.domain_name);
1286         return NT_STATUS_INVALID_PARAMETER;
1287 }
1288
1289