d3fba167d95c2a500e7f91cd9e47171b3d7e6db6
[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_search_dn(r->in.ads, &res, r->in.account_ou, attrs);
211         if (!ADS_ERR_OK(status)) {
212                 return status;
213         }
214
215         if (ads_count_replies(r->in.ads, res) != 1) {
216                 ads_msgfree(r->in.ads, res);
217                 return ADS_ERROR_LDAP(LDAP_NO_SUCH_OBJECT);
218         }
219
220         ads_msgfree(r->in.ads, res);
221
222         /* Attempt to create the machine account and bail if this fails.
223            Assume that the admin wants exactly what they requested */
224
225         status = ads_create_machine_acct(r->in.ads,
226                                          r->in.machine_name,
227                                          r->in.account_ou);
228
229         if (ADS_ERR_OK(status)) {
230                 DEBUG(1,("machine account creation created\n"));
231                 return status;
232         } else  if ((status.error_type == ENUM_ADS_ERROR_LDAP) &&
233                     (status.err.rc == LDAP_ALREADY_EXISTS)) {
234                 status = ADS_SUCCESS;
235         }
236
237         if (!ADS_ERR_OK(status)) {
238                 DEBUG(1,("machine account creation failed\n"));
239                 return status;
240         }
241
242         status = ads_move_machine_acct(r->in.ads,
243                                        r->in.machine_name,
244                                        r->in.account_ou,
245                                        &moved);
246         if (!ADS_ERR_OK(status)) {
247                 DEBUG(1,("failure to locate/move pre-existing "
248                         "machine account\n"));
249                 return status;
250         }
251
252         DEBUG(1,("The machine account %s the specified OU.\n",
253                 moved ? "was moved into" : "already exists in"));
254
255         return status;
256 }
257
258 /****************************************************************
259 ****************************************************************/
260
261 static ADS_STATUS libnet_unjoin_remove_machine_acct(TALLOC_CTX *mem_ctx,
262                                                     struct libnet_UnjoinCtx *r)
263 {
264         ADS_STATUS status;
265
266         if (!r->in.ads) {
267                 status = libnet_unjoin_connect_ads(mem_ctx, r);
268                 if (!ADS_ERR_OK(status)) {
269                         return status;
270                 }
271         }
272
273         status = ads_leave_realm(r->in.ads, r->in.machine_name);
274         if (!ADS_ERR_OK(status)) {
275                 libnet_unjoin_set_error_string(mem_ctx, r,
276                         "failed to leave realm: %s",
277                         ads_errstr(status));
278                 return status;
279         }
280
281         return ADS_SUCCESS;
282 }
283
284 /****************************************************************
285 ****************************************************************/
286
287 static ADS_STATUS libnet_join_find_machine_acct(TALLOC_CTX *mem_ctx,
288                                                 struct libnet_JoinCtx *r)
289 {
290         ADS_STATUS status;
291         LDAPMessage *res = NULL;
292         char *dn = NULL;
293
294         if (!r->in.machine_name) {
295                 return ADS_ERROR(LDAP_NO_MEMORY);
296         }
297
298         status = ads_find_machine_acct(r->in.ads,
299                                        &res,
300                                        r->in.machine_name);
301         if (!ADS_ERR_OK(status)) {
302                 return status;
303         }
304
305         if (ads_count_replies(r->in.ads, res) != 1) {
306                 status = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
307                 goto done;
308         }
309
310         dn = ads_get_dn(r->in.ads, res);
311         if (!dn) {
312                 status = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
313                 goto done;
314         }
315
316         r->out.dn = talloc_strdup(mem_ctx, dn);
317         if (!r->out.dn) {
318                 status = ADS_ERROR_LDAP(LDAP_NO_MEMORY);
319                 goto done;
320         }
321
322  done:
323         ads_msgfree(r->in.ads, res);
324         ads_memfree(r->in.ads, dn);
325
326         return status;
327 }
328
329 /****************************************************************
330  Set a machines dNSHostName and servicePrincipalName attributes
331 ****************************************************************/
332
333 static ADS_STATUS libnet_join_set_machine_spn(TALLOC_CTX *mem_ctx,
334                                               struct libnet_JoinCtx *r)
335 {
336         ADS_STATUS status;
337         ADS_MODLIST mods;
338         fstring my_fqdn;
339         const char *spn_array[3] = {NULL, NULL, NULL};
340         char *spn = NULL;
341
342         /* Find our DN */
343
344         status = libnet_join_find_machine_acct(mem_ctx, r);
345         if (!ADS_ERR_OK(status)) {
346                 return status;
347         }
348
349         /* Windows only creates HOST/shortname & HOST/fqdn. */
350
351         spn = talloc_asprintf(mem_ctx, "HOST/%s", r->in.machine_name);
352         if (!spn) {
353                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
354         }
355         strupper_m(spn);
356         spn_array[0] = spn;
357
358         if (name_to_fqdn(my_fqdn, r->in.machine_name) &&
359             !strequal(my_fqdn, r->in.machine_name)) {
360
361                 strlower_m(my_fqdn);
362                 spn = talloc_asprintf(mem_ctx, "HOST/%s", my_fqdn);
363                 if (!spn) {
364                         return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
365                 }
366                 spn_array[1] = spn;
367         }
368
369         mods = ads_init_mods(mem_ctx);
370         if (!mods) {
371                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
372         }
373
374         /* fields of primary importance */
375
376         status = ads_mod_str(mem_ctx, &mods, "dNSHostName", my_fqdn);
377         if (!ADS_ERR_OK(status)) {
378                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
379         }
380
381         status = ads_mod_strlist(mem_ctx, &mods, "servicePrincipalName",
382                                  spn_array);
383         if (!ADS_ERR_OK(status)) {
384                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
385         }
386
387         return ads_gen_mod(r->in.ads, r->out.dn, mods);
388 }
389
390 /****************************************************************
391 ****************************************************************/
392
393 static ADS_STATUS libnet_join_set_machine_upn(TALLOC_CTX *mem_ctx,
394                                               struct libnet_JoinCtx *r)
395 {
396         ADS_STATUS status;
397         ADS_MODLIST mods;
398
399         if (!r->in.create_upn) {
400                 return ADS_SUCCESS;
401         }
402
403         /* Find our DN */
404
405         status = libnet_join_find_machine_acct(mem_ctx, r);
406         if (!ADS_ERR_OK(status)) {
407                 return status;
408         }
409
410         if (!r->in.upn) {
411                 r->in.upn = talloc_asprintf(mem_ctx,
412                                             "host/%s@%s",
413                                             r->in.machine_name,
414                                             r->out.dns_domain_name);
415                 if (!r->in.upn) {
416                         return ADS_ERROR(LDAP_NO_MEMORY);
417                 }
418         }
419
420         /* now do the mods */
421
422         mods = ads_init_mods(mem_ctx);
423         if (!mods) {
424                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
425         }
426
427         /* fields of primary importance */
428
429         status = ads_mod_str(mem_ctx, &mods, "userPrincipalName", r->in.upn);
430         if (!ADS_ERR_OK(status)) {
431                 return ADS_ERROR_LDAP(LDAP_NO_MEMORY);
432         }
433
434         return ads_gen_mod(r->in.ads, r->out.dn, mods);
435 }
436
437
438 /****************************************************************
439 ****************************************************************/
440
441 static ADS_STATUS libnet_join_set_os_attributes(TALLOC_CTX *mem_ctx,
442                                                 struct libnet_JoinCtx *r)
443 {
444         ADS_STATUS status;
445         ADS_MODLIST mods;
446         char *os_sp = NULL;
447
448         if (!r->in.os_name || !r->in.os_version ) {
449                 return ADS_SUCCESS;
450         }
451
452         /* Find our DN */
453
454         status = libnet_join_find_machine_acct(mem_ctx, r);
455         if (!ADS_ERR_OK(status)) {
456                 return status;
457         }
458
459         /* now do the mods */
460
461         mods = ads_init_mods(mem_ctx);
462         if (!mods) {
463                 return ADS_ERROR(LDAP_NO_MEMORY);
464         }
465
466         os_sp = talloc_asprintf(mem_ctx, "Samba %s", SAMBA_VERSION_STRING);
467         if (!os_sp) {
468                 return ADS_ERROR(LDAP_NO_MEMORY);
469         }
470
471         /* fields of primary importance */
472
473         status = ads_mod_str(mem_ctx, &mods, "operatingSystem",
474                              r->in.os_name);
475         if (!ADS_ERR_OK(status)) {
476                 return status;
477         }
478
479         status = ads_mod_str(mem_ctx, &mods, "operatingSystemVersion",
480                              r->in.os_version);
481         if (!ADS_ERR_OK(status)) {
482                 return status;
483         }
484
485         status = ads_mod_str(mem_ctx, &mods, "operatingSystemServicePack",
486                              os_sp);
487         if (!ADS_ERR_OK(status)) {
488                 return status;
489         }
490
491         return ads_gen_mod(r->in.ads, r->out.dn, mods);
492 }
493
494 /****************************************************************
495 ****************************************************************/
496
497 static bool libnet_join_create_keytab(TALLOC_CTX *mem_ctx,
498                                       struct libnet_JoinCtx *r)
499 {
500         if (!lp_use_kerberos_keytab()) {
501                 return true;
502         }
503
504         if (!ads_keytab_create_default(r->in.ads)) {
505                 return false;
506         }
507
508         return true;
509 }
510
511 /****************************************************************
512 ****************************************************************/
513
514 static bool libnet_join_derive_salting_principal(TALLOC_CTX *mem_ctx,
515                                                  struct libnet_JoinCtx *r)
516 {
517         uint32_t domain_func;
518         ADS_STATUS status;
519         const char *salt = NULL;
520         char *std_salt = NULL;
521
522         status = ads_domain_func_level(r->in.ads, &domain_func);
523         if (!ADS_ERR_OK(status)) {
524                 libnet_join_set_error_string(mem_ctx, r,
525                         "failed to determine domain functional level: %s",
526                         ads_errstr(status));
527                 return false;
528         }
529
530         /* go ahead and setup the default salt */
531
532         std_salt = kerberos_standard_des_salt();
533         if (!std_salt) {
534                 libnet_join_set_error_string(mem_ctx, r,
535                         "failed to obtain standard DES salt");
536                 return false;
537         }
538
539         salt = talloc_strdup(mem_ctx, std_salt);
540         if (!salt) {
541                 return false;
542         }
543
544         SAFE_FREE(std_salt);
545
546         /* if it's a Windows functional domain, we have to look for the UPN */
547
548         if (domain_func == DS_DOMAIN_FUNCTION_2000) {
549                 char *upn;
550
551                 upn = ads_get_upn(r->in.ads, mem_ctx,
552                                   r->in.machine_name);
553                 if (upn) {
554                         salt = talloc_strdup(mem_ctx, upn);
555                         if (!salt) {
556                                 return false;
557                         }
558                 }
559         }
560
561         return kerberos_secrets_store_des_salt(salt);
562 }
563
564 /****************************************************************
565 ****************************************************************/
566
567 static ADS_STATUS libnet_join_post_processing_ads(TALLOC_CTX *mem_ctx,
568                                                   struct libnet_JoinCtx *r)
569 {
570         ADS_STATUS status;
571
572         if (!r->in.ads) {
573                 status = libnet_join_connect_ads(mem_ctx, r);
574                 if (!ADS_ERR_OK(status)) {
575                         return status;
576                 }
577         }
578
579         status = libnet_join_set_machine_spn(mem_ctx, r);
580         if (!ADS_ERR_OK(status)) {
581                 libnet_join_set_error_string(mem_ctx, r,
582                         "failed to set machine spn: %s",
583                         ads_errstr(status));
584                 return status;
585         }
586
587         status = libnet_join_set_os_attributes(mem_ctx, r);
588         if (!ADS_ERR_OK(status)) {
589                 libnet_join_set_error_string(mem_ctx, r,
590                         "failed to set machine os attributes: %s",
591                         ads_errstr(status));
592                 return status;
593         }
594
595         status = libnet_join_set_machine_upn(mem_ctx, r);
596         if (!ADS_ERR_OK(status)) {
597                 libnet_join_set_error_string(mem_ctx, r,
598                         "failed to set machine upn: %s",
599                         ads_errstr(status));
600                 return status;
601         }
602
603         if (!libnet_join_derive_salting_principal(mem_ctx, r)) {
604                 return ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
605         }
606
607         if (!libnet_join_create_keytab(mem_ctx, r)) {
608                 libnet_join_set_error_string(mem_ctx, r,
609                         "failed to create kerberos keytab");
610                 return ADS_ERROR_NT(NT_STATUS_UNSUCCESSFUL);
611         }
612
613         return ADS_SUCCESS;
614 }
615 #endif /* WITH_ADS */
616
617 /****************************************************************
618  Store the machine password and domain SID
619 ****************************************************************/
620
621 static bool libnet_join_joindomain_store_secrets(TALLOC_CTX *mem_ctx,
622                                                  struct libnet_JoinCtx *r)
623 {
624         if (!secrets_store_domain_sid(r->out.netbios_domain_name,
625                                       r->out.domain_sid))
626         {
627                 DEBUG(1,("Failed to save domain sid\n"));
628                 return false;
629         }
630
631         if (!secrets_store_machine_password(r->in.machine_password,
632                                             r->out.netbios_domain_name,
633                                             r->in.secure_channel_type))
634         {
635                 DEBUG(1,("Failed to save machine password\n"));
636                 return false;
637         }
638
639         return true;
640 }
641
642 /****************************************************************
643  Do the domain join
644 ****************************************************************/
645
646 static NTSTATUS libnet_join_joindomain_rpc(TALLOC_CTX *mem_ctx,
647                                            struct libnet_JoinCtx *r)
648 {
649         struct cli_state *cli = NULL;
650         struct rpc_pipe_client *pipe_hnd = NULL;
651         POLICY_HND sam_pol, domain_pol, user_pol, lsa_pol;
652         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
653         char *acct_name;
654         struct lsa_String lsa_acct_name;
655         uint32_t user_rid;
656         uint32_t acct_flags = ACB_WSTRUST;
657         uchar pwbuf[532];
658         struct MD5Context md5ctx;
659         uchar md5buffer[16];
660         DATA_BLOB digested_session_key;
661         uchar md4_trust_password[16];
662         union lsa_PolicyInformation *info = NULL;
663         struct samr_Ids user_rids;
664         struct samr_Ids name_types;
665         union samr_UserInfo user_info;
666
667         if (!r->in.machine_password) {
668                 r->in.machine_password = talloc_strdup(mem_ctx, generate_random_str(DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH));
669                 NT_STATUS_HAVE_NO_MEMORY(r->in.machine_password);
670         }
671
672         status = cli_full_connection(&cli, NULL,
673                                      r->in.dc_name,
674                                      NULL, 0,
675                                      "IPC$", "IPC",
676                                      r->in.admin_account,
677                                      NULL,
678                                      r->in.admin_password,
679                                      0,
680                                      Undefined, NULL);
681
682         if (!NT_STATUS_IS_OK(status)) {
683                 goto done;
684         }
685
686         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_LSARPC, &status);
687         if (!pipe_hnd) {
688                 DEBUG(0,("Error connecting to LSA pipe. Error was %s\n",
689                         nt_errstr(status)));
690                 goto done;
691         }
692
693         status = rpccli_lsa_open_policy(pipe_hnd, mem_ctx, true,
694                                         SEC_RIGHTS_MAXIMUM_ALLOWED, &lsa_pol);
695         if (!NT_STATUS_IS_OK(status)) {
696                 goto done;
697         }
698
699         status = rpccli_lsa_QueryInfoPolicy2(pipe_hnd, mem_ctx,
700                                              &lsa_pol,
701                                              LSA_POLICY_INFO_DNS,
702                                              &info);
703         if (NT_STATUS_IS_OK(status)) {
704                 r->out.domain_is_ad = true;
705                 r->out.netbios_domain_name = info->dns.name.string;
706                 r->out.dns_domain_name = info->dns.dns_domain.string;
707                 r->out.domain_sid = info->dns.sid;
708         }
709
710         if (!NT_STATUS_IS_OK(status)) {
711                 status = rpccli_lsa_QueryInfoPolicy(pipe_hnd, mem_ctx,
712                                                     &lsa_pol,
713                                                     LSA_POLICY_INFO_ACCOUNT_DOMAIN,
714                                                     &info);
715                 if (!NT_STATUS_IS_OK(status)) {
716                         goto done;
717                 }
718
719                 r->out.netbios_domain_name = info->account_domain.name.string;
720                 r->out.domain_sid = info->account_domain.sid;
721         }
722
723         rpccli_lsa_Close(pipe_hnd, mem_ctx, &lsa_pol);
724         cli_rpc_pipe_close(pipe_hnd);
725
726         /* Open the domain */
727
728         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SAMR, &status);
729         if (!pipe_hnd) {
730                 DEBUG(0,("Error connecting to SAM pipe. Error was %s\n",
731                         nt_errstr(status)));
732                 goto done;
733         }
734
735         status = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
736                                       pipe_hnd->cli->desthost,
737                                       SEC_RIGHTS_MAXIMUM_ALLOWED,
738                                       &sam_pol);
739         if (!NT_STATUS_IS_OK(status)) {
740                 goto done;
741         }
742
743         status = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
744                                         &sam_pol,
745                                         SEC_RIGHTS_MAXIMUM_ALLOWED,
746                                         r->out.domain_sid,
747                                         &domain_pol);
748         if (!NT_STATUS_IS_OK(status)) {
749                 goto done;
750         }
751
752         /* Create domain user */
753
754         acct_name = talloc_asprintf(mem_ctx, "%s$", r->in.machine_name);
755         strlower_m(acct_name);
756
757         init_lsa_String(&lsa_acct_name, acct_name);
758
759         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE) {
760                 uint32_t access_desired =
761                         SEC_GENERIC_READ | SEC_GENERIC_WRITE | SEC_GENERIC_EXECUTE |
762                         SEC_STD_WRITE_DAC | SEC_STD_DELETE |
763                         SAMR_USER_ACCESS_SET_PASSWORD |
764                         SAMR_USER_ACCESS_GET_ATTRIBUTES |
765                         SAMR_USER_ACCESS_SET_ATTRIBUTES;
766                 uint32_t access_granted = 0;
767
768                 /* Don't try to set any acct_flags flags other than ACB_WSTRUST */
769
770                 DEBUG(10,("Creating account with desired access mask: %d\n",
771                         access_desired));
772
773                 status = rpccli_samr_CreateUser2(pipe_hnd, mem_ctx,
774                                                  &domain_pol,
775                                                  &lsa_acct_name,
776                                                  ACB_WSTRUST,
777                                                  access_desired,
778                                                  &user_pol,
779                                                  &access_granted,
780                                                  &user_rid);
781                 if (!NT_STATUS_IS_OK(status) &&
782                     !NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
783
784                         DEBUG(10,("Creation of workstation account failed: %s\n",
785                                 nt_errstr(status)));
786
787                         /* If NT_STATUS_ACCESS_DENIED then we have a valid
788                            username/password combo but the user does not have
789                            administrator access. */
790
791                         if (NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED)) {
792                                 libnet_join_set_error_string(mem_ctx, r,
793                                         "User specified does not have "
794                                         "administrator privileges");
795                         }
796
797                         return status;
798                 }
799
800                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
801                         if (!(r->in.join_flags &
802                               WKSSVC_JOIN_FLAGS_DOMAIN_JOIN_IF_JOINED)) {
803                                 goto done;
804                         }
805                 }
806
807                 /* We *must* do this.... don't ask... */
808
809                 if (NT_STATUS_IS_OK(status)) {
810                         rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
811                 }
812         }
813
814         status = rpccli_samr_LookupNames(pipe_hnd, mem_ctx,
815                                          &domain_pol,
816                                          1,
817                                          &lsa_acct_name,
818                                          &user_rids,
819                                          &name_types);
820         if (!NT_STATUS_IS_OK(status)) {
821                 goto done;
822         }
823
824         if (name_types.ids[0] != SID_NAME_USER) {
825                 DEBUG(0,("%s is not a user account (type=%d)\n",
826                         acct_name, name_types.ids[0]));
827                 status = NT_STATUS_INVALID_WORKSTATION;
828                 goto done;
829         }
830
831         user_rid = user_rids.ids[0];
832
833         /* Open handle on user */
834
835         status = rpccli_samr_OpenUser(pipe_hnd, mem_ctx,
836                                       &domain_pol,
837                                       SEC_RIGHTS_MAXIMUM_ALLOWED,
838                                       user_rid,
839                                       &user_pol);
840         if (!NT_STATUS_IS_OK(status)) {
841                 goto done;
842         }
843
844         /* Create a random machine account password and generate the hash */
845
846         E_md4hash(r->in.machine_password, md4_trust_password);
847         encode_pw_buffer(pwbuf, r->in.machine_password, STR_UNICODE);
848
849         generate_random_buffer((uint8_t*)md5buffer, sizeof(md5buffer));
850         digested_session_key = data_blob_talloc(mem_ctx, 0, 16);
851
852         MD5Init(&md5ctx);
853         MD5Update(&md5ctx, md5buffer, sizeof(md5buffer));
854         MD5Update(&md5ctx, cli->user_session_key.data,
855                   cli->user_session_key.length);
856         MD5Final(digested_session_key.data, &md5ctx);
857
858         SamOEMhashBlob(pwbuf, sizeof(pwbuf), &digested_session_key);
859         memcpy(&pwbuf[516], md5buffer, sizeof(md5buffer));
860
861         /* Fill in the additional account flags now */
862
863         acct_flags |= ACB_PWNOEXP;
864         if (r->out.domain_is_ad) {
865 #if !defined(ENCTYPE_ARCFOUR_HMAC)
866                 acct_flags |= ACB_USE_DES_KEY_ONLY;
867 #endif
868                 ;;
869         }
870
871         /* Set password and account flags on machine account */
872
873         ZERO_STRUCT(user_info.info25);
874
875         user_info.info25.info.fields_present = ACCT_NT_PWD_SET |
876                                                ACCT_LM_PWD_SET |
877                                                SAMR_FIELD_ACCT_FLAGS;
878
879         user_info.info25.info.acct_flags = acct_flags;
880         memcpy(&user_info.info25.password.data, pwbuf, sizeof(pwbuf));
881
882         status = rpccli_samr_SetUserInfo(pipe_hnd, mem_ctx,
883                                          &user_pol,
884                                          25,
885                                          &user_info);
886
887         if (NT_STATUS_EQUAL(status, NT_STATUS(DCERPC_FAULT_INVALID_TAG))) {
888
889                 uchar pwbuf2[516];
890
891                 encode_pw_buffer(pwbuf2, r->in.machine_password, STR_UNICODE);
892
893                 /* retry with level 24 */
894                 init_samr_user_info24(&user_info.info24, pwbuf2, 24);
895
896                 SamOEMhashBlob(user_info.info24.password.data, 516,
897                                &cli->user_session_key);
898
899                 status = rpccli_samr_SetUserInfo2(pipe_hnd, mem_ctx,
900                                                   &user_pol,
901                                                   24,
902                                                   &user_info);
903         }
904
905         if (!NT_STATUS_IS_OK(status)) {
906                 libnet_join_set_error_string(mem_ctx, r,
907                         "Failed to set password for machine account (%s)\n",
908                         nt_errstr(status));
909                 goto done;
910         }
911
912         rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
913         cli_rpc_pipe_close(pipe_hnd);
914
915         status = NT_STATUS_OK;
916  done:
917         if (cli) {
918                 cli_shutdown(cli);
919         }
920
921         return status;
922 }
923
924 /****************************************************************
925 ****************************************************************/
926
927 NTSTATUS libnet_join_ok(const char *netbios_domain_name,
928                         const char *machine_name,
929                         const char *dc_name)
930 {
931         uint32_t neg_flags = NETLOGON_NEG_SELECT_AUTH2_FLAGS |
932                              NETLOGON_NEG_SCHANNEL;
933         struct cli_state *cli = NULL;
934         struct rpc_pipe_client *pipe_hnd = NULL;
935         struct rpc_pipe_client *netlogon_pipe = NULL;
936         NTSTATUS status;
937         char *machine_password = NULL;
938         char *machine_account = NULL;
939
940         if (!dc_name) {
941                 return NT_STATUS_INVALID_PARAMETER;
942         }
943
944         if (!secrets_init()) {
945                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
946         }
947
948         machine_password = secrets_fetch_machine_password(netbios_domain_name,
949                                                           NULL, NULL);
950         if (!machine_password) {
951                 return NT_STATUS_NO_TRUST_LSA_SECRET;
952         }
953
954         asprintf(&machine_account, "%s$", machine_name);
955         if (!machine_account) {
956                 SAFE_FREE(machine_password);
957                 return NT_STATUS_NO_MEMORY;
958         }
959
960         status = cli_full_connection(&cli, NULL,
961                                      dc_name,
962                                      NULL, 0,
963                                      "IPC$", "IPC",
964                                      machine_account,
965                                      NULL,
966                                      machine_password,
967                                      0,
968                                      Undefined, NULL);
969         free(machine_account);
970         free(machine_password);
971
972         if (!NT_STATUS_IS_OK(status)) {
973                 status = cli_full_connection(&cli, NULL,
974                                              dc_name,
975                                              NULL, 0,
976                                              "IPC$", "IPC",
977                                              "",
978                                              NULL,
979                                              "",
980                                              0,
981                                              Undefined, NULL);
982         }
983
984         if (!NT_STATUS_IS_OK(status)) {
985                 return status;
986         }
987
988         netlogon_pipe = get_schannel_session_key(cli,
989                                                  netbios_domain_name,
990                                                  &neg_flags, &status);
991         if (!netlogon_pipe) {
992                 if (NT_STATUS_EQUAL(status, NT_STATUS_INVALID_NETWORK_RESPONSE)) {
993                         cli_shutdown(cli);
994                         return NT_STATUS_OK;
995                 }
996
997                 DEBUG(0,("libnet_join_ok: failed to get schannel session "
998                         "key from server %s for domain %s. Error was %s\n",
999                 cli->desthost, netbios_domain_name, nt_errstr(status)));
1000                 cli_shutdown(cli);
1001                 return status;
1002         }
1003
1004         if (!lp_client_schannel()) {
1005                 cli_shutdown(cli);
1006                 return NT_STATUS_OK;
1007         }
1008
1009         pipe_hnd = cli_rpc_pipe_open_schannel_with_key(cli, PI_NETLOGON,
1010                                                        PIPE_AUTH_LEVEL_PRIVACY,
1011                                                        netbios_domain_name,
1012                                                        netlogon_pipe->dc,
1013                                                        &status);
1014
1015         cli_shutdown(cli);
1016
1017         if (!pipe_hnd) {
1018                 DEBUG(0,("libnet_join_ok: failed to open schannel session "
1019                         "on netlogon pipe to server %s for domain %s. "
1020                         "Error was %s\n",
1021                         cli->desthost, netbios_domain_name, nt_errstr(status)));
1022                 return status;
1023         }
1024
1025         return NT_STATUS_OK;
1026 }
1027
1028 /****************************************************************
1029 ****************************************************************/
1030
1031 static WERROR libnet_join_post_verify(TALLOC_CTX *mem_ctx,
1032                                       struct libnet_JoinCtx *r)
1033 {
1034         NTSTATUS status;
1035
1036         status = libnet_join_ok(r->out.netbios_domain_name,
1037                                 r->in.machine_name,
1038                                 r->in.dc_name);
1039         if (!NT_STATUS_IS_OK(status)) {
1040                 libnet_join_set_error_string(mem_ctx, r,
1041                         "failed to verify domain membership after joining: %s",
1042                         get_friendly_nt_error_msg(status));
1043                 return WERR_SETUP_NOT_JOINED;
1044         }
1045
1046         return WERR_OK;
1047 }
1048
1049 /****************************************************************
1050 ****************************************************************/
1051
1052 static bool libnet_join_unjoindomain_remove_secrets(TALLOC_CTX *mem_ctx,
1053                                                     struct libnet_UnjoinCtx *r)
1054 {
1055         if (!secrets_delete_machine_password_ex(lp_workgroup())) {
1056                 return false;
1057         }
1058
1059         if (!secrets_delete_domain_sid(lp_workgroup())) {
1060                 return false;
1061         }
1062
1063         return true;
1064 }
1065
1066 /****************************************************************
1067 ****************************************************************/
1068
1069 static NTSTATUS libnet_join_unjoindomain_rpc(TALLOC_CTX *mem_ctx,
1070                                              struct libnet_UnjoinCtx *r)
1071 {
1072         struct cli_state *cli = NULL;
1073         struct rpc_pipe_client *pipe_hnd = NULL;
1074         POLICY_HND sam_pol, domain_pol, user_pol;
1075         NTSTATUS status = NT_STATUS_UNSUCCESSFUL;
1076         char *acct_name;
1077         uint32_t user_rid;
1078         struct lsa_String lsa_acct_name;
1079         struct samr_Ids user_rids;
1080         struct samr_Ids name_types;
1081         union samr_UserInfo *info = NULL;
1082
1083         status = cli_full_connection(&cli, NULL,
1084                                      r->in.dc_name,
1085                                      NULL, 0,
1086                                      "IPC$", "IPC",
1087                                      r->in.admin_account,
1088                                      NULL,
1089                                      r->in.admin_password,
1090                                      0, Undefined, NULL);
1091
1092         if (!NT_STATUS_IS_OK(status)) {
1093                 goto done;
1094         }
1095
1096         /* Open the domain */
1097
1098         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SAMR, &status);
1099         if (!pipe_hnd) {
1100                 DEBUG(0,("Error connecting to SAM pipe. Error was %s\n",
1101                         nt_errstr(status)));
1102                 goto done;
1103         }
1104
1105         status = rpccli_samr_Connect2(pipe_hnd, mem_ctx,
1106                                       pipe_hnd->cli->desthost,
1107                                       SEC_RIGHTS_MAXIMUM_ALLOWED,
1108                                       &sam_pol);
1109         if (!NT_STATUS_IS_OK(status)) {
1110                 goto done;
1111         }
1112
1113         status = rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
1114                                         &sam_pol,
1115                                         SEC_RIGHTS_MAXIMUM_ALLOWED,
1116                                         r->in.domain_sid,
1117                                         &domain_pol);
1118         if (!NT_STATUS_IS_OK(status)) {
1119                 goto done;
1120         }
1121
1122         /* Create domain user */
1123
1124         acct_name = talloc_asprintf(mem_ctx, "%s$", r->in.machine_name);
1125         strlower_m(acct_name);
1126
1127         init_lsa_String(&lsa_acct_name, acct_name);
1128
1129         status = rpccli_samr_LookupNames(pipe_hnd, mem_ctx,
1130                                          &domain_pol,
1131                                          1,
1132                                          &lsa_acct_name,
1133                                          &user_rids,
1134                                          &name_types);
1135
1136         if (!NT_STATUS_IS_OK(status)) {
1137                 goto done;
1138         }
1139
1140         if (name_types.ids[0] != SID_NAME_USER) {
1141                 DEBUG(0, ("%s is not a user account (type=%d)\n", acct_name,
1142                         name_types.ids[0]));
1143                 status = NT_STATUS_INVALID_WORKSTATION;
1144                 goto done;
1145         }
1146
1147         user_rid = user_rids.ids[0];
1148
1149         /* Open handle on user */
1150
1151         status = rpccli_samr_OpenUser(pipe_hnd, mem_ctx,
1152                                       &domain_pol,
1153                                       SEC_RIGHTS_MAXIMUM_ALLOWED,
1154                                       user_rid,
1155                                       &user_pol);
1156         if (!NT_STATUS_IS_OK(status)) {
1157                 goto done;
1158         }
1159
1160         /* Get user info */
1161
1162         status = rpccli_samr_QueryUserInfo(pipe_hnd, mem_ctx,
1163                                            &user_pol,
1164                                            16,
1165                                            &info);
1166         if (!NT_STATUS_IS_OK(status)) {
1167                 rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
1168                 goto done;
1169         }
1170
1171         /* now disable and setuser info */
1172
1173         info->info16.acct_flags |= ACB_DISABLED;
1174
1175         status = rpccli_samr_SetUserInfo(pipe_hnd, mem_ctx,
1176                                          &user_pol,
1177                                          16,
1178                                          info);
1179
1180         rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
1181
1182 done:
1183         if (pipe_hnd) {
1184                 rpccli_samr_Close(pipe_hnd, mem_ctx, &domain_pol);
1185                 rpccli_samr_Close(pipe_hnd, mem_ctx, &sam_pol);
1186                 cli_rpc_pipe_close(pipe_hnd);
1187         }
1188
1189         if (cli) {
1190                 cli_shutdown(cli);
1191         }
1192
1193         return status;
1194 }
1195
1196 /****************************************************************
1197 ****************************************************************/
1198
1199 static WERROR do_join_modify_vals_config(struct libnet_JoinCtx *r)
1200 {
1201         WERROR werr;
1202         struct smbconf_ctx *ctx;
1203
1204         werr = smbconf_init_reg(r, &ctx);
1205         if (!W_ERROR_IS_OK(werr)) {
1206                 goto done;
1207         }
1208
1209         if (!(r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE)) {
1210
1211                 werr = smbconf_set_global_parameter(ctx, "security", "user");
1212                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1213
1214                 werr = smbconf_set_global_parameter(ctx, "workgroup",
1215                                                     r->in.domain_name);
1216                 goto done;
1217         }
1218
1219         werr = smbconf_set_global_parameter(ctx, "security", "domain");
1220         W_ERROR_NOT_OK_GOTO_DONE(werr);
1221
1222         werr = smbconf_set_global_parameter(ctx, "workgroup",
1223                                             r->out.netbios_domain_name);
1224         W_ERROR_NOT_OK_GOTO_DONE(werr);
1225
1226         if (r->out.domain_is_ad) {
1227                 werr = smbconf_set_global_parameter(ctx, "security", "ads");
1228                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1229
1230                 werr = smbconf_set_global_parameter(ctx, "realm",
1231                                                     r->out.dns_domain_name);
1232                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1233         }
1234
1235  done:
1236         smbconf_shutdown(ctx);
1237         return werr;
1238 }
1239
1240 /****************************************************************
1241 ****************************************************************/
1242
1243 static WERROR do_unjoin_modify_vals_config(struct libnet_UnjoinCtx *r)
1244 {
1245         WERROR werr = WERR_OK;
1246         struct smbconf_ctx *ctx;
1247
1248         werr = smbconf_init_reg(r, &ctx);
1249         if (!W_ERROR_IS_OK(werr)) {
1250                 goto done;
1251         }
1252
1253         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1254
1255                 werr = smbconf_set_global_parameter(ctx, "security", "user");
1256                 W_ERROR_NOT_OK_GOTO_DONE(werr);
1257                 smbconf_delete_global_parameter(ctx, "realm");
1258         }
1259
1260  done:
1261         smbconf_shutdown(ctx);
1262         return werr;
1263 }
1264
1265 /****************************************************************
1266 ****************************************************************/
1267
1268 static WERROR do_JoinConfig(struct libnet_JoinCtx *r)
1269 {
1270         WERROR werr;
1271
1272         if (!W_ERROR_IS_OK(r->out.result)) {
1273                 return r->out.result;
1274         }
1275
1276         if (!r->in.modify_config) {
1277                 return WERR_OK;
1278         }
1279
1280         werr = do_join_modify_vals_config(r);
1281         if (!W_ERROR_IS_OK(werr)) {
1282                 return werr;
1283         }
1284
1285         r->out.modified_config = true;
1286         r->out.result = werr;
1287
1288         return werr;
1289 }
1290
1291 /****************************************************************
1292 ****************************************************************/
1293
1294 static WERROR libnet_unjoin_config(struct libnet_UnjoinCtx *r)
1295 {
1296         WERROR werr;
1297
1298         if (!W_ERROR_IS_OK(r->out.result)) {
1299                 return r->out.result;
1300         }
1301
1302         if (!r->in.modify_config) {
1303                 return WERR_OK;
1304         }
1305
1306         werr = do_unjoin_modify_vals_config(r);
1307         if (!W_ERROR_IS_OK(werr)) {
1308                 return werr;
1309         }
1310
1311         r->out.modified_config = true;
1312         r->out.result = werr;
1313
1314         return werr;
1315 }
1316
1317 /****************************************************************
1318 ****************************************************************/
1319
1320 static WERROR libnet_join_pre_processing(TALLOC_CTX *mem_ctx,
1321                                          struct libnet_JoinCtx *r)
1322 {
1323         if (!r->in.domain_name) {
1324                 libnet_join_set_error_string(mem_ctx, r,
1325                         "No domain name defined");
1326                 return WERR_INVALID_PARAM;
1327         }
1328
1329         if (r->in.modify_config && !lp_config_backend_is_registry()) {
1330                 libnet_join_set_error_string(mem_ctx, r,
1331                         "Configuration manipulation requested but not "
1332                         "supported by backend");
1333                 return WERR_NOT_SUPPORTED;
1334         }
1335
1336         if (IS_DC) {
1337                 return WERR_SETUP_DOMAIN_CONTROLLER;
1338         }
1339
1340         if (!secrets_init()) {
1341                 libnet_join_set_error_string(mem_ctx, r,
1342                         "Unable to open secrets database");
1343                 return WERR_CAN_NOT_COMPLETE;
1344         }
1345
1346         return WERR_OK;
1347 }
1348
1349 /****************************************************************
1350 ****************************************************************/
1351
1352 static WERROR libnet_join_post_processing(TALLOC_CTX *mem_ctx,
1353                                           struct libnet_JoinCtx *r)
1354 {
1355         WERROR werr;
1356
1357         if (!W_ERROR_IS_OK(r->out.result)) {
1358                 return r->out.result;
1359         }
1360
1361         werr = do_JoinConfig(r);
1362         if (!W_ERROR_IS_OK(werr)) {
1363                 return werr;
1364         }
1365
1366         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1367                 saf_store(r->in.domain_name, r->in.dc_name);
1368         }
1369
1370         return WERR_OK;
1371 }
1372
1373 /****************************************************************
1374 ****************************************************************/
1375
1376 static int libnet_destroy_JoinCtx(struct libnet_JoinCtx *r)
1377 {
1378         if (r->in.ads) {
1379                 ads_destroy(&r->in.ads);
1380         }
1381
1382         return 0;
1383 }
1384
1385 /****************************************************************
1386 ****************************************************************/
1387
1388 static int libnet_destroy_UnjoinCtx(struct libnet_UnjoinCtx *r)
1389 {
1390         if (r->in.ads) {
1391                 ads_destroy(&r->in.ads);
1392         }
1393
1394         return 0;
1395 }
1396
1397 /****************************************************************
1398 ****************************************************************/
1399
1400 WERROR libnet_init_JoinCtx(TALLOC_CTX *mem_ctx,
1401                            struct libnet_JoinCtx **r)
1402 {
1403         struct libnet_JoinCtx *ctx;
1404
1405         ctx = talloc_zero(mem_ctx, struct libnet_JoinCtx);
1406         if (!ctx) {
1407                 return WERR_NOMEM;
1408         }
1409
1410         talloc_set_destructor(ctx, libnet_destroy_JoinCtx);
1411
1412         ctx->in.machine_name = talloc_strdup(mem_ctx, global_myname());
1413         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
1414
1415         ctx->in.secure_channel_type = SEC_CHAN_WKSTA;
1416
1417         *r = ctx;
1418
1419         return WERR_OK;
1420 }
1421
1422 /****************************************************************
1423 ****************************************************************/
1424
1425 WERROR libnet_init_UnjoinCtx(TALLOC_CTX *mem_ctx,
1426                              struct libnet_UnjoinCtx **r)
1427 {
1428         struct libnet_UnjoinCtx *ctx;
1429
1430         ctx = talloc_zero(mem_ctx, struct libnet_UnjoinCtx);
1431         if (!ctx) {
1432                 return WERR_NOMEM;
1433         }
1434
1435         talloc_set_destructor(ctx, libnet_destroy_UnjoinCtx);
1436
1437         ctx->in.machine_name = talloc_strdup(mem_ctx, global_myname());
1438         W_ERROR_HAVE_NO_MEMORY(ctx->in.machine_name);
1439
1440         *r = ctx;
1441
1442         return WERR_OK;
1443 }
1444
1445 /****************************************************************
1446 ****************************************************************/
1447
1448 static WERROR libnet_DomainJoin(TALLOC_CTX *mem_ctx,
1449                                 struct libnet_JoinCtx *r)
1450 {
1451         NTSTATUS status;
1452 #ifdef WITH_ADS
1453         ADS_STATUS ads_status;
1454 #endif /* WITH_ADS */
1455
1456         if (!r->in.dc_name) {
1457                 struct netr_DsRGetDCNameInfo *info;
1458                 status = dsgetdcname(mem_ctx,
1459                                      r->in.domain_name,
1460                                      NULL,
1461                                      NULL,
1462                                      DS_DIRECTORY_SERVICE_REQUIRED |
1463                                      DS_WRITABLE_REQUIRED |
1464                                      DS_RETURN_DNS_NAME,
1465                                      &info);
1466                 if (!NT_STATUS_IS_OK(status)) {
1467                         libnet_join_set_error_string(mem_ctx, r,
1468                                 "failed to find DC for domain %s",
1469                                 r->in.domain_name,
1470                                 get_friendly_nt_error_msg(status));
1471                         return WERR_DOMAIN_CONTROLLER_NOT_FOUND;
1472                 }
1473
1474                 r->in.dc_name = talloc_strdup(mem_ctx,
1475                                               info->dc_unc);
1476                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
1477         }
1478
1479 #ifdef WITH_ADS
1480         if (r->in.account_ou) {
1481
1482                 ads_status = libnet_join_connect_ads(mem_ctx, r);
1483                 if (!ADS_ERR_OK(ads_status)) {
1484                         return WERR_DEFAULT_JOIN_REQUIRED;
1485                 }
1486
1487                 ads_status = libnet_join_precreate_machine_acct(mem_ctx, r);
1488                 if (!ADS_ERR_OK(ads_status)) {
1489                         libnet_join_set_error_string(mem_ctx, r,
1490                                 "failed to precreate account in ou %s: %s",
1491                                 r->in.account_ou,
1492                                 ads_errstr(ads_status));
1493                         return WERR_DEFAULT_JOIN_REQUIRED;
1494                 }
1495
1496                 r->in.join_flags &= ~WKSSVC_JOIN_FLAGS_ACCOUNT_CREATE;
1497         }
1498 #endif /* WITH_ADS */
1499
1500         status = libnet_join_joindomain_rpc(mem_ctx, r);
1501         if (!NT_STATUS_IS_OK(status)) {
1502                 libnet_join_set_error_string(mem_ctx, r,
1503                         "failed to join domain over rpc: %s",
1504                         get_friendly_nt_error_msg(status));
1505                 if (NT_STATUS_EQUAL(status, NT_STATUS_USER_EXISTS)) {
1506                         return WERR_SETUP_ALREADY_JOINED;
1507                 }
1508                 return ntstatus_to_werror(status);
1509         }
1510
1511         if (!libnet_join_joindomain_store_secrets(mem_ctx, r)) {
1512                 return WERR_SETUP_NOT_JOINED;
1513         }
1514
1515 #ifdef WITH_ADS
1516         if (r->out.domain_is_ad) {
1517                 ads_status  = libnet_join_post_processing_ads(mem_ctx, r);
1518                 if (!ADS_ERR_OK(ads_status)) {
1519                         return WERR_GENERAL_FAILURE;
1520                 }
1521         }
1522 #endif /* WITH_ADS */
1523
1524         return WERR_OK;
1525 }
1526
1527 /****************************************************************
1528 ****************************************************************/
1529
1530 WERROR libnet_Join(TALLOC_CTX *mem_ctx,
1531                    struct libnet_JoinCtx *r)
1532 {
1533         WERROR werr;
1534
1535         if (r->in.debug) {
1536                 LIBNET_JOIN_IN_DUMP_CTX(mem_ctx, r);
1537         }
1538
1539         werr = libnet_join_pre_processing(mem_ctx, r);
1540         if (!W_ERROR_IS_OK(werr)) {
1541                 goto done;
1542         }
1543
1544         if (r->in.join_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1545                 werr = libnet_DomainJoin(mem_ctx, r);
1546                 if (!W_ERROR_IS_OK(werr)) {
1547                         goto done;
1548                 }
1549
1550                 werr = libnet_join_post_verify(mem_ctx, r);
1551                 if (!W_ERROR_IS_OK(werr)) {
1552                         goto done;
1553                 }
1554         }
1555
1556         werr = libnet_join_post_processing(mem_ctx, r);
1557         if (!W_ERROR_IS_OK(werr)) {
1558                 goto done;
1559         }
1560  done:
1561         r->out.result = werr;
1562
1563         if (r->in.debug) {
1564                 LIBNET_JOIN_OUT_DUMP_CTX(mem_ctx, r);
1565         }
1566         return werr;
1567 }
1568
1569 /****************************************************************
1570 ****************************************************************/
1571
1572 static WERROR libnet_DomainUnjoin(TALLOC_CTX *mem_ctx,
1573                                   struct libnet_UnjoinCtx *r)
1574 {
1575         NTSTATUS status;
1576
1577         if (!r->in.domain_sid) {
1578                 struct dom_sid sid;
1579                 if (!secrets_fetch_domain_sid(lp_workgroup(), &sid)) {
1580                         libnet_unjoin_set_error_string(mem_ctx, r,
1581                                 "Unable to fetch domain sid: are we joined?");
1582                         return WERR_SETUP_NOT_JOINED;
1583                 }
1584                 r->in.domain_sid = sid_dup_talloc(mem_ctx, &sid);
1585                 W_ERROR_HAVE_NO_MEMORY(r->in.domain_sid);
1586         }
1587
1588         if (!r->in.dc_name) {
1589                 struct netr_DsRGetDCNameInfo *info;
1590                 status = dsgetdcname(mem_ctx,
1591                                      r->in.domain_name,
1592                                      NULL,
1593                                      NULL,
1594                                      DS_DIRECTORY_SERVICE_REQUIRED |
1595                                      DS_WRITABLE_REQUIRED |
1596                                      DS_RETURN_DNS_NAME,
1597                                      &info);
1598                 if (!NT_STATUS_IS_OK(status)) {
1599                         libnet_unjoin_set_error_string(mem_ctx, r,
1600                                 "failed to find DC for domain %s",
1601                                 r->in.domain_name,
1602                                 get_friendly_nt_error_msg(status));
1603                         return WERR_DOMAIN_CONTROLLER_NOT_FOUND;
1604                 }
1605
1606                 r->in.dc_name = talloc_strdup(mem_ctx,
1607                                               info->dc_unc);
1608                 W_ERROR_HAVE_NO_MEMORY(r->in.dc_name);
1609         }
1610
1611         status = libnet_join_unjoindomain_rpc(mem_ctx, r);
1612         if (!NT_STATUS_IS_OK(status)) {
1613                 libnet_unjoin_set_error_string(mem_ctx, r,
1614                         "failed to disable machine account via rpc: %s",
1615                         get_friendly_nt_error_msg(status));
1616                 if (NT_STATUS_EQUAL(status, NT_STATUS_NO_SUCH_USER)) {
1617                         return WERR_SETUP_NOT_JOINED;
1618                 }
1619                 return ntstatus_to_werror(status);
1620         }
1621
1622         r->out.disabled_machine_account = true;
1623
1624 #ifdef WITH_ADS
1625         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_ACCOUNT_DELETE) {
1626                 ADS_STATUS ads_status;
1627                 libnet_unjoin_connect_ads(mem_ctx, r);
1628                 ads_status = libnet_unjoin_remove_machine_acct(mem_ctx, r);
1629                 if (!ADS_ERR_OK(ads_status)) {
1630                         libnet_unjoin_set_error_string(mem_ctx, r,
1631                                 "failed to remove machine account from AD: %s",
1632                                 ads_errstr(ads_status));
1633                 } else {
1634                         r->out.deleted_machine_account = true;
1635                         /* dirty hack */
1636                         r->out.dns_domain_name = talloc_strdup(mem_ctx,
1637                                                                r->in.ads->server.realm);
1638                         W_ERROR_HAVE_NO_MEMORY(r->out.dns_domain_name);
1639                 }
1640         }
1641 #endif /* WITH_ADS */
1642
1643         libnet_join_unjoindomain_remove_secrets(mem_ctx, r);
1644
1645         return WERR_OK;
1646 }
1647
1648 /****************************************************************
1649 ****************************************************************/
1650
1651 static WERROR libnet_unjoin_pre_processing(TALLOC_CTX *mem_ctx,
1652                                            struct libnet_UnjoinCtx *r)
1653 {
1654         if (!r->in.domain_name) {
1655                 libnet_unjoin_set_error_string(mem_ctx, r,
1656                         "No domain name defined");
1657                 return WERR_INVALID_PARAM;
1658         }
1659
1660         if (r->in.modify_config && !lp_config_backend_is_registry()) {
1661                 libnet_unjoin_set_error_string(mem_ctx, r,
1662                         "Configuration manipulation requested but not "
1663                         "supported by backend");
1664                 return WERR_NOT_SUPPORTED;
1665         }
1666
1667         if (IS_DC) {
1668                 return WERR_SETUP_DOMAIN_CONTROLLER;
1669         }
1670
1671         if (!secrets_init()) {
1672                 libnet_unjoin_set_error_string(mem_ctx, r,
1673                         "Unable to open secrets database");
1674                 return WERR_CAN_NOT_COMPLETE;
1675         }
1676
1677         return WERR_OK;
1678 }
1679
1680 /****************************************************************
1681 ****************************************************************/
1682
1683 static WERROR libnet_unjoin_post_processing(TALLOC_CTX *mem_ctx,
1684                                             struct libnet_UnjoinCtx *r)
1685 {
1686         saf_delete(r->out.netbios_domain_name);
1687         saf_delete(r->out.dns_domain_name);
1688
1689         return libnet_unjoin_config(r);
1690 }
1691
1692 /****************************************************************
1693 ****************************************************************/
1694
1695 WERROR libnet_Unjoin(TALLOC_CTX *mem_ctx,
1696                      struct libnet_UnjoinCtx *r)
1697 {
1698         WERROR werr;
1699
1700         if (r->in.debug) {
1701                 LIBNET_UNJOIN_IN_DUMP_CTX(mem_ctx, r);
1702         }
1703
1704         werr = libnet_unjoin_pre_processing(mem_ctx, r);
1705         if (!W_ERROR_IS_OK(werr)) {
1706                 goto done;
1707         }
1708
1709         if (r->in.unjoin_flags & WKSSVC_JOIN_FLAGS_JOIN_TYPE) {
1710                 werr = libnet_DomainUnjoin(mem_ctx, r);
1711                 if (!W_ERROR_IS_OK(werr)) {
1712                         libnet_unjoin_config(r);
1713                         goto done;
1714                 }
1715         }
1716
1717         werr = libnet_unjoin_post_processing(mem_ctx, r);
1718         if (!W_ERROR_IS_OK(werr)) {
1719                 goto done;
1720         }
1721
1722  done:
1723         r->out.result = werr;
1724
1725         if (r->in.debug) {
1726                 LIBNET_UNJOIN_OUT_DUMP_CTX(mem_ctx, r);
1727         }
1728
1729         return werr;
1730 }