libnetjoin: Fix unjoining when no KRB5CCNAME is around.
[vlendec/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 "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(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->in.domain_name,
146                                     r->in.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)) {
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  Do the domain join
646 ****************************************************************/
647
648 static NTSTATUS libnet_join_joindomain_rpc(TALLOC_CTX *mem_ctx,
649                                            struct libnet_JoinCtx *r)
650 {
651         struct cli_state *cli = NULL;
652         struct rpc_pipe_client *pipe_hnd = NULL;
653         POLICY_HND sam_pol, domain_pol, user_pol, lsa_pol;
654         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
655         char *acct_name;
656         struct lsa_String lsa_acct_name;
657         uint32_t user_rid;
658         uint32_t acct_flags = ACB_WSTRUST;
659         uchar pwbuf[532];
660         struct MD5Context md5ctx;
661         uchar md5buffer[16];
662         DATA_BLOB digested_session_key;
663         uchar md4_trust_password[16];
664         union lsa_PolicyInformation *info = NULL;
665         struct samr_Ids user_rids;
666         struct samr_Ids name_types;
667         union samr_UserInfo user_info;
668
669         if (!r->in.machine_password) {
670                 r->in.machine_password = talloc_strdup(mem_ctx, generate_random_str(DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH));
671                 NT_STATUS_HAVE_NO_MEMORY(r->in.machine_password);
672         }
673
674         status = cli_full_connection(&cli, NULL,
675                                      r->in.dc_name,
676                                      NULL, 0,
677                                      "IPC$", "IPC",
678                                      r->in.admin_account,
679                                      NULL,
680                                      r->in.admin_password,
681                                      0,
682                                      Undefined, NULL);
683
684         if (!NT_STATUS_IS_OK(status)) {
685                 goto done;
686         }
687
688         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_LSARPC, &status);
689         if (!pipe_hnd) {
690                 DEBUG(0,("Error connecting to LSA pipe. Error was %s\n",
691                         nt_errstr(status)));
692                 goto done;
693         }
694
695         status = rpccli_lsa_open_policy(pipe_hnd, mem_ctx, true,
696                                         SEC_RIGHTS_MAXIMUM_ALLOWED, &lsa_pol);
697         if (!NT_STATUS_IS_OK(status)) {
698                 goto done;
699         }
700
701         status = rpccli_lsa_QueryInfoPolicy2(pipe_hnd, mem_ctx,
702                                              &lsa_pol,
703                                              LSA_POLICY_INFO_DNS,
704                                              &info);
705         if (NT_STATUS_IS_OK(status)) {
706                 r->out.domain_is_ad = true;
707                 r->out.netbios_domain_name = info->dns.name.string;
708                 r->out.dns_domain_name = info->dns.dns_domain.string;
709                 r->out.domain_sid = info->dns.sid;
710         }
711
712         if (!NT_STATUS_IS_OK(status)) {
713                 status = rpccli_lsa_QueryInfoPolicy(pipe_hnd, mem_ctx,
714                                                     &lsa_pol,
715                                                     LSA_POLICY_INFO_ACCOUNT_DOMAIN,
716                                                     &info);
717                 if (!NT_STATUS_IS_OK(status)) {
718                         goto done;
719                 }
720
721                 r->out.netbios_domain_name = info->account_domain.name.string;
722                 r->out.domain_sid = info->account_domain.sid;
723         }
724
725         rpccli_lsa_Close(pipe_hnd, mem_ctx, &lsa_pol);
726         cli_rpc_pipe_close(pipe_hnd);
727
728         /* Open the domain */
729
730         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SAMR, &status);
731         if (!pipe_hnd) {
732                 DEBUG(0,("Error connecting to SAM pipe. Error was %s\n",
733                         nt_errstr(status)));
734                 goto done;
735         }
736
737         status = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
738                                       pipe_hnd->cli->desthost,
739                                       SEC_RIGHTS_MAXIMUM_ALLOWED,
740                                       &sam_pol);
741         if (!NT_STATUS_IS_OK(status)) {
742                 goto done;
743         }
744
745         status = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
746                                         &sam_pol,
747                                         SEC_RIGHTS_MAXIMUM_ALLOWED,
748                                         r->out.domain_sid,
749                                         &domain_pol);
750         if (!NT_STATUS_IS_OK(status)) {
751                 goto done;
752         }
753
754         /* Create domain user */
755
756         acct_name = talloc_asprintf(mem_ctx, "%s$", r->in.machine_name);
757         strlower_m(acct_name);
758
759         init_lsa_String(&lsa_acct_name, acct_name);
760
761         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE) {
762                 uint32_t access_desired =
763                         SEC_GENERIC_READ | SEC_GENERIC_WRITE | SEC_GENERIC_EXECUTE |
764                         SEC_STD_WRITE_DAC | SEC_STD_DELETE |
765                         SAMR_USER_ACCESS_SET_PASSWORD |
766                         SAMR_USER_ACCESS_GET_ATTRIBUTES |
767                         SAMR_USER_ACCESS_SET_ATTRIBUTES;
768                 uint32_t access_granted = 0;
769
770                 /* Don't try to set any acct_flags flags other than ACB_WSTRUST */
771
772                 DEBUG(10,("Creating account with desired access mask: %d\n",
773                         access_desired));
774
775                 status = rpccli_samr_CreateUser2(pipe_hnd, mem_ctx,
776                                                  &domain_pol,
777                                                  &lsa_acct_name,
778                                                  ACB_WSTRUST,
779                                                  access_desired,
780                                                  &user_pol,
781                                                  &access_granted,
782                                                  &user_rid);
783                 if (!NT_STATUS_IS_OK(status) &&
784                     !NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
785
786                         DEBUG(10,("Creation of workstation account failed: %s\n",
787                                 nt_errstr(status)));
788
789                         /* If NT_STATUS_ACCESS_DENIED then we have a valid
790                            username/password combo but the user does not have
791                            administrator access. */
792
793                         if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
794                                 libnet_join_set_error_string(mem_ctx, r,
795                                         "User specified does not have "
796                                         "administrator privileges");
797                         }
798
799                         return status;
800                 }
801
802                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
803                         if (!(r->in.join_flags &
804                               WKSSVC_JOIN_FLAGS_DOMAIN_JOIN_IF_JOINED)) {
805                                 goto done;
806                         }
807                 }
808
809                 /* We *must* do this.... don't ask... */
810
811                 if (NT_STATUS_IS_OK(status)) {
812                         rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
813                 }
814         }
815
816         status = rpccli_samr_LookupNames(pipe_hnd, mem_ctx,
817                                          &domain_pol,
818                                          1,
819                                          &lsa_acct_name,
820                                          &user_rids,
821                                          &name_types);
822         if (!NT_STATUS_IS_OK(status)) {
823                 goto done;
824         }
825
826         if (name_types.ids[0] != SID_NAME_USER) {
827                 DEBUG(0,("%s is not a user account (type=%d)\n",
828                         acct_name, name_types.ids[0]));
829                 status = NT_STATUS_INVALID_WORKSTATION;
830                 goto done;
831         }
832
833         user_rid = user_rids.ids[0];
834
835         /* Open handle on user */
836
837         status = rpccli_samr_OpenUser(pipe_hnd, mem_ctx,
838                                       &domain_pol,
839                                       SEC_RIGHTS_MAXIMUM_ALLOWED,
840                                       user_rid,
841                                       &user_pol);
842         if (!NT_STATUS_IS_OK(status)) {
843                 goto done;
844         }
845
846         /* Create a random machine account password and generate the hash */
847
848         E_md4hash(r->in.machine_password, md4_trust_password);
849         encode_pw_buffer(pwbuf, r->in.machine_password, STR_UNICODE);
850
851         generate_random_buffer((uint8_t*)md5buffer, sizeof(md5buffer));
852         digested_session_key = data_blob_talloc(mem_ctx, 0, 16);
853
854         MD5Init(&md5ctx);
855         MD5Update(&md5ctx, md5buffer, sizeof(md5buffer));
856         MD5Update(&md5ctx, cli->user_session_key.data,
857                   cli->user_session_key.length);
858         MD5Final(digested_session_key.data, &md5ctx);
859
860         SamOEMhashBlob(pwbuf, sizeof(pwbuf), &digested_session_key);
861         memcpy(&pwbuf[516], md5buffer, sizeof(md5buffer));
862
863         /* Fill in the additional account flags now */
864
865         acct_flags |= ACB_PWNOEXP;
866         if (r->out.domain_is_ad) {
867 #if !defined(ENCTYPE_ARCFOUR_HMAC)
868                 acct_flags |= ACB_USE_DES_KEY_ONLY;
869 #endif
870                 ;;
871         }
872
873         /* Set password and account flags on machine account */
874
875         ZERO_STRUCT(user_info.info25);
876
877         user_info.info25.info.fields_present = ACCT_NT_PWD_SET |
878                                                ACCT_LM_PWD_SET |
879                                                SAMR_FIELD_ACCT_FLAGS;
880
881         user_info.info25.info.acct_flags = acct_flags;
882         memcpy(&user_info.info25.password.data, pwbuf, sizeof(pwbuf));
883
884         status = rpccli_samr_SetUserInfo(pipe_hnd, mem_ctx,
885                                          &user_pol,
886                                          25,
887                                          &user_info);
888
889         if (NT_STATUS_EQUAL(status, NT_STATUS(DCERPC_FAULT_INVALID_TAG))) {
890
891                 uchar pwbuf2[516];
892
893                 encode_pw_buffer(pwbuf2, r->in.machine_password, STR_UNICODE);
894
895                 /* retry with level 24 */
896                 init_samr_user_info24(&user_info.info24, pwbuf2, 24);
897
898                 SamOEMhashBlob(user_info.info24.password.data, 516,
899                                &cli->user_session_key);
900
901                 status = rpccli_samr_SetUserInfo2(pipe_hnd, mem_ctx,
902                                                   &user_pol,
903                                                   24,
904                                                   &user_info);
905         }
906
907         if (!NT_STATUS_IS_OK(status)) {
908
909                 rpccli_samr_DeleteUser(pipe_hnd, mem_ctx,
910                                        &user_pol);
911
912                 libnet_join_set_error_string(mem_ctx, r,
913                         "Failed to set password for machine account (%s)\n",
914                         nt_errstr(status));
915                 goto done;
916         }
917
918         rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
919         cli_rpc_pipe_close(pipe_hnd);
920
921         status = NT_STATUS_OK;
922  done:
923         if (cli) {
924                 cli_shutdown(cli);
925         }
926
927         return status;
928 }
929
930 /****************************************************************
931 ****************************************************************/
932
933 NTSTATUS libnet_join_ok(const char *netbios_domain_name,
934                         const char *machine_name,
935                         const char *dc_name)
936 {
937         uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
938         struct cli_state *cli = NULL;
939         struct rpc_pipe_client *pipe_hnd = NULL;
940         struct rpc_pipe_client *netlogon_pipe = NULL;
941         NTSTATUS status;
942         char *machine_password = NULL;
943         char *machine_account = NULL;
944
945         if (!dc_name) {
946                 return NT_STATUS_INVALID_PARAMETER;
947         }
948
949         if (!secrets_init()) {
950                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
951         }
952
953         machine_password = secrets_fetch_machine_password(netbios_domain_name,
954                                                           NULL, NULL);
955         if (!machine_password) {
956                 return NT_STATUS_NO_TRUST_LSA_SECRET;
957         }
958
959         asprintf(&machine_account, "%s$", machine_name);
960         if (!machine_account) {
961                 SAFE_FREE(machine_password);
962                 return NT_STATUS_NO_MEMORY;
963         }
964
965         status = cli_full_connection(&cli, NULL,
966                                      dc_name,
967                                      NULL, 0,
968                                      "IPC$", "IPC",
969                                      machine_account,
970                                      NULL,
971                                      machine_password,
972                                      0,
973                                      Undefined, NULL);
974         free(machine_account);
975         free(machine_password);
976
977         if (!NT_STATUS_IS_OK(status)) {
978                 status = cli_full_connection(&cli, NULL,
979                                              dc_name,
980                                              NULL, 0,
981                                              "IPC$", "IPC",
982                                              "",
983                                              NULL,
984                                              "",
985                                              0,
986                                              Undefined, NULL);
987         }
988
989         if (!NT_STATUS_IS_OK(status)) {
990                 return status;
991         }
992
993         netlogon_pipe = get_schannel_session_key(cli,
994                                                  netbios_domain_name,
995                                                  &neg_flags, &status);
996         if (!netlogon_pipe) {
997                 if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_NETWORK_RESPONSE)) {
998                         cli_shutdown(cli);
999                         return NT_STATUS_OK;
1000                 }
1001
1002                 DEBUG(0,("libnet_join_ok: failed to get schannel session "
1003                         "key from server %s for domain %s. Error was %s\n",
1004                 cli->desthost, netbios_domain_name, nt_errstr(status)));
1005                 cli_shutdown(cli);
1006                 return status;
1007         }
1008
1009         if (!lp_client_schannel()) {
1010                 cli_shutdown(cli);
1011                 return NT_STATUS_OK;
1012         }
1013
1014         pipe_hnd = cli_rpc_pipe_open_schannel_with_key(cli, PI_NETLOGON,
1015                                                        PIPE_AUTH_LEVEL_PRIVACY,
1016                                                        netbios_domain_name,
1017                                                        netlogon_pipe->dc,
1018                                                        &status);
1019
1020         cli_shutdown(cli);
1021
1022         if (!pipe_hnd) {
1023                 DEBUG(0,("libnet_join_ok: failed to open schannel session "
1024                         "on netlogon pipe to server %s for domain %s. "
1025                         "Error was %s\n",
1026                         cli->desthost, netbios_domain_name, nt_errstr(status)));
1027                 return status;
1028         }
1029
1030         return NT_STATUS_OK;
1031 }
1032
1033 /****************************************************************
1034 ****************************************************************/
1035
1036 static WERROR libnet_join_post_verify(TALLOC_CTX *mem_ctx,
1037                                       struct libnet_JoinCtx *r)
1038 {
1039         NTSTATUS status;
1040
1041         status = libnet_join_ok(r->out.netbios_domain_name,
1042                                 r->in.machine_name,
1043                                 r->in.dc_name);
1044         if (!NT_STATUS_IS_OK(status)) {
1045                 libnet_join_set_error_string(mem_ctx, r,
1046                         "failed to verify domain membership after joining: %s",
1047                         get_friendly_nt_error_msg(status));
1048                 return WERR_SETUP_NOT_JOINED;
1049         }
1050
1051         return WERR_OK;
1052 }
1053
1054 /****************************************************************
1055 ****************************************************************/
1056
1057 static bool libnet_join_unjoindomain_remove_secrets(TALLOC_CTX *mem_ctx,
1058                                                     struct libnet_UnjoinCtx *r)
1059 {
1060         if (!secrets_delete_machine_password_ex(lp_workgroup())) {
1061                 return false;
1062         }
1063
1064         if (!secrets_delete_domain_sid(lp_workgroup())) {
1065                 return false;
1066         }
1067
1068         return true;
1069 }
1070
1071 /****************************************************************
1072 ****************************************************************/
1073
1074 static NTSTATUS libnet_join_unjoindomain_rpc(TALLOC_CTX *mem_ctx,
1075                                              struct libnet_UnjoinCtx *r)
1076 {
1077         struct cli_state *cli = NULL;
1078         struct rpc_pipe_client *pipe_hnd = NULL;
1079         POLICY_HND sam_pol, domain_pol, user_pol;
1080         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1081         char *acct_name;
1082         uint32_t user_rid;
1083         struct lsa_String lsa_acct_name;
1084         struct samr_Ids user_rids;
1085         struct samr_Ids name_types;
1086         union samr_UserInfo *info = NULL;
1087
1088         status = cli_full_connection(&cli, NULL,
1089                                      r->in.dc_name,
1090                                      NULL, 0,
1091                                      "IPC$", "IPC",
1092                                      r->in.admin_account,
1093                                      NULL,
1094                                      r->in.admin_password,
1095                                      0, Undefined, NULL);
1096
1097         if (!NT_STATUS_IS_OK(status)) {
1098                 goto done;
1099         }
1100
1101         /* Open the domain */
1102
1103         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SAMR, &status);
1104         if (!pipe_hnd) {
1105                 DEBUG(0,("Error connecting to SAM pipe. Error was %s\n",
1106                         nt_errstr(status)));
1107                 goto done;
1108         }
1109
1110         status = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
1111                                       pipe_hnd->cli->desthost,
1112                                       SEC_RIGHTS_MAXIMUM_ALLOWED,
1113                                       &sam_pol);
1114         if (!NT_STATUS_IS_OK(status)) {
1115                 goto done;
1116         }
1117
1118         status = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
1119                                         &sam_pol,
1120                                         SEC_RIGHTS_MAXIMUM_ALLOWED,
1121                                         r->in.domain_sid,
1122                                         &domain_pol);
1123         if (!NT_STATUS_IS_OK(status)) {
1124                 goto done;
1125         }
1126
1127         /* Create domain user */
1128
1129         acct_name = talloc_asprintf(mem_ctx, "%s$", r->in.machine_name);
1130         strlower_m(acct_name);
1131
1132         init_lsa_String(&lsa_acct_name, acct_name);
1133
1134         status = rpccli_samr_LookupNames(pipe_hnd, mem_ctx,
1135                                          &domain_pol,
1136                                          1,
1137                                          &lsa_acct_name,
1138                                          &user_rids,
1139                                          &name_types);
1140
1141         if (!NT_STATUS_IS_OK(status)) {
1142                 goto done;
1143         }
1144
1145         if (name_types.ids[0] != SID_NAME_USER) {
1146                 DEBUG(0, ("%s is not a user account (type=%d)\n", acct_name,
1147                         name_types.ids[0]));
1148                 status = NT_STATUS_INVALID_WORKSTATION;
1149                 goto done;
1150         }
1151
1152         user_rid = user_rids.ids[0];
1153
1154         /* Open handle on user */
1155
1156         status = rpccli_samr_OpenUser(pipe_hnd, mem_ctx,
1157                                       &domain_pol,
1158                                       SEC_RIGHTS_MAXIMUM_ALLOWED,
1159                                       user_rid,
1160                                       &user_pol);
1161         if (!NT_STATUS_IS_OK(status)) {
1162                 goto done;
1163         }
1164
1165         /* Get user info */
1166
1167         status = rpccli_samr_QueryUserInfo(pipe_hnd, mem_ctx,
1168                                            &user_pol,
1169                                            16,
1170                                            &info);
1171         if (!NT_STATUS_IS_OK(status)) {
1172                 rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
1173                 goto done;
1174         }
1175
1176         /* now disable and setuser info */
1177
1178         info->info16.acct_flags |= ACB_DISABLED;
1179
1180         status = rpccli_samr_SetUserInfo(pipe_hnd, mem_ctx,
1181                                          &user_pol,
1182                                          16,
1183                                          info);
1184
1185         rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
1186
1187 done:
1188         if (pipe_hnd) {
1189                 rpccli_samr_Close(pipe_hnd, mem_ctx, &domain_pol);
1190                 rpccli_samr_Close(pipe_hnd, mem_ctx, &sam_pol);
1191                 cli_rpc_pipe_close(pipe_hnd);
1192         }
1193
1194         if (cli) {
1195                 cli_shutdown(cli);
1196         }
1197
1198         return status;
1199 }
1200
1201 /****************************************************************
1202 ****************************************************************/
1203
1204 static WERROR do_join_modify_vals_config(struct libnet_JoinCtx *r)
1205 {
1206         WERROR werr;
1207         struct smbconf_ctx *ctx;
1208
1209         werr = smbconf_init_reg(r, &ctx, NULL);
1210         if (!W_ERROR_IS_OK(werr)) {
1211                 goto done;
1212         }
1213
1214         if (!(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE)) {
1215
1216                 werr = smbconf_set_global_parameter(ctx, "security", "user");
1217                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1218
1219                 werr = smbconf_set_global_parameter(ctx, "workgroup",
1220                                                     r->in.domain_name);
1221                 goto done;
1222         }
1223
1224         werr = smbconf_set_global_parameter(ctx, "security", "domain");
1225         W_ERROR_NOT_OK_GOTO_DONE(werr);
1226
1227         werr = smbconf_set_global_parameter(ctx, "workgroup",
1228                                             r->out.netbios_domain_name);
1229         W_ERROR_NOT_OK_GOTO_DONE(werr);
1230
1231         if (r->out.domain_is_ad) {
1232                 werr = smbconf_set_global_parameter(ctx, "security", "ads");
1233                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1234
1235                 werr = smbconf_set_global_parameter(ctx, "realm",
1236                                                     r->out.dns_domain_name);
1237                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1238         }
1239
1240  done:
1241         smbconf_shutdown(ctx);
1242         return werr;
1243 }
1244
1245 /****************************************************************
1246 ****************************************************************/
1247
1248 static WERROR do_unjoin_modify_vals_config(struct libnet_UnjoinCtx *r)
1249 {
1250         WERROR werr = WERR_OK;
1251         struct smbconf_ctx *ctx;
1252
1253         werr = smbconf_init_reg(r, &ctx, NULL);
1254         if (!W_ERROR_IS_OK(werr)) {
1255                 goto done;
1256         }
1257
1258         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1259
1260                 werr = smbconf_set_global_parameter(ctx, "security", "user");
1261                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1262                 smbconf_delete_global_parameter(ctx, "realm");
1263         }
1264
1265  done:
1266         smbconf_shutdown(ctx);
1267         return werr;
1268 }
1269
1270 /****************************************************************
1271 ****************************************************************/
1272
1273 static WERROR do_JoinConfig(struct libnet_JoinCtx *r)
1274 {
1275         WERROR werr;
1276
1277         if (!W_ERROR_IS_OK(r->out.result)) {
1278                 return r->out.result;
1279         }
1280
1281         if (!r->in.modify_config) {
1282                 return WERR_OK;
1283         }
1284
1285         werr = do_join_modify_vals_config(r);
1286         if (!W_ERROR_IS_OK(werr)) {
1287                 return werr;
1288         }
1289
1290         r->out.modified_config = true;
1291         r->out.result = werr;
1292
1293         return werr;
1294 }
1295
1296 /****************************************************************
1297 ****************************************************************/
1298
1299 static WERROR libnet_unjoin_config(struct libnet_UnjoinCtx *r)
1300 {
1301         WERROR werr;
1302
1303         if (!W_ERROR_IS_OK(r->out.result)) {
1304                 return r->out.result;
1305         }
1306
1307         if (!r->in.modify_config) {
1308                 return WERR_OK;
1309         }
1310
1311         werr = do_unjoin_modify_vals_config(r);
1312         if (!W_ERROR_IS_OK(werr)) {
1313                 return werr;
1314         }
1315
1316         r->out.modified_config = true;
1317         r->out.result = werr;
1318
1319         return werr;
1320 }
1321
1322 /****************************************************************
1323 ****************************************************************/
1324
1325 static bool libnet_parse_domain_dc(TALLOC_CTX *mem_ctx,
1326                                    const char *domain_str,
1327                                    const char **domain_p,
1328                                    const char **dc_p)
1329 {
1330         char *domain = NULL;
1331         char *dc = NULL;
1332         const char *p = NULL;
1333
1334         if (!domain_str || !domain_p || !dc_p) {
1335                 return false;
1336         }
1337
1338         p = strchr_m(domain_str, '\\');
1339
1340         if (p != NULL) {
1341                 domain = talloc_strndup(mem_ctx, domain_str,
1342                                          PTR_DIFF(p, domain_str));
1343                 dc = talloc_strdup(mem_ctx, p+1);
1344                 if (!dc) {
1345                         return false;
1346                 }
1347         } else {
1348                 domain = talloc_strdup(mem_ctx, domain_str);
1349                 dc = NULL;
1350         }
1351         if (!domain) {
1352                 return false;
1353         }
1354
1355         *domain_p = domain;
1356
1357         if (!*dc_p && dc) {
1358                 *dc_p = dc;
1359         }
1360
1361         return true;
1362 }
1363
1364 /****************************************************************
1365 ****************************************************************/
1366
1367 static WERROR libnet_join_pre_processing(TALLOC_CTX *mem_ctx,
1368                                          struct libnet_JoinCtx *r)
1369 {
1370         if (!r->in.domain_name) {
1371                 libnet_join_set_error_string(mem_ctx, r,
1372                         "No domain name defined");
1373                 return WERR_INVALID_PARAM;
1374         }
1375
1376         if (!libnet_parse_domain_dc(mem_ctx, r->in.domain_name,
1377                                     &r->in.domain_name,
1378                                     &r->in.dc_name)) {
1379                 libnet_join_set_error_string(mem_ctx, r,
1380                         "Failed to parse domain name");
1381                 return WERR_INVALID_PARAM;
1382         }
1383
1384         if (r->in.modify_config && !lp_config_backend_is_registry()) {
1385                 libnet_join_set_error_string(mem_ctx, r,
1386                         "Configuration manipulation requested but not "
1387                         "supported by backend");
1388                 return WERR_NOT_SUPPORTED;
1389         }
1390
1391         if (IS_DC) {
1392                 return WERR_SETUP_DOMAIN_CONTROLLER;
1393         }
1394
1395         if (!secrets_init()) {
1396                 libnet_join_set_error_string(mem_ctx, r,
1397                         "Unable to open secrets database");
1398                 return WERR_CAN_NOT_COMPLETE;
1399         }
1400
1401         return WERR_OK;
1402 }
1403
1404 /****************************************************************
1405 ****************************************************************/
1406
1407 static WERROR libnet_join_post_processing(TALLOC_CTX *mem_ctx,
1408                                           struct libnet_JoinCtx *r)
1409 {
1410         WERROR werr;
1411
1412         if (!W_ERROR_IS_OK(r->out.result)) {
1413                 return r->out.result;
1414         }
1415
1416         werr = do_JoinConfig(r);
1417         if (!W_ERROR_IS_OK(werr)) {
1418                 return werr;
1419         }
1420
1421         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1422                 saf_store(r->in.domain_name, r->in.dc_name);
1423         }
1424
1425         return WERR_OK;
1426 }
1427
1428 /****************************************************************
1429 ****************************************************************/
1430
1431 static int libnet_destroy_JoinCtx(struct libnet_JoinCtx *r)
1432 {
1433         const char *krb5_cc_env = NULL;
1434
1435         if (r->in.ads) {
1436                 ads_destroy(&r->in.ads);
1437         }
1438
1439         krb5_cc_env = getenv(KRB5_ENV_CCNAME);
1440         if (krb5_cc_env && StrCaseCmp(krb5_cc_env, "MEMORY:libnetjoin")) {
1441                 unsetenv(KRB5_ENV_CCNAME);
1442         }
1443
1444         return 0;
1445 }
1446
1447 /****************************************************************
1448 ****************************************************************/
1449
1450 static int libnet_destroy_UnjoinCtx(struct libnet_UnjoinCtx *r)
1451 {
1452         const char *krb5_cc_env = NULL;
1453
1454         if (r->in.ads) {
1455                 ads_destroy(&r->in.ads);
1456         }
1457
1458         krb5_cc_env = getenv(KRB5_ENV_CCNAME);
1459         if (krb5_cc_env && StrCaseCmp(krb5_cc_env, "MEMORY:libnetjoin")) {
1460                 unsetenv(KRB5_ENV_CCNAME);
1461         }
1462
1463
1464         return 0;
1465 }
1466
1467 /****************************************************************
1468 ****************************************************************/
1469
1470 WERROR libnet_init_JoinCtx(TALLOC_CTX *mem_ctx,
1471                            struct libnet_JoinCtx **r)
1472 {
1473         struct libnet_JoinCtx *ctx;
1474         const char *krb5_cc_env = NULL;
1475
1476         ctx = talloc_zero(mem_ctx, struct libnet_JoinCtx);
1477         if (!ctx) {
1478                 return WERR_NOMEM;
1479         }
1480
1481         talloc_set_destructor(ctx, libnet_destroy_JoinCtx);
1482
1483         ctx->in.machine_name = talloc_strdup(mem_ctx, global_myname());
1484         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
1485
1486         krb5_cc_env = getenv(KRB5_ENV_CCNAME);
1487         if (!krb5_cc_env || (strlen(krb5_cc_env) == 0)) {
1488                 krb5_cc_env = talloc_strdup(mem_ctx, "MEMORY:libnetjoin");
1489                 W_ERROR_HAVE_NO_MEMORY(krb5_cc_env);
1490                 setenv(KRB5_ENV_CCNAME, krb5_cc_env, 1);
1491         }
1492
1493         ctx->in.secure_channel_type = SEC_CHAN_WKSTA;
1494
1495         *r = ctx;
1496
1497         return WERR_OK;
1498 }
1499
1500 /****************************************************************
1501 ****************************************************************/
1502
1503 WERROR libnet_init_UnjoinCtx(TALLOC_CTX *mem_ctx,
1504                              struct libnet_UnjoinCtx **r)
1505 {
1506         struct libnet_UnjoinCtx *ctx;
1507         const char *krb5_cc_env = NULL;
1508
1509         ctx = talloc_zero(mem_ctx, struct libnet_UnjoinCtx);
1510         if (!ctx) {
1511                 return WERR_NOMEM;
1512         }
1513
1514         talloc_set_destructor(ctx, libnet_destroy_UnjoinCtx);
1515
1516         ctx->in.machine_name = talloc_strdup(mem_ctx, global_myname());
1517         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
1518
1519         krb5_cc_env = getenv(KRB5_ENV_CCNAME);
1520         if (!krb5_cc_env || (strlen(krb5_cc_env) == 0)) {
1521                 krb5_cc_env = talloc_strdup(mem_ctx, "MEMORY:libnetjoin");
1522                 W_ERROR_HAVE_NO_MEMORY(krb5_cc_env);
1523                 setenv(KRB5_ENV_CCNAME, krb5_cc_env, 1);
1524         }
1525
1526         *r = ctx;
1527
1528         return WERR_OK;
1529 }
1530
1531 /****************************************************************
1532 ****************************************************************/
1533
1534 static WERROR libnet_DomainJoin(TALLOC_CTX *mem_ctx,
1535                                 struct libnet_JoinCtx *r)
1536 {
1537         NTSTATUS status;
1538 #ifdef WITH_ADS
1539         ADS_STATUS ads_status;
1540 #endif /* WITH_ADS */
1541
1542         if (!r->in.dc_name) {
1543                 struct netr_DsRGetDCNameInfo *info;
1544                 status = dsgetdcname(mem_ctx,
1545                                      r->in.domain_name,
1546                                      NULL,
1547                                      NULL,
1548                                      DS_DIRECTORY_SERVICE_REQUIRED |
1549                                      DS_WRITABLE_REQUIRED |
1550                                      DS_RETURN_DNS_NAME,
1551                                      &info);
1552                 if (!NT_STATUS_IS_OK(status)) {
1553                         libnet_join_set_error_string(mem_ctx, r,
1554                                 "failed to find DC for domain %s",
1555                                 r->in.domain_name,
1556                                 get_friendly_nt_error_msg(status));
1557                         return WERR_DOMAIN_CONTROLLER_NOT_FOUND;
1558                 }
1559
1560                 r->in.dc_name = talloc_strdup(mem_ctx,
1561                                               info->dc_unc);
1562                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
1563         }
1564
1565 #ifdef WITH_ADS
1566         if (r->in.account_ou) {
1567
1568                 ads_status = libnet_join_connect_ads(mem_ctx, r);
1569                 if (!ADS_ERR_OK(ads_status)) {
1570                         return WERR_DEFAULT_JOIN_REQUIRED;
1571                 }
1572
1573                 ads_status = libnet_join_precreate_machine_acct(mem_ctx, r);
1574                 if (!ADS_ERR_OK(ads_status)) {
1575                         libnet_join_set_error_string(mem_ctx, r,
1576                                 "failed to precreate account in ou %s: %s",
1577                                 r->in.account_ou,
1578                                 ads_errstr(ads_status));
1579                         return WERR_DEFAULT_JOIN_REQUIRED;
1580                 }
1581
1582                 r->in.join_flags &= ~WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE;
1583         }
1584 #endif /* WITH_ADS */
1585
1586         status = libnet_join_joindomain_rpc(mem_ctx, r);
1587         if (!NT_STATUS_IS_OK(status)) {
1588                 libnet_join_set_error_string(mem_ctx, r,
1589                         "failed to join domain over rpc: %s",
1590                         get_friendly_nt_error_msg(status));
1591                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
1592                         return WERR_SETUP_ALREADY_JOINED;
1593                 }
1594                 return ntstatus_to_werror(status);
1595         }
1596
1597         if (!libnet_join_joindomain_store_secrets(mem_ctx, r)) {
1598                 return WERR_SETUP_NOT_JOINED;
1599         }
1600
1601 #ifdef WITH_ADS
1602         if (r->out.domain_is_ad) {
1603                 ads_status  = libnet_join_post_processing_ads(mem_ctx, r);
1604                 if (!ADS_ERR_OK(ads_status)) {
1605                         return WERR_GENERAL_FAILURE;
1606                 }
1607         }
1608 #endif /* WITH_ADS */
1609
1610         return WERR_OK;
1611 }
1612
1613 /****************************************************************
1614 ****************************************************************/
1615
1616 WERROR libnet_Join(TALLOC_CTX *mem_ctx,
1617                    struct libnet_JoinCtx *r)
1618 {
1619         WERROR werr;
1620
1621         if (r->in.debug) {
1622                 LIBNET_JOIN_IN_DUMP_CTX(mem_ctx, r);
1623         }
1624
1625         werr = libnet_join_pre_processing(mem_ctx, r);
1626         if (!W_ERROR_IS_OK(werr)) {
1627                 goto done;
1628         }
1629
1630         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1631                 werr = libnet_DomainJoin(mem_ctx, r);
1632                 if (!W_ERROR_IS_OK(werr)) {
1633                         goto done;
1634                 }
1635
1636                 werr = libnet_join_post_verify(mem_ctx, r);
1637                 if (!W_ERROR_IS_OK(werr)) {
1638                         goto done;
1639                 }
1640         }
1641
1642         werr = libnet_join_post_processing(mem_ctx, r);
1643         if (!W_ERROR_IS_OK(werr)) {
1644                 goto done;
1645         }
1646  done:
1647         r->out.result = werr;
1648
1649         if (r->in.debug) {
1650                 LIBNET_JOIN_OUT_DUMP_CTX(mem_ctx, r);
1651         }
1652         return werr;
1653 }
1654
1655 /****************************************************************
1656 ****************************************************************/
1657
1658 static WERROR libnet_DomainUnjoin(TALLOC_CTX *mem_ctx,
1659                                   struct libnet_UnjoinCtx *r)
1660 {
1661         NTSTATUS status;
1662
1663         if (!r->in.domain_sid) {
1664                 struct dom_sid sid;
1665                 if (!secrets_fetch_domain_sid(lp_workgroup(), &sid)) {
1666                         libnet_unjoin_set_error_string(mem_ctx, r,
1667                                 "Unable to fetch domain sid: are we joined?");
1668                         return WERR_SETUP_NOT_JOINED;
1669                 }
1670                 r->in.domain_sid = sid_dup_talloc(mem_ctx, &sid);
1671                 W_ERROR_HAVE_NO_MEMORY(r->in.domain_sid);
1672         }
1673
1674         if (!r->in.dc_name) {
1675                 struct netr_DsRGetDCNameInfo *info;
1676                 status = dsgetdcname(mem_ctx,
1677                                      r->in.domain_name,
1678                                      NULL,
1679                                      NULL,
1680                                      DS_DIRECTORY_SERVICE_REQUIRED |
1681                                      DS_WRITABLE_REQUIRED |
1682                                      DS_RETURN_DNS_NAME,
1683                                      &info);
1684                 if (!NT_STATUS_IS_OK(status)) {
1685                         libnet_unjoin_set_error_string(mem_ctx, r,
1686                                 "failed to find DC for domain %s",
1687                                 r->in.domain_name,
1688                                 get_friendly_nt_error_msg(status));
1689                         return WERR_DOMAIN_CONTROLLER_NOT_FOUND;
1690                 }
1691
1692                 r->in.dc_name = talloc_strdup(mem_ctx,
1693                                               info->dc_unc);
1694                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
1695         }
1696
1697         status = libnet_join_unjoindomain_rpc(mem_ctx, r);
1698         if (!NT_STATUS_IS_OK(status)) {
1699                 libnet_unjoin_set_error_string(mem_ctx, r,
1700                         "failed to disable machine account via rpc: %s",
1701                         get_friendly_nt_error_msg(status));
1702                 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER)) {
1703                         return WERR_SETUP_NOT_JOINED;
1704                 }
1705                 return ntstatus_to_werror(status);
1706         }
1707
1708         r->out.disabled_machine_account = true;
1709
1710 #ifdef WITH_ADS
1711         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE) {
1712                 ADS_STATUS ads_status;
1713                 libnet_unjoin_connect_ads(mem_ctx, r);
1714                 ads_status = libnet_unjoin_remove_machine_acct(mem_ctx, r);
1715                 if (!ADS_ERR_OK(ads_status)) {
1716                         libnet_unjoin_set_error_string(mem_ctx, r,
1717                                 "failed to remove machine account from AD: %s",
1718                                 ads_errstr(ads_status));
1719                 } else {
1720                         r->out.deleted_machine_account = true;
1721                         /* dirty hack */
1722                         r->out.dns_domain_name = talloc_strdup(mem_ctx,
1723                                                                r->in.ads->server.realm);
1724                         W_ERROR_HAVE_NO_MEMORY(r->out.dns_domain_name);
1725                 }
1726         }
1727 #endif /* WITH_ADS */
1728
1729         libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
1730
1731         return WERR_OK;
1732 }
1733
1734 /****************************************************************
1735 ****************************************************************/
1736
1737 static WERROR libnet_unjoin_pre_processing(TALLOC_CTX *mem_ctx,
1738                                            struct libnet_UnjoinCtx *r)
1739 {
1740         if (!r->in.domain_name) {
1741                 libnet_unjoin_set_error_string(mem_ctx, r,
1742                         "No domain name defined");
1743                 return WERR_INVALID_PARAM;
1744         }
1745
1746         if (!libnet_parse_domain_dc(mem_ctx, r->in.domain_name,
1747                                     &r->in.domain_name,
1748                                     &r->in.dc_name)) {
1749                 libnet_unjoin_set_error_string(mem_ctx, r,
1750                         "Failed to parse domain name");
1751                 return WERR_INVALID_PARAM;
1752         }
1753
1754         if (r->in.modify_config && !lp_config_backend_is_registry()) {
1755                 libnet_unjoin_set_error_string(mem_ctx, r,
1756                         "Configuration manipulation requested but not "
1757                         "supported by backend");
1758                 return WERR_NOT_SUPPORTED;
1759         }
1760
1761         if (IS_DC) {
1762                 return WERR_SETUP_DOMAIN_CONTROLLER;
1763         }
1764
1765         if (!secrets_init()) {
1766                 libnet_unjoin_set_error_string(mem_ctx, r,
1767                         "Unable to open secrets database");
1768                 return WERR_CAN_NOT_COMPLETE;
1769         }
1770
1771         return WERR_OK;
1772 }
1773
1774 /****************************************************************
1775 ****************************************************************/
1776
1777 static WERROR libnet_unjoin_post_processing(TALLOC_CTX *mem_ctx,
1778                                             struct libnet_UnjoinCtx *r)
1779 {
1780         saf_delete(r->out.netbios_domain_name);
1781         saf_delete(r->out.dns_domain_name);
1782
1783         return libnet_unjoin_config(r);
1784 }
1785
1786 /****************************************************************
1787 ****************************************************************/
1788
1789 WERROR libnet_Unjoin(TALLOC_CTX *mem_ctx,
1790                      struct libnet_UnjoinCtx *r)
1791 {
1792         WERROR werr;
1793
1794         if (r->in.debug) {
1795                 LIBNET_UNJOIN_IN_DUMP_CTX(mem_ctx, r);
1796         }
1797
1798         werr = libnet_unjoin_pre_processing(mem_ctx, r);
1799         if (!W_ERROR_IS_OK(werr)) {
1800                 goto done;
1801         }
1802
1803         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1804                 werr = libnet_DomainUnjoin(mem_ctx, r);
1805                 if (!W_ERROR_IS_OK(werr)) {
1806                         libnet_unjoin_config(r);
1807                         goto done;
1808                 }
1809         }
1810
1811         werr = libnet_unjoin_post_processing(mem_ctx, r);
1812         if (!W_ERROR_IS_OK(werr)) {
1813                 goto done;
1814         }
1815
1816  done:
1817         r->out.result = werr;
1818
1819         if (r->in.debug) {
1820                 LIBNET_UNJOIN_OUT_DUMP_CTX(mem_ctx, r);
1821         }
1822
1823         return werr;
1824 }