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