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