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