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