Use rpccli_lsa_QueryInfoPolicy() all over the place.
[samba.git] / source / 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
7    This program is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 3 of the License, or
10    (at your option) any later version.
11    
12    This program is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16    
17    You should have received a copy of the GNU General Public License
18    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
19  
20 #include "includes.h"
21 #include "utils/net.h"
22
23 /* Macro for checking RPC error codes to make things more readable */
24
25 #define CHECK_RPC_ERR(rpc, msg) \
26         if (!NT_STATUS_IS_OK(result = rpc)) { \
27                 DEBUG(0, (msg ": %s\n", nt_errstr(result))); \
28                 goto done; \
29         }
30
31 #define CHECK_RPC_ERR_DEBUG(rpc, debug_args) \
32         if (!NT_STATUS_IS_OK(result = rpc)) { \
33                 DEBUG(0, debug_args); \
34                 goto done; \
35         }
36
37 static void init_lsa_String(struct lsa_String *name, const char *s)
38 {
39         name->string = s;
40 }
41
42
43 /**
44  * confirm that a domain join is still valid
45  *
46  * @return A shell status integer (0 for success)
47  *
48  **/
49 NTSTATUS net_rpc_join_ok(const char *domain, const char *server,
50                          struct sockaddr_storage *pss)
51 {
52         enum security_types sec;
53         unsigned int conn_flags = NET_FLAGS_PDC;
54         uint32 neg_flags = NETLOGON_NEG_SELECT_AUTH2_FLAGS|NETLOGON_NEG_SCHANNEL;
55         struct cli_state *cli = NULL;
56         struct rpc_pipe_client *pipe_hnd = NULL;
57         struct rpc_pipe_client *netlogon_pipe = NULL;
58         NTSTATUS ntret = NT_STATUS_UNSUCCESSFUL;
59
60         sec = (enum security_types)lp_security();
61
62         if (sec == SEC_ADS) {
63                 /* Connect to IPC$ using machine account's credentials. We don't use anonymous
64                    connection here, as it may be denied by server's local policy. */
65                 net_use_machine_account();
66
67         } else {
68                 /* some servers (e.g. WinNT) don't accept machine-authenticated
69                    smb connections */
70                 conn_flags |= NET_FLAGS_ANONYMOUS;
71         }
72
73         /* Connect to remote machine */
74         ntret = net_make_ipc_connection_ex(domain, server, pss, conn_flags, &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         netlogon_pipe = get_schannel_session_key(cli, domain, &neg_flags, &ntret);
81
82         /* We return NT_STATUS_INVALID_NETWORK_RESPONSE if the server is refusing
83            to negotiate schannel, but the creds were set up ok. That'll have to do. */
84
85         if (!netlogon_pipe) {
86                 if (NT_STATUS_EQUAL(ntret, NT_STATUS_INVALID_NETWORK_RESPONSE)) {
87                         cli_shutdown(cli);
88                         return NT_STATUS_OK;
89                 } else {
90                         DEBUG(0,("net_rpc_join_ok: failed to get schannel session "
91                                         "key from server %s for domain %s. Error was %s\n",
92                                 cli->desthost, domain, nt_errstr(ntret) ));
93                         cli_shutdown(cli);
94                         return ntret;
95                 }
96         }
97
98         /* Only do the rest of the schannel test if the client is allowed to do this. */
99         if (!lp_client_schannel()) {
100                 cli_shutdown(cli);
101                 /* We're good... */
102                 return ntret;
103         }
104
105         pipe_hnd = cli_rpc_pipe_open_schannel_with_key(cli, PI_NETLOGON,
106                                 PIPE_AUTH_LEVEL_PRIVACY,
107                                 domain, netlogon_pipe->dc, &ntret);
108
109         if (!pipe_hnd) {
110                 DEBUG(0,("net_rpc_join_ok: failed to open schannel session "
111                                 "on netlogon pipe to server %s for domain %s. Error was %s\n",
112                         cli->desthost, domain, nt_errstr(ntret) ));
113                 /*
114                  * Note: here, we have:
115                  * (pipe_hnd != NULL) if and only if NT_STATUS_IS_OK(ntret)
116                  */
117         }
118
119         cli_shutdown(cli);
120         return ntret;
121 }
122
123 /**
124  * Join a domain using the administrator username and password
125  *
126  * @param argc  Standard main() style argc
127  * @param argc  Standard main() style argv.  Initial components are already
128  *              stripped.  Currently not used.
129  * @return A shell status integer (0 for success)
130  *
131  **/
132
133 int net_rpc_join_newstyle(int argc, const char **argv) 
134 {
135
136         /* libsmb variables */
137
138         struct cli_state *cli;
139         TALLOC_CTX *mem_ctx;
140         uint32 acb_info = ACB_WSTRUST;
141         uint32 neg_flags = NETLOGON_NEG_SELECT_AUTH2_FLAGS|(lp_client_schannel() ? NETLOGON_NEG_SCHANNEL : 0);
142         uint32 sec_channel_type;
143         struct rpc_pipe_client *pipe_hnd = NULL;
144
145         /* rpc variables */
146
147         POLICY_HND lsa_pol, sam_pol, domain_pol, user_pol;
148         DOM_SID *domain_sid;
149         uint32 user_rid;
150
151         /* Password stuff */
152
153         char *clear_trust_password = NULL;
154         uchar pwbuf[516];
155         SAM_USERINFO_CTR ctr;
156         SAM_USER_INFO_24 p24;
157         SAM_USER_INFO_16 p16;
158         uchar md4_trust_password[16];
159
160         /* Misc */
161
162         NTSTATUS result;
163         int retval = 1;
164         const char *domain = NULL;
165         uint32 num_rids, *name_types, *user_rids;
166         uint32 flags = 0x3e8;
167         char *acct_name;
168         const char *const_acct_name;
169         struct lsa_String lsa_acct_name;
170         uint32 acct_flags=0;
171         uint32_t access_granted = 0;
172         union lsa_PolicyInformation *info = NULL;
173
174         /* check what type of join */
175         if (argc >= 0) {
176                 sec_channel_type = get_sec_channel_type(argv[0]);
177         } else {
178                 sec_channel_type = get_sec_channel_type(NULL);
179         }
180
181         switch (sec_channel_type) {
182         case SEC_CHAN_WKSTA:
183                 acb_info = ACB_WSTRUST;
184                 break;
185         case SEC_CHAN_BDC:
186                 acb_info = ACB_SVRTRUST;
187                 break;
188 #if 0
189         case SEC_CHAN_DOMAIN:
190                 acb_info = ACB_DOMTRUST;
191                 break;
192 #endif
193         }
194
195         /* Make authenticated connection to remote machine */
196
197         result = net_make_ipc_connection(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         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_LSARPC, &result);
210         if (!pipe_hnd) {
211                 DEBUG(0, ("Error connecting to LSA pipe. Error was %s\n",
212                         nt_errstr(result) ));
213                 goto done;
214         }
215
216
217         CHECK_RPC_ERR(rpccli_lsa_open_policy(pipe_hnd, mem_ctx, True,
218                                           SEC_RIGHTS_MAXIMUM_ALLOWED,
219                                           &lsa_pol),
220                       "error opening lsa policy handle");
221
222         CHECK_RPC_ERR(rpccli_lsa_QueryInfoPolicy(pipe_hnd, mem_ctx,
223                                                  &lsa_pol,
224                                                  LSA_POLICY_INFO_ACCOUNT_DOMAIN,
225                                                  &info),
226                       "error querying info policy");
227
228         domain = info->account_domain.name.string;
229         domain_sid = info->account_domain.sid;
230
231         rpccli_lsa_Close(pipe_hnd, mem_ctx, &lsa_pol);
232         cli_rpc_pipe_close(pipe_hnd); /* Done with this pipe */
233
234         /* Bail out if domain didn't get set. */
235         if (!domain) {
236                 DEBUG(0, ("Could not get domain name.\n"));
237                 goto done;
238         }
239
240         /* Create domain user */
241         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SAMR, &result);
242         if (!pipe_hnd) {
243                 DEBUG(0, ("Error connecting to SAM pipe. Error was %s\n",
244                         nt_errstr(result) ));
245                 goto done;
246         }
247
248         CHECK_RPC_ERR(rpccli_samr_Connect2(pipe_hnd, mem_ctx,
249                                            pipe_hnd->cli->desthost,
250                                            SEC_RIGHTS_MAXIMUM_ALLOWED,
251                                            &sam_pol),
252                       "could not connect to SAM database");
253
254
255         CHECK_RPC_ERR(rpccli_samr_OpenDomain(pipe_hnd, mem_ctx,
256                                              &sam_pol,
257                                              SEC_RIGHTS_MAXIMUM_ALLOWED,
258                                              domain_sid,
259                                              &domain_pol),
260                       "could not open domain");
261
262         /* Create domain user */
263         if ((acct_name = talloc_asprintf(mem_ctx, "%s$", global_myname())) == NULL) {
264                 result = NT_STATUS_NO_MEMORY;
265                 goto done;
266         }
267         strlower_m(acct_name);
268         const_acct_name = acct_name;
269
270         init_lsa_String(&lsa_acct_name, acct_name);
271
272         acct_flags = SEC_GENERIC_READ | SEC_GENERIC_WRITE | SEC_GENERIC_EXECUTE |
273                      SEC_STD_WRITE_DAC | SEC_STD_DELETE |
274                      SAMR_USER_ACCESS_SET_PASSWORD |
275                      SAMR_USER_ACCESS_GET_ATTRIBUTES |
276                      SAMR_USER_ACCESS_SET_ATTRIBUTES;
277
278         DEBUG(10, ("Creating account with flags: %d\n",acct_flags));
279
280         result = rpccli_samr_CreateUser2(pipe_hnd, mem_ctx,
281                                          &domain_pol,
282                                          &lsa_acct_name,
283                                          acb_info,
284                                          acct_flags,
285                                          &user_pol,
286                                          &access_granted,
287                                          &user_rid);
288
289         if (!NT_STATUS_IS_OK(result) && 
290             !NT_STATUS_EQUAL(result, NT_STATUS_USER_EXISTS)) {
291                 d_fprintf(stderr, "Creation of workstation account failed\n");
292
293                 /* If NT_STATUS_ACCESS_DENIED then we have a valid
294                    username/password combo but the user does not have
295                    administrator access. */
296
297                 if (NT_STATUS_V(result) == NT_STATUS_V(NT_STATUS_ACCESS_DENIED))
298                         d_fprintf(stderr, "User specified does not have administrator privileges\n");
299
300                 goto done;
301         }
302
303         /* We *must* do this.... don't ask... */
304
305         if (NT_STATUS_IS_OK(result)) {
306                 rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
307         }
308
309         CHECK_RPC_ERR_DEBUG(rpccli_samr_lookup_names(pipe_hnd, mem_ctx,
310                                                   &domain_pol, flags,
311                                                   1, &const_acct_name, 
312                                                   &num_rids,
313                                                   &user_rids, &name_types),
314                             ("error looking up rid for user %s: %s\n",
315                              acct_name, nt_errstr(result)));
316
317         if (name_types[0] != SID_NAME_USER) {
318                 DEBUG(0, ("%s is not a user account (type=%d)\n", acct_name, name_types[0]));
319                 goto done;
320         }
321
322         user_rid = user_rids[0];
323                 
324         /* Open handle on user */
325
326         CHECK_RPC_ERR_DEBUG(
327                 rpccli_samr_OpenUser(pipe_hnd, mem_ctx,
328                                      &domain_pol,
329                                      SEC_RIGHTS_MAXIMUM_ALLOWED,
330                                      user_rid,
331                                      &user_pol),
332                 ("could not re-open existing user %s: %s\n",
333                  acct_name, nt_errstr(result)));
334         
335         /* Create a random machine account password */
336
337         { 
338                 char *str;
339                 str = generate_random_str(DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH);
340                 clear_trust_password = SMB_STRDUP(str);
341                 E_md4hash(clear_trust_password, md4_trust_password);
342         }
343
344         encode_pw_buffer(pwbuf, clear_trust_password, STR_UNICODE);
345
346         /* Set password on machine account */
347
348         ZERO_STRUCT(ctr);
349         ZERO_STRUCT(p24);
350
351         init_sam_user_info24(&p24, (char *)pwbuf,24);
352
353         ctr.switch_value = 24;
354         ctr.info.id24 = &p24;
355
356         CHECK_RPC_ERR(rpccli_samr_set_userinfo(pipe_hnd, mem_ctx, &user_pol, 24, 
357                                             &cli->user_session_key, &ctr),
358                       "error setting trust account password");
359
360         /* Why do we have to try to (re-)set the ACB to be the same as what
361            we passed in the samr_create_dom_user() call?  When a NT
362            workstation is joined to a domain by an administrator the
363            acb_info is set to 0x80.  For a normal user with "Add
364            workstations to the domain" rights the acb_info is 0x84.  I'm
365            not sure whether it is supposed to make a difference or not.  NT
366            seems to cope with either value so don't bomb out if the set
367            userinfo2 level 0x10 fails.  -tpot */
368
369         ZERO_STRUCT(ctr);
370         ctr.switch_value = 16;
371         ctr.info.id16 = &p16;
372
373         init_sam_user_info16(&p16, 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_set_userinfo2(pipe_hnd, mem_ctx, &user_pol, 16, 
379                                         &cli->user_session_key, &ctr);
380
381         rpccli_samr_Close(pipe_hnd, mem_ctx, &user_pol);
382         cli_rpc_pipe_close(pipe_hnd); /* Done with this pipe */
383
384         /* Now check the whole process from top-to-bottom */
385
386         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_NETLOGON, &result);
387         if (!pipe_hnd) {
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 account\n"
409                                  "named like this machine (%s) exists in the domain\n",
410                                  global_myname());
411                 }
412
413                 goto done;
414         }
415
416         /* We can only check the schannel connection if the client is allowed
417            to do this and the server supports it. If not, just assume success
418            (after all the rpccli_netlogon_setup_creds() succeeded, and we'll
419            do the same again (setup creds) in net_rpc_join_ok(). JRA. */
420
421         if (lp_client_schannel() && (neg_flags & NETLOGON_NEG_SCHANNEL)) {
422                 struct rpc_pipe_client *netlogon_schannel_pipe = 
423                                                 cli_rpc_pipe_open_schannel_with_key(cli,
424                                                         PI_NETLOGON,
425                                                         PIPE_AUTH_LEVEL_PRIVACY,
426                                                         domain,
427                                                         pipe_hnd->dc,
428                                                         &result);
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 computer account\n"
437                                          "named like this machine (%s) exists in the domain\n",
438                                          global_myname());
439                         }
440
441                         goto done;
442                 }
443                 cli_rpc_pipe_close(netlogon_schannel_pipe);
444         }
445
446         cli_rpc_pipe_close(pipe_hnd);
447
448         /* Now store the secret in the secrets database */
449
450         strupper_m(CONST_DISCARD(char *, domain));
451
452         if (!secrets_store_domain_sid(domain, domain_sid)) {
453                 DEBUG(0, ("error storing domain sid for %s\n", domain));
454                 goto done;
455         }
456
457         if (!secrets_store_machine_password(clear_trust_password, domain, sec_channel_type)) {
458                 DEBUG(0, ("error storing plaintext domain secrets for %s\n", domain));
459         }
460
461         /* double-check, connection from scratch */
462         result = net_rpc_join_ok(domain, cli->desthost, &cli->dest_ss);
463         retval = NT_STATUS_IS_OK(result) ? 0 : -1;
464
465 done:
466
467         /* Display success or failure */
468
469         if (domain) {
470                 if (retval != 0) {
471                         fprintf(stderr,"Unable to join domain %s.\n",domain);
472                 } else {
473                         printf("Joined domain %s.\n",domain);
474                 }
475         }
476         
477         cli_shutdown(cli);
478
479         SAFE_FREE(clear_trust_password);
480
481         return retval;
482 }
483
484 /**
485  * check that a join is OK
486  *
487  * @return A shell status integer (0 for success)
488  *
489  **/
490 int net_rpc_testjoin(int argc, const char **argv) 
491 {
492         char *domain = smb_xstrdup(opt_target_workgroup);
493         NTSTATUS nt_status;
494
495         /* Display success or failure */
496         nt_status = net_rpc_join_ok(domain, NULL, NULL);
497         if (!NT_STATUS_IS_OK(nt_status)) {
498                 fprintf(stderr,"Join to domain '%s' is not valid: %s\n",
499                         nt_errstr(nt_status), domain);
500                 free(domain);
501                 return -1;
502         }
503
504         printf("Join to '%s' is OK\n",domain);
505         free(domain);
506         return 0;
507 }