r25197: Change net_make_ipc_connection() and net_make_ipc_connection_ex() to
[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 /**
38  * confirm that a domain join is still valid
39  *
40  * @return A shell status integer (0 for success)
41  *
42  **/
43 int net_rpc_join_ok(const char *domain, const char *server, struct in_addr *ip )
44 {
45         enum security_types sec;
46         unsigned int conn_flags = NET_FLAGS_PDC;
47         uint32 neg_flags = NETLOGON_NEG_AUTH2_FLAGS|NETLOGON_NEG_SCHANNEL;
48         struct cli_state *cli = NULL;
49         struct rpc_pipe_client *pipe_hnd = NULL;
50         struct rpc_pipe_client *netlogon_pipe = NULL;
51         NTSTATUS ntret = NT_STATUS_UNSUCCESSFUL;
52
53         sec = (enum security_types)lp_security();
54
55         if (sec == SEC_ADS) {
56                 /* Connect to IPC$ using machine account's credentials. We don't use anonymous
57                    connection here, as it may be denied by server's local policy. */
58                 net_use_machine_account();
59
60         } else {
61                 /* some servers (e.g. WinNT) don't accept machine-authenticated
62                    smb connections */
63                 conn_flags |= NET_FLAGS_ANONYMOUS;
64         }
65
66         /* Connect to remote machine */
67         ntret = net_make_ipc_connection_ex(domain, server, ip, conn_flags, &cli);
68         if (!NT_STATUS_IS_OK(ntret)) {
69                 return -1;
70         }
71
72         /* Setup the creds as though we're going to do schannel... */
73         netlogon_pipe = get_schannel_session_key(cli, domain, &neg_flags, &ntret);
74
75         /* We return NT_STATUS_INVALID_NETWORK_RESPONSE if the server is refusing
76            to negotiate schannel, but the creds were set up ok. That'll have to do. */
77
78         if (!netlogon_pipe) {
79                 if (NT_STATUS_EQUAL(ntret, NT_STATUS_INVALID_NETWORK_RESPONSE)) {
80                         cli_shutdown(cli);
81                         return 0;
82                 } else {
83                         DEBUG(0,("net_rpc_join_ok: failed to get schannel session "
84                                         "key from server %s for domain %s. Error was %s\n",
85                                 cli->desthost, domain, nt_errstr(ntret) ));
86                         cli_shutdown(cli);
87                         return -1;
88                 }
89         }
90
91         /* Only do the rest of the schannel test if the client is allowed to do this. */
92         if (!lp_client_schannel()) {
93                 cli_shutdown(cli);
94                 /* We're good... */
95                 return 0;
96         }
97
98         pipe_hnd = cli_rpc_pipe_open_schannel_with_key(cli, PI_NETLOGON,
99                                 PIPE_AUTH_LEVEL_PRIVACY,
100                                 domain, netlogon_pipe->dc, &ntret);
101
102         if (!pipe_hnd) {
103                 DEBUG(0,("net_rpc_join_ok: failed to open schannel session "
104                                 "on netlogon pipe to server %s for domain %s. Error was %s\n",
105                         cli->desthost, domain, nt_errstr(ntret) ));
106                 cli_shutdown(cli);
107                 return -1;
108         }
109
110         cli_shutdown(cli);
111         return 0;
112 }
113
114 /**
115  * Join a domain using the administrator username and password
116  *
117  * @param argc  Standard main() style argc
118  * @param argc  Standard main() style argv.  Initial components are already
119  *              stripped.  Currently not used.
120  * @return A shell status integer (0 for success)
121  *
122  **/
123
124 int net_rpc_join_newstyle(int argc, const char **argv) 
125 {
126
127         /* libsmb variables */
128
129         struct cli_state *cli;
130         TALLOC_CTX *mem_ctx;
131         uint32 acb_info = ACB_WSTRUST;
132         uint32 neg_flags = NETLOGON_NEG_AUTH2_FLAGS|(lp_client_schannel() ? NETLOGON_NEG_SCHANNEL : 0);
133         uint32 sec_channel_type;
134         struct rpc_pipe_client *pipe_hnd = NULL;
135
136         /* rpc variables */
137
138         POLICY_HND lsa_pol, sam_pol, domain_pol, user_pol;
139         DOM_SID *domain_sid;
140         uint32 user_rid;
141
142         /* Password stuff */
143
144         char *clear_trust_password = NULL;
145         uchar pwbuf[516];
146         SAM_USERINFO_CTR ctr;
147         SAM_USER_INFO_24 p24;
148         SAM_USER_INFO_16 p16;
149         uchar md4_trust_password[16];
150
151         /* Misc */
152
153         NTSTATUS result;
154         int retval = 1;
155         char *domain = NULL;
156         uint32 num_rids, *name_types, *user_rids;
157         uint32 flags = 0x3e8;
158         char *acct_name;
159         const char *const_acct_name;
160
161         /* check what type of join */
162         if (argc >= 0) {
163                 sec_channel_type = get_sec_channel_type(argv[0]);
164         } else {
165                 sec_channel_type = get_sec_channel_type(NULL);
166         }
167
168         switch (sec_channel_type) {
169         case SEC_CHAN_WKSTA:
170                 acb_info = ACB_WSTRUST;
171                 break;
172         case SEC_CHAN_BDC:
173                 acb_info = ACB_SVRTRUST;
174                 break;
175 #if 0
176         case SEC_CHAN_DOMAIN:
177                 acb_info = ACB_DOMTRUST;
178                 break;
179 #endif
180         }
181
182         /* Make authenticated connection to remote machine */
183
184         result = net_make_ipc_connection(NET_FLAGS_PDC, &cli);
185         if (!NT_STATUS_IS_OK(result)) {
186                 return 1;
187         }
188
189         if (!(mem_ctx = talloc_init("net_rpc_join_newstyle"))) {
190                 DEBUG(0, ("Could not initialise talloc context\n"));
191                 goto done;
192         }
193
194         /* Fetch domain sid */
195
196         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_LSARPC, &result);
197         if (!pipe_hnd) {
198                 DEBUG(0, ("Error connecting to LSA pipe. Error was %s\n",
199                         nt_errstr(result) ));
200                 goto done;
201         }
202
203
204         CHECK_RPC_ERR(rpccli_lsa_open_policy(pipe_hnd, mem_ctx, True,
205                                           SEC_RIGHTS_MAXIMUM_ALLOWED,
206                                           &lsa_pol),
207                       "error opening lsa policy handle");
208
209         CHECK_RPC_ERR(rpccli_lsa_query_info_policy(pipe_hnd, mem_ctx, &lsa_pol,
210                                                 5, &domain, &domain_sid),
211                       "error querying info policy");
212
213         rpccli_lsa_Close(pipe_hnd, mem_ctx, &lsa_pol);
214         cli_rpc_pipe_close(pipe_hnd); /* Done with this pipe */
215
216         /* Bail out if domain didn't get set. */
217         if (!domain) {
218                 DEBUG(0, ("Could not get domain name.\n"));
219                 goto done;
220         }
221
222         /* Create domain user */
223         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_SAMR, &result);
224         if (!pipe_hnd) {
225                 DEBUG(0, ("Error connecting to SAM pipe. Error was %s\n",
226                         nt_errstr(result) ));
227                 goto done;
228         }
229
230         CHECK_RPC_ERR(rpccli_samr_connect(pipe_hnd, mem_ctx, 
231                                        SEC_RIGHTS_MAXIMUM_ALLOWED,
232                                        &sam_pol),
233                       "could not connect to SAM database");
234
235         
236         CHECK_RPC_ERR(rpccli_samr_open_domain(pipe_hnd, mem_ctx, &sam_pol,
237                                            SEC_RIGHTS_MAXIMUM_ALLOWED,
238                                            domain_sid, &domain_pol),
239                       "could not open domain");
240
241         /* Create domain user */
242         if ((acct_name = talloc_asprintf(mem_ctx, "%s$", global_myname())) == NULL) {
243                 result = NT_STATUS_NO_MEMORY;
244                 goto done;
245         }
246         strlower_m(acct_name);
247         const_acct_name = acct_name;
248
249         result = rpccli_samr_create_dom_user(pipe_hnd, mem_ctx, &domain_pol,
250                                           acct_name, acb_info,
251                                           0xe005000b, &user_pol, 
252                                           &user_rid);
253
254         if (!NT_STATUS_IS_OK(result) && 
255             !NT_STATUS_EQUAL(result, NT_STATUS_USER_EXISTS)) {
256                 d_fprintf(stderr, "Creation of workstation account failed\n");
257
258                 /* If NT_STATUS_ACCESS_DENIED then we have a valid
259                    username/password combo but the user does not have
260                    administrator access. */
261
262                 if (NT_STATUS_V(result) == NT_STATUS_V(NT_STATUS_ACCESS_DENIED))
263                         d_fprintf(stderr, "User specified does not have administrator privileges\n");
264
265                 goto done;
266         }
267
268         /* We *must* do this.... don't ask... */
269
270         if (NT_STATUS_IS_OK(result)) {
271                 rpccli_samr_close(pipe_hnd, mem_ctx, &user_pol);
272         }
273
274         CHECK_RPC_ERR_DEBUG(rpccli_samr_lookup_names(pipe_hnd, mem_ctx,
275                                                   &domain_pol, flags,
276                                                   1, &const_acct_name, 
277                                                   &num_rids,
278                                                   &user_rids, &name_types),
279                             ("error looking up rid for user %s: %s\n",
280                              acct_name, nt_errstr(result)));
281
282         if (name_types[0] != SID_NAME_USER) {
283                 DEBUG(0, ("%s is not a user account (type=%d)\n", acct_name, name_types[0]));
284                 goto done;
285         }
286
287         user_rid = user_rids[0];
288                 
289         /* Open handle on user */
290
291         CHECK_RPC_ERR_DEBUG(
292                 rpccli_samr_open_user(pipe_hnd, mem_ctx, &domain_pol,
293                                    SEC_RIGHTS_MAXIMUM_ALLOWED,
294                                    user_rid, &user_pol),
295                 ("could not re-open existing user %s: %s\n",
296                  acct_name, nt_errstr(result)));
297         
298         /* Create a random machine account password */
299
300         { 
301                 char *str;
302                 str = generate_random_str(DEFAULT_TRUST_ACCOUNT_PASSWORD_LENGTH);
303                 clear_trust_password = SMB_STRDUP(str);
304                 E_md4hash(clear_trust_password, md4_trust_password);
305         }
306
307         encode_pw_buffer(pwbuf, clear_trust_password, STR_UNICODE);
308
309         /* Set password on machine account */
310
311         ZERO_STRUCT(ctr);
312         ZERO_STRUCT(p24);
313
314         init_sam_user_info24(&p24, (char *)pwbuf,24);
315
316         ctr.switch_value = 24;
317         ctr.info.id24 = &p24;
318
319         CHECK_RPC_ERR(rpccli_samr_set_userinfo(pipe_hnd, mem_ctx, &user_pol, 24, 
320                                             &cli->user_session_key, &ctr),
321                       "error setting trust account password");
322
323         /* Why do we have to try to (re-)set the ACB to be the same as what
324            we passed in the samr_create_dom_user() call?  When a NT
325            workstation is joined to a domain by an administrator the
326            acb_info is set to 0x80.  For a normal user with "Add
327            workstations to the domain" rights the acb_info is 0x84.  I'm
328            not sure whether it is supposed to make a difference or not.  NT
329            seems to cope with either value so don't bomb out if the set
330            userinfo2 level 0x10 fails.  -tpot */
331
332         ZERO_STRUCT(ctr);
333         ctr.switch_value = 16;
334         ctr.info.id16 = &p16;
335
336         init_sam_user_info16(&p16, acb_info);
337
338         /* Ignoring the return value is necessary for joining a domain
339            as a normal user with "Add workstation to domain" privilege. */
340
341         result = rpccli_samr_set_userinfo2(pipe_hnd, mem_ctx, &user_pol, 16, 
342                                         &cli->user_session_key, &ctr);
343
344         rpccli_samr_close(pipe_hnd, mem_ctx, &user_pol);
345         cli_rpc_pipe_close(pipe_hnd); /* Done with this pipe */
346
347         /* Now check the whole process from top-to-bottom */
348
349         pipe_hnd = cli_rpc_pipe_open_noauth(cli, PI_NETLOGON, &result);
350         if (!pipe_hnd) {
351                 DEBUG(0,("Error connecting to NETLOGON pipe. Error was %s\n",
352                         nt_errstr(result) ));
353                 goto done;
354         }
355
356         result = rpccli_netlogon_setup_creds(pipe_hnd,
357                                         cli->desthost, /* server name */
358                                         domain,        /* domain */
359                                         global_myname(), /* client name */
360                                         global_myname(), /* machine account name */
361                                         md4_trust_password,
362                                         sec_channel_type,
363                                         &neg_flags);
364
365         if (!NT_STATUS_IS_OK(result)) {
366                 DEBUG(0, ("Error in domain join verification (credential setup failed): %s\n\n",
367                           nt_errstr(result)));
368
369                 if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) &&
370                      (sec_channel_type == SEC_CHAN_BDC) ) {
371                         d_fprintf(stderr, "Please make sure that no computer account\n"
372                                  "named like this machine (%s) exists in the domain\n",
373                                  global_myname());
374                 }
375
376                 goto done;
377         }
378
379         /* We can only check the schannel connection if the client is allowed
380            to do this and the server supports it. If not, just assume success
381            (after all the rpccli_netlogon_setup_creds() succeeded, and we'll
382            do the same again (setup creds) in net_rpc_join_ok(). JRA. */
383
384         if (lp_client_schannel() && (neg_flags & NETLOGON_NEG_SCHANNEL)) {
385                 struct rpc_pipe_client *netlogon_schannel_pipe = 
386                                                 cli_rpc_pipe_open_schannel_with_key(cli,
387                                                         PI_NETLOGON,
388                                                         PIPE_AUTH_LEVEL_PRIVACY,
389                                                         domain,
390                                                         pipe_hnd->dc,
391                                                         &result);
392
393                 if (!NT_STATUS_IS_OK(result)) {
394                         DEBUG(0, ("Error in domain join verification (schannel setup failed): %s\n\n",
395                                   nt_errstr(result)));
396
397                         if ( NT_STATUS_EQUAL(result, NT_STATUS_ACCESS_DENIED) &&
398                              (sec_channel_type == SEC_CHAN_BDC) ) {
399                                 d_fprintf(stderr, "Please make sure that no computer account\n"
400                                          "named like this machine (%s) exists in the domain\n",
401                                          global_myname());
402                         }
403
404                         goto done;
405                 }
406                 cli_rpc_pipe_close(netlogon_schannel_pipe);
407         }
408
409         cli_rpc_pipe_close(pipe_hnd);
410
411         /* Now store the secret in the secrets database */
412
413         strupper_m(domain);
414
415         if (!secrets_store_domain_sid(domain, domain_sid)) {
416                 DEBUG(0, ("error storing domain sid for %s\n", domain));
417                 goto done;
418         }
419
420         if (!secrets_store_machine_password(clear_trust_password, domain, sec_channel_type)) {
421                 DEBUG(0, ("error storing plaintext domain secrets for %s\n", domain));
422         }
423
424         /* double-check, connection from scratch */
425         retval = net_rpc_join_ok(domain, cli->desthost, &cli->dest_ip);
426         
427 done:
428
429         /* Display success or failure */
430
431         if (domain) {
432                 if (retval != 0) {
433                         fprintf(stderr,"Unable to join domain %s.\n",domain);
434                 } else {
435                         printf("Joined domain %s.\n",domain);
436                 }
437         }
438         
439         cli_shutdown(cli);
440
441         SAFE_FREE(clear_trust_password);
442
443         return retval;
444 }
445
446 /**
447  * check that a join is OK
448  *
449  * @return A shell status integer (0 for success)
450  *
451  **/
452 int net_rpc_testjoin(int argc, const char **argv) 
453 {
454         char *domain = smb_xstrdup(opt_target_workgroup);
455
456         /* Display success or failure */
457         if (net_rpc_join_ok(domain, NULL, NULL) != 0) {
458                 fprintf(stderr,"Join to domain '%s' is not valid\n",domain);
459                 free(domain);
460                 return -1;
461         }
462
463         printf("Join to '%s' is OK\n",domain);
464         free(domain);
465         return 0;
466 }