source: trunk/src/reglookup.c @ 126

Last change on this file since 126 was 126, checked in by tim, 16 years ago

improved validation and output of key class names, MULTI_SZ and other unicode strings, and improved warnings and other error messages.

  • Property svn:keywords set to Id
File size: 16.4 KB
Line 
1/*
2 * A utility to read a Windows NT/2K/XP/2K3 registry file, using
3 * Gerald Carter''s regfio interface.
4 *
5 * Copyright (C) 2005-2008 Timothy D. Morgan
6 * Copyright (C) 2002 Richard Sharpe, rsharpe@richardsharpe.com
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; version 3 of the License.
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 * $Id: reglookup.c 126 2008-08-19 23:31:33Z tim $
22 */
23
24
25#include <stdlib.h>
26#include <sysexits.h>
27#include <stdio.h>
28#include <string.h>
29#include <strings.h>
30#include <time.h>
31#include "../include/regfi.h"
32#include "../include/void_stack.h"
33
34/* Globals, influenced by command line parameters */
35bool print_verbose = false;
36bool print_security = false;
37bool print_header = true;
38bool path_filter_enabled = false;
39bool type_filter_enabled = false;
40char* path_filter = NULL;
41int type_filter;
42char* registry_file = NULL;
43
44/* Other globals */
45REGF_FILE* f;
46
47
48/* XXX: A hack to share some functions with reglookup-recover.c.
49 *      Should move these into a proper library at some point.
50 */
51#include "common.c"
52
53
54void printValue(const REGF_VK_REC* vk, char* prefix)
55{
56  char* quoted_value = NULL;
57  char* quoted_name = NULL;
58  char* conv_error = NULL;
59  const char* str_type = NULL;
60  uint32 size = vk->data_size;
61
62  /* Microsoft's documentation indicates that "available memory" is
63   * the limit on value sizes.  Annoying.  We limit it to 1M which
64   * should rarely be exceeded, unless the file is corrupt or
65   * malicious. For more info, see:
66   *   http://msdn2.microsoft.com/en-us/library/ms724872.aspx
67   */
68  if(size > VK_MAX_DATA_LENGTH)
69  {
70    fprintf(stderr, "WARNING: value data size %d larger than "
71            "%d, truncating...\n", size, VK_MAX_DATA_LENGTH);
72    size = VK_MAX_DATA_LENGTH;
73  }
74 
75  quoted_name = quote_string(vk->valuename, key_special_chars);
76  if (quoted_name == NULL)
77  { /* Value names are NULL when we're looking at the "(default)" value.
78     * Currently we just return a 0-length string to try an eliminate
79     * ambiguity with a literal "(default)" value.  The data type of a line
80     * in the output allows one to differentiate between the parent key and
81     * this value.
82     */
83    quoted_name = malloc(1*sizeof(char));
84    if(quoted_name == NULL)
85      bailOut(EX_OSERR, "ERROR: Could not allocate sufficient memory.\n");
86    quoted_name[0] = '\0';
87  }
88
89  quoted_value = data_to_ascii(vk->data, size, vk->type, &conv_error);
90  if(quoted_value == NULL)
91  {
92    if(conv_error == NULL)
93      fprintf(stderr, "WARNING: Could not quote value for '%s/%s'.  "
94              "Memory allocation failure likely.\n", prefix, quoted_name);
95    else if(print_verbose)
96      fprintf(stderr, "WARNING: Could not quote value for '%s/%s'.  "
97              "Returned error: %s\n", prefix, quoted_name, conv_error);
98  }
99  else if(conv_error != NULL && print_verbose)
100    fprintf(stderr, "VERBOSE: While quoting value for '%s/%s', "
101            "warning returned: %s\n", prefix, quoted_name, conv_error);
102
103  str_type = regfi_type_val2str(vk->type);
104  if(print_security)
105  {
106    if(str_type == NULL)
107      printf("%s/%s,0x%.8X,%s,,,,,\n", prefix, quoted_name,
108             vk->type, quoted_value);
109    else
110      printf("%s/%s,%s,%s,,,,,\n", prefix, quoted_name,
111             str_type, quoted_value);
112  }
113  else
114  {
115    if(str_type == NULL)
116      printf("%s/%s,0x%.8X,%s,\n", prefix, quoted_name,
117             vk->type, quoted_value);
118    else
119      printf("%s/%s,%s,%s,\n", prefix, quoted_name,
120             str_type, quoted_value);
121  }
122
123  if(quoted_value != NULL)
124    free(quoted_value);
125  if(quoted_name != NULL)
126    free(quoted_name);
127  if(conv_error != NULL)
128    free(conv_error);
129}
130
131
132
133/* XXX: Each chunk must be unquoted after it is split out.
134 *      Quoting syntax may need to be standardized and pushed into the API
135 *      to deal with this issue and others.
136 */
137char** splitPath(const char* s)
138{
139  char** ret_val;
140  const char* cur = s;
141  char* next = NULL;
142  char* copy;
143  uint32 ret_cur = 0;
144
145  ret_val = (char**)malloc((REGF_MAX_DEPTH+1+1)*sizeof(char**));
146  if (ret_val == NULL)
147    return NULL;
148  ret_val[0] = NULL;
149
150  /* We return a well-formed, 0-length, path even when input is icky. */
151  if (s == NULL)
152    return ret_val;
153 
154  while((next = strchr(cur, '/')) != NULL)
155  {
156    if ((next-cur) > 0)
157    {
158      copy = (char*)malloc((next-cur+1)*sizeof(char));
159      if(copy == NULL)
160        bailOut(EX_OSERR, "ERROR: Memory allocation problem.\n");
161         
162      memcpy(copy, cur, next-cur);
163      copy[next-cur] = '\0';
164      ret_val[ret_cur++] = copy;
165      if(ret_cur < (REGF_MAX_DEPTH+1+1))
166        ret_val[ret_cur] = NULL;
167      else
168        bailOut(EX_DATAERR, "ERROR: Registry maximum depth exceeded.\n");
169    }
170    cur = next+1;
171  }
172
173  /* Grab last element, if path doesn't end in '/'. */
174  if(strlen(cur) > 0)
175  {
176    copy = strdup(cur);
177    ret_val[ret_cur++] = copy;
178    if(ret_cur < (REGF_MAX_DEPTH+1+1))
179      ret_val[ret_cur] = NULL;
180    else
181      bailOut(EX_DATAERR, "ERROR: Registry maximum depth exceeded.\n");
182  }
183
184  return ret_val;
185}
186
187
188void freePath(char** path)
189{
190  uint32 i;
191
192  if(path == NULL)
193    return;
194
195  for(i=0; path[i] != NULL; i++)
196    free(path[i]);
197
198  free(path);
199}
200
201
202/* Returns a quoted path from an iterator's stack */
203/* XXX: Some way should be found to integrate this into regfi's API
204 *      The problem is that the escaping is sorta reglookup-specific.
205 */
206char* iter2Path(REGFI_ITERATOR* i)
207{
208  const REGFI_ITER_POSITION* cur;
209  uint32 buf_left = 127;
210  uint32 buf_len = buf_left+1;
211  uint32 name_len = 0;
212  uint32 grow_amt;
213  char* buf;
214  char* new_buf;
215  char* name;
216  const char* cur_name;
217  void_stack_iterator* iter;
218 
219  buf = (char*)malloc((buf_len)*sizeof(char));
220  if (buf == NULL)
221    return NULL;
222  buf[0] = '\0';
223
224  iter = void_stack_iterator_new(i->key_positions);
225  if (iter == NULL)
226  {
227    free(buf);
228    return NULL;
229  }
230
231  /* skip root element */
232  if(void_stack_size(i->key_positions) < 1)
233  {
234    buf[0] = '/';
235    buf[1] = '\0';
236    return buf;
237  }
238  cur = void_stack_iterator_next(iter);
239
240  do
241  {
242    cur = void_stack_iterator_next(iter);
243    if (cur == NULL)
244      cur_name = i->cur_key->keyname;
245    else
246      cur_name = cur->nk->keyname;
247
248    buf[buf_len-buf_left-1] = '/';
249    buf_left -= 1;
250    name = quote_string(cur_name, key_special_chars);
251    name_len = strlen(name);
252    if(name_len+1 > buf_left)
253    {
254      grow_amt = (uint32)(buf_len/2);
255      buf_len += name_len+1+grow_amt-buf_left;
256      if((new_buf = realloc(buf, buf_len)) == NULL)
257      {
258        free(buf);
259        free(iter);
260        return NULL;
261      }
262      buf = new_buf;
263      buf_left = grow_amt + name_len + 1;
264    }
265    strncpy(buf+(buf_len-buf_left-1), name, name_len);
266    buf_left -= name_len;
267    buf[buf_len-buf_left-1] = '\0';
268    free(name);
269  } while(cur != NULL);
270
271  return buf;
272}
273
274
275void printValueList(REGFI_ITERATOR* i, char* prefix)
276{
277  const REGF_VK_REC* value;
278
279  value = regfi_iterator_first_value(i);
280  while(value != NULL)
281  {
282    if(!type_filter_enabled || (value->type == type_filter))
283      printValue(value, prefix);
284    value = regfi_iterator_next_value(i);
285  }
286}
287
288
289void printKey(REGFI_ITERATOR* i, char* full_path)
290{
291  static char empty_str[1] = "";
292  char* owner = NULL;
293  char* group = NULL;
294  char* sacl = NULL;
295  char* dacl = NULL;
296  char* quoted_classname;
297  char* error_msg = NULL;
298  char mtime[20];
299  time_t tmp_time[1];
300  struct tm* tmp_time_s = NULL;
301  const REGF_SK_REC* sk;
302  const REGF_NK_REC* k = regfi_iterator_cur_key(i);
303
304  *tmp_time = nt_time_to_unix(&k->mtime);
305  tmp_time_s = gmtime(tmp_time);
306  strftime(mtime, sizeof(mtime), "%Y-%m-%d %H:%M:%S", tmp_time_s);
307
308  if(print_security && (sk=regfi_iterator_cur_sk(i)))
309  {
310    owner = regfi_get_owner(sk->sec_desc);
311    group = regfi_get_group(sk->sec_desc);
312    sacl = regfi_get_sacl(sk->sec_desc);
313    dacl = regfi_get_dacl(sk->sec_desc);
314    if(owner == NULL)
315      owner = empty_str;
316    if(group == NULL)
317      group = empty_str;
318    if(sacl == NULL)
319      sacl = empty_str;
320    if(dacl == NULL)
321      dacl = empty_str;
322
323    if(k->classname != NULL)
324    {
325      quoted_classname = quote_unicode((uint8*)k->classname, k->classname_length,
326                                       key_special_chars, &error_msg);
327      if(quoted_classname == NULL)
328      {
329        if(error_msg == NULL)
330          fprintf(stderr, "ERROR: Could not quote classname"
331                  " for key '%s' due to unknown error.\n", full_path);
332        else
333        {
334          fprintf(stderr, "ERROR: Could not quote classname"
335                  " for key '%s' due to error: %s\n", full_path, error_msg);
336          free(error_msg);
337        }
338      }
339      else if (error_msg != NULL)
340      {
341        if(print_verbose)
342          fprintf(stderr, "WARNING: While converting classname"
343                  " for key '%s': %s.\n", full_path, error_msg);
344        free(error_msg);
345      }
346    }
347    else
348      quoted_classname = empty_str;
349
350    printf("%s,KEY,,%s,%s,%s,%s,%s,%s\n", full_path, mtime, 
351           owner, group, sacl, dacl, quoted_classname);
352
353    if(owner != empty_str)
354      free(owner);
355    if(group != empty_str)
356      free(group);
357    if(sacl != empty_str)
358      free(sacl);
359    if(dacl != empty_str)
360      free(dacl);
361    if(quoted_classname != empty_str)
362      free(quoted_classname);
363  }
364  else
365    printf("%s,KEY,,%s\n", full_path, mtime);
366}
367
368
369void printKeyTree(REGFI_ITERATOR* iter)
370{
371  const REGF_NK_REC* root = NULL;
372  const REGF_NK_REC* cur = NULL;
373  const REGF_NK_REC* sub = NULL;
374  char* path = NULL;
375  int key_type = regfi_type_str2val("KEY");
376  bool print_this = true;
377
378  root = cur = regfi_iterator_cur_key(iter);
379  sub = regfi_iterator_first_subkey(iter);
380 
381  if(root == NULL)
382    bailOut(EX_DATAERR, "ERROR: root cannot be NULL.\n");
383 
384  do
385  {
386    if(print_this)
387    {
388      path = iter2Path(iter);
389      if(path == NULL)
390        bailOut(EX_OSERR, "ERROR: Could not construct iterator's path.\n");
391     
392      if(!type_filter_enabled || (key_type == type_filter))
393        printKey(iter, path);
394      if(!type_filter_enabled || (key_type != type_filter))
395        printValueList(iter, path);
396     
397      free(path);
398    }
399   
400    if(sub == NULL)
401    {
402      if(cur != root)
403      {
404        /* We're done with this sub-tree, going up and hitting other branches. */
405        if(!regfi_iterator_up(iter))
406          bailOut(EX_DATAERR, "ERROR: could not traverse iterator upward.\n");
407       
408        cur = regfi_iterator_cur_key(iter);
409        if(cur == NULL)
410          bailOut(EX_DATAERR, "ERROR: unexpected NULL for key.\n");
411       
412        sub = regfi_iterator_next_subkey(iter);
413      }
414      print_this = false;
415    }
416    else
417    { /* We have unexplored sub-keys. 
418       * Let's move down and print this first sub-tree out.
419       */
420      if(!regfi_iterator_down(iter))
421        bailOut(EX_DATAERR, "ERROR: could not traverse iterator downward.\n");
422
423      cur = sub;
424      sub = regfi_iterator_first_subkey(iter);
425      print_this = true;
426    }
427  } while(!((cur == root) && (sub == NULL)));
428
429  if(print_verbose)
430    fprintf(stderr, "VERBOSE: Finished printing key tree.\n");
431}
432
433
434/* XXX: what if there is BOTH a value AND a key with that name?? */
435/*
436 * Returns 0 if path was not found.
437 * Returns 1 if path was found as value.
438 * Returns 2 if path was found as key.
439 * Returns less than 0 on other error.
440 */
441int retrievePath(REGFI_ITERATOR* iter, char** path)
442{
443  const REGF_VK_REC* value;
444  char* tmp_path_joined;
445  const char** tmp_path;
446  uint32 i;
447 
448  if(path == NULL)
449    return -1;
450
451  /* One extra for any value at the end, and one more for NULL */
452  tmp_path = (const char**)malloc(sizeof(const char**)*(REGF_MAX_DEPTH+1+1));
453  if(tmp_path == NULL)
454    return -2;
455
456  /* Strip any potential value name at end of path */
457  for(i=0; 
458      (path[i] != NULL) && (path[i+1] != NULL) 
459        && (i < REGF_MAX_DEPTH+1+1);
460      i++)
461    tmp_path[i] = path[i];
462
463  tmp_path[i] = NULL;
464
465  if(print_verbose)
466    fprintf(stderr, "VERBOSE: Attempting to retrieve specified path: %s\n",
467            path_filter);
468
469  /* Special check for '/' path filter */
470  if(path[0] == NULL)
471  {
472    if(print_verbose)
473      fprintf(stderr, "VERBOSE: Found final path element as root key.\n");
474    return 2;
475  }
476
477  if(!regfi_iterator_walk_path(iter, tmp_path))
478  {
479    free(tmp_path);
480    return 0;
481  }
482
483  if(regfi_iterator_find_value(iter, path[i]))
484  {
485    if(print_verbose)
486      fprintf(stderr, "VERBOSE: Found final path element as value.\n");
487
488    value = regfi_iterator_cur_value(iter);
489    tmp_path_joined = iter2Path(iter);
490
491    if((value == NULL) || (tmp_path_joined == NULL))
492      bailOut(EX_OSERR, "ERROR: Unexpected error before printValue.\n");
493
494    if(!type_filter_enabled || (value->type == type_filter))
495      printValue(value, tmp_path_joined);
496
497    free(tmp_path);
498    free(tmp_path_joined);
499    return 1;
500  }
501  else if(regfi_iterator_find_subkey(iter, path[i]))
502  {
503    if(print_verbose)
504      fprintf(stderr, "VERBOSE: Found final path element as key.\n");
505
506    if(!regfi_iterator_down(iter))
507      bailOut(EX_DATAERR, "ERROR: Unexpected error on traversing path filter key.\n");
508
509    return 2;
510  }
511
512  if(print_verbose)
513    fprintf(stderr, "VERBOSE: Could not find last element of path.\n");
514
515  return 0;
516}
517
518
519static void usage(void)
520{
521  fprintf(stderr, "Usage: reglookup [-v] [-s]"
522          " [-p <PATH_FILTER>] [-t <TYPE_FILTER>]"
523          " <REGISTRY_FILE>\n");
524  fprintf(stderr, "Version: %s\n", REGLOOKUP_VERSION);
525  fprintf(stderr, "Options:\n");
526  fprintf(stderr, "\t-v\t sets verbose mode.\n");
527  fprintf(stderr, "\t-h\t enables header row. (default)\n");
528  fprintf(stderr, "\t-H\t disables header row.\n");
529  fprintf(stderr, "\t-s\t enables security descriptor output.\n");
530  fprintf(stderr, "\t-S\t disables security descriptor output. (default)\n");
531  fprintf(stderr, "\t-p\t restrict output to elements below this path.\n");
532  fprintf(stderr, "\t-t\t restrict results to this specific data type.\n");
533  fprintf(stderr, "\n");
534}
535
536
537int main(int argc, char** argv)
538{
539  char** path = NULL;
540  REGFI_ITERATOR* iter;
541  int retr_path_ret;
542  uint32 argi, arge;
543
544  /* Process command line arguments */
545  if(argc < 2)
546  {
547    usage();
548    bailOut(EX_USAGE, "ERROR: Requires at least one argument.\n");
549  }
550 
551  arge = argc-1;
552  for(argi = 1; argi < arge; argi++)
553  {
554    if (strcmp("-p", argv[argi]) == 0)
555    {
556      if(++argi >= arge)
557      {
558        usage();
559        bailOut(EX_USAGE, "ERROR: '-p' option requires parameter.\n");
560      }
561      if((path_filter = strdup(argv[argi])) == NULL)
562        bailOut(EX_OSERR, "ERROR: Memory allocation problem.\n");
563
564      path_filter_enabled = true;
565    }
566    else if (strcmp("-t", argv[argi]) == 0)
567    {
568      if(++argi >= arge)
569      {
570        usage();
571        bailOut(EX_USAGE, "ERROR: '-t' option requires parameter.\n");
572      }
573      if((type_filter = regfi_type_str2val(argv[argi])) < 0)
574      {
575        fprintf(stderr, "ERROR: Invalid type specified: %s.\n", argv[argi]);
576        bailOut(EX_USAGE, "");
577      }
578      type_filter_enabled = true;
579    }
580    else if (strcmp("-h", argv[argi]) == 0)
581      print_header = true;
582    else if (strcmp("-H", argv[argi]) == 0)
583      print_header = false;
584    else if (strcmp("-s", argv[argi]) == 0)
585      print_security = true;
586    else if (strcmp("-S", argv[argi]) == 0)
587      print_security = false;
588    else if (strcmp("-v", argv[argi]) == 0)
589      print_verbose = true;
590    else
591    {
592      usage();
593      fprintf(stderr, "ERROR: Unrecognized option: %s\n", argv[argi]);
594      bailOut(EX_USAGE, "");
595    }
596  }
597  if((registry_file = strdup(argv[argi])) == NULL)
598    bailOut(EX_OSERR, "ERROR: Memory allocation problem.\n");
599
600  f = regfi_open(registry_file);
601  if(f == NULL)
602  {
603    fprintf(stderr, "ERROR: Couldn't open registry file: %s\n", registry_file);
604    bailOut(EX_NOINPUT, "");
605  }
606
607  iter = regfi_iterator_new(f);
608  if(iter == NULL)
609    bailOut(EX_OSERR, "ERROR: Couldn't create registry iterator.\n");
610
611  if(print_header)
612  {
613    if(print_security)
614      printf("PATH,TYPE,VALUE,MTIME,OWNER,GROUP,SACL,DACL,CLASS\n");
615    else
616      printf("PATH,TYPE,VALUE,MTIME\n");
617  }
618
619  if(path_filter_enabled && path_filter != NULL)
620    path = splitPath(path_filter);
621
622  if(path != NULL)
623  {
624    retr_path_ret = retrievePath(iter, path);
625    freePath(path);
626
627    if(retr_path_ret == 0)
628      fprintf(stderr, "WARNING: specified path not found.\n");
629    else if (retr_path_ret == 2)
630      printKeyTree(iter);
631    else if(retr_path_ret < 0)
632    {
633      fprintf(stderr, "ERROR: retrievePath() returned %d.\n", 
634              retr_path_ret);
635      bailOut(EX_DATAERR,"ERROR: Unknown error occurred in retrieving path.\n");
636    }
637  }
638  else
639    printKeyTree(iter);
640
641  regfi_iterator_free(iter);
642  regfi_close(f);
643
644  return 0;
645}
Note: See TracBrowser for help on using the repository browser.