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