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