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