s3-krb5 Only build ADS support if arcfour-hmac-md5 is available
[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
986         /* Set account flags on machine account */
987         ZERO_STRUCT(user_info.info16);
988         user_info.info16.acct_flags = acct_flags;
989
990         status = rpccli_samr_SetUserInfo(pipe_hnd, mem_ctx,
991                                          &user_pol,
992                                          16,
993                                          &user_info);
994
995         if (!NT_STATUS_IS_OK(status)) {
996
997                 rpccli_samr_DeleteUser(pipe_hnd, mem_ctx,
998                                        &user_pol);
999
1000                 libnet_join_set_error_string(mem_ctx, r,
1001                         "Failed to set account flags for machine account (%s)\n",
1002                         nt_errstr(status));
1003                 goto done;
1004         }
1005
1006         /* Set password on machine account - first try level 26 */
1007
1008         init_samr_CryptPasswordEx(r->in.machine_password,
1009                                   &cli->user_session_key,
1010                                   &crypt_pwd_ex);
1011
1012         user_info.info26.password = crypt_pwd_ex;
1013         user_info.info26.password_expired = PASS_DONT_CHANGE_AT_NEXT_LOGON;
1014
1015         status = rpccli_samr_SetUserInfo2(pipe_hnd, mem_ctx,
1016                                           &user_pol,
1017                                           26,
1018                                           &user_info);
1019
1020         if (NT_STATUS_EQUAL(status, NT_STATUS(DCERPC_FAULT_INVALID_TAG))) {
1021
1022                 /* retry with level 24 */
1023
1024                 init_samr_CryptPassword(r->in.machine_password,
1025                                         &cli->user_session_key,
1026                                         &crypt_pwd);
1027
1028                 user_info.info24.password = crypt_pwd;
1029                 user_info.info24.password_expired = PASS_DONT_CHANGE_AT_NEXT_LOGON;
1030
1031                 status = rpccli_samr_SetUserInfo2(pipe_hnd, mem_ctx,
1032                                                   &user_pol,
1033                                                   24,
1034                                                   &user_info);
1035         }
1036
1037         if (!NT_STATUS_IS_OK(status)) {
1038
1039                 rpccli_samr_DeleteUser(pipe_hnd, mem_ctx,
1040                                        &user_pol);
1041
1042                 libnet_join_set_error_string(mem_ctx, r,
1043                         "Failed to set password for machine account (%s)\n",
1044                         nt_errstr(status));
1045                 goto done;
1046         }
1047
1048         status = NT_STATUS_OK;
1049
1050  done:
1051         if (!pipe_hnd) {
1052                 return status;
1053         }
1054
1055         if (is_valid_policy_hnd(&sam_pol)) {
1056                 rpccli_samr_Close(pipe_hnd, mem_ctx, &sam_pol);
1057         }
1058         if (is_valid_policy_hnd(&domain_pol)) {
1059                 rpccli_samr_Close(pipe_hnd, mem_ctx, &domain_pol);
1060         }
1061         if (is_valid_policy_hnd(&user_pol)) {
1062                 rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
1063         }
1064         TALLOC_FREE(pipe_hnd);
1065
1066         return status;
1067 }
1068
1069 /****************************************************************
1070 ****************************************************************/
1071
1072 NTSTATUS libnet_join_ok(const char *netbios_domain_name,
1073                         const char *machine_name,
1074                         const char *dc_name)
1075 {
1076         uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
1077         struct cli_state *cli = NULL;
1078         struct rpc_pipe_client *pipe_hnd = NULL;
1079         struct rpc_pipe_client *netlogon_pipe = NULL;
1080         NTSTATUS status;
1081         char *machine_password = NULL;
1082         char *machine_account = NULL;
1083
1084         if (!dc_name) {
1085                 return NT_STATUS_INVALID_PARAMETER;
1086         }
1087
1088         if (!secrets_init()) {
1089                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1090         }
1091
1092         machine_password = secrets_fetch_machine_password(netbios_domain_name,
1093                                                           NULL, NULL);
1094         if (!machine_password) {
1095                 return NT_STATUS_NO_TRUST_LSA_SECRET;
1096         }
1097
1098         if (asprintf(&machine_account, "%s$", machine_name) == -1) {
1099                 SAFE_FREE(machine_password);
1100                 return NT_STATUS_NO_MEMORY;
1101         }
1102
1103         status = cli_full_connection(&cli, NULL,
1104                                      dc_name,
1105                                      NULL, 0,
1106                                      "IPC$", "IPC",
1107                                      machine_account,
1108                                      NULL,
1109                                      machine_password,
1110                                      0,
1111                                      Undefined, NULL);
1112         free(machine_account);
1113         free(machine_password);
1114
1115         if (!NT_STATUS_IS_OK(status)) {
1116                 status = cli_full_connection(&cli, NULL,
1117                                              dc_name,
1118                                              NULL, 0,
1119                                              "IPC$", "IPC",
1120                                              "",
1121                                              NULL,
1122                                              "",
1123                                              0,
1124                                              Undefined, NULL);
1125         }
1126
1127         if (!NT_STATUS_IS_OK(status)) {
1128                 return status;
1129         }
1130
1131         status = get_schannel_session_key(cli, netbios_domain_name,
1132                                           &neg_flags, &netlogon_pipe);
1133         if (!NT_STATUS_IS_OK(status)) {
1134                 if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_NETWORK_RESPONSE)) {
1135                         cli_shutdown(cli);
1136                         return NT_STATUS_OK;
1137                 }
1138
1139                 DEBUG(0,("libnet_join_ok: failed to get schannel session "
1140                         "key from server %s for domain %s. Error was %s\n",
1141                 cli->desthost, netbios_domain_name, nt_errstr(status)));
1142                 cli_shutdown(cli);
1143                 return status;
1144         }
1145
1146         if (!lp_client_schannel()) {
1147                 cli_shutdown(cli);
1148                 return NT_STATUS_OK;
1149         }
1150
1151         status = cli_rpc_pipe_open_schannel_with_key(
1152                 cli, &ndr_table_netlogon.syntax_id, NCACN_NP,
1153                 DCERPC_AUTH_LEVEL_PRIVACY,
1154                 netbios_domain_name, &netlogon_pipe->dc, &pipe_hnd);
1155
1156         cli_shutdown(cli);
1157
1158         if (!NT_STATUS_IS_OK(status)) {
1159                 DEBUG(0,("libnet_join_ok: failed to open schannel session "
1160                         "on netlogon pipe to server %s for domain %s. "
1161                         "Error was %s\n",
1162                         cli->desthost, netbios_domain_name, nt_errstr(status)));
1163                 return status;
1164         }
1165
1166         return NT_STATUS_OK;
1167 }
1168
1169 /****************************************************************
1170 ****************************************************************/
1171
1172 static WERROR libnet_join_post_verify(TALLOC_CTX *mem_ctx,
1173                                       struct libnet_JoinCtx *r)
1174 {
1175         NTSTATUS status;
1176
1177         status = libnet_join_ok(r->out.netbios_domain_name,
1178                                 r->in.machine_name,
1179                                 r->in.dc_name);
1180         if (!NT_STATUS_IS_OK(status)) {
1181                 libnet_join_set_error_string(mem_ctx, r,
1182                         "failed to verify domain membership after joining: %s",
1183                         get_friendly_nt_error_msg(status));
1184                 return WERR_SETUP_NOT_JOINED;
1185         }
1186
1187         return WERR_OK;
1188 }
1189
1190 /****************************************************************
1191 ****************************************************************/
1192
1193 static bool libnet_join_unjoindomain_remove_secrets(TALLOC_CTX *mem_ctx,
1194                                                     struct libnet_UnjoinCtx *r)
1195 {
1196         if (!secrets_delete_machine_password_ex(lp_workgroup())) {
1197                 return false;
1198         }
1199
1200         if (!secrets_delete_domain_sid(lp_workgroup())) {
1201                 return false;
1202         }
1203
1204         return true;
1205 }
1206
1207 /****************************************************************
1208 ****************************************************************/
1209
1210 static NTSTATUS libnet_join_unjoindomain_rpc(TALLOC_CTX *mem_ctx,
1211                                              struct libnet_UnjoinCtx *r)
1212 {
1213         struct cli_state *cli = NULL;
1214         struct rpc_pipe_client *pipe_hnd = NULL;
1215         struct policy_handle sam_pol, domain_pol, user_pol;
1216         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1217         char *acct_name;
1218         uint32_t user_rid;
1219         struct lsa_String lsa_acct_name;
1220         struct samr_Ids user_rids;
1221         struct samr_Ids name_types;
1222         union samr_UserInfo *info = NULL;
1223
1224         ZERO_STRUCT(sam_pol);
1225         ZERO_STRUCT(domain_pol);
1226         ZERO_STRUCT(user_pol);
1227
1228         status = libnet_join_connect_dc_ipc(r->in.dc_name,
1229                                             r->in.admin_account,
1230                                             r->in.admin_password,
1231                                             r->in.use_kerberos,
1232                                             &cli);
1233         if (!NT_STATUS_IS_OK(status)) {
1234                 goto done;
1235         }
1236
1237         /* Open the domain */
1238
1239         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_samr.syntax_id,
1240                                           &pipe_hnd);
1241         if (!NT_STATUS_IS_OK(status)) {
1242                 DEBUG(0,("Error connecting to SAM pipe. Error was %s\n",
1243                         nt_errstr(status)));
1244                 goto done;
1245         }
1246
1247         status = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
1248                                       pipe_hnd->desthost,
1249                                       SEC_FLAG_MAXIMUM_ALLOWED,
1250                                       &sam_pol);
1251         if (!NT_STATUS_IS_OK(status)) {
1252                 goto done;
1253         }
1254
1255         status = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
1256                                         &sam_pol,
1257                                         SEC_FLAG_MAXIMUM_ALLOWED,
1258                                         r->in.domain_sid,
1259                                         &domain_pol);
1260         if (!NT_STATUS_IS_OK(status)) {
1261                 goto done;
1262         }
1263
1264         /* Create domain user */
1265
1266         acct_name = talloc_asprintf(mem_ctx, "%s$", r->in.machine_name);
1267         strlower_m(acct_name);
1268
1269         init_lsa_String(&lsa_acct_name, acct_name);
1270
1271         status = rpccli_samr_LookupNames(pipe_hnd, mem_ctx,
1272                                          &domain_pol,
1273                                          1,
1274                                          &lsa_acct_name,
1275                                          &user_rids,
1276                                          &name_types);
1277
1278         if (!NT_STATUS_IS_OK(status)) {
1279                 goto done;
1280         }
1281
1282         if (name_types.ids[0] != SID_NAME_USER) {
1283                 DEBUG(0, ("%s is not a user account (type=%d)\n", acct_name,
1284                         name_types.ids[0]));
1285                 status = NT_STATUS_INVALID_WORKSTATION;
1286                 goto done;
1287         }
1288
1289         user_rid = user_rids.ids[0];
1290
1291         /* Open handle on user */
1292
1293         status = rpccli_samr_OpenUser(pipe_hnd, mem_ctx,
1294                                       &domain_pol,
1295                                       SEC_FLAG_MAXIMUM_ALLOWED,
1296                                       user_rid,
1297                                       &user_pol);
1298         if (!NT_STATUS_IS_OK(status)) {
1299                 goto done;
1300         }
1301
1302         /* Get user info */
1303
1304         status = rpccli_samr_QueryUserInfo(pipe_hnd, mem_ctx,
1305                                            &user_pol,
1306                                            16,
1307                                            &info);
1308         if (!NT_STATUS_IS_OK(status)) {
1309                 rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
1310                 goto done;
1311         }
1312
1313         /* now disable and setuser info */
1314
1315         info->info16.acct_flags |= ACB_DISABLED;
1316
1317         status = rpccli_samr_SetUserInfo(pipe_hnd, mem_ctx,
1318                                          &user_pol,
1319                                          16,
1320                                          info);
1321
1322         rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
1323
1324 done:
1325         if (pipe_hnd) {
1326                 if (is_valid_policy_hnd(&domain_pol)) {
1327                         rpccli_samr_Close(pipe_hnd, mem_ctx, &domain_pol);
1328                 }
1329                 if (is_valid_policy_hnd(&sam_pol)) {
1330                         rpccli_samr_Close(pipe_hnd, mem_ctx, &sam_pol);
1331                 }
1332                 TALLOC_FREE(pipe_hnd);
1333         }
1334
1335         if (cli) {
1336                 cli_shutdown(cli);
1337         }
1338
1339         return status;
1340 }
1341
1342 /****************************************************************
1343 ****************************************************************/
1344
1345 static WERROR do_join_modify_vals_config(struct libnet_JoinCtx *r)
1346 {
1347         WERROR werr;
1348         struct smbconf_ctx *ctx;
1349
1350         werr = smbconf_init_reg(r, &ctx, NULL);
1351         if (!W_ERROR_IS_OK(werr)) {
1352                 goto done;
1353         }
1354
1355         if (!(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE)) {
1356
1357                 werr = smbconf_set_global_parameter(ctx, "security", "user");
1358                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1359
1360                 werr = smbconf_set_global_parameter(ctx, "workgroup",
1361                                                     r->in.domain_name);
1362
1363                 smbconf_delete_global_parameter(ctx, "realm");
1364                 goto done;
1365         }
1366
1367         werr = smbconf_set_global_parameter(ctx, "security", "domain");
1368         W_ERROR_NOT_OK_GOTO_DONE(werr);
1369
1370         werr = smbconf_set_global_parameter(ctx, "workgroup",
1371                                             r->out.netbios_domain_name);
1372         W_ERROR_NOT_OK_GOTO_DONE(werr);
1373
1374         if (r->out.domain_is_ad) {
1375                 werr = smbconf_set_global_parameter(ctx, "security", "ads");
1376                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1377
1378                 werr = smbconf_set_global_parameter(ctx, "realm",
1379                                                     r->out.dns_domain_name);
1380                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1381         }
1382
1383  done:
1384         smbconf_shutdown(ctx);
1385         return werr;
1386 }
1387
1388 /****************************************************************
1389 ****************************************************************/
1390
1391 static WERROR do_unjoin_modify_vals_config(struct libnet_UnjoinCtx *r)
1392 {
1393         WERROR werr = WERR_OK;
1394         struct smbconf_ctx *ctx;
1395
1396         werr = smbconf_init_reg(r, &ctx, NULL);
1397         if (!W_ERROR_IS_OK(werr)) {
1398                 goto done;
1399         }
1400
1401         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1402
1403                 werr = smbconf_set_global_parameter(ctx, "security", "user");
1404                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1405
1406                 werr = smbconf_delete_global_parameter(ctx, "workgroup");
1407                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1408
1409                 smbconf_delete_global_parameter(ctx, "realm");
1410         }
1411
1412  done:
1413         smbconf_shutdown(ctx);
1414         return werr;
1415 }
1416
1417 /****************************************************************
1418 ****************************************************************/
1419
1420 static WERROR do_JoinConfig(struct libnet_JoinCtx *r)
1421 {
1422         WERROR werr;
1423
1424         if (!W_ERROR_IS_OK(r->out.result)) {
1425                 return r->out.result;
1426         }
1427
1428         if (!r->in.modify_config) {
1429                 return WERR_OK;
1430         }
1431
1432         werr = do_join_modify_vals_config(r);
1433         if (!W_ERROR_IS_OK(werr)) {
1434                 return werr;
1435         }
1436
1437         lp_load(get_dyn_CONFIGFILE(),true,false,false,true);
1438
1439         r->out.modified_config = true;
1440         r->out.result = werr;
1441
1442         return werr;
1443 }
1444
1445 /****************************************************************
1446 ****************************************************************/
1447
1448 static WERROR libnet_unjoin_config(struct libnet_UnjoinCtx *r)
1449 {
1450         WERROR werr;
1451
1452         if (!W_ERROR_IS_OK(r->out.result)) {
1453                 return r->out.result;
1454         }
1455
1456         if (!r->in.modify_config) {
1457                 return WERR_OK;
1458         }
1459
1460         werr = do_unjoin_modify_vals_config(r);
1461         if (!W_ERROR_IS_OK(werr)) {
1462                 return werr;
1463         }
1464
1465         lp_load(get_dyn_CONFIGFILE(),true,false,false,true);
1466
1467         r->out.modified_config = true;
1468         r->out.result = werr;
1469
1470         return werr;
1471 }
1472
1473 /****************************************************************
1474 ****************************************************************/
1475
1476 static bool libnet_parse_domain_dc(TALLOC_CTX *mem_ctx,
1477                                    const char *domain_str,
1478                                    const char **domain_p,
1479                                    const char **dc_p)
1480 {
1481         char *domain = NULL;
1482         char *dc = NULL;
1483         const char *p = NULL;
1484
1485         if (!domain_str || !domain_p || !dc_p) {
1486                 return false;
1487         }
1488
1489         p = strchr_m(domain_str, '\\');
1490
1491         if (p != NULL) {
1492                 domain = talloc_strndup(mem_ctx, domain_str,
1493                                          PTR_DIFF(p, domain_str));
1494                 dc = talloc_strdup(mem_ctx, p+1);
1495                 if (!dc) {
1496                         return false;
1497                 }
1498         } else {
1499                 domain = talloc_strdup(mem_ctx, domain_str);
1500                 dc = NULL;
1501         }
1502         if (!domain) {
1503                 return false;
1504         }
1505
1506         *domain_p = domain;
1507
1508         if (!*dc_p && dc) {
1509                 *dc_p = dc;
1510         }
1511
1512         return true;
1513 }
1514
1515 /****************************************************************
1516 ****************************************************************/
1517
1518 static WERROR libnet_join_pre_processing(TALLOC_CTX *mem_ctx,
1519                                          struct libnet_JoinCtx *r)
1520 {
1521         if (!r->in.domain_name) {
1522                 libnet_join_set_error_string(mem_ctx, r,
1523                         "No domain name defined");
1524                 return WERR_INVALID_PARAM;
1525         }
1526
1527         if (!libnet_parse_domain_dc(mem_ctx, r->in.domain_name,
1528                                     &r->in.domain_name,
1529                                     &r->in.dc_name)) {
1530                 libnet_join_set_error_string(mem_ctx, r,
1531                         "Failed to parse domain name");
1532                 return WERR_INVALID_PARAM;
1533         }
1534
1535         if (IS_DC) {
1536                 return WERR_SETUP_DOMAIN_CONTROLLER;
1537         }
1538
1539         if (!secrets_init()) {
1540                 libnet_join_set_error_string(mem_ctx, r,
1541                         "Unable to open secrets database");
1542                 return WERR_CAN_NOT_COMPLETE;
1543         }
1544
1545         return WERR_OK;
1546 }
1547
1548 /****************************************************************
1549 ****************************************************************/
1550
1551 static void libnet_join_add_dom_rids_to_builtins(struct dom_sid *domain_sid)
1552 {
1553         NTSTATUS status;
1554
1555         /* Try adding dom admins to builtin\admins. Only log failures. */
1556         status = create_builtin_administrators(domain_sid);
1557         if (NT_STATUS_EQUAL(status, NT_STATUS_PROTOCOL_UNREACHABLE)) {
1558                 DEBUG(10,("Unable to auto-add domain administrators to "
1559                           "BUILTIN\\Administrators during join because "
1560                           "winbindd must be running."));
1561         } else if (!NT_STATUS_IS_OK(status)) {
1562                 DEBUG(5, ("Failed to auto-add domain administrators to "
1563                           "BUILTIN\\Administrators during join: %s\n",
1564                           nt_errstr(status)));
1565         }
1566
1567         /* Try adding dom users to builtin\users. Only log failures. */
1568         status = create_builtin_users(domain_sid);
1569         if (NT_STATUS_EQUAL(status, NT_STATUS_PROTOCOL_UNREACHABLE)) {
1570                 DEBUG(10,("Unable to auto-add domain users to BUILTIN\\users "
1571                           "during join because winbindd must be running."));
1572         } else if (!NT_STATUS_IS_OK(status)) {
1573                 DEBUG(5, ("Failed to auto-add domain administrators to "
1574                           "BUILTIN\\Administrators during join: %s\n",
1575                           nt_errstr(status)));
1576         }
1577 }
1578
1579 /****************************************************************
1580 ****************************************************************/
1581
1582 static WERROR libnet_join_post_processing(TALLOC_CTX *mem_ctx,
1583                                           struct libnet_JoinCtx *r)
1584 {
1585         WERROR werr;
1586
1587         if (!W_ERROR_IS_OK(r->out.result)) {
1588                 return r->out.result;
1589         }
1590
1591         werr = do_JoinConfig(r);
1592         if (!W_ERROR_IS_OK(werr)) {
1593                 return werr;
1594         }
1595
1596         if (!(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE)) {
1597                 return WERR_OK;
1598         }
1599
1600         saf_join_store(r->out.netbios_domain_name, r->in.dc_name);
1601         if (r->out.dns_domain_name) {
1602                 saf_join_store(r->out.dns_domain_name, r->in.dc_name);
1603         }
1604
1605 #ifdef WITH_ADS
1606         if (r->out.domain_is_ad &&
1607             !(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE)) {
1608                 ADS_STATUS ads_status;
1609
1610                 ads_status  = libnet_join_post_processing_ads(mem_ctx, r);
1611                 if (!ADS_ERR_OK(ads_status)) {
1612                         return WERR_GENERAL_FAILURE;
1613                 }
1614         }
1615 #endif /* WITH_ADS */
1616
1617         libnet_join_add_dom_rids_to_builtins(r->out.domain_sid);
1618
1619         return WERR_OK;
1620 }
1621
1622 /****************************************************************
1623 ****************************************************************/
1624
1625 static int libnet_destroy_JoinCtx(struct libnet_JoinCtx *r)
1626 {
1627         const char *krb5_cc_env = NULL;
1628
1629         if (r->in.ads) {
1630                 ads_destroy(&r->in.ads);
1631         }
1632
1633         krb5_cc_env = getenv(KRB5_ENV_CCNAME);
1634         if (krb5_cc_env && StrCaseCmp(krb5_cc_env, "MEMORY:libnetjoin")) {
1635                 unsetenv(KRB5_ENV_CCNAME);
1636         }
1637
1638         return 0;
1639 }
1640
1641 /****************************************************************
1642 ****************************************************************/
1643
1644 static int libnet_destroy_UnjoinCtx(struct libnet_UnjoinCtx *r)
1645 {
1646         const char *krb5_cc_env = NULL;
1647
1648         if (r->in.ads) {
1649                 ads_destroy(&r->in.ads);
1650         }
1651
1652         krb5_cc_env = getenv(KRB5_ENV_CCNAME);
1653         if (krb5_cc_env && StrCaseCmp(krb5_cc_env, "MEMORY:libnetjoin")) {
1654                 unsetenv(KRB5_ENV_CCNAME);
1655         }
1656
1657         return 0;
1658 }
1659
1660 /****************************************************************
1661 ****************************************************************/
1662
1663 WERROR libnet_init_JoinCtx(TALLOC_CTX *mem_ctx,
1664                            struct libnet_JoinCtx **r)
1665 {
1666         struct libnet_JoinCtx *ctx;
1667         const char *krb5_cc_env = NULL;
1668
1669         ctx = talloc_zero(mem_ctx, struct libnet_JoinCtx);
1670         if (!ctx) {
1671                 return WERR_NOMEM;
1672         }
1673
1674         talloc_set_destructor(ctx, libnet_destroy_JoinCtx);
1675
1676         ctx->in.machine_name = talloc_strdup(mem_ctx, global_myname());
1677         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
1678
1679         krb5_cc_env = getenv(KRB5_ENV_CCNAME);
1680         if (!krb5_cc_env || (strlen(krb5_cc_env) == 0)) {
1681                 krb5_cc_env = talloc_strdup(mem_ctx, "MEMORY:libnetjoin");
1682                 W_ERROR_HAVE_NO_MEMORY(krb5_cc_env);
1683                 setenv(KRB5_ENV_CCNAME, krb5_cc_env, 1);
1684         }
1685
1686         ctx->in.secure_channel_type = SEC_CHAN_WKSTA;
1687
1688         *r = ctx;
1689
1690         return WERR_OK;
1691 }
1692
1693 /****************************************************************
1694 ****************************************************************/
1695
1696 WERROR libnet_init_UnjoinCtx(TALLOC_CTX *mem_ctx,
1697                              struct libnet_UnjoinCtx **r)
1698 {
1699         struct libnet_UnjoinCtx *ctx;
1700         const char *krb5_cc_env = NULL;
1701
1702         ctx = talloc_zero(mem_ctx, struct libnet_UnjoinCtx);
1703         if (!ctx) {
1704                 return WERR_NOMEM;
1705         }
1706
1707         talloc_set_destructor(ctx, libnet_destroy_UnjoinCtx);
1708
1709         ctx->in.machine_name = talloc_strdup(mem_ctx, global_myname());
1710         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
1711
1712         krb5_cc_env = getenv(KRB5_ENV_CCNAME);
1713         if (!krb5_cc_env || (strlen(krb5_cc_env) == 0)) {
1714                 krb5_cc_env = talloc_strdup(mem_ctx, "MEMORY:libnetjoin");
1715                 W_ERROR_HAVE_NO_MEMORY(krb5_cc_env);
1716                 setenv(KRB5_ENV_CCNAME, krb5_cc_env, 1);
1717         }
1718
1719         *r = ctx;
1720
1721         return WERR_OK;
1722 }
1723
1724 /****************************************************************
1725 ****************************************************************/
1726
1727 static WERROR libnet_join_check_config(TALLOC_CTX *mem_ctx,
1728                                        struct libnet_JoinCtx *r)
1729 {
1730         bool valid_security = false;
1731         bool valid_workgroup = false;
1732         bool valid_realm = false;
1733
1734         /* check if configuration is already set correctly */
1735
1736         valid_workgroup = strequal(lp_workgroup(), r->out.netbios_domain_name);
1737
1738         switch (r->out.domain_is_ad) {
1739                 case false:
1740                         valid_security = (lp_security() == SEC_DOMAIN);
1741                         if (valid_workgroup && valid_security) {
1742                                 /* nothing to be done */
1743                                 return WERR_OK;
1744                         }
1745                         break;
1746                 case true:
1747                         valid_realm = strequal(lp_realm(), r->out.dns_domain_name);
1748                         switch (lp_security()) {
1749                         case SEC_DOMAIN:
1750                         case SEC_ADS:
1751                                 valid_security = true;
1752                         }
1753
1754                         if (valid_workgroup && valid_realm && valid_security) {
1755                                 /* nothing to be done */
1756                                 return WERR_OK;
1757                         }
1758                         break;
1759         }
1760
1761         /* check if we are supposed to manipulate configuration */
1762
1763         if (!r->in.modify_config) {
1764
1765                 char *wrong_conf = talloc_strdup(mem_ctx, "");
1766
1767                 if (!valid_workgroup) {
1768                         wrong_conf = talloc_asprintf_append(wrong_conf,
1769                                 "\"workgroup\" set to '%s', should be '%s'",
1770                                 lp_workgroup(), r->out.netbios_domain_name);
1771                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
1772                 }
1773
1774                 if (!valid_realm) {
1775                         wrong_conf = talloc_asprintf_append(wrong_conf,
1776                                 "\"realm\" set to '%s', should be '%s'",
1777                                 lp_realm(), r->out.dns_domain_name);
1778                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
1779                 }
1780
1781                 if (!valid_security) {
1782                         const char *sec = NULL;
1783                         switch (lp_security()) {
1784                         case SEC_SHARE: sec = "share"; break;
1785                         case SEC_USER:  sec = "user"; break;
1786                         case SEC_DOMAIN: sec = "domain"; break;
1787                         case SEC_ADS: sec = "ads"; break;
1788                         }
1789                         wrong_conf = talloc_asprintf_append(wrong_conf,
1790                                 "\"security\" set to '%s', should be %s",
1791                                 sec, r->out.domain_is_ad ?
1792                                 "either 'domain' or 'ads'" : "'domain'");
1793                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
1794                 }
1795
1796                 libnet_join_set_error_string(mem_ctx, r,
1797                         "Invalid configuration (%s) and configuration modification "
1798                         "was not requested", wrong_conf);
1799                 return WERR_CAN_NOT_COMPLETE;
1800         }
1801
1802         /* check if we are able to manipulate configuration */
1803
1804         if (!lp_config_backend_is_registry()) {
1805                 libnet_join_set_error_string(mem_ctx, r,
1806                         "Configuration manipulation requested but not "
1807                         "supported by backend");
1808                 return WERR_NOT_SUPPORTED;
1809         }
1810
1811         return WERR_OK;
1812 }
1813
1814 /****************************************************************
1815 ****************************************************************/
1816
1817 static WERROR libnet_DomainJoin(TALLOC_CTX *mem_ctx,
1818                                 struct libnet_JoinCtx *r)
1819 {
1820         NTSTATUS status;
1821         WERROR werr;
1822         struct cli_state *cli = NULL;
1823 #ifdef WITH_ADS
1824         ADS_STATUS ads_status;
1825 #endif /* WITH_ADS */
1826
1827         if (!r->in.dc_name) {
1828                 struct netr_DsRGetDCNameInfo *info;
1829                 const char *dc;
1830                 status = dsgetdcname(mem_ctx,
1831                                      r->in.msg_ctx,
1832                                      r->in.domain_name,
1833                                      NULL,
1834                                      NULL,
1835                                      DS_FORCE_REDISCOVERY |
1836                                      DS_DIRECTORY_SERVICE_REQUIRED |
1837                                      DS_WRITABLE_REQUIRED |
1838                                      DS_RETURN_DNS_NAME,
1839                                      &info);
1840                 if (!NT_STATUS_IS_OK(status)) {
1841                         libnet_join_set_error_string(mem_ctx, r,
1842                                 "failed to find DC for domain %s",
1843                                 r->in.domain_name,
1844                                 get_friendly_nt_error_msg(status));
1845                         return WERR_DCNOTFOUND;
1846                 }
1847
1848                 dc = strip_hostname(info->dc_unc);
1849                 r->in.dc_name = talloc_strdup(mem_ctx, dc);
1850                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
1851         }
1852
1853         status = libnet_join_lookup_dc_rpc(mem_ctx, r, &cli);
1854         if (!NT_STATUS_IS_OK(status)) {
1855                 libnet_join_set_error_string(mem_ctx, r,
1856                         "failed to lookup DC info for domain '%s' over rpc: %s",
1857                         r->in.domain_name, get_friendly_nt_error_msg(status));
1858                 return ntstatus_to_werror(status);
1859         }
1860
1861         werr = libnet_join_check_config(mem_ctx, r);
1862         if (!W_ERROR_IS_OK(werr)) {
1863                 goto done;
1864         }
1865
1866 #ifdef WITH_ADS
1867         if (r->out.domain_is_ad && r->in.account_ou &&
1868             !(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE)) {
1869
1870                 ads_status = libnet_join_connect_ads(mem_ctx, r);
1871                 if (!ADS_ERR_OK(ads_status)) {
1872                         return WERR_DEFAULT_JOIN_REQUIRED;
1873                 }
1874
1875                 ads_status = libnet_join_precreate_machine_acct(mem_ctx, r);
1876                 if (!ADS_ERR_OK(ads_status)) {
1877                         libnet_join_set_error_string(mem_ctx, r,
1878                                 "failed to precreate account in ou %s: %s",
1879                                 r->in.account_ou,
1880                                 ads_errstr(ads_status));
1881                         return WERR_DEFAULT_JOIN_REQUIRED;
1882                 }
1883
1884                 r->in.join_flags &= ~WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE;
1885         }
1886 #endif /* WITH_ADS */
1887
1888         if ((r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE) &&
1889             (r->in.join_flags & WKSSVC_JOIN_FLAGS_MACHINE_PWD_PASSED)) {
1890                 status = libnet_join_joindomain_rpc_unsecure(mem_ctx, r, cli);
1891         } else {
1892                 status = libnet_join_joindomain_rpc(mem_ctx, r, cli);
1893         }
1894         if (!NT_STATUS_IS_OK(status)) {
1895                 libnet_join_set_error_string(mem_ctx, r,
1896                         "failed to join domain '%s' over rpc: %s",
1897                         r->in.domain_name, get_friendly_nt_error_msg(status));
1898                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
1899                         return WERR_SETUP_ALREADY_JOINED;
1900                 }
1901                 werr = ntstatus_to_werror(status);
1902                 goto done;
1903         }
1904
1905         if (!libnet_join_joindomain_store_secrets(mem_ctx, r)) {
1906                 werr = WERR_SETUP_NOT_JOINED;
1907                 goto done;
1908         }
1909
1910         werr = WERR_OK;
1911
1912  done:
1913         if (cli) {
1914                 cli_shutdown(cli);
1915         }
1916
1917         return werr;
1918 }
1919
1920 /****************************************************************
1921 ****************************************************************/
1922
1923 static WERROR libnet_join_rollback(TALLOC_CTX *mem_ctx,
1924                                    struct libnet_JoinCtx *r)
1925 {
1926         WERROR werr;
1927         struct libnet_UnjoinCtx *u = NULL;
1928
1929         werr = libnet_init_UnjoinCtx(mem_ctx, &u);
1930         if (!W_ERROR_IS_OK(werr)) {
1931                 return werr;
1932         }
1933
1934         u->in.debug             = r->in.debug;
1935         u->in.dc_name           = r->in.dc_name;
1936         u->in.domain_name       = r->in.domain_name;
1937         u->in.admin_account     = r->in.admin_account;
1938         u->in.admin_password    = r->in.admin_password;
1939         u->in.modify_config     = r->in.modify_config;
1940         u->in.unjoin_flags      = WKSSVC_JOIN_FLAGS_JOIN_TYPE |
1941                                   WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE;
1942
1943         werr = libnet_Unjoin(mem_ctx, u);
1944         TALLOC_FREE(u);
1945
1946         return werr;
1947 }
1948
1949 /****************************************************************
1950 ****************************************************************/
1951
1952 WERROR libnet_Join(TALLOC_CTX *mem_ctx,
1953                    struct libnet_JoinCtx *r)
1954 {
1955         WERROR werr;
1956
1957         if (r->in.debug) {
1958                 LIBNET_JOIN_IN_DUMP_CTX(mem_ctx, r);
1959         }
1960
1961         werr = libnet_join_pre_processing(mem_ctx, r);
1962         if (!W_ERROR_IS_OK(werr)) {
1963                 goto done;
1964         }
1965
1966         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1967                 werr = libnet_DomainJoin(mem_ctx, r);
1968                 if (!W_ERROR_IS_OK(werr)) {
1969                         goto done;
1970                 }
1971         }
1972
1973         werr = libnet_join_post_processing(mem_ctx, r);
1974         if (!W_ERROR_IS_OK(werr)) {
1975                 goto done;
1976         }
1977
1978         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1979                 werr = libnet_join_post_verify(mem_ctx, r);
1980                 if (!W_ERROR_IS_OK(werr)) {
1981                         libnet_join_rollback(mem_ctx, r);
1982                 }
1983         }
1984
1985  done:
1986         r->out.result = werr;
1987
1988         if (r->in.debug) {
1989                 LIBNET_JOIN_OUT_DUMP_CTX(mem_ctx, r);
1990         }
1991         return werr;
1992 }
1993
1994 /****************************************************************
1995 ****************************************************************/
1996
1997 static WERROR libnet_DomainUnjoin(TALLOC_CTX *mem_ctx,
1998                                   struct libnet_UnjoinCtx *r)
1999 {
2000         NTSTATUS status;
2001
2002         if (!r->in.domain_sid) {
2003                 struct dom_sid sid;
2004                 if (!secrets_fetch_domain_sid(lp_workgroup(), &sid)) {
2005                         libnet_unjoin_set_error_string(mem_ctx, r,
2006                                 "Unable to fetch domain sid: are we joined?");
2007                         return WERR_SETUP_NOT_JOINED;
2008                 }
2009                 r->in.domain_sid = sid_dup_talloc(mem_ctx, &sid);
2010                 W_ERROR_HAVE_NO_MEMORY(r->in.domain_sid);
2011         }
2012
2013         if (!(r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE) && 
2014             !r->in.delete_machine_account) {
2015                 libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2016                 return WERR_OK;
2017         }
2018
2019         if (!r->in.dc_name) {
2020                 struct netr_DsRGetDCNameInfo *info;
2021                 const char *dc;
2022                 status = dsgetdcname(mem_ctx,
2023                                      r->in.msg_ctx,
2024                                      r->in.domain_name,
2025                                      NULL,
2026                                      NULL,
2027                                      DS_DIRECTORY_SERVICE_REQUIRED |
2028                                      DS_WRITABLE_REQUIRED |
2029                                      DS_RETURN_DNS_NAME,
2030                                      &info);
2031                 if (!NT_STATUS_IS_OK(status)) {
2032                         libnet_unjoin_set_error_string(mem_ctx, r,
2033                                 "failed to find DC for domain %s",
2034                                 r->in.domain_name,
2035                                 get_friendly_nt_error_msg(status));
2036                         return WERR_DCNOTFOUND;
2037                 }
2038
2039                 dc = strip_hostname(info->dc_unc);
2040                 r->in.dc_name = talloc_strdup(mem_ctx, dc);
2041                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
2042         }
2043
2044 #ifdef WITH_ADS
2045         /* for net ads leave, try to delete the account.  If it works, 
2046            no sense in disabling.  If it fails, we can still try to 
2047            disable it. jmcd */
2048            
2049         if (r->in.delete_machine_account) {
2050                 ADS_STATUS ads_status;
2051                 ads_status = libnet_unjoin_connect_ads(mem_ctx, r);
2052                 if (ADS_ERR_OK(ads_status)) {
2053                         /* dirty hack */
2054                         r->out.dns_domain_name = 
2055                                 talloc_strdup(mem_ctx,
2056                                               r->in.ads->server.realm);
2057                         ads_status = 
2058                                 libnet_unjoin_remove_machine_acct(mem_ctx, r);
2059                 }
2060                 if (!ADS_ERR_OK(ads_status)) {
2061                         libnet_unjoin_set_error_string(mem_ctx, r,
2062                                 "failed to remove machine account from AD: %s",
2063                                 ads_errstr(ads_status));
2064                 } else {
2065                         r->out.deleted_machine_account = true;
2066                         W_ERROR_HAVE_NO_MEMORY(r->out.dns_domain_name);
2067                         libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2068                         return WERR_OK;
2069                 }
2070         }
2071 #endif /* WITH_ADS */
2072
2073         /* The WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE flag really means 
2074            "disable".  */
2075         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE) {
2076                 status = libnet_join_unjoindomain_rpc(mem_ctx, r);
2077                 if (!NT_STATUS_IS_OK(status)) {
2078                         libnet_unjoin_set_error_string(mem_ctx, r,
2079                                 "failed to disable machine account via rpc: %s",
2080                                 get_friendly_nt_error_msg(status));
2081                         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER)) {
2082                                 return WERR_SETUP_NOT_JOINED;
2083                         }
2084                         return ntstatus_to_werror(status);
2085                 }
2086                 
2087                 r->out.disabled_machine_account = true;
2088         }
2089
2090         /* If disable succeeded or was not requested at all, we 
2091            should be getting rid of our end of things */
2092
2093         libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2094
2095         return WERR_OK;
2096 }
2097
2098 /****************************************************************
2099 ****************************************************************/
2100
2101 static WERROR libnet_unjoin_pre_processing(TALLOC_CTX *mem_ctx,
2102                                            struct libnet_UnjoinCtx *r)
2103 {
2104         if (!r->in.domain_name) {
2105                 libnet_unjoin_set_error_string(mem_ctx, r,
2106                         "No domain name defined");
2107                 return WERR_INVALID_PARAM;
2108         }
2109
2110         if (!libnet_parse_domain_dc(mem_ctx, r->in.domain_name,
2111                                     &r->in.domain_name,
2112                                     &r->in.dc_name)) {
2113                 libnet_unjoin_set_error_string(mem_ctx, r,
2114                         "Failed to parse domain name");
2115                 return WERR_INVALID_PARAM;
2116         }
2117
2118         if (IS_DC) {
2119                 return WERR_SETUP_DOMAIN_CONTROLLER;
2120         }
2121
2122         if (!secrets_init()) {
2123                 libnet_unjoin_set_error_string(mem_ctx, r,
2124                         "Unable to open secrets database");
2125                 return WERR_CAN_NOT_COMPLETE;
2126         }
2127
2128         return WERR_OK;
2129 }
2130
2131 /****************************************************************
2132 ****************************************************************/
2133
2134 static WERROR libnet_unjoin_post_processing(TALLOC_CTX *mem_ctx,
2135                                             struct libnet_UnjoinCtx *r)
2136 {
2137         saf_delete(r->out.netbios_domain_name);
2138         saf_delete(r->out.dns_domain_name);
2139
2140         return libnet_unjoin_config(r);
2141 }
2142
2143 /****************************************************************
2144 ****************************************************************/
2145
2146 WERROR libnet_Unjoin(TALLOC_CTX *mem_ctx,
2147                      struct libnet_UnjoinCtx *r)
2148 {
2149         WERROR werr;
2150
2151         if (r->in.debug) {
2152                 LIBNET_UNJOIN_IN_DUMP_CTX(mem_ctx, r);
2153         }
2154
2155         werr = libnet_unjoin_pre_processing(mem_ctx, r);
2156         if (!W_ERROR_IS_OK(werr)) {
2157                 goto done;
2158         }
2159
2160         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
2161                 werr = libnet_DomainUnjoin(mem_ctx, r);
2162                 if (!W_ERROR_IS_OK(werr)) {
2163                         libnet_unjoin_config(r);
2164                         goto done;
2165                 }
2166         }
2167
2168         werr = libnet_unjoin_post_processing(mem_ctx, r);
2169         if (!W_ERROR_IS_OK(werr)) {
2170                 goto done;
2171         }
2172
2173  done:
2174         r->out.result = werr;
2175
2176         if (r->in.debug) {
2177                 LIBNET_UNJOIN_OUT_DUMP_CTX(mem_ctx, r);
2178         }
2179
2180         return werr;
2181 }