s3:rpcclient: use talloc_stackframe() in do_cmd()
[samba.git] / source3 / rpcclient / rpcclient.c
1 /* 
2    Unix SMB/CIFS implementation.
3    RPC pipe client
4
5    Copyright (C) Tim Potter 2000-2001
6    Copyright (C) Martin Pool 2003
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
22 #include "includes.h"
23 #include "popt_common.h"
24 #include "rpcclient.h"
25 #include "../libcli/auth/libcli_auth.h"
26 #include "../librpc/gen_ndr/ndr_lsa_c.h"
27 #include "rpc_client/cli_lsarpc.h"
28 #include "../librpc/gen_ndr/ndr_netlogon.h"
29 #include "rpc_client/cli_netlogon.h"
30 #include "../libcli/smbreadline/smbreadline.h"
31 #include "../libcli/security/security.h"
32 #include "passdb.h"
33 #include "libsmb/libsmb.h"
34 #include "auth/gensec/gensec.h"
35 #include "../libcli/smb/smbXcli_base.h"
36
37 enum pipe_auth_type_spnego {
38         PIPE_AUTH_TYPE_SPNEGO_NONE = 0,
39         PIPE_AUTH_TYPE_SPNEGO_NTLMSSP,
40         PIPE_AUTH_TYPE_SPNEGO_KRB5
41 };
42
43 struct dom_sid domain_sid;
44
45 static enum dcerpc_AuthType pipe_default_auth_type = DCERPC_AUTH_TYPE_NONE;
46 static enum pipe_auth_type_spnego pipe_default_auth_spnego_type = 0;
47 static enum dcerpc_AuthLevel pipe_default_auth_level = DCERPC_AUTH_LEVEL_NONE;
48 static unsigned int timeout = 0;
49 static enum dcerpc_transport_t default_transport = NCACN_NP;
50
51 struct user_auth_info *rpcclient_auth_info;
52
53 /* List to hold groups of commands.
54  *
55  * Commands are defined in a list of arrays: arrays are easy to
56  * statically declare, and lists are easier to dynamically extend.
57  */
58
59 static struct cmd_list {
60         struct cmd_list *prev, *next;
61         struct cmd_set *cmd_set;
62 } *cmd_list;
63
64 /****************************************************************************
65 handle completion of commands for readline
66 ****************************************************************************/
67 static char **completion_fn(const char *text, int start, int end)
68 {
69 #define MAX_COMPLETIONS 1000
70         char **matches;
71         int i, count=0;
72         struct cmd_list *commands = cmd_list;
73
74 #if 0   /* JERRY */
75         /* FIXME!!!  -- what to do when completing argument? */
76         /* for words not at the start of the line fallback 
77            to filename completion */
78         if (start) 
79                 return NULL;
80 #endif
81
82         /* make sure we have a list of valid commands */
83         if (!commands) {
84                 return NULL;
85         }
86
87         matches = SMB_MALLOC_ARRAY(char *, MAX_COMPLETIONS);
88         if (!matches) {
89                 return NULL;
90         }
91
92         matches[count++] = SMB_STRDUP(text);
93         if (!matches[0]) {
94                 SAFE_FREE(matches);
95                 return NULL;
96         }
97
98         while (commands && count < MAX_COMPLETIONS-1) {
99                 if (!commands->cmd_set) {
100                         break;
101                 }
102
103                 for (i=0; commands->cmd_set[i].name; i++) {
104                         if ((strncmp(text, commands->cmd_set[i].name, strlen(text)) == 0) &&
105                                 (( commands->cmd_set[i].returntype == RPC_RTYPE_NTSTATUS &&
106                         commands->cmd_set[i].ntfn ) || 
107                       ( commands->cmd_set[i].returntype == RPC_RTYPE_WERROR &&
108                         commands->cmd_set[i].wfn))) {
109                                 matches[count] = SMB_STRDUP(commands->cmd_set[i].name);
110                                 if (!matches[count]) {
111                                         for (i = 0; i < count; i++) {
112                                                 SAFE_FREE(matches[count]);
113                                         }
114                                         SAFE_FREE(matches);
115                                         return NULL;
116                                 }
117                                 count++;
118                         }
119                 }
120                 commands = commands->next;
121         }
122
123         if (count == 2) {
124                 SAFE_FREE(matches[0]);
125                 matches[0] = SMB_STRDUP(matches[1]);
126         }
127         matches[count] = NULL;
128         return matches;
129 }
130
131 static char *next_command (char **cmdstr)
132 {
133         char *command;
134         char                    *p;
135
136         if (!cmdstr || !(*cmdstr))
137                 return NULL;
138
139         p = strchr_m(*cmdstr, ';');
140         if (p)
141                 *p = '\0';
142         command = SMB_STRDUP(*cmdstr);
143         if (p)
144                 *cmdstr = p + 1;
145         else
146                 *cmdstr = NULL;
147
148         return command;
149 }
150
151 /* Fetch the SID for this computer */
152
153 static void fetch_machine_sid(struct cli_state *cli)
154 {
155         struct policy_handle pol;
156         NTSTATUS result = NT_STATUS_OK, status;
157         static bool got_domain_sid;
158         TALLOC_CTX *mem_ctx;
159         struct rpc_pipe_client *lsapipe = NULL;
160         union lsa_PolicyInformation *info = NULL;
161         struct dcerpc_binding_handle *b;
162
163         if (got_domain_sid) return;
164
165         if (!(mem_ctx=talloc_init("fetch_machine_sid"))) {
166                 DEBUG(0,("fetch_machine_sid: talloc_init returned NULL!\n"));
167                 goto error;
168         }
169
170         result = cli_rpc_pipe_open_noauth(cli, &ndr_table_lsarpc,
171                                           &lsapipe);
172         if (!NT_STATUS_IS_OK(result)) {
173                 fprintf(stderr, "could not initialise lsa pipe. Error was %s\n", nt_errstr(result) );
174                 goto error;
175         }
176
177         b = lsapipe->binding_handle;
178
179         result = rpccli_lsa_open_policy(lsapipe, mem_ctx, True, 
180                                      SEC_FLAG_MAXIMUM_ALLOWED,
181                                      &pol);
182         if (!NT_STATUS_IS_OK(result)) {
183                 goto error;
184         }
185
186         status = dcerpc_lsa_QueryInfoPolicy(b, mem_ctx,
187                                             &pol,
188                                             LSA_POLICY_INFO_ACCOUNT_DOMAIN,
189                                             &info,
190                                             &result);
191         if (!NT_STATUS_IS_OK(status)) {
192                 result = status;
193                 goto error;
194         }
195         if (!NT_STATUS_IS_OK(result)) {
196                 goto error;
197         }
198
199         got_domain_sid = True;
200         sid_copy(&domain_sid, info->account_domain.sid);
201
202         dcerpc_lsa_Close(b, mem_ctx, &pol, &result);
203         TALLOC_FREE(lsapipe);
204         talloc_destroy(mem_ctx);
205
206         return;
207
208  error:
209
210         if (lsapipe) {
211                 TALLOC_FREE(lsapipe);
212         }
213
214         fprintf(stderr, "could not obtain sid for domain %s\n", cli->domain);
215
216         if (!NT_STATUS_IS_OK(result)) {
217                 fprintf(stderr, "error: %s\n", nt_errstr(result));
218         }
219
220         exit(1);
221 }
222
223 /* List the available commands on a given pipe */
224
225 static NTSTATUS cmd_listcommands(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
226                                  int argc, const char **argv)
227 {
228         struct cmd_list *tmp;
229         struct cmd_set *tmp_set;
230         int i;
231
232         /* Usage */
233
234         if (argc != 2) {
235                 printf("Usage: %s <pipe>\n", argv[0]);
236                 return NT_STATUS_OK;
237         }
238
239         /* Help on one command */
240
241         for (tmp = cmd_list; tmp; tmp = tmp->next) 
242         {
243                 tmp_set = tmp->cmd_set;
244
245                 if (!strcasecmp_m(argv[1], tmp_set->name))
246                 {
247                         printf("Available commands on the %s pipe:\n\n", tmp_set->name);
248
249                         i = 0;
250                         tmp_set++;
251                         while(tmp_set->name) {
252                                 printf("%30s", tmp_set->name);
253                                 tmp_set++;
254                                 i++;
255                                 if (i%3 == 0)
256                                         printf("\n");
257                         }
258
259                         /* drop out of the loop */
260                         break;
261                 }
262         }
263         printf("\n\n");
264
265         return NT_STATUS_OK;
266 }
267
268 /* Display help on commands */
269
270 static NTSTATUS cmd_help(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
271                          int argc, const char **argv)
272 {
273         struct cmd_list *tmp;
274         struct cmd_set *tmp_set;
275
276         /* Usage */
277
278         if (argc > 2) {
279                 printf("Usage: %s [command]\n", argv[0]);
280                 return NT_STATUS_OK;
281         }
282
283         /* Help on one command */
284
285         if (argc == 2) {
286                 for (tmp = cmd_list; tmp; tmp = tmp->next) {
287
288                         tmp_set = tmp->cmd_set;
289
290                         while(tmp_set->name) {
291                                 if (strequal(argv[1], tmp_set->name)) {
292                                         if (tmp_set->usage &&
293                                             tmp_set->usage[0])
294                                                 printf("%s\n", tmp_set->usage);
295                                         else
296                                                 printf("No help for %s\n", tmp_set->name);
297
298                                         return NT_STATUS_OK;
299                                 }
300
301                                 tmp_set++;
302                         }
303                 }
304
305                 printf("No such command: %s\n", argv[1]);
306                 return NT_STATUS_OK;
307         }
308
309         /* List all commands */
310
311         for (tmp = cmd_list; tmp; tmp = tmp->next) {
312
313                 tmp_set = tmp->cmd_set;
314
315                 while(tmp_set->name) {
316
317                         printf("%15s\t\t%s\n", tmp_set->name,
318                                tmp_set->description ? tmp_set->description:
319                                "");
320
321                         tmp_set++;
322                 }
323         }
324
325         return NT_STATUS_OK;
326 }
327
328 /* Change the debug level */
329
330 static NTSTATUS cmd_debuglevel(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
331                                int argc, const char **argv)
332 {
333         if (argc > 2) {
334                 printf("Usage: %s [debuglevel]\n", argv[0]);
335                 return NT_STATUS_OK;
336         }
337
338         if (argc == 2) {
339                 lp_set_cmdline("log level", argv[1]);
340         }
341
342         printf("debuglevel is %d\n", DEBUGLEVEL);
343
344         return NT_STATUS_OK;
345 }
346
347 static NTSTATUS cmd_quit(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
348                          int argc, const char **argv)
349 {
350         exit(0);
351         return NT_STATUS_OK; /* NOTREACHED */
352 }
353
354 static NTSTATUS cmd_set_ss_level(void)
355 {
356         struct cmd_list *tmp;
357
358         /* Close any existing connections not at this level. */
359
360         for (tmp = cmd_list; tmp; tmp = tmp->next) {
361                 struct cmd_set *tmp_set;
362
363                 for (tmp_set = tmp->cmd_set; tmp_set->name; tmp_set++) {
364                         if (tmp_set->rpc_pipe == NULL) {
365                                 continue;
366                         }
367
368                         if ((tmp_set->rpc_pipe->auth->auth_type
369                              != pipe_default_auth_type)
370                             || (tmp_set->rpc_pipe->auth->auth_level
371                                 != pipe_default_auth_level)) {
372                                 TALLOC_FREE(tmp_set->rpc_pipe);
373                                 tmp_set->rpc_pipe = NULL;
374                         }
375                 }
376         }
377         return NT_STATUS_OK;
378 }
379
380 static NTSTATUS cmd_set_transport(void)
381 {
382         struct cmd_list *tmp;
383
384         /* Close any existing connections not at this level. */
385
386         for (tmp = cmd_list; tmp; tmp = tmp->next) {
387                 struct cmd_set *tmp_set;
388
389                 for (tmp_set = tmp->cmd_set; tmp_set->name; tmp_set++) {
390                         if (tmp_set->rpc_pipe == NULL) {
391                                 continue;
392                         }
393
394                         if (tmp_set->rpc_pipe->transport->transport != default_transport) {
395                                 TALLOC_FREE(tmp_set->rpc_pipe);
396                                 tmp_set->rpc_pipe = NULL;
397                         }
398                 }
399         }
400         return NT_STATUS_OK;
401 }
402
403 static NTSTATUS cmd_sign(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
404                          int argc, const char **argv)
405 {
406         const char *p = "[KRB5|KRB5_SPNEGO|NTLMSSP|NTLMSSP_SPNEGO|SCHANNEL]";
407         const char *type = "NTLMSSP";
408
409         pipe_default_auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
410         pipe_default_auth_type = DCERPC_AUTH_TYPE_NTLMSSP;
411
412         if (argc > 2) {
413                 printf("Usage: %s %s\n", argv[0], p);
414                 return NT_STATUS_OK;
415         }
416
417         if (argc == 2) {
418                 type = argv[1];
419                 if (strequal(type, "KRB5")) {
420                         pipe_default_auth_type = DCERPC_AUTH_TYPE_KRB5;
421                 } else if (strequal(type, "KRB5_SPNEGO")) {
422                         pipe_default_auth_type = DCERPC_AUTH_TYPE_SPNEGO;
423                         pipe_default_auth_spnego_type = PIPE_AUTH_TYPE_SPNEGO_KRB5;
424                 } else if (strequal(type, "NTLMSSP")) {
425                         pipe_default_auth_type = DCERPC_AUTH_TYPE_NTLMSSP;
426                 } else if (strequal(type, "NTLMSSP_SPNEGO")) {
427                         pipe_default_auth_type = DCERPC_AUTH_TYPE_SPNEGO;
428                         pipe_default_auth_spnego_type = PIPE_AUTH_TYPE_SPNEGO_NTLMSSP;
429                 } else if (strequal(type, "SCHANNEL")) {
430                         pipe_default_auth_type = DCERPC_AUTH_TYPE_SCHANNEL;
431                 } else {
432                         printf("unknown type %s\n", type);
433                         printf("Usage: %s %s\n", argv[0], p);
434                         return NT_STATUS_INVALID_LEVEL;
435                 }
436         }
437
438         d_printf("Setting %s - sign\n", type);
439
440         return cmd_set_ss_level();
441 }
442
443 static NTSTATUS cmd_seal(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
444                          int argc, const char **argv)
445 {
446         const char *p = "[KRB5|KRB5_SPNEGO|NTLMSSP|NTLMSSP_SPNEGO|SCHANNEL]";
447         const char *type = "NTLMSSP";
448
449         pipe_default_auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
450         pipe_default_auth_type = DCERPC_AUTH_TYPE_NTLMSSP;
451
452         if (argc > 2) {
453                 printf("Usage: %s %s\n", argv[0], p);
454                 return NT_STATUS_OK;
455         }
456
457         if (argc == 2) {
458                 type = argv[1];
459                 if (strequal(type, "KRB5")) {
460                         pipe_default_auth_type = DCERPC_AUTH_TYPE_KRB5;
461                 } else if (strequal(type, "KRB5_SPNEGO")) {
462                         pipe_default_auth_type = DCERPC_AUTH_TYPE_SPNEGO;
463                         pipe_default_auth_spnego_type = PIPE_AUTH_TYPE_SPNEGO_KRB5;
464                 } else if (strequal(type, "NTLMSSP")) {
465                         pipe_default_auth_type = DCERPC_AUTH_TYPE_NTLMSSP;
466                 } else if (strequal(type, "NTLMSSP_SPNEGO")) {
467                         pipe_default_auth_type = DCERPC_AUTH_TYPE_SPNEGO;
468                         pipe_default_auth_spnego_type = PIPE_AUTH_TYPE_SPNEGO_NTLMSSP;
469                 } else if (strequal(type, "SCHANNEL")) {
470                         pipe_default_auth_type = DCERPC_AUTH_TYPE_SCHANNEL;
471                 } else {
472                         printf("unknown type %s\n", type);
473                         printf("Usage: %s %s\n", argv[0], p);
474                         return NT_STATUS_INVALID_LEVEL;
475                 }
476         }
477
478         d_printf("Setting %s - sign and seal\n", type);
479
480         return cmd_set_ss_level();
481 }
482
483 static NTSTATUS cmd_timeout(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
484                             int argc, const char **argv)
485 {
486         struct cmd_list *tmp;
487
488         if (argc > 2) {
489                 printf("Usage: %s timeout\n", argv[0]);
490                 return NT_STATUS_OK;
491         }
492
493         if (argc == 2) {
494                 timeout = atoi(argv[1]);
495
496                 for (tmp = cmd_list; tmp; tmp = tmp->next) {
497
498                         struct cmd_set *tmp_set;
499
500                         for (tmp_set = tmp->cmd_set; tmp_set->name; tmp_set++) {
501                                 if (tmp_set->rpc_pipe == NULL) {
502                                         continue;
503                                 }
504
505                                 rpccli_set_timeout(tmp_set->rpc_pipe, timeout);
506                         }
507                 }
508         }
509
510         printf("timeout is %d\n", timeout);
511
512         return NT_STATUS_OK;
513 }
514
515
516 static NTSTATUS cmd_none(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
517                          int argc, const char **argv)
518 {
519         pipe_default_auth_level = DCERPC_AUTH_LEVEL_NONE;
520         pipe_default_auth_type = DCERPC_AUTH_TYPE_NONE;
521         pipe_default_auth_spnego_type = PIPE_AUTH_TYPE_SPNEGO_NONE;
522
523         return cmd_set_ss_level();
524 }
525
526 static NTSTATUS cmd_schannel(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
527                              int argc, const char **argv)
528 {
529         d_printf("Setting schannel - sign and seal\n");
530         pipe_default_auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
531         pipe_default_auth_type = DCERPC_AUTH_TYPE_SCHANNEL;
532
533         return cmd_set_ss_level();
534 }
535
536 static NTSTATUS cmd_schannel_sign(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
537                              int argc, const char **argv)
538 {
539         d_printf("Setting schannel - sign only\n");
540         pipe_default_auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
541         pipe_default_auth_type = DCERPC_AUTH_TYPE_SCHANNEL;
542
543         return cmd_set_ss_level();
544 }
545
546 static NTSTATUS cmd_choose_transport(struct rpc_pipe_client *cli, TALLOC_CTX *mem_ctx,
547                                      int argc, const char **argv)
548 {
549         NTSTATUS status;
550
551         if (argc != 2) {
552                 printf("Usage: %s [NCACN_NP|NCACN_IP_TCP]\n", argv[0]);
553                 return NT_STATUS_OK;
554         }
555
556         if (strequal(argv[1], "NCACN_NP")) {
557                 default_transport = NCACN_NP;
558         } else if (strequal(argv[1], "NCACN_IP_TCP")) {
559                 default_transport = NCACN_IP_TCP;
560         } else {
561                 printf("transport type: %s unknown or not supported\n", argv[1]);
562                 return NT_STATUS_NOT_SUPPORTED;
563         }
564
565         status = cmd_set_transport();
566         if (!NT_STATUS_IS_OK(status)) {
567                 return status;
568         }
569
570         printf("default transport is now: %s\n", argv[1]);
571
572         return NT_STATUS_OK;
573 }
574
575 /* Built in rpcclient commands */
576
577 static struct cmd_set rpcclient_commands[] = {
578
579         { "GENERAL OPTIONS" },
580
581         { "help", RPC_RTYPE_NTSTATUS, cmd_help, NULL,     NULL, NULL,   "Get help on commands", "[command]" },
582         { "?",  RPC_RTYPE_NTSTATUS, cmd_help, NULL,       NULL, NULL,   "Get help on commands", "[command]" },
583         { "debuglevel", RPC_RTYPE_NTSTATUS, cmd_debuglevel, NULL,   NULL,       NULL, "Set debug level", "level" },
584         { "debug", RPC_RTYPE_NTSTATUS, cmd_debuglevel, NULL,   NULL,    NULL, "Set debug level", "level" },
585         { "list",       RPC_RTYPE_NTSTATUS, cmd_listcommands, NULL, NULL,       NULL, "List available commands on <pipe>", "pipe" },
586         { "exit", RPC_RTYPE_NTSTATUS, cmd_quit, NULL,   NULL,   NULL,   "Exit program", "" },
587         { "quit", RPC_RTYPE_NTSTATUS, cmd_quit, NULL,     NULL, NULL, "Exit program", "" },
588         { "sign", RPC_RTYPE_NTSTATUS, cmd_sign, NULL,     NULL, NULL, "Force RPC pipe connections to be signed", "" },
589         { "seal", RPC_RTYPE_NTSTATUS, cmd_seal, NULL,     NULL, NULL, "Force RPC pipe connections to be sealed", "" },
590         { "schannel", RPC_RTYPE_NTSTATUS, cmd_schannel, NULL,     NULL, NULL,   "Force RPC pipe connections to be sealed with 'schannel'.  Assumes valid machine account to this domain controller.", "" },
591         { "schannelsign", RPC_RTYPE_NTSTATUS, cmd_schannel_sign, NULL,    NULL, NULL, "Force RPC pipe connections to be signed (not sealed) with 'schannel'.  Assumes valid machine account to this domain controller.", "" },
592         { "timeout", RPC_RTYPE_NTSTATUS, cmd_timeout, NULL,       NULL, NULL, "Set timeout (in milliseconds) for RPC operations", "" },
593         { "transport", RPC_RTYPE_NTSTATUS, cmd_choose_transport, NULL,    NULL, NULL, "Choose ncacn transport for RPC operations", "" },
594         { "none", RPC_RTYPE_NTSTATUS, cmd_none, NULL,     NULL, NULL, "Force RPC pipe connections to have no special properties", "" },
595
596         { NULL }
597 };
598
599 static struct cmd_set separator_command[] = {
600         { "---------------", MAX_RPC_RETURN_TYPE, NULL, NULL,   NULL, NULL, "----------------------" },
601         { NULL }
602 };
603
604
605 /* Various pipe commands */
606
607 extern struct cmd_set lsarpc_commands[];
608 extern struct cmd_set samr_commands[];
609 extern struct cmd_set spoolss_commands[];
610 extern struct cmd_set netlogon_commands[];
611 extern struct cmd_set srvsvc_commands[];
612 extern struct cmd_set dfs_commands[];
613 extern struct cmd_set ds_commands[];
614 extern struct cmd_set echo_commands[];
615 extern struct cmd_set epmapper_commands[];
616 extern struct cmd_set shutdown_commands[];
617 extern struct cmd_set test_commands[];
618 extern struct cmd_set wkssvc_commands[];
619 extern struct cmd_set ntsvcs_commands[];
620 extern struct cmd_set drsuapi_commands[];
621 extern struct cmd_set eventlog_commands[];
622 extern struct cmd_set winreg_commands[];
623 extern struct cmd_set fss_commands[];
624
625 static struct cmd_set *rpcclient_command_list[] = {
626         rpcclient_commands,
627         lsarpc_commands,
628         ds_commands,
629         samr_commands,
630         spoolss_commands,
631         netlogon_commands,
632         srvsvc_commands,
633         dfs_commands,
634         echo_commands,
635         epmapper_commands,
636         shutdown_commands,
637         test_commands,
638         wkssvc_commands,
639         ntsvcs_commands,
640         drsuapi_commands,
641         eventlog_commands,
642         winreg_commands,
643         fss_commands,
644         NULL
645 };
646
647 static void add_command_set(struct cmd_set *cmd_set)
648 {
649         struct cmd_list *entry;
650
651         if (!(entry = SMB_MALLOC_P(struct cmd_list))) {
652                 DEBUG(0, ("out of memory\n"));
653                 return;
654         }
655
656         ZERO_STRUCTP(entry);
657
658         entry->cmd_set = cmd_set;
659         DLIST_ADD(cmd_list, entry);
660 }
661
662
663 /**
664  * Call an rpcclient function, passing an argv array.
665  *
666  * @param cmd Command to run, as a single string.
667  **/
668 static NTSTATUS do_cmd(struct cli_state *cli,
669                        struct user_auth_info *auth_info,
670                        struct cmd_set *cmd_entry,
671                        struct dcerpc_binding *binding,
672                        int argc, char **argv)
673 {
674         NTSTATUS ntresult;
675         WERROR wresult;
676
677         TALLOC_CTX *mem_ctx;
678
679         /* Create mem_ctx */
680
681         if (!(mem_ctx = talloc_stackframe())) {
682                 DEBUG(0, ("talloc_init() failed\n"));
683                 return NT_STATUS_NO_MEMORY;
684         }
685
686         /* Open pipe */
687
688         if ((cmd_entry->table != NULL) && (cmd_entry->rpc_pipe == NULL)) {
689                 switch (pipe_default_auth_type) {
690                 case DCERPC_AUTH_TYPE_NONE:
691                         ntresult = cli_rpc_pipe_open_noauth_transport(
692                                 cli, default_transport,
693                                 cmd_entry->table,
694                                 &cmd_entry->rpc_pipe);
695                         break;
696                 case DCERPC_AUTH_TYPE_SPNEGO:
697                 {
698                         /* won't happen, but if it does it will fail in cli_rpc_pipe_open_spnego() eventually */
699                         const char *oid = "INVALID";
700                         switch (pipe_default_auth_spnego_type) {
701                         case PIPE_AUTH_TYPE_SPNEGO_NTLMSSP:
702                                 oid = GENSEC_OID_NTLMSSP;
703                                 break;
704                         case PIPE_AUTH_TYPE_SPNEGO_KRB5:
705                                 oid = GENSEC_OID_KERBEROS5;
706                                 break;
707                         case PIPE_AUTH_TYPE_SPNEGO_NONE:
708                                 break;
709                         }
710                         ntresult = cli_rpc_pipe_open_spnego(
711                                 cli, cmd_entry->table,
712                                 default_transport,
713                                 oid,
714                                 pipe_default_auth_level,
715                                 smbXcli_conn_remote_name(cli->conn),
716                                 get_cmdline_auth_info_domain(auth_info),
717                                 get_cmdline_auth_info_username(auth_info),
718                                 get_cmdline_auth_info_password(auth_info),
719                                 &cmd_entry->rpc_pipe);
720                         break;
721                 }
722                 case DCERPC_AUTH_TYPE_NTLMSSP:
723                 case DCERPC_AUTH_TYPE_KRB5:
724                         ntresult = cli_rpc_pipe_open_generic_auth(
725                                 cli, cmd_entry->table,
726                                 default_transport,
727                                 pipe_default_auth_type,
728                                 pipe_default_auth_level,
729                                 smbXcli_conn_remote_name(cli->conn),
730                                 get_cmdline_auth_info_domain(auth_info),
731                                 get_cmdline_auth_info_username(auth_info),
732                                 get_cmdline_auth_info_password(auth_info),
733                                 &cmd_entry->rpc_pipe);
734                         break;
735                 case DCERPC_AUTH_TYPE_SCHANNEL:
736                         ntresult = cli_rpc_pipe_open_schannel(
737                                 cli, cmd_entry->table,
738                                 default_transport,
739                                 pipe_default_auth_level,
740                                 get_cmdline_auth_info_domain(auth_info),
741                                 &cmd_entry->rpc_pipe);
742                         break;
743                 default:
744                         DEBUG(0, ("Could not initialise %s. Invalid "
745                                   "auth type %u\n",
746                                   cmd_entry->table->name,
747                                   pipe_default_auth_type ));
748                         talloc_free(mem_ctx);
749                         return NT_STATUS_UNSUCCESSFUL;
750                 }
751                 if (!NT_STATUS_IS_OK(ntresult)) {
752                         DEBUG(0, ("Could not initialise %s. Error was %s\n",
753                                   cmd_entry->table->name,
754                                   nt_errstr(ntresult) ));
755                         talloc_free(mem_ctx);
756                         return ntresult;
757                 }
758
759                 if (ndr_syntax_id_equal(&cmd_entry->table->syntax_id,
760                                         &ndr_table_netlogon.syntax_id)) {
761                         uint32_t neg_flags = NETLOGON_NEG_AUTH2_ADS_FLAGS;
762                         enum netr_SchannelType sec_channel_type;
763                         uchar trust_password[16];
764                         const char *machine_account;
765
766                         if (!get_trust_pw_hash(get_cmdline_auth_info_domain(auth_info),
767                                                trust_password, &machine_account,
768                                                &sec_channel_type))
769                         {
770                                 talloc_free(mem_ctx);
771                                 return NT_STATUS_CANT_ACCESS_DOMAIN_INFO;
772                         }
773
774                         ntresult = rpccli_netlogon_setup_creds(cmd_entry->rpc_pipe,
775                                                 cmd_entry->rpc_pipe->desthost,   /* server name */
776                                                 get_cmdline_auth_info_domain(auth_info),  /* domain */
777                                                 lp_netbios_name(), /* client name */
778                                                 machine_account, /* machine account name */
779                                                 trust_password,
780                                                 sec_channel_type,
781                                                 &neg_flags);
782
783                         if (!NT_STATUS_IS_OK(ntresult)) {
784                                 DEBUG(0, ("Could not initialise credentials for %s.\n",
785                                           cmd_entry->table->name));
786                                 talloc_free(mem_ctx);
787                                 return ntresult;
788                         }
789                 }
790         }
791
792         /* Run command */
793
794         if ( cmd_entry->returntype == RPC_RTYPE_NTSTATUS ) {
795                 ntresult = cmd_entry->ntfn(cmd_entry->rpc_pipe, mem_ctx, argc, (const char **) argv);
796                 if (!NT_STATUS_IS_OK(ntresult)) {
797                         printf("result was %s\n", nt_errstr(ntresult));
798                 }
799         } else {
800                 wresult = cmd_entry->wfn(cmd_entry->rpc_pipe, mem_ctx, argc, (const char **) argv);
801                 /* print out the DOS error */
802                 if (!W_ERROR_IS_OK(wresult)) {
803                         printf( "result was %s\n", win_errstr(wresult));
804                 }
805                 ntresult = W_ERROR_IS_OK(wresult)?NT_STATUS_OK:NT_STATUS_UNSUCCESSFUL;
806         }
807
808         /* Cleanup */
809
810         talloc_free(mem_ctx);
811
812         return ntresult;
813 }
814
815
816 /**
817  * Process a command entered at the prompt or as part of -c
818  *
819  * @returns The NTSTATUS from running the command.
820  **/
821 static NTSTATUS process_cmd(struct user_auth_info *auth_info,
822                             struct cli_state *cli,
823                             struct dcerpc_binding *binding,
824                             char *cmd)
825 {
826         struct cmd_list *temp_list;
827         NTSTATUS result = NT_STATUS_OK;
828         int ret;
829         int argc;
830         char **argv = NULL;
831
832         if ((ret = poptParseArgvString(cmd, &argc, (const char ***) &argv)) != 0) {
833                 fprintf(stderr, "rpcclient: %s\n", poptStrerror(ret));
834                 return NT_STATUS_UNSUCCESSFUL;
835         }
836
837
838         /* Walk through a dlist of arrays of commands. */
839         for (temp_list = cmd_list; temp_list; temp_list = temp_list->next) {
840                 struct cmd_set *temp_set = temp_list->cmd_set;
841
842                 while (temp_set->name) {
843                         if (strequal(argv[0], temp_set->name)) {
844                                 if (!(temp_set->returntype == RPC_RTYPE_NTSTATUS && temp_set->ntfn ) &&
845                          !(temp_set->returntype == RPC_RTYPE_WERROR && temp_set->wfn )) {
846                                         fprintf (stderr, "Invalid command\n");
847                                         goto out_free;
848                                 }
849
850                                 result = do_cmd(cli, auth_info, temp_set,
851                                                 binding, argc, argv);
852
853                                 goto out_free;
854                         }
855                         temp_set++;
856                 }
857         }
858
859         if (argv[0]) {
860                 printf("command not found: %s\n", argv[0]);
861         }
862
863 out_free:
864 /* moved to do_cmd()
865         if (!NT_STATUS_IS_OK(result)) {
866                 printf("result was %s\n", nt_errstr(result));
867         }
868 */
869
870         /* NOTE: popt allocates the whole argv, including the
871          * strings, as a single block.  So a single free is
872          * enough to release it -- we don't free the
873          * individual strings.  rtfm. */
874         free(argv);
875
876         return result;
877 }
878
879
880 /* Main function */
881
882  int main(int argc, char *argv[])
883 {
884         int                     opt;
885         static char             *cmdstr = NULL;
886         const char *server;
887         struct cli_state        *cli = NULL;
888         static char             *opt_ipaddr=NULL;
889         struct cmd_set          **cmd_set;
890         struct sockaddr_storage server_ss;
891         NTSTATUS                nt_status;
892         static int              opt_port = 0;
893         int result = 0;
894         TALLOC_CTX *frame = talloc_stackframe();
895         uint32_t flags = 0;
896         struct dcerpc_binding *binding = NULL;
897         const char *binding_string = NULL;
898         char *user, *domain, *q;
899
900         /* make sure the vars that get altered (4th field) are in
901            a fixed location or certain compilers complain */
902         poptContext pc;
903         struct poptOption long_options[] = {
904                 POPT_AUTOHELP
905                 {"command",     'c', POPT_ARG_STRING,   &cmdstr, 'c', "Execute semicolon separated cmds", "COMMANDS"},
906                 {"dest-ip", 'I', POPT_ARG_STRING,   &opt_ipaddr, 'I', "Specify destination IP address", "IP"},
907                 {"port", 'p', POPT_ARG_INT,   &opt_port, 'p', "Specify port number", "PORT"},
908                 POPT_COMMON_SAMBA
909                 POPT_COMMON_CONNECTION
910                 POPT_COMMON_CREDENTIALS
911                 POPT_TABLEEND
912         };
913
914         load_case_tables();
915
916         zero_sockaddr(&server_ss);
917
918         setlinebuf(stdout);
919
920         /* the following functions are part of the Samba debugging
921            facilities.  See lib/debug.c */
922         setup_logging("rpcclient", DEBUG_STDOUT);
923
924         rpcclient_auth_info = user_auth_info_init(frame);
925         if (rpcclient_auth_info == NULL) {
926                 exit(1);
927         }
928         popt_common_set_auth_info(rpcclient_auth_info);
929
930         /* Parse options */
931
932         pc = poptGetContext("rpcclient", argc, (const char **) argv,
933                             long_options, 0);
934
935         if (argc == 1) {
936                 poptPrintHelp(pc, stderr, 0);
937                 goto done;
938         }
939
940         while((opt = poptGetNextOpt(pc)) != -1) {
941                 switch (opt) {
942
943                 case 'I':
944                         if (!interpret_string_addr(&server_ss,
945                                                 opt_ipaddr,
946                                                 AI_NUMERICHOST)) {
947                                 fprintf(stderr, "%s not a valid IP address\n",
948                                         opt_ipaddr);
949                                 result = 1;
950                                 goto done;
951                         }
952                 }
953         }
954
955         /* Get server as remaining unparsed argument.  Print usage if more
956            than one unparsed argument is present. */
957
958         server = poptGetArg(pc);
959
960         if (!server || poptGetArg(pc)) {
961                 poptPrintHelp(pc, stderr, 0);
962                 result = 1;
963                 goto done;
964         }
965
966         poptFreeContext(pc);
967         popt_burn_cmdline_password(argc, argv);
968
969         if (!init_names()) {
970                 result = 1;
971                 goto done;
972         }
973
974         /* Load smb.conf file */
975
976         if (!lp_load_global(get_dyn_CONFIGFILE()))
977                 fprintf(stderr, "Can't load %s\n", get_dyn_CONFIGFILE());
978
979         /* We must load interfaces after we load the smb.conf */
980         load_interfaces();
981
982         /*
983          * Get password
984          * from stdin if necessary
985          */
986
987         if (get_cmdline_auth_info_use_machine_account(rpcclient_auth_info) &&
988             !set_cmdline_auth_info_machine_account_creds(rpcclient_auth_info)) {
989                 result = 1;
990                 goto done;
991         }
992
993         set_cmdline_auth_info_getpass(rpcclient_auth_info);
994
995         if ((server[0] == '/' && server[1] == '/') ||
996                         (server[0] == '\\' && server[1] ==  '\\')) {
997                 server += 2;
998         }
999
1000         nt_status = dcerpc_parse_binding(frame, server, &binding);
1001
1002         if (!NT_STATUS_IS_OK(nt_status)) {
1003
1004                 binding_string = talloc_asprintf(frame, "ncacn_np:%s",
1005                                                  strip_hostname(server));
1006                 if (!binding_string) {
1007                         result = 1;
1008                         goto done;
1009                 }
1010
1011                 nt_status = dcerpc_parse_binding(frame, binding_string, &binding);
1012                 if (!NT_STATUS_IS_OK(nt_status)) {
1013                         result = -1;
1014                         goto done;
1015                 }
1016         }
1017
1018         if (binding->transport == NCA_UNKNOWN) {
1019                 binding->transport = NCACN_NP;
1020         }
1021
1022         if (binding->flags & DCERPC_SIGN) {
1023                 pipe_default_auth_level = DCERPC_AUTH_LEVEL_INTEGRITY;
1024                 pipe_default_auth_type = DCERPC_AUTH_TYPE_NTLMSSP;
1025         }
1026         if (binding->flags & DCERPC_SEAL) {
1027                 pipe_default_auth_level = DCERPC_AUTH_LEVEL_PRIVACY;
1028                 pipe_default_auth_type = DCERPC_AUTH_TYPE_NTLMSSP;
1029         }
1030         if (binding->flags & DCERPC_AUTH_SPNEGO) {
1031                 pipe_default_auth_type = DCERPC_AUTH_TYPE_SPNEGO;
1032                 pipe_default_auth_spnego_type = PIPE_AUTH_TYPE_SPNEGO_NTLMSSP;
1033         }
1034         if (binding->flags & DCERPC_AUTH_NTLM) {
1035                 /* If neither Integrity or Privacy are requested then
1036                  * Use just Connect level */
1037                 if (pipe_default_auth_level == DCERPC_AUTH_LEVEL_NONE) {
1038                         pipe_default_auth_level = DCERPC_AUTH_LEVEL_CONNECT;
1039                 }
1040
1041                 if (pipe_default_auth_type == DCERPC_AUTH_TYPE_SPNEGO) {
1042                         pipe_default_auth_spnego_type = PIPE_AUTH_TYPE_SPNEGO_NTLMSSP;
1043                 } else {
1044                         pipe_default_auth_type = DCERPC_AUTH_TYPE_NTLMSSP;
1045                 }
1046         }
1047         if (binding->flags & DCERPC_AUTH_KRB5) {
1048                 /* If neither Integrity or Privacy are requested then
1049                  * Use just Connect level */
1050                 if (pipe_default_auth_level == DCERPC_AUTH_LEVEL_NONE) {
1051                         pipe_default_auth_level = DCERPC_AUTH_LEVEL_CONNECT;
1052                 }
1053
1054                 if (pipe_default_auth_type == DCERPC_AUTH_TYPE_SPNEGO) {
1055                         pipe_default_auth_spnego_type = PIPE_AUTH_TYPE_SPNEGO_KRB5;
1056                 } else {
1057                         pipe_default_auth_type = DCERPC_AUTH_TYPE_KRB5;
1058                 }
1059         }
1060
1061         if (get_cmdline_auth_info_use_kerberos(rpcclient_auth_info)) {
1062                 flags |= CLI_FULL_CONNECTION_USE_KERBEROS |
1063                          CLI_FULL_CONNECTION_FALLBACK_AFTER_KERBEROS;
1064         }
1065         if (get_cmdline_auth_info_use_ccache(rpcclient_auth_info)) {
1066                 flags |= CLI_FULL_CONNECTION_USE_CCACHE;
1067         }
1068
1069         user = talloc_strdup(frame, get_cmdline_auth_info_username(rpcclient_auth_info));
1070         SMB_ASSERT(user != NULL);
1071         domain = talloc_strdup(frame, lp_workgroup());
1072         SMB_ASSERT(domain != NULL);
1073         set_cmdline_auth_info_domain(rpcclient_auth_info, domain);
1074
1075         if ((q = strchr_m(user,'\\'))) {
1076                 *q = 0;
1077                 set_cmdline_auth_info_domain(rpcclient_auth_info, user);
1078                 set_cmdline_auth_info_username(rpcclient_auth_info, q+1);
1079         }
1080
1081
1082         nt_status = cli_full_connection(&cli, lp_netbios_name(), binding->host,
1083                                         opt_ipaddr ? &server_ss : NULL, opt_port,
1084                                         "IPC$", "IPC",
1085                                         get_cmdline_auth_info_username(rpcclient_auth_info),
1086                                         get_cmdline_auth_info_domain(rpcclient_auth_info),
1087                                         get_cmdline_auth_info_password(rpcclient_auth_info),
1088                                         flags,
1089                                         get_cmdline_auth_info_signing_state(rpcclient_auth_info));
1090
1091         if (!NT_STATUS_IS_OK(nt_status)) {
1092                 DEBUG(0,("Cannot connect to server.  Error was %s\n", nt_errstr(nt_status)));
1093                 result = 1;
1094                 goto done;
1095         }
1096
1097         if (get_cmdline_auth_info_smb_encrypt(rpcclient_auth_info)) {
1098                 nt_status = cli_cm_force_encryption(cli,
1099                                         get_cmdline_auth_info_username(rpcclient_auth_info),
1100                                         get_cmdline_auth_info_password(rpcclient_auth_info),
1101                                         get_cmdline_auth_info_domain(rpcclient_auth_info),
1102                                         "IPC$");
1103                 if (!NT_STATUS_IS_OK(nt_status)) {
1104                         result = 1;
1105                         goto done;
1106                 }
1107         }
1108
1109 #if 0   /* COMMENT OUT FOR TESTING */
1110         memset(cmdline_auth_info.password,'X',sizeof(cmdline_auth_info.password));
1111 #endif
1112
1113         /* Load command lists */
1114
1115         timeout = cli_set_timeout(cli, 10000);
1116
1117         cmd_set = rpcclient_command_list;
1118
1119         while(*cmd_set) {
1120                 add_command_set(*cmd_set);
1121                 add_command_set(separator_command);
1122                 cmd_set++;
1123         }
1124
1125         default_transport = binding->transport;
1126
1127         fetch_machine_sid(cli);
1128
1129        /* Do anything specified with -c */
1130         if (cmdstr && cmdstr[0]) {
1131                 char    *cmd;
1132                 char    *p = cmdstr;
1133
1134                 result = 0;
1135
1136                 while((cmd=next_command(&p)) != NULL) {
1137                         NTSTATUS cmd_result = process_cmd(rpcclient_auth_info, cli,
1138                                                           binding, cmd);
1139                         SAFE_FREE(cmd);
1140                         result = NT_STATUS_IS_ERR(cmd_result);
1141                 }
1142
1143                 goto done;
1144         }
1145
1146         /* Loop around accepting commands */
1147
1148         while(1) {
1149                 char *line = NULL;
1150
1151                 line = smb_readline("rpcclient $> ", NULL, completion_fn);
1152
1153                 if (line == NULL)
1154                         break;
1155
1156                 if (line[0] != '\n')
1157                         process_cmd(rpcclient_auth_info, cli, binding, line);
1158                 SAFE_FREE(line);
1159         }
1160
1161 done:
1162         if (cli != NULL) {
1163                 cli_shutdown(cli);
1164         }
1165         TALLOC_FREE(frame);
1166         return result;
1167 }