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