source: trunk/src/reglookup.c @ 147

Last change on this file since 147 was 147, checked in by tim, 15 years ago

added talloc library

incorporated talloc into winsec and lru_cache modules

introduced talloc into SK caching system

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