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