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