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