s3:libnet_join: move kerberos_secrets_store_des_salt() out of libnet_join_derive_salt...
[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(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         if (r->out.krb5_salt != NULL) {
968                 bool ok;
969
970                 ok = kerberos_secrets_store_des_salt(r->out.krb5_salt);
971                 if (!ok) {
972                         libnet_join_set_error_string(mem_ctx, r,
973                                 "failed to store krb5_salt");
974                         return ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
975                 }
976         }
977
978         if (!libnet_join_create_keytab(mem_ctx, r)) {
979                 libnet_join_set_error_string(mem_ctx, r,
980                         "failed to create kerberos keytab");
981                 return ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
982         }
983
984         return ADS_SUCCESS;
985 }
986 #endif /* HAVE_ADS */
987
988 /****************************************************************
989  Store the machine password and domain SID
990 ****************************************************************/
991
992 static bool libnet_join_joindomain_store_secrets(TALLOC_CTX *mem_ctx,
993                                                  struct libnet_JoinCtx *r)
994 {
995         if (!secrets_store_domain_sid(r->out.netbios_domain_name,
996                                       r->out.domain_sid))
997         {
998                 DEBUG(1,("Failed to save domain sid\n"));
999                 return false;
1000         }
1001
1002         if (!secrets_store_machine_password(r->in.machine_password,
1003                                             r->out.netbios_domain_name,
1004                                             r->in.secure_channel_type))
1005         {
1006                 DEBUG(1,("Failed to save machine password\n"));
1007                 return false;
1008         }
1009
1010         return true;
1011 }
1012
1013 /****************************************************************
1014  Connect dc's IPC$ share
1015 ****************************************************************/
1016
1017 static NTSTATUS libnet_join_connect_dc_ipc(const char *dc,
1018                                            const char *user,
1019                                            const char *domain,
1020                                            const char *pass,
1021                                            bool use_kerberos,
1022                                            struct cli_state **cli)
1023 {
1024         int flags = 0;
1025
1026         if (use_kerberos) {
1027                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
1028         }
1029
1030         if (use_kerberos && pass) {
1031                 flags |= CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;
1032         }
1033
1034         return cli_full_connection(cli, NULL,
1035                                    dc,
1036                                    NULL, 0,
1037                                    "IPC$", "IPC",
1038                                    user,
1039                                    domain,
1040                                    pass,
1041                                    flags,
1042                                    SMB_SIGNING_IPC_DEFAULT);
1043 }
1044
1045 /****************************************************************
1046  Lookup domain dc's info
1047 ****************************************************************/
1048
1049 static NTSTATUS libnet_join_lookup_dc_rpc(TALLOC_CTX *mem_ctx,
1050                                           struct libnet_JoinCtx *r,
1051                                           struct cli_state **cli)
1052 {
1053         struct rpc_pipe_client *pipe_hnd = NULL;
1054         struct policy_handle lsa_pol;
1055         NTSTATUS status, result;
1056         union lsa_PolicyInformation *info = NULL;
1057         struct dcerpc_binding_handle *b;
1058
1059         status = libnet_join_connect_dc_ipc(r->in.dc_name,
1060                                             r->in.admin_account,
1061                                             r->in.admin_domain,
1062                                             r->in.admin_password,
1063                                             r->in.use_kerberos,
1064                                             cli);
1065         if (!NT_STATUS_IS_OK(status)) {
1066                 goto done;
1067         }
1068
1069         status = cli_rpc_pipe_open_noauth(*cli, &ndr_table_lsarpc,
1070                                           &pipe_hnd);
1071         if (!NT_STATUS_IS_OK(status)) {
1072                 DEBUG(0,("Error connecting to LSA pipe. Error was %s\n",
1073                         nt_errstr(status)));
1074                 goto done;
1075         }
1076
1077         b = pipe_hnd->binding_handle;
1078
1079         status = rpccli_lsa_open_policy(pipe_hnd, mem_ctx, true,
1080                                         SEC_FLAG_MAXIMUM_ALLOWED, &lsa_pol);
1081         if (!NT_STATUS_IS_OK(status)) {
1082                 goto done;
1083         }
1084
1085         status = dcerpc_lsa_QueryInfoPolicy2(b, mem_ctx,
1086                                              &lsa_pol,
1087                                              LSA_POLICY_INFO_DNS,
1088                                              &info,
1089                                              &result);
1090         if (NT_STATUS_IS_OK(status) && NT_STATUS_IS_OK(result)) {
1091                 r->out.domain_is_ad = true;
1092                 r->out.netbios_domain_name = info->dns.name.string;
1093                 r->out.dns_domain_name = info->dns.dns_domain.string;
1094                 r->out.forest_name = info->dns.dns_forest.string;
1095                 r->out.domain_guid = info->dns.domain_guid;
1096                 r->out.domain_sid = dom_sid_dup(mem_ctx, info->dns.sid);
1097                 NT_STATUS_HAVE_NO_MEMORY(r->out.domain_sid);
1098         }
1099
1100         if (!NT_STATUS_IS_OK(status)) {
1101                 status = dcerpc_lsa_QueryInfoPolicy(b, mem_ctx,
1102                                                     &lsa_pol,
1103                                                     LSA_POLICY_INFO_ACCOUNT_DOMAIN,
1104                                                     &info,
1105                                                     &result);
1106                 if (!NT_STATUS_IS_OK(status)) {
1107                         goto done;
1108                 }
1109                 if (!NT_STATUS_IS_OK(result)) {
1110                         status = result;
1111                         goto done;
1112                 }
1113
1114                 r->out.netbios_domain_name = info->account_domain.name.string;
1115                 r->out.domain_sid = dom_sid_dup(mem_ctx, info->account_domain.sid);
1116                 NT_STATUS_HAVE_NO_MEMORY(r->out.domain_sid);
1117         }
1118
1119         dcerpc_lsa_Close(b, mem_ctx, &lsa_pol, &result);
1120         TALLOC_FREE(pipe_hnd);
1121
1122  done:
1123         return status;
1124 }
1125
1126 /****************************************************************
1127  Do the domain join unsecure
1128 ****************************************************************/
1129
1130 static NTSTATUS libnet_join_joindomain_rpc_unsecure(TALLOC_CTX *mem_ctx,
1131                                                     struct libnet_JoinCtx *r,
1132                                                     struct cli_state *cli)
1133 {
1134         TALLOC_CTX *frame = talloc_stackframe();
1135         struct rpc_pipe_client *netlogon_pipe = NULL;
1136         struct netlogon_creds_cli_context *netlogon_creds = NULL;
1137         struct samr_Password current_nt_hash;
1138         NTSTATUS status;
1139
1140         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_netlogon,
1141                                           &netlogon_pipe);
1142         if (!NT_STATUS_IS_OK(status)) {
1143                 TALLOC_FREE(frame);
1144                 return status;
1145         }
1146
1147         if (!r->in.machine_password) {
1148                 int security = r->in.ads ? SEC_ADS : SEC_DOMAIN;
1149
1150                 r->in.machine_password = trust_pw_new_value(mem_ctx,
1151                                                 r->in.secure_channel_type,
1152                                                 security);
1153                 if (r->in.machine_password == NULL) {
1154                         TALLOC_FREE(frame);
1155                         return NT_STATUS_NO_MEMORY;
1156                 }
1157         }
1158
1159         /* according to WKSSVC_JOIN_FLAGS_MACHINE_PWD_PASSED */
1160         E_md4hash(r->in.admin_password, current_nt_hash.hash);
1161
1162         status = rpccli_create_netlogon_creds(netlogon_pipe->desthost,
1163                                               r->in.domain_name,
1164                                               r->out.account_name,
1165                                               r->in.secure_channel_type,
1166                                               r->in.msg_ctx,
1167                                               frame,
1168                                               &netlogon_creds);
1169         if (!NT_STATUS_IS_OK(status)) {
1170                 TALLOC_FREE(frame);
1171                 return status;
1172         }
1173
1174         status = rpccli_setup_netlogon_creds(cli, NCACN_NP,
1175                                              netlogon_creds,
1176                                              true, /* force_reauth */
1177                                              current_nt_hash,
1178                                              NULL); /* previous_nt_hash */
1179         if (!NT_STATUS_IS_OK(status)) {
1180                 TALLOC_FREE(frame);
1181                 return status;
1182         }
1183
1184         status = netlogon_creds_cli_ServerPasswordSet(netlogon_creds,
1185                                                       netlogon_pipe->binding_handle,
1186                                                       r->in.machine_password,
1187                                                       NULL); /* new_version */
1188         if (!NT_STATUS_IS_OK(status)) {
1189                 TALLOC_FREE(frame);
1190                 return status;
1191         }
1192
1193         TALLOC_FREE(frame);
1194         return NT_STATUS_OK;
1195 }
1196
1197 /****************************************************************
1198  Do the domain join
1199 ****************************************************************/
1200
1201 static NTSTATUS libnet_join_joindomain_rpc(TALLOC_CTX *mem_ctx,
1202                                            struct libnet_JoinCtx *r,
1203                                            struct cli_state *cli)
1204 {
1205         struct rpc_pipe_client *pipe_hnd = NULL;
1206         struct policy_handle sam_pol, domain_pol, user_pol;
1207         NTSTATUS status = NT_STATUS_UNSUCCESSFUL, result;
1208         char *acct_name;
1209         struct lsa_String lsa_acct_name;
1210         uint32_t user_rid;
1211         uint32_t acct_flags = ACB_WSTRUST;
1212         struct samr_Ids user_rids;
1213         struct samr_Ids name_types;
1214         union samr_UserInfo user_info;
1215         struct dcerpc_binding_handle *b = NULL;
1216         unsigned int old_timeout = 0;
1217
1218         DATA_BLOB session_key = data_blob_null;
1219         struct samr_CryptPassword crypt_pwd;
1220         struct samr_CryptPasswordEx crypt_pwd_ex;
1221
1222         ZERO_STRUCT(sam_pol);
1223         ZERO_STRUCT(domain_pol);
1224         ZERO_STRUCT(user_pol);
1225
1226         switch (r->in.secure_channel_type) {
1227         case SEC_CHAN_WKSTA:
1228                 acct_flags = ACB_WSTRUST;
1229                 break;
1230         case SEC_CHAN_BDC:
1231                 acct_flags = ACB_SVRTRUST;
1232                 break;
1233         default:
1234                 return NT_STATUS_INVALID_PARAMETER;
1235         }
1236
1237         if (!r->in.machine_password) {
1238                 int security = r->in.ads ? SEC_ADS : SEC_DOMAIN;
1239
1240                 r->in.machine_password = trust_pw_new_value(mem_ctx,
1241                                                 r->in.secure_channel_type,
1242                                                 security);
1243                 NT_STATUS_HAVE_NO_MEMORY(r->in.machine_password);
1244         }
1245
1246         /* Open the domain */
1247
1248         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_samr,
1249                                           &pipe_hnd);
1250         if (!NT_STATUS_IS_OK(status)) {
1251                 DEBUG(0,("Error connecting to SAM pipe. Error was %s\n",
1252                         nt_errstr(status)));
1253                 goto done;
1254         }
1255
1256         b = pipe_hnd->binding_handle;
1257
1258         status = cli_get_session_key(mem_ctx, pipe_hnd, &session_key);
1259         if (!NT_STATUS_IS_OK(status)) {
1260                 DEBUG(0,("Error getting session_key of SAM pipe. Error was %s\n",
1261                         nt_errstr(status)));
1262                 goto done;
1263         }
1264
1265         status = dcerpc_samr_Connect2(b, mem_ctx,
1266                                       pipe_hnd->desthost,
1267                                       SAMR_ACCESS_ENUM_DOMAINS
1268                                       | SAMR_ACCESS_LOOKUP_DOMAIN,
1269                                       &sam_pol,
1270                                       &result);
1271         if (!NT_STATUS_IS_OK(status)) {
1272                 goto done;
1273         }
1274         if (!NT_STATUS_IS_OK(result)) {
1275                 status = result;
1276                 goto done;
1277         }
1278
1279         status = dcerpc_samr_OpenDomain(b, mem_ctx,
1280                                         &sam_pol,
1281                                         SAMR_DOMAIN_ACCESS_LOOKUP_INFO_1
1282                                         | SAMR_DOMAIN_ACCESS_CREATE_USER
1283                                         | SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
1284                                         r->out.domain_sid,
1285                                         &domain_pol,
1286                                         &result);
1287         if (!NT_STATUS_IS_OK(status)) {
1288                 goto done;
1289         }
1290         if (!NT_STATUS_IS_OK(result)) {
1291                 status = result;
1292                 goto done;
1293         }
1294
1295         /* Create domain user */
1296
1297         acct_name = talloc_asprintf(mem_ctx, "%s$", r->in.machine_name);
1298         if (!strlower_m(acct_name)) {
1299                 status = NT_STATUS_INVALID_PARAMETER;
1300                 goto done;
1301         }
1302
1303         init_lsa_String(&lsa_acct_name, acct_name);
1304
1305         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE) {
1306                 uint32_t access_desired =
1307                         SEC_GENERIC_READ | SEC_GENERIC_WRITE | SEC_GENERIC_EXECUTE |
1308                         SEC_STD_WRITE_DAC | SEC_STD_DELETE |
1309                         SAMR_USER_ACCESS_SET_PASSWORD |
1310                         SAMR_USER_ACCESS_GET_ATTRIBUTES |
1311                         SAMR_USER_ACCESS_SET_ATTRIBUTES;
1312                 uint32_t access_granted = 0;
1313
1314                 DEBUG(10,("Creating account with desired access mask: %d\n",
1315                         access_desired));
1316
1317                 status = dcerpc_samr_CreateUser2(b, mem_ctx,
1318                                                  &domain_pol,
1319                                                  &lsa_acct_name,
1320                                                  acct_flags,
1321                                                  access_desired,
1322                                                  &user_pol,
1323                                                  &access_granted,
1324                                                  &user_rid,
1325                                                  &result);
1326                 if (!NT_STATUS_IS_OK(status)) {
1327                         goto done;
1328                 }
1329
1330                 status = result;
1331                 if (!NT_STATUS_IS_OK(status) &&
1332                     !NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
1333
1334                         DEBUG(10,("Creation of workstation account failed: %s\n",
1335                                 nt_errstr(status)));
1336
1337                         /* If NT_STATUS_ACCESS_DENIED then we have a valid
1338                            username/password combo but the user does not have
1339                            administrator access. */
1340
1341                         if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
1342                                 libnet_join_set_error_string(mem_ctx, r,
1343                                         "User specified does not have "
1344                                         "administrator privileges");
1345                         }
1346
1347                         goto done;
1348                 }
1349
1350                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
1351                         if (!(r->in.join_flags &
1352                               WKSSVC_JOIN_FLAGS_DOMAIN_JOIN_IF_JOINED)) {
1353                                 goto done;
1354                         }
1355                 }
1356
1357                 /* We *must* do this.... don't ask... */
1358
1359                 if (NT_STATUS_IS_OK(status)) {
1360                         dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1361                 }
1362         }
1363
1364         status = dcerpc_samr_LookupNames(b, mem_ctx,
1365                                          &domain_pol,
1366                                          1,
1367                                          &lsa_acct_name,
1368                                          &user_rids,
1369                                          &name_types,
1370                                          &result);
1371         if (!NT_STATUS_IS_OK(status)) {
1372                 goto done;
1373         }
1374         if (!NT_STATUS_IS_OK(result)) {
1375                 status = result;
1376                 goto done;
1377         }
1378         if (user_rids.count != 1) {
1379                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
1380                 goto done;
1381         }
1382         if (name_types.count != 1) {
1383                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
1384                 goto done;
1385         }
1386
1387         if (name_types.ids[0] != SID_NAME_USER) {
1388                 DEBUG(0,("%s is not a user account (type=%d)\n",
1389                         acct_name, name_types.ids[0]));
1390                 status = NT_STATUS_INVALID_WORKSTATION;
1391                 goto done;
1392         }
1393
1394         user_rid = user_rids.ids[0];
1395
1396         /* Open handle on user */
1397
1398         status = dcerpc_samr_OpenUser(b, mem_ctx,
1399                                       &domain_pol,
1400                                       SEC_FLAG_MAXIMUM_ALLOWED,
1401                                       user_rid,
1402                                       &user_pol,
1403                                       &result);
1404         if (!NT_STATUS_IS_OK(status)) {
1405                 goto done;
1406         }
1407         if (!NT_STATUS_IS_OK(result)) {
1408                 status = result;
1409                 goto done;
1410         }
1411
1412         /* Fill in the additional account flags now */
1413
1414         acct_flags |= ACB_PWNOEXP;
1415
1416         /* Set account flags on machine account */
1417         ZERO_STRUCT(user_info.info16);
1418         user_info.info16.acct_flags = acct_flags;
1419
1420         status = dcerpc_samr_SetUserInfo2(b, mem_ctx,
1421                                           &user_pol,
1422                                           UserControlInformation,
1423                                           &user_info,
1424                                           &result);
1425         if (!NT_STATUS_IS_OK(status)) {
1426                 dcerpc_samr_DeleteUser(b, mem_ctx,
1427                                        &user_pol,
1428                                        &result);
1429
1430                 libnet_join_set_error_string(mem_ctx, r,
1431                         "Failed to set account flags for machine account (%s)\n",
1432                         nt_errstr(status));
1433                 goto done;
1434         }
1435
1436         if (!NT_STATUS_IS_OK(result)) {
1437                 status = result;
1438
1439                 dcerpc_samr_DeleteUser(b, mem_ctx,
1440                                        &user_pol,
1441                                        &result);
1442
1443                 libnet_join_set_error_string(mem_ctx, r,
1444                         "Failed to set account flags for machine account (%s)\n",
1445                         nt_errstr(status));
1446                 goto done;
1447         }
1448
1449         /* Set password on machine account - first try level 26 */
1450
1451         /*
1452          * increase the timeout as password filter modules on the DC
1453          * might delay the operation for a significant amount of time
1454          */
1455         old_timeout = rpccli_set_timeout(pipe_hnd, 600000);
1456
1457         init_samr_CryptPasswordEx(r->in.machine_password,
1458                                   &session_key,
1459                                   &crypt_pwd_ex);
1460
1461         user_info.info26.password = crypt_pwd_ex;
1462         user_info.info26.password_expired = PASS_DONT_CHANGE_AT_NEXT_LOGON;
1463
1464         status = dcerpc_samr_SetUserInfo2(b, mem_ctx,
1465                                           &user_pol,
1466                                           UserInternal5InformationNew,
1467                                           &user_info,
1468                                           &result);
1469
1470         if (NT_STATUS_EQUAL(status, NT_STATUS_RPC_ENUM_VALUE_OUT_OF_RANGE)) {
1471
1472                 /* retry with level 24 */
1473
1474                 init_samr_CryptPassword(r->in.machine_password,
1475                                         &session_key,
1476                                         &crypt_pwd);
1477
1478                 user_info.info24.password = crypt_pwd;
1479                 user_info.info24.password_expired = PASS_DONT_CHANGE_AT_NEXT_LOGON;
1480
1481                 status = dcerpc_samr_SetUserInfo2(b, mem_ctx,
1482                                                   &user_pol,
1483                                                   UserInternal5Information,
1484                                                   &user_info,
1485                                                   &result);
1486         }
1487
1488         old_timeout = rpccli_set_timeout(pipe_hnd, old_timeout);
1489
1490         if (!NT_STATUS_IS_OK(status)) {
1491
1492                 dcerpc_samr_DeleteUser(b, mem_ctx,
1493                                        &user_pol,
1494                                        &result);
1495
1496                 libnet_join_set_error_string(mem_ctx, r,
1497                         "Failed to set password for machine account (%s)\n",
1498                         nt_errstr(status));
1499                 goto done;
1500         }
1501         if (!NT_STATUS_IS_OK(result)) {
1502                 status = result;
1503
1504                 dcerpc_samr_DeleteUser(b, mem_ctx,
1505                                        &user_pol,
1506                                        &result);
1507
1508                 libnet_join_set_error_string(mem_ctx, r,
1509                         "Failed to set password for machine account (%s)\n",
1510                         nt_errstr(status));
1511                 goto done;
1512         }
1513
1514         status = NT_STATUS_OK;
1515
1516  done:
1517         if (!pipe_hnd) {
1518                 return status;
1519         }
1520
1521         data_blob_clear_free(&session_key);
1522
1523         if (is_valid_policy_hnd(&sam_pol)) {
1524                 dcerpc_samr_Close(b, mem_ctx, &sam_pol, &result);
1525         }
1526         if (is_valid_policy_hnd(&domain_pol)) {
1527                 dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
1528         }
1529         if (is_valid_policy_hnd(&user_pol)) {
1530                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1531         }
1532         TALLOC_FREE(pipe_hnd);
1533
1534         return status;
1535 }
1536
1537 /****************************************************************
1538 ****************************************************************/
1539
1540 NTSTATUS libnet_join_ok(struct messaging_context *msg_ctx,
1541                         const char *netbios_domain_name,
1542                         const char *dc_name,
1543                         const bool use_kerberos)
1544 {
1545         TALLOC_CTX *frame = talloc_stackframe();
1546         struct cli_state *cli = NULL;
1547         struct rpc_pipe_client *netlogon_pipe = NULL;
1548         struct cli_credentials *cli_creds = NULL;
1549         struct netlogon_creds_cli_context *netlogon_creds = NULL;
1550         struct netlogon_creds_CredentialState *creds = NULL;
1551         uint32_t netlogon_flags = 0;
1552         NTSTATUS status;
1553         int flags = 0;
1554
1555         if (!dc_name) {
1556                 TALLOC_FREE(frame);
1557                 return NT_STATUS_INVALID_PARAMETER;
1558         }
1559
1560         if (!secrets_init()) {
1561                 TALLOC_FREE(frame);
1562                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1563         }
1564
1565         status = pdb_get_trust_credentials(netbios_domain_name, NULL,
1566                                            frame, &cli_creds);
1567         if (!NT_STATUS_IS_OK(status)) {
1568                 TALLOC_FREE(frame);
1569                 return status;
1570         }
1571
1572         /* we don't want any old password */
1573         cli_credentials_set_old_password(cli_creds, NULL, CRED_SPECIFIED);
1574
1575         if (use_kerberos) {
1576                 cli_credentials_set_kerberos_state(cli_creds,
1577                                 CRED_MUST_USE_KERBEROS);
1578         }
1579
1580         status = cli_full_connection_creds(&cli, NULL,
1581                                            dc_name,
1582                                            NULL, 0,
1583                                            "IPC$", "IPC",
1584                                            cli_creds,
1585                                            flags,
1586                                            SMB_SIGNING_IPC_DEFAULT);
1587
1588         if (!NT_STATUS_IS_OK(status)) {
1589                 status = cli_full_connection(&cli, NULL,
1590                                              dc_name,
1591                                              NULL, 0,
1592                                              "IPC$", "IPC",
1593                                              "",
1594                                              NULL,
1595                                              "",
1596                                              0,
1597                                              SMB_SIGNING_IPC_DEFAULT);
1598         }
1599
1600         if (!NT_STATUS_IS_OK(status)) {
1601                 TALLOC_FREE(frame);
1602                 return status;
1603         }
1604
1605         status = rpccli_create_netlogon_creds_with_creds(cli_creds,
1606                                                          dc_name,
1607                                                          msg_ctx,
1608                                                          frame,
1609                                                          &netlogon_creds);
1610         if (!NT_STATUS_IS_OK(status)) {
1611                 cli_shutdown(cli);
1612                 TALLOC_FREE(frame);
1613                 return status;
1614         }
1615
1616         status = rpccli_setup_netlogon_creds_with_creds(cli, NCACN_NP,
1617                                                         netlogon_creds,
1618                                                         true, /* force_reauth */
1619                                                         cli_creds);
1620         if (!NT_STATUS_IS_OK(status)) {
1621                 DEBUG(0,("connect_to_domain_password_server: "
1622                          "unable to open the domain client session to "
1623                          "machine %s. Flags[0x%08X] Error was : %s.\n",
1624                          dc_name, (unsigned)netlogon_flags,
1625                          nt_errstr(status)));
1626                 cli_shutdown(cli);
1627                 TALLOC_FREE(frame);
1628                 return status;
1629         }
1630
1631         status = netlogon_creds_cli_get(netlogon_creds,
1632                                         talloc_tos(),
1633                                         &creds);
1634         if (!NT_STATUS_IS_OK(status)) {
1635                 cli_shutdown(cli);
1636                 TALLOC_FREE(frame);
1637                 return status;
1638         }
1639         netlogon_flags = creds->negotiate_flags;
1640         TALLOC_FREE(creds);
1641
1642         if (!(netlogon_flags & NETLOGON_NEG_AUTHENTICATED_RPC)) {
1643                 cli_shutdown(cli);
1644                 TALLOC_FREE(frame);
1645                 return NT_STATUS_OK;
1646         }
1647
1648         status = cli_rpc_pipe_open_schannel_with_creds(
1649                 cli, &ndr_table_netlogon, NCACN_NP,
1650                 cli_creds,
1651                 netlogon_creds, &netlogon_pipe);
1652
1653         TALLOC_FREE(netlogon_pipe);
1654
1655         if (!NT_STATUS_IS_OK(status)) {
1656                 DEBUG(0,("libnet_join_ok: failed to open schannel session "
1657                         "on netlogon pipe to server %s for domain %s. "
1658                         "Error was %s\n",
1659                         smbXcli_conn_remote_name(cli->conn),
1660                         netbios_domain_name, nt_errstr(status)));
1661                 cli_shutdown(cli);
1662                 TALLOC_FREE(frame);
1663                 return status;
1664         }
1665
1666         cli_shutdown(cli);
1667         TALLOC_FREE(frame);
1668         return NT_STATUS_OK;
1669 }
1670
1671 /****************************************************************
1672 ****************************************************************/
1673
1674 static WERROR libnet_join_post_verify(TALLOC_CTX *mem_ctx,
1675                                       struct libnet_JoinCtx *r)
1676 {
1677         NTSTATUS status;
1678
1679         status = libnet_join_ok(r->in.msg_ctx,
1680                                 r->out.netbios_domain_name,
1681                                 r->in.dc_name,
1682                                 r->in.use_kerberos);
1683         if (!NT_STATUS_IS_OK(status)) {
1684                 libnet_join_set_error_string(mem_ctx, r,
1685                         "failed to verify domain membership after joining: %s",
1686                         get_friendly_nt_error_msg(status));
1687                 return WERR_NERR_SETUPNOTJOINED;
1688         }
1689
1690         return WERR_OK;
1691 }
1692
1693 /****************************************************************
1694 ****************************************************************/
1695
1696 static bool libnet_join_unjoindomain_remove_secrets(TALLOC_CTX *mem_ctx,
1697                                                     struct libnet_UnjoinCtx *r)
1698 {
1699         if (!secrets_delete_machine_password_ex(lp_workgroup())) {
1700                 return false;
1701         }
1702
1703         if (!secrets_delete_domain_sid(lp_workgroup())) {
1704                 return false;
1705         }
1706
1707         return true;
1708 }
1709
1710 /****************************************************************
1711 ****************************************************************/
1712
1713 static NTSTATUS libnet_join_unjoindomain_rpc(TALLOC_CTX *mem_ctx,
1714                                              struct libnet_UnjoinCtx *r)
1715 {
1716         struct cli_state *cli = NULL;
1717         struct rpc_pipe_client *pipe_hnd = NULL;
1718         struct policy_handle sam_pol, domain_pol, user_pol;
1719         NTSTATUS status = NT_STATUS_UNSUCCESSFUL, result;
1720         char *acct_name;
1721         uint32_t user_rid;
1722         struct lsa_String lsa_acct_name;
1723         struct samr_Ids user_rids;
1724         struct samr_Ids name_types;
1725         union samr_UserInfo *info = NULL;
1726         struct dcerpc_binding_handle *b = NULL;
1727
1728         ZERO_STRUCT(sam_pol);
1729         ZERO_STRUCT(domain_pol);
1730         ZERO_STRUCT(user_pol);
1731
1732         status = libnet_join_connect_dc_ipc(r->in.dc_name,
1733                                             r->in.admin_account,
1734                                             r->in.admin_domain,
1735                                             r->in.admin_password,
1736                                             r->in.use_kerberos,
1737                                             &cli);
1738         if (!NT_STATUS_IS_OK(status)) {
1739                 goto done;
1740         }
1741
1742         /* Open the domain */
1743
1744         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_samr,
1745                                           &pipe_hnd);
1746         if (!NT_STATUS_IS_OK(status)) {
1747                 DEBUG(0,("Error connecting to SAM pipe. Error was %s\n",
1748                         nt_errstr(status)));
1749                 goto done;
1750         }
1751
1752         b = pipe_hnd->binding_handle;
1753
1754         status = dcerpc_samr_Connect2(b, mem_ctx,
1755                                       pipe_hnd->desthost,
1756                                       SEC_FLAG_MAXIMUM_ALLOWED,
1757                                       &sam_pol,
1758                                       &result);
1759         if (!NT_STATUS_IS_OK(status)) {
1760                 goto done;
1761         }
1762         if (!NT_STATUS_IS_OK(result)) {
1763                 status = result;
1764                 goto done;
1765         }
1766
1767         status = dcerpc_samr_OpenDomain(b, mem_ctx,
1768                                         &sam_pol,
1769                                         SEC_FLAG_MAXIMUM_ALLOWED,
1770                                         r->in.domain_sid,
1771                                         &domain_pol,
1772                                         &result);
1773         if (!NT_STATUS_IS_OK(status)) {
1774                 goto done;
1775         }
1776         if (!NT_STATUS_IS_OK(result)) {
1777                 status = result;
1778                 goto done;
1779         }
1780
1781         /* Create domain user */
1782
1783         acct_name = talloc_asprintf(mem_ctx, "%s$", r->in.machine_name);
1784         if (!strlower_m(acct_name)) {
1785                 status = NT_STATUS_INVALID_PARAMETER;
1786                 goto done;
1787         }
1788
1789         init_lsa_String(&lsa_acct_name, acct_name);
1790
1791         status = dcerpc_samr_LookupNames(b, mem_ctx,
1792                                          &domain_pol,
1793                                          1,
1794                                          &lsa_acct_name,
1795                                          &user_rids,
1796                                          &name_types,
1797                                          &result);
1798
1799         if (!NT_STATUS_IS_OK(status)) {
1800                 goto done;
1801         }
1802         if (!NT_STATUS_IS_OK(result)) {
1803                 status = result;
1804                 goto done;
1805         }
1806         if (user_rids.count != 1) {
1807                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
1808                 goto done;
1809         }
1810         if (name_types.count != 1) {
1811                 status = NT_STATUS_INVALID_NETWORK_RESPONSE;
1812                 goto done;
1813         }
1814
1815         if (name_types.ids[0] != SID_NAME_USER) {
1816                 DEBUG(0, ("%s is not a user account (type=%d)\n", acct_name,
1817                         name_types.ids[0]));
1818                 status = NT_STATUS_INVALID_WORKSTATION;
1819                 goto done;
1820         }
1821
1822         user_rid = user_rids.ids[0];
1823
1824         /* Open handle on user */
1825
1826         status = dcerpc_samr_OpenUser(b, mem_ctx,
1827                                       &domain_pol,
1828                                       SEC_FLAG_MAXIMUM_ALLOWED,
1829                                       user_rid,
1830                                       &user_pol,
1831                                       &result);
1832         if (!NT_STATUS_IS_OK(status)) {
1833                 goto done;
1834         }
1835         if (!NT_STATUS_IS_OK(result)) {
1836                 status = result;
1837                 goto done;
1838         }
1839
1840         /* Get user info */
1841
1842         status = dcerpc_samr_QueryUserInfo(b, mem_ctx,
1843                                            &user_pol,
1844                                            16,
1845                                            &info,
1846                                            &result);
1847         if (!NT_STATUS_IS_OK(status)) {
1848                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1849                 goto done;
1850         }
1851         if (!NT_STATUS_IS_OK(result)) {
1852                 status = result;
1853                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1854                 goto done;
1855         }
1856
1857         /* now disable and setuser info */
1858
1859         info->info16.acct_flags |= ACB_DISABLED;
1860
1861         status = dcerpc_samr_SetUserInfo(b, mem_ctx,
1862                                          &user_pol,
1863                                          16,
1864                                          info,
1865                                          &result);
1866         if (!NT_STATUS_IS_OK(status)) {
1867                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1868                 goto done;
1869         }
1870         if (!NT_STATUS_IS_OK(result)) {
1871                 status = result;
1872                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1873                 goto done;
1874         }
1875         status = result;
1876         dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1877
1878 done:
1879         if (pipe_hnd && b) {
1880                 if (is_valid_policy_hnd(&domain_pol)) {
1881                         dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
1882                 }
1883                 if (is_valid_policy_hnd(&sam_pol)) {
1884                         dcerpc_samr_Close(b, mem_ctx, &sam_pol, &result);
1885                 }
1886                 TALLOC_FREE(pipe_hnd);
1887         }
1888
1889         if (cli) {
1890                 cli_shutdown(cli);
1891         }
1892
1893         return status;
1894 }
1895
1896 /****************************************************************
1897 ****************************************************************/
1898
1899 static WERROR do_join_modify_vals_config(struct libnet_JoinCtx *r)
1900 {
1901         WERROR werr = WERR_OK;
1902         sbcErr err;
1903         struct smbconf_ctx *ctx;
1904
1905         err = smbconf_init_reg(r, &ctx, NULL);
1906         if (!SBC_ERROR_IS_OK(err)) {
1907                 werr = WERR_SERVICE_DOES_NOT_EXIST;
1908                 goto done;
1909         }
1910
1911         if (!(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE)) {
1912
1913                 err = smbconf_set_global_parameter(ctx, "security", "user");
1914                 if (!SBC_ERROR_IS_OK(err)) {
1915                         werr = WERR_SERVICE_DOES_NOT_EXIST;
1916                         goto done;
1917                 }
1918
1919                 err = smbconf_set_global_parameter(ctx, "workgroup",
1920                                                    r->in.domain_name);
1921                 if (!SBC_ERROR_IS_OK(err)) {
1922                         werr = WERR_SERVICE_DOES_NOT_EXIST;
1923                         goto done;
1924                 }
1925
1926                 smbconf_delete_global_parameter(ctx, "realm");
1927                 goto done;
1928         }
1929
1930         err = smbconf_set_global_parameter(ctx, "security", "domain");
1931         if (!SBC_ERROR_IS_OK(err)) {
1932                 werr = WERR_SERVICE_DOES_NOT_EXIST;
1933                 goto done;
1934         }
1935
1936         err = smbconf_set_global_parameter(ctx, "workgroup",
1937                                            r->out.netbios_domain_name);
1938         if (!SBC_ERROR_IS_OK(err)) {
1939                 werr = WERR_SERVICE_DOES_NOT_EXIST;
1940                 goto done;
1941         }
1942
1943         if (r->out.domain_is_ad) {
1944                 err = smbconf_set_global_parameter(ctx, "security", "ads");
1945                 if (!SBC_ERROR_IS_OK(err)) {
1946                         werr = WERR_SERVICE_DOES_NOT_EXIST;
1947                         goto done;
1948                 }
1949
1950                 err = smbconf_set_global_parameter(ctx, "realm",
1951                                                    r->out.dns_domain_name);
1952                 if (!SBC_ERROR_IS_OK(err)) {
1953                         werr = WERR_SERVICE_DOES_NOT_EXIST;
1954                         goto done;
1955                 }
1956         }
1957
1958  done:
1959         smbconf_shutdown(ctx);
1960         return werr;
1961 }
1962
1963 /****************************************************************
1964 ****************************************************************/
1965
1966 static WERROR do_unjoin_modify_vals_config(struct libnet_UnjoinCtx *r)
1967 {
1968         WERROR werr = WERR_OK;
1969         sbcErr err;
1970         struct smbconf_ctx *ctx;
1971
1972         err = smbconf_init_reg(r, &ctx, NULL);
1973         if (!SBC_ERROR_IS_OK(err)) {
1974                 werr = WERR_SERVICE_DOES_NOT_EXIST;
1975                 goto done;
1976         }
1977
1978         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1979
1980                 err = smbconf_set_global_parameter(ctx, "security", "user");
1981                 if (!SBC_ERROR_IS_OK(err)) {
1982                         werr = WERR_SERVICE_DOES_NOT_EXIST;
1983                         goto done;
1984                 }
1985
1986                 err = smbconf_delete_global_parameter(ctx, "workgroup");
1987                 if (!SBC_ERROR_IS_OK(err)) {
1988                         werr = WERR_SERVICE_DOES_NOT_EXIST;
1989                         goto done;
1990                 }
1991
1992                 smbconf_delete_global_parameter(ctx, "realm");
1993         }
1994
1995  done:
1996         smbconf_shutdown(ctx);
1997         return werr;
1998 }
1999
2000 /****************************************************************
2001 ****************************************************************/
2002
2003 static WERROR do_JoinConfig(struct libnet_JoinCtx *r)
2004 {
2005         WERROR werr;
2006
2007         if (!W_ERROR_IS_OK(r->out.result)) {
2008                 return r->out.result;
2009         }
2010
2011         if (!r->in.modify_config) {
2012                 return WERR_OK;
2013         }
2014
2015         werr = do_join_modify_vals_config(r);
2016         if (!W_ERROR_IS_OK(werr)) {
2017                 return werr;
2018         }
2019
2020         lp_load_global(get_dyn_CONFIGFILE());
2021
2022         r->out.modified_config = true;
2023         r->out.result = werr;
2024
2025         return werr;
2026 }
2027
2028 /****************************************************************
2029 ****************************************************************/
2030
2031 static WERROR libnet_unjoin_config(struct libnet_UnjoinCtx *r)
2032 {
2033         WERROR werr;
2034
2035         if (!W_ERROR_IS_OK(r->out.result)) {
2036                 return r->out.result;
2037         }
2038
2039         if (!r->in.modify_config) {
2040                 return WERR_OK;
2041         }
2042
2043         werr = do_unjoin_modify_vals_config(r);
2044         if (!W_ERROR_IS_OK(werr)) {
2045                 return werr;
2046         }
2047
2048         lp_load_global(get_dyn_CONFIGFILE());
2049
2050         r->out.modified_config = true;
2051         r->out.result = werr;
2052
2053         return werr;
2054 }
2055
2056 /****************************************************************
2057 ****************************************************************/
2058
2059 static bool libnet_parse_domain_dc(TALLOC_CTX *mem_ctx,
2060                                    const char *domain_str,
2061                                    const char **domain_p,
2062                                    const char **dc_p)
2063 {
2064         char *domain = NULL;
2065         char *dc = NULL;
2066         const char *p = NULL;
2067
2068         if (!domain_str || !domain_p || !dc_p) {
2069                 return false;
2070         }
2071
2072         p = strchr_m(domain_str, '\\');
2073
2074         if (p != NULL) {
2075                 domain = talloc_strndup(mem_ctx, domain_str,
2076                                          PTR_DIFF(p, domain_str));
2077                 dc = talloc_strdup(mem_ctx, p+1);
2078                 if (!dc) {
2079                         return false;
2080                 }
2081         } else {
2082                 domain = talloc_strdup(mem_ctx, domain_str);
2083                 dc = NULL;
2084         }
2085         if (!domain) {
2086                 return false;
2087         }
2088
2089         *domain_p = domain;
2090
2091         if (!*dc_p && dc) {
2092                 *dc_p = dc;
2093         }
2094
2095         return true;
2096 }
2097
2098 /****************************************************************
2099 ****************************************************************/
2100
2101 static WERROR libnet_join_pre_processing(TALLOC_CTX *mem_ctx,
2102                                          struct libnet_JoinCtx *r)
2103 {
2104         if (!r->in.domain_name) {
2105                 libnet_join_set_error_string(mem_ctx, r,
2106                         "No domain name defined");
2107                 return WERR_INVALID_PARAMETER;
2108         }
2109
2110         if (strlen(r->in.machine_name) > 15) {
2111                 libnet_join_set_error_string(mem_ctx, r,
2112                         "Our netbios name can be at most 15 chars long, "
2113                          "\"%s\" is %u chars long\n",
2114                          r->in.machine_name,
2115                          (unsigned int)strlen(r->in.machine_name));
2116                 return WERR_INVALID_PARAMETER;
2117         }
2118
2119         r->out.account_name = talloc_asprintf(mem_ctx, "%s$",
2120                                        r->in.machine_name);
2121         if (r->out.account_name == NULL) {
2122                 libnet_join_set_error_string(mem_ctx, r,
2123                         "Unable to construct r->out.account_name");
2124                 return WERR_NOT_ENOUGH_MEMORY;
2125         }
2126
2127         if (!libnet_parse_domain_dc(mem_ctx, r->in.domain_name,
2128                                     &r->in.domain_name,
2129                                     &r->in.dc_name)) {
2130                 libnet_join_set_error_string(mem_ctx, r,
2131                         "Failed to parse domain name");
2132                 return WERR_INVALID_PARAMETER;
2133         }
2134
2135         if (!r->in.admin_domain) {
2136                 char *admin_domain = NULL;
2137                 char *admin_account = NULL;
2138                 bool ok;
2139
2140                 ok = split_domain_user(mem_ctx,
2141                                        r->in.admin_account,
2142                                        &admin_domain,
2143                                        &admin_account);
2144                 if (!ok) {
2145                         return WERR_NOT_ENOUGH_MEMORY;
2146                 }
2147
2148                 if (admin_domain != NULL) {
2149                         r->in.admin_domain = admin_domain;
2150                 } else {
2151                         r->in.admin_domain = r->in.domain_name;
2152                 }
2153                 r->in.admin_account = admin_account;
2154         }
2155
2156         if (!secrets_init()) {
2157                 libnet_join_set_error_string(mem_ctx, r,
2158                         "Unable to open secrets database");
2159                 return WERR_CAN_NOT_COMPLETE;
2160         }
2161
2162         return WERR_OK;
2163 }
2164
2165 /****************************************************************
2166 ****************************************************************/
2167
2168 static void libnet_join_add_dom_rids_to_builtins(struct dom_sid *domain_sid)
2169 {
2170         NTSTATUS status;
2171
2172         /* Try adding dom admins to builtin\admins. Only log failures. */
2173         status = create_builtin_administrators(domain_sid);
2174         if (NT_STATUS_EQUAL(status, NT_STATUS_PROTOCOL_UNREACHABLE)) {
2175                 DEBUG(10,("Unable to auto-add domain administrators to "
2176                           "BUILTIN\\Administrators during join because "
2177                           "winbindd must be running.\n"));
2178         } else if (!NT_STATUS_IS_OK(status)) {
2179                 DEBUG(5, ("Failed to auto-add domain administrators to "
2180                           "BUILTIN\\Administrators during join: %s\n",
2181                           nt_errstr(status)));
2182         }
2183
2184         /* Try adding dom users to builtin\users. Only log failures. */
2185         status = create_builtin_users(domain_sid);
2186         if (NT_STATUS_EQUAL(status, NT_STATUS_PROTOCOL_UNREACHABLE)) {
2187                 DEBUG(10,("Unable to auto-add domain users to BUILTIN\\users "
2188                           "during join because winbindd must be running.\n"));
2189         } else if (!NT_STATUS_IS_OK(status)) {
2190                 DEBUG(5, ("Failed to auto-add domain administrators to "
2191                           "BUILTIN\\Administrators during join: %s\n",
2192                           nt_errstr(status)));
2193         }
2194 }
2195
2196 /****************************************************************
2197 ****************************************************************/
2198
2199 static WERROR libnet_join_post_processing(TALLOC_CTX *mem_ctx,
2200                                           struct libnet_JoinCtx *r)
2201 {
2202         WERROR werr;
2203
2204         if (!W_ERROR_IS_OK(r->out.result)) {
2205                 return r->out.result;
2206         }
2207
2208         werr = do_JoinConfig(r);
2209         if (!W_ERROR_IS_OK(werr)) {
2210                 return werr;
2211         }
2212
2213         if (!(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE)) {
2214                 return WERR_OK;
2215         }
2216
2217         saf_join_store(r->out.netbios_domain_name, r->in.dc_name);
2218         if (r->out.dns_domain_name) {
2219                 saf_join_store(r->out.dns_domain_name, r->in.dc_name);
2220         }
2221
2222 #ifdef HAVE_ADS
2223         if (r->out.domain_is_ad &&
2224             !(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE)) {
2225                 ADS_STATUS ads_status;
2226
2227                 ads_status  = libnet_join_post_processing_ads(mem_ctx, r);
2228                 if (!ADS_ERR_OK(ads_status)) {
2229                         return WERR_GEN_FAILURE;
2230                 }
2231         }
2232 #endif /* HAVE_ADS */
2233
2234         libnet_join_add_dom_rids_to_builtins(r->out.domain_sid);
2235
2236         return WERR_OK;
2237 }
2238
2239 /****************************************************************
2240 ****************************************************************/
2241
2242 static int libnet_destroy_JoinCtx(struct libnet_JoinCtx *r)
2243 {
2244         if (r->in.ads) {
2245                 ads_destroy(&r->in.ads);
2246         }
2247
2248         return 0;
2249 }
2250
2251 /****************************************************************
2252 ****************************************************************/
2253
2254 static int libnet_destroy_UnjoinCtx(struct libnet_UnjoinCtx *r)
2255 {
2256         if (r->in.ads) {
2257                 ads_destroy(&r->in.ads);
2258         }
2259
2260         return 0;
2261 }
2262
2263 /****************************************************************
2264 ****************************************************************/
2265
2266 WERROR libnet_init_JoinCtx(TALLOC_CTX *mem_ctx,
2267                            struct libnet_JoinCtx **r)
2268 {
2269         struct libnet_JoinCtx *ctx;
2270
2271         ctx = talloc_zero(mem_ctx, struct libnet_JoinCtx);
2272         if (!ctx) {
2273                 return WERR_NOT_ENOUGH_MEMORY;
2274         }
2275
2276         talloc_set_destructor(ctx, libnet_destroy_JoinCtx);
2277
2278         ctx->in.machine_name = talloc_strdup(mem_ctx, lp_netbios_name());
2279         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
2280
2281         ctx->in.secure_channel_type = SEC_CHAN_WKSTA;
2282
2283         ctx->in.desired_encryption_types = ENC_CRC32 |
2284                                            ENC_RSA_MD5 |
2285                                            ENC_RC4_HMAC_MD5;
2286 #ifdef HAVE_ENCTYPE_AES128_CTS_HMAC_SHA1_96
2287         ctx->in.desired_encryption_types |= ENC_HMAC_SHA1_96_AES128;
2288 #endif
2289 #ifdef HAVE_ENCTYPE_AES256_CTS_HMAC_SHA1_96
2290         ctx->in.desired_encryption_types |= ENC_HMAC_SHA1_96_AES256;
2291 #endif
2292
2293         *r = ctx;
2294
2295         return WERR_OK;
2296 }
2297
2298 /****************************************************************
2299 ****************************************************************/
2300
2301 WERROR libnet_init_UnjoinCtx(TALLOC_CTX *mem_ctx,
2302                              struct libnet_UnjoinCtx **r)
2303 {
2304         struct libnet_UnjoinCtx *ctx;
2305
2306         ctx = talloc_zero(mem_ctx, struct libnet_UnjoinCtx);
2307         if (!ctx) {
2308                 return WERR_NOT_ENOUGH_MEMORY;
2309         }
2310
2311         talloc_set_destructor(ctx, libnet_destroy_UnjoinCtx);
2312
2313         ctx->in.machine_name = talloc_strdup(mem_ctx, lp_netbios_name());
2314         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
2315
2316         *r = ctx;
2317
2318         return WERR_OK;
2319 }
2320
2321 /****************************************************************
2322 ****************************************************************/
2323
2324 static WERROR libnet_join_check_config(TALLOC_CTX *mem_ctx,
2325                                        struct libnet_JoinCtx *r)
2326 {
2327         bool valid_security = false;
2328         bool valid_workgroup = false;
2329         bool valid_realm = false;
2330         bool ignored_realm = false;
2331
2332         /* check if configuration is already set correctly */
2333
2334         valid_workgroup = strequal(lp_workgroup(), r->out.netbios_domain_name);
2335
2336         switch (r->out.domain_is_ad) {
2337                 case false:
2338                         valid_security = (lp_security() == SEC_DOMAIN)
2339                                 || (lp_server_role() == ROLE_DOMAIN_PDC)
2340                                 || (lp_server_role() == ROLE_DOMAIN_BDC);
2341                         if (valid_workgroup && valid_security) {
2342                                 /* nothing to be done */
2343                                 return WERR_OK;
2344                         }
2345                         break;
2346                 case true:
2347                         valid_realm = strequal(lp_realm(), r->out.dns_domain_name);
2348                         switch (lp_security()) {
2349                         case SEC_DOMAIN:
2350                                 if (!valid_realm && lp_winbind_rpc_only()) {
2351                                         valid_realm = true;
2352                                         ignored_realm = true;
2353                                 }
2354                                 /* FALL THROUGH */
2355                         case SEC_ADS:
2356                                 valid_security = true;
2357                         }
2358
2359                         if (valid_workgroup && valid_realm && valid_security) {
2360                                 if (ignored_realm && !r->in.modify_config)
2361                                 {
2362                                         libnet_join_set_error_string(mem_ctx, r,
2363                                                 "Warning: ignoring realm when "
2364                                                 "joining AD domain with "
2365                                                 "'security=domain' and "
2366                                                 "'winbind rpc only = yes'. "
2367                                                 "(realm set to '%s', "
2368                                                 "should be '%s').", lp_realm(),
2369                                                 r->out.dns_domain_name);
2370                                 }
2371                                 /* nothing to be done */
2372                                 return WERR_OK;
2373                         }
2374                         break;
2375         }
2376
2377         /* check if we are supposed to manipulate configuration */
2378
2379         if (!r->in.modify_config) {
2380
2381                 char *wrong_conf = talloc_strdup(mem_ctx, "");
2382
2383                 if (!valid_workgroup) {
2384                         wrong_conf = talloc_asprintf_append(wrong_conf,
2385                                 "\"workgroup\" set to '%s', should be '%s'",
2386                                 lp_workgroup(), r->out.netbios_domain_name);
2387                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
2388                 }
2389
2390                 if (!valid_realm) {
2391                         wrong_conf = talloc_asprintf_append(wrong_conf,
2392                                 "\"realm\" set to '%s', should be '%s'",
2393                                 lp_realm(), r->out.dns_domain_name);
2394                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
2395                 }
2396
2397                 if (!valid_security) {
2398                         const char *sec = NULL;
2399                         switch (lp_security()) {
2400                         case SEC_USER:  sec = "user"; break;
2401                         case SEC_DOMAIN: sec = "domain"; break;
2402                         case SEC_ADS: sec = "ads"; break;
2403                         }
2404                         wrong_conf = talloc_asprintf_append(wrong_conf,
2405                                 "\"security\" set to '%s', should be %s",
2406                                 sec, r->out.domain_is_ad ?
2407                                 "either 'domain' or 'ads'" : "'domain'");
2408                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
2409                 }
2410
2411                 libnet_join_set_error_string(mem_ctx, r,
2412                         "Invalid configuration (%s) and configuration modification "
2413                         "was not requested", wrong_conf);
2414                 return WERR_CAN_NOT_COMPLETE;
2415         }
2416
2417         /* check if we are able to manipulate configuration */
2418
2419         if (!lp_config_backend_is_registry()) {
2420                 libnet_join_set_error_string(mem_ctx, r,
2421                         "Configuration manipulation requested but not "
2422                         "supported by backend");
2423                 return WERR_NOT_SUPPORTED;
2424         }
2425
2426         return WERR_OK;
2427 }
2428
2429 /****************************************************************
2430 ****************************************************************/
2431
2432 static WERROR libnet_DomainJoin(TALLOC_CTX *mem_ctx,
2433                                 struct libnet_JoinCtx *r)
2434 {
2435         NTSTATUS status;
2436         WERROR werr;
2437         struct cli_state *cli = NULL;
2438 #ifdef HAVE_ADS
2439         ADS_STATUS ads_status;
2440 #endif /* HAVE_ADS */
2441         const char *pre_connect_realm = NULL;
2442         const char *numeric_dcip = NULL;
2443         const char *sitename = NULL;
2444
2445         /* Before contacting a DC, we can securely know
2446          * the realm only if the user specifies it.
2447          */
2448         if (r->in.use_kerberos &&
2449             r->in.domain_name_type == JoinDomNameTypeDNS) {
2450                 pre_connect_realm = r->in.domain_name;
2451         }
2452
2453         if (!r->in.dc_name) {
2454                 struct netr_DsRGetDCNameInfo *info;
2455                 const char *dc;
2456                 uint32_t name_type_flags = 0;
2457                 if (r->in.domain_name_type == JoinDomNameTypeDNS) {
2458                         name_type_flags = DS_IS_DNS_NAME;
2459                 } else if (r->in.domain_name_type == JoinDomNameTypeNBT) {
2460                         name_type_flags = DS_IS_FLAT_NAME;
2461                 }
2462                 status = dsgetdcname(mem_ctx,
2463                                      r->in.msg_ctx,
2464                                      r->in.domain_name,
2465                                      NULL,
2466                                      NULL,
2467                                      DS_FORCE_REDISCOVERY |
2468                                      DS_DIRECTORY_SERVICE_REQUIRED |
2469                                      DS_WRITABLE_REQUIRED |
2470                                      DS_RETURN_DNS_NAME |
2471                                      name_type_flags,
2472                                      &info);
2473                 if (!NT_STATUS_IS_OK(status)) {
2474                         libnet_join_set_error_string(mem_ctx, r,
2475                                 "failed to find DC for domain %s - %s",
2476                                 r->in.domain_name,
2477                                 get_friendly_nt_error_msg(status));
2478                         return WERR_NERR_DCNOTFOUND;
2479                 }
2480
2481                 dc = strip_hostname(info->dc_unc);
2482                 r->in.dc_name = talloc_strdup(mem_ctx, dc);
2483                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
2484
2485                 if (info->dc_address == NULL || info->dc_address[0] != '\\' ||
2486                     info->dc_address[1] != '\\') {
2487                         DBG_ERR("ill-formed DC address '%s'\n",
2488                                 info->dc_address);
2489                         return WERR_NERR_DCNOTFOUND;
2490                 }
2491
2492                 numeric_dcip = info->dc_address + 2;
2493                 sitename = info->dc_site_name;
2494                 /* info goes out of scope but the memory stays
2495                    allocated on the talloc context */
2496         }
2497
2498         if (pre_connect_realm != NULL) {
2499                 struct sockaddr_storage ss = {0};
2500
2501                 if (numeric_dcip != NULL) {
2502                         if (!interpret_string_addr(&ss, numeric_dcip,
2503                                                    AI_NUMERICHOST)) {
2504                                 DBG_ERR(
2505                                     "cannot parse IP address '%s' of DC '%s'\n",
2506                                     numeric_dcip, r->in.dc_name);
2507                                 return WERR_NERR_DCNOTFOUND;
2508                         }
2509                 } else {
2510                         if (!interpret_string_addr(&ss, r->in.dc_name, 0)) {
2511                                 DBG_WARNING(
2512                                     "cannot resolve IP address of DC '%s'\n",
2513                                     r->in.dc_name);
2514                                 return WERR_NERR_DCNOTFOUND;
2515                         }
2516                 }
2517
2518                 /* The domain parameter is only used as modifier
2519                  * to krb5.conf file name. .JOIN is is not a valid
2520                  * NetBIOS name so it cannot clash with another domain
2521                  * -- Uri.
2522                  */
2523                 create_local_private_krb5_conf_for_domain(
2524                     pre_connect_realm, ".JOIN", sitename, &ss);
2525         }
2526
2527         status = libnet_join_lookup_dc_rpc(mem_ctx, r, &cli);
2528         if (!NT_STATUS_IS_OK(status)) {
2529                 libnet_join_set_error_string(mem_ctx, r,
2530                         "failed to lookup DC info for domain '%s' over rpc: %s",
2531                         r->in.domain_name, get_friendly_nt_error_msg(status));
2532                 return ntstatus_to_werror(status);
2533         }
2534
2535         werr = libnet_join_check_config(mem_ctx, r);
2536         if (!W_ERROR_IS_OK(werr)) {
2537                 goto done;
2538         }
2539
2540 #ifdef HAVE_ADS
2541
2542         if (r->out.domain_is_ad) {
2543                 create_local_private_krb5_conf_for_domain(
2544                         r->out.dns_domain_name, r->out.netbios_domain_name,
2545                         sitename, smbXcli_conn_remote_sockaddr(cli->conn));
2546         }
2547
2548         if (r->out.domain_is_ad &&
2549             !(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE)) {
2550
2551                 const char *initial_account_ou = r->in.account_ou;
2552
2553                 /*
2554                  * we want to create the msDS-SupportedEncryptionTypes attribute
2555                  * as early as possible so always try an LDAP create as the user
2556                  * first. We copy r->in.account_ou because it may be changed
2557                  * during the machine pre-creation.
2558                  */
2559
2560                 ads_status = libnet_join_connect_ads_user(mem_ctx, r);
2561                 if (!ADS_ERR_OK(ads_status)) {
2562                         return WERR_NERR_DEFAULTJOINREQUIRED;
2563                 }
2564
2565                 ads_status = libnet_join_precreate_machine_acct(mem_ctx, r);
2566                 if (ADS_ERR_OK(ads_status)) {
2567
2568                         /*
2569                          * LDAP object create succeeded, now go to the rpc
2570                          * password set routines
2571                          */
2572
2573                         r->in.join_flags &= ~WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE;
2574                         goto rpc_join;
2575                 }
2576
2577                 if (initial_account_ou != NULL) {
2578                         libnet_join_set_error_string(mem_ctx, r,
2579                                 "failed to precreate account in ou %s: %s",
2580                                 r->in.account_ou,
2581                                 ads_errstr(ads_status));
2582                         return WERR_NERR_DEFAULTJOINREQUIRED;
2583                 }
2584
2585                 DEBUG(5, ("failed to precreate account in ou %s: %s",
2586                         r->in.account_ou, ads_errstr(ads_status)));
2587         }
2588 #endif /* HAVE_ADS */
2589
2590  rpc_join:
2591         if ((r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE) &&
2592             (r->in.join_flags & WKSSVC_JOIN_FLAGS_MACHINE_PWD_PASSED)) {
2593                 status = libnet_join_joindomain_rpc_unsecure(mem_ctx, r, cli);
2594         } else {
2595                 status = libnet_join_joindomain_rpc(mem_ctx, r, cli);
2596         }
2597         if (!NT_STATUS_IS_OK(status)) {
2598                 libnet_join_set_error_string(mem_ctx, r,
2599                         "failed to join domain '%s' over rpc: %s",
2600                         r->in.domain_name, get_friendly_nt_error_msg(status));
2601                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
2602                         return WERR_NERR_SETUPALREADYJOINED;
2603                 }
2604                 werr = ntstatus_to_werror(status);
2605                 goto done;
2606         }
2607
2608         if (!libnet_join_joindomain_store_secrets(mem_ctx, r)) {
2609                 werr = WERR_NERR_SETUPNOTJOINED;
2610                 goto done;
2611         }
2612
2613         werr = WERR_OK;
2614
2615  done:
2616         if (cli) {
2617                 cli_shutdown(cli);
2618         }
2619
2620         return werr;
2621 }
2622
2623 /****************************************************************
2624 ****************************************************************/
2625
2626 static WERROR libnet_join_rollback(TALLOC_CTX *mem_ctx,
2627                                    struct libnet_JoinCtx *r)
2628 {
2629         WERROR werr;
2630         struct libnet_UnjoinCtx *u = NULL;
2631
2632         werr = libnet_init_UnjoinCtx(mem_ctx, &u);
2633         if (!W_ERROR_IS_OK(werr)) {
2634                 return werr;
2635         }
2636
2637         u->in.debug             = r->in.debug;
2638         u->in.dc_name           = r->in.dc_name;
2639         u->in.domain_name       = r->in.domain_name;
2640         u->in.admin_account     = r->in.admin_account;
2641         u->in.admin_password    = r->in.admin_password;
2642         u->in.modify_config     = r->in.modify_config;
2643         u->in.use_kerberos      = r->in.use_kerberos;
2644         u->in.unjoin_flags      = WKSSVC_JOIN_FLAGS_JOIN_TYPE |
2645                                   WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE;
2646
2647         werr = libnet_Unjoin(mem_ctx, u);
2648         TALLOC_FREE(u);
2649
2650         return werr;
2651 }
2652
2653 /****************************************************************
2654 ****************************************************************/
2655
2656 WERROR libnet_Join(TALLOC_CTX *mem_ctx,
2657                    struct libnet_JoinCtx *r)
2658 {
2659         WERROR werr;
2660
2661         if (r->in.debug) {
2662                 LIBNET_JOIN_IN_DUMP_CTX(mem_ctx, r);
2663         }
2664
2665         ZERO_STRUCT(r->out);
2666
2667         werr = libnet_join_pre_processing(mem_ctx, r);
2668         if (!W_ERROR_IS_OK(werr)) {
2669                 goto done;
2670         }
2671
2672         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
2673                 werr = libnet_DomainJoin(mem_ctx, r);
2674                 if (!W_ERROR_IS_OK(werr)) {
2675                         goto done;
2676                 }
2677         }
2678
2679         werr = libnet_join_post_processing(mem_ctx, r);
2680         if (!W_ERROR_IS_OK(werr)) {
2681                 goto done;
2682         }
2683
2684         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
2685                 werr = libnet_join_post_verify(mem_ctx, r);
2686                 if (!W_ERROR_IS_OK(werr)) {
2687                         libnet_join_rollback(mem_ctx, r);
2688                 }
2689         }
2690
2691  done:
2692         r->out.result = werr;
2693
2694         if (r->in.debug) {
2695                 LIBNET_JOIN_OUT_DUMP_CTX(mem_ctx, r);
2696         }
2697         return werr;
2698 }
2699
2700 /****************************************************************
2701 ****************************************************************/
2702
2703 static WERROR libnet_DomainUnjoin(TALLOC_CTX *mem_ctx,
2704                                   struct libnet_UnjoinCtx *r)
2705 {
2706         NTSTATUS status;
2707
2708         if (!r->in.domain_sid) {
2709                 struct dom_sid sid;
2710                 if (!secrets_fetch_domain_sid(lp_workgroup(), &sid)) {
2711                         libnet_unjoin_set_error_string(mem_ctx, r,
2712                                 "Unable to fetch domain sid: are we joined?");
2713                         return WERR_NERR_SETUPNOTJOINED;
2714                 }
2715                 r->in.domain_sid = dom_sid_dup(mem_ctx, &sid);
2716                 W_ERROR_HAVE_NO_MEMORY(r->in.domain_sid);
2717         }
2718
2719         if (!(r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE) && 
2720             !r->in.delete_machine_account) {
2721                 libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2722                 return WERR_OK;
2723         }
2724
2725         if (!r->in.dc_name) {
2726                 struct netr_DsRGetDCNameInfo *info;
2727                 const char *dc;
2728                 status = dsgetdcname(mem_ctx,
2729                                      r->in.msg_ctx,
2730                                      r->in.domain_name,
2731                                      NULL,
2732                                      NULL,
2733                                      DS_DIRECTORY_SERVICE_REQUIRED |
2734                                      DS_WRITABLE_REQUIRED |
2735                                      DS_RETURN_DNS_NAME,
2736                                      &info);
2737                 if (!NT_STATUS_IS_OK(status)) {
2738                         libnet_unjoin_set_error_string(mem_ctx, r,
2739                                 "failed to find DC for domain %s - %s",
2740                                 r->in.domain_name,
2741                                 get_friendly_nt_error_msg(status));
2742                         return WERR_NERR_DCNOTFOUND;
2743                 }
2744
2745                 dc = strip_hostname(info->dc_unc);
2746                 r->in.dc_name = talloc_strdup(mem_ctx, dc);
2747                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
2748         }
2749
2750 #ifdef HAVE_ADS
2751         /* for net ads leave, try to delete the account.  If it works, 
2752            no sense in disabling.  If it fails, we can still try to 
2753            disable it. jmcd */
2754
2755         if (r->in.delete_machine_account) {
2756                 ADS_STATUS ads_status;
2757                 ads_status = libnet_unjoin_connect_ads(mem_ctx, r);
2758                 if (ADS_ERR_OK(ads_status)) {
2759                         /* dirty hack */
2760                         r->out.dns_domain_name = 
2761                                 talloc_strdup(mem_ctx,
2762                                               r->in.ads->server.realm);
2763                         ads_status = 
2764                                 libnet_unjoin_remove_machine_acct(mem_ctx, r);
2765                 }
2766                 if (!ADS_ERR_OK(ads_status)) {
2767                         libnet_unjoin_set_error_string(mem_ctx, r,
2768                                 "failed to remove machine account from AD: %s",
2769                                 ads_errstr(ads_status));
2770                 } else {
2771                         r->out.deleted_machine_account = true;
2772                         W_ERROR_HAVE_NO_MEMORY(r->out.dns_domain_name);
2773                         libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2774                         return WERR_OK;
2775                 }
2776         }
2777 #endif /* HAVE_ADS */
2778
2779         /* The WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE flag really means 
2780            "disable".  */
2781         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE) {
2782                 status = libnet_join_unjoindomain_rpc(mem_ctx, r);
2783                 if (!NT_STATUS_IS_OK(status)) {
2784                         libnet_unjoin_set_error_string(mem_ctx, r,
2785                                 "failed to disable machine account via rpc: %s",
2786                                 get_friendly_nt_error_msg(status));
2787                         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER)) {
2788                                 return WERR_NERR_SETUPNOTJOINED;
2789                         }
2790                         return ntstatus_to_werror(status);
2791                 }
2792
2793                 r->out.disabled_machine_account = true;
2794         }
2795
2796         /* If disable succeeded or was not requested at all, we 
2797            should be getting rid of our end of things */
2798
2799         libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2800
2801         return WERR_OK;
2802 }
2803
2804 /****************************************************************
2805 ****************************************************************/
2806
2807 static WERROR libnet_unjoin_pre_processing(TALLOC_CTX *mem_ctx,
2808                                            struct libnet_UnjoinCtx *r)
2809 {
2810         if (!r->in.domain_name) {
2811                 libnet_unjoin_set_error_string(mem_ctx, r,
2812                         "No domain name defined");
2813                 return WERR_INVALID_PARAMETER;
2814         }
2815
2816         if (!libnet_parse_domain_dc(mem_ctx, r->in.domain_name,
2817                                     &r->in.domain_name,
2818                                     &r->in.dc_name)) {
2819                 libnet_unjoin_set_error_string(mem_ctx, r,
2820                         "Failed to parse domain name");
2821                 return WERR_INVALID_PARAMETER;
2822         }
2823
2824         if (IS_DC) {
2825                 return WERR_NERR_SETUPDOMAINCONTROLLER;
2826         }
2827
2828         if (!r->in.admin_domain) {
2829                 char *admin_domain = NULL;
2830                 char *admin_account = NULL;
2831                 bool ok;
2832
2833                 ok = split_domain_user(mem_ctx,
2834                                        r->in.admin_account,
2835                                        &admin_domain,
2836                                        &admin_account);
2837                 if (!ok) {
2838                         return WERR_NOT_ENOUGH_MEMORY;
2839                 }
2840
2841                 if (admin_domain != NULL) {
2842                         r->in.admin_domain = admin_domain;
2843                 } else {
2844                         r->in.admin_domain = r->in.domain_name;
2845                 }
2846                 r->in.admin_account = admin_account;
2847         }
2848
2849         if (!secrets_init()) {
2850                 libnet_unjoin_set_error_string(mem_ctx, r,
2851                         "Unable to open secrets database");
2852                 return WERR_CAN_NOT_COMPLETE;
2853         }
2854
2855         return WERR_OK;
2856 }
2857
2858 /****************************************************************
2859 ****************************************************************/
2860
2861 static WERROR libnet_unjoin_post_processing(TALLOC_CTX *mem_ctx,
2862                                             struct libnet_UnjoinCtx *r)
2863 {
2864         saf_delete(r->out.netbios_domain_name);
2865         saf_delete(r->out.dns_domain_name);
2866
2867         return libnet_unjoin_config(r);
2868 }
2869
2870 /****************************************************************
2871 ****************************************************************/
2872
2873 WERROR libnet_Unjoin(TALLOC_CTX *mem_ctx,
2874                      struct libnet_UnjoinCtx *r)
2875 {
2876         WERROR werr;
2877
2878         if (r->in.debug) {
2879                 LIBNET_UNJOIN_IN_DUMP_CTX(mem_ctx, r);
2880         }
2881
2882         werr = libnet_unjoin_pre_processing(mem_ctx, r);
2883         if (!W_ERROR_IS_OK(werr)) {
2884                 goto done;
2885         }
2886
2887         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
2888                 werr = libnet_DomainUnjoin(mem_ctx, r);
2889                 if (!W_ERROR_IS_OK(werr)) {
2890                         libnet_unjoin_config(r);
2891                         goto done;
2892                 }
2893         }
2894
2895         werr = libnet_unjoin_post_processing(mem_ctx, r);
2896         if (!W_ERROR_IS_OK(werr)) {
2897                 goto done;
2898         }
2899
2900  done:
2901         r->out.result = werr;
2902
2903         if (r->in.debug) {
2904                 LIBNET_UNJOIN_OUT_DUMP_CTX(mem_ctx, r);
2905         }
2906
2907         return werr;
2908 }