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