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