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