50383fee6b52b1513f86dd1611623046a1af1197
[kai/samba.git] / source3 / utils / net_rpc_join.c
1 /*
2    Samba Unix/Linux SMB client library
3    Distributed SMB/CIFS Server Management Utility
4    Copyright (C) 2001 Andrew Bartlett (abartlet@samba.org)
5    Copyright (C) Tim Potter     2001
6    Copyright (C) 2008 Guenther Deschner
7
8    This program is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 3 of the License, or
11    (at your option) any later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
20
21 #include "includes.h"
22 #include "utils/net.h"
23 #include "rpc_client/cli_pipe.h"
24 #include "../libcli/auth/libcli_auth.h"
25 #include "../librpc/gen_ndr/ndr_lsa_c.h"
26 #include "rpc_client/cli_lsarpc.h"
27 #include "../librpc/gen_ndr/ndr_samr_c.h"
28 #include "rpc_client/init_samr.h"
29 #include "../librpc/gen_ndr/ndr_netlogon.h"
30 #include "rpc_client/cli_netlogon.h"
31 #include "secrets.h"
32 #include "rpc_client/init_lsa.h"
33 #include "libsmb/libsmb.h"
34 #include "../libcli/smb/smbXcli_base.h"
35
36 /* Macro for checking RPC error codes to make things more readable */
37
38 #define CHECK_RPC_ERR(rpc, msg) \
39         if (!NT_STATUS_IS_OK(status = rpc)) { \
40                 DEBUG(0, (msg ": %s\n", nt_errstr(status))); \
41                 goto done; \
42         }
43
44 #define CHECK_DCERPC_ERR(rpc, msg) \
45         if (!NT_STATUS_IS_OK(status = rpc)) { \
46                 DEBUG(0, (msg ": %s\n", nt_errstr(status))); \
47                 goto done; \
48         } \
49         if (!NT_STATUS_IS_OK(result)) { \
50                 status = result; \
51                 DEBUG(0, (msg ": %s\n", nt_errstr(result))); \
52                 goto done; \
53         }
54
55
56 #define CHECK_RPC_ERR_DEBUG(rpc, debug_args) \
57         if (!NT_STATUS_IS_OK(status = rpc)) { \
58                 DEBUG(0, debug_args); \
59                 goto done; \
60         }
61
62 #define CHECK_DCERPC_ERR_DEBUG(rpc, debug_args) \
63         if (!NT_STATUS_IS_OK(status = rpc)) { \
64                 DEBUG(0, debug_args); \
65                 goto done; \
66         } \
67         if (!NT_STATUS_IS_OK(result)) { \
68                 status = result; \
69                 DEBUG(0, debug_args); \
70                 goto done; \
71         }
72
73
74 /**
75  * confirm that a domain join is still valid
76  *
77  * @return A shell status integer (0 for success)
78  *
79  **/
80 NTSTATUS net_rpc_join_ok(struct net_context *c, const char *domain,
81                          const char *server,
82                          const struct sockaddr_storage *server_ss)
83 {
84         enum security_types sec;
85         unsigned int conn_flags = NET_FLAGS_PDC;
86         uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
87         struct cli_state *cli = NULL;
88         struct rpc_pipe_client *pipe_hnd = NULL;
89         struct rpc_pipe_client *netlogon_pipe = NULL;
90         NTSTATUS ntret = NT_STATUS_UNSUCCESSFUL;
91
92         sec = (enum security_types)lp_security();
93
94         if (sec == SEC_ADS) {
95                 /* Connect to IPC$ using machine account's credentials. We don't use anonymous
96                    connection here, as it may be denied by server's local policy. */
97                 net_use_machine_account(c);
98
99         } else {
100                 /* some servers (e.g. WinNT) don't accept machine-authenticated
101                    smb connections */
102                 conn_flags |= NET_FLAGS_ANONYMOUS;
103         }
104
105         /* Connect to remote machine */
106         ntret = net_make_ipc_connection_ex(c, domain, server, server_ss,
107                                            conn_flags, &cli);
108         if (!NT_STATUS_IS_OK(ntret)) {
109                 return ntret;
110         }
111
112         /* Setup the creds as though we're going to do schannel... */
113         ntret = get_schannel_session_key(cli, domain, &neg_flags,
114                                          &netlogon_pipe);
115
116         /* We return NT_STATUS_INVALID_NETWORK_RESPONSE if the server is refusing
117            to negotiate schannel, but the creds were set up ok. That'll have to do. */
118
119         if (!NT_STATUS_IS_OK(ntret)) {
120                 if (NT_STATUS_EQUAL(ntret, NT_STATUS_INVALID_NETWORK_RESPONSE)) {
121                         cli_shutdown(cli);
122                         return NT_STATUS_OK;
123                 } else {
124                         DEBUG(0,("net_rpc_join_ok: failed to get schannel session "
125                                         "key from server %s for domain %s. Error was %s\n",
126                                 smbXcli_conn_remote_name(cli->conn), domain, nt_errstr(ntret) ));
127                         cli_shutdown(cli);
128                         return ntret;
129                 }
130         }
131
132         /* Only do the rest of the schannel test if the client is allowed to do this. */
133         if (!lp_client_schannel()) {
134                 cli_shutdown(cli);
135                 /* We're good... */
136                 return ntret;
137         }
138
139         ntret = cli_rpc_pipe_open_schannel_with_key(
140                 cli, &ndr_table_netlogon.syntax_id, NCACN_NP,
141                 DCERPC_AUTH_LEVEL_PRIVACY,
142                 domain, &netlogon_pipe->dc, &pipe_hnd);
143
144         if (!NT_STATUS_IS_OK(ntret)) {
145                 DEBUG(0,("net_rpc_join_ok: failed to open schannel session "
146                                 "on netlogon pipe to server %s for domain %s. Error was %s\n",
147                         smbXcli_conn_remote_name(cli->conn), domain, nt_errstr(ntret) ));
148                 /*
149                  * Note: here, we have:
150                  * (pipe_hnd != NULL) if and only if NT_STATUS_IS_OK(ntret)
151                  */
152         }
153
154         cli_shutdown(cli);
155         return ntret;
156 }
157
158 /**
159  * Join a domain using the administrator username and password
160  *
161  * @param argc  Standard main() style argc
162  * @param argc  Standard main() style argv.  Initial components are already
163  *              stripped.  Currently not used.
164  * @return A shell status integer (0 for success)
165  *
166  **/
167
168 int net_rpc_join_newstyle(struct net_context *c, int argc, const char **argv)
169 {
170
171         /* libsmb variables */
172
173         struct cli_state *cli;
174         TALLOC_CTX *mem_ctx;
175         uint32 acb_info = ACB_WSTRUST;
176         uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
177         enum netr_SchannelType sec_channel_type;
178         struct rpc_pipe_client *pipe_hnd = NULL;
179         struct dcerpc_binding_handle *b = NULL;
180
181         /* rpc variables */
182
183         struct policy_handle lsa_pol, sam_pol, domain_pol, user_pol;
184         struct dom_sid *domain_sid;
185         uint32 user_rid;
186
187         /* Password stuff */
188
189         DATA_BLOB session_key = data_blob_null;
190         char *clear_trust_password = NULL;
191         struct samr_CryptPassword crypt_pwd;
192         uchar md4_trust_password[16];
193         union samr_UserInfo set_info;
194
195         /* Misc */
196
197         NTSTATUS status, result;
198         int retval = 1;
199         const char *domain = NULL;
200         char *acct_name;
201         struct lsa_String lsa_acct_name;
202         uint32 acct_flags=0;
203         uint32_t access_granted = 0;
204         union lsa_PolicyInformation *info = NULL;
205         struct samr_Ids user_rids;
206         struct samr_Ids name_types;
207
208
209         /* check what type of join */
210         if (argc >= 0) {
211                 sec_channel_type = get_sec_channel_type(argv[0]);
212         } else {
213                 sec_channel_type = get_sec_channel_type(NULL);
214         }
215
216         switch (sec_channel_type) {
217         case SEC_CHAN_WKSTA:
218                 acb_info = ACB_WSTRUST;
219                 break;
220         case SEC_CHAN_BDC:
221                 acb_info = ACB_SVRTRUST;
222                 break;
223 #if 0
224         case SEC_CHAN_DOMAIN:
225                 acb_info = ACB_DOMTRUST;
226                 break;
227 #endif
228         default:
229                 DEBUG(0,("secure channel type %d not yet supported\n",
230                         sec_channel_type));
231                 break;
232         }
233
234         /* Make authenticated connection to remote machine */
235
236         status = net_make_ipc_connection(c, NET_FLAGS_PDC, &cli);
237         if (!NT_STATUS_IS_OK(status)) {
238                 return 1;
239         }
240
241         if (!(mem_ctx = talloc_init("net_rpc_join_newstyle"))) {
242                 DEBUG(0, ("Could not initialise talloc context\n"));
243                 goto done;
244         }
245
246         /* Fetch domain sid */
247
248         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc.syntax_id,
249                                           &pipe_hnd);
250         if (!NT_STATUS_IS_OK(status)) {
251                 DEBUG(0, ("Error connecting to LSA pipe. Error was %s\n",
252                         nt_errstr(status) ));
253                 goto done;
254         }
255
256         b = pipe_hnd->binding_handle;
257
258         CHECK_RPC_ERR(rpccli_lsa_open_policy(pipe_hnd, mem_ctx, true,
259                                           SEC_FLAG_MAXIMUM_ALLOWED,
260                                           &lsa_pol),
261                       "error opening lsa policy handle");
262
263         CHECK_DCERPC_ERR(dcerpc_lsa_QueryInfoPolicy(b, mem_ctx,
264                                                     &lsa_pol,
265                                                     LSA_POLICY_INFO_ACCOUNT_DOMAIN,
266                                                     &info,
267                                                     &result),
268                       "error querying info policy");
269
270         domain = info->account_domain.name.string;
271         domain_sid = info->account_domain.sid;
272
273         dcerpc_lsa_Close(b, mem_ctx, &lsa_pol, &result);
274         TALLOC_FREE(pipe_hnd); /* Done with this pipe */
275
276         /* Bail out if domain didn't get set. */
277         if (!domain) {
278                 DEBUG(0, ("Could not get domain name.\n"));
279                 goto done;
280         }
281
282         /* Create domain user */
283         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_samr.syntax_id,
284                                           &pipe_hnd);
285         if (!NT_STATUS_IS_OK(status)) {
286                 DEBUG(0, ("Error connecting to SAM pipe. Error was %s\n",
287                         nt_errstr(status) ));
288                 goto done;
289         }
290
291         b = pipe_hnd->binding_handle;
292
293         status = cli_get_session_key(mem_ctx, pipe_hnd, &session_key);
294         if (!NT_STATUS_IS_OK(status)) {
295                 DEBUG(0,("Error getting session_key of SAM pipe. Error was %s\n",
296                         nt_errstr(status)));
297                 goto done;
298         }
299
300         CHECK_DCERPC_ERR(dcerpc_samr_Connect2(b, mem_ctx,
301                                               pipe_hnd->desthost,
302                                               SAMR_ACCESS_ENUM_DOMAINS
303                                               | SAMR_ACCESS_LOOKUP_DOMAIN,
304                                               &sam_pol,
305                                               &result),
306                       "could not connect to SAM database");
307
308
309         CHECK_DCERPC_ERR(dcerpc_samr_OpenDomain(b, mem_ctx,
310                                                 &sam_pol,
311                                                 SAMR_DOMAIN_ACCESS_LOOKUP_INFO_1
312                                                 | SAMR_DOMAIN_ACCESS_CREATE_USER
313                                                 | SAMR_DOMAIN_ACCESS_OPEN_ACCOUNT,
314                                                 domain_sid,
315                                                 &domain_pol,
316                                                 &result),
317                       "could not open domain");
318
319         /* Create domain user */
320         if ((acct_name = talloc_asprintf(mem_ctx, "%s$", lp_netbios_name())) == NULL) {
321                 status = NT_STATUS_NO_MEMORY;
322                 goto done;
323         }
324         strlower_m(acct_name);
325
326         init_lsa_String(&lsa_acct_name, acct_name);
327
328         acct_flags = SEC_GENERIC_READ | SEC_GENERIC_WRITE | SEC_GENERIC_EXECUTE |
329                      SEC_STD_WRITE_DAC | SEC_STD_DELETE |
330                      SAMR_USER_ACCESS_SET_PASSWORD |
331                      SAMR_USER_ACCESS_GET_ATTRIBUTES |
332                      SAMR_USER_ACCESS_SET_ATTRIBUTES;
333
334         DEBUG(10, ("Creating account with flags: %d\n",acct_flags));
335
336         status = dcerpc_samr_CreateUser2(b, mem_ctx,
337                                          &domain_pol,
338                                          &lsa_acct_name,
339                                          acb_info,
340                                          acct_flags,
341                                          &user_pol,
342                                          &access_granted,
343                                          &user_rid,
344                                          &result);
345         if (!NT_STATUS_IS_OK(status)) {
346                 goto done;
347         }
348         if (!NT_STATUS_IS_OK(result) &&
349             !NT_STATUS_EQUAL(result, NT_STATUS_USER_EXISTS)) {
350                 status = result;
351                 d_fprintf(stderr,_("Creation of workstation account failed\n"));
352
353                 /* If NT_STATUS_ACCESS_DENIED then we have a valid
354                    username/password combo but the user does not have
355                    administrator access. */
356
357                 if (NT_STATUS_V(result) == NT_STATUS_V(NT_STATUS_ACCESS_DENIED))
358                         d_fprintf(stderr, _("User specified does not have "
359                                             "administrator privileges\n"));
360
361                 goto done;
362         }
363
364         /* We *must* do this.... don't ask... */
365
366         if (NT_STATUS_IS_OK(result)) {
367                 dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
368         }
369
370         CHECK_DCERPC_ERR_DEBUG(dcerpc_samr_LookupNames(b, mem_ctx,
371                                                        &domain_pol,
372                                                        1,
373                                                        &lsa_acct_name,
374                                                        &user_rids,
375                                                        &name_types,
376                                                        &result),
377                             ("error looking up rid for user %s: %s/%s\n",
378                              acct_name, nt_errstr(status), nt_errstr(result)));
379
380         if (name_types.ids[0] != SID_NAME_USER) {
381                 DEBUG(0, ("%s is not a user account (type=%d)\n", acct_name, name_types.ids[0]));
382                 goto done;
383         }
384
385         user_rid = user_rids.ids[0];
386
387         /* Open handle on user */
388
389         CHECK_DCERPC_ERR_DEBUG(
390                 dcerpc_samr_OpenUser(b, mem_ctx,
391                                      &domain_pol,
392                                      SEC_FLAG_MAXIMUM_ALLOWED,
393                                      user_rid,
394                                      &user_pol,
395                                      &result),
396                 ("could not re-open existing user %s: %s/%s\n",
397                  acct_name, nt_errstr(status), nt_errstr(result)));
398         
399         /* Create a random machine account password */
400
401         clear_trust_password = generate_random_str(talloc_tos(), DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH);
402         E_md4hash(clear_trust_password, md4_trust_password);
403
404         /* Set password on machine account */
405
406         init_samr_CryptPassword(clear_trust_password,
407                                 &session_key,
408                                 &crypt_pwd);
409
410         set_info.info24.password = crypt_pwd;
411         set_info.info24.password_expired = PASS_DONT_CHANGE_AT_NEXT_LOGON;
412
413         CHECK_DCERPC_ERR(dcerpc_samr_SetUserInfo2(b, mem_ctx,
414                                                   &user_pol,
415                                                   24,
416                                                   &set_info,
417                                                   &result),
418                       "error setting trust account password");
419
420         /* Why do we have to try to (re-)set the ACB to be the same as what
421            we passed in the samr_create_dom_user() call?  When a NT
422            workstation is joined to a domain by an administrator the
423            acb_info is set to 0x80.  For a normal user with "Add
424            workstations to the domain" rights the acb_info is 0x84.  I'm
425            not sure whether it is supposed to make a difference or not.  NT
426            seems to cope with either value so don't bomb out if the set
427            userinfo2 level 0x10 fails.  -tpot */
428
429         set_info.info16.acct_flags = acb_info;
430
431         /* Ignoring the return value is necessary for joining a domain
432            as a normal user with "Add workstation to domain" privilege. */
433
434         status = dcerpc_samr_SetUserInfo(b, mem_ctx,
435                                          &user_pol,
436                                          16,
437                                          &set_info,
438                                          &result);
439
440         dcerpc_samr_Close(b, mem_ctx, &user_pol, &result);
441         TALLOC_FREE(pipe_hnd); /* Done with this pipe */
442
443         /* Now check the whole process from top-to-bottom */
444
445         status = cli_rpc_pipe_open_noauth(cli, &ndr_table_netlogon.syntax_id,
446                                           &pipe_hnd);
447         if (!NT_STATUS_IS_OK(status)) {
448                 DEBUG(0,("Error connecting to NETLOGON pipe. Error was %s\n",
449                         nt_errstr(status) ));
450                 goto done;
451         }
452
453         status = rpccli_netlogon_setup_creds(pipe_hnd,
454                                         pipe_hnd->desthost, /* server name */
455                                         domain,        /* domain */
456                                         lp_netbios_name(), /* client name */
457                                         lp_netbios_name(), /* machine account name */
458                                         md4_trust_password,
459                                         sec_channel_type,
460                                         &neg_flags);
461
462         if (!NT_STATUS_IS_OK(status)) {
463                 DEBUG(0, ("Error in domain join verification (credential setup failed): %s\n\n",
464                           nt_errstr(status)));
465
466                 if ( NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) &&
467                      (sec_channel_type == SEC_CHAN_BDC) ) {
468                         d_fprintf(stderr, _("Please make sure that no computer "
469                                             "account\nnamed like this machine "
470                                             "(%s) exists in the domain\n"),
471                                  lp_netbios_name());
472                 }
473
474                 goto done;
475         }
476
477         /* We can only check the schannel connection if the client is allowed
478            to do this and the server supports it. If not, just assume success
479            (after all the rpccli_netlogon_setup_creds() succeeded, and we'll
480            do the same again (setup creds) in net_rpc_join_ok(). JRA. */
481
482         if (lp_client_schannel() && (neg_flags & NETLOGON_NEG_SCHANNEL)) {
483                 struct rpc_pipe_client *netlogon_schannel_pipe;
484
485                 status = cli_rpc_pipe_open_schannel_with_key(
486                         cli, &ndr_table_netlogon.syntax_id, NCACN_NP,
487                         DCERPC_AUTH_LEVEL_PRIVACY, domain, &pipe_hnd->dc,
488                         &netlogon_schannel_pipe);
489
490                 if (!NT_STATUS_IS_OK(status)) {
491                         DEBUG(0, ("Error in domain join verification (schannel setup failed): %s\n\n",
492                                   nt_errstr(status)));
493
494                         if ( NT_STATUS_EQUAL(status, NT_STATUS_ACCESS_DENIED) &&
495                              (sec_channel_type == SEC_CHAN_BDC) ) {
496                                 d_fprintf(stderr, _("Please make sure that no "
497                                                     "computer account\nnamed "
498                                                     "like this machine (%s) "
499                                                     "exists in the domain\n"),
500                                          lp_netbios_name());
501                         }
502
503                         goto done;
504                 }
505                 TALLOC_FREE(netlogon_schannel_pipe);
506         }
507
508         TALLOC_FREE(pipe_hnd);
509
510         /* Now store the secret in the secrets database */
511
512         if (!strupper_m(discard_const_p(char, domain))) {
513                 DEBUG(0, ("strupper_m %s failed\n", domain));
514                 goto done;
515         }
516
517         if (!secrets_store_domain_sid(domain, domain_sid)) {
518                 DEBUG(0, ("error storing domain sid for %s\n", domain));
519                 goto done;
520         }
521
522         if (!secrets_store_machine_password(clear_trust_password, domain, sec_channel_type)) {
523                 DEBUG(0, ("error storing plaintext domain secrets for %s\n", domain));
524         }
525
526         /* double-check, connection from scratch */
527         status = net_rpc_join_ok(c, domain, smbXcli_conn_remote_name(cli->conn),
528                                  smbXcli_conn_remote_sockaddr(cli->conn));
529         retval = NT_STATUS_IS_OK(status) ? 0 : -1;
530
531 done:
532
533         /* Display success or failure */
534
535         if (domain) {
536                 if (retval != 0) {
537                         fprintf(stderr,_("Unable to join domain %s.\n"),domain);
538                 } else {
539                         printf(_("Joined domain %s.\n"),domain);
540                 }
541         }
542
543         cli_shutdown(cli);
544
545         TALLOC_FREE(clear_trust_password);
546         data_blob_clear_free(&session_key);
547
548         return retval;
549 }
550
551 /**
552  * check that a join is OK
553  *
554  * @return A shell status integer (0 for success)
555  *
556  **/
557 int net_rpc_testjoin(struct net_context *c, int argc, const char **argv)
558 {
559         NTSTATUS nt_status;
560
561         if (c->display_usage) {
562                 d_printf(_("Usage\n"
563                            "net rpc testjoin\n"
564                            "    Test if a join is OK\n"));
565                 return 0;
566         }
567
568         /* Display success or failure */
569         nt_status = net_rpc_join_ok(c, c->opt_target_workgroup, NULL, NULL);
570         if (!NT_STATUS_IS_OK(nt_status)) {
571                 fprintf(stderr, _("Join to domain '%s' is not valid: %s\n"),
572                         c->opt_target_workgroup, nt_errstr(nt_status));
573                 return -1;
574         }
575
576         printf(_("Join to '%s' is OK\n"), c->opt_target_workgroup);
577         return 0;
578 }