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