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