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