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