source: trunk/src/reglookup.c @ 135

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

cleaned up regfi API

started adding debugging infrastructure, but currently broken

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