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