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