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