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