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