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