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