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