s3-rpc_cli: pass down ndr_interface_table to cli_rpc_pipe_open_noauth().
[samba.git] / source3 / libnet / libnet_join.c
1 /*
2  *  Unix SMB/CIFS implementation.
3  *  libnet Join Support
4  *  Copyright (C) Gerald (Jerry) Carter 2006
5  *  Copyright (C) Guenther Deschner 2007-2008
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 3 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "includes.h"
22 #include "ads.h"
23 #include "librpc/gen_ndr/ndr_libnet_join.h"
24 #include "libnet/libnet_join.h"
25 #include "libcli/auth/libcli_auth.h"
26 #include "../librpc/gen_ndr/ndr_samr_c.h"
27 #include "rpc_client/init_samr.h"
28 #include "../librpc/gen_ndr/ndr_lsa_c.h"
29 #include "rpc_client/cli_lsarpc.h"
30 #include "../librpc/gen_ndr/ndr_netlogon.h"
31 #include "rpc_client/cli_netlogon.h"
32 #include "lib/smbconf/smbconf.h"
33 #include "lib/smbconf/smbconf_reg.h"
34 #include "../libds/common/flags.h"
35 #include "secrets.h"
36 #include "rpc_client/init_lsa.h"
37 #include "rpc_client/cli_pipe.h"
38 #include "../libcli/security/security.h"
39 #include "passdb.h"
40 #include "libsmb/libsmb.h"
41 #include "../libcli/smb/smbXcli_base.h"
42 #include "lib/param/loadparm.h"
43
44 /****************************************************************
45 ****************************************************************/
46
47 #define LIBNET_JOIN_DUMP_CTX(ctx, r, f) \
48         do { \
49                 char *str = NULL; \
50                 str = NDR_PRINT_FUNCTION_STRING(ctx, libnet_JoinCtx, f, r); \
51                 DEBUG(1,("libnet_Join:\n%s", str)); \
52                 TALLOC_FREE(str); \
53         } while (0)
54
55 #define LIBNET_JOIN_IN_DUMP_CTX(ctx, r) \
56         LIBNET_JOIN_DUMP_CTX(ctx, r, NDR_IN | NDR_SET_VALUES)
57 #define LIBNET_JOIN_OUT_DUMP_CTX(ctx, r) \
58         LIBNET_JOIN_DUMP_CTX(ctx, r, NDR_OUT)
59
60 #define LIBNET_UNJOIN_DUMP_CTX(ctx, r, f) \
61         do { \
62                 char *str = NULL; \
63                 str = NDR_PRINT_FUNCTION_STRING(ctx, libnet_UnjoinCtx, f, r); \
64                 DEBUG(1,("libnet_Unjoin:\n%s", str)); \
65                 TALLOC_FREE(str); \
66         } while (0)
67
68 #define LIBNET_UNJOIN_IN_DUMP_CTX(ctx, r) \
69         LIBNET_UNJOIN_DUMP_CTX(ctx, r, NDR_IN | NDR_SET_VALUES)
70 #define LIBNET_UNJOIN_OUT_DUMP_CTX(ctx, r) \
71         LIBNET_UNJOIN_DUMP_CTX(ctx, r, NDR_OUT)
72
73 /****************************************************************
74 ****************************************************************/
75
76 static void libnet_join_set_error_string(TALLOC_CTX *mem_ctx,
77                                          struct libnet_JoinCtx *r,
78                                          const char *format, ...)
79 {
80         va_list args;
81
82         if (r->out.error_string) {
83                 return;
84         }
85
86         va_start(args, format);
87         r->out.error_string = talloc_vasprintf(mem_ctx, format, args);
88         va_end(args);
89 }
90
91 /****************************************************************
92 ****************************************************************/
93
94 static void libnet_unjoin_set_error_string(TALLOC_CTX *mem_ctx,
95                                            struct libnet_UnjoinCtx *r,
96                                            const char *format, ...)
97 {
98         va_list args;
99
100         if (r->out.error_string) {
101                 return;
102         }
103
104         va_start(args, format);
105         r->out.error_string = talloc_vasprintf(mem_ctx, format, args);
106         va_end(args);
107 }
108
109 #ifdef HAVE_ADS
110
111 /****************************************************************
112 ****************************************************************/
113
114 static ADS_STATUS libnet_connect_ads(const char *dns_domain_name,
115                                      const char *netbios_domain_name,
116                                      const char *dc_name,
117                                      const char *user_name,
118                                      const char *password,
119                                      ADS_STRUCT **ads)
120 {
121         ADS_STATUS status;
122         ADS_STRUCT *my_ads = NULL;
123         char *cp;
124
125         my_ads = ads_init(dns_domain_name,
126                           netbios_domain_name,
127                           dc_name);
128         if (!my_ads) {
129                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
130         }
131
132         if (user_name) {
133                 SAFE_FREE(my_ads->auth.user_name);
134                 my_ads->auth.user_name = SMB_STRDUP(user_name);
135                 if ((cp = strchr_m(my_ads->auth.user_name, '@'))!=0) {
136                         *cp++ = '\0';
137                         SAFE_FREE(my_ads->auth.realm);
138                         my_ads->auth.realm = smb_xstrdup(cp);
139                         if (!strupper_m(my_ads->auth.realm)) {
140                                 ads_destroy(&my_ads);
141                                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
142                         }
143                 }
144         }
145
146         if (password) {
147                 SAFE_FREE(my_ads->auth.password);
148                 my_ads->auth.password = SMB_STRDUP(password);
149         }
150
151         status = ads_connect_user_creds(my_ads);
152         if (!ADS_ERR_OK(status)) {
153                 ads_destroy(&my_ads);
154                 return status;
155         }
156
157         *ads = my_ads;
158         return ADS_SUCCESS;
159 }
160
161 /****************************************************************
162 ****************************************************************/
163
164 static ADS_STATUS libnet_join_connect_ads(TALLOC_CTX *mem_ctx,
165                                           struct libnet_JoinCtx *r)
166 {
167         ADS_STATUS status;
168
169         status = libnet_connect_ads(r->out.dns_domain_name,
170                                     r->out.netbios_domain_name,
171                                     r->in.dc_name,
172                                     r->in.admin_account,
173                                     r->in.admin_password,
174                                     &r->in.ads);
175         if (!ADS_ERR_OK(status)) {
176                 libnet_join_set_error_string(mem_ctx, r,
177                         "failed to connect to AD: %s",
178                         ads_errstr(status));
179                 return status;
180         }
181
182         if (!r->out.netbios_domain_name) {
183                 r->out.netbios_domain_name = talloc_strdup(mem_ctx,
184                                                            r->in.ads->server.workgroup);
185                 ADS_ERROR_HAVE_NO_MEMORY(r->out.netbios_domain_name);
186         }
187
188         if (!r->out.dns_domain_name) {
189                 r->out.dns_domain_name = talloc_strdup(mem_ctx,
190                                                        r->in.ads->config.realm);
191                 ADS_ERROR_HAVE_NO_MEMORY(r->out.dns_domain_name);
192         }
193
194         r->out.domain_is_ad = true;
195
196         return ADS_SUCCESS;
197 }
198
199 /****************************************************************
200 ****************************************************************/
201
202 static ADS_STATUS libnet_unjoin_connect_ads(TALLOC_CTX *mem_ctx,
203                                             struct libnet_UnjoinCtx *r)
204 {
205         ADS_STATUS status;
206
207         status = libnet_connect_ads(r->in.domain_name,
208                                     r->in.domain_name,
209                                     r->in.dc_name,
210                                     r->in.admin_account,
211                                     r->in.admin_password,
212                                     &r->in.ads);
213         if (!ADS_ERR_OK(status)) {
214                 libnet_unjoin_set_error_string(mem_ctx, r,
215                         "failed to connect to AD: %s",
216                         ads_errstr(status));
217         }
218
219         return status;
220 }
221
222 /****************************************************************
223  join a domain using ADS (LDAP mods)
224 ****************************************************************/
225
226 static ADS_STATUS libnet_join_precreate_machine_acct(TALLOC_CTX *mem_ctx,
227                                                      struct libnet_JoinCtx *r)
228 {
229         ADS_STATUS status;
230         LDAPMessage *res = NULL;
231         const char *attrs[] = { "dn", NULL };
232         bool moved = false;
233
234         status = ads_check_ou_dn(mem_ctx, r->in.ads, &r->in.account_ou);
235         if (!ADS_ERR_OK(status)) {
236                 return status;
237         }
238
239         status = ads_search_dn(r->in.ads, &res, r->in.account_ou, attrs);
240         if (!ADS_ERR_OK(status)) {
241                 return status;
242         }
243
244         if (ads_count_replies(r->in.ads, res) != 1) {
245                 ads_msgfree(r->in.ads, res);
246                 return ADS_ERROR_LDAP(LDAP_NO_SUCH_OBJECT);
247         }
248
249         ads_msgfree(r->in.ads, res);
250
251         /* Attempt to create the machine account and bail if this fails.
252            Assume that the admin wants exactly what they requested */
253
254         status = ads_create_machine_acct(r->in.ads,
255                                          r->in.machine_name,
256                                          r->in.account_ou);
257
258         if (ADS_ERR_OK(status)) {
259                 DEBUG(1,("machine account creation created\n"));
260                 return status;
261         } else  if ((status.error_type == ENUM_ADS_ERROR_LDAP) &&
262                     (status.err.rc == LDAP_ALREADY_EXISTS)) {
263                 status = ADS_SUCCESS;
264         }
265
266         if (!ADS_ERR_OK(status)) {
267                 DEBUG(1,("machine account creation failed\n"));
268                 return status;
269         }
270
271         status = ads_move_machine_acct(r->in.ads,
272                                        r->in.machine_name,
273                                        r->in.account_ou,
274                                        &moved);
275         if (!ADS_ERR_OK(status)) {
276                 DEBUG(1,("failure to locate/move pre-existing "
277                         "machine account\n"));
278                 return status;
279         }
280
281         DEBUG(1,("The machine account %s the specified OU.\n",
282                 moved ? "was moved into" : "already exists in"));
283
284         return status;
285 }
286
287 /****************************************************************
288 ****************************************************************/
289
290 static ADS_STATUS libnet_unjoin_remove_machine_acct(TALLOC_CTX *mem_ctx,
291                                                     struct libnet_UnjoinCtx *r)
292 {
293         ADS_STATUS status;
294
295         if (!r->in.ads) {
296                 status = libnet_unjoin_connect_ads(mem_ctx, r);
297                 if (!ADS_ERR_OK(status)) {
298                         libnet_unjoin_set_error_string(mem_ctx, r,
299                                 "failed to connect to AD: %s",
300                                 ads_errstr(status));
301                         return status;
302                 }
303         }
304
305         status = ads_leave_realm(r->in.ads, r->in.machine_name);
306         if (!ADS_ERR_OK(status)) {
307                 libnet_unjoin_set_error_string(mem_ctx, r,
308                         "failed to leave realm: %s",
309                         ads_errstr(status));
310                 return status;
311         }
312
313         return ADS_SUCCESS;
314 }
315
316 /****************************************************************
317 ****************************************************************/
318
319 static ADS_STATUS libnet_join_find_machine_acct(TALLOC_CTX *mem_ctx,
320                                                 struct libnet_JoinCtx *r)
321 {
322         ADS_STATUS status;
323         LDAPMessage *res = NULL;
324         char *dn = NULL;
325
326         if (!r->in.machine_name) {
327                 return ADS_ERROR(LDAP_NO_MEMORY);
328         }
329
330         status = ads_find_machine_acct(r->in.ads,
331                                        &res,
332                                        r->in.machine_name);
333         if (!ADS_ERR_OK(status)) {
334                 return status;
335         }
336
337         if (ads_count_replies(r->in.ads, res) != 1) {
338                 status = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
339                 goto done;
340         }
341
342         dn = ads_get_dn(r->in.ads, mem_ctx, res);
343         if (!dn) {
344                 status = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
345                 goto done;
346         }
347
348         r->out.dn = talloc_strdup(mem_ctx, dn);
349         if (!r->out.dn) {
350                 status = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
351                 goto done;
352         }
353
354  done:
355         ads_msgfree(r->in.ads, res);
356         TALLOC_FREE(dn);
357
358         return status;
359 }
360
361 /****************************************************************
362  Set a machines dNSHostName and servicePrincipalName attributes
363 ****************************************************************/
364
365 static ADS_STATUS libnet_join_set_machine_spn(TALLOC_CTX *mem_ctx,
366                                               struct libnet_JoinCtx *r)
367 {
368         ADS_STATUS status;
369         ADS_MODLIST mods;
370         fstring my_fqdn;
371         const char *spn_array[3] = {NULL, NULL, NULL};
372         char *spn = NULL;
373
374         /* Find our DN */
375
376         status = libnet_join_find_machine_acct(mem_ctx, r);
377         if (!ADS_ERR_OK(status)) {
378                 return status;
379         }
380
381         /* Windows only creates HOST/shortname & HOST/fqdn. */
382
383         spn = talloc_asprintf(mem_ctx, "HOST/%s", r->in.machine_name);
384         if (!spn) {
385                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
386         }
387         if (!strupper_m(spn)) {
388                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
389         }
390         spn_array[0] = spn;
391
392         if (!name_to_fqdn(my_fqdn, r->in.machine_name)
393             || (strchr(my_fqdn, '.') == NULL)) {
394                 fstr_sprintf(my_fqdn, "%s.%s", r->in.machine_name,
395                              r->out.dns_domain_name);
396         }
397
398         if (!strlower_m(my_fqdn)) {
399                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
400         }
401
402         if (!strequal(my_fqdn, r->in.machine_name)) {
403                 spn = talloc_asprintf(mem_ctx, "HOST/%s", my_fqdn);
404                 if (!spn) {
405                         return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
406                 }
407                 spn_array[1] = spn;
408         }
409
410         mods = ads_init_mods(mem_ctx);
411         if (!mods) {
412                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
413         }
414
415         /* fields of primary importance */
416
417         status = ads_mod_str(mem_ctx, &mods, "dNSHostName", my_fqdn);
418         if (!ADS_ERR_OK(status)) {
419                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
420         }
421
422         status = ads_mod_strlist(mem_ctx, &mods, "servicePrincipalName",
423                                  spn_array);
424         if (!ADS_ERR_OK(status)) {
425                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
426         }
427
428         return ads_gen_mod(r->in.ads, r->out.dn, mods);
429 }
430
431 /****************************************************************
432 ****************************************************************/
433
434 static ADS_STATUS libnet_join_set_machine_upn(TALLOC_CTX *mem_ctx,
435                                               struct libnet_JoinCtx *r)
436 {
437         ADS_STATUS status;
438         ADS_MODLIST mods;
439
440         if (!r->in.create_upn) {
441                 return ADS_SUCCESS;
442         }
443
444         /* Find our DN */
445
446         status = libnet_join_find_machine_acct(mem_ctx, r);
447         if (!ADS_ERR_OK(status)) {
448                 return status;
449         }
450
451         if (!r->in.upn) {
452                 r->in.upn = talloc_asprintf(mem_ctx,
453                                             "host/%s@%s",
454                                             r->in.machine_name,
455                                             r->out.dns_domain_name);
456                 if (!r->in.upn) {
457                         return ADS_ERROR(LDAP_NO_MEMORY);
458                 }
459         }
460
461         /* now do the mods */
462
463         mods = ads_init_mods(mem_ctx);
464         if (!mods) {
465                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
466         }
467
468         /* fields of primary importance */
469
470         status = ads_mod_str(mem_ctx, &mods, "userPrincipalName", r->in.upn);
471         if (!ADS_ERR_OK(status)) {
472                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
473         }
474
475         return ads_gen_mod(r->in.ads, r->out.dn, mods);
476 }
477
478
479 /****************************************************************
480 ****************************************************************/
481
482 static ADS_STATUS libnet_join_set_os_attributes(TALLOC_CTX *mem_ctx,
483                                                 struct libnet_JoinCtx *r)
484 {
485         ADS_STATUS status;
486         ADS_MODLIST mods;
487         char *os_sp = NULL;
488
489         if (!r->in.os_name || !r->in.os_version ) {
490                 return ADS_SUCCESS;
491         }
492
493         /* Find our DN */
494
495         status = libnet_join_find_machine_acct(mem_ctx, r);
496         if (!ADS_ERR_OK(status)) {
497                 return status;
498         }
499
500         /* now do the mods */
501
502         mods = ads_init_mods(mem_ctx);
503         if (!mods) {
504                 return ADS_ERROR(LDAP_NO_MEMORY);
505         }
506
507         os_sp = talloc_asprintf(mem_ctx, "Samba %s", samba_version_string());
508         if (!os_sp) {
509                 return ADS_ERROR(LDAP_NO_MEMORY);
510         }
511
512         /* fields of primary importance */
513
514         status = ads_mod_str(mem_ctx, &mods, "operatingSystem",
515                              r->in.os_name);
516         if (!ADS_ERR_OK(status)) {
517                 return status;
518         }
519
520         status = ads_mod_str(mem_ctx, &mods, "operatingSystemVersion",
521                              r->in.os_version);
522         if (!ADS_ERR_OK(status)) {
523                 return status;
524         }
525
526         status = ads_mod_str(mem_ctx, &mods, "operatingSystemServicePack",
527                              os_sp);
528         if (!ADS_ERR_OK(status)) {
529                 return status;
530         }
531
532         return ads_gen_mod(r->in.ads, r->out.dn, mods);
533 }
534
535 /****************************************************************
536 ****************************************************************/
537
538 static bool libnet_join_create_keytab(TALLOC_CTX *mem_ctx,
539                                       struct libnet_JoinCtx *r)
540 {
541         if (!USE_SYSTEM_KEYTAB) {
542                 return true;
543         }
544
545         if (ads_keytab_create_default(r->in.ads) != 0) {
546                 return false;
547         }
548
549         return true;
550 }
551
552 /****************************************************************
553 ****************************************************************/
554
555 static bool libnet_join_derive_salting_principal(TALLOC_CTX *mem_ctx,
556                                                  struct libnet_JoinCtx *r)
557 {
558         uint32_t domain_func;
559         ADS_STATUS status;
560         const char *salt = NULL;
561         char *std_salt = NULL;
562
563         status = ads_domain_func_level(r->in.ads, &domain_func);
564         if (!ADS_ERR_OK(status)) {
565                 libnet_join_set_error_string(mem_ctx, r,
566                         "failed to determine domain functional level: %s",
567                         ads_errstr(status));
568                 return false;
569         }
570
571         /* go ahead and setup the default salt */
572
573         std_salt = kerberos_standard_des_salt();
574         if (!std_salt) {
575                 libnet_join_set_error_string(mem_ctx, r,
576                         "failed to obtain standard DES salt");
577                 return false;
578         }
579
580         salt = talloc_strdup(mem_ctx, std_salt);
581         if (!salt) {
582                 return false;
583         }
584
585         SAFE_FREE(std_salt);
586
587         /* if it's a Windows functional domain, we have to look for the UPN */
588
589         if (domain_func == DS_DOMAIN_FUNCTION_2000) {
590                 char *upn;
591
592                 upn = ads_get_upn(r->in.ads, mem_ctx,
593                                   r->in.machine_name);
594                 if (upn) {
595                         salt = talloc_strdup(mem_ctx, upn);
596                         if (!salt) {
597                                 return false;
598                         }
599                 }
600         }
601
602         return kerberos_secrets_store_des_salt(salt);
603 }
604
605 /****************************************************************
606 ****************************************************************/
607
608 static ADS_STATUS libnet_join_post_processing_ads(TALLOC_CTX *mem_ctx,
609                                                   struct libnet_JoinCtx *r)
610 {
611         ADS_STATUS status;
612
613         if (!r->in.ads) {
614                 status = libnet_join_connect_ads(mem_ctx, r);
615                 if (!ADS_ERR_OK(status)) {
616                         return status;
617                 }
618         }
619
620         status = libnet_join_set_machine_spn(mem_ctx, r);
621         if (!ADS_ERR_OK(status)) {
622                 libnet_join_set_error_string(mem_ctx, r,
623                         "failed to set machine spn: %s",
624                         ads_errstr(status));
625                 return status;
626         }
627
628         status = libnet_join_set_os_attributes(mem_ctx, r);
629         if (!ADS_ERR_OK(status)) {
630                 libnet_join_set_error_string(mem_ctx, r,
631                         "failed to set machine os attributes: %s",
632                         ads_errstr(status));
633                 return status;
634         }
635
636         status = libnet_join_set_machine_upn(mem_ctx, r);
637         if (!ADS_ERR_OK(status)) {
638                 libnet_join_set_error_string(mem_ctx, r,
639                         "failed to set machine upn: %s",
640                         ads_errstr(status));
641                 return status;
642         }
643
644         if (!libnet_join_derive_salting_principal(mem_ctx, r)) {
645                 return ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
646         }
647
648         if (!libnet_join_create_keytab(mem_ctx, r)) {
649                 libnet_join_set_error_string(mem_ctx, r,
650                         "failed to create kerberos keytab");
651                 return ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
652         }
653
654         return ADS_SUCCESS;
655 }
656 #endif /* HAVE_ADS */
657
658 /****************************************************************
659  Store the machine password and domain SID
660 ****************************************************************/
661
662 static bool libnet_join_joindomain_store_secrets(TALLOC_CTX *mem_ctx,
663                                                  struct libnet_JoinCtx *r)
664 {
665         if (!secrets_store_domain_sid(r->out.netbios_domain_name,
666                                       r->out.domain_sid))
667         {
668                 DEBUG(1,("Failed to save domain sid\n"));
669                 return false;
670         }
671
672         if (!secrets_store_machine_password(r->in.machine_password,
673                                             r->out.netbios_domain_name,
674                                             r->in.secure_channel_type))
675         {
676                 DEBUG(1,("Failed to save machine password\n"));
677                 return false;
678         }
679
680         return true;
681 }
682
683 /****************************************************************
684  Connect dc's IPC$ share
685 ****************************************************************/
686
687 static NTSTATUS libnet_join_connect_dc_ipc(const char *dc,
688                                            const char *user,
689                                            const char *pass,
690                                            bool use_kerberos,
691                                            struct cli_state **cli)
692 {
693         int flags = 0;
694
695         if (use_kerberos) {
696                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
697         }
698
699         if (use_kerberos && pass) {
700                 flags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;
701         }
702
703         return cli_full_connection(cli, NULL,
704                                    dc,
705                                    NULL, 0,
706                                    "IPC$", "IPC",
707                                    user,
708                                    NULL,
709                                    pass,
710                                    flags,
711                                    SMB_SIGNING_DEFAULT);
712 }
713
714 /****************************************************************
715  Lookup domain dc's info
716 ****************************************************************/
717
718 static NTSTATUS libnet_join_lookup_dc_rpc(TALLOC_CTX *mem_ctx,
719                                           struct libnet_JoinCtx *r,
720                                           struct cli_state **cli)
721 {
722         struct rpc_pipe_client *pipe_hnd = NULL;
723         struct policy_handle lsa_pol;
724         NTSTATUS status, result;
725         union lsa_PolicyInformation *info = NULL;
726         struct dcerpc_binding_handle *b;
727
728         status = libnet_join_connect_dc_ipc(r->in.dc_name,
729                                             r->in.admin_account,
730                                             r->in.admin_password,
731                                             r->in.use_kerberos,
732                                             cli);
733         if (!NT_STATUS_IS_OK(status)) {
734                 goto done;
735         }
736
737         status = cli_rpc_pipe_open_noauth(*cli, &ndr_table_lsarpc,
738                                           &pipe_hnd);
739         if (!NT_STATUS_IS_OK(status)) {
740                 DEBUG(0,("Error connecting to LSA pipe. Error was %s\n",
741                         nt_errstr(status)));
742                 goto done;
743         }
744
745         b = pipe_hnd->binding_handle;
746
747         status = rpccli_lsa_open_policy(pipe_hnd, mem_ctx, true,
748                                         SEC_FLAG_MAXIMUM_ALLOWED, &lsa_pol);
749         if (!NT_STATUS_IS_OK(status)) {
750                 goto done;
751         }
752
753         status = dcerpc_lsa_QueryInfoPolicy2(b, mem_ctx,
754                                              &lsa_pol,
755                                              LSA_POLICY_INFO_DNS,
756                                              &info,
757                                              &result);
758         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
759                 r->out.domain_is_ad = true;
760                 r->out.netbios_domain_name = info->dns.name.string;
761                 r->out.dns_domain_name = info->dns.dns_domain.string;
762                 r->out.forest_name = info->dns.dns_forest.string;
763                 r->out.domain_sid = dom_sid_dup(mem_ctx, info->dns.sid);
764                 NT_STATUS_HAVE_NO_MEMORY(r->out.domain_sid);
765         }
766
767         if (!NT_STATUS_IS_OK(status)) {
768                 status = dcerpc_lsa_QueryInfoPolicy(b, mem_ctx,
769                                                     &lsa_pol,
770                                                     LSA_POLICY_INFO_ACCOUNT_DOMAIN,
771                                                     &info,
772                                                     &result);
773                 if (!NT_STATUS_IS_OK(status)) {
774                         goto done;
775                 }
776                 if (!NT_STATUS_IS_OK(result)) {
777                         status = result;
778                         goto done;
779                 }
780
781                 r->out.netbios_domain_name = info->account_domain.name.string;
782                 r->out.domain_sid = dom_sid_dup(mem_ctx, info->account_domain.sid);
783                 NT_STATUS_HAVE_NO_MEMORY(r->out.domain_sid);
784         }
785
786         dcerpc_lsa_Close(b, mem_ctx, &lsa_pol, &result);
787         TALLOC_FREE(pipe_hnd);
788
789  done:
790         return status;
791 }
792
793 /****************************************************************
794  Do the domain join unsecure
795 ****************************************************************/
796
797 static NTSTATUS libnet_join_joindomain_rpc_unsecure(TALLOC_CTX *mem_ctx,
798                                                     struct libnet_JoinCtx *r,
799                                                     struct cli_state *cli)
800 {
801         struct rpc_pipe_client *pipe_hnd = NULL;
802         unsigned char orig_trust_passwd_hash[16];
803         unsigned char new_trust_passwd_hash[16];
804         fstring trust_passwd;
805         NTSTATUS status;
806
807         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_netlogon,
808                                           &pipe_hnd);
809         if (!NT_STATUS_IS_OK(status)) {
810                 return status;
811         }
812
813         if (!r->in.machine_password) {
814                 r->in.machine_password = generate_random_password(mem_ctx,
815                                 DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH,
816                                 DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH);
817                 NT_STATUS_HAVE_NO_MEMORY(r->in.machine_password);
818         }
819
820         E_md4hash(r->in.machine_password, new_trust_passwd_hash);
821
822         /* according to WKSSVC_JOIN_FLAGS_MACHINE_PWD_PASSED */
823         fstrcpy(trust_passwd, r->in.admin_password);
824         if (!strlower_m(trust_passwd)) {
825                 return NT_STATUS_INVALID_PARAMETER;
826         }
827
828         /*
829          * Machine names can be 15 characters, but the max length on
830          * a password is 14.  --jerry
831          */
832
833         trust_passwd[14] = '\0';
834
835         E_md4hash(trust_passwd, orig_trust_passwd_hash);
836
837         status = rpccli_netlogon_set_trust_password(pipe_hnd, mem_ctx,
838                                                     r->in.machine_name,
839                                                     orig_trust_passwd_hash,
840                                                     r->in.machine_password,
841                                                     new_trust_passwd_hash,
842                                                     r->in.secure_channel_type);
843
844         return status;
845 }
846
847 /****************************************************************
848  Do the domain join
849 ****************************************************************/
850
851 static NTSTATUS libnet_join_joindomain_rpc(TALLOC_CTX *mem_ctx,
852                                            struct libnet_JoinCtx *r,
853                                            struct cli_state *cli)
854 {
855         struct rpc_pipe_client *pipe_hnd = NULL;
856         struct policy_handle sam_pol, domain_pol, user_pol;
857         NTSTATUS status = NT_STATUS_UNSUCCESSFUL, result;
858         char *acct_name;
859         struct lsa_String lsa_acct_name;
860         uint32_t user_rid;
861         uint32_t acct_flags = ACB_WSTRUST;
862         struct samr_Ids user_rids;
863         struct samr_Ids name_types;
864         union samr_UserInfo user_info;
865         struct dcerpc_binding_handle *b = NULL;
866         unsigned int old_timeout = 0;
867
868         DATA_BLOB session_key = data_blob_null;
869         struct samr_CryptPassword crypt_pwd;
870         struct samr_CryptPasswordEx crypt_pwd_ex;
871
872         ZERO_STRUCT(sam_pol);
873         ZERO_STRUCT(domain_pol);
874         ZERO_STRUCT(user_pol);
875
876         switch (r->in.secure_channel_type) {
877         case SEC_CHAN_WKSTA:
878                 acct_flags = ACB_WSTRUST;
879                 break;
880         case SEC_CHAN_BDC:
881                 acct_flags = ACB_SVRTRUST;
882                 break;
883         default:
884                 return NT_STATUS_INVALID_PARAMETER;
885         }
886
887         if (!r->in.machine_password) {
888                 r->in.machine_password = generate_random_password(mem_ctx,
889                                 DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH,
890                                 DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH);
891                 NT_STATUS_HAVE_NO_MEMORY(r->in.machine_password);
892         }
893
894         /* Open the domain */
895
896         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_samr,
897                                           &pipe_hnd);
898         if (!NT_STATUS_IS_OK(status)) {
899                 DEBUG(0,("Error connecting to SAM pipe. Error was %s\n",
900                         nt_errstr(status)));
901                 goto done;
902         }
903
904         b = pipe_hnd->binding_handle;
905
906         status = cli_get_session_key(mem_ctx, pipe_hnd, &session_key);
907         if (!NT_STATUS_IS_OK(status)) {
908                 DEBUG(0,("Error getting session_key of SAM pipe. Error was %s\n",
909                         nt_errstr(status)));
910                 goto done;
911         }
912
913         status = dcerpc_samr_Connect2(b, mem_ctx,
914                                       pipe_hnd->desthost,
915                                       SAMR_ACCESS_ENUM_DOMAINS
916                                       | SAMR_ACCESS_LOOKUP_DOMAIN,
917                                       &sam_pol,
918                                       &result);
919         if (!NT_STATUS_IS_OK(status)) {
920                 goto done;
921         }
922         if (!NT_STATUS_IS_OK(result)) {
923                 status = result;
924                 goto done;
925         }
926
927         status = dcerpc_samr_OpenDomain(b, mem_ctx,
928                                         &sam_pol,
929                                         SAMR_DOMAIN_ACCESS_LOOKUP_INFO_1
930                                         | SAMR_DOMAIN_ACCESS_CREATE_USER
931                                         | SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
932                                         r->out.domain_sid,
933                                         &domain_pol,
934                                         &result);
935         if (!NT_STATUS_IS_OK(status)) {
936                 goto done;
937         }
938         if (!NT_STATUS_IS_OK(result)) {
939                 status = result;
940                 goto done;
941         }
942
943         /* Create domain user */
944
945         acct_name = talloc_asprintf(mem_ctx, "%s$", r->in.machine_name);
946         if (!strlower_m(acct_name)) {
947                 status = NT_STATUS_INVALID_PARAMETER;
948                 goto done;
949         }
950
951         init_lsa_String(&lsa_acct_name, acct_name);
952
953         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE) {
954                 uint32_t access_desired =
955                         SEC_GENERIC_READ | SEC_GENERIC_WRITE | SEC_GENERIC_EXECUTE |
956                         SEC_STD_WRITE_DAC | SEC_STD_DELETE |
957                         SAMR_USER_ACCESS_SET_PASSWORD |
958                         SAMR_USER_ACCESS_GET_ATTRIBUTES |
959                         SAMR_USER_ACCESS_SET_ATTRIBUTES;
960                 uint32_t access_granted = 0;
961
962                 DEBUG(10,("Creating account with desired access mask: %d\n",
963                         access_desired));
964
965                 status = dcerpc_samr_CreateUser2(b, mem_ctx,
966                                                  &domain_pol,
967                                                  &lsa_acct_name,
968                                                  acct_flags,
969                                                  access_desired,
970                                                  &user_pol,
971                                                  &access_granted,
972                                                  &user_rid,
973                                                  &result);
974                 if (!NT_STATUS_IS_OK(status)) {
975                         goto done;
976                 }
977
978                 status = result;
979                 if (!NT_STATUS_IS_OK(status) &&
980                     !NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
981
982                         DEBUG(10,("Creation of workstation account failed: %s\n",
983                                 nt_errstr(status)));
984
985                         /* If NT_STATUS_ACCESS_DENIED then we have a valid
986                            username/password combo but the user does not have
987                            administrator access. */
988
989                         if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
990                                 libnet_join_set_error_string(mem_ctx, r,
991                                         "User specified does not have "
992                                         "administrator privileges");
993                         }
994
995                         goto done;
996                 }
997
998                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
999                         if (!(r->in.join_flags &
1000                               WKSSVC_JOIN_FLAGS_DOMAIN_JOIN_IF_JOINED)) {
1001                                 goto done;
1002                         }
1003                 }
1004
1005                 /* We *must* do this.... don't ask... */
1006
1007                 if (NT_STATUS_IS_OK(status)) {
1008                         dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1009                 }
1010         }
1011
1012         status = dcerpc_samr_LookupNames(b, mem_ctx,
1013                                          &domain_pol,
1014                                          1,
1015                                          &lsa_acct_name,
1016                                          &user_rids,
1017                                          &name_types,
1018                                          &result);
1019         if (!NT_STATUS_IS_OK(status)) {
1020                 goto done;
1021         }
1022         if (!NT_STATUS_IS_OK(result)) {
1023                 status = result;
1024                 goto done;
1025         }
1026
1027         if (name_types.ids[0] != SID_NAME_USER) {
1028                 DEBUG(0,("%s is not a user account (type=%d)\n",
1029                         acct_name, name_types.ids[0]));
1030                 status = NT_STATUS_INVALID_WORKSTATION;
1031                 goto done;
1032         }
1033
1034         user_rid = user_rids.ids[0];
1035
1036         /* Open handle on user */
1037
1038         status = dcerpc_samr_OpenUser(b, mem_ctx,
1039                                       &domain_pol,
1040                                       SEC_FLAG_MAXIMUM_ALLOWED,
1041                                       user_rid,
1042                                       &user_pol,
1043                                       &result);
1044         if (!NT_STATUS_IS_OK(status)) {
1045                 goto done;
1046         }
1047         if (!NT_STATUS_IS_OK(result)) {
1048                 status = result;
1049                 goto done;
1050         }
1051
1052         /* Fill in the additional account flags now */
1053
1054         acct_flags |= ACB_PWNOEXP;
1055
1056         /* Set account flags on machine account */
1057         ZERO_STRUCT(user_info.info16);
1058         user_info.info16.acct_flags = acct_flags;
1059
1060         status = dcerpc_samr_SetUserInfo(b, mem_ctx,
1061                                          &user_pol,
1062                                          16,
1063                                          &user_info,
1064                                          &result);
1065         if (!NT_STATUS_IS_OK(status)) {
1066                 dcerpc_samr_DeleteUser(b, mem_ctx,
1067                                        &user_pol,
1068                                        &result);
1069
1070                 libnet_join_set_error_string(mem_ctx, r,
1071                         "Failed to set account flags for machine account (%s)\n",
1072                         nt_errstr(status));
1073                 goto done;
1074         }
1075
1076         if (!NT_STATUS_IS_OK(result)) {
1077                 status = result;
1078
1079                 dcerpc_samr_DeleteUser(b, mem_ctx,
1080                                        &user_pol,
1081                                        &result);
1082
1083                 libnet_join_set_error_string(mem_ctx, r,
1084                         "Failed to set account flags for machine account (%s)\n",
1085                         nt_errstr(status));
1086                 goto done;
1087         }
1088
1089         /* Set password on machine account - first try level 26 */
1090
1091         /*
1092          * increase the timeout as password filter modules on the DC
1093          * might delay the operation for a significant amount of time
1094          */
1095         old_timeout = rpccli_set_timeout(pipe_hnd, 600000);
1096
1097         init_samr_CryptPasswordEx(r->in.machine_password,
1098                                   &session_key,
1099                                   &crypt_pwd_ex);
1100
1101         user_info.info26.password = crypt_pwd_ex;
1102         user_info.info26.password_expired = PASS_DONT_CHANGE_AT_NEXT_LOGON;
1103
1104         status = dcerpc_samr_SetUserInfo2(b, mem_ctx,
1105                                           &user_pol,
1106                                           26,
1107                                           &user_info,
1108                                           &result);
1109
1110         if (NT_STATUS_EQUAL(status, NT_STATUS_RPC_ENUM_VALUE_OUT_OF_RANGE)) {
1111
1112                 /* retry with level 24 */
1113
1114                 init_samr_CryptPassword(r->in.machine_password,
1115                                         &session_key,
1116                                         &crypt_pwd);
1117
1118                 user_info.info24.password = crypt_pwd;
1119                 user_info.info24.password_expired = PASS_DONT_CHANGE_AT_NEXT_LOGON;
1120
1121                 status = dcerpc_samr_SetUserInfo2(b, mem_ctx,
1122                                                   &user_pol,
1123                                                   24,
1124                                                   &user_info,
1125                                                   &result);
1126         }
1127
1128         old_timeout = rpccli_set_timeout(pipe_hnd, old_timeout);
1129
1130         if (!NT_STATUS_IS_OK(status)) {
1131
1132                 dcerpc_samr_DeleteUser(b, mem_ctx,
1133                                        &user_pol,
1134                                        &result);
1135
1136                 libnet_join_set_error_string(mem_ctx, r,
1137                         "Failed to set password for machine account (%s)\n",
1138                         nt_errstr(status));
1139                 goto done;
1140         }
1141         if (!NT_STATUS_IS_OK(result)) {
1142                 status = result;
1143
1144                 dcerpc_samr_DeleteUser(b, mem_ctx,
1145                                        &user_pol,
1146                                        &result);
1147
1148                 libnet_join_set_error_string(mem_ctx, r,
1149                         "Failed to set password for machine account (%s)\n",
1150                         nt_errstr(status));
1151                 goto done;
1152         }
1153
1154         status = NT_STATUS_OK;
1155
1156  done:
1157         if (!pipe_hnd) {
1158                 return status;
1159         }
1160
1161         data_blob_clear_free(&session_key);
1162
1163         if (is_valid_policy_hnd(&sam_pol)) {
1164                 dcerpc_samr_Close(b, mem_ctx, &sam_pol, &result);
1165         }
1166         if (is_valid_policy_hnd(&domain_pol)) {
1167                 dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
1168         }
1169         if (is_valid_policy_hnd(&user_pol)) {
1170                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1171         }
1172         TALLOC_FREE(pipe_hnd);
1173
1174         return status;
1175 }
1176
1177 /****************************************************************
1178 ****************************************************************/
1179
1180 NTSTATUS libnet_join_ok(const char *netbios_domain_name,
1181                         const char *machine_name,
1182                         const char *dc_name,
1183                         const bool use_kerberos)
1184 {
1185         uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
1186         struct cli_state *cli = NULL;
1187         struct rpc_pipe_client *pipe_hnd = NULL;
1188         struct rpc_pipe_client *netlogon_pipe = NULL;
1189         NTSTATUS status;
1190         char *machine_password = NULL;
1191         char *machine_account = NULL;
1192         int flags = 0;
1193
1194         if (!dc_name) {
1195                 return NT_STATUS_INVALID_PARAMETER;
1196         }
1197
1198         if (!secrets_init()) {
1199                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1200         }
1201
1202         machine_password = secrets_fetch_machine_password(netbios_domain_name,
1203                                                           NULL, NULL);
1204         if (!machine_password) {
1205                 return NT_STATUS_NO_TRUST_LSA_SECRET;
1206         }
1207
1208         if (asprintf(&machine_account, "%s$", machine_name) == -1) {
1209                 SAFE_FREE(machine_password);
1210                 return NT_STATUS_NO_MEMORY;
1211         }
1212
1213         if (use_kerberos) {
1214                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
1215         }
1216
1217         status = cli_full_connection(&cli, NULL,
1218                                      dc_name,
1219                                      NULL, 0,
1220                                      "IPC$", "IPC",
1221                                      machine_account,
1222                                      NULL,
1223                                      machine_password,
1224                                      flags,
1225                                      SMB_SIGNING_DEFAULT);
1226         free(machine_account);
1227         free(machine_password);
1228
1229         if (!NT_STATUS_IS_OK(status)) {
1230                 status = cli_full_connection(&cli, NULL,
1231                                              dc_name,
1232                                              NULL, 0,
1233                                              "IPC$", "IPC",
1234                                              "",
1235                                              NULL,
1236                                              "",
1237                                              0,
1238                                              SMB_SIGNING_DEFAULT);
1239         }
1240
1241         if (!NT_STATUS_IS_OK(status)) {
1242                 return status;
1243         }
1244
1245         status = get_schannel_session_key(cli, netbios_domain_name,
1246                                           &neg_flags, &netlogon_pipe);
1247         if (!NT_STATUS_IS_OK(status)) {
1248                 if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_NETWORK_RESPONSE)) {
1249                         cli_shutdown(cli);
1250                         return NT_STATUS_OK;
1251                 }
1252
1253                 DEBUG(0,("libnet_join_ok: failed to get schannel session "
1254                         "key from server %s for domain %s. Error was %s\n",
1255                         smbXcli_conn_remote_name(cli->conn),
1256                         netbios_domain_name, nt_errstr(status)));
1257                 cli_shutdown(cli);
1258                 return status;
1259         }
1260
1261         if (!lp_client_schannel()) {
1262                 cli_shutdown(cli);
1263                 return NT_STATUS_OK;
1264         }
1265
1266         status = cli_rpc_pipe_open_schannel_with_key(
1267                 cli, &ndr_table_netlogon, NCACN_NP,
1268                 DCERPC_AUTH_LEVEL_PRIVACY,
1269                 netbios_domain_name, &netlogon_pipe->dc, &pipe_hnd);
1270
1271         cli_shutdown(cli);
1272
1273         if (!NT_STATUS_IS_OK(status)) {
1274                 DEBUG(0,("libnet_join_ok: failed to open schannel session "
1275                         "on netlogon pipe to server %s for domain %s. "
1276                         "Error was %s\n",
1277                         smbXcli_conn_remote_name(cli->conn),
1278                         netbios_domain_name, nt_errstr(status)));
1279                 return status;
1280         }
1281
1282         return NT_STATUS_OK;
1283 }
1284
1285 /****************************************************************
1286 ****************************************************************/
1287
1288 static WERROR libnet_join_post_verify(TALLOC_CTX *mem_ctx,
1289                                       struct libnet_JoinCtx *r)
1290 {
1291         NTSTATUS status;
1292
1293         status = libnet_join_ok(r->out.netbios_domain_name,
1294                                 r->in.machine_name,
1295                                 r->in.dc_name,
1296                                 r->in.use_kerberos);
1297         if (!NT_STATUS_IS_OK(status)) {
1298                 libnet_join_set_error_string(mem_ctx, r,
1299                         "failed to verify domain membership after joining: %s",
1300                         get_friendly_nt_error_msg(status));
1301                 return WERR_SETUP_NOT_JOINED;
1302         }
1303
1304         return WERR_OK;
1305 }
1306
1307 /****************************************************************
1308 ****************************************************************/
1309
1310 static bool libnet_join_unjoindomain_remove_secrets(TALLOC_CTX *mem_ctx,
1311                                                     struct libnet_UnjoinCtx *r)
1312 {
1313         if (!secrets_delete_machine_password_ex(lp_workgroup())) {
1314                 return false;
1315         }
1316
1317         if (!secrets_delete_domain_sid(lp_workgroup())) {
1318                 return false;
1319         }
1320
1321         return true;
1322 }
1323
1324 /****************************************************************
1325 ****************************************************************/
1326
1327 static NTSTATUS libnet_join_unjoindomain_rpc(TALLOC_CTX *mem_ctx,
1328                                              struct libnet_UnjoinCtx *r)
1329 {
1330         struct cli_state *cli = NULL;
1331         struct rpc_pipe_client *pipe_hnd = NULL;
1332         struct policy_handle sam_pol, domain_pol, user_pol;
1333         NTSTATUS status = NT_STATUS_UNSUCCESSFUL, result;
1334         char *acct_name;
1335         uint32_t user_rid;
1336         struct lsa_String lsa_acct_name;
1337         struct samr_Ids user_rids;
1338         struct samr_Ids name_types;
1339         union samr_UserInfo *info = NULL;
1340         struct dcerpc_binding_handle *b = NULL;
1341
1342         ZERO_STRUCT(sam_pol);
1343         ZERO_STRUCT(domain_pol);
1344         ZERO_STRUCT(user_pol);
1345
1346         status = libnet_join_connect_dc_ipc(r->in.dc_name,
1347                                             r->in.admin_account,
1348                                             r->in.admin_password,
1349                                             r->in.use_kerberos,
1350                                             &cli);
1351         if (!NT_STATUS_IS_OK(status)) {
1352                 goto done;
1353         }
1354
1355         /* Open the domain */
1356
1357         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_samr,
1358                                           &pipe_hnd);
1359         if (!NT_STATUS_IS_OK(status)) {
1360                 DEBUG(0,("Error connecting to SAM pipe. Error was %s\n",
1361                         nt_errstr(status)));
1362                 goto done;
1363         }
1364
1365         b = pipe_hnd->binding_handle;
1366
1367         status = dcerpc_samr_Connect2(b, mem_ctx,
1368                                       pipe_hnd->desthost,
1369                                       SEC_FLAG_MAXIMUM_ALLOWED,
1370                                       &sam_pol,
1371                                       &result);
1372         if (!NT_STATUS_IS_OK(status)) {
1373                 goto done;
1374         }
1375         if (!NT_STATUS_IS_OK(result)) {
1376                 status = result;
1377                 goto done;
1378         }
1379
1380         status = dcerpc_samr_OpenDomain(b, mem_ctx,
1381                                         &sam_pol,
1382                                         SEC_FLAG_MAXIMUM_ALLOWED,
1383                                         r->in.domain_sid,
1384                                         &domain_pol,
1385                                         &result);
1386         if (!NT_STATUS_IS_OK(status)) {
1387                 goto done;
1388         }
1389         if (!NT_STATUS_IS_OK(result)) {
1390                 status = result;
1391                 goto done;
1392         }
1393
1394         /* Create domain user */
1395
1396         acct_name = talloc_asprintf(mem_ctx, "%s$", r->in.machine_name);
1397         if (!strlower_m(acct_name)) {
1398                 status = NT_STATUS_INVALID_PARAMETER;
1399                 goto done;
1400         }
1401
1402         init_lsa_String(&lsa_acct_name, acct_name);
1403
1404         status = dcerpc_samr_LookupNames(b, mem_ctx,
1405                                          &domain_pol,
1406                                          1,
1407                                          &lsa_acct_name,
1408                                          &user_rids,
1409                                          &name_types,
1410                                          &result);
1411
1412         if (!NT_STATUS_IS_OK(status)) {
1413                 goto done;
1414         }
1415         if (!NT_STATUS_IS_OK(result)) {
1416                 status = result;
1417                 goto done;
1418         }
1419
1420         if (name_types.ids[0] != SID_NAME_USER) {
1421                 DEBUG(0, ("%s is not a user account (type=%d)\n", acct_name,
1422                         name_types.ids[0]));
1423                 status = NT_STATUS_INVALID_WORKSTATION;
1424                 goto done;
1425         }
1426
1427         user_rid = user_rids.ids[0];
1428
1429         /* Open handle on user */
1430
1431         status = dcerpc_samr_OpenUser(b, mem_ctx,
1432                                       &domain_pol,
1433                                       SEC_FLAG_MAXIMUM_ALLOWED,
1434                                       user_rid,
1435                                       &user_pol,
1436                                       &result);
1437         if (!NT_STATUS_IS_OK(status)) {
1438                 goto done;
1439         }
1440         if (!NT_STATUS_IS_OK(result)) {
1441                 status = result;
1442                 goto done;
1443         }
1444
1445         /* Get user info */
1446
1447         status = dcerpc_samr_QueryUserInfo(b, mem_ctx,
1448                                            &user_pol,
1449                                            16,
1450                                            &info,
1451                                            &result);
1452         if (!NT_STATUS_IS_OK(status)) {
1453                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1454                 goto done;
1455         }
1456         if (!NT_STATUS_IS_OK(result)) {
1457                 status = result;
1458                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1459                 goto done;
1460         }
1461
1462         /* now disable and setuser info */
1463
1464         info->info16.acct_flags |= ACB_DISABLED;
1465
1466         status = dcerpc_samr_SetUserInfo(b, mem_ctx,
1467                                          &user_pol,
1468                                          16,
1469                                          info,
1470                                          &result);
1471         if (!NT_STATUS_IS_OK(status)) {
1472                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1473                 goto done;
1474         }
1475         if (!NT_STATUS_IS_OK(result)) {
1476                 status = result;
1477                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1478                 goto done;
1479         }
1480         status = result;
1481         dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1482
1483 done:
1484         if (pipe_hnd && b) {
1485                 if (is_valid_policy_hnd(&domain_pol)) {
1486                         dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
1487                 }
1488                 if (is_valid_policy_hnd(&sam_pol)) {
1489                         dcerpc_samr_Close(b, mem_ctx, &sam_pol, &result);
1490                 }
1491                 TALLOC_FREE(pipe_hnd);
1492         }
1493
1494         if (cli) {
1495                 cli_shutdown(cli);
1496         }
1497
1498         return status;
1499 }
1500
1501 /****************************************************************
1502 ****************************************************************/
1503
1504 static WERROR do_join_modify_vals_config(struct libnet_JoinCtx *r)
1505 {
1506         WERROR werr = WERR_OK;
1507         sbcErr err;
1508         struct smbconf_ctx *ctx;
1509
1510         err = smbconf_init_reg(r, &ctx, NULL);
1511         if (!SBC_ERROR_IS_OK(err)) {
1512                 werr = WERR_NO_SUCH_SERVICE;
1513                 goto done;
1514         }
1515
1516         if (!(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE)) {
1517
1518                 err = smbconf_set_global_parameter(ctx, "security", "user");
1519                 if (!SBC_ERROR_IS_OK(err)) {
1520                         werr = WERR_NO_SUCH_SERVICE;
1521                         goto done;
1522                 }
1523
1524                 err = smbconf_set_global_parameter(ctx, "workgroup",
1525                                                    r->in.domain_name);
1526                 if (!SBC_ERROR_IS_OK(err)) {
1527                         werr = WERR_NO_SUCH_SERVICE;
1528                         goto done;
1529                 }
1530
1531                 smbconf_delete_global_parameter(ctx, "realm");
1532                 goto done;
1533         }
1534
1535         err = smbconf_set_global_parameter(ctx, "security", "domain");
1536         if (!SBC_ERROR_IS_OK(err)) {
1537                 werr = WERR_NO_SUCH_SERVICE;
1538                 goto done;
1539         }
1540
1541         err = smbconf_set_global_parameter(ctx, "workgroup",
1542                                            r->out.netbios_domain_name);
1543         if (!SBC_ERROR_IS_OK(err)) {
1544                 werr = WERR_NO_SUCH_SERVICE;
1545                 goto done;
1546         }
1547
1548         if (r->out.domain_is_ad) {
1549                 err = smbconf_set_global_parameter(ctx, "security", "ads");
1550                 if (!SBC_ERROR_IS_OK(err)) {
1551                         werr = WERR_NO_SUCH_SERVICE;
1552                         goto done;
1553                 }
1554
1555                 err = smbconf_set_global_parameter(ctx, "realm",
1556                                                    r->out.dns_domain_name);
1557                 if (!SBC_ERROR_IS_OK(err)) {
1558                         werr = WERR_NO_SUCH_SERVICE;
1559                         goto done;
1560                 }
1561         }
1562
1563  done:
1564         smbconf_shutdown(ctx);
1565         return werr;
1566 }
1567
1568 /****************************************************************
1569 ****************************************************************/
1570
1571 static WERROR do_unjoin_modify_vals_config(struct libnet_UnjoinCtx *r)
1572 {
1573         WERROR werr = WERR_OK;
1574         sbcErr err;
1575         struct smbconf_ctx *ctx;
1576
1577         err = smbconf_init_reg(r, &ctx, NULL);
1578         if (!SBC_ERROR_IS_OK(err)) {
1579                 werr = WERR_NO_SUCH_SERVICE;
1580                 goto done;
1581         }
1582
1583         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1584
1585                 err = smbconf_set_global_parameter(ctx, "security", "user");
1586                 if (!SBC_ERROR_IS_OK(err)) {
1587                         werr = WERR_NO_SUCH_SERVICE;
1588                         goto done;
1589                 }
1590
1591                 err = smbconf_delete_global_parameter(ctx, "workgroup");
1592                 if (!SBC_ERROR_IS_OK(err)) {
1593                         werr = WERR_NO_SUCH_SERVICE;
1594                         goto done;
1595                 }
1596
1597                 smbconf_delete_global_parameter(ctx, "realm");
1598         }
1599
1600  done:
1601         smbconf_shutdown(ctx);
1602         return werr;
1603 }
1604
1605 /****************************************************************
1606 ****************************************************************/
1607
1608 static WERROR do_JoinConfig(struct libnet_JoinCtx *r)
1609 {
1610         WERROR werr;
1611
1612         if (!W_ERROR_IS_OK(r->out.result)) {
1613                 return r->out.result;
1614         }
1615
1616         if (!r->in.modify_config) {
1617                 return WERR_OK;
1618         }
1619
1620         werr = do_join_modify_vals_config(r);
1621         if (!W_ERROR_IS_OK(werr)) {
1622                 return werr;
1623         }
1624
1625         lp_load_global(get_dyn_CONFIGFILE());
1626
1627         r->out.modified_config = true;
1628         r->out.result = werr;
1629
1630         return werr;
1631 }
1632
1633 /****************************************************************
1634 ****************************************************************/
1635
1636 static WERROR libnet_unjoin_config(struct libnet_UnjoinCtx *r)
1637 {
1638         WERROR werr;
1639
1640         if (!W_ERROR_IS_OK(r->out.result)) {
1641                 return r->out.result;
1642         }
1643
1644         if (!r->in.modify_config) {
1645                 return WERR_OK;
1646         }
1647
1648         werr = do_unjoin_modify_vals_config(r);
1649         if (!W_ERROR_IS_OK(werr)) {
1650                 return werr;
1651         }
1652
1653         lp_load_global(get_dyn_CONFIGFILE());
1654
1655         r->out.modified_config = true;
1656         r->out.result = werr;
1657
1658         return werr;
1659 }
1660
1661 /****************************************************************
1662 ****************************************************************/
1663
1664 static bool libnet_parse_domain_dc(TALLOC_CTX *mem_ctx,
1665                                    const char *domain_str,
1666                                    const char **domain_p,
1667                                    const char **dc_p)
1668 {
1669         char *domain = NULL;
1670         char *dc = NULL;
1671         const char *p = NULL;
1672
1673         if (!domain_str || !domain_p || !dc_p) {
1674                 return false;
1675         }
1676
1677         p = strchr_m(domain_str, '\\');
1678
1679         if (p != NULL) {
1680                 domain = talloc_strndup(mem_ctx, domain_str,
1681                                          PTR_DIFF(p, domain_str));
1682                 dc = talloc_strdup(mem_ctx, p+1);
1683                 if (!dc) {
1684                         return false;
1685                 }
1686         } else {
1687                 domain = talloc_strdup(mem_ctx, domain_str);
1688                 dc = NULL;
1689         }
1690         if (!domain) {
1691                 return false;
1692         }
1693
1694         *domain_p = domain;
1695
1696         if (!*dc_p && dc) {
1697                 *dc_p = dc;
1698         }
1699
1700         return true;
1701 }
1702
1703 /****************************************************************
1704 ****************************************************************/
1705
1706 static WERROR libnet_join_pre_processing(TALLOC_CTX *mem_ctx,
1707                                          struct libnet_JoinCtx *r)
1708 {
1709         if (!r->in.domain_name) {
1710                 libnet_join_set_error_string(mem_ctx, r,
1711                         "No domain name defined");
1712                 return WERR_INVALID_PARAM;
1713         }
1714
1715         if (!libnet_parse_domain_dc(mem_ctx, r->in.domain_name,
1716                                     &r->in.domain_name,
1717                                     &r->in.dc_name)) {
1718                 libnet_join_set_error_string(mem_ctx, r,
1719                         "Failed to parse domain name");
1720                 return WERR_INVALID_PARAM;
1721         }
1722
1723         if (IS_DC) {
1724                 return WERR_SETUP_DOMAIN_CONTROLLER;
1725         }
1726
1727         if (!secrets_init()) {
1728                 libnet_join_set_error_string(mem_ctx, r,
1729                         "Unable to open secrets database");
1730                 return WERR_CAN_NOT_COMPLETE;
1731         }
1732
1733         return WERR_OK;
1734 }
1735
1736 /****************************************************************
1737 ****************************************************************/
1738
1739 static void libnet_join_add_dom_rids_to_builtins(struct dom_sid *domain_sid)
1740 {
1741         NTSTATUS status;
1742
1743         /* Try adding dom admins to builtin\admins. Only log failures. */
1744         status = create_builtin_administrators(domain_sid);
1745         if (NT_STATUS_EQUAL(status, NT_STATUS_PROTOCOL_UNREACHABLE)) {
1746                 DEBUG(10,("Unable to auto-add domain administrators to "
1747                           "BUILTIN\\Administrators during join because "
1748                           "winbindd must be running.\n"));
1749         } else if (!NT_STATUS_IS_OK(status)) {
1750                 DEBUG(5, ("Failed to auto-add domain administrators to "
1751                           "BUILTIN\\Administrators during join: %s\n",
1752                           nt_errstr(status)));
1753         }
1754
1755         /* Try adding dom users to builtin\users. Only log failures. */
1756         status = create_builtin_users(domain_sid);
1757         if (NT_STATUS_EQUAL(status, NT_STATUS_PROTOCOL_UNREACHABLE)) {
1758                 DEBUG(10,("Unable to auto-add domain users to BUILTIN\\users "
1759                           "during join because winbindd must be running.\n"));
1760         } else if (!NT_STATUS_IS_OK(status)) {
1761                 DEBUG(5, ("Failed to auto-add domain administrators to "
1762                           "BUILTIN\\Administrators during join: %s\n",
1763                           nt_errstr(status)));
1764         }
1765 }
1766
1767 /****************************************************************
1768 ****************************************************************/
1769
1770 static WERROR libnet_join_post_processing(TALLOC_CTX *mem_ctx,
1771                                           struct libnet_JoinCtx *r)
1772 {
1773         WERROR werr;
1774
1775         if (!W_ERROR_IS_OK(r->out.result)) {
1776                 return r->out.result;
1777         }
1778
1779         werr = do_JoinConfig(r);
1780         if (!W_ERROR_IS_OK(werr)) {
1781                 return werr;
1782         }
1783
1784         if (!(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE)) {
1785                 return WERR_OK;
1786         }
1787
1788         saf_join_store(r->out.netbios_domain_name, r->in.dc_name);
1789         if (r->out.dns_domain_name) {
1790                 saf_join_store(r->out.dns_domain_name, r->in.dc_name);
1791         }
1792
1793 #ifdef HAVE_ADS
1794         if (r->out.domain_is_ad &&
1795             !(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE)) {
1796                 ADS_STATUS ads_status;
1797
1798                 ads_status  = libnet_join_post_processing_ads(mem_ctx, r);
1799                 if (!ADS_ERR_OK(ads_status)) {
1800                         return WERR_GENERAL_FAILURE;
1801                 }
1802         }
1803 #endif /* HAVE_ADS */
1804
1805         libnet_join_add_dom_rids_to_builtins(r->out.domain_sid);
1806
1807         return WERR_OK;
1808 }
1809
1810 /****************************************************************
1811 ****************************************************************/
1812
1813 static int libnet_destroy_JoinCtx(struct libnet_JoinCtx *r)
1814 {
1815         if (r->in.ads) {
1816                 ads_destroy(&r->in.ads);
1817         }
1818
1819         return 0;
1820 }
1821
1822 /****************************************************************
1823 ****************************************************************/
1824
1825 static int libnet_destroy_UnjoinCtx(struct libnet_UnjoinCtx *r)
1826 {
1827         if (r->in.ads) {
1828                 ads_destroy(&r->in.ads);
1829         }
1830
1831         return 0;
1832 }
1833
1834 /****************************************************************
1835 ****************************************************************/
1836
1837 WERROR libnet_init_JoinCtx(TALLOC_CTX *mem_ctx,
1838                            struct libnet_JoinCtx **r)
1839 {
1840         struct libnet_JoinCtx *ctx;
1841
1842         ctx = talloc_zero(mem_ctx, struct libnet_JoinCtx);
1843         if (!ctx) {
1844                 return WERR_NOMEM;
1845         }
1846
1847         talloc_set_destructor(ctx, libnet_destroy_JoinCtx);
1848
1849         ctx->in.machine_name = talloc_strdup(mem_ctx, lp_netbios_name());
1850         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
1851
1852         ctx->in.secure_channel_type = SEC_CHAN_WKSTA;
1853
1854         *r = ctx;
1855
1856         return WERR_OK;
1857 }
1858
1859 /****************************************************************
1860 ****************************************************************/
1861
1862 WERROR libnet_init_UnjoinCtx(TALLOC_CTX *mem_ctx,
1863                              struct libnet_UnjoinCtx **r)
1864 {
1865         struct libnet_UnjoinCtx *ctx;
1866
1867         ctx = talloc_zero(mem_ctx, struct libnet_UnjoinCtx);
1868         if (!ctx) {
1869                 return WERR_NOMEM;
1870         }
1871
1872         talloc_set_destructor(ctx, libnet_destroy_UnjoinCtx);
1873
1874         ctx->in.machine_name = talloc_strdup(mem_ctx, lp_netbios_name());
1875         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
1876
1877         *r = ctx;
1878
1879         return WERR_OK;
1880 }
1881
1882 /****************************************************************
1883 ****************************************************************/
1884
1885 static WERROR libnet_join_check_config(TALLOC_CTX *mem_ctx,
1886                                        struct libnet_JoinCtx *r)
1887 {
1888         bool valid_security = false;
1889         bool valid_workgroup = false;
1890         bool valid_realm = false;
1891
1892         /* check if configuration is already set correctly */
1893
1894         valid_workgroup = strequal(lp_workgroup(), r->out.netbios_domain_name);
1895
1896         switch (r->out.domain_is_ad) {
1897                 case false:
1898                         valid_security = (lp_security() == SEC_DOMAIN);
1899                         if (valid_workgroup && valid_security) {
1900                                 /* nothing to be done */
1901                                 return WERR_OK;
1902                         }
1903                         break;
1904                 case true:
1905                         valid_realm = strequal(lp_realm(), r->out.dns_domain_name);
1906                         switch (lp_security()) {
1907                         case SEC_DOMAIN:
1908                         case SEC_ADS:
1909                                 valid_security = true;
1910                         }
1911
1912                         if (valid_workgroup && valid_realm && valid_security) {
1913                                 /* nothing to be done */
1914                                 return WERR_OK;
1915                         }
1916                         break;
1917         }
1918
1919         /* check if we are supposed to manipulate configuration */
1920
1921         if (!r->in.modify_config) {
1922
1923                 char *wrong_conf = talloc_strdup(mem_ctx, "");
1924
1925                 if (!valid_workgroup) {
1926                         wrong_conf = talloc_asprintf_append(wrong_conf,
1927                                 "\"workgroup\" set to '%s', should be '%s'",
1928                                 lp_workgroup(), r->out.netbios_domain_name);
1929                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
1930                 }
1931
1932                 if (!valid_realm) {
1933                         wrong_conf = talloc_asprintf_append(wrong_conf,
1934                                 "\"realm\" set to '%s', should be '%s'",
1935                                 lp_realm(), r->out.dns_domain_name);
1936                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
1937                 }
1938
1939                 if (!valid_security) {
1940                         const char *sec = NULL;
1941                         switch (lp_security()) {
1942                         case SEC_USER:  sec = "user"; break;
1943                         case SEC_DOMAIN: sec = "domain"; break;
1944                         case SEC_ADS: sec = "ads"; break;
1945                         }
1946                         wrong_conf = talloc_asprintf_append(wrong_conf,
1947                                 "\"security\" set to '%s', should be %s",
1948                                 sec, r->out.domain_is_ad ?
1949                                 "either 'domain' or 'ads'" : "'domain'");
1950                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
1951                 }
1952
1953                 libnet_join_set_error_string(mem_ctx, r,
1954                         "Invalid configuration (%s) and configuration modification "
1955                         "was not requested", wrong_conf);
1956                 return WERR_CAN_NOT_COMPLETE;
1957         }
1958
1959         /* check if we are able to manipulate configuration */
1960
1961         if (!lp_config_backend_is_registry()) {
1962                 libnet_join_set_error_string(mem_ctx, r,
1963                         "Configuration manipulation requested but not "
1964                         "supported by backend");
1965                 return WERR_NOT_SUPPORTED;
1966         }
1967
1968         return WERR_OK;
1969 }
1970
1971 /****************************************************************
1972 ****************************************************************/
1973
1974 static WERROR libnet_DomainJoin(TALLOC_CTX *mem_ctx,
1975                                 struct libnet_JoinCtx *r)
1976 {
1977         NTSTATUS status;
1978         WERROR werr;
1979         struct cli_state *cli = NULL;
1980 #ifdef HAVE_ADS
1981         ADS_STATUS ads_status;
1982 #endif /* HAVE_ADS */
1983
1984         if (!r->in.dc_name) {
1985                 struct netr_DsRGetDCNameInfo *info;
1986                 const char *dc;
1987                 status = dsgetdcname(mem_ctx,
1988                                      r->in.msg_ctx,
1989                                      r->in.domain_name,
1990                                      NULL,
1991                                      NULL,
1992                                      DS_FORCE_REDISCOVERY |
1993                                      DS_DIRECTORY_SERVICE_REQUIRED |
1994                                      DS_WRITABLE_REQUIRED |
1995                                      DS_RETURN_DNS_NAME,
1996                                      &info);
1997                 if (!NT_STATUS_IS_OK(status)) {
1998                         libnet_join_set_error_string(mem_ctx, r,
1999                                 "failed to find DC for domain %s",
2000                                 r->in.domain_name,
2001                                 get_friendly_nt_error_msg(status));
2002                         return WERR_DCNOTFOUND;
2003                 }
2004
2005                 dc = strip_hostname(info->dc_unc);
2006                 r->in.dc_name = talloc_strdup(mem_ctx, dc);
2007                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
2008         }
2009
2010         status = libnet_join_lookup_dc_rpc(mem_ctx, r, &cli);
2011         if (!NT_STATUS_IS_OK(status)) {
2012                 libnet_join_set_error_string(mem_ctx, r,
2013                         "failed to lookup DC info for domain '%s' over rpc: %s",
2014                         r->in.domain_name, get_friendly_nt_error_msg(status));
2015                 return ntstatus_to_werror(status);
2016         }
2017
2018         werr = libnet_join_check_config(mem_ctx, r);
2019         if (!W_ERROR_IS_OK(werr)) {
2020                 goto done;
2021         }
2022
2023 #ifdef HAVE_ADS
2024
2025         create_local_private_krb5_conf_for_domain(
2026                 r->out.dns_domain_name, r->out.netbios_domain_name,
2027                 NULL, smbXcli_conn_remote_sockaddr(cli->conn),
2028                 smbXcli_conn_remote_name(cli->conn));
2029
2030         if (r->out.domain_is_ad && r->in.account_ou &&
2031             !(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE)) {
2032
2033                 ads_status = libnet_join_connect_ads(mem_ctx, r);
2034                 if (!ADS_ERR_OK(ads_status)) {
2035                         return WERR_DEFAULT_JOIN_REQUIRED;
2036                 }
2037
2038                 ads_status = libnet_join_precreate_machine_acct(mem_ctx, r);
2039                 if (!ADS_ERR_OK(ads_status)) {
2040                         libnet_join_set_error_string(mem_ctx, r,
2041                                 "failed to precreate account in ou %s: %s",
2042                                 r->in.account_ou,
2043                                 ads_errstr(ads_status));
2044                         return WERR_DEFAULT_JOIN_REQUIRED;
2045                 }
2046
2047                 r->in.join_flags &= ~WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE;
2048         }
2049 #endif /* HAVE_ADS */
2050
2051         if ((r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE) &&
2052             (r->in.join_flags & WKSSVC_JOIN_FLAGS_MACHINE_PWD_PASSED)) {
2053                 status = libnet_join_joindomain_rpc_unsecure(mem_ctx, r, cli);
2054         } else {
2055                 status = libnet_join_joindomain_rpc(mem_ctx, r, cli);
2056         }
2057         if (!NT_STATUS_IS_OK(status)) {
2058                 libnet_join_set_error_string(mem_ctx, r,
2059                         "failed to join domain '%s' over rpc: %s",
2060                         r->in.domain_name, get_friendly_nt_error_msg(status));
2061                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
2062                         return WERR_SETUP_ALREADY_JOINED;
2063                 }
2064                 werr = ntstatus_to_werror(status);
2065                 goto done;
2066         }
2067
2068         if (!libnet_join_joindomain_store_secrets(mem_ctx, r)) {
2069                 werr = WERR_SETUP_NOT_JOINED;
2070                 goto done;
2071         }
2072
2073         werr = WERR_OK;
2074
2075  done:
2076         if (cli) {
2077                 cli_shutdown(cli);
2078         }
2079
2080         return werr;
2081 }
2082
2083 /****************************************************************
2084 ****************************************************************/
2085
2086 static WERROR libnet_join_rollback(TALLOC_CTX *mem_ctx,
2087                                    struct libnet_JoinCtx *r)
2088 {
2089         WERROR werr;
2090         struct libnet_UnjoinCtx *u = NULL;
2091
2092         werr = libnet_init_UnjoinCtx(mem_ctx, &u);
2093         if (!W_ERROR_IS_OK(werr)) {
2094                 return werr;
2095         }
2096
2097         u->in.debug             = r->in.debug;
2098         u->in.dc_name           = r->in.dc_name;
2099         u->in.domain_name       = r->in.domain_name;
2100         u->in.admin_account     = r->in.admin_account;
2101         u->in.admin_password    = r->in.admin_password;
2102         u->in.modify_config     = r->in.modify_config;
2103         u->in.use_kerberos      = r->in.use_kerberos;
2104         u->in.unjoin_flags      = WKSSVC_JOIN_FLAGS_JOIN_TYPE |
2105                                   WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE;
2106
2107         werr = libnet_Unjoin(mem_ctx, u);
2108         TALLOC_FREE(u);
2109
2110         return werr;
2111 }
2112
2113 /****************************************************************
2114 ****************************************************************/
2115
2116 WERROR libnet_Join(TALLOC_CTX *mem_ctx,
2117                    struct libnet_JoinCtx *r)
2118 {
2119         WERROR werr;
2120
2121         if (r->in.debug) {
2122                 LIBNET_JOIN_IN_DUMP_CTX(mem_ctx, r);
2123         }
2124
2125         ZERO_STRUCT(r->out);
2126
2127         werr = libnet_join_pre_processing(mem_ctx, r);
2128         if (!W_ERROR_IS_OK(werr)) {
2129                 goto done;
2130         }
2131
2132         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
2133                 werr = libnet_DomainJoin(mem_ctx, r);
2134                 if (!W_ERROR_IS_OK(werr)) {
2135                         goto done;
2136                 }
2137         }
2138
2139         werr = libnet_join_post_processing(mem_ctx, r);
2140         if (!W_ERROR_IS_OK(werr)) {
2141                 goto done;
2142         }
2143
2144         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
2145                 werr = libnet_join_post_verify(mem_ctx, r);
2146                 if (!W_ERROR_IS_OK(werr)) {
2147                         libnet_join_rollback(mem_ctx, r);
2148                 }
2149         }
2150
2151  done:
2152         r->out.result = werr;
2153
2154         if (r->in.debug) {
2155                 LIBNET_JOIN_OUT_DUMP_CTX(mem_ctx, r);
2156         }
2157         return werr;
2158 }
2159
2160 /****************************************************************
2161 ****************************************************************/
2162
2163 static WERROR libnet_DomainUnjoin(TALLOC_CTX *mem_ctx,
2164                                   struct libnet_UnjoinCtx *r)
2165 {
2166         NTSTATUS status;
2167
2168         if (!r->in.domain_sid) {
2169                 struct dom_sid sid;
2170                 if (!secrets_fetch_domain_sid(lp_workgroup(), &sid)) {
2171                         libnet_unjoin_set_error_string(mem_ctx, r,
2172                                 "Unable to fetch domain sid: are we joined?");
2173                         return WERR_SETUP_NOT_JOINED;
2174                 }
2175                 r->in.domain_sid = dom_sid_dup(mem_ctx, &sid);
2176                 W_ERROR_HAVE_NO_MEMORY(r->in.domain_sid);
2177         }
2178
2179         if (!(r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE) && 
2180             !r->in.delete_machine_account) {
2181                 libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2182                 return WERR_OK;
2183         }
2184
2185         if (!r->in.dc_name) {
2186                 struct netr_DsRGetDCNameInfo *info;
2187                 const char *dc;
2188                 status = dsgetdcname(mem_ctx,
2189                                      r->in.msg_ctx,
2190                                      r->in.domain_name,
2191                                      NULL,
2192                                      NULL,
2193                                      DS_DIRECTORY_SERVICE_REQUIRED |
2194                                      DS_WRITABLE_REQUIRED |
2195                                      DS_RETURN_DNS_NAME,
2196                                      &info);
2197                 if (!NT_STATUS_IS_OK(status)) {
2198                         libnet_unjoin_set_error_string(mem_ctx, r,
2199                                 "failed to find DC for domain %s",
2200                                 r->in.domain_name,
2201                                 get_friendly_nt_error_msg(status));
2202                         return WERR_DCNOTFOUND;
2203                 }
2204
2205                 dc = strip_hostname(info->dc_unc);
2206                 r->in.dc_name = talloc_strdup(mem_ctx, dc);
2207                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
2208         }
2209
2210 #ifdef HAVE_ADS
2211         /* for net ads leave, try to delete the account.  If it works, 
2212            no sense in disabling.  If it fails, we can still try to 
2213            disable it. jmcd */
2214
2215         if (r->in.delete_machine_account) {
2216                 ADS_STATUS ads_status;
2217                 ads_status = libnet_unjoin_connect_ads(mem_ctx, r);
2218                 if (ADS_ERR_OK(ads_status)) {
2219                         /* dirty hack */
2220                         r->out.dns_domain_name = 
2221                                 talloc_strdup(mem_ctx,
2222                                               r->in.ads->server.realm);
2223                         ads_status = 
2224                                 libnet_unjoin_remove_machine_acct(mem_ctx, r);
2225                 }
2226                 if (!ADS_ERR_OK(ads_status)) {
2227                         libnet_unjoin_set_error_string(mem_ctx, r,
2228                                 "failed to remove machine account from AD: %s",
2229                                 ads_errstr(ads_status));
2230                 } else {
2231                         r->out.deleted_machine_account = true;
2232                         W_ERROR_HAVE_NO_MEMORY(r->out.dns_domain_name);
2233                         libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2234                         return WERR_OK;
2235                 }
2236         }
2237 #endif /* HAVE_ADS */
2238
2239         /* The WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE flag really means 
2240            "disable".  */
2241         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE) {
2242                 status = libnet_join_unjoindomain_rpc(mem_ctx, r);
2243                 if (!NT_STATUS_IS_OK(status)) {
2244                         libnet_unjoin_set_error_string(mem_ctx, r,
2245                                 "failed to disable machine account via rpc: %s",
2246                                 get_friendly_nt_error_msg(status));
2247                         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER)) {
2248                                 return WERR_SETUP_NOT_JOINED;
2249                         }
2250                         return ntstatus_to_werror(status);
2251                 }
2252
2253                 r->out.disabled_machine_account = true;
2254         }
2255
2256         /* If disable succeeded or was not requested at all, we 
2257            should be getting rid of our end of things */
2258
2259         libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2260
2261         return WERR_OK;
2262 }
2263
2264 /****************************************************************
2265 ****************************************************************/
2266
2267 static WERROR libnet_unjoin_pre_processing(TALLOC_CTX *mem_ctx,
2268                                            struct libnet_UnjoinCtx *r)
2269 {
2270         if (!r->in.domain_name) {
2271                 libnet_unjoin_set_error_string(mem_ctx, r,
2272                         "No domain name defined");
2273                 return WERR_INVALID_PARAM;
2274         }
2275
2276         if (!libnet_parse_domain_dc(mem_ctx, r->in.domain_name,
2277                                     &r->in.domain_name,
2278                                     &r->in.dc_name)) {
2279                 libnet_unjoin_set_error_string(mem_ctx, r,
2280                         "Failed to parse domain name");
2281                 return WERR_INVALID_PARAM;
2282         }
2283
2284         if (IS_DC) {
2285                 return WERR_SETUP_DOMAIN_CONTROLLER;
2286         }
2287
2288         if (!secrets_init()) {
2289                 libnet_unjoin_set_error_string(mem_ctx, r,
2290                         "Unable to open secrets database");
2291                 return WERR_CAN_NOT_COMPLETE;
2292         }
2293
2294         return WERR_OK;
2295 }
2296
2297 /****************************************************************
2298 ****************************************************************/
2299
2300 static WERROR libnet_unjoin_post_processing(TALLOC_CTX *mem_ctx,
2301                                             struct libnet_UnjoinCtx *r)
2302 {
2303         saf_delete(r->out.netbios_domain_name);
2304         saf_delete(r->out.dns_domain_name);
2305
2306         return libnet_unjoin_config(r);
2307 }
2308
2309 /****************************************************************
2310 ****************************************************************/
2311
2312 WERROR libnet_Unjoin(TALLOC_CTX *mem_ctx,
2313                      struct libnet_UnjoinCtx *r)
2314 {
2315         WERROR werr;
2316
2317         if (r->in.debug) {
2318                 LIBNET_UNJOIN_IN_DUMP_CTX(mem_ctx, r);
2319         }
2320
2321         werr = libnet_unjoin_pre_processing(mem_ctx, r);
2322         if (!W_ERROR_IS_OK(werr)) {
2323                 goto done;
2324         }
2325
2326         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
2327                 werr = libnet_DomainUnjoin(mem_ctx, r);
2328                 if (!W_ERROR_IS_OK(werr)) {
2329                         libnet_unjoin_config(r);
2330                         goto done;
2331                 }
2332         }
2333
2334         werr = libnet_unjoin_post_processing(mem_ctx, r);
2335         if (!W_ERROR_IS_OK(werr)) {
2336                 goto done;
2337         }
2338
2339  done:
2340         r->out.result = werr;
2341
2342         if (r->in.debug) {
2343                 LIBNET_UNJOIN_OUT_DUMP_CTX(mem_ctx, r);
2344         }
2345
2346         return werr;
2347 }