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