Merge branch 'master' of ctdb into 'master' of samba
[nivanova/samba-autobuild/.git] / source3 / libnet / libnet_join.c
1 /*
2  *  Unix SMB/CIFS implementation.
3  *  libnet Join Support
4  *  Copyright (C) Gerald (Jerry) Carter 2006
5  *  Copyright (C) Guenther Deschner 2007-2008
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 3 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License
18  *  along with this program; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include "includes.h"
22 #include "ads.h"
23 #include "librpc/gen_ndr/ndr_libnet_join.h"
24 #include "libnet/libnet_join.h"
25 #include "libcli/auth/libcli_auth.h"
26 #include "../librpc/gen_ndr/ndr_samr_c.h"
27 #include "rpc_client/init_samr.h"
28 #include "../librpc/gen_ndr/ndr_lsa_c.h"
29 #include "rpc_client/cli_lsarpc.h"
30 #include "../librpc/gen_ndr/ndr_netlogon.h"
31 #include "rpc_client/cli_netlogon.h"
32 #include "lib/smbconf/smbconf.h"
33 #include "lib/smbconf/smbconf_reg.h"
34 #include "../libds/common/flags.h"
35 #include "secrets.h"
36 #include "rpc_client/init_lsa.h"
37 #include "rpc_client/cli_pipe.h"
38 #include "../libcli/security/security.h"
39 #include "passdb.h"
40 #include "libsmb/libsmb.h"
41 #include "../libcli/smb/smbXcli_base.h"
42 #include "lib/param/loadparm.h"
43
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                 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
1031         if (name_types.ids[0] != SID_NAME_USER) {
1032                 DEBUG(0,("%s is not a user account (type=%d)\n",
1033                         acct_name, name_types.ids[0]));
1034                 status = NT_STATUS_INVALID_WORKSTATION;
1035                 goto done;
1036         }
1037
1038         user_rid = user_rids.ids[0];
1039
1040         /* Open handle on user */
1041
1042         status = dcerpc_samr_OpenUser(b, mem_ctx,
1043                                       &domain_pol,
1044                                       SEC_FLAG_MAXIMUM_ALLOWED,
1045                                       user_rid,
1046                                       &user_pol,
1047                                       &result);
1048         if (!NT_STATUS_IS_OK(status)) {
1049                 goto done;
1050         }
1051         if (!NT_STATUS_IS_OK(result)) {
1052                 status = result;
1053                 goto done;
1054         }
1055
1056         /* Fill in the additional account flags now */
1057
1058         acct_flags |= ACB_PWNOEXP;
1059
1060         /* Set account flags on machine account */
1061         ZERO_STRUCT(user_info.info16);
1062         user_info.info16.acct_flags = acct_flags;
1063
1064         status = dcerpc_samr_SetUserInfo(b, mem_ctx,
1065                                          &user_pol,
1066                                          16,
1067                                          &user_info,
1068                                          &result);
1069         if (!NT_STATUS_IS_OK(status)) {
1070                 dcerpc_samr_DeleteUser(b, mem_ctx,
1071                                        &user_pol,
1072                                        &result);
1073
1074                 libnet_join_set_error_string(mem_ctx, r,
1075                         "Failed to set account flags for machine account (%s)\n",
1076                         nt_errstr(status));
1077                 goto done;
1078         }
1079
1080         if (!NT_STATUS_IS_OK(result)) {
1081                 status = result;
1082
1083                 dcerpc_samr_DeleteUser(b, mem_ctx,
1084                                        &user_pol,
1085                                        &result);
1086
1087                 libnet_join_set_error_string(mem_ctx, r,
1088                         "Failed to set account flags for machine account (%s)\n",
1089                         nt_errstr(status));
1090                 goto done;
1091         }
1092
1093         /* Set password on machine account - first try level 26 */
1094
1095         /*
1096          * increase the timeout as password filter modules on the DC
1097          * might delay the operation for a significant amount of time
1098          */
1099         old_timeout = rpccli_set_timeout(pipe_hnd, 600000);
1100
1101         init_samr_CryptPasswordEx(r->in.machine_password,
1102                                   &session_key,
1103                                   &crypt_pwd_ex);
1104
1105         user_info.info26.password = crypt_pwd_ex;
1106         user_info.info26.password_expired = PASS_DONT_CHANGE_AT_NEXT_LOGON;
1107
1108         status = dcerpc_samr_SetUserInfo2(b, mem_ctx,
1109                                           &user_pol,
1110                                           26,
1111                                           &user_info,
1112                                           &result);
1113
1114         if (NT_STATUS_EQUAL(status, NT_STATUS_RPC_ENUM_VALUE_OUT_OF_RANGE)) {
1115
1116                 /* retry with level 24 */
1117
1118                 init_samr_CryptPassword(r->in.machine_password,
1119                                         &session_key,
1120                                         &crypt_pwd);
1121
1122                 user_info.info24.password = crypt_pwd;
1123                 user_info.info24.password_expired = PASS_DONT_CHANGE_AT_NEXT_LOGON;
1124
1125                 status = dcerpc_samr_SetUserInfo2(b, mem_ctx,
1126                                                   &user_pol,
1127                                                   24,
1128                                                   &user_info,
1129                                                   &result);
1130         }
1131
1132         old_timeout = rpccli_set_timeout(pipe_hnd, old_timeout);
1133
1134         if (!NT_STATUS_IS_OK(status)) {
1135
1136                 dcerpc_samr_DeleteUser(b, mem_ctx,
1137                                        &user_pol,
1138                                        &result);
1139
1140                 libnet_join_set_error_string(mem_ctx, r,
1141                         "Failed to set password for machine account (%s)\n",
1142                         nt_errstr(status));
1143                 goto done;
1144         }
1145         if (!NT_STATUS_IS_OK(result)) {
1146                 status = result;
1147
1148                 dcerpc_samr_DeleteUser(b, mem_ctx,
1149                                        &user_pol,
1150                                        &result);
1151
1152                 libnet_join_set_error_string(mem_ctx, r,
1153                         "Failed to set password for machine account (%s)\n",
1154                         nt_errstr(status));
1155                 goto done;
1156         }
1157
1158         status = NT_STATUS_OK;
1159
1160  done:
1161         if (!pipe_hnd) {
1162                 return status;
1163         }
1164
1165         data_blob_clear_free(&session_key);
1166
1167         if (is_valid_policy_hnd(&sam_pol)) {
1168                 dcerpc_samr_Close(b, mem_ctx, &sam_pol, &result);
1169         }
1170         if (is_valid_policy_hnd(&domain_pol)) {
1171                 dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
1172         }
1173         if (is_valid_policy_hnd(&user_pol)) {
1174                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1175         }
1176         TALLOC_FREE(pipe_hnd);
1177
1178         return status;
1179 }
1180
1181 /****************************************************************
1182 ****************************************************************/
1183
1184 NTSTATUS libnet_join_ok(const char *netbios_domain_name,
1185                         const char *machine_name,
1186                         const char *dc_name,
1187                         const bool use_kerberos)
1188 {
1189         uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS |
1190                                 NETLOGON_NEG_SUPPORTS_AES;
1191         struct cli_state *cli = NULL;
1192         struct rpc_pipe_client *pipe_hnd = NULL;
1193         struct rpc_pipe_client *netlogon_pipe = NULL;
1194         NTSTATUS status;
1195         char *machine_password = NULL;
1196         char *machine_account = NULL;
1197         int flags = 0;
1198
1199         if (!dc_name) {
1200                 return NT_STATUS_INVALID_PARAMETER;
1201         }
1202
1203         if (!secrets_init()) {
1204                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
1205         }
1206
1207         machine_password = secrets_fetch_machine_password(netbios_domain_name,
1208                                                           NULL, NULL);
1209         if (!machine_password) {
1210                 return NT_STATUS_NO_TRUST_LSA_SECRET;
1211         }
1212
1213         if (asprintf(&machine_account, "%s$", machine_name) == -1) {
1214                 SAFE_FREE(machine_password);
1215                 return NT_STATUS_NO_MEMORY;
1216         }
1217
1218         if (use_kerberos) {
1219                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS;
1220         }
1221
1222         status = cli_full_connection(&cli, NULL,
1223                                      dc_name,
1224                                      NULL, 0,
1225                                      "IPC$", "IPC",
1226                                      machine_account,
1227                                      NULL,
1228                                      machine_password,
1229                                      flags,
1230                                      SMB_SIGNING_DEFAULT);
1231         free(machine_account);
1232         free(machine_password);
1233
1234         if (!NT_STATUS_IS_OK(status)) {
1235                 status = cli_full_connection(&cli, NULL,
1236                                              dc_name,
1237                                              NULL, 0,
1238                                              "IPC$", "IPC",
1239                                              "",
1240                                              NULL,
1241                                              "",
1242                                              0,
1243                                              SMB_SIGNING_DEFAULT);
1244         }
1245
1246         if (!NT_STATUS_IS_OK(status)) {
1247                 return status;
1248         }
1249
1250         status = get_schannel_session_key(cli, netbios_domain_name,
1251                                           &neg_flags, &netlogon_pipe);
1252         if (!NT_STATUS_IS_OK(status)) {
1253                 if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_NETWORK_RESPONSE)) {
1254                         cli_shutdown(cli);
1255                         return NT_STATUS_OK;
1256                 }
1257
1258                 DEBUG(0,("libnet_join_ok: failed to get schannel session "
1259                         "key from server %s for domain %s. Error was %s\n",
1260                         smbXcli_conn_remote_name(cli->conn),
1261                         netbios_domain_name, nt_errstr(status)));
1262                 cli_shutdown(cli);
1263                 return status;
1264         }
1265
1266         if (!lp_client_schannel()) {
1267                 cli_shutdown(cli);
1268                 return NT_STATUS_OK;
1269         }
1270
1271         status = cli_rpc_pipe_open_schannel_with_key(
1272                 cli, &ndr_table_netlogon, NCACN_NP,
1273                 DCERPC_AUTH_LEVEL_PRIVACY,
1274                 netbios_domain_name, &netlogon_pipe->dc, &pipe_hnd);
1275
1276         cli_shutdown(cli);
1277
1278         if (!NT_STATUS_IS_OK(status)) {
1279                 DEBUG(0,("libnet_join_ok: failed to open schannel session "
1280                         "on netlogon pipe to server %s for domain %s. "
1281                         "Error was %s\n",
1282                         smbXcli_conn_remote_name(cli->conn),
1283                         netbios_domain_name, nt_errstr(status)));
1284                 return status;
1285         }
1286
1287         return NT_STATUS_OK;
1288 }
1289
1290 /****************************************************************
1291 ****************************************************************/
1292
1293 static WERROR libnet_join_post_verify(TALLOC_CTX *mem_ctx,
1294                                       struct libnet_JoinCtx *r)
1295 {
1296         NTSTATUS status;
1297
1298         status = libnet_join_ok(r->out.netbios_domain_name,
1299                                 r->in.machine_name,
1300                                 r->in.dc_name,
1301                                 r->in.use_kerberos);
1302         if (!NT_STATUS_IS_OK(status)) {
1303                 libnet_join_set_error_string(mem_ctx, r,
1304                         "failed to verify domain membership after joining: %s",
1305                         get_friendly_nt_error_msg(status));
1306                 return WERR_SETUP_NOT_JOINED;
1307         }
1308
1309         return WERR_OK;
1310 }
1311
1312 /****************************************************************
1313 ****************************************************************/
1314
1315 static bool libnet_join_unjoindomain_remove_secrets(TALLOC_CTX *mem_ctx,
1316                                                     struct libnet_UnjoinCtx *r)
1317 {
1318         if (!secrets_delete_machine_password_ex(lp_workgroup())) {
1319                 return false;
1320         }
1321
1322         if (!secrets_delete_domain_sid(lp_workgroup())) {
1323                 return false;
1324         }
1325
1326         return true;
1327 }
1328
1329 /****************************************************************
1330 ****************************************************************/
1331
1332 static NTSTATUS libnet_join_unjoindomain_rpc(TALLOC_CTX *mem_ctx,
1333                                              struct libnet_UnjoinCtx *r)
1334 {
1335         struct cli_state *cli = NULL;
1336         struct rpc_pipe_client *pipe_hnd = NULL;
1337         struct policy_handle sam_pol, domain_pol, user_pol;
1338         NTSTATUS status = NT_STATUS_UNSUCCESSFUL, result;
1339         char *acct_name;
1340         uint32_t user_rid;
1341         struct lsa_String lsa_acct_name;
1342         struct samr_Ids user_rids;
1343         struct samr_Ids name_types;
1344         union samr_UserInfo *info = NULL;
1345         struct dcerpc_binding_handle *b = NULL;
1346
1347         ZERO_STRUCT(sam_pol);
1348         ZERO_STRUCT(domain_pol);
1349         ZERO_STRUCT(user_pol);
1350
1351         status = libnet_join_connect_dc_ipc(r->in.dc_name,
1352                                             r->in.admin_account,
1353                                             r->in.admin_domain,
1354                                             r->in.admin_password,
1355                                             r->in.use_kerberos,
1356                                             &cli);
1357         if (!NT_STATUS_IS_OK(status)) {
1358                 goto done;
1359         }
1360
1361         /* Open the domain */
1362
1363         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_samr,
1364                                           &pipe_hnd);
1365         if (!NT_STATUS_IS_OK(status)) {
1366                 DEBUG(0,("Error connecting to SAM pipe. Error was %s\n",
1367                         nt_errstr(status)));
1368                 goto done;
1369         }
1370
1371         b = pipe_hnd->binding_handle;
1372
1373         status = dcerpc_samr_Connect2(b, mem_ctx,
1374                                       pipe_hnd->desthost,
1375                                       SEC_FLAG_MAXIMUM_ALLOWED,
1376                                       &sam_pol,
1377                                       &result);
1378         if (!NT_STATUS_IS_OK(status)) {
1379                 goto done;
1380         }
1381         if (!NT_STATUS_IS_OK(result)) {
1382                 status = result;
1383                 goto done;
1384         }
1385
1386         status = dcerpc_samr_OpenDomain(b, mem_ctx,
1387                                         &sam_pol,
1388                                         SEC_FLAG_MAXIMUM_ALLOWED,
1389                                         r->in.domain_sid,
1390                                         &domain_pol,
1391                                         &result);
1392         if (!NT_STATUS_IS_OK(status)) {
1393                 goto done;
1394         }
1395         if (!NT_STATUS_IS_OK(result)) {
1396                 status = result;
1397                 goto done;
1398         }
1399
1400         /* Create domain user */
1401
1402         acct_name = talloc_asprintf(mem_ctx, "%s$", r->in.machine_name);
1403         if (!strlower_m(acct_name)) {
1404                 status = NT_STATUS_INVALID_PARAMETER;
1405                 goto done;
1406         }
1407
1408         init_lsa_String(&lsa_acct_name, acct_name);
1409
1410         status = dcerpc_samr_LookupNames(b, mem_ctx,
1411                                          &domain_pol,
1412                                          1,
1413                                          &lsa_acct_name,
1414                                          &user_rids,
1415                                          &name_types,
1416                                          &result);
1417
1418         if (!NT_STATUS_IS_OK(status)) {
1419                 goto done;
1420         }
1421         if (!NT_STATUS_IS_OK(result)) {
1422                 status = result;
1423                 goto done;
1424         }
1425
1426         if (name_types.ids[0] != SID_NAME_USER) {
1427                 DEBUG(0, ("%s is not a user account (type=%d)\n", acct_name,
1428                         name_types.ids[0]));
1429                 status = NT_STATUS_INVALID_WORKSTATION;
1430                 goto done;
1431         }
1432
1433         user_rid = user_rids.ids[0];
1434
1435         /* Open handle on user */
1436
1437         status = dcerpc_samr_OpenUser(b, mem_ctx,
1438                                       &domain_pol,
1439                                       SEC_FLAG_MAXIMUM_ALLOWED,
1440                                       user_rid,
1441                                       &user_pol,
1442                                       &result);
1443         if (!NT_STATUS_IS_OK(status)) {
1444                 goto done;
1445         }
1446         if (!NT_STATUS_IS_OK(result)) {
1447                 status = result;
1448                 goto done;
1449         }
1450
1451         /* Get user info */
1452
1453         status = dcerpc_samr_QueryUserInfo(b, mem_ctx,
1454                                            &user_pol,
1455                                            16,
1456                                            &info,
1457                                            &result);
1458         if (!NT_STATUS_IS_OK(status)) {
1459                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1460                 goto done;
1461         }
1462         if (!NT_STATUS_IS_OK(result)) {
1463                 status = result;
1464                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1465                 goto done;
1466         }
1467
1468         /* now disable and setuser info */
1469
1470         info->info16.acct_flags |= ACB_DISABLED;
1471
1472         status = dcerpc_samr_SetUserInfo(b, mem_ctx,
1473                                          &user_pol,
1474                                          16,
1475                                          info,
1476                                          &result);
1477         if (!NT_STATUS_IS_OK(status)) {
1478                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1479                 goto done;
1480         }
1481         if (!NT_STATUS_IS_OK(result)) {
1482                 status = result;
1483                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1484                 goto done;
1485         }
1486         status = result;
1487         dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
1488
1489 done:
1490         if (pipe_hnd && b) {
1491                 if (is_valid_policy_hnd(&domain_pol)) {
1492                         dcerpc_samr_Close(b, mem_ctx, &domain_pol, &result);
1493                 }
1494                 if (is_valid_policy_hnd(&sam_pol)) {
1495                         dcerpc_samr_Close(b, mem_ctx, &sam_pol, &result);
1496                 }
1497                 TALLOC_FREE(pipe_hnd);
1498         }
1499
1500         if (cli) {
1501                 cli_shutdown(cli);
1502         }
1503
1504         return status;
1505 }
1506
1507 /****************************************************************
1508 ****************************************************************/
1509
1510 static WERROR do_join_modify_vals_config(struct libnet_JoinCtx *r)
1511 {
1512         WERROR werr = WERR_OK;
1513         sbcErr err;
1514         struct smbconf_ctx *ctx;
1515
1516         err = smbconf_init_reg(r, &ctx, NULL);
1517         if (!SBC_ERROR_IS_OK(err)) {
1518                 werr = WERR_NO_SUCH_SERVICE;
1519                 goto done;
1520         }
1521
1522         if (!(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE)) {
1523
1524                 err = smbconf_set_global_parameter(ctx, "security", "user");
1525                 if (!SBC_ERROR_IS_OK(err)) {
1526                         werr = WERR_NO_SUCH_SERVICE;
1527                         goto done;
1528                 }
1529
1530                 err = smbconf_set_global_parameter(ctx, "workgroup",
1531                                                    r->in.domain_name);
1532                 if (!SBC_ERROR_IS_OK(err)) {
1533                         werr = WERR_NO_SUCH_SERVICE;
1534                         goto done;
1535                 }
1536
1537                 smbconf_delete_global_parameter(ctx, "realm");
1538                 goto done;
1539         }
1540
1541         err = smbconf_set_global_parameter(ctx, "security", "domain");
1542         if (!SBC_ERROR_IS_OK(err)) {
1543                 werr = WERR_NO_SUCH_SERVICE;
1544                 goto done;
1545         }
1546
1547         err = smbconf_set_global_parameter(ctx, "workgroup",
1548                                            r->out.netbios_domain_name);
1549         if (!SBC_ERROR_IS_OK(err)) {
1550                 werr = WERR_NO_SUCH_SERVICE;
1551                 goto done;
1552         }
1553
1554         if (r->out.domain_is_ad) {
1555                 err = smbconf_set_global_parameter(ctx, "security", "ads");
1556                 if (!SBC_ERROR_IS_OK(err)) {
1557                         werr = WERR_NO_SUCH_SERVICE;
1558                         goto done;
1559                 }
1560
1561                 err = smbconf_set_global_parameter(ctx, "realm",
1562                                                    r->out.dns_domain_name);
1563                 if (!SBC_ERROR_IS_OK(err)) {
1564                         werr = WERR_NO_SUCH_SERVICE;
1565                         goto done;
1566                 }
1567         }
1568
1569  done:
1570         smbconf_shutdown(ctx);
1571         return werr;
1572 }
1573
1574 /****************************************************************
1575 ****************************************************************/
1576
1577 static WERROR do_unjoin_modify_vals_config(struct libnet_UnjoinCtx *r)
1578 {
1579         WERROR werr = WERR_OK;
1580         sbcErr err;
1581         struct smbconf_ctx *ctx;
1582
1583         err = smbconf_init_reg(r, &ctx, NULL);
1584         if (!SBC_ERROR_IS_OK(err)) {
1585                 werr = WERR_NO_SUCH_SERVICE;
1586                 goto done;
1587         }
1588
1589         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1590
1591                 err = smbconf_set_global_parameter(ctx, "security", "user");
1592                 if (!SBC_ERROR_IS_OK(err)) {
1593                         werr = WERR_NO_SUCH_SERVICE;
1594                         goto done;
1595                 }
1596
1597                 err = smbconf_delete_global_parameter(ctx, "workgroup");
1598                 if (!SBC_ERROR_IS_OK(err)) {
1599                         werr = WERR_NO_SUCH_SERVICE;
1600                         goto done;
1601                 }
1602
1603                 smbconf_delete_global_parameter(ctx, "realm");
1604         }
1605
1606  done:
1607         smbconf_shutdown(ctx);
1608         return werr;
1609 }
1610
1611 /****************************************************************
1612 ****************************************************************/
1613
1614 static WERROR do_JoinConfig(struct libnet_JoinCtx *r)
1615 {
1616         WERROR werr;
1617
1618         if (!W_ERROR_IS_OK(r->out.result)) {
1619                 return r->out.result;
1620         }
1621
1622         if (!r->in.modify_config) {
1623                 return WERR_OK;
1624         }
1625
1626         werr = do_join_modify_vals_config(r);
1627         if (!W_ERROR_IS_OK(werr)) {
1628                 return werr;
1629         }
1630
1631         lp_load_global(get_dyn_CONFIGFILE());
1632
1633         r->out.modified_config = true;
1634         r->out.result = werr;
1635
1636         return werr;
1637 }
1638
1639 /****************************************************************
1640 ****************************************************************/
1641
1642 static WERROR libnet_unjoin_config(struct libnet_UnjoinCtx *r)
1643 {
1644         WERROR werr;
1645
1646         if (!W_ERROR_IS_OK(r->out.result)) {
1647                 return r->out.result;
1648         }
1649
1650         if (!r->in.modify_config) {
1651                 return WERR_OK;
1652         }
1653
1654         werr = do_unjoin_modify_vals_config(r);
1655         if (!W_ERROR_IS_OK(werr)) {
1656                 return werr;
1657         }
1658
1659         lp_load_global(get_dyn_CONFIGFILE());
1660
1661         r->out.modified_config = true;
1662         r->out.result = werr;
1663
1664         return werr;
1665 }
1666
1667 /****************************************************************
1668 ****************************************************************/
1669
1670 static bool libnet_parse_domain_dc(TALLOC_CTX *mem_ctx,
1671                                    const char *domain_str,
1672                                    const char **domain_p,
1673                                    const char **dc_p)
1674 {
1675         char *domain = NULL;
1676         char *dc = NULL;
1677         const char *p = NULL;
1678
1679         if (!domain_str || !domain_p || !dc_p) {
1680                 return false;
1681         }
1682
1683         p = strchr_m(domain_str, '\\');
1684
1685         if (p != NULL) {
1686                 domain = talloc_strndup(mem_ctx, domain_str,
1687                                          PTR_DIFF(p, domain_str));
1688                 dc = talloc_strdup(mem_ctx, p+1);
1689                 if (!dc) {
1690                         return false;
1691                 }
1692         } else {
1693                 domain = talloc_strdup(mem_ctx, domain_str);
1694                 dc = NULL;
1695         }
1696         if (!domain) {
1697                 return false;
1698         }
1699
1700         *domain_p = domain;
1701
1702         if (!*dc_p && dc) {
1703                 *dc_p = dc;
1704         }
1705
1706         return true;
1707 }
1708
1709 /****************************************************************
1710 ****************************************************************/
1711
1712 static WERROR libnet_join_pre_processing(TALLOC_CTX *mem_ctx,
1713                                          struct libnet_JoinCtx *r)
1714 {
1715         if (!r->in.domain_name) {
1716                 libnet_join_set_error_string(mem_ctx, r,
1717                         "No domain name defined");
1718                 return WERR_INVALID_PARAM;
1719         }
1720
1721         if (strlen(r->in.machine_name) > 15) {
1722                 libnet_join_set_error_string(mem_ctx, r,
1723                         "Our netbios name can be at most 15 chars long, "
1724                          "\"%s\" is %u chars long\n",
1725                          r->in.machine_name,
1726                          (unsigned int)strlen(r->in.machine_name));
1727                 return WERR_INVALID_PARAM;
1728         }
1729
1730         if (!libnet_parse_domain_dc(mem_ctx, r->in.domain_name,
1731                                     &r->in.domain_name,
1732                                     &r->in.dc_name)) {
1733                 libnet_join_set_error_string(mem_ctx, r,
1734                         "Failed to parse domain name");
1735                 return WERR_INVALID_PARAM;
1736         }
1737
1738         if (IS_DC) {
1739                 return WERR_SETUP_DOMAIN_CONTROLLER;
1740         }
1741
1742         if (!r->in.admin_domain) {
1743                 char *admin_domain = NULL;
1744                 char *admin_account = NULL;
1745                 split_domain_user(mem_ctx,
1746                                   r->in.admin_account,
1747                                   &admin_domain,
1748                                   &admin_account);
1749                 r->in.admin_domain = admin_domain;
1750                 r->in.admin_account = admin_account;
1751         }
1752
1753         if (!secrets_init()) {
1754                 libnet_join_set_error_string(mem_ctx, r,
1755                         "Unable to open secrets database");
1756                 return WERR_CAN_NOT_COMPLETE;
1757         }
1758
1759         return WERR_OK;
1760 }
1761
1762 /****************************************************************
1763 ****************************************************************/
1764
1765 static void libnet_join_add_dom_rids_to_builtins(struct dom_sid *domain_sid)
1766 {
1767         NTSTATUS status;
1768
1769         /* Try adding dom admins to builtin\admins. Only log failures. */
1770         status = create_builtin_administrators(domain_sid);
1771         if (NT_STATUS_EQUAL(status, NT_STATUS_PROTOCOL_UNREACHABLE)) {
1772                 DEBUG(10,("Unable to auto-add domain administrators to "
1773                           "BUILTIN\\Administrators during join because "
1774                           "winbindd must be running.\n"));
1775         } else if (!NT_STATUS_IS_OK(status)) {
1776                 DEBUG(5, ("Failed to auto-add domain administrators to "
1777                           "BUILTIN\\Administrators during join: %s\n",
1778                           nt_errstr(status)));
1779         }
1780
1781         /* Try adding dom users to builtin\users. Only log failures. */
1782         status = create_builtin_users(domain_sid);
1783         if (NT_STATUS_EQUAL(status, NT_STATUS_PROTOCOL_UNREACHABLE)) {
1784                 DEBUG(10,("Unable to auto-add domain users to BUILTIN\\users "
1785                           "during join because winbindd must be running.\n"));
1786         } else if (!NT_STATUS_IS_OK(status)) {
1787                 DEBUG(5, ("Failed to auto-add domain administrators to "
1788                           "BUILTIN\\Administrators during join: %s\n",
1789                           nt_errstr(status)));
1790         }
1791 }
1792
1793 /****************************************************************
1794 ****************************************************************/
1795
1796 static WERROR libnet_join_post_processing(TALLOC_CTX *mem_ctx,
1797                                           struct libnet_JoinCtx *r)
1798 {
1799         WERROR werr;
1800
1801         if (!W_ERROR_IS_OK(r->out.result)) {
1802                 return r->out.result;
1803         }
1804
1805         werr = do_JoinConfig(r);
1806         if (!W_ERROR_IS_OK(werr)) {
1807                 return werr;
1808         }
1809
1810         if (!(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE)) {
1811                 return WERR_OK;
1812         }
1813
1814         saf_join_store(r->out.netbios_domain_name, r->in.dc_name);
1815         if (r->out.dns_domain_name) {
1816                 saf_join_store(r->out.dns_domain_name, r->in.dc_name);
1817         }
1818
1819 #ifdef HAVE_ADS
1820         if (r->out.domain_is_ad &&
1821             !(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE)) {
1822                 ADS_STATUS ads_status;
1823
1824                 ads_status  = libnet_join_post_processing_ads(mem_ctx, r);
1825                 if (!ADS_ERR_OK(ads_status)) {
1826                         return WERR_GENERAL_FAILURE;
1827                 }
1828         }
1829 #endif /* HAVE_ADS */
1830
1831         libnet_join_add_dom_rids_to_builtins(r->out.domain_sid);
1832
1833         return WERR_OK;
1834 }
1835
1836 /****************************************************************
1837 ****************************************************************/
1838
1839 static int libnet_destroy_JoinCtx(struct libnet_JoinCtx *r)
1840 {
1841         if (r->in.ads) {
1842                 ads_destroy(&r->in.ads);
1843         }
1844
1845         return 0;
1846 }
1847
1848 /****************************************************************
1849 ****************************************************************/
1850
1851 static int libnet_destroy_UnjoinCtx(struct libnet_UnjoinCtx *r)
1852 {
1853         if (r->in.ads) {
1854                 ads_destroy(&r->in.ads);
1855         }
1856
1857         return 0;
1858 }
1859
1860 /****************************************************************
1861 ****************************************************************/
1862
1863 WERROR libnet_init_JoinCtx(TALLOC_CTX *mem_ctx,
1864                            struct libnet_JoinCtx **r)
1865 {
1866         struct libnet_JoinCtx *ctx;
1867
1868         ctx = talloc_zero(mem_ctx, struct libnet_JoinCtx);
1869         if (!ctx) {
1870                 return WERR_NOMEM;
1871         }
1872
1873         talloc_set_destructor(ctx, libnet_destroy_JoinCtx);
1874
1875         ctx->in.machine_name = talloc_strdup(mem_ctx, lp_netbios_name());
1876         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
1877
1878         ctx->in.secure_channel_type = SEC_CHAN_WKSTA;
1879
1880         *r = ctx;
1881
1882         return WERR_OK;
1883 }
1884
1885 /****************************************************************
1886 ****************************************************************/
1887
1888 WERROR libnet_init_UnjoinCtx(TALLOC_CTX *mem_ctx,
1889                              struct libnet_UnjoinCtx **r)
1890 {
1891         struct libnet_UnjoinCtx *ctx;
1892
1893         ctx = talloc_zero(mem_ctx, struct libnet_UnjoinCtx);
1894         if (!ctx) {
1895                 return WERR_NOMEM;
1896         }
1897
1898         talloc_set_destructor(ctx, libnet_destroy_UnjoinCtx);
1899
1900         ctx->in.machine_name = talloc_strdup(mem_ctx, lp_netbios_name());
1901         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
1902
1903         *r = ctx;
1904
1905         return WERR_OK;
1906 }
1907
1908 /****************************************************************
1909 ****************************************************************/
1910
1911 static WERROR libnet_join_check_config(TALLOC_CTX *mem_ctx,
1912                                        struct libnet_JoinCtx *r)
1913 {
1914         bool valid_security = false;
1915         bool valid_workgroup = false;
1916         bool valid_realm = false;
1917
1918         /* check if configuration is already set correctly */
1919
1920         valid_workgroup = strequal(lp_workgroup(), r->out.netbios_domain_name);
1921
1922         switch (r->out.domain_is_ad) {
1923                 case false:
1924                         valid_security = (lp_security() == SEC_DOMAIN);
1925                         if (valid_workgroup && valid_security) {
1926                                 /* nothing to be done */
1927                                 return WERR_OK;
1928                         }
1929                         break;
1930                 case true:
1931                         valid_realm = strequal(lp_realm(), r->out.dns_domain_name);
1932                         switch (lp_security()) {
1933                         case SEC_DOMAIN:
1934                         case SEC_ADS:
1935                                 valid_security = true;
1936                         }
1937
1938                         if (valid_workgroup && valid_realm && valid_security) {
1939                                 /* nothing to be done */
1940                                 return WERR_OK;
1941                         }
1942                         break;
1943         }
1944
1945         /* check if we are supposed to manipulate configuration */
1946
1947         if (!r->in.modify_config) {
1948
1949                 char *wrong_conf = talloc_strdup(mem_ctx, "");
1950
1951                 if (!valid_workgroup) {
1952                         wrong_conf = talloc_asprintf_append(wrong_conf,
1953                                 "\"workgroup\" set to '%s', should be '%s'",
1954                                 lp_workgroup(), r->out.netbios_domain_name);
1955                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
1956                 }
1957
1958                 if (!valid_realm) {
1959                         wrong_conf = talloc_asprintf_append(wrong_conf,
1960                                 "\"realm\" set to '%s', should be '%s'",
1961                                 lp_realm(), r->out.dns_domain_name);
1962                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
1963                 }
1964
1965                 if (!valid_security) {
1966                         const char *sec = NULL;
1967                         switch (lp_security()) {
1968                         case SEC_USER:  sec = "user"; break;
1969                         case SEC_DOMAIN: sec = "domain"; break;
1970                         case SEC_ADS: sec = "ads"; break;
1971                         }
1972                         wrong_conf = talloc_asprintf_append(wrong_conf,
1973                                 "\"security\" set to '%s', should be %s",
1974                                 sec, r->out.domain_is_ad ?
1975                                 "either 'domain' or 'ads'" : "'domain'");
1976                         W_ERROR_HAVE_NO_MEMORY(wrong_conf);
1977                 }
1978
1979                 libnet_join_set_error_string(mem_ctx, r,
1980                         "Invalid configuration (%s) and configuration modification "
1981                         "was not requested", wrong_conf);
1982                 return WERR_CAN_NOT_COMPLETE;
1983         }
1984
1985         /* check if we are able to manipulate configuration */
1986
1987         if (!lp_config_backend_is_registry()) {
1988                 libnet_join_set_error_string(mem_ctx, r,
1989                         "Configuration manipulation requested but not "
1990                         "supported by backend");
1991                 return WERR_NOT_SUPPORTED;
1992         }
1993
1994         return WERR_OK;
1995 }
1996
1997 /****************************************************************
1998 ****************************************************************/
1999
2000 static WERROR libnet_DomainJoin(TALLOC_CTX *mem_ctx,
2001                                 struct libnet_JoinCtx *r)
2002 {
2003         NTSTATUS status;
2004         WERROR werr;
2005         struct cli_state *cli = NULL;
2006 #ifdef HAVE_ADS
2007         ADS_STATUS ads_status;
2008 #endif /* HAVE_ADS */
2009
2010         if (!r->in.dc_name) {
2011                 struct netr_DsRGetDCNameInfo *info;
2012                 const char *dc;
2013                 status = dsgetdcname(mem_ctx,
2014                                      r->in.msg_ctx,
2015                                      r->in.domain_name,
2016                                      NULL,
2017                                      NULL,
2018                                      DS_FORCE_REDISCOVERY |
2019                                      DS_DIRECTORY_SERVICE_REQUIRED |
2020                                      DS_WRITABLE_REQUIRED |
2021                                      DS_RETURN_DNS_NAME,
2022                                      &info);
2023                 if (!NT_STATUS_IS_OK(status)) {
2024                         libnet_join_set_error_string(mem_ctx, r,
2025                                 "failed to find DC for domain %s",
2026                                 r->in.domain_name,
2027                                 get_friendly_nt_error_msg(status));
2028                         return WERR_DCNOTFOUND;
2029                 }
2030
2031                 dc = strip_hostname(info->dc_unc);
2032                 r->in.dc_name = talloc_strdup(mem_ctx, dc);
2033                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
2034         }
2035
2036         status = libnet_join_lookup_dc_rpc(mem_ctx, r, &cli);
2037         if (!NT_STATUS_IS_OK(status)) {
2038                 libnet_join_set_error_string(mem_ctx, r,
2039                         "failed to lookup DC info for domain '%s' over rpc: %s",
2040                         r->in.domain_name, get_friendly_nt_error_msg(status));
2041                 return ntstatus_to_werror(status);
2042         }
2043
2044         werr = libnet_join_check_config(mem_ctx, r);
2045         if (!W_ERROR_IS_OK(werr)) {
2046                 goto done;
2047         }
2048
2049 #ifdef HAVE_ADS
2050
2051         create_local_private_krb5_conf_for_domain(
2052                 r->out.dns_domain_name, r->out.netbios_domain_name,
2053                 NULL, smbXcli_conn_remote_sockaddr(cli->conn),
2054                 smbXcli_conn_remote_name(cli->conn));
2055
2056         if (r->out.domain_is_ad && r->in.account_ou &&
2057             !(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE)) {
2058
2059                 ads_status = libnet_join_connect_ads(mem_ctx, r);
2060                 if (!ADS_ERR_OK(ads_status)) {
2061                         return WERR_DEFAULT_JOIN_REQUIRED;
2062                 }
2063
2064                 ads_status = libnet_join_precreate_machine_acct(mem_ctx, r);
2065                 if (!ADS_ERR_OK(ads_status)) {
2066                         libnet_join_set_error_string(mem_ctx, r,
2067                                 "failed to precreate account in ou %s: %s",
2068                                 r->in.account_ou,
2069                                 ads_errstr(ads_status));
2070                         return WERR_DEFAULT_JOIN_REQUIRED;
2071                 }
2072
2073                 r->in.join_flags &= ~WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE;
2074         }
2075 #endif /* HAVE_ADS */
2076
2077         if ((r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_UNSECURE) &&
2078             (r->in.join_flags & WKSSVC_JOIN_FLAGS_MACHINE_PWD_PASSED)) {
2079                 status = libnet_join_joindomain_rpc_unsecure(mem_ctx, r, cli);
2080         } else {
2081                 status = libnet_join_joindomain_rpc(mem_ctx, r, cli);
2082         }
2083         if (!NT_STATUS_IS_OK(status)) {
2084                 libnet_join_set_error_string(mem_ctx, r,
2085                         "failed to join domain '%s' over rpc: %s",
2086                         r->in.domain_name, get_friendly_nt_error_msg(status));
2087                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
2088                         return WERR_SETUP_ALREADY_JOINED;
2089                 }
2090                 werr = ntstatus_to_werror(status);
2091                 goto done;
2092         }
2093
2094         if (!libnet_join_joindomain_store_secrets(mem_ctx, r)) {
2095                 werr = WERR_SETUP_NOT_JOINED;
2096                 goto done;
2097         }
2098
2099         werr = WERR_OK;
2100
2101  done:
2102         if (cli) {
2103                 cli_shutdown(cli);
2104         }
2105
2106         return werr;
2107 }
2108
2109 /****************************************************************
2110 ****************************************************************/
2111
2112 static WERROR libnet_join_rollback(TALLOC_CTX *mem_ctx,
2113                                    struct libnet_JoinCtx *r)
2114 {
2115         WERROR werr;
2116         struct libnet_UnjoinCtx *u = NULL;
2117
2118         werr = libnet_init_UnjoinCtx(mem_ctx, &u);
2119         if (!W_ERROR_IS_OK(werr)) {
2120                 return werr;
2121         }
2122
2123         u->in.debug             = r->in.debug;
2124         u->in.dc_name           = r->in.dc_name;
2125         u->in.domain_name       = r->in.domain_name;
2126         u->in.admin_account     = r->in.admin_account;
2127         u->in.admin_password    = r->in.admin_password;
2128         u->in.modify_config     = r->in.modify_config;
2129         u->in.use_kerberos      = r->in.use_kerberos;
2130         u->in.unjoin_flags      = WKSSVC_JOIN_FLAGS_JOIN_TYPE |
2131                                   WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE;
2132
2133         werr = libnet_Unjoin(mem_ctx, u);
2134         TALLOC_FREE(u);
2135
2136         return werr;
2137 }
2138
2139 /****************************************************************
2140 ****************************************************************/
2141
2142 WERROR libnet_Join(TALLOC_CTX *mem_ctx,
2143                    struct libnet_JoinCtx *r)
2144 {
2145         WERROR werr;
2146
2147         if (r->in.debug) {
2148                 LIBNET_JOIN_IN_DUMP_CTX(mem_ctx, r);
2149         }
2150
2151         ZERO_STRUCT(r->out);
2152
2153         werr = libnet_join_pre_processing(mem_ctx, r);
2154         if (!W_ERROR_IS_OK(werr)) {
2155                 goto done;
2156         }
2157
2158         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
2159                 werr = libnet_DomainJoin(mem_ctx, r);
2160                 if (!W_ERROR_IS_OK(werr)) {
2161                         goto done;
2162                 }
2163         }
2164
2165         werr = libnet_join_post_processing(mem_ctx, r);
2166         if (!W_ERROR_IS_OK(werr)) {
2167                 goto done;
2168         }
2169
2170         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
2171                 werr = libnet_join_post_verify(mem_ctx, r);
2172                 if (!W_ERROR_IS_OK(werr)) {
2173                         libnet_join_rollback(mem_ctx, r);
2174                 }
2175         }
2176
2177  done:
2178         r->out.result = werr;
2179
2180         if (r->in.debug) {
2181                 LIBNET_JOIN_OUT_DUMP_CTX(mem_ctx, r);
2182         }
2183         return werr;
2184 }
2185
2186 /****************************************************************
2187 ****************************************************************/
2188
2189 static WERROR libnet_DomainUnjoin(TALLOC_CTX *mem_ctx,
2190                                   struct libnet_UnjoinCtx *r)
2191 {
2192         NTSTATUS status;
2193
2194         if (!r->in.domain_sid) {
2195                 struct dom_sid sid;
2196                 if (!secrets_fetch_domain_sid(lp_workgroup(), &sid)) {
2197                         libnet_unjoin_set_error_string(mem_ctx, r,
2198                                 "Unable to fetch domain sid: are we joined?");
2199                         return WERR_SETUP_NOT_JOINED;
2200                 }
2201                 r->in.domain_sid = dom_sid_dup(mem_ctx, &sid);
2202                 W_ERROR_HAVE_NO_MEMORY(r->in.domain_sid);
2203         }
2204
2205         if (!(r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE) && 
2206             !r->in.delete_machine_account) {
2207                 libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2208                 return WERR_OK;
2209         }
2210
2211         if (!r->in.dc_name) {
2212                 struct netr_DsRGetDCNameInfo *info;
2213                 const char *dc;
2214                 status = dsgetdcname(mem_ctx,
2215                                      r->in.msg_ctx,
2216                                      r->in.domain_name,
2217                                      NULL,
2218                                      NULL,
2219                                      DS_DIRECTORY_SERVICE_REQUIRED |
2220                                      DS_WRITABLE_REQUIRED |
2221                                      DS_RETURN_DNS_NAME,
2222                                      &info);
2223                 if (!NT_STATUS_IS_OK(status)) {
2224                         libnet_unjoin_set_error_string(mem_ctx, r,
2225                                 "failed to find DC for domain %s",
2226                                 r->in.domain_name,
2227                                 get_friendly_nt_error_msg(status));
2228                         return WERR_DCNOTFOUND;
2229                 }
2230
2231                 dc = strip_hostname(info->dc_unc);
2232                 r->in.dc_name = talloc_strdup(mem_ctx, dc);
2233                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
2234         }
2235
2236 #ifdef HAVE_ADS
2237         /* for net ads leave, try to delete the account.  If it works, 
2238            no sense in disabling.  If it fails, we can still try to 
2239            disable it. jmcd */
2240
2241         if (r->in.delete_machine_account) {
2242                 ADS_STATUS ads_status;
2243                 ads_status = libnet_unjoin_connect_ads(mem_ctx, r);
2244                 if (ADS_ERR_OK(ads_status)) {
2245                         /* dirty hack */
2246                         r->out.dns_domain_name = 
2247                                 talloc_strdup(mem_ctx,
2248                                               r->in.ads->server.realm);
2249                         ads_status = 
2250                                 libnet_unjoin_remove_machine_acct(mem_ctx, r);
2251                 }
2252                 if (!ADS_ERR_OK(ads_status)) {
2253                         libnet_unjoin_set_error_string(mem_ctx, r,
2254                                 "failed to remove machine account from AD: %s",
2255                                 ads_errstr(ads_status));
2256                 } else {
2257                         r->out.deleted_machine_account = true;
2258                         W_ERROR_HAVE_NO_MEMORY(r->out.dns_domain_name);
2259                         libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2260                         return WERR_OK;
2261                 }
2262         }
2263 #endif /* HAVE_ADS */
2264
2265         /* The WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE flag really means 
2266            "disable".  */
2267         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE) {
2268                 status = libnet_join_unjoindomain_rpc(mem_ctx, r);
2269                 if (!NT_STATUS_IS_OK(status)) {
2270                         libnet_unjoin_set_error_string(mem_ctx, r,
2271                                 "failed to disable machine account via rpc: %s",
2272                                 get_friendly_nt_error_msg(status));
2273                         if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER)) {
2274                                 return WERR_SETUP_NOT_JOINED;
2275                         }
2276                         return ntstatus_to_werror(status);
2277                 }
2278
2279                 r->out.disabled_machine_account = true;
2280         }
2281
2282         /* If disable succeeded or was not requested at all, we 
2283            should be getting rid of our end of things */
2284
2285         libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
2286
2287         return WERR_OK;
2288 }
2289
2290 /****************************************************************
2291 ****************************************************************/
2292
2293 static WERROR libnet_unjoin_pre_processing(TALLOC_CTX *mem_ctx,
2294                                            struct libnet_UnjoinCtx *r)
2295 {
2296         if (!r->in.domain_name) {
2297                 libnet_unjoin_set_error_string(mem_ctx, r,
2298                         "No domain name defined");
2299                 return WERR_INVALID_PARAM;
2300         }
2301
2302         if (!libnet_parse_domain_dc(mem_ctx, r->in.domain_name,
2303                                     &r->in.domain_name,
2304                                     &r->in.dc_name)) {
2305                 libnet_unjoin_set_error_string(mem_ctx, r,
2306                         "Failed to parse domain name");
2307                 return WERR_INVALID_PARAM;
2308         }
2309
2310         if (IS_DC) {
2311                 return WERR_SETUP_DOMAIN_CONTROLLER;
2312         }
2313
2314         if (!r->in.admin_domain) {
2315                 char *admin_domain = NULL;
2316                 char *admin_account = NULL;
2317                 split_domain_user(mem_ctx,
2318                                   r->in.admin_account,
2319                                   &admin_domain,
2320                                   &admin_account);
2321                 r->in.admin_domain = admin_domain;
2322                 r->in.admin_account = admin_account;
2323         }
2324
2325         if (!secrets_init()) {
2326                 libnet_unjoin_set_error_string(mem_ctx, r,
2327                         "Unable to open secrets database");
2328                 return WERR_CAN_NOT_COMPLETE;
2329         }
2330
2331         return WERR_OK;
2332 }
2333
2334 /****************************************************************
2335 ****************************************************************/
2336
2337 static WERROR libnet_unjoin_post_processing(TALLOC_CTX *mem_ctx,
2338                                             struct libnet_UnjoinCtx *r)
2339 {
2340         saf_delete(r->out.netbios_domain_name);
2341         saf_delete(r->out.dns_domain_name);
2342
2343         return libnet_unjoin_config(r);
2344 }
2345
2346 /****************************************************************
2347 ****************************************************************/
2348
2349 WERROR libnet_Unjoin(TALLOC_CTX *mem_ctx,
2350                      struct libnet_UnjoinCtx *r)
2351 {
2352         WERROR werr;
2353
2354         if (r->in.debug) {
2355                 LIBNET_UNJOIN_IN_DUMP_CTX(mem_ctx, r);
2356         }
2357
2358         werr = libnet_unjoin_pre_processing(mem_ctx, r);
2359         if (!W_ERROR_IS_OK(werr)) {
2360                 goto done;
2361         }
2362
2363         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
2364                 werr = libnet_DomainUnjoin(mem_ctx, r);
2365                 if (!W_ERROR_IS_OK(werr)) {
2366                         libnet_unjoin_config(r);
2367                         goto done;
2368                 }
2369         }
2370
2371         werr = libnet_unjoin_post_processing(mem_ctx, r);
2372         if (!W_ERROR_IS_OK(werr)) {
2373                 goto done;
2374         }
2375
2376  done:
2377         r->out.result = werr;
2378
2379         if (r->in.debug) {
2380                 LIBNET_UNJOIN_OUT_DUMP_CTX(mem_ctx, r);
2381         }
2382
2383         return werr;
2384 }