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