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