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