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