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