90e1b5941e52c176397521663daa03ab95235196
[jra/samba/.git] / source / 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                 libnet_join_set_error_string(mem_ctx, r,
909                         "Failed to set password for machine account (%s)\n",
910                         nt_errstr(status));
911                 goto done;
912         }
913
914         rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
915         cli_rpc_pipe_close(pipe_hnd);
916
917         status = NT_STATUS_OK;
918  done:
919         if (cli) {
920                 cli_shutdown(cli);
921         }
922
923         return status;
924 }
925
926 /****************************************************************
927 ****************************************************************/
928
929 NTSTATUS libnet_join_ok(const char *netbios_domain_name,
930                         const char *machine_name,
931                         const char *dc_name)
932 {
933         uint32_t neg_flags = NETLOGON_NEG_SELECT_AUTH2_FLAGS |
934                              NETLOGON_NEG_SCHANNEL;
935         struct cli_state *cli = NULL;
936         struct rpc_pipe_client *pipe_hnd = NULL;
937         struct rpc_pipe_client *netlogon_pipe = NULL;
938         NTSTATUS status;
939         char *machine_password = NULL;
940         char *machine_account = NULL;
941
942         if (!dc_name) {
943                 return NT_STATUS_INVALID_PARAMETER;
944         }
945
946         if (!secrets_init()) {
947                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
948         }
949
950         machine_password = secrets_fetch_machine_password(netbios_domain_name,
951                                                           NULL, NULL);
952         if (!machine_password) {
953                 return NT_STATUS_NO_TRUST_LSA_SECRET;
954         }
955
956         asprintf(&machine_account, "%s$", machine_name);
957         if (!machine_account) {
958                 SAFE_FREE(machine_password);
959                 return NT_STATUS_NO_MEMORY;
960         }
961
962         status = cli_full_connection(&cli, NULL,
963                                      dc_name,
964                                      NULL, 0,
965                                      "IPC$", "IPC",
966                                      machine_account,
967                                      NULL,
968                                      machine_password,
969                                      0,
970                                      Undefined, NULL);
971         free(machine_account);
972         free(machine_password);
973
974         if (!NT_STATUS_IS_OK(status)) {
975                 status = cli_full_connection(&cli, NULL,
976                                              dc_name,
977                                              NULL, 0,
978                                              "IPC$", "IPC",
979                                              "",
980                                              NULL,
981                                              "",
982                                              0,
983                                              Undefined, NULL);
984         }
985
986         if (!NT_STATUS_IS_OK(status)) {
987                 return status;
988         }
989
990         netlogon_pipe = get_schannel_session_key(cli,
991                                                  netbios_domain_name,
992                                                  &neg_flags, &status);
993         if (!netlogon_pipe) {
994                 if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_NETWORK_RESPONSE)) {
995                         cli_shutdown(cli);
996                         return NT_STATUS_OK;
997                 }
998
999                 DEBUG(0,("libnet_join_ok: failed to get schannel session "
1000                         "key from server %s for domain %s. Error was %s\n",
1001                 cli->desthost, netbios_domain_name, nt_errstr(status)));
1002                 cli_shutdown(cli);
1003                 return status;
1004         }
1005
1006         if (!lp_client_schannel()) {
1007                 cli_shutdown(cli);
1008                 return NT_STATUS_OK;
1009         }
1010
1011         pipe_hnd = cli_rpc_pipe_open_schannel_with_key(cli, PI_NETLOGON,
1012                                                        PIPE_AUTH_LEVEL_PRIVACY,
1013                                                        netbios_domain_name,
1014                                                        netlogon_pipe->dc,
1015                                                        &status);
1016
1017         cli_shutdown(cli);
1018
1019         if (!pipe_hnd) {
1020                 DEBUG(0,("libnet_join_ok: failed to open schannel session "
1021                         "on netlogon pipe to server %s for domain %s. "
1022                         "Error was %s\n",
1023                         cli->desthost, netbios_domain_name, nt_errstr(status)));
1024                 return status;
1025         }
1026
1027         return NT_STATUS_OK;
1028 }
1029
1030 /****************************************************************
1031 ****************************************************************/
1032
1033 static WERROR libnet_join_post_verify(TALLOC_CTX *mem_ctx,
1034                                       struct libnet_JoinCtx *r)
1035 {
1036         NTSTATUS status;
1037
1038         status = libnet_join_ok(r->out.netbios_domain_name,
1039                                 r->in.machine_name,
1040                                 r->in.dc_name);
1041         if (!NT_STATUS_IS_OK(status)) {
1042                 libnet_join_set_error_string(mem_ctx, r,
1043                         "failed to verify domain membership after joining: %s",
1044                         get_friendly_nt_error_msg(status));
1045                 return WERR_SETUP_NOT_JOINED;
1046         }
1047
1048         return WERR_OK;
1049 }
1050
1051 /****************************************************************
1052 ****************************************************************/
1053
1054 static bool libnet_join_unjoindomain_remove_secrets(TALLOC_CTX *mem_ctx,
1055                                                     struct libnet_UnjoinCtx *r)
1056 {
1057         if (!secrets_delete_machine_password_ex(lp_workgroup())) {
1058                 return false;
1059         }
1060
1061         if (!secrets_delete_domain_sid(lp_workgroup())) {
1062                 return false;
1063         }
1064
1065         return true;
1066 }
1067
1068 /****************************************************************
1069 ****************************************************************/
1070
1071 static NTSTATUS libnet_join_unjoindomain_rpc(TALLOC_CTX *mem_ctx,
1072                                              struct libnet_UnjoinCtx *r)
1073 {
1074         struct cli_state *cli = NULL;
1075         struct rpc_pipe_client *pipe_hnd = NULL;
1076         POLICY_HND sam_pol, domain_pol, user_pol;
1077         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1078         char *acct_name;
1079         uint32_t user_rid;
1080         struct lsa_String lsa_acct_name;
1081         struct samr_Ids user_rids;
1082         struct samr_Ids name_types;
1083         union samr_UserInfo *info = NULL;
1084
1085         status = cli_full_connection(&cli, NULL,
1086                                      r->in.dc_name,
1087                                      NULL, 0,
1088                                      "IPC$", "IPC",
1089                                      r->in.admin_account,
1090                                      NULL,
1091                                      r->in.admin_password,
1092                                      0, Undefined, NULL);
1093
1094         if (!NT_STATUS_IS_OK(status)) {
1095                 goto done;
1096         }
1097
1098         /* Open the domain */
1099
1100         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SAMR, &status);
1101         if (!pipe_hnd) {
1102                 DEBUG(0,("Error connecting to SAM pipe. Error was %s\n",
1103                         nt_errstr(status)));
1104                 goto done;
1105         }
1106
1107         status = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
1108                                       pipe_hnd->cli->desthost,
1109                                       SEC_RIGHTS_MAXIMUM_ALLOWED,
1110                                       &sam_pol);
1111         if (!NT_STATUS_IS_OK(status)) {
1112                 goto done;
1113         }
1114
1115         status = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
1116                                         &sam_pol,
1117                                         SEC_RIGHTS_MAXIMUM_ALLOWED,
1118                                         r->in.domain_sid,
1119                                         &domain_pol);
1120         if (!NT_STATUS_IS_OK(status)) {
1121                 goto done;
1122         }
1123
1124         /* Create domain user */
1125
1126         acct_name = talloc_asprintf(mem_ctx, "%s$", r->in.machine_name);
1127         strlower_m(acct_name);
1128
1129         init_lsa_String(&lsa_acct_name, acct_name);
1130
1131         status = rpccli_samr_LookupNames(pipe_hnd, mem_ctx,
1132                                          &domain_pol,
1133                                          1,
1134                                          &lsa_acct_name,
1135                                          &user_rids,
1136                                          &name_types);
1137
1138         if (!NT_STATUS_IS_OK(status)) {
1139                 goto done;
1140         }
1141
1142         if (name_types.ids[0] != SID_NAME_USER) {
1143                 DEBUG(0, ("%s is not a user account (type=%d)\n", acct_name,
1144                         name_types.ids[0]));
1145                 status = NT_STATUS_INVALID_WORKSTATION;
1146                 goto done;
1147         }
1148
1149         user_rid = user_rids.ids[0];
1150
1151         /* Open handle on user */
1152
1153         status = rpccli_samr_OpenUser(pipe_hnd, mem_ctx,
1154                                       &domain_pol,
1155                                       SEC_RIGHTS_MAXIMUM_ALLOWED,
1156                                       user_rid,
1157                                       &user_pol);
1158         if (!NT_STATUS_IS_OK(status)) {
1159                 goto done;
1160         }
1161
1162         /* Get user info */
1163
1164         status = rpccli_samr_QueryUserInfo(pipe_hnd, mem_ctx,
1165                                            &user_pol,
1166                                            16,
1167                                            &info);
1168         if (!NT_STATUS_IS_OK(status)) {
1169                 rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
1170                 goto done;
1171         }
1172
1173         /* now disable and setuser info */
1174
1175         info->info16.acct_flags |= ACB_DISABLED;
1176
1177         status = rpccli_samr_SetUserInfo(pipe_hnd, mem_ctx,
1178                                          &user_pol,
1179                                          16,
1180                                          info);
1181
1182         rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
1183
1184 done:
1185         if (pipe_hnd) {
1186                 rpccli_samr_Close(pipe_hnd, mem_ctx, &domain_pol);
1187                 rpccli_samr_Close(pipe_hnd, mem_ctx, &sam_pol);
1188                 cli_rpc_pipe_close(pipe_hnd);
1189         }
1190
1191         if (cli) {
1192                 cli_shutdown(cli);
1193         }
1194
1195         return status;
1196 }
1197
1198 /****************************************************************
1199 ****************************************************************/
1200
1201 static WERROR do_join_modify_vals_config(struct libnet_JoinCtx *r)
1202 {
1203         WERROR werr;
1204         struct smbconf_ctx *ctx;
1205
1206         werr = smbconf_init_reg(r, &ctx, NULL);
1207         if (!W_ERROR_IS_OK(werr)) {
1208                 goto done;
1209         }
1210
1211         if (!(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE)) {
1212
1213                 werr = smbconf_set_global_parameter(ctx, "security", "user");
1214                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1215
1216                 werr = smbconf_set_global_parameter(ctx, "workgroup",
1217                                                     r->in.domain_name);
1218                 goto done;
1219         }
1220
1221         werr = smbconf_set_global_parameter(ctx, "security", "domain");
1222         W_ERROR_NOT_OK_GOTO_DONE(werr);
1223
1224         werr = smbconf_set_global_parameter(ctx, "workgroup",
1225                                             r->out.netbios_domain_name);
1226         W_ERROR_NOT_OK_GOTO_DONE(werr);
1227
1228         if (r->out.domain_is_ad) {
1229                 werr = smbconf_set_global_parameter(ctx, "security", "ads");
1230                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1231
1232                 werr = smbconf_set_global_parameter(ctx, "realm",
1233                                                     r->out.dns_domain_name);
1234                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1235         }
1236
1237  done:
1238         smbconf_shutdown(ctx);
1239         return werr;
1240 }
1241
1242 /****************************************************************
1243 ****************************************************************/
1244
1245 static WERROR do_unjoin_modify_vals_config(struct libnet_UnjoinCtx *r)
1246 {
1247         WERROR werr = WERR_OK;
1248         struct smbconf_ctx *ctx;
1249
1250         werr = smbconf_init_reg(r, &ctx, NULL);
1251         if (!W_ERROR_IS_OK(werr)) {
1252                 goto done;
1253         }
1254
1255         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1256
1257                 werr = smbconf_set_global_parameter(ctx, "security", "user");
1258                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1259                 smbconf_delete_global_parameter(ctx, "realm");
1260         }
1261
1262  done:
1263         smbconf_shutdown(ctx);
1264         return werr;
1265 }
1266
1267 /****************************************************************
1268 ****************************************************************/
1269
1270 static WERROR do_JoinConfig(struct libnet_JoinCtx *r)
1271 {
1272         WERROR werr;
1273
1274         if (!W_ERROR_IS_OK(r->out.result)) {
1275                 return r->out.result;
1276         }
1277
1278         if (!r->in.modify_config) {
1279                 return WERR_OK;
1280         }
1281
1282         werr = do_join_modify_vals_config(r);
1283         if (!W_ERROR_IS_OK(werr)) {
1284                 return werr;
1285         }
1286
1287         r->out.modified_config = true;
1288         r->out.result = werr;
1289
1290         return werr;
1291 }
1292
1293 /****************************************************************
1294 ****************************************************************/
1295
1296 static WERROR libnet_unjoin_config(struct libnet_UnjoinCtx *r)
1297 {
1298         WERROR werr;
1299
1300         if (!W_ERROR_IS_OK(r->out.result)) {
1301                 return r->out.result;
1302         }
1303
1304         if (!r->in.modify_config) {
1305                 return WERR_OK;
1306         }
1307
1308         werr = do_unjoin_modify_vals_config(r);
1309         if (!W_ERROR_IS_OK(werr)) {
1310                 return werr;
1311         }
1312
1313         r->out.modified_config = true;
1314         r->out.result = werr;
1315
1316         return werr;
1317 }
1318
1319 /****************************************************************
1320 ****************************************************************/
1321
1322 static bool libnet_parse_domain_dc(TALLOC_CTX *mem_ctx,
1323                                    const char *domain_str,
1324                                    const char **domain_p,
1325                                    const char **dc_p)
1326 {
1327         char *domain = NULL;
1328         char *dc = NULL;
1329         const char *p = NULL;
1330
1331         if (!domain_str || !domain_p || !dc_p) {
1332                 return false;
1333         }
1334
1335         p = strchr_m(domain_str, '\\');
1336
1337         if (p != NULL) {
1338                 domain = talloc_strndup(mem_ctx, domain_str,
1339                                          PTR_DIFF(p, domain_str));
1340                 dc = talloc_strdup(mem_ctx, p+1);
1341                 if (!dc) {
1342                         return false;
1343                 }
1344         } else {
1345                 domain = talloc_strdup(mem_ctx, domain_str);
1346                 dc = NULL;
1347         }
1348         if (!domain) {
1349                 return false;
1350         }
1351
1352         *domain_p = domain;
1353
1354         if (!*dc_p && dc) {
1355                 *dc_p = dc;
1356         }
1357
1358         return true;
1359 }
1360
1361 /****************************************************************
1362 ****************************************************************/
1363
1364 static WERROR libnet_join_pre_processing(TALLOC_CTX *mem_ctx,
1365                                          struct libnet_JoinCtx *r)
1366 {
1367         if (!r->in.domain_name) {
1368                 libnet_join_set_error_string(mem_ctx, r,
1369                         "No domain name defined");
1370                 return WERR_INVALID_PARAM;
1371         }
1372
1373         if (!libnet_parse_domain_dc(mem_ctx, r->in.domain_name,
1374                                     &r->in.domain_name,
1375                                     &r->in.dc_name)) {
1376                 libnet_join_set_error_string(mem_ctx, r,
1377                         "Failed to parse domain name");
1378                 return WERR_INVALID_PARAM;
1379         }
1380
1381         if (r->in.modify_config && !lp_config_backend_is_registry()) {
1382                 libnet_join_set_error_string(mem_ctx, r,
1383                         "Configuration manipulation requested but not "
1384                         "supported by backend");
1385                 return WERR_NOT_SUPPORTED;
1386         }
1387
1388         if (IS_DC) {
1389                 return WERR_SETUP_DOMAIN_CONTROLLER;
1390         }
1391
1392         if (!secrets_init()) {
1393                 libnet_join_set_error_string(mem_ctx, r,
1394                         "Unable to open secrets database");
1395                 return WERR_CAN_NOT_COMPLETE;
1396         }
1397
1398         return WERR_OK;
1399 }
1400
1401 /****************************************************************
1402 ****************************************************************/
1403
1404 static WERROR libnet_join_post_processing(TALLOC_CTX *mem_ctx,
1405                                           struct libnet_JoinCtx *r)
1406 {
1407         WERROR werr;
1408
1409         if (!W_ERROR_IS_OK(r->out.result)) {
1410                 return r->out.result;
1411         }
1412
1413         werr = do_JoinConfig(r);
1414         if (!W_ERROR_IS_OK(werr)) {
1415                 return werr;
1416         }
1417
1418         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1419                 saf_store(r->in.domain_name, r->in.dc_name);
1420         }
1421
1422         return WERR_OK;
1423 }
1424
1425 /****************************************************************
1426 ****************************************************************/
1427
1428 static int libnet_destroy_JoinCtx(struct libnet_JoinCtx *r)
1429 {
1430         if (r->in.ads) {
1431                 ads_destroy(&r->in.ads);
1432         }
1433
1434         return 0;
1435 }
1436
1437 /****************************************************************
1438 ****************************************************************/
1439
1440 static int libnet_destroy_UnjoinCtx(struct libnet_UnjoinCtx *r)
1441 {
1442         if (r->in.ads) {
1443                 ads_destroy(&r->in.ads);
1444         }
1445
1446         return 0;
1447 }
1448
1449 /****************************************************************
1450 ****************************************************************/
1451
1452 WERROR libnet_init_JoinCtx(TALLOC_CTX *mem_ctx,
1453                            struct libnet_JoinCtx **r)
1454 {
1455         struct libnet_JoinCtx *ctx;
1456
1457         ctx = talloc_zero(mem_ctx, struct libnet_JoinCtx);
1458         if (!ctx) {
1459                 return WERR_NOMEM;
1460         }
1461
1462         talloc_set_destructor(ctx, libnet_destroy_JoinCtx);
1463
1464         ctx->in.machine_name = talloc_strdup(mem_ctx, global_myname());
1465         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
1466
1467         ctx->in.secure_channel_type = SEC_CHAN_WKSTA;
1468
1469         *r = ctx;
1470
1471         return WERR_OK;
1472 }
1473
1474 /****************************************************************
1475 ****************************************************************/
1476
1477 WERROR libnet_init_UnjoinCtx(TALLOC_CTX *mem_ctx,
1478                              struct libnet_UnjoinCtx **r)
1479 {
1480         struct libnet_UnjoinCtx *ctx;
1481
1482         ctx = talloc_zero(mem_ctx, struct libnet_UnjoinCtx);
1483         if (!ctx) {
1484                 return WERR_NOMEM;
1485         }
1486
1487         talloc_set_destructor(ctx, libnet_destroy_UnjoinCtx);
1488
1489         ctx->in.machine_name = talloc_strdup(mem_ctx, global_myname());
1490         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
1491
1492         *r = ctx;
1493
1494         return WERR_OK;
1495 }
1496
1497 /****************************************************************
1498 ****************************************************************/
1499
1500 static WERROR libnet_DomainJoin(TALLOC_CTX *mem_ctx,
1501                                 struct libnet_JoinCtx *r)
1502 {
1503         NTSTATUS status;
1504 #ifdef WITH_ADS
1505         ADS_STATUS ads_status;
1506 #endif /* WITH_ADS */
1507
1508         if (!r->in.dc_name) {
1509                 struct netr_DsRGetDCNameInfo *info;
1510                 status = dsgetdcname(mem_ctx,
1511                                      r->in.domain_name,
1512                                      NULL,
1513                                      NULL,
1514                                      DS_DIRECTORY_SERVICE_REQUIRED |
1515                                      DS_WRITABLE_REQUIRED |
1516                                      DS_RETURN_DNS_NAME,
1517                                      &info);
1518                 if (!NT_STATUS_IS_OK(status)) {
1519                         libnet_join_set_error_string(mem_ctx, r,
1520                                 "failed to find DC for domain %s",
1521                                 r->in.domain_name,
1522                                 get_friendly_nt_error_msg(status));
1523                         return WERR_DOMAIN_CONTROLLER_NOT_FOUND;
1524                 }
1525
1526                 r->in.dc_name = talloc_strdup(mem_ctx,
1527                                               info->dc_unc);
1528                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
1529         }
1530
1531 #ifdef WITH_ADS
1532         if (r->in.account_ou) {
1533
1534                 ads_status = libnet_join_connect_ads(mem_ctx, r);
1535                 if (!ADS_ERR_OK(ads_status)) {
1536                         return WERR_DEFAULT_JOIN_REQUIRED;
1537                 }
1538
1539                 ads_status = libnet_join_precreate_machine_acct(mem_ctx, r);
1540                 if (!ADS_ERR_OK(ads_status)) {
1541                         libnet_join_set_error_string(mem_ctx, r,
1542                                 "failed to precreate account in ou %s: %s",
1543                                 r->in.account_ou,
1544                                 ads_errstr(ads_status));
1545                         return WERR_DEFAULT_JOIN_REQUIRED;
1546                 }
1547
1548                 r->in.join_flags &= ~WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE;
1549         }
1550 #endif /* WITH_ADS */
1551
1552         status = libnet_join_joindomain_rpc(mem_ctx, r);
1553         if (!NT_STATUS_IS_OK(status)) {
1554                 libnet_join_set_error_string(mem_ctx, r,
1555                         "failed to join domain over rpc: %s",
1556                         get_friendly_nt_error_msg(status));
1557                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
1558                         return WERR_SETUP_ALREADY_JOINED;
1559                 }
1560                 return ntstatus_to_werror(status);
1561         }
1562
1563         if (!libnet_join_joindomain_store_secrets(mem_ctx, r)) {
1564                 return WERR_SETUP_NOT_JOINED;
1565         }
1566
1567 #ifdef WITH_ADS
1568         if (r->out.domain_is_ad) {
1569                 ads_status  = libnet_join_post_processing_ads(mem_ctx, r);
1570                 if (!ADS_ERR_OK(ads_status)) {
1571                         return WERR_GENERAL_FAILURE;
1572                 }
1573         }
1574 #endif /* WITH_ADS */
1575
1576         return WERR_OK;
1577 }
1578
1579 /****************************************************************
1580 ****************************************************************/
1581
1582 WERROR libnet_Join(TALLOC_CTX *mem_ctx,
1583                    struct libnet_JoinCtx *r)
1584 {
1585         WERROR werr;
1586
1587         if (r->in.debug) {
1588                 LIBNET_JOIN_IN_DUMP_CTX(mem_ctx, r);
1589         }
1590
1591         werr = libnet_join_pre_processing(mem_ctx, r);
1592         if (!W_ERROR_IS_OK(werr)) {
1593                 goto done;
1594         }
1595
1596         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1597                 werr = libnet_DomainJoin(mem_ctx, r);
1598                 if (!W_ERROR_IS_OK(werr)) {
1599                         goto done;
1600                 }
1601
1602                 werr = libnet_join_post_verify(mem_ctx, r);
1603                 if (!W_ERROR_IS_OK(werr)) {
1604                         goto done;
1605                 }
1606         }
1607
1608         werr = libnet_join_post_processing(mem_ctx, r);
1609         if (!W_ERROR_IS_OK(werr)) {
1610                 goto done;
1611         }
1612  done:
1613         r->out.result = werr;
1614
1615         if (r->in.debug) {
1616                 LIBNET_JOIN_OUT_DUMP_CTX(mem_ctx, r);
1617         }
1618         return werr;
1619 }
1620
1621 /****************************************************************
1622 ****************************************************************/
1623
1624 static WERROR libnet_DomainUnjoin(TALLOC_CTX *mem_ctx,
1625                                   struct libnet_UnjoinCtx *r)
1626 {
1627         NTSTATUS status;
1628
1629         if (!r->in.domain_sid) {
1630                 struct dom_sid sid;
1631                 if (!secrets_fetch_domain_sid(lp_workgroup(), &sid)) {
1632                         libnet_unjoin_set_error_string(mem_ctx, r,
1633                                 "Unable to fetch domain sid: are we joined?");
1634                         return WERR_SETUP_NOT_JOINED;
1635                 }
1636                 r->in.domain_sid = sid_dup_talloc(mem_ctx, &sid);
1637                 W_ERROR_HAVE_NO_MEMORY(r->in.domain_sid);
1638         }
1639
1640         if (!r->in.dc_name) {
1641                 struct netr_DsRGetDCNameInfo *info;
1642                 status = dsgetdcname(mem_ctx,
1643                                      r->in.domain_name,
1644                                      NULL,
1645                                      NULL,
1646                                      DS_DIRECTORY_SERVICE_REQUIRED |
1647                                      DS_WRITABLE_REQUIRED |
1648                                      DS_RETURN_DNS_NAME,
1649                                      &info);
1650                 if (!NT_STATUS_IS_OK(status)) {
1651                         libnet_unjoin_set_error_string(mem_ctx, r,
1652                                 "failed to find DC for domain %s",
1653                                 r->in.domain_name,
1654                                 get_friendly_nt_error_msg(status));
1655                         return WERR_DOMAIN_CONTROLLER_NOT_FOUND;
1656                 }
1657
1658                 r->in.dc_name = talloc_strdup(mem_ctx,
1659                                               info->dc_unc);
1660                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
1661         }
1662
1663         status = libnet_join_unjoindomain_rpc(mem_ctx, r);
1664         if (!NT_STATUS_IS_OK(status)) {
1665                 libnet_unjoin_set_error_string(mem_ctx, r,
1666                         "failed to disable machine account via rpc: %s",
1667                         get_friendly_nt_error_msg(status));
1668                 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER)) {
1669                         return WERR_SETUP_NOT_JOINED;
1670                 }
1671                 return ntstatus_to_werror(status);
1672         }
1673
1674         r->out.disabled_machine_account = true;
1675
1676 #ifdef WITH_ADS
1677         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE) {
1678                 ADS_STATUS ads_status;
1679                 libnet_unjoin_connect_ads(mem_ctx, r);
1680                 ads_status = libnet_unjoin_remove_machine_acct(mem_ctx, r);
1681                 if (!ADS_ERR_OK(ads_status)) {
1682                         libnet_unjoin_set_error_string(mem_ctx, r,
1683                                 "failed to remove machine account from AD: %s",
1684                                 ads_errstr(ads_status));
1685                 } else {
1686                         r->out.deleted_machine_account = true;
1687                         /* dirty hack */
1688                         r->out.dns_domain_name = talloc_strdup(mem_ctx,
1689                                                                r->in.ads->server.realm);
1690                         W_ERROR_HAVE_NO_MEMORY(r->out.dns_domain_name);
1691                 }
1692         }
1693 #endif /* WITH_ADS */
1694
1695         libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
1696
1697         return WERR_OK;
1698 }
1699
1700 /****************************************************************
1701 ****************************************************************/
1702
1703 static WERROR libnet_unjoin_pre_processing(TALLOC_CTX *mem_ctx,
1704                                            struct libnet_UnjoinCtx *r)
1705 {
1706         if (!r->in.domain_name) {
1707                 libnet_unjoin_set_error_string(mem_ctx, r,
1708                         "No domain name defined");
1709                 return WERR_INVALID_PARAM;
1710         }
1711
1712         if (!libnet_parse_domain_dc(mem_ctx, r->in.domain_name,
1713                                     &r->in.domain_name,
1714                                     &r->in.dc_name)) {
1715                 libnet_unjoin_set_error_string(mem_ctx, r,
1716                         "Failed to parse domain name");
1717                 return WERR_INVALID_PARAM;
1718         }
1719
1720         if (r->in.modify_config && !lp_config_backend_is_registry()) {
1721                 libnet_unjoin_set_error_string(mem_ctx, r,
1722                         "Configuration manipulation requested but not "
1723                         "supported by backend");
1724                 return WERR_NOT_SUPPORTED;
1725         }
1726
1727         if (IS_DC) {
1728                 return WERR_SETUP_DOMAIN_CONTROLLER;
1729         }
1730
1731         if (!secrets_init()) {
1732                 libnet_unjoin_set_error_string(mem_ctx, r,
1733                         "Unable to open secrets database");
1734                 return WERR_CAN_NOT_COMPLETE;
1735         }
1736
1737         return WERR_OK;
1738 }
1739
1740 /****************************************************************
1741 ****************************************************************/
1742
1743 static WERROR libnet_unjoin_post_processing(TALLOC_CTX *mem_ctx,
1744                                             struct libnet_UnjoinCtx *r)
1745 {
1746         saf_delete(r->out.netbios_domain_name);
1747         saf_delete(r->out.dns_domain_name);
1748
1749         return libnet_unjoin_config(r);
1750 }
1751
1752 /****************************************************************
1753 ****************************************************************/
1754
1755 WERROR libnet_Unjoin(TALLOC_CTX *mem_ctx,
1756                      struct libnet_UnjoinCtx *r)
1757 {
1758         WERROR werr;
1759
1760         if (r->in.debug) {
1761                 LIBNET_UNJOIN_IN_DUMP_CTX(mem_ctx, r);
1762         }
1763
1764         werr = libnet_unjoin_pre_processing(mem_ctx, r);
1765         if (!W_ERROR_IS_OK(werr)) {
1766                 goto done;
1767         }
1768
1769         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1770                 werr = libnet_DomainUnjoin(mem_ctx, r);
1771                 if (!W_ERROR_IS_OK(werr)) {
1772                         libnet_unjoin_config(r);
1773                         goto done;
1774                 }
1775         }
1776
1777         werr = libnet_unjoin_post_processing(mem_ctx, r);
1778         if (!W_ERROR_IS_OK(werr)) {
1779                 goto done;
1780         }
1781
1782  done:
1783         r->out.result = werr;
1784
1785         if (r->in.debug) {
1786                 LIBNET_UNJOIN_OUT_DUMP_CTX(mem_ctx, r);
1787         }
1788
1789         return werr;
1790 }