s3:libads: setup the msDS-SupportedEncryptionTypes attribute on ldap_add
[nivanova/samba-autobuild/.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 bool libnet_join_create_keytab(TALLOC_CTX *mem_ctx,
620                                       struct libnet_JoinCtx *r)
621 {
622         if (!USE_SYSTEM_KEYTAB) {
623                 return true;
624         }
625
626         if (ads_keytab_create_default(r->in.ads) != 0) {
627                 return false;
628         }
629
630         return true;
631 }
632
633 /****************************************************************
634 ****************************************************************/
635
636 static bool libnet_join_derive_salting_principal(TALLOC_CTX *mem_ctx,
637                                                  struct libnet_JoinCtx *r)
638 {
639         uint32_t domain_func;
640         ADS_STATUS status;
641         const char *salt = NULL;
642         char *std_salt = NULL;
643
644         status = ads_domain_func_level(r->in.ads, &domain_func);
645         if (!ADS_ERR_OK(status)) {
646                 libnet_join_set_error_string(mem_ctx, r,
647                         "failed to determine domain functional level: %s",
648                         ads_errstr(status));
649                 return false;
650         }
651
652         /* go ahead and setup the default salt */
653
654         std_salt = kerberos_standard_des_salt();
655         if (!std_salt) {
656                 libnet_join_set_error_string(mem_ctx, r,
657                         "failed to obtain standard DES salt");
658                 return false;
659         }
660
661         salt = talloc_strdup(mem_ctx, std_salt);
662         if (!salt) {
663                 return false;
664         }
665
666         SAFE_FREE(std_salt);
667
668         /* if it's a Windows functional domain, we have to look for the UPN */
669
670         if (domain_func == DS_DOMAIN_FUNCTION_2000) {
671                 char *upn;
672
673                 upn = ads_get_upn(r->in.ads, mem_ctx,
674                                   r->in.machine_name);
675                 if (upn) {
676                         salt = talloc_strdup(mem_ctx, upn);
677                         if (!salt) {
678                                 return false;
679                         }
680                 }
681         }
682
683         return kerberos_secrets_store_des_salt(salt);
684 }
685
686 /****************************************************************
687 ****************************************************************/
688
689 static ADS_STATUS libnet_join_post_processing_ads(TALLOC_CTX *mem_ctx,
690                                                   struct libnet_JoinCtx *r)
691 {
692         ADS_STATUS status;
693
694         if (!r->in.ads) {
695                 status = libnet_join_connect_ads(mem_ctx, r);
696                 if (!ADS_ERR_OK(status)) {
697                         return status;
698                 }
699         }
700
701         status = libnet_join_set_machine_spn(mem_ctx, r);
702         if (!ADS_ERR_OK(status)) {
703                 libnet_join_set_error_string(mem_ctx, r,
704                         "Failed to set machine spn: %s\n"
705                         "Do you have sufficient permissions to create machine "
706                         "accounts?",
707                         ads_errstr(status));
708                 return status;
709         }
710
711         status = libnet_join_set_os_attributes(mem_ctx, r);
712         if (!ADS_ERR_OK(status)) {
713                 libnet_join_set_error_string(mem_ctx, r,
714                         "failed to set machine os attributes: %s",
715                         ads_errstr(status));
716                 return status;
717         }
718
719         status = libnet_join_set_machine_upn(mem_ctx, r);
720         if (!ADS_ERR_OK(status)) {
721                 libnet_join_set_error_string(mem_ctx, r,
722                         "failed to set machine upn: %s",
723                         ads_errstr(status));
724                 return status;
725         }
726
727         if (!libnet_join_derive_salting_principal(mem_ctx, r)) {
728                 return ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
729         }
730
731         if (!libnet_join_create_keytab(mem_ctx, r)) {
732                 libnet_join_set_error_string(mem_ctx, r,
733                         "failed to create kerberos keytab");
734                 return ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
735         }
736
737         return ADS_SUCCESS;
738 }
739 #endif /* HAVE_ADS */
740
741 /****************************************************************
742  Store the machine password and domain SID
743 ****************************************************************/
744
745 static bool libnet_join_joindomain_store_secrets(TALLOC_CTX *mem_ctx,
746                                                  struct libnet_JoinCtx *r)
747 {
748         if (!secrets_store_domain_sid(r->out.netbios_domain_name,
749                                       r->out.domain_sid))
750         {
751                 DEBUG(1,("Failed to save domain sid\n"));
752                 return false;
753         }
754
755         if (!secrets_store_machine_password(r->in.machine_password,
756                                             r->out.netbios_domain_name,
757                                             r->in.secure_channel_type))
758         {
759                 DEBUG(1,("Failed to save machine password\n"));
760                 return false;
761         }
762
763         return true;
764 }
765
766 /****************************************************************
767  Connect dc's IPC$ share
768 ****************************************************************/
769
770 static NTSTATUS libnet_join_connect_dc_ipc(const char *dc,
771                                            const char *user,
772                                            const char *domain,
773                                            const char *pass,
774                                            bool use_kerberos,
775                                            struct cli_state **cli)
776 {
777         int flags = 0;
778
779         if (use_kerberos) {
780                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
781         }
782
783         if (use_kerberos && pass) {
784                 flags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;
785         }
786
787         return cli_full_connection(cli, NULL,
788                                    dc,
789                                    NULL, 0,
790                                    "IPC$", "IPC",
791                                    user,
792                                    domain,
793                                    pass,
794                                    flags,
795                                    SMB_SIGNING_DEFAULT);
796 }
797
798 /****************************************************************
799  Lookup domain dc's info
800 ****************************************************************/
801
802 static NTSTATUS libnet_join_lookup_dc_rpc(TALLOC_CTX *mem_ctx,
803                                           struct libnet_JoinCtx *r,
804                                           struct cli_state **cli)
805 {
806         struct rpc_pipe_client *pipe_hnd = NULL;
807         struct policy_handle lsa_pol;
808         NTSTATUS status, result;
809         union lsa_PolicyInformation *info = NULL;
810         struct dcerpc_binding_handle *b;
811
812         status = libnet_join_connect_dc_ipc(r->in.dc_name,
813                                             r->in.admin_account,
814                                             r->in.admin_domain,
815                                             r->in.admin_password,
816                                             r->in.use_kerberos,
817                                             cli);
818         if (!NT_STATUS_IS_OK(status)) {
819                 goto done;
820         }
821
822         status = cli_rpc_pipe_open_noauth(*cli, &ndr_table_lsarpc,
823                                           &pipe_hnd);
824         if (!NT_STATUS_IS_OK(status)) {
825                 DEBUG(0,("Error connecting to LSA pipe. Error was %s\n",
826                         nt_errstr(status)));
827                 goto done;
828         }
829
830         b = pipe_hnd->binding_handle;
831
832         status = rpccli_lsa_open_policy(pipe_hnd, mem_ctx, true,
833                                         SEC_FLAG_MAXIMUM_ALLOWED, &lsa_pol);
834         if (!NT_STATUS_IS_OK(status)) {
835                 goto done;
836         }
837
838         status = dcerpc_lsa_QueryInfoPolicy2(b, mem_ctx,
839                                              &lsa_pol,
840                                              LSA_POLICY_INFO_DNS,
841                                              &info,
842                                              &result);
843         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
844                 r->out.domain_is_ad = true;
845                 r->out.netbios_domain_name = info->dns.name.string;
846                 r->out.dns_domain_name = info->dns.dns_domain.string;
847                 r->out.forest_name = info->dns.dns_forest.string;
848                 r->out.domain_sid = dom_sid_dup(mem_ctx, info->dns.sid);
849                 NT_STATUS_HAVE_NO_MEMORY(r->out.domain_sid);
850         }
851
852         if (!NT_STATUS_IS_OK(status)) {
853                 status = dcerpc_lsa_QueryInfoPolicy(b, mem_ctx,
854                                                     &lsa_pol,
855                                                     LSA_POLICY_INFO_ACCOUNT_DOMAIN,
856                                                     &info,
857                                                     &result);
858                 if (!NT_STATUS_IS_OK(status)) {
859                         goto done;
860                 }
861                 if (!NT_STATUS_IS_OK(result)) {
862                         status = result;
863                         goto done;
864                 }
865
866                 r->out.netbios_domain_name = info->account_domain.name.string;
867                 r->out.domain_sid = dom_sid_dup(mem_ctx, info->account_domain.sid);
868                 NT_STATUS_HAVE_NO_MEMORY(r->out.domain_sid);
869         }
870
871         dcerpc_lsa_Close(b, mem_ctx, &lsa_pol, &result);
872         TALLOC_FREE(pipe_hnd);
873
874  done:
875         return status;
876 }
877
878 /****************************************************************
879  Do the domain join unsecure
880 ****************************************************************/
881
882 static NTSTATUS libnet_join_joindomain_rpc_unsecure(TALLOC_CTX *mem_ctx,
883                                                     struct libnet_JoinCtx *r,
884                                                     struct cli_state *cli)
885 {
886         TALLOC_CTX *frame = talloc_stackframe();
887         struct rpc_pipe_client *netlogon_pipe = NULL;
888         struct netlogon_creds_cli_context *netlogon_creds = NULL;
889         struct samr_Password current_nt_hash;
890         const char *account_name = NULL;
891         NTSTATUS status;
892
893         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_netlogon,
894                                           &netlogon_pipe);
895         if (!NT_STATUS_IS_OK(status)) {
896                 TALLOC_FREE(frame);
897                 return status;
898         }
899
900         if (!r->in.machine_password) {
901                 r->in.machine_password = generate_random_password(mem_ctx,
902                                 DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH,
903                                 DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH);
904                 if (r->in.machine_password == NULL) {
905                         TALLOC_FREE(frame);
906                         return NT_STATUS_NO_MEMORY;
907                 }
908         }
909
910         /* according to WKSSVC_JOIN_FLAGS_MACHINE_PWD_PASSED */
911         E_md4hash(r->in.admin_password, current_nt_hash.hash);
912
913         account_name = talloc_asprintf(frame, "%s$",
914                                        r->in.machine_name);
915         if (account_name == NULL) {
916                 TALLOC_FREE(frame);
917                 return NT_STATUS_NO_MEMORY;
918         }
919
920         status = rpccli_create_netlogon_creds(netlogon_pipe->desthost,
921                                               r->in.domain_name,
922                                               account_name,
923                                               r->in.secure_channel_type,
924                                               r->in.msg_ctx,
925                                               frame,
926                                               &netlogon_creds);
927         if (!NT_STATUS_IS_OK(status)) {
928                 TALLOC_FREE(frame);
929                 return status;
930         }
931
932         status = rpccli_setup_netlogon_creds(cli, NCACN_NP,
933                                              netlogon_creds,
934                                              true, /* force_reauth */
935                                              current_nt_hash,
936                                              NULL); /* previous_nt_hash */
937         if (!NT_STATUS_IS_OK(status)) {
938                 TALLOC_FREE(frame);
939                 return status;
940         }
941
942         status = netlogon_creds_cli_ServerPasswordSet(netlogon_creds,
943                                                       netlogon_pipe->binding_handle,
944                                                       r->in.machine_password,
945                                                       NULL); /* new_version */
946         if (!NT_STATUS_IS_OK(status)) {
947                 TALLOC_FREE(frame);
948                 return status;
949         }
950
951         TALLOC_FREE(frame);
952         return NT_STATUS_OK;
953 }
954
955 /****************************************************************
956  Do the domain join
957 ****************************************************************/
958
959 static NTSTATUS libnet_join_joindomain_rpc(TALLOC_CTX *mem_ctx,
960                                            struct libnet_JoinCtx *r,
961                                            struct cli_state *cli)
962 {
963         struct rpc_pipe_client *pipe_hnd = NULL;
964         struct policy_handle sam_pol, domain_pol, user_pol;
965         NTSTATUS status = NT_STATUS_UNSUCCESSFUL, result;
966         char *acct_name;
967         struct lsa_String lsa_acct_name;
968         uint32_t user_rid;
969         uint32_t acct_flags = ACB_WSTRUST;
970         struct samr_Ids user_rids;
971         struct samr_Ids name_types;
972         union samr_UserInfo user_info;
973         struct dcerpc_binding_handle *b = NULL;
974         unsigned int old_timeout = 0;
975
976         DATA_BLOB session_key = data_blob_null;
977         struct samr_CryptPassword crypt_pwd;
978         struct samr_CryptPasswordEx crypt_pwd_ex;
979
980         ZERO_STRUCT(sam_pol);
981         ZERO_STRUCT(domain_pol);
982         ZERO_STRUCT(user_pol);
983
984         switch (r->in.secure_channel_type) {
985         case SEC_CHAN_WKSTA:
986                 acct_flags = ACB_WSTRUST;
987                 break;
988         case SEC_CHAN_BDC:
989                 acct_flags = ACB_SVRTRUST;
990                 break;
991         default:
992                 return NT_STATUS_INVALID_PARAMETER;
993         }
994
995         if (!r->in.machine_password) {
996                 r->in.machine_password = generate_random_password(mem_ctx,
997                                 DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH,
998                                 DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH);
999                 NT_STATUS_HAVE_NO_MEMORY(r->in.machine_password);
1000         }
1001
1002         /* Open the domain */
1003
1004         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_samr,
1005                                           &pipe_hnd);
1006         if (!NT_STATUS_IS_OK(status)) {
1007                 DEBUG(0,("Error connecting to SAM pipe. Error was %s\n",
1008                         nt_errstr(status)));
1009                 goto done;
1010         }
1011
1012         b = pipe_hnd->binding_handle;
1013
1014         status = cli_get_session_key(mem_ctx, pipe_hnd, &session_key);
1015         if (!NT_STATUS_IS_OK(status)) {
1016                 DEBUG(0,("Error getting session_key of SAM pipe. Error was %s\n",
1017                         nt_errstr(status)));
1018                 goto done;
1019         }
1020
1021         status = dcerpc_samr_Connect2(b, mem_ctx,
1022                                       pipe_hnd->desthost,
1023                                       SAMR_ACCESS_ENUM_DOMAINS
1024                                       | SAMR_ACCESS_LOOKUP_DOMAIN,
1025                                       &sam_pol,
1026                                       &result);
1027         if (!NT_STATUS_IS_OK(status)) {
1028                 goto done;
1029         }
1030         if (!NT_STATUS_IS_OK(result)) {
1031                 status = result;
1032                 goto done;
1033         }
1034
1035         status = dcerpc_samr_OpenDomain(b, mem_ctx,
1036                                         &sam_pol,
1037                                         SAMR_DOMAIN_ACCESS_LOOKUP_INFO_1
1038                                         | SAMR_DOMAIN_ACCESS_CREATE_USER
1039                                         | SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
1040                                         r->out.domain_sid,
1041                                         &domain_pol,
1042                                         &result);
1043         if (!NT_STATUS_IS_OK(status)) {
1044                 goto done;
1045         }
1046         if (!NT_STATUS_IS_OK(result)) {
1047                 status = result;
1048                 goto done;
1049         }
1050
1051         /* Create domain user */
1052
1053         acct_name = talloc_asprintf(mem_ctx, "%s$", r->in.machine_name);
1054         if (!strlower_m(acct_name)) {
1055                 status = NT_STATUS_INVALID_PARAMETER;
1056                 goto done;
1057         }
1058
1059         init_lsa_String(&lsa_acct_name, acct_name);
1060
1061         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE) {
1062                 uint32_t access_desired =
1063                         SEC_GENERIC_READ | SEC_GENERIC_WRITE | SEC_GENERIC_EXECUTE |
1064                         SEC_STD_WRITE_DAC | SEC_STD_DELETE |
1065                         SAMR_USER_ACCESS_SET_PASSWORD |
1066                         SAMR_USER_ACCESS_GET_ATTRIBUTES |
1067                         SAMR_USER_ACCESS_SET_ATTRIBUTES;
1068                 uint32_t access_granted = 0;
1069
1070                 DEBUG(10,("Creating account with desired access mask: %d\n",
1071                         access_desired));
1072
1073                 status = dcerpc_samr_CreateUser2(b, mem_ctx,
1074                                                  &domain_pol,
1075                                                  &lsa_acct_name,
1076                                                  acct_flags,
1077                                                  access_desired,
1078                                                  &user_pol,
1079                                                  &access_granted,
1080                                                  &user_rid,
1081                                                  &result);
1082                 if (!NT_STATUS_IS_OK(status)) {
1083                         goto done;
1084                 }
1085
1086                 status = result;
1087                 if (!NT_STATUS_IS_OK(status) &&
1088                     !NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
1089
1090                         DEBUG(10,("Creation of workstation account failed: %s\n",
1091                                 nt_errstr(status)));
1092
1093                         /* If NT_STATUS_ACCESS_DENIED then we have a valid
1094                            username/password combo but the user does not have
1095                            administrator access. */
1096
1097                         if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
1098                                 libnet_join_set_error_string(mem_ctx, r,
1099                                         "User specified does not have "
1100                                         "administrator privileges");
1101                         }
1102
1103                         goto done;
1104                 }
1105
1106                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
1107                         if (!(r->in.join_flags &
1108                               WKSSVC_JOIN_FLAGS_DOMAIN_JOIN_IF_JOINED)) {
1109                                 goto done;
1110                         }
1111                 }
1112
1113                 /* We *must* do this.... don't ask... */
1114
1115                 if (NT_STATUS_IS_OK(status)) {
1116                         dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1117                 }
1118         }
1119
1120         status = dcerpc_samr_LookupNames(b, mem_ctx,
1121                                          &domain_pol,
1122                                          1,
1123                                          &lsa_acct_name,
1124                                          &user_rids,
1125                                          &name_types,
1126                                          &result);
1127         if (!NT_STATUS_IS_OK(status)) {
1128                 goto done;
1129         }
1130         if (!NT_STATUS_IS_OK(result)) {
1131                 status = result;
1132                 goto done;
1133         }
1134         if (user_rids.count != 1) {
1135                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
1136                 goto done;
1137         }
1138         if (name_types.count != 1) {
1139                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
1140                 goto done;
1141         }
1142
1143         if (name_types.ids[0] != SID_NAME_USER) {
1144                 DEBUG(0,("%s is not a user account (type=%d)\n",
1145                         acct_name, name_types.ids[0]));
1146                 status = NT_STATUS_INVALID_WORKSTATION;
1147                 goto done;
1148         }
1149
1150         user_rid = user_rids.ids[0];
1151
1152         /* Open handle on user */
1153
1154         status = dcerpc_samr_OpenUser(b, mem_ctx,
1155                                       &domain_pol,
1156                                       SEC_FLAG_MAXIMUM_ALLOWED,
1157                                       user_rid,
1158                                       &user_pol,
1159                                       &result);
1160         if (!NT_STATUS_IS_OK(status)) {
1161                 goto done;
1162         }
1163         if (!NT_STATUS_IS_OK(result)) {
1164                 status = result;
1165                 goto done;
1166         }
1167
1168         /* Fill in the additional account flags now */
1169
1170         acct_flags |= ACB_PWNOEXP;
1171
1172         /* Set account flags on machine account */
1173         ZERO_STRUCT(user_info.info16);
1174         user_info.info16.acct_flags = acct_flags;
1175
1176         status = dcerpc_samr_SetUserInfo(b, mem_ctx,
1177                                          &user_pol,
1178                                          16,
1179                                          &user_info,
1180                                          &result);
1181         if (!NT_STATUS_IS_OK(status)) {
1182                 dcerpc_samr_DeleteUser(b, mem_ctx,
1183                                        &user_pol,
1184                                        &result);
1185
1186                 libnet_join_set_error_string(mem_ctx, r,
1187                         "Failed to set account flags for machine account (%s)\n",
1188                         nt_errstr(status));
1189                 goto done;
1190         }
1191
1192         if (!NT_STATUS_IS_OK(result)) {
1193                 status = result;
1194
1195                 dcerpc_samr_DeleteUser(b, mem_ctx,
1196                                        &user_pol,
1197                                        &result);
1198
1199                 libnet_join_set_error_string(mem_ctx, r,
1200                         "Failed to set account flags for machine account (%s)\n",
1201                         nt_errstr(status));
1202                 goto done;
1203         }
1204
1205         /* Set password on machine account - first try level 26 */
1206
1207         /*
1208          * increase the timeout as password filter modules on the DC
1209          * might delay the operation for a significant amount of time
1210          */
1211         old_timeout = rpccli_set_timeout(pipe_hnd, 600000);
1212
1213         init_samr_CryptPasswordEx(r->in.machine_password,
1214                                   &session_key,
1215                                   &crypt_pwd_ex);
1216
1217         user_info.info26.password = crypt_pwd_ex;
1218         user_info.info26.password_expired = PASS_DONT_CHANGE_AT_NEXT_LOGON;
1219
1220         status = dcerpc_samr_SetUserInfo2(b, mem_ctx,
1221                                           &user_pol,
1222                                           26,
1223                                           &user_info,
1224                                           &result);
1225
1226         if (NT_STATUS_EQUAL(status, NT_STATUS_RPC_ENUM_VALUE_OUT_OF_RANGE)) {
1227
1228                 /* retry with level 24 */
1229
1230                 init_samr_CryptPassword(r->in.machine_password,
1231                                         &session_key,
1232                                         &crypt_pwd);
1233
1234                 user_info.info24.password = crypt_pwd;
1235                 user_info.info24.password_expired = PASS_DONT_CHANGE_AT_NEXT_LOGON;
1236
1237                 status = dcerpc_samr_SetUserInfo2(b, mem_ctx,
1238                                                   &user_pol,
1239                                                   24,
1240                                                   &user_info,
1241                                                   &result);
1242         }
1243
1244         old_timeout = rpccli_set_timeout(pipe_hnd, old_timeout);
1245
1246         if (!NT_STATUS_IS_OK(status)) {
1247
1248                 dcerpc_samr_DeleteUser(b, mem_ctx,
1249                                        &user_pol,
1250                                        &result);
1251
1252                 libnet_join_set_error_string(mem_ctx, r,
1253                         "Failed to set password for machine account (%s)\n",
1254                         nt_errstr(status));
1255                 goto done;
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 password for machine account (%s)\n",
1266                         nt_errstr(status));
1267                 goto done;
1268         }
1269
1270         status = NT_STATUS_OK;
1271
1272  done:
1273         if (!pipe_hnd) {
1274                 return status;
1275         }
1276
1277         data_blob_clear_free(&session_key);
1278
1279         if (is_valid_policy_hnd(&sam_pol)) {
1280                 dcerpc_samr_Close(b, mem_ctx, &sam_pol, &result);
1281         }
1282         if (is_valid_policy_hnd(&domain_pol)) {
1283                 dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
1284         }
1285         if (is_valid_policy_hnd(&user_pol)) {
1286                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1287         }
1288         TALLOC_FREE(pipe_hnd);
1289
1290         return status;
1291 }
1292
1293 /****************************************************************
1294 ****************************************************************/
1295
1296 NTSTATUS libnet_join_ok(struct messaging_context *msg_ctx,
1297                         const char *netbios_domain_name,
1298                         const char *dc_name,
1299                         const bool use_kerberos)
1300 {
1301         TALLOC_CTX *frame = talloc_stackframe();
1302         struct cli_state *cli = NULL;
1303         struct rpc_pipe_client *netlogon_pipe = NULL;
1304         struct cli_credentials *cli_creds = NULL;
1305         struct netlogon_creds_cli_context *netlogon_creds = NULL;
1306         struct netlogon_creds_CredentialState *creds = NULL;
1307         uint32_t netlogon_flags = 0;
1308         NTSTATUS status;
1309         const char *machine_account = NULL;
1310         const char *machine_domain = NULL;
1311         const char *machine_password = NULL;
1312         int flags = 0;
1313
1314         if (!dc_name) {
1315                 TALLOC_FREE(frame);
1316                 return NT_STATUS_INVALID_PARAMETER;
1317         }
1318
1319         if (!secrets_init()) {
1320                 TALLOC_FREE(frame);
1321                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1322         }
1323
1324         status = pdb_get_trust_credentials(netbios_domain_name, NULL,
1325                                            frame, &cli_creds);
1326         if (!NT_STATUS_IS_OK(status)) {
1327                 TALLOC_FREE(frame);
1328                 return status;
1329         }
1330
1331         /* we don't want any old password */
1332         cli_credentials_set_old_password(cli_creds, NULL, CRED_SPECIFIED);
1333
1334         if (use_kerberos) {
1335                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
1336         }
1337
1338         machine_account = cli_credentials_get_username(cli_creds);
1339         machine_domain = cli_credentials_get_domain(cli_creds);
1340         machine_password = cli_credentials_get_password(cli_creds);
1341
1342         status = cli_full_connection(&cli, NULL,
1343                                      dc_name,
1344                                      NULL, 0,
1345                                      "IPC$", "IPC",
1346                                      machine_account,
1347                                      machine_domain,
1348                                      machine_password,
1349                                      flags,
1350                                      SMB_SIGNING_DEFAULT);
1351
1352         if (!NT_STATUS_IS_OK(status)) {
1353                 status = cli_full_connection(&cli, NULL,
1354                                              dc_name,
1355                                              NULL, 0,
1356                                              "IPC$", "IPC",
1357                                              "",
1358                                              NULL,
1359                                              "",
1360                                              0,
1361                                              SMB_SIGNING_DEFAULT);
1362         }
1363
1364         if (!NT_STATUS_IS_OK(status)) {
1365                 TALLOC_FREE(frame);
1366                 return status;
1367         }
1368
1369         status = rpccli_create_netlogon_creds_with_creds(cli_creds,
1370                                                          dc_name,
1371                                                          msg_ctx,
1372                                                          frame,
1373                                                          &netlogon_creds);
1374         if (!NT_STATUS_IS_OK(status)) {
1375                 cli_shutdown(cli);
1376                 TALLOC_FREE(frame);
1377                 return status;
1378         }
1379
1380         status = rpccli_setup_netlogon_creds_with_creds(cli, NCACN_NP,
1381                                                         netlogon_creds,
1382                                                         true, /* force_reauth */
1383                                                         cli_creds);
1384         if (!NT_STATUS_IS_OK(status)) {
1385                 DEBUG(0,("connect_to_domain_password_server: "
1386                          "unable to open the domain client session to "
1387                          "machine %s. Flags[0x%08X] Error was : %s.\n",
1388                          dc_name, (unsigned)netlogon_flags,
1389                          nt_errstr(status)));
1390                 cli_shutdown(cli);
1391                 TALLOC_FREE(frame);
1392                 return status;
1393         }
1394
1395         status = netlogon_creds_cli_get(netlogon_creds,
1396                                         talloc_tos(),
1397                                         &creds);
1398         if (!NT_STATUS_IS_OK(status)) {
1399                 cli_shutdown(cli);
1400                 TALLOC_FREE(frame);
1401                 return status;
1402         }
1403         netlogon_flags = creds->negotiate_flags;
1404         TALLOC_FREE(creds);
1405
1406         if (!(netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
1407                 cli_shutdown(cli);
1408                 TALLOC_FREE(frame);
1409                 return NT_STATUS_OK;
1410         }
1411
1412         status = cli_rpc_pipe_open_schannel_with_creds(
1413                 cli, &ndr_table_netlogon, NCACN_NP,
1414                 cli_creds,
1415                 netlogon_creds, &netlogon_pipe);
1416
1417         TALLOC_FREE(netlogon_pipe);
1418
1419         if (!NT_STATUS_IS_OK(status)) {
1420                 DEBUG(0,("libnet_join_ok: failed to open schannel session "
1421                         "on netlogon pipe to server %s for domain %s. "
1422                         "Error was %s\n",
1423                         smbXcli_conn_remote_name(cli->conn),
1424                         netbios_domain_name, nt_errstr(status)));
1425                 cli_shutdown(cli);
1426                 TALLOC_FREE(frame);
1427                 return status;
1428         }
1429
1430         cli_shutdown(cli);
1431         TALLOC_FREE(frame);
1432         return NT_STATUS_OK;
1433 }
1434
1435 /****************************************************************
1436 ****************************************************************/
1437
1438 static WERROR libnet_join_post_verify(TALLOC_CTX *mem_ctx,
1439                                       struct libnet_JoinCtx *r)
1440 {
1441         NTSTATUS status;
1442
1443         status = libnet_join_ok(r->in.msg_ctx,
1444                                 r->out.netbios_domain_name,
1445                                 r->in.dc_name,
1446                                 r->in.use_kerberos);
1447         if (!NT_STATUS_IS_OK(status)) {
1448                 libnet_join_set_error_string(mem_ctx, r,
1449                         "failed to verify domain membership after joining: %s",
1450                         get_friendly_nt_error_msg(status));
1451                 return WERR_SETUP_NOT_JOINED;
1452         }
1453
1454         return WERR_OK;
1455 }
1456
1457 /****************************************************************
1458 ****************************************************************/
1459
1460 static bool libnet_join_unjoindomain_remove_secrets(TALLOC_CTX *mem_ctx,
1461                                                     struct libnet_UnjoinCtx *r)
1462 {
1463         if (!secrets_delete_machine_password_ex(lp_workgroup())) {
1464                 return false;
1465         }
1466
1467         if (!secrets_delete_domain_sid(lp_workgroup())) {
1468                 return false;
1469         }
1470
1471         return true;
1472 }
1473
1474 /****************************************************************
1475 ****************************************************************/
1476
1477 static NTSTATUS libnet_join_unjoindomain_rpc(TALLOC_CTX *mem_ctx,
1478                                              struct libnet_UnjoinCtx *r)
1479 {
1480         struct cli_state *cli = NULL;
1481         struct rpc_pipe_client *pipe_hnd = NULL;
1482         struct policy_handle sam_pol, domain_pol, user_pol;
1483         NTSTATUS status = NT_STATUS_UNSUCCESSFUL, result;
1484         char *acct_name;
1485         uint32_t user_rid;
1486         struct lsa_String lsa_acct_name;
1487         struct samr_Ids user_rids;
1488         struct samr_Ids name_types;
1489         union samr_UserInfo *info = NULL;
1490         struct dcerpc_binding_handle *b = NULL;
1491
1492         ZERO_STRUCT(sam_pol);
1493         ZERO_STRUCT(domain_pol);
1494         ZERO_STRUCT(user_pol);
1495
1496         status = libnet_join_connect_dc_ipc(r->in.dc_name,
1497                                             r->in.admin_account,
1498                                             r->in.admin_domain,
1499                                             r->in.admin_password,
1500                                             r->in.use_kerberos,
1501                                             &cli);
1502         if (!NT_STATUS_IS_OK(status)) {
1503                 goto done;
1504         }
1505
1506         /* Open the domain */
1507
1508         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_samr,
1509                                           &pipe_hnd);
1510         if (!NT_STATUS_IS_OK(status)) {
1511                 DEBUG(0,("Error connecting to SAM pipe. Error was %s\n",
1512                         nt_errstr(status)));
1513                 goto done;
1514         }
1515
1516         b = pipe_hnd->binding_handle;
1517
1518         status = dcerpc_samr_Connect2(b, mem_ctx,
1519                                       pipe_hnd->desthost,
1520                                       SEC_FLAG_MAXIMUM_ALLOWED,
1521                                       &sam_pol,
1522                                       &result);
1523         if (!NT_STATUS_IS_OK(status)) {
1524                 goto done;
1525         }
1526         if (!NT_STATUS_IS_OK(result)) {
1527                 status = result;
1528                 goto done;
1529         }
1530
1531         status = dcerpc_samr_OpenDomain(b, mem_ctx,
1532                                         &sam_pol,
1533                                         SEC_FLAG_MAXIMUM_ALLOWED,
1534                                         r->in.domain_sid,
1535                                         &domain_pol,
1536                                         &result);
1537         if (!NT_STATUS_IS_OK(status)) {
1538                 goto done;
1539         }
1540         if (!NT_STATUS_IS_OK(result)) {
1541                 status = result;
1542                 goto done;
1543         }
1544
1545         /* Create domain user */
1546
1547         acct_name = talloc_asprintf(mem_ctx, "%s$", r->in.machine_name);
1548         if (!strlower_m(acct_name)) {
1549                 status = NT_STATUS_INVALID_PARAMETER;
1550                 goto done;
1551         }
1552
1553         init_lsa_String(&lsa_acct_name, acct_name);
1554
1555         status = dcerpc_samr_LookupNames(b, mem_ctx,
1556                                          &domain_pol,
1557                                          1,
1558                                          &lsa_acct_name,
1559                                          &user_rids,
1560                                          &name_types,
1561                                          &result);
1562
1563         if (!NT_STATUS_IS_OK(status)) {
1564                 goto done;
1565         }
1566         if (!NT_STATUS_IS_OK(result)) {
1567                 status = result;
1568                 goto done;
1569         }
1570         if (user_rids.count != 1) {
1571                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
1572                 goto done;
1573         }
1574         if (name_types.count != 1) {
1575                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
1576                 goto done;
1577         }
1578
1579         if (name_types.ids[0] != SID_NAME_USER) {
1580                 DEBUG(0, ("%s is not a user account (type=%d)\n", acct_name,
1581                         name_types.ids[0]));
1582                 status = NT_STATUS_INVALID_WORKSTATION;
1583                 goto done;
1584         }
1585
1586         user_rid = user_rids.ids[0];
1587
1588         /* Open handle on user */
1589
1590         status = dcerpc_samr_OpenUser(b, mem_ctx,
1591                                       &domain_pol,
1592                                       SEC_FLAG_MAXIMUM_ALLOWED,
1593                                       user_rid,
1594                                       &user_pol,
1595                                       &result);
1596         if (!NT_STATUS_IS_OK(status)) {
1597                 goto done;
1598         }
1599         if (!NT_STATUS_IS_OK(result)) {
1600                 status = result;
1601                 goto done;
1602         }
1603
1604         /* Get user info */
1605
1606         status = dcerpc_samr_QueryUserInfo(b, mem_ctx,
1607                                            &user_pol,
1608                                            16,
1609                                            &info,
1610                                            &result);
1611         if (!NT_STATUS_IS_OK(status)) {
1612                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1613                 goto done;
1614         }
1615         if (!NT_STATUS_IS_OK(result)) {
1616                 status = result;
1617                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1618                 goto done;
1619         }
1620
1621         /* now disable and setuser info */
1622
1623         info->info16.acct_flags |= ACB_DISABLED;
1624
1625         status = dcerpc_samr_SetUserInfo(b, mem_ctx,
1626                                          &user_pol,
1627                                          16,
1628                                          info,
1629                                          &result);
1630         if (!NT_STATUS_IS_OK(status)) {
1631                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1632                 goto done;
1633         }
1634         if (!NT_STATUS_IS_OK(result)) {
1635                 status = result;
1636                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1637                 goto done;
1638         }
1639         status = result;
1640         dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1641
1642 done:
1643         if (pipe_hnd && b) {
1644                 if (is_valid_policy_hnd(&domain_pol)) {
1645                         dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
1646                 }
1647                 if (is_valid_policy_hnd(&sam_pol)) {
1648                         dcerpc_samr_Close(b, mem_ctx, &sam_pol, &result);
1649                 }
1650                 TALLOC_FREE(pipe_hnd);
1651         }
1652
1653         if (cli) {
1654                 cli_shutdown(cli);
1655         }
1656
1657         return status;
1658 }
1659
1660 /****************************************************************
1661 ****************************************************************/
1662
1663 static WERROR do_join_modify_vals_config(struct libnet_JoinCtx *r)
1664 {
1665         WERROR werr = WERR_OK;
1666         sbcErr err;
1667         struct smbconf_ctx *ctx;
1668
1669         err = smbconf_init_reg(r, &ctx, NULL);
1670         if (!SBC_ERROR_IS_OK(err)) {
1671                 werr = WERR_NO_SUCH_SERVICE;
1672                 goto done;
1673         }
1674
1675         if (!(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE)) {
1676
1677                 err = smbconf_set_global_parameter(ctx, "security", "user");
1678                 if (!SBC_ERROR_IS_OK(err)) {
1679                         werr = WERR_NO_SUCH_SERVICE;
1680                         goto done;
1681                 }
1682
1683                 err = smbconf_set_global_parameter(ctx, "workgroup",
1684                                                    r->in.domain_name);
1685                 if (!SBC_ERROR_IS_OK(err)) {
1686                         werr = WERR_NO_SUCH_SERVICE;
1687                         goto done;
1688                 }
1689
1690                 smbconf_delete_global_parameter(ctx, "realm");
1691                 goto done;
1692         }
1693
1694         err = smbconf_set_global_parameter(ctx, "security", "domain");
1695         if (!SBC_ERROR_IS_OK(err)) {
1696                 werr = WERR_NO_SUCH_SERVICE;
1697                 goto done;
1698         }
1699
1700         err = smbconf_set_global_parameter(ctx, "workgroup",
1701                                            r->out.netbios_domain_name);
1702         if (!SBC_ERROR_IS_OK(err)) {
1703                 werr = WERR_NO_SUCH_SERVICE;
1704                 goto done;
1705         }
1706
1707         if (r->out.domain_is_ad) {
1708                 err = smbconf_set_global_parameter(ctx, "security", "ads");
1709                 if (!SBC_ERROR_IS_OK(err)) {
1710                         werr = WERR_NO_SUCH_SERVICE;
1711                         goto done;
1712                 }
1713
1714                 err = smbconf_set_global_parameter(ctx, "realm",
1715                                                    r->out.dns_domain_name);
1716                 if (!SBC_ERROR_IS_OK(err)) {
1717                         werr = WERR_NO_SUCH_SERVICE;
1718                         goto done;
1719                 }
1720         }
1721
1722  done:
1723         smbconf_shutdown(ctx);
1724         return werr;
1725 }
1726
1727 /****************************************************************
1728 ****************************************************************/
1729
1730 static WERROR do_unjoin_modify_vals_config(struct libnet_UnjoinCtx *r)
1731 {
1732         WERROR werr = WERR_OK;
1733         sbcErr err;
1734         struct smbconf_ctx *ctx;
1735
1736         err = smbconf_init_reg(r, &ctx, NULL);
1737         if (!SBC_ERROR_IS_OK(err)) {
1738                 werr = WERR_NO_SUCH_SERVICE;
1739                 goto done;
1740         }
1741
1742         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1743
1744                 err = smbconf_set_global_parameter(ctx, "security", "user");
1745                 if (!SBC_ERROR_IS_OK(err)) {
1746                         werr = WERR_NO_SUCH_SERVICE;
1747                         goto done;
1748                 }
1749
1750                 err = smbconf_delete_global_parameter(ctx, "workgroup");
1751                 if (!SBC_ERROR_IS_OK(err)) {
1752                         werr = WERR_NO_SUCH_SERVICE;
1753                         goto done;
1754                 }
1755
1756                 smbconf_delete_global_parameter(ctx, "realm");
1757         }
1758
1759  done:
1760         smbconf_shutdown(ctx);
1761         return werr;
1762 }
1763
1764 /****************************************************************
1765 ****************************************************************/
1766
1767 static WERROR do_JoinConfig(struct libnet_JoinCtx *r)
1768 {
1769         WERROR werr;
1770
1771         if (!W_ERROR_IS_OK(r->out.result)) {
1772                 return r->out.result;
1773         }
1774
1775         if (!r->in.modify_config) {
1776                 return WERR_OK;
1777         }
1778
1779         werr = do_join_modify_vals_config(r);
1780         if (!W_ERROR_IS_OK(werr)) {
1781                 return werr;
1782         }
1783
1784         lp_load_global(get_dyn_CONFIGFILE());
1785
1786         r->out.modified_config = true;
1787         r->out.result = werr;
1788
1789         return werr;
1790 }
1791
1792 /****************************************************************
1793 ****************************************************************/
1794
1795 static WERROR libnet_unjoin_config(struct libnet_UnjoinCtx *r)
1796 {
1797         WERROR werr;
1798
1799         if (!W_ERROR_IS_OK(r->out.result)) {
1800                 return r->out.result;
1801         }
1802
1803         if (!r->in.modify_config) {
1804                 return WERR_OK;
1805         }
1806
1807         werr = do_unjoin_modify_vals_config(r);
1808         if (!W_ERROR_IS_OK(werr)) {
1809                 return werr;
1810         }
1811
1812         lp_load_global(get_dyn_CONFIGFILE());
1813
1814         r->out.modified_config = true;
1815         r->out.result = werr;
1816
1817         return werr;
1818 }
1819
1820 /****************************************************************
1821 ****************************************************************/
1822
1823 static bool libnet_parse_domain_dc(TALLOC_CTX *mem_ctx,
1824                                    const char *domain_str,
1825                                    const char **domain_p,
1826                                    const char **dc_p)
1827 {
1828         char *domain = NULL;
1829         char *dc = NULL;
1830         const char *p = NULL;
1831
1832         if (!domain_str || !domain_p || !dc_p) {
1833                 return false;
1834         }
1835
1836         p = strchr_m(domain_str, '\\');
1837
1838         if (p != NULL) {
1839                 domain = talloc_strndup(mem_ctx, domain_str,
1840                                          PTR_DIFF(p, domain_str));
1841                 dc = talloc_strdup(mem_ctx, p+1);
1842                 if (!dc) {
1843                         return false;
1844                 }
1845         } else {
1846                 domain = talloc_strdup(mem_ctx, domain_str);
1847                 dc = NULL;
1848         }
1849         if (!domain) {
1850                 return false;
1851         }
1852
1853         *domain_p = domain;
1854
1855         if (!*dc_p && dc) {
1856                 *dc_p = dc;
1857         }
1858
1859         return true;
1860 }
1861
1862 /****************************************************************
1863 ****************************************************************/
1864
1865 static WERROR libnet_join_pre_processing(TALLOC_CTX *mem_ctx,
1866                                          struct libnet_JoinCtx *r)
1867 {
1868         if (!r->in.domain_name) {
1869                 libnet_join_set_error_string(mem_ctx, r,
1870                         "No domain name defined");
1871                 return WERR_INVALID_PARAM;
1872         }
1873
1874         if (strlen(r->in.machine_name) > 15) {
1875                 libnet_join_set_error_string(mem_ctx, r,
1876                         "Our netbios name can be at most 15 chars long, "
1877                          "\"%s\" is %u chars long\n",
1878                          r->in.machine_name,
1879                          (unsigned int)strlen(r->in.machine_name));
1880                 return WERR_INVALID_PARAM;
1881         }
1882
1883         if (!libnet_parse_domain_dc(mem_ctx, r->in.domain_name,
1884                                     &r->in.domain_name,
1885                                     &r->in.dc_name)) {
1886                 libnet_join_set_error_string(mem_ctx, r,
1887                         "Failed to parse domain name");
1888                 return WERR_INVALID_PARAM;
1889         }
1890
1891         if (!r->in.admin_domain) {
1892                 char *admin_domain = NULL;
1893                 char *admin_account = NULL;
1894                 split_domain_user(mem_ctx,
1895                                   r->in.admin_account,
1896                                   &admin_domain,
1897                                   &admin_account);
1898                 r->in.admin_domain = admin_domain;
1899                 r->in.admin_account = admin_account;
1900         }
1901
1902         if (!secrets_init()) {
1903                 libnet_join_set_error_string(mem_ctx, r,
1904                         "Unable to open secrets database");
1905                 return WERR_CAN_NOT_COMPLETE;
1906         }
1907
1908         return WERR_OK;
1909 }
1910
1911 /****************************************************************
1912 ****************************************************************/
1913
1914 static void libnet_join_add_dom_rids_to_builtins(struct dom_sid *domain_sid)
1915 {
1916         NTSTATUS status;
1917
1918         /* Try adding dom admins to builtin\admins. Only log failures. */
1919         status = create_builtin_administrators(domain_sid);
1920         if (NT_STATUS_EQUAL(status, NT_STATUS_PROTOCOL_UNREACHABLE)) {
1921                 DEBUG(10,("Unable to auto-add domain administrators to "
1922                           "BUILTIN\\Administrators during join because "
1923                           "winbindd must be running.\n"));
1924         } else if (!NT_STATUS_IS_OK(status)) {
1925                 DEBUG(5, ("Failed to auto-add domain administrators to "
1926                           "BUILTIN\\Administrators during join: %s\n",
1927                           nt_errstr(status)));
1928         }
1929
1930         /* Try adding dom users to builtin\users. Only log failures. */
1931         status = create_builtin_users(domain_sid);
1932         if (NT_STATUS_EQUAL(status, NT_STATUS_PROTOCOL_UNREACHABLE)) {
1933                 DEBUG(10,("Unable to auto-add domain users to BUILTIN\\users "
1934                           "during join because winbindd must be running.\n"));
1935         } else if (!NT_STATUS_IS_OK(status)) {
1936                 DEBUG(5, ("Failed to auto-add domain administrators to "
1937                           "BUILTIN\\Administrators during join: %s\n",
1938                           nt_errstr(status)));
1939         }
1940 }
1941
1942 /****************************************************************
1943 ****************************************************************/
1944
1945 static WERROR libnet_join_post_processing(TALLOC_CTX *mem_ctx,
1946                                           struct libnet_JoinCtx *r)
1947 {
1948         WERROR werr;
1949
1950         if (!W_ERROR_IS_OK(r->out.result)) {
1951                 return r->out.result;
1952         }
1953
1954         werr = do_JoinConfig(r);
1955         if (!W_ERROR_IS_OK(werr)) {
1956                 return werr;
1957         }
1958
1959         if (!(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE)) {
1960                 return WERR_OK;
1961         }
1962
1963         saf_join_store(r->out.netbios_domain_name, r->in.dc_name);
1964         if (r->out.dns_domain_name) {
1965                 saf_join_store(r->out.dns_domain_name, r->in.dc_name);
1966         }
1967
1968 #ifdef HAVE_ADS
1969         if (r->out.domain_is_ad &&
1970             !(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE)) {
1971                 ADS_STATUS ads_status;
1972
1973                 ads_status  = libnet_join_post_processing_ads(mem_ctx, r);
1974                 if (!ADS_ERR_OK(ads_status)) {
1975                         return WERR_GENERAL_FAILURE;
1976                 }
1977         }
1978 #endif /* HAVE_ADS */
1979
1980         libnet_join_add_dom_rids_to_builtins(r->out.domain_sid);
1981
1982         return WERR_OK;
1983 }
1984
1985 /****************************************************************
1986 ****************************************************************/
1987
1988 static int libnet_destroy_JoinCtx(struct libnet_JoinCtx *r)
1989 {
1990         if (r->in.ads) {
1991                 ads_destroy(&r->in.ads);
1992         }
1993
1994         return 0;
1995 }
1996
1997 /****************************************************************
1998 ****************************************************************/
1999
2000 static int libnet_destroy_UnjoinCtx(struct libnet_UnjoinCtx *r)
2001 {
2002         if (r->in.ads) {
2003                 ads_destroy(&r->in.ads);
2004         }
2005
2006         return 0;
2007 }
2008
2009 /****************************************************************
2010 ****************************************************************/
2011
2012 WERROR libnet_init_JoinCtx(TALLOC_CTX *mem_ctx,
2013                            struct libnet_JoinCtx **r)
2014 {
2015         struct libnet_JoinCtx *ctx;
2016
2017         ctx = talloc_zero(mem_ctx, struct libnet_JoinCtx);
2018         if (!ctx) {
2019                 return WERR_NOMEM;
2020         }
2021
2022         talloc_set_destructor(ctx, libnet_destroy_JoinCtx);
2023
2024         ctx->in.machine_name = talloc_strdup(mem_ctx, lp_netbios_name());
2025         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
2026
2027         ctx->in.secure_channel_type = SEC_CHAN_WKSTA;
2028
2029         *r = ctx;
2030
2031         return WERR_OK;
2032 }
2033
2034 /****************************************************************
2035 ****************************************************************/
2036
2037 WERROR libnet_init_UnjoinCtx(TALLOC_CTX *mem_ctx,
2038                              struct libnet_UnjoinCtx **r)
2039 {
2040         struct libnet_UnjoinCtx *ctx;
2041
2042         ctx = talloc_zero(mem_ctx, struct libnet_UnjoinCtx);
2043         if (!ctx) {
2044                 return WERR_NOMEM;
2045         }
2046
2047         talloc_set_destructor(ctx, libnet_destroy_UnjoinCtx);
2048
2049         ctx->in.machine_name = talloc_strdup(mem_ctx, lp_netbios_name());
2050         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
2051
2052         *r = ctx;
2053
2054         return WERR_OK;
2055 }
2056
2057 /****************************************************************
2058 ****************************************************************/
2059
2060 static WERROR libnet_join_check_config(TALLOC_CTX *mem_ctx,
2061                                        struct libnet_JoinCtx *r)
2062 {
2063         bool valid_security = false;
2064         bool valid_workgroup = false;
2065         bool valid_realm = false;
2066
2067         /* check if configuration is already set correctly */
2068
2069         valid_workgroup = strequal(lp_workgroup(), r->out.netbios_domain_name);
2070
2071         switch (r->out.domain_is_ad) {
2072                 case false:
2073                         valid_security = (lp_security() == SEC_DOMAIN)
2074                                 || (lp_server_role() == ROLE_DOMAIN_PDC)
2075                                 || (lp_server_role() == ROLE_DOMAIN_BDC);
2076                         if (valid_workgroup && valid_security) {
2077                                 /* nothing to be done */
2078                                 return WERR_OK;
2079                         }
2080                         break;
2081                 case true:
2082                         valid_realm = strequal(lp_realm(), r->out.dns_domain_name);
2083                         switch (lp_security()) {
2084                         case SEC_DOMAIN:
2085                         case SEC_ADS:
2086                                 valid_security = true;
2087                         }
2088
2089                         if (valid_workgroup && valid_realm && valid_security) {
2090                                 /* nothing to be done */
2091                                 return WERR_OK;
2092                         }
2093                         break;
2094         }
2095
2096         /* check if we are supposed to manipulate configuration */
2097
2098         if (!r->in.modify_config) {
2099
2100                 char *wrong_conf = talloc_strdup(mem_ctx, "");
2101
2102                 if (!valid_workgroup) {
2103                         wrong_conf = talloc_asprintf_append(wrong_conf,
2104                                 "\"workgroup\" set to '%s', should be '%s'",
2105                                 lp_workgroup(), r->out.netbios_domain_name);
2106                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
2107                 }
2108
2109                 if (!valid_realm) {
2110                         wrong_conf = talloc_asprintf_append(wrong_conf,
2111                                 "\"realm\" set to '%s', should be '%s'",
2112                                 lp_realm(), r->out.dns_domain_name);
2113                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
2114                 }
2115
2116                 if (!valid_security) {
2117                         const char *sec = NULL;
2118                         switch (lp_security()) {
2119                         case SEC_USER:  sec = "user"; break;
2120                         case SEC_DOMAIN: sec = "domain"; break;
2121                         case SEC_ADS: sec = "ads"; break;
2122                         }
2123                         wrong_conf = talloc_asprintf_append(wrong_conf,
2124                                 "\"security\" set to '%s', should be %s",
2125                                 sec, r->out.domain_is_ad ?
2126                                 "either 'domain' or 'ads'" : "'domain'");
2127                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
2128                 }
2129
2130                 libnet_join_set_error_string(mem_ctx, r,
2131                         "Invalid configuration (%s) and configuration modification "
2132                         "was not requested", wrong_conf);
2133                 return WERR_CAN_NOT_COMPLETE;
2134         }
2135
2136         /* check if we are able to manipulate configuration */
2137
2138         if (!lp_config_backend_is_registry()) {
2139                 libnet_join_set_error_string(mem_ctx, r,
2140                         "Configuration manipulation requested but not "
2141                         "supported by backend");
2142                 return WERR_NOT_SUPPORTED;
2143         }
2144
2145         return WERR_OK;
2146 }
2147
2148 /****************************************************************
2149 ****************************************************************/
2150
2151 static WERROR libnet_DomainJoin(TALLOC_CTX *mem_ctx,
2152                                 struct libnet_JoinCtx *r)
2153 {
2154         NTSTATUS status;
2155         WERROR werr;
2156         struct cli_state *cli = NULL;
2157 #ifdef HAVE_ADS
2158         ADS_STATUS ads_status;
2159 #endif /* HAVE_ADS */
2160
2161         if (!r->in.dc_name) {
2162                 struct netr_DsRGetDCNameInfo *info;
2163                 const char *dc;
2164                 uint32_t name_type_flags = 0;
2165                 if (r->in.domain_name_type == JoinDomNameTypeDNS) {
2166                         name_type_flags = DS_IS_DNS_NAME;
2167                 } else if (r->in.domain_name_type == JoinDomNameTypeNBT) {
2168                         name_type_flags = DS_IS_FLAT_NAME;
2169                 }
2170                 status = dsgetdcname(mem_ctx,
2171                                      r->in.msg_ctx,
2172                                      r->in.domain_name,
2173                                      NULL,
2174                                      NULL,
2175                                      DS_FORCE_REDISCOVERY |
2176                                      DS_DIRECTORY_SERVICE_REQUIRED |
2177                                      DS_WRITABLE_REQUIRED |
2178                                      DS_RETURN_DNS_NAME |
2179                                      name_type_flags,
2180                                      &info);
2181                 if (!NT_STATUS_IS_OK(status)) {
2182                         libnet_join_set_error_string(mem_ctx, r,
2183                                 "failed to find DC for domain %s",
2184                                 r->in.domain_name,
2185                                 get_friendly_nt_error_msg(status));
2186                         return WERR_DCNOTFOUND;
2187                 }
2188
2189                 dc = strip_hostname(info->dc_unc);
2190                 r->in.dc_name = talloc_strdup(mem_ctx, dc);
2191                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
2192         }
2193
2194         status = libnet_join_lookup_dc_rpc(mem_ctx, r, &cli);
2195         if (!NT_STATUS_IS_OK(status)) {
2196                 libnet_join_set_error_string(mem_ctx, r,
2197                         "failed to lookup DC info for domain '%s' over rpc: %s",
2198                         r->in.domain_name, get_friendly_nt_error_msg(status));
2199                 return ntstatus_to_werror(status);
2200         }
2201
2202         werr = libnet_join_check_config(mem_ctx, r);
2203         if (!W_ERROR_IS_OK(werr)) {
2204                 goto done;
2205         }
2206
2207 #ifdef HAVE_ADS
2208
2209         create_local_private_krb5_conf_for_domain(
2210                 r->out.dns_domain_name, r->out.netbios_domain_name,
2211                 NULL, smbXcli_conn_remote_sockaddr(cli->conn));
2212
2213         if (r->out.domain_is_ad && r->in.account_ou &&
2214             !(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE)) {
2215
2216                 ads_status = libnet_join_connect_ads(mem_ctx, r);
2217                 if (!ADS_ERR_OK(ads_status)) {
2218                         return WERR_DEFAULT_JOIN_REQUIRED;
2219                 }
2220
2221                 ads_status = libnet_join_precreate_machine_acct(mem_ctx, r);
2222                 if (!ADS_ERR_OK(ads_status)) {
2223                         libnet_join_set_error_string(mem_ctx, r,
2224                                 "failed to precreate account in ou %s: %s",
2225                                 r->in.account_ou,
2226                                 ads_errstr(ads_status));
2227                         return WERR_DEFAULT_JOIN_REQUIRED;
2228                 }
2229
2230                 r->in.join_flags &= ~WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE;
2231         }
2232 #endif /* HAVE_ADS */
2233
2234         if ((r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE) &&
2235             (r->in.join_flags & WKSSVC_JOIN_FLAGS_MACHINE_PWD_PASSED)) {
2236                 status = libnet_join_joindomain_rpc_unsecure(mem_ctx, r, cli);
2237         } else {
2238                 status = libnet_join_joindomain_rpc(mem_ctx, r, cli);
2239         }
2240         if (!NT_STATUS_IS_OK(status)) {
2241                 libnet_join_set_error_string(mem_ctx, r,
2242                         "failed to join domain '%s' over rpc: %s",
2243                         r->in.domain_name, get_friendly_nt_error_msg(status));
2244                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
2245                         return WERR_SETUP_ALREADY_JOINED;
2246                 }
2247                 werr = ntstatus_to_werror(status);
2248                 goto done;
2249         }
2250
2251         if (!libnet_join_joindomain_store_secrets(mem_ctx, r)) {
2252                 werr = WERR_SETUP_NOT_JOINED;
2253                 goto done;
2254         }
2255
2256         werr = WERR_OK;
2257
2258  done:
2259         if (cli) {
2260                 cli_shutdown(cli);
2261         }
2262
2263         return werr;
2264 }
2265
2266 /****************************************************************
2267 ****************************************************************/
2268
2269 static WERROR libnet_join_rollback(TALLOC_CTX *mem_ctx,
2270                                    struct libnet_JoinCtx *r)
2271 {
2272         WERROR werr;
2273         struct libnet_UnjoinCtx *u = NULL;
2274
2275         werr = libnet_init_UnjoinCtx(mem_ctx, &u);
2276         if (!W_ERROR_IS_OK(werr)) {
2277                 return werr;
2278         }
2279
2280         u->in.debug             = r->in.debug;
2281         u->in.dc_name           = r->in.dc_name;
2282         u->in.domain_name       = r->in.domain_name;
2283         u->in.admin_account     = r->in.admin_account;
2284         u->in.admin_password    = r->in.admin_password;
2285         u->in.modify_config     = r->in.modify_config;
2286         u->in.use_kerberos      = r->in.use_kerberos;
2287         u->in.unjoin_flags      = WKSSVC_JOIN_FLAGS_JOIN_TYPE |
2288                                   WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE;
2289
2290         werr = libnet_Unjoin(mem_ctx, u);
2291         TALLOC_FREE(u);
2292
2293         return werr;
2294 }
2295
2296 /****************************************************************
2297 ****************************************************************/
2298
2299 WERROR libnet_Join(TALLOC_CTX *mem_ctx,
2300                    struct libnet_JoinCtx *r)
2301 {
2302         WERROR werr;
2303
2304         if (r->in.debug) {
2305                 LIBNET_JOIN_IN_DUMP_CTX(mem_ctx, r);
2306         }
2307
2308         ZERO_STRUCT(r->out);
2309
2310         werr = libnet_join_pre_processing(mem_ctx, r);
2311         if (!W_ERROR_IS_OK(werr)) {
2312                 goto done;
2313         }
2314
2315         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
2316                 werr = libnet_DomainJoin(mem_ctx, r);
2317                 if (!W_ERROR_IS_OK(werr)) {
2318                         goto done;
2319                 }
2320         }
2321
2322         werr = libnet_join_post_processing(mem_ctx, r);
2323         if (!W_ERROR_IS_OK(werr)) {
2324                 goto done;
2325         }
2326
2327         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
2328                 werr = libnet_join_post_verify(mem_ctx, r);
2329                 if (!W_ERROR_IS_OK(werr)) {
2330                         libnet_join_rollback(mem_ctx, r);
2331                 }
2332         }
2333
2334  done:
2335         r->out.result = werr;
2336
2337         if (r->in.debug) {
2338                 LIBNET_JOIN_OUT_DUMP_CTX(mem_ctx, r);
2339         }
2340         return werr;
2341 }
2342
2343 /****************************************************************
2344 ****************************************************************/
2345
2346 static WERROR libnet_DomainUnjoin(TALLOC_CTX *mem_ctx,
2347                                   struct libnet_UnjoinCtx *r)
2348 {
2349         NTSTATUS status;
2350
2351         if (!r->in.domain_sid) {
2352                 struct dom_sid sid;
2353                 if (!secrets_fetch_domain_sid(lp_workgroup(), &sid)) {
2354                         libnet_unjoin_set_error_string(mem_ctx, r,
2355                                 "Unable to fetch domain sid: are we joined?");
2356                         return WERR_SETUP_NOT_JOINED;
2357                 }
2358                 r->in.domain_sid = dom_sid_dup(mem_ctx, &sid);
2359                 W_ERROR_HAVE_NO_MEMORY(r->in.domain_sid);
2360         }
2361
2362         if (!(r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE) && 
2363             !r->in.delete_machine_account) {
2364                 libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2365                 return WERR_OK;
2366         }
2367
2368         if (!r->in.dc_name) {
2369                 struct netr_DsRGetDCNameInfo *info;
2370                 const char *dc;
2371                 status = dsgetdcname(mem_ctx,
2372                                      r->in.msg_ctx,
2373                                      r->in.domain_name,
2374                                      NULL,
2375                                      NULL,
2376                                      DS_DIRECTORY_SERVICE_REQUIRED |
2377                                      DS_WRITABLE_REQUIRED |
2378                                      DS_RETURN_DNS_NAME,
2379                                      &info);
2380                 if (!NT_STATUS_IS_OK(status)) {
2381                         libnet_unjoin_set_error_string(mem_ctx, r,
2382                                 "failed to find DC for domain %s",
2383                                 r->in.domain_name,
2384                                 get_friendly_nt_error_msg(status));
2385                         return WERR_DCNOTFOUND;
2386                 }
2387
2388                 dc = strip_hostname(info->dc_unc);
2389                 r->in.dc_name = talloc_strdup(mem_ctx, dc);
2390                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
2391         }
2392
2393 #ifdef HAVE_ADS
2394         /* for net ads leave, try to delete the account.  If it works, 
2395            no sense in disabling.  If it fails, we can still try to 
2396            disable it. jmcd */
2397
2398         if (r->in.delete_machine_account) {
2399                 ADS_STATUS ads_status;
2400                 ads_status = libnet_unjoin_connect_ads(mem_ctx, r);
2401                 if (ADS_ERR_OK(ads_status)) {
2402                         /* dirty hack */
2403                         r->out.dns_domain_name = 
2404                                 talloc_strdup(mem_ctx,
2405                                               r->in.ads->server.realm);
2406                         ads_status = 
2407                                 libnet_unjoin_remove_machine_acct(mem_ctx, r);
2408                 }
2409                 if (!ADS_ERR_OK(ads_status)) {
2410                         libnet_unjoin_set_error_string(mem_ctx, r,
2411                                 "failed to remove machine account from AD: %s",
2412                                 ads_errstr(ads_status));
2413                 } else {
2414                         r->out.deleted_machine_account = true;
2415                         W_ERROR_HAVE_NO_MEMORY(r->out.dns_domain_name);
2416                         libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2417                         return WERR_OK;
2418                 }
2419         }
2420 #endif /* HAVE_ADS */
2421
2422         /* The WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE flag really means 
2423            "disable".  */
2424         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE) {
2425                 status = libnet_join_unjoindomain_rpc(mem_ctx, r);
2426                 if (!NT_STATUS_IS_OK(status)) {
2427                         libnet_unjoin_set_error_string(mem_ctx, r,
2428                                 "failed to disable machine account via rpc: %s",
2429                                 get_friendly_nt_error_msg(status));
2430                         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER)) {
2431                                 return WERR_SETUP_NOT_JOINED;
2432                         }
2433                         return ntstatus_to_werror(status);
2434                 }
2435
2436                 r->out.disabled_machine_account = true;
2437         }
2438
2439         /* If disable succeeded or was not requested at all, we 
2440            should be getting rid of our end of things */
2441
2442         libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2443
2444         return WERR_OK;
2445 }
2446
2447 /****************************************************************
2448 ****************************************************************/
2449
2450 static WERROR libnet_unjoin_pre_processing(TALLOC_CTX *mem_ctx,
2451                                            struct libnet_UnjoinCtx *r)
2452 {
2453         if (!r->in.domain_name) {
2454                 libnet_unjoin_set_error_string(mem_ctx, r,
2455                         "No domain name defined");
2456                 return WERR_INVALID_PARAM;
2457         }
2458
2459         if (!libnet_parse_domain_dc(mem_ctx, r->in.domain_name,
2460                                     &r->in.domain_name,
2461                                     &r->in.dc_name)) {
2462                 libnet_unjoin_set_error_string(mem_ctx, r,
2463                         "Failed to parse domain name");
2464                 return WERR_INVALID_PARAM;
2465         }
2466
2467         if (IS_DC) {
2468                 return WERR_SETUP_DOMAIN_CONTROLLER;
2469         }
2470
2471         if (!r->in.admin_domain) {
2472                 char *admin_domain = NULL;
2473                 char *admin_account = NULL;
2474                 split_domain_user(mem_ctx,
2475                                   r->in.admin_account,
2476                                   &admin_domain,
2477                                   &admin_account);
2478                 r->in.admin_domain = admin_domain;
2479                 r->in.admin_account = admin_account;
2480         }
2481
2482         if (!secrets_init()) {
2483                 libnet_unjoin_set_error_string(mem_ctx, r,
2484                         "Unable to open secrets database");
2485                 return WERR_CAN_NOT_COMPLETE;
2486         }
2487
2488         return WERR_OK;
2489 }
2490
2491 /****************************************************************
2492 ****************************************************************/
2493
2494 static WERROR libnet_unjoin_post_processing(TALLOC_CTX *mem_ctx,
2495                                             struct libnet_UnjoinCtx *r)
2496 {
2497         saf_delete(r->out.netbios_domain_name);
2498         saf_delete(r->out.dns_domain_name);
2499
2500         return libnet_unjoin_config(r);
2501 }
2502
2503 /****************************************************************
2504 ****************************************************************/
2505
2506 WERROR libnet_Unjoin(TALLOC_CTX *mem_ctx,
2507                      struct libnet_UnjoinCtx *r)
2508 {
2509         WERROR werr;
2510
2511         if (r->in.debug) {
2512                 LIBNET_UNJOIN_IN_DUMP_CTX(mem_ctx, r);
2513         }
2514
2515         werr = libnet_unjoin_pre_processing(mem_ctx, r);
2516         if (!W_ERROR_IS_OK(werr)) {
2517                 goto done;
2518         }
2519
2520         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
2521                 werr = libnet_DomainUnjoin(mem_ctx, r);
2522                 if (!W_ERROR_IS_OK(werr)) {
2523                         libnet_unjoin_config(r);
2524                         goto done;
2525                 }
2526         }
2527
2528         werr = libnet_unjoin_post_processing(mem_ctx, r);
2529         if (!W_ERROR_IS_OK(werr)) {
2530                 goto done;
2531         }
2532
2533  done:
2534         r->out.result = werr;
2535
2536         if (r->in.debug) {
2537                 LIBNET_UNJOIN_OUT_DUMP_CTX(mem_ctx, r);
2538         }
2539
2540         return werr;
2541 }