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