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