source: trunk/src/reglookup.c @ 83

Last change on this file since 83 was 83, checked in by tim, 17 years ago

fixed minor memory leak.

  • Property svn:keywords set to Id
File size: 24.0 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-2007 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 2 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 83 2007-01-17 19:11:19Z tim $
22 */
23
24
25#include <stdlib.h>
26#include <stdio.h>
27#include <string.h>
28#include <strings.h>
29#include <time.h>
30#include <iconv.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 */
45const char* key_special_chars = ",\"\\/";
46const char* subfield_special_chars = ",\"\\|";
47const char* common_special_chars = ",\"\\";
48
49iconv_t conv_desc;
50
51
52void bailOut(int code, char* message)
53{
54  fprintf(stderr, message);
55  exit(code);
56}
57
58
59/* Returns a newly malloc()ed string which contains original buffer,
60 * except for non-printable or special characters are quoted in hex
61 * with the syntax '\xQQ' where QQ is the hex ascii value of the quoted
62 * character.  A null terminator is added, since only ascii, not binary,
63 * is returned.
64 */
65static char* quote_buffer(const unsigned char* str, 
66                          unsigned int len, const char* special)
67{
68  unsigned int i, added_len;
69  unsigned int num_written = 0;
70
71  unsigned int buf_len = sizeof(char)*(len+1);
72  char* ret_val = malloc(buf_len);
73  char* tmp_buf;
74
75  if(ret_val == NULL)
76    return NULL;
77
78  for(i=0; i<len; i++)
79  {
80    if(buf_len <= (num_written+5))
81    {
82      /* Expand the buffer by the memory consumption rate seen so far
83       * times the amount of input left to process.  The expansion is bounded
84       * below by a minimum safety increase, and above by the maximum possible
85       * output string length.  This should minimize both the number of
86       * reallocs() and the amount of wasted memory.
87       */
88      added_len = (len-i)*num_written/(i+1);
89      if((buf_len+added_len) > (len*4+1))
90        buf_len = len*4+1;
91      else
92      {
93        if (added_len < 5)
94          buf_len += 5;
95        else
96          buf_len += added_len;
97      }
98
99      tmp_buf = realloc(ret_val, buf_len);
100      if(tmp_buf == NULL)
101      {
102        free(ret_val);
103        return NULL;
104      }
105      ret_val = tmp_buf;
106    }
107   
108    if(str[i] < 32 || str[i] > 126 || strchr(special, str[i]) != NULL)
109    {
110      num_written += snprintf(ret_val + num_written, buf_len - num_written,
111                              "\\x%.2X", str[i]);
112    }
113    else
114      ret_val[num_written++] = str[i];
115  }
116  ret_val[num_written] = '\0';
117
118  return ret_val;
119}
120
121
122/* Returns a newly malloc()ed string which contains original string,
123 * except for non-printable or special characters are quoted in hex
124 * with the syntax '\xQQ' where QQ is the hex ascii value of the quoted
125 * character.
126 */
127static char* quote_string(const char* str, const char* special)
128{
129  unsigned int len;
130
131  if(str == NULL)
132    return NULL;
133
134  len = strlen(str);
135  return quote_buffer((const unsigned char*)str, len, special);
136}
137
138
139/*
140 * Convert from UTF-16LE to ASCII.  Accepts a Unicode buffer, uni, and
141 * it's length, uni_max.  Writes ASCII to the buffer ascii, whose size
142 * is ascii_max.  Writes at most (ascii_max-1) bytes to ascii, and null
143 * terminates the string.  Returns the length of the string stored in
144 * ascii.  On error, returns a negative errno code.
145 */
146static int uni_to_ascii(unsigned char* uni, char* ascii, 
147                        unsigned int uni_max, unsigned int ascii_max)
148{
149  char* inbuf = (char*)uni;
150  char* outbuf = ascii;
151  size_t in_len = (size_t)uni_max;
152  size_t out_len = (size_t)(ascii_max-1);
153  int ret;
154
155  /* Set up conversion descriptor. */
156  conv_desc = iconv_open("US-ASCII", "UTF-16LE");
157
158  ret = iconv(conv_desc, &inbuf, &in_len, &outbuf, &out_len);
159  if(ret == -1)
160  {
161    iconv_close(conv_desc);
162    return -errno;
163  }
164  *outbuf = '\0';
165
166  iconv_close(conv_desc); 
167  return strlen(ascii);
168}
169
170
171/*
172 * Convert a data value to a string for display.  Returns NULL on error,
173 * and the string to display if there is no error, or a non-fatal
174 * error.  On any error (fatal or non-fatal) occurs, (*error_msg) will
175 * be set to a newly allocated string, containing an error message.  If
176 * a memory allocation failure occurs while generating the error
177 * message, both the return value and (*error_msg) will be NULL.  It
178 * is the responsibility of the caller to free both a non-NULL return
179 * value, and a non-NULL (*error_msg).
180 */
181static char* data_to_ascii(unsigned char *datap, uint32 len, uint32 type, 
182                           char** error_msg)
183{
184  char* asciip;
185  char* ascii;
186  unsigned char* cur_str;
187  char* cur_ascii;
188  char* cur_quoted;
189  char* tmp_err;
190  const char* str_type;
191  uint32 i;
192  uint32 cur_str_len;
193  uint32 ascii_max, cur_str_max;
194  uint32 str_rem, cur_str_rem, alen;
195  int ret_err;
196  unsigned short num_nulls;
197
198  *error_msg = NULL;
199
200  switch (type) 
201  {
202  case REG_SZ:
203  case REG_EXPAND_SZ:
204    /* REG_LINK is a symbolic link, stored as a unicode string. */
205  case REG_LINK:
206    ascii_max = sizeof(char)*(len+1);
207    ascii = malloc(ascii_max);
208    if(ascii == NULL)
209      return NULL;
210   
211    /* Sometimes values have binary stored in them.  If the unicode
212     * conversion fails, just quote it raw.
213     */
214    ret_err = uni_to_ascii(datap, ascii, len, ascii_max);
215    if(ret_err < 0)
216    {
217      tmp_err = strerror(-ret_err);
218      str_type = regfi_type_val2str(type);
219      *error_msg = (char*)malloc(65+strlen(str_type)+strlen(tmp_err)+1);
220      if(*error_msg == NULL)
221      {
222        free(ascii);
223        return NULL;
224      }
225      sprintf(*error_msg, "Unicode conversion failed on %s field; "
226               "printing as binary.  Error: %s", str_type, tmp_err);
227     
228      cur_quoted = quote_buffer(datap, len, common_special_chars);
229    }
230    else
231      cur_quoted = quote_string(ascii, common_special_chars);
232    free(ascii);
233    if(cur_quoted == NULL)
234    {
235      *error_msg = (char*)malloc(27+1);
236      if(*error_msg != NULL)
237        strcpy(*error_msg, "Buffer could not be quoted.");
238    }
239    return cur_quoted;
240    break;
241
242  case REG_DWORD:
243    ascii_max = sizeof(char)*(8+2+1);
244    ascii = malloc(ascii_max);
245    if(ascii == NULL)
246      return NULL;
247
248    snprintf(ascii, ascii_max, "0x%.2X%.2X%.2X%.2X", 
249             datap[0], datap[1], datap[2], datap[3]);
250    return ascii;
251    break;
252
253  case REG_DWORD_BE:
254    ascii_max = sizeof(char)*(8+2+1);
255    ascii = malloc(ascii_max);
256    if(ascii == NULL)
257      return NULL;
258
259    snprintf(ascii, ascii_max, "0x%.2X%.2X%.2X%.2X", 
260             datap[3], datap[2], datap[1], datap[0]);
261    return ascii;
262    break;
263
264  case REG_QWORD:
265    ascii_max = sizeof(char)*(16+2+1);
266    ascii = malloc(ascii_max);
267    if(ascii == NULL)
268      return NULL;
269
270    snprintf(ascii, ascii_max, "0x%.2X%.2X%.2X%.2X%.2X%.2X%.2X%.2X",
271             datap[7], datap[6], datap[5], datap[4],
272             datap[3], datap[2], datap[1], datap[0]);
273    return ascii;
274    break;
275   
276
277  /* XXX: this MULTI_SZ parser is pretty inefficient.  Should be
278   *      redone with fewer malloc calls and better string concatenation.
279   */
280  case REG_MULTI_SZ:
281    ascii_max = sizeof(char)*(len*4+1);
282    cur_str_max = sizeof(char)*(len+1);
283    cur_str = malloc(cur_str_max);
284    cur_ascii = malloc(cur_str_max);
285    ascii = malloc(ascii_max);
286    if(ascii == NULL || cur_str == NULL || cur_ascii == NULL)
287      return NULL;
288
289    /* Reads until it reaches 4 consecutive NULLs,
290     * which is two nulls in unicode, or until it reaches len, or until we
291     * run out of buffer.  The latter should never happen, but we shouldn't
292     * trust our file to have the right lengths/delimiters.
293     */
294    asciip = ascii;
295    num_nulls = 0;
296    str_rem = ascii_max;
297    cur_str_rem = cur_str_max;
298    cur_str_len = 0;
299
300    for(i=0; (i < len) && str_rem > 0; i++)
301    {
302      *(cur_str+cur_str_len) = *(datap+i);
303      if(*(cur_str+cur_str_len) == 0)
304        num_nulls++;
305      else
306        num_nulls = 0;
307      cur_str_len++;
308
309      if(num_nulls == 2)
310      {
311        ret_err = uni_to_ascii(cur_str, cur_ascii, cur_str_len-1, cur_str_max);
312        if(ret_err < 0)
313        {
314          /* XXX: should every sub-field error be enumerated? */
315          if(*error_msg == NULL)
316          {
317            tmp_err = strerror(-ret_err);
318            *error_msg = (char*)malloc(90+strlen(tmp_err)+1);
319            if(*error_msg == NULL)
320            {
321              free(cur_str);
322              free(cur_ascii);
323              free(ascii);
324              return NULL;
325            }
326            sprintf(*error_msg, "Unicode conversion failed on at least one "
327                    "MULTI_SZ sub-field; printing as binary.  Error: %s",
328                    tmp_err);
329          }
330          cur_quoted = quote_buffer(cur_str, cur_str_len-1, 
331                                    subfield_special_chars);
332        }
333        else
334          cur_quoted = quote_string(cur_ascii, subfield_special_chars);
335
336        alen = snprintf(asciip, str_rem, "%s", cur_quoted);
337        asciip += alen;
338        str_rem -= alen;
339        free(cur_quoted);
340
341        if(*(datap+i+1) == 0 && *(datap+i+2) == 0)
342          break;
343        else
344        {
345          if(str_rem > 0)
346          {
347            asciip[0] = '|';
348            asciip[1] = '\0';
349            asciip++;
350            str_rem--;
351          }
352          memset(cur_str, 0, cur_str_max);
353          cur_str_len = 0;
354          num_nulls = 0;
355          /* To eliminate leading nulls in subsequent strings. */
356          i++;
357        }
358      }
359    }
360    *asciip = 0;
361    free(cur_str);
362    free(cur_ascii);
363    return ascii;
364    break;
365
366  /* XXX: Dont know what to do with these yet, just print as binary... */
367  default:
368    fprintf(stderr, "WARNING: Unrecognized registry data type (0x%.8X); quoting as binary.\n", type);
369   
370  case REG_NONE:
371  case REG_RESOURCE_LIST:
372  case REG_FULL_RESOURCE_DESCRIPTOR:
373  case REG_RESOURCE_REQUIREMENTS_LIST:
374
375  case REG_BINARY:
376    return quote_buffer(datap, len, common_special_chars);
377    break;
378  }
379
380  return NULL;
381}
382
383
384/* XXX: Each chunk must be unquoted after it is split out.
385 *      Quoting syntax may need to be standardized and pushed into the API
386 *      to deal with this issue and others.
387 */
388char** splitPath(const char* s)
389{
390  char** ret_val;
391  const char* cur = s;
392  char* next = NULL;
393  char* copy;
394  uint32 ret_cur = 0;
395
396  ret_val = (char**)malloc((REGF_MAX_DEPTH+1+1)*sizeof(char**));
397  if (ret_val == NULL)
398    return NULL;
399  ret_val[0] = NULL;
400
401  /* We return a well-formed, 0-length, path even when input is icky. */
402  if (s == NULL)
403    return ret_val;
404 
405  while((next = strchr(cur, '/')) != NULL)
406  {
407    if ((next-cur) > 0)
408    {
409      copy = (char*)malloc((next-cur+1)*sizeof(char));
410      if(copy == NULL)
411        bailOut(2, "ERROR: Memory allocation problem.\n");
412         
413      memcpy(copy, cur, next-cur);
414      copy[next-cur] = '\0';
415      ret_val[ret_cur++] = copy;
416      if(ret_cur < (REGF_MAX_DEPTH+1+1))
417        ret_val[ret_cur] = NULL;
418      else
419        bailOut(2, "ERROR: Registry maximum depth exceeded.\n");
420    }
421    cur = next+1;
422  }
423
424  /* Grab last element, if path doesn't end in '/'. */
425  if(strlen(cur) > 0)
426  {
427    copy = strdup(cur);
428    ret_val[ret_cur++] = copy;
429    if(ret_cur < (REGF_MAX_DEPTH+1+1))
430      ret_val[ret_cur] = NULL;
431    else
432      bailOut(2, "ERROR: Registry maximum depth exceeded.\n");
433  }
434
435  return ret_val;
436}
437
438
439void freePath(char** path)
440{
441  uint32 i;
442
443  if(path == NULL)
444    return;
445
446  for(i=0; path[i] != NULL; i++)
447    free(path[i]);
448
449  free(path);
450}
451
452
453/* Returns a quoted path from an iterator's stack */
454/* XXX: Some way should be found to integrate this into regfi's API
455 *      The problem is that the escaping is sorta reglookup-specific.
456 */
457char* iter2Path(REGFI_ITERATOR* i)
458{
459  const REGFI_ITER_POSITION* cur;
460  uint32 buf_left = 127;
461  uint32 buf_len = buf_left+1;
462  uint32 name_len = 0;
463  uint32 grow_amt;
464  char* buf;
465  char* new_buf;
466  char* name;
467  const char* cur_name;
468  void_stack_iterator* iter;
469 
470  buf = (char*)malloc((buf_len)*sizeof(char));
471  if (buf == NULL)
472    return NULL;
473  buf[0] = '\0';
474
475  iter = void_stack_iterator_new(i->key_positions);
476  if (iter == NULL)
477  {
478    free(buf);
479    return NULL;
480  }
481
482  /* skip root element */
483  if(void_stack_size(i->key_positions) < 1)
484  {
485    buf[0] = '/';
486    buf[1] = '\0';
487    return buf;
488  }
489  cur = void_stack_iterator_next(iter);
490
491  do
492  {
493    cur = void_stack_iterator_next(iter);
494    if (cur == NULL)
495      cur_name = i->cur_key->keyname;
496    else
497      cur_name = cur->nk->keyname;
498
499    buf[buf_len-buf_left-1] = '/';
500    buf_left -= 1;
501    name = quote_string(cur_name, key_special_chars);
502    name_len = strlen(name);
503    if(name_len+1 > buf_left)
504    {
505      grow_amt = (uint32)(buf_len/2);
506      buf_len += name_len+1+grow_amt-buf_left;
507      if((new_buf = realloc(buf, buf_len)) == NULL)
508      {
509        free(buf);
510        free(iter);
511        return NULL;
512      }
513      buf = new_buf;
514      buf_left = grow_amt + name_len + 1;
515    }
516    strncpy(buf+(buf_len-buf_left-1), name, name_len);
517    buf_left -= name_len;
518    buf[buf_len-buf_left-1] = '\0';
519    free(name);
520  } while(cur != NULL);
521
522  return buf;
523}
524
525
526void printValue(REGF_VK_REC* vk, char* prefix)
527{
528  char* quoted_value = NULL;
529  char* quoted_name = NULL;
530  char* conv_error = NULL;
531  const char* str_type = NULL;
532  uint32 size;
533  uint8 tmp_buf[4];
534
535  /* Thanks Microsoft for making this process so straight-forward!!! */
536  size = (vk->data_size & ~VK_DATA_IN_OFFSET);
537  if(vk->data_size & VK_DATA_IN_OFFSET)
538  {
539    tmp_buf[0] = (uint8)((vk->data_off >> 3) & 0xFF);
540    tmp_buf[1] = (uint8)((vk->data_off >> 2) & 0xFF);
541    tmp_buf[2] = (uint8)((vk->data_off >> 1) & 0xFF);
542    tmp_buf[3] = (uint8)(vk->data_off & 0xFF);
543    if(size > 4)
544      /* XXX: should we kick out a warning here?  If it is in the
545       *      offset and longer than four, file could be corrupt
546       *      or malicious... */
547      size = 4;
548    quoted_value = data_to_ascii(tmp_buf, 4, vk->type, &conv_error);
549  }
550  else
551  {
552    /* Microsoft's documentation indicates that "available memory" is
553     * the limit on value sizes.  Annoying.  We limit it to 1M which
554     * should rarely be exceeded, unless the file is corrupt or
555     * malicious. For more info, see:
556     *   http://msdn2.microsoft.com/en-us/library/ms724872.aspx
557     */
558    if(size > VK_MAX_DATA_LENGTH)
559    {
560      fprintf(stderr, "WARNING: value data size %d larger than "
561              "%d, truncating...\n", size, VK_MAX_DATA_LENGTH);
562      size = VK_MAX_DATA_LENGTH;
563    }
564
565    quoted_value = data_to_ascii(vk->data, vk->data_size, 
566                                 vk->type, &conv_error);
567  }
568 
569  /* XXX: Sometimes value names can be NULL in registry.  Need to
570   *      figure out why and when, and generate the appropriate output
571   *      for that condition.
572   */
573  quoted_name = quote_string(vk->valuename, common_special_chars);
574
575  if(quoted_value == NULL)
576  {
577    if(conv_error == NULL)
578      fprintf(stderr, "WARNING: Could not quote value for '%s/%s'.  "
579              "Memory allocation failure likely.\n", prefix, quoted_name);
580    else
581      fprintf(stderr, "WARNING: Could not quote value for '%s/%s'.  "
582              "Returned error: %s\n", prefix, quoted_name, conv_error);
583  }
584  /* XXX: should these always be printed? */
585  else if(conv_error != NULL && print_verbose)
586      fprintf(stderr, "VERBOSE: While quoting value for '%s/%s', "
587              "warning returned: %s\n", prefix, quoted_name, conv_error);
588
589  str_type = regfi_type_val2str(vk->type);
590  if(print_security)
591  {
592    if(str_type == NULL)
593      printf("%s/%s,0x%.8X,%s,,,,,\n", prefix, quoted_name,
594             vk->type, quoted_value);
595    else
596      printf("%s/%s,%s,%s,,,,,\n", prefix, quoted_name,
597             str_type, quoted_value);
598  }
599  else
600  {
601    if(str_type == NULL)
602      printf("%s/%s,0x%.8X,%s,\n", prefix, quoted_name,
603             vk->type, quoted_value);
604    else
605      printf("%s/%s,%s,%s,\n", prefix, quoted_name,
606             str_type, quoted_value);
607  }
608
609  if(quoted_value != NULL)
610    free(quoted_value);
611  if(quoted_name != NULL)
612    free(quoted_name);
613  if(conv_error != NULL)
614    free(conv_error);
615}
616
617
618void printValueList(REGFI_ITERATOR* i, char* prefix)
619{
620  REGF_VK_REC* value;
621
622  value = regfi_iterator_first_value(i);
623  while(value != NULL)
624  {
625    if(!type_filter_enabled || (value->type == type_filter))
626      printValue(value, prefix);
627    value = regfi_iterator_next_value(i);
628  }
629}
630
631
632void printKey(REGF_NK_REC* k, char* full_path)
633{
634  static char empty_str[1] = "";
635  char* owner = NULL;
636  char* group = NULL;
637  char* sacl = NULL;
638  char* dacl = NULL;
639  char mtime[20];
640  time_t tmp_time[1];
641  struct tm* tmp_time_s = NULL;
642
643  *tmp_time = nt_time_to_unix(&k->mtime);
644  tmp_time_s = gmtime(tmp_time);
645  strftime(mtime, sizeof(mtime), "%Y-%m-%d %H:%M:%S", tmp_time_s);
646
647  if(print_security)
648  {
649    owner = regfi_get_owner(k->sec_desc->sec_desc);
650    group = regfi_get_group(k->sec_desc->sec_desc);
651    sacl = regfi_get_sacl(k->sec_desc->sec_desc);
652    dacl = regfi_get_dacl(k->sec_desc->sec_desc);
653    if(owner == NULL)
654      owner = empty_str;
655    if(group == NULL)
656      group = empty_str;
657    if(sacl == NULL)
658      sacl = empty_str;
659    if(dacl == NULL)
660      dacl = empty_str;
661
662    printf("%s,KEY,,%s,%s,%s,%s,%s\n", full_path, mtime, 
663           owner, group, sacl, dacl);
664
665    if(owner != empty_str)
666      free(owner);
667    if(group != empty_str)
668      free(group);
669    if(sacl != empty_str)
670      free(sacl);
671    if(dacl != empty_str)
672      free(dacl);
673  }
674  else
675    printf("%s,KEY,,%s\n", full_path, mtime);
676}
677
678
679void printKeyTree(REGFI_ITERATOR* iter)
680{
681  REGF_NK_REC* root = NULL;
682  REGF_NK_REC* cur = NULL;
683  REGF_NK_REC* sub = NULL;
684  char* path = NULL;
685  int key_type = regfi_type_str2val("KEY");
686  bool print_this = true;
687
688  root = cur = regfi_iterator_cur_key(iter);
689  sub = regfi_iterator_first_subkey(iter);
690 
691  if(root == NULL)
692    bailOut(3, "ERROR: root cannot be NULL.\n");
693 
694  do
695  {
696    if(print_this)
697    {
698      path = iter2Path(iter);
699      if(path == NULL)
700        bailOut(2, "ERROR: Could not construct iterator's path.\n");
701     
702      if(!type_filter_enabled || (key_type == type_filter))
703        printKey(cur, path);
704      if(!type_filter_enabled || (key_type != type_filter))
705        printValueList(iter, path);
706     
707      free(path);
708    }
709   
710    if(sub == NULL)
711    {
712      if(cur != root)
713      {
714        /* We're done with this sub-tree, going up and hitting other branches. */
715        if(!regfi_iterator_up(iter))
716          bailOut(3, "ERROR: could not traverse iterator upward.\n");
717       
718        cur = regfi_iterator_cur_key(iter);
719        if(cur == NULL)
720          bailOut(3, "ERROR: unexpected NULL for key.\n");
721       
722        sub = regfi_iterator_next_subkey(iter);
723      }
724      print_this = false;
725    }
726    else
727    { /* We have unexplored sub-keys. 
728       * Let's move down and print this first sub-tree out.
729       */
730      if(!regfi_iterator_down(iter))
731        bailOut(3, "ERROR: could not traverse iterator downward.\n");
732
733      cur = sub;
734      sub = regfi_iterator_first_subkey(iter);
735      print_this = true;
736    }
737  } while(!((cur == root) && (sub == NULL)));
738
739  if(print_verbose)
740    fprintf(stderr, "VERBOSE: Finished printing key tree.\n");
741}
742
743
744/*
745 * Returns 0 if path was not found.
746 * Returns 1 if path was found as value.
747 * Returns 2 if path was found as key.
748 * Returns less than 0 on other error.
749 */
750int retrievePath(REGFI_ITERATOR* iter, char** path)
751{
752  REGF_VK_REC* value;
753  char* tmp_path_joined;
754  const char** tmp_path;
755  uint32 i;
756 
757  if(path == NULL)
758    return -1;
759
760  /* One extra for any value at the end, and one more for NULL */
761  tmp_path = (const char**)malloc(sizeof(const char**)*(REGF_MAX_DEPTH+1+1));
762  if(tmp_path == NULL)
763    return -2;
764
765  /* Strip any potential value name at end of path */
766  for(i=0; 
767      (path[i] != NULL) && (path[i+1] != NULL) 
768        && (i < REGF_MAX_DEPTH+1+1);
769      i++)
770    tmp_path[i] = path[i];
771
772  tmp_path[i] = NULL;
773
774  if(print_verbose)
775    fprintf(stderr, "VERBOSE: Attempting to retrieve specified path: %s\n",
776            path_filter);
777
778  /* Special check for '/' path filter */
779  if(path[0] == NULL)
780  {
781    if(print_verbose)
782      fprintf(stderr, "VERBOSE: Found final path element as root key.\n");
783    return 2;
784  }
785
786  if(!regfi_iterator_walk_path(iter, tmp_path))
787  {
788    free(tmp_path);
789    return 0;
790  }
791
792  if(regfi_iterator_find_value(iter, path[i]))
793  {
794    if(print_verbose)
795      fprintf(stderr, "VERBOSE: Found final path element as value.\n");
796
797    value = regfi_iterator_cur_value(iter);
798    tmp_path_joined = iter2Path(iter);
799
800    if((value == NULL) || (tmp_path_joined == NULL))
801      bailOut(2, "ERROR: Unexpected error before printValue.\n");
802
803    printValue(value, tmp_path_joined);
804
805    free(tmp_path);
806    free(tmp_path_joined);
807    return 1;
808  }
809  else if(regfi_iterator_find_subkey(iter, path[i]))
810  {
811    if(print_verbose)
812      fprintf(stderr, "VERBOSE: Found final path element as key.\n");
813
814    if(!regfi_iterator_down(iter))
815      bailOut(2, "ERROR: Unexpected error on traversing path filter key.\n");
816
817    return 2;
818  }
819
820  if(print_verbose)
821    fprintf(stderr, "VERBOSE: Could not find last element of path.\n");
822
823  return 0;
824}
825
826
827static void usage(void)
828{
829  fprintf(stderr, "Usage: reglookup [-v] [-s]"
830          " [-p <PATH_FILTER>] [-t <TYPE_FILTER>]"
831          " <REGISTRY_FILE>\n");
832  fprintf(stderr, "Version: 0.3.0\n");
833  fprintf(stderr, "Options:\n");
834  fprintf(stderr, "\t-v\t sets verbose mode.\n");
835  fprintf(stderr, "\t-h\t enables header row. (default)\n");
836  fprintf(stderr, "\t-H\t disables header row.\n");
837  fprintf(stderr, "\t-s\t enables security descriptor output.\n");
838  fprintf(stderr, "\t-S\t disables security descriptor output. (default)\n");
839  fprintf(stderr, "\t-p\t restrict output to elements below this path.\n");
840  fprintf(stderr, "\t-t\t restrict results to this specific data type.\n");
841  fprintf(stderr, "\n");
842}
843
844
845int main(int argc, char** argv)
846{
847  char** path = NULL;
848  REGF_FILE* f;
849  REGFI_ITERATOR* iter;
850  int retr_path_ret;
851  uint32 argi, arge;
852
853  /* Process command line arguments */
854  if(argc < 2)
855  {
856    usage();
857    bailOut(1, "ERROR: Requires at least one argument.\n");
858  }
859 
860  arge = argc-1;
861  for(argi = 1; argi < arge; argi++)
862  {
863    if (strcmp("-p", argv[argi]) == 0)
864    {
865      if(++argi >= arge)
866      {
867        usage();
868        bailOut(1, "ERROR: '-p' option requires parameter.\n");
869      }
870      if((path_filter = strdup(argv[argi])) == NULL)
871        bailOut(2, "ERROR: Memory allocation problem.\n");
872
873      path_filter_enabled = true;
874    }
875    else if (strcmp("-t", argv[argi]) == 0)
876    {
877      if(++argi >= arge)
878      {
879        usage();
880        bailOut(1, "ERROR: '-t' option requires parameter.\n");
881      }
882      if((type_filter = regfi_type_str2val(argv[argi])) < 0)
883      {
884        fprintf(stderr, "ERROR: Invalid type specified: %s.\n", argv[argi]);
885        bailOut(1, "");
886      }
887      type_filter_enabled = true;
888    }
889    else if (strcmp("-h", argv[argi]) == 0)
890      print_header = true;
891    else if (strcmp("-H", argv[argi]) == 0)
892      print_header = false;
893    else if (strcmp("-s", argv[argi]) == 0)
894      print_security = true;
895    else if (strcmp("-S", argv[argi]) == 0)
896      print_security = false;
897    else if (strcmp("-v", argv[argi]) == 0)
898      print_verbose = true;
899    else
900    {
901      usage();
902      fprintf(stderr, "ERROR: Unrecognized option: %s\n", argv[argi]);
903      bailOut(1, "");
904    }
905  }
906  if((registry_file = strdup(argv[argi])) == NULL)
907    bailOut(2, "ERROR: Memory allocation problem.\n");
908
909  f = regfi_open(registry_file);
910  if(f == NULL)
911  {
912    fprintf(stderr, "ERROR: Couldn't open registry file: %s\n", registry_file);
913    bailOut(3, "");
914  }
915
916  iter = regfi_iterator_new(f);
917  if(iter == NULL)
918    bailOut(3, "ERROR: Couldn't create registry iterator.\n");
919
920  if(print_header)
921  {
922    if(print_security)
923      printf("PATH,TYPE,VALUE,MTIME,OWNER,GROUP,SACL,DACL\n");
924    else
925      printf("PATH,TYPE,VALUE,MTIME\n");
926  }
927
928  if(path_filter_enabled && path_filter != NULL)
929    path = splitPath(path_filter);
930
931  if(path != NULL)
932  {
933    retr_path_ret = retrievePath(iter, path);
934    freePath(path);
935
936    if(retr_path_ret == 0)
937      fprintf(stderr, "WARNING: specified path not found.\n");
938    else if (retr_path_ret == 2)
939      printKeyTree(iter);
940    else if(retr_path_ret != 0)
941      bailOut(4, "ERROR: Unknown error occurred in retrieving path.\n");
942  }
943  else
944    printKeyTree(iter);
945
946  regfi_iterator_free(iter);
947  regfi_close(f);
948
949  return 0;
950}
Note: See TracBrowser for help on using the repository browser.