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