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