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