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