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