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