changed syntax of registry commands so keys can start with HKLM or HKU.
[samba.git] / source3 / rpcclient / rpcclient.c
1 /* 
2    Unix SMB/Netbios implementation.
3    Version 1.9.
4    SMB client
5    Copyright (C) Andrew Tridgell 1994-1998
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 2 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, write to the Free Software
19    Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
20 */
21
22 #ifdef SYSLOG
23 #undef SYSLOG
24 #endif
25
26 #include "includes.h"
27
28 #ifndef REGISTER
29 #define REGISTER 0
30 #endif
31
32 extern pstring debugf;
33 extern pstring scope;
34 extern pstring global_myname;
35
36 extern pstring user_socket_options;
37
38
39 extern int DEBUGLEVEL;
40
41
42 extern file_info def_finfo;
43
44 #define CNV_LANG(s) dos2unix_format(s,False)
45 #define CNV_INPUT(s) unix2dos_format(s,True)
46
47 static int process_tok(fstring tok);
48 static void cmd_help(struct client_info *info);
49 static void cmd_quit(struct client_info *info);
50
51 static struct cli_state smbcli;
52 struct cli_state *smb_cli = &smbcli;
53
54 FILE *out_hnd;
55
56 /****************************************************************************
57 initialise smb client structure
58 ****************************************************************************/
59 void rpcclient_init(void)
60 {
61         bzero(smb_cli, sizeof(smb_cli));
62         cli_initialise(smb_cli);
63         smb_cli->capabilities |= CAP_NT_SMBS;
64 }
65
66 /****************************************************************************
67 make smb client connection
68 ****************************************************************************/
69 static BOOL rpcclient_connect(struct client_info *info)
70 {
71         struct nmb_name calling;
72         struct nmb_name called;
73
74         make_nmb_name(&called , dns_to_netbios_name(info->dest_host ), info->name_type, scope);
75         make_nmb_name(&calling, dns_to_netbios_name(info->myhostname), 0x0            , scope);
76
77         if (!cli_establish_connection(smb_cli, 
78                                   info->dest_host, &info->dest_ip, 
79                                   &calling, &called,
80                                   info->share, info->svc_type,
81                                   False, True))
82         {
83                 DEBUG(0,("rpcclient_connect: connection failed\n"));
84                 cli_shutdown(smb_cli);
85                 return False;
86         }
87
88         return True;
89 }
90
91 /****************************************************************************
92 stop the smb connection(s?)
93 ****************************************************************************/
94 static void rpcclient_stop(void)
95 {
96         cli_shutdown(smb_cli);
97 }
98 /****************************************************************************
99  This defines the commands supported by this client
100  ****************************************************************************/
101 struct
102 {
103   char *name;
104   void (*fn)(struct client_info*);
105   char *description;
106 } commands[] = 
107 {
108   {"regenum",    cmd_reg_enum,         "<keyname> Registry Enumeration (keys, values)"},
109   {"regdeletekey",cmd_reg_delete_key,  "<keyname> Registry Key Delete"},
110   {"regcreatekey",cmd_reg_create_key,  "<keyname> [keyclass] Registry Key Create"},
111   {"regquerykey",cmd_reg_query_key,    "<keyname> Registry Key Query"},
112   {"regdeleteval",cmd_reg_delete_val,  "<valname> Registry Value Delete"},
113   {"regcreateval",cmd_reg_create_val,  "<valname> <valtype> <value> Registry Key Create"},
114   {"reggetsec",  cmd_reg_get_key_sec,  "<keyname> Registry Key Security"},
115   {"ntlogin",    cmd_netlogon_login_test, "[username] [password] NT Domain login test"},
116   {"wksinfo",    cmd_wks_query_info,   "Workstation Query Info"},
117   {"srvinfo",    cmd_srv_query_info,   "Server Query Info"},
118   {"srvsessions",cmd_srv_enum_sess,    "List sessions on a server"},
119   {"srvshares",  cmd_srv_enum_shares,  "List shares on a server"},
120   {"srvconnections",cmd_srv_enum_conn, "List connections on a server"},
121   {"srvfiles",   cmd_srv_enum_files,   "List files on a server"},
122   {"lsaquery",   cmd_lsa_query_info,   "Query Info Policy (domain member or server)"},
123   {"lookupsids", cmd_lsa_lookup_sids,  "Resolve names from SIDs"},
124   {"enumusers",  cmd_sam_enum_users,   "SAM User Database Query (experimental!)"},
125   {"ntpass",     cmd_sam_ntchange_pwd, "NT SAM Password Change"},
126   {"samuser",    cmd_sam_query_user,   "<username> SAM User Query (experimental!)"},
127   {"samtest",    cmd_sam_test      ,   "SAM User Encrypted RPC test (experimental!)"},
128   {"enumaliases",cmd_sam_enum_aliases, "SAM Aliases Database Query (experimental!)"},
129 #if 0
130   {"enumgroups", cmd_sam_enum_groups,  "SAM Group Database Query (experimental!)"},
131 #endif
132   {"samgroups",  cmd_sam_query_groups, "SAM Group Database Query (experimental!)"},
133   {"quit",       cmd_quit,        "logoff the server"},
134   {"q",          cmd_quit,        "logoff the server"},
135   {"exit",       cmd_quit,        "logoff the server"},
136   {"bye",        cmd_quit,        "logoff the server"},
137   {"help",       cmd_help,        "[command] give help on a command"},
138   {"?",          cmd_help,        "[command] give help on a command"},
139   {"!",          NULL,            "run a shell command on the local system"},
140   {"",           NULL,            NULL}
141 };
142
143
144 /****************************************************************************
145 do a (presumably graceful) quit...
146 ****************************************************************************/
147 static void cmd_quit(struct client_info *info)
148 {
149         rpcclient_stop();
150 #ifdef MEM_MAN
151         {
152                 extern FILE* dbf;
153                 smb_mem_write_status(dbf);
154                 smb_mem_write_errors(dbf);
155                 smb_mem_write_verbose(dbf);
156         }
157 #endif
158         exit(0);
159 }
160
161 /****************************************************************************
162 help
163 ****************************************************************************/
164 static void cmd_help(struct client_info *info)
165 {
166   int i=0,j;
167   fstring buf;
168
169   if (next_token(NULL,buf,NULL, sizeof(buf)))
170     {
171       if ((i = process_tok(buf)) >= 0)
172         fprintf(out_hnd, "HELP %s:\n\t%s\n\n",commands[i].name,commands[i].description);                    
173     }
174   else
175     while (commands[i].description)
176       {
177         for (j=0; commands[i].description && (j<5); j++) {
178           fprintf(out_hnd, "%-15s",commands[i].name);
179           i++;
180         }
181         fprintf(out_hnd, "\n");
182       }
183 }
184
185 /*******************************************************************
186   lookup a command string in the list of commands, including 
187   abbreviations
188   ******************************************************************/
189 static int process_tok(fstring tok)
190 {
191   int i = 0, matches = 0;
192   int cmd=0;
193   int tok_len = strlen(tok);
194   
195   while (commands[i].fn != NULL)
196     {
197       if (strequal(commands[i].name,tok))
198         {
199           matches = 1;
200           cmd = i;
201           break;
202         }
203       else if (strnequal(commands[i].name, tok, tok_len))
204         {
205           matches++;
206           cmd = i;
207         }
208       i++;
209     }
210   
211   if (matches == 0)
212     return(-1);
213   else if (matches == 1)
214     return(cmd);
215   else
216     return(-2);
217 }
218
219 /****************************************************************************
220 wait for keyboard activity, swallowing network packets
221 ****************************************************************************/
222 static void wait_keyboard(struct cli_state *cli)
223 {
224   fd_set fds;
225   struct timeval timeout;
226   
227   while (1) 
228     {
229       FD_ZERO(&fds);
230       FD_SET(cli->fd,&fds);
231       FD_SET(fileno(stdin),&fds);
232
233       timeout.tv_sec = 20;
234       timeout.tv_usec = 0;
235       sys_select(MAX(cli->fd,fileno(stdin))+1,&fds,&timeout);
236       
237       if (FD_ISSET(fileno(stdin),&fds))
238         return;
239
240       /* We deliberately use receive_smb instead of
241          client_receive_smb as we want to receive
242          session keepalives and then drop them here.
243        */
244       if (FD_ISSET(cli->fd,&fds))
245         receive_smb(cli->fd,cli->inbuf,0);
246     }  
247 }
248
249 /****************************************************************************
250   process commands from the client
251 ****************************************************************************/
252 static void do_command(struct client_info *info, char *tok, char *line)
253 {
254         int i;
255
256         if ((i = process_tok(tok)) >= 0)
257         {
258                 commands[i].fn(info);
259         }
260         else if (i == -2)
261         {
262                 fprintf(out_hnd, "%s: command abbreviation ambiguous\n", CNV_LANG(tok));
263         }
264         else
265         {
266                 fprintf(out_hnd, "%s: command not found\n", CNV_LANG(tok));
267         }
268 }
269
270 /****************************************************************************
271   process commands from the client
272 ****************************************************************************/
273 static BOOL process( struct client_info *info, char *cmd_str)
274 {
275         pstring line;
276         char *cmd = cmd_str;
277
278         if (cmd[0] != '\0') while (cmd[0] != '\0')
279         {
280                 char *p;
281                 fstring tok;
282
283                 if ((p = strchr(cmd, ';')) == 0)
284                 {
285                         strncpy(line, cmd, 999);
286                         line[1000] = '\0';
287                         cmd += strlen(cmd);
288                 }
289                 else
290                 {
291                         if (p - cmd > 999) p = cmd + 999;
292                         strncpy(line, cmd, p - cmd);
293                         line[p - cmd] = '\0';
294                         cmd = p + 1;
295                 }
296
297                 /* input language code to internal one */
298                 CNV_INPUT (line);
299
300                 /* get the first part of the command */
301                 {
302                         char *ptr = line;
303                         if (!next_token(&ptr,tok,NULL, sizeof(tok))) continue;
304                 }
305
306                 do_command(info, tok, line);
307         }
308         else while (!feof(stdin))
309         {
310                 fstring tok;
311
312                 /* display a prompt */
313                 fprintf(out_hnd, "smb: %s> ", CNV_LANG(info->cur_dir));
314                 fflush(out_hnd);
315
316 #ifdef CLIX
317                 line[0] = wait_keyboard(smb_cli);
318                 /* this might not be such a good idea... */
319                 if ( line[0] == EOF)
320                 {
321                         break;
322                 }
323 #else
324                 wait_keyboard(smb_cli);
325 #endif
326
327                 /* and get a response */
328 #ifdef CLIX
329                 fgets( &line[1],999, stdin);
330 #else
331                 if (!fgets(line,1000,stdin))
332                 {
333                         break;
334                 }
335 #endif
336
337                 /* input language code to internal one */
338                 CNV_INPUT (line);
339
340                 /* special case - first char is ! */
341                 if (*line == '!')
342                 {
343                         system(line + 1);
344                         continue;
345                 }
346
347                 fprintf(out_hnd, "%s\n", line);
348
349                 /* get the first part of the command */
350                 {
351                         char *ptr = line;
352                         if (!next_token(&ptr,tok,NULL, sizeof(tok))) continue;
353                 }
354
355                 do_command(info, tok, line);
356         }
357
358         return(True);
359 }
360
361 /****************************************************************************
362 usage on the program
363 ****************************************************************************/
364 static void usage(char *pname)
365 {
366   fprintf(out_hnd, "Usage: %s service <password> [-d debuglevel] [-l log] ",
367            pname);
368
369   fprintf(out_hnd, "\nVersion %s\n",VERSION);
370   fprintf(out_hnd, "\t-d debuglevel         set the debuglevel\n");
371   fprintf(out_hnd, "\t-l log basename.      Basename for log/debug files\n");
372   fprintf(out_hnd, "\t-n netbios name.      Use this name as my netbios name\n");
373   fprintf(out_hnd, "\t-N                    don't ask for a password\n");
374   fprintf(out_hnd, "\t-m max protocol       set the max protocol level\n");
375   fprintf(out_hnd, "\t-I dest IP            use this IP to connect to\n");
376   fprintf(out_hnd, "\t-E                    write messages to stderr instead of stdout\n");
377   fprintf(out_hnd, "\t-U username           set the network username\n");
378   fprintf(out_hnd, "\t-W workgroup          set the workgroup name\n");
379   fprintf(out_hnd, "\t-c command string     execute semicolon separated commands\n");
380   fprintf(out_hnd, "\t-t terminal code      terminal i/o code {sjis|euc|jis7|jis8|junet|hex}\n");
381   fprintf(out_hnd, "\n");
382 }
383
384 enum client_action
385 {
386         CLIENT_NONE,
387         CLIENT_IPC,
388         CLIENT_SVC
389 };
390
391 /****************************************************************************
392   main program
393 ****************************************************************************/
394  int main(int argc,char *argv[])
395 {
396         BOOL interactive = True;
397
398         int opt;
399         extern FILE *dbf;
400         extern char *optarg;
401         extern int optind;
402         static pstring servicesf = CONFIGFILE;
403         pstring term_code;
404         char *p;
405         BOOL got_pass = False;
406         char *cmd_str="";
407         mode_t myumask = 0755;
408         enum client_action cli_action = CLIENT_NONE;
409
410         struct client_info cli_info;
411
412         pstring password; /* local copy only, if one is entered */
413
414         out_hnd = stdout;
415         fstrcpy(debugf, argv[0]);
416
417         rpcclient_init();
418
419 #ifdef KANJI
420         pstrcpy(term_code, KANJI);
421 #else /* KANJI */
422         *term_code = 0;
423 #endif /* KANJI */
424
425         DEBUGLEVEL = 2;
426
427         cli_info.put_total_size = 0;
428         cli_info.put_total_time_ms = 0;
429         cli_info.get_total_size = 0;
430         cli_info.get_total_time_ms = 0;
431
432         cli_info.dir_total = 0;
433         cli_info.newer_than = 0;
434         cli_info.archive_level = 0;
435         cli_info.print_mode = 1;
436
437         cli_info.translation = False;
438         cli_info.recurse_dir = False;
439         cli_info.lowercase = False;
440         cli_info.prompt = True;
441         cli_info.abort_mget = True;
442
443         cli_info.dest_ip.s_addr = 0;
444         cli_info.name_type = 0x20;
445
446         pstrcpy(cli_info.cur_dir , "\\");
447         pstrcpy(cli_info.file_sel, "");
448         pstrcpy(cli_info.base_dir, "");
449         pstrcpy(smb_cli->domain, "");
450         pstrcpy(smb_cli->user_name, "");
451         pstrcpy(cli_info.myhostname, "");
452         pstrcpy(cli_info.dest_host, "");
453
454         pstrcpy(cli_info.svc_type, "A:");
455         pstrcpy(cli_info.share, "");
456         pstrcpy(cli_info.service, "");
457
458         ZERO_STRUCT(cli_info.dom.level3_sid);
459         ZERO_STRUCT(cli_info.dom.level5_sid);
460         fstrcpy(cli_info.dom.level3_dom, "");
461         fstrcpy(cli_info.dom.level5_dom, "");
462
463         smb_cli->nt_pipe_fnum   = 0xffff;
464
465         TimeInit();
466         charset_initialise();
467
468         myumask = umask(0);
469         umask(myumask);
470
471         if (!get_myname(global_myname, NULL))
472         {
473                 fprintf(stderr, "Failed to get my hostname.\n");
474         }
475
476         if (getenv("USER"))
477         {
478                 pstrcpy(smb_cli->user_name,getenv("USER"));
479
480                 /* modification to support userid%passwd syntax in the USER var
481                 25.Aug.97, jdblair@uab.edu */
482
483                 if ((p=strchr(smb_cli->user_name,'%')))
484                 {
485                         *p = 0;
486                         pstrcpy(password,p+1);
487                         got_pass = True;
488                         memset(strchr(getenv("USER"),'%')+1,'X',strlen(password));
489                 }
490                 strupper(smb_cli->user_name);
491         }
492
493         password[0] = 0;
494
495         /* modification to support PASSWD environmental var
496            25.Aug.97, jdblair@uab.edu */
497         if (getenv("PASSWD"))
498         {
499                 pstrcpy(password,getenv("PASSWD"));
500         }
501
502         if (*smb_cli->user_name == 0 && getenv("LOGNAME"))
503         {
504                 pstrcpy(smb_cli->user_name,getenv("LOGNAME"));
505                 strupper(smb_cli->user_name);
506         }
507
508         if (argc < 2)
509         {
510                 usage(argv[0]);
511                 exit(1);
512         }
513
514         if (*argv[1] != '-')
515         {
516
517                 pstrcpy(cli_info.service, argv[1]);  
518                 /* Convert any '/' characters in the service name to '\' characters */
519                 string_replace( cli_info.service, '/','\\');
520                 argc--;
521                 argv++;
522
523                 fprintf(out_hnd, "service: %s\n", cli_info.service);
524
525                 if (count_chars(cli_info.service,'\\') < 3)
526                 {
527                         usage(argv[0]);
528                         printf("\n%s: Not enough '\\' characters in service\n", cli_info.service);
529                         exit(1);
530                 }
531
532                 /*
533                 if (count_chars(cli_info.service,'\\') > 3)
534                 {
535                         usage(pname);
536                         printf("\n%s: Too many '\\' characters in service\n", cli_info.service);
537                         exit(1);
538                 }
539                 */
540
541                 if (argc > 1 && (*argv[1] != '-'))
542                 {
543                         got_pass = True;
544                         pstrcpy(password,argv[1]);  
545                         memset(argv[1],'X',strlen(argv[1]));
546                         argc--;
547                         argv++;
548                 }
549
550                 cli_action = CLIENT_SVC;
551         }
552
553         while ((opt = getopt(argc, argv,"s:B:O:M:S:i:N:n:d:l:hI:EB:U:L:t:m:W:T:D:c:")) != EOF)
554         {
555                 switch (opt)
556                 {
557                         case 'm':
558                         {
559                                 /* FIXME ... max_protocol seems to be funny here */
560
561                                 int max_protocol = 0;
562                                 max_protocol = interpret_protocol(optarg,max_protocol);
563                                 fprintf(stderr, "max protocol not currently supported\n");
564                                 break;
565                         }
566
567                         case 'O':
568                         {
569                                 pstrcpy(user_socket_options,optarg);
570                                 break;  
571                         }
572
573                         case 'S':
574                         {
575                                 pstrcpy(cli_info.dest_host,optarg);
576                                 strupper(cli_info.dest_host);
577                                 cli_action = CLIENT_IPC;
578                                 break;
579                         }
580
581                         case 'B':
582                         {
583                                 iface_set_default(NULL,optarg,NULL);
584                                 break;
585                         }
586
587                         case 'i':
588                         {
589                                 pstrcpy(scope, optarg);
590                                 break;
591                         }
592
593                         case 'U':
594                         {
595                                 char *lp;
596                                 pstrcpy(smb_cli->user_name,optarg);
597                                 if ((lp=strchr(smb_cli->user_name,'%')))
598                                 {
599                                         *lp = 0;
600                                         pstrcpy(password,lp+1);
601                                         got_pass = True;
602                                         memset(strchr(optarg,'%')+1,'X',strlen(password));
603                                 }
604                                 break;
605                         }
606
607                         case 'W':
608                         {
609                                 pstrcpy(smb_cli->domain,optarg);
610                                 break;
611                         }
612
613                         case 'E':
614                         {
615                                 dbf = stderr;
616                                 break;
617                         }
618
619                         case 'I':
620                         {
621                                 cli_info.dest_ip = *interpret_addr2(optarg);
622                                 if (zero_ip(cli_info.dest_ip))
623                                 {
624                                         exit(1);
625                                 }
626                                 break;
627                         }
628
629                         case 'n':
630                         {
631                                 fstrcpy(global_myname, optarg);
632                                 break;
633                         }
634
635                         case 'N':
636                         {
637                                 got_pass = True;
638                                 break;
639                         }
640
641                         case 'd':
642                         {
643                                 if (*optarg == 'A')
644                                         DEBUGLEVEL = 10000;
645                                 else
646                                         DEBUGLEVEL = atoi(optarg);
647                                 break;
648                         }
649
650                         case 'l':
651                         {
652                                 slprintf(debugf, sizeof(debugf)-1,
653                                          "%s.client", optarg);
654                                 interactive = False;
655                                 break;
656                         }
657
658                         case 'c':
659                         {
660                                 cmd_str = optarg;
661                                 got_pass = True;
662                                 break;
663                         }
664
665                         case 'h':
666                         {
667                                 usage(argv[0]);
668                                 exit(0);
669                                 break;
670                         }
671
672                         case 's':
673                         {
674                                 pstrcpy(servicesf, optarg);
675                                 break;
676                         }
677
678                         case 't':
679                         {
680                                 pstrcpy(term_code, optarg);
681                                 break;
682                         }
683
684                         default:
685                         {
686                                 usage(argv[0]);
687                                 exit(1);
688                                 break;
689                         }
690                 }
691         }
692
693         setup_logging(debugf, interactive);
694
695         if (cli_action == CLIENT_NONE)
696         {
697                 usage(argv[0]);
698                 exit(1);
699         }
700
701         strupper(global_myname);
702         fstrcpy(cli_info.myhostname, global_myname);
703
704         DEBUG(3,("%s client started (version %s)\n",timestring(),VERSION));
705
706         if (!lp_load(servicesf,True, False, False))
707         {
708                 fprintf(stderr, "Can't load %s - run testparm to debug it\n", servicesf);
709         }
710
711         codepage_initialise(lp_client_code_page());
712
713         if (*smb_cli->domain == 0) pstrcpy(smb_cli->domain,lp_workgroup());
714
715         load_interfaces();
716
717         if (cli_action == CLIENT_IPC)
718         {
719                 pstrcpy(cli_info.share, "IPC$");
720                 pstrcpy(cli_info.svc_type, "IPC");
721         }
722
723         fstrcpy(cli_info.mach_acct, cli_info.myhostname);
724         strupper(cli_info.mach_acct);
725         fstrcat(cli_info.mach_acct, "$");
726
727         /* set the password cache info */
728         if (got_pass)
729         {
730                 if (password[0] == 0)
731                 {
732                         pwd_set_nullpwd(&(smb_cli->pwd));
733                 }
734                 else
735                 {
736                         pwd_make_lm_nt_16(&(smb_cli->pwd), password); /* generate 16 byte hashes */
737                 }
738         }
739         else 
740         {
741                 pwd_read(&(smb_cli->pwd), "Enter Password:", True);
742         }
743
744         /* paranoia: destroy the local copy of the password */
745         bzero(password, sizeof(password)); 
746
747         /* establish connections.  nothing to stop these being re-established. */
748         rpcclient_connect(&cli_info);
749
750         DEBUG(5,("rpcclient_connect: smb_cli->fd:%d\n", smb_cli->fd));
751         if (smb_cli->fd <= 0)
752         {
753                 fprintf(stderr, "warning: connection could not be established to %s<%02x>\n",
754                                  cli_info.dest_host, cli_info.name_type);
755                 fprintf(stderr, "this version of smbclient may crash if you proceed\n");
756                 exit(-1);
757         }
758
759         switch (cli_action)
760         {
761                 case CLIENT_IPC:
762                 {
763                         process(&cli_info, cmd_str);
764                         break;
765                 }
766
767                 default:
768                 {
769                         fprintf(stderr, "unknown client action requested\n");
770                         break;
771                 }
772         }
773
774         rpcclient_stop();
775
776         return(0);
777 }