source: trunk/lib/regfi.c @ 169

Last change on this file since 169 was 169, checked in by tim, 14 years ago

filled in additional, minimal documentation

  • Property svn:keywords set to Id
File size: 89.4 KB
Line 
1/*
2 * Copyright (C) 2005-2010 Timothy D. Morgan
3 * Copyright (C) 2005 Gerald (Jerry) Carter
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; version 3 of the License.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, write to the Free Software
16 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17 *
18 * $Id: regfi.c 169 2010-03-03 19:24:58Z tim $
19 */
20
21/**
22 * @file
23 *
24 * Windows NT (and later) read-only registry library
25 *
26 * See @ref regfi.h for more information.
27 *
28 * Branched from Samba project Subversion repository, version #7470:
29 *   http://viewcvs.samba.org/cgi-bin/viewcvs.cgi/trunk/source/registry/regfio.c?rev=7470&view=auto
30 *
31 * Since then, it has been heavily rewritten, simplified, and improved.
32 */
33
34#include "regfi.h"
35
36
37/* Registry types mapping */
38const unsigned int regfi_num_reg_types = 12;
39static const char* regfi_type_names[] =
40  {"NONE", "SZ", "EXPAND_SZ", "BINARY", "DWORD", "DWORD_BE", "LINK",
41   "MULTI_SZ", "RSRC_LIST", "RSRC_DESC", "RSRC_REQ_LIST", "QWORD"};
42
43const char* regfi_encoding_names[] =
44  {"US-ASCII//TRANSLIT", "UTF-8//TRANSLIT", "UTF-16LE//TRANSLIT"};
45
46
47/******************************************************************************
48 ******************************************************************************/
49void regfi_add_message(REGFI_FILE* file, uint16_t msg_type, const char* fmt, ...)
50{
51  /* XXX: This function is not particularly efficient,
52   *      but then it is mostly used during errors.
53   */
54  uint32_t buf_size, buf_used;
55  char* new_msg;
56  va_list args;
57
58  if((file->msg_mask & msg_type) != 0)
59  {
60    if(file->last_message == NULL)
61      buf_used = 0;
62    else
63      buf_used = strlen(file->last_message);
64   
65    buf_size = buf_used+strlen(fmt)+160;
66    new_msg = realloc(file->last_message, buf_size);
67    if(new_msg == NULL)
68      /* XXX: should we report this? */
69      return;
70
71    switch (msg_type)
72    {
73    case REGFI_MSG_INFO:
74      strcpy(new_msg+buf_used, "INFO: ");
75      buf_used += 6;
76      break;
77    case REGFI_MSG_WARN:
78      strcpy(new_msg+buf_used, "WARN: ");
79      buf_used += 6;
80      break;
81    case REGFI_MSG_ERROR:
82      strcpy(new_msg+buf_used, "ERROR: ");
83      buf_used += 7;
84      break;
85    }
86
87    va_start(args, fmt);
88    vsnprintf(new_msg+buf_used, buf_size-buf_used, fmt, args);
89    va_end(args);
90    strncat(new_msg, "\n", buf_size-1);
91   
92    file->last_message = new_msg;
93  }
94}
95
96
97/******************************************************************************
98 ******************************************************************************/
99char* regfi_get_messages(REGFI_FILE* file)
100{
101  char* ret_val = file->last_message;
102  file->last_message = NULL;
103
104  return ret_val;
105}
106
107
108void regfi_set_message_mask(REGFI_FILE* file, uint16_t mask)
109{
110  file->msg_mask = mask;
111}
112
113
114/******************************************************************************
115 * Returns NULL for an invalid e
116 *****************************************************************************/
117static const char* regfi_encoding_int2str(REGFI_ENCODING e)
118{
119  if(e < REGFI_NUM_ENCODINGS)
120    return regfi_encoding_names[e];
121
122  return NULL;
123}
124
125
126/******************************************************************************
127 * Returns NULL for an invalid val
128 *****************************************************************************/
129const char* regfi_type_val2str(unsigned int val)
130{
131  if(val == REG_KEY)
132    return "KEY";
133 
134  if(val >= regfi_num_reg_types)
135    return NULL;
136 
137  return regfi_type_names[val];
138}
139
140
141/******************************************************************************
142 * Returns -1 on error
143 *****************************************************************************/
144int regfi_type_str2val(const char* str)
145{
146  int i;
147
148  if(strcmp("KEY", str) == 0)
149    return REG_KEY;
150
151  for(i=0; i < regfi_num_reg_types; i++)
152    if (strcmp(regfi_type_names[i], str) == 0) 
153      return i;
154
155  if(strcmp("DWORD_LE", str) == 0)
156    return REG_DWORD_LE;
157
158  return -1;
159}
160
161
162/* Security descriptor formatting functions  */
163
164const char* regfi_ace_type2str(uint8_t type)
165{
166  static const char* map[7] 
167    = {"ALLOW", "DENY", "AUDIT", "ALARM", 
168       "ALLOW CPD", "OBJ ALLOW", "OBJ DENY"};
169  if(type < 7)
170    return map[type];
171  else
172    /* XXX: would be nice to return the unknown integer value. 
173     *      However, as it is a const string, it can't be free()ed later on,
174     *      so that would need to change.
175     */
176    return "UNKNOWN";
177}
178
179
180/* XXX: need a better reference on the meaning of each flag. */
181/* For more info, see:
182 *   http://msdn2.microsoft.com/en-us/library/aa772242.aspx
183 */
184char* regfi_ace_flags2str(uint8_t flags)
185{
186  static const char* flag_map[32] = 
187    { "OI", /* Object Inherit */
188      "CI", /* Container Inherit */
189      "NP", /* Non-Propagate */
190      "IO", /* Inherit Only */
191      "IA", /* Inherited ACE */
192      NULL,
193      NULL,
194      NULL,
195    };
196
197  char* ret_val = malloc(35*sizeof(char));
198  char* fo = ret_val;
199  uint32_t i;
200  uint8_t f;
201
202  if(ret_val == NULL)
203    return NULL;
204
205  fo[0] = '\0';
206  if (!flags)
207    return ret_val;
208
209  for(i=0; i < 8; i++)
210  {
211    f = (1<<i);
212    if((flags & f) && (flag_map[i] != NULL))
213    {
214      strcpy(fo, flag_map[i]);
215      fo += strlen(flag_map[i]);
216      *(fo++) = ' ';
217      flags ^= f;
218    }
219  }
220 
221  /* Any remaining unknown flags are added at the end in hex. */
222  if(flags != 0)
223    sprintf(fo, "0x%.2X ", flags);
224
225  /* Chop off the last space if we've written anything to ret_val */
226  if(fo != ret_val)
227    fo[-1] = '\0';
228
229  return ret_val;
230}
231
232
233char* regfi_ace_perms2str(uint32_t perms)
234{
235  uint32_t i, p;
236  /* This is more than is needed by a fair margin. */
237  char* ret_val = malloc(350*sizeof(char));
238  char* r = ret_val;
239
240  /* Each represents one of 32 permissions bits.  NULL is for undefined/reserved bits.
241   * For more information, see:
242   *   http://msdn2.microsoft.com/en-gb/library/aa374892.aspx
243   *   http://msdn2.microsoft.com/en-gb/library/ms724878.aspx
244   */
245  static const char* perm_map[32] = 
246    {/* object-specific permissions (registry keys, in this case) */
247      "QRY_VAL",       /* KEY_QUERY_VALUE */
248      "SET_VAL",       /* KEY_SET_VALUE */
249      "CREATE_KEY",    /* KEY_CREATE_SUB_KEY */
250      "ENUM_KEYS",     /* KEY_ENUMERATE_SUB_KEYS */
251      "NOTIFY",        /* KEY_NOTIFY */
252      "CREATE_LNK",    /* KEY_CREATE_LINK - Reserved for system use. */
253      NULL,
254      NULL,
255      "WOW64_64",      /* KEY_WOW64_64KEY */
256      "WOW64_32",      /* KEY_WOW64_32KEY */
257      NULL,
258      NULL,
259      NULL,
260      NULL,
261      NULL,
262      NULL,
263      /* standard access rights */
264      "DELETE",        /* DELETE */
265      "R_CONT",        /* READ_CONTROL */
266      "W_DAC",         /* WRITE_DAC */
267      "W_OWNER",       /* WRITE_OWNER */
268      "SYNC",          /* SYNCHRONIZE - Shouldn't be set in registries */
269      NULL,
270      NULL,
271      NULL,
272      /* other generic */
273      "SYS_SEC",       /* ACCESS_SYSTEM_SECURITY */
274      "MAX_ALLWD",     /* MAXIMUM_ALLOWED */
275      NULL,
276      NULL,
277      "GEN_A",         /* GENERIC_ALL */
278      "GEN_X",         /* GENERIC_EXECUTE */
279      "GEN_W",         /* GENERIC_WRITE */
280      "GEN_R",         /* GENERIC_READ */
281    };
282
283
284  if(ret_val == NULL)
285    return NULL;
286
287  r[0] = '\0';
288  for(i=0; i < 32; i++)
289  {
290    p = (1<<i);
291    if((perms & p) && (perm_map[i] != NULL))
292    {
293      strcpy(r, perm_map[i]);
294      r += strlen(perm_map[i]);
295      *(r++) = ' ';
296      perms ^= p;
297    }
298  }
299 
300  /* Any remaining unknown permission bits are added at the end in hex. */
301  if(perms != 0)
302    sprintf(r, "0x%.8X ", perms);
303
304  /* Chop off the last space if we've written anything to ret_val */
305  if(r != ret_val)
306    r[-1] = '\0';
307
308  return ret_val;
309}
310
311
312char* regfi_sid2str(WINSEC_DOM_SID* sid)
313{
314  uint32_t i, size = WINSEC_MAX_SUBAUTHS*11 + 24;
315  uint32_t left = size;
316  uint8_t comps = sid->num_auths;
317  char* ret_val = malloc(size);
318 
319  if(ret_val == NULL)
320    return NULL;
321
322  if(comps > WINSEC_MAX_SUBAUTHS)
323    comps = WINSEC_MAX_SUBAUTHS;
324
325  left -= sprintf(ret_val, "S-%u-%u", sid->sid_rev_num, sid->id_auth[5]);
326
327  for (i = 0; i < comps; i++) 
328    left -= snprintf(ret_val+(size-left), left, "-%u", sid->sub_auths[i]);
329
330  return ret_val;
331}
332
333
334char* regfi_get_acl(WINSEC_ACL* acl)
335{
336  uint32_t i, extra, size = 0;
337  const char* type_str;
338  char* flags_str;
339  char* perms_str;
340  char* sid_str;
341  char* ace_delim = "";
342  char* ret_val = NULL;
343  char* tmp_val = NULL;
344  bool failed = false;
345  char field_delim = ':';
346
347  for (i = 0; i < acl->num_aces && !failed; i++)
348  {
349    sid_str = regfi_sid2str(acl->aces[i]->trustee);
350    type_str = regfi_ace_type2str(acl->aces[i]->type);
351    perms_str = regfi_ace_perms2str(acl->aces[i]->access_mask);
352    flags_str = regfi_ace_flags2str(acl->aces[i]->flags);
353   
354    if(flags_str != NULL && perms_str != NULL 
355       && type_str != NULL && sid_str != NULL)
356    {
357      /* XXX: this is slow */
358      extra = strlen(sid_str) + strlen(type_str) 
359        + strlen(perms_str) + strlen(flags_str) + 5;
360      tmp_val = realloc(ret_val, size+extra);
361
362      if(tmp_val == NULL)
363      {
364        free(ret_val);
365        ret_val = NULL;
366        failed = true;
367      }
368      else
369      {
370        ret_val = tmp_val;
371        size += sprintf(ret_val+size, "%s%s%c%s%c%s%c%s",
372                        ace_delim,sid_str,
373                        field_delim,type_str,
374                        field_delim,perms_str,
375                        field_delim,flags_str);
376        ace_delim = "|";
377      }
378    }
379    else
380      failed = true;
381
382    if(sid_str != NULL)
383      free(sid_str);
384    if(sid_str != NULL)
385      free(perms_str);
386    if(sid_str != NULL)
387      free(flags_str);
388  }
389
390  return ret_val;
391}
392
393
394char* regfi_get_sacl(WINSEC_DESC *sec_desc)
395{
396  if (sec_desc->sacl)
397    return regfi_get_acl(sec_desc->sacl);
398  else
399    return NULL;
400}
401
402
403char* regfi_get_dacl(WINSEC_DESC *sec_desc)
404{
405  if (sec_desc->dacl)
406    return regfi_get_acl(sec_desc->dacl);
407  else
408    return NULL;
409}
410
411
412char* regfi_get_owner(WINSEC_DESC *sec_desc)
413{
414  return regfi_sid2str(sec_desc->owner_sid);
415}
416
417
418char* regfi_get_group(WINSEC_DESC *sec_desc)
419{
420  return regfi_sid2str(sec_desc->grp_sid);
421}
422
423
424/*****************************************************************************
425 * This function is just like read(2), except that it continues to
426 * re-try reading from the file descriptor if EINTR or EAGAIN is received. 
427 * regfi_read will attempt to read length bytes from fd and write them to buf.
428 *
429 * On success, 0 is returned.  Upon failure, an errno code is returned.
430 *
431 * The number of bytes successfully read is returned through the length
432 * parameter by reference.  If both the return value and length parameter are
433 * returned as 0, then EOF was encountered immediately
434 *****************************************************************************/
435uint32_t regfi_read(int fd, uint8_t* buf, uint32_t* length)
436{
437  uint32_t rsize = 0;
438  uint32_t rret = 0;
439
440  do
441  {
442    rret = read(fd, buf + rsize, *length - rsize);
443    if(rret > 0)
444      rsize += rret;
445  }while(*length - rsize > 0 
446         && (rret > 0 || (rret == -1 && (errno == EAGAIN || errno == EINTR))));
447 
448  *length = rsize;
449  if (rret == -1 && errno != EINTR && errno != EAGAIN)
450    return errno;
451
452  return 0;
453}
454
455
456/*****************************************************************************
457 *
458 *****************************************************************************/
459bool regfi_parse_cell(int fd, uint32_t offset, uint8_t* hdr, uint32_t hdr_len,
460                      uint32_t* cell_length, bool* unalloc)
461{
462  uint32_t length;
463  int32_t raw_length;
464  uint8_t tmp[4];
465
466  if(lseek(fd, offset, SEEK_SET) == -1)
467    return false;
468
469  length = 4;
470  if((regfi_read(fd, tmp, &length) != 0) || length != 4)
471    return false;
472  raw_length = IVALS(tmp, 0);
473
474  if(raw_length < 0)
475  {
476    (*cell_length) = raw_length*(-1);
477    (*unalloc) = false;
478  }
479  else
480  {
481    (*cell_length) = raw_length;
482    (*unalloc) = true;
483  }
484
485  if(*cell_length - 4 < hdr_len)
486    return false;
487
488  if(hdr_len > 0)
489  {
490    length = hdr_len;
491    if((regfi_read(fd, hdr, &length) != 0) || length != hdr_len)
492      return false;
493  }
494
495  return true;
496}
497
498
499/******************************************************************************
500 * Given an offset and an hbin, is the offset within that hbin?
501 * The offset is a virtual file offset.
502 ******************************************************************************/
503static bool regfi_offset_in_hbin(const REGFI_HBIN* hbin, uint32_t voffset)
504{
505  if(!hbin)
506    return false;
507
508  if((voffset > hbin->first_hbin_off) 
509     && (voffset < (hbin->first_hbin_off + hbin->block_size)))
510    return true;
511               
512  return false;
513}
514
515
516
517/******************************************************************************
518 * Provide a physical offset and receive the correpsonding HBIN
519 * block for it.  NULL if one doesn't exist.
520 ******************************************************************************/
521const REGFI_HBIN* regfi_lookup_hbin(REGFI_FILE* file, uint32_t offset)
522{
523  return (const REGFI_HBIN*)range_list_find_data(file->hbins, offset);
524}
525
526
527/******************************************************************************
528 * Calculate the largest possible cell size given a physical offset.
529 * Largest size is based on the HBIN the offset is currently a member of.
530 * Returns negative values on error.
531 * (Since cells can only be ~2^31 in size, this works out.)
532 ******************************************************************************/
533int32_t regfi_calc_maxsize(REGFI_FILE* file, uint32_t offset)
534{
535  const REGFI_HBIN* hbin = regfi_lookup_hbin(file, offset);
536  if(hbin == NULL)
537    return -1;
538
539  return (hbin->block_size + hbin->file_off) - offset;
540}
541
542
543/******************************************************************************
544 ******************************************************************************/
545REGFI_SUBKEY_LIST* regfi_load_subkeylist(REGFI_FILE* file, uint32_t offset, 
546                                         uint32_t num_keys, uint32_t max_size, 
547                                         bool strict)
548{
549  REGFI_SUBKEY_LIST* ret_val;
550
551  ret_val = regfi_load_subkeylist_aux(file, offset, max_size, strict, 
552                                      REGFI_MAX_SUBKEY_DEPTH);
553  if(ret_val == NULL)
554  {
555    regfi_add_message(file, REGFI_MSG_WARN, "Failed to load subkey list at"
556                      " offset 0x%.8X.", offset);
557    return NULL;
558  }
559
560  if(num_keys != ret_val->num_keys)
561  {
562    /*  Not sure which should be authoritative, the number from the
563     *  NK record, or the number in the subkey list.  Just emit a warning for
564     *  now if they don't match.
565     */
566    regfi_add_message(file, REGFI_MSG_WARN, "Number of subkeys listed in parent"
567                      " (%d) did not match number found in subkey list/tree (%d)"
568                      " while parsing subkey list/tree at offset 0x%.8X.", 
569                      num_keys, ret_val->num_keys, offset);
570  }
571
572  return ret_val;
573}
574
575
576/******************************************************************************
577 ******************************************************************************/
578REGFI_SUBKEY_LIST* regfi_load_subkeylist_aux(REGFI_FILE* file, uint32_t offset, 
579                                             uint32_t max_size, bool strict,
580                                             uint8_t depth_left)
581{
582  REGFI_SUBKEY_LIST* ret_val;
583  REGFI_SUBKEY_LIST** sublists;
584  uint32_t i, num_sublists, off;
585  int32_t sublist_maxsize;
586
587  if(depth_left == 0)
588  {
589    regfi_add_message(file, REGFI_MSG_WARN, "Maximum depth reached"
590                      " while parsing subkey list/tree at offset 0x%.8X.", 
591                      offset);
592    return NULL;
593  }
594
595  ret_val = regfi_parse_subkeylist(file, offset, max_size, strict);
596  if(ret_val == NULL)
597    return NULL;
598
599  if(ret_val->recursive_type)
600  {
601    num_sublists = ret_val->num_children;
602    sublists = (REGFI_SUBKEY_LIST**)malloc(num_sublists
603                                           * sizeof(REGFI_SUBKEY_LIST*));
604    for(i=0; i < num_sublists; i++)
605    {
606      off = ret_val->elements[i].offset + REGFI_REGF_SIZE;
607
608      sublist_maxsize = regfi_calc_maxsize(file, off);
609      if(sublist_maxsize < 0)
610        sublists[i] = NULL;
611      else
612        sublists[i] = regfi_load_subkeylist_aux(file, off, sublist_maxsize, 
613                                                strict, depth_left-1);
614    }
615    talloc_free(ret_val);
616
617    return regfi_merge_subkeylists(num_sublists, sublists, strict);
618  }
619
620  return ret_val;
621}
622
623
624/******************************************************************************
625 ******************************************************************************/
626REGFI_SUBKEY_LIST* regfi_parse_subkeylist(REGFI_FILE* file, uint32_t offset, 
627                                          uint32_t max_size, bool strict)
628{
629  REGFI_SUBKEY_LIST* ret_val;
630  uint32_t i, cell_length, length, elem_size, read_len;
631  uint8_t* elements = NULL;
632  uint8_t buf[REGFI_SUBKEY_LIST_MIN_LEN];
633  bool unalloc;
634  bool recursive_type;
635
636  if(!regfi_parse_cell(file->fd, offset, buf, REGFI_SUBKEY_LIST_MIN_LEN, 
637                       &cell_length, &unalloc))
638  {
639    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell while "
640                      "parsing subkey-list at offset 0x%.8X.", offset);
641    return NULL;
642  }
643
644  if(cell_length > max_size)
645  {
646    regfi_add_message(file, REGFI_MSG_WARN, "Cell size longer than max_size"
647                      " while parsing subkey-list at offset 0x%.8X.", offset);
648    if(strict)
649      return NULL;
650    cell_length = max_size & 0xFFFFFFF8;
651  }
652
653  recursive_type = false;
654  if(buf[0] == 'r' && buf[1] == 'i')
655  {
656    recursive_type = true;
657    elem_size = sizeof(uint32_t);
658  }
659  else if(buf[0] == 'l' && buf[1] == 'i')
660    elem_size = sizeof(uint32_t);
661  else if((buf[0] == 'l') && (buf[1] == 'f' || buf[1] == 'h'))
662    elem_size = sizeof(REGFI_SUBKEY_LIST_ELEM);
663  else
664  {
665    regfi_add_message(file, REGFI_MSG_ERROR, "Unknown magic number"
666                      " (0x%.2X, 0x%.2X) encountered while parsing"
667                      " subkey-list at offset 0x%.8X.", buf[0], buf[1], offset);
668    return NULL;
669  }
670
671  ret_val = talloc(NULL, REGFI_SUBKEY_LIST);
672  if(ret_val == NULL)
673    return NULL;
674
675  ret_val->offset = offset;
676  ret_val->cell_size = cell_length;
677  ret_val->magic[0] = buf[0];
678  ret_val->magic[1] = buf[1];
679  ret_val->recursive_type = recursive_type;
680  ret_val->num_children = SVAL(buf, 0x2);
681
682  if(!recursive_type)
683    ret_val->num_keys = ret_val->num_children;
684
685  length = elem_size*ret_val->num_children;
686  if(cell_length - REGFI_SUBKEY_LIST_MIN_LEN - sizeof(uint32_t) < length)
687  {
688    regfi_add_message(file, REGFI_MSG_WARN, "Number of elements too large for"
689                      " cell while parsing subkey-list at offset 0x%.8X.", 
690                      offset);
691    if(strict)
692      goto fail;
693    length = cell_length - REGFI_SUBKEY_LIST_MIN_LEN - sizeof(uint32_t);
694  }
695
696  ret_val->elements = talloc_array(ret_val, REGFI_SUBKEY_LIST_ELEM, 
697                                   ret_val->num_children);
698  if(ret_val->elements == NULL)
699    goto fail;
700
701  elements = (uint8_t*)malloc(length);
702  if(elements == NULL)
703    goto fail;
704
705  read_len = length;
706  if(regfi_read(file->fd, elements, &read_len) != 0 || read_len != length)
707    goto fail;
708
709  if(elem_size == sizeof(uint32_t))
710  {
711    for (i=0; i < ret_val->num_children; i++)
712    {
713      ret_val->elements[i].offset = IVAL(elements, i*elem_size);
714      ret_val->elements[i].hash = 0;
715    }
716  }
717  else
718  {
719    for (i=0; i < ret_val->num_children; i++)
720    {
721      ret_val->elements[i].offset = IVAL(elements, i*elem_size);
722      ret_val->elements[i].hash = IVAL(elements, i*elem_size+4);
723    }
724  }
725  free(elements);
726
727  return ret_val;
728
729 fail:
730  if(elements != NULL)
731    free(elements);
732  talloc_free(ret_val);
733  return NULL;
734}
735
736
737/*******************************************************************
738 *******************************************************************/
739REGFI_SUBKEY_LIST* regfi_merge_subkeylists(uint16_t num_lists, 
740                                           REGFI_SUBKEY_LIST** lists,
741                                           bool strict)
742{
743  uint32_t i,j,k;
744  REGFI_SUBKEY_LIST* ret_val;
745
746  if(lists == NULL)
747    return NULL;
748  ret_val = talloc(NULL, REGFI_SUBKEY_LIST);
749
750  if(ret_val == NULL)
751    return NULL;
752 
753  /* Obtain total number of elements */
754  ret_val->num_keys = 0;
755  for(i=0; i < num_lists; i++)
756  {
757    if(lists[i] != NULL)
758      ret_val->num_keys += lists[i]->num_children;
759  }
760  ret_val->num_children = ret_val->num_keys;
761
762  if(ret_val->num_keys > 0)
763  {
764    ret_val->elements = talloc_array(ret_val, REGFI_SUBKEY_LIST_ELEM,
765                                     ret_val->num_keys);
766    k=0;
767
768    if(ret_val->elements != NULL)
769    {
770      for(i=0; i < num_lists; i++)
771      {
772        if(lists[i] != NULL)
773        {
774          for(j=0; j < lists[i]->num_keys; j++)
775          {
776            ret_val->elements[k].hash = lists[i]->elements[j].hash;
777            ret_val->elements[k++].offset = lists[i]->elements[j].offset;
778          }
779        }
780      }
781    }
782  }
783 
784  for(i=0; i < num_lists; i++)
785    regfi_subkeylist_free(lists[i]);
786  free(lists);
787
788  return ret_val;
789}
790
791
792/******************************************************************************
793 *
794 ******************************************************************************/
795REGFI_SK_REC* regfi_parse_sk(REGFI_FILE* file, uint32_t offset, uint32_t max_size, 
796                             bool strict)
797{
798  REGFI_SK_REC* ret_val;
799  uint8_t* sec_desc_buf = NULL;
800  uint32_t cell_length, length;
801  uint8_t sk_header[REGFI_SK_MIN_LENGTH];
802  bool unalloc = false;
803
804  if(!regfi_parse_cell(file->fd, offset, sk_header, REGFI_SK_MIN_LENGTH,
805                       &cell_length, &unalloc))
806  {
807    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse SK record cell"
808                      " at offset 0x%.8X.", offset);
809    return NULL;
810  }
811   
812  if(sk_header[0] != 's' || sk_header[1] != 'k')
813  {
814    regfi_add_message(file, REGFI_MSG_WARN, "Magic number mismatch in parsing"
815                      " SK record at offset 0x%.8X.", offset);
816    return NULL;
817  }
818
819  ret_val = talloc(NULL, REGFI_SK_REC);
820  if(ret_val == NULL)
821    return NULL;
822
823  ret_val->offset = offset;
824  /* XXX: Is there a way to be more conservative (shorter) with
825   *      cell length when cell is unallocated?
826   */
827  ret_val->cell_size = cell_length;
828
829  if(ret_val->cell_size > max_size)
830    ret_val->cell_size = max_size & 0xFFFFFFF8;
831  if((ret_val->cell_size < REGFI_SK_MIN_LENGTH) 
832     || (strict && (ret_val->cell_size & 0x00000007) != 0))
833  {
834    regfi_add_message(file, REGFI_MSG_WARN, "Invalid cell size found while"
835                      " parsing SK record at offset 0x%.8X.", offset);
836    goto fail;
837  }
838
839  ret_val->magic[0] = sk_header[0];
840  ret_val->magic[1] = sk_header[1];
841
842  ret_val->unknown_tag = SVAL(sk_header, 0x2);
843  ret_val->prev_sk_off = IVAL(sk_header, 0x4);
844  ret_val->next_sk_off = IVAL(sk_header, 0x8);
845  ret_val->ref_count = IVAL(sk_header, 0xC);
846  ret_val->desc_size = IVAL(sk_header, 0x10);
847
848  if((ret_val->prev_sk_off & 0x00000007) != 0
849     || (ret_val->next_sk_off & 0x00000007) != 0)
850  {
851    regfi_add_message(file, REGFI_MSG_WARN, "SK record's next/previous offsets"
852                      " are not a multiple of 8 while parsing SK record at"
853                      " offset 0x%.8X.", offset);
854    goto fail;
855  }
856
857  if(ret_val->desc_size + REGFI_SK_MIN_LENGTH > ret_val->cell_size)
858  {
859    regfi_add_message(file, REGFI_MSG_WARN, "Security descriptor too large for"
860                      " cell while parsing SK record at offset 0x%.8X.", 
861                      offset);
862    goto fail;
863  }
864
865  sec_desc_buf = (uint8_t*)malloc(ret_val->desc_size);
866  if(sec_desc_buf == NULL)
867    goto fail;
868
869  length = ret_val->desc_size;
870  if(regfi_read(file->fd, sec_desc_buf, &length) != 0 
871     || length != ret_val->desc_size)
872  {
873    regfi_add_message(file, REGFI_MSG_ERROR, "Failed to read security"
874                      " descriptor while parsing SK record at offset 0x%.8X.",
875                      offset);
876    goto fail;
877  }
878
879  if(!(ret_val->sec_desc = winsec_parse_desc(ret_val, sec_desc_buf, 
880                                                   ret_val->desc_size)))
881  {
882    regfi_add_message(file, REGFI_MSG_ERROR, "Failed to parse security"
883                      " descriptor while parsing SK record at offset 0x%.8X.",
884                      offset);
885    goto fail;
886  }
887
888  free(sec_desc_buf);
889  return ret_val;
890
891 fail:
892  if(sec_desc_buf != NULL)
893    free(sec_desc_buf);
894  talloc_free(ret_val);
895  return NULL;
896}
897
898
899REGFI_VALUE_LIST* regfi_parse_valuelist(REGFI_FILE* file, uint32_t offset, 
900                                        uint32_t num_values, bool strict)
901{
902  REGFI_VALUE_LIST* ret_val;
903  uint32_t i, cell_length, length, read_len;
904  bool unalloc;
905
906  if(!regfi_parse_cell(file->fd, offset, NULL, 0, &cell_length, &unalloc))
907  {
908    regfi_add_message(file, REGFI_MSG_ERROR, "Failed to read cell header"
909                      " while parsing value list at offset 0x%.8X.", offset);
910    return NULL;
911  }
912
913  if((cell_length & 0x00000007) != 0)
914  {
915    regfi_add_message(file, REGFI_MSG_WARN, "Cell length not a multiple of 8"
916                      " while parsing value list at offset 0x%.8X.", offset);
917    if(strict)
918      return NULL;
919    cell_length = cell_length & 0xFFFFFFF8;
920  }
921
922  if((num_values * sizeof(uint32_t)) > cell_length-sizeof(uint32_t))
923  {
924    regfi_add_message(file, REGFI_MSG_WARN, "Too many values found"
925                      " while parsing value list at offset 0x%.8X.", offset);
926    if(strict)
927      return NULL;
928    num_values = cell_length/sizeof(uint32_t) - sizeof(uint32_t);
929  }
930
931  read_len = num_values*sizeof(uint32_t);
932  ret_val = talloc(NULL, REGFI_VALUE_LIST);
933  if(ret_val == NULL)
934    return NULL;
935
936  ret_val->elements = (REGFI_VALUE_LIST_ELEM*)talloc_size(ret_val, read_len);
937  if(ret_val->elements == NULL)
938  {
939    talloc_free(ret_val);
940    return NULL;
941  }
942  ret_val->num_values = num_values;
943
944  length = read_len;
945  if((regfi_read(file->fd, (uint8_t*)ret_val->elements, &length) != 0) 
946     || length != read_len)
947  {
948    regfi_add_message(file, REGFI_MSG_ERROR, "Failed to read value pointers"
949                      " while parsing value list at offset 0x%.8X.", offset);
950    talloc_free(ret_val);
951    return NULL;
952  }
953 
954  for(i=0; i < num_values; i++)
955  {
956    /* Fix endianness */
957    ret_val->elements[i] = IVAL(&ret_val->elements[i], 0);
958
959    /* Validate the first num_values values to ensure they make sense */
960    if(strict)
961    {
962      /* XXX: Need to revisit this file length check when we start dealing
963       *      with partial files. */
964      if((ret_val->elements[i] + REGFI_REGF_SIZE > file->file_length)
965         || ((ret_val->elements[i] & 0x00000007) != 0))
966      {
967        regfi_add_message(file, REGFI_MSG_WARN, "Invalid value pointer"
968                          " (0x%.8X) found while parsing value list at offset"
969                          " 0x%.8X.", ret_val->elements[i], offset);
970        talloc_free(ret_val);
971        return NULL;
972      }
973    }
974  }
975
976  return ret_val;
977}
978
979
980
981/******************************************************************************
982 ******************************************************************************/
983REGFI_VK_REC* regfi_load_value(REGFI_FILE* file, uint32_t offset, 
984                               REGFI_ENCODING output_encoding, bool strict)
985{
986  REGFI_VK_REC* ret_val = NULL;
987  int32_t max_size, tmp_size;
988  REGFI_ENCODING from_encoding;
989
990  max_size = regfi_calc_maxsize(file, offset);
991  if(max_size < 0)
992    return NULL;
993 
994  ret_val = regfi_parse_vk(file, offset, max_size, strict);
995  if(ret_val == NULL)
996    return NULL;
997
998  /* XXX: Registry value names are supposedly limited to 16383 characters
999   *      according to:
1000   *      http://msdn.microsoft.com/en-us/library/ms724872%28VS.85%29.aspx
1001   *      Might want to emit a warning if this is exceeded. 
1002   *      It is expected that "characters" could be variable width.
1003   *      Also, it may be useful to use this information to limit false positives
1004   *      when recovering deleted VK records.
1005   */
1006
1007  from_encoding = (ret_val->flags & REGFI_VK_FLAG_ASCIINAME)
1008    ? REGFI_ENCODING_ASCII : REGFI_ENCODING_UTF16LE;
1009
1010  if(from_encoding == output_encoding)
1011  {
1012    ret_val->valuename_raw = talloc_realloc(ret_val, ret_val->valuename_raw,
1013                                            uint8_t, ret_val->name_length+1);
1014    ret_val->valuename_raw[ret_val->name_length] = '\0';
1015    ret_val->valuename = (char*)ret_val->valuename_raw;
1016  }
1017  else
1018  {
1019    ret_val->valuename = talloc_array(ret_val, char, ret_val->name_length+1);
1020    if(ret_val->valuename == NULL)
1021    {
1022      regfi_free_value(ret_val);
1023      return NULL;
1024    }
1025
1026    tmp_size = regfi_conv_charset(regfi_encoding_int2str(from_encoding),
1027                                  regfi_encoding_int2str(output_encoding),
1028                                  ret_val->valuename_raw, ret_val->valuename,
1029                                  ret_val->name_length, ret_val->name_length+1);
1030    if(tmp_size < 0)
1031    {
1032      regfi_add_message(file, REGFI_MSG_WARN, "Error occurred while converting"
1033                        " valuename to encoding %s.  Error message: %s",
1034                        regfi_encoding_int2str(output_encoding), 
1035                        strerror(-tmp_size));
1036      talloc_free(ret_val->valuename);
1037      ret_val->valuename = NULL;
1038    }
1039  }
1040
1041  return ret_val;
1042}
1043
1044
1045/******************************************************************************
1046 * If !strict, the list may contain NULLs, VK records may point to NULL.
1047 ******************************************************************************/
1048REGFI_VALUE_LIST* regfi_load_valuelist(REGFI_FILE* file, uint32_t offset, 
1049                                       uint32_t num_values, uint32_t max_size,
1050                                       bool strict)
1051{
1052  uint32_t usable_num_values;
1053
1054  if((num_values+1) * sizeof(uint32_t) > max_size)
1055  {
1056    regfi_add_message(file, REGFI_MSG_WARN, "Number of values indicated by"
1057                      " parent key (%d) would cause cell to straddle HBIN"
1058                      " boundary while loading value list at offset"
1059                      " 0x%.8X.", num_values, offset);
1060    if(strict)
1061      return NULL;
1062    usable_num_values = max_size/sizeof(uint32_t) - sizeof(uint32_t);
1063  }
1064  else
1065    usable_num_values = num_values;
1066
1067  return regfi_parse_valuelist(file, offset, usable_num_values, strict);
1068}
1069
1070
1071
1072/******************************************************************************
1073 *
1074 ******************************************************************************/
1075REGFI_NK_REC* regfi_load_key(REGFI_FILE* file, uint32_t offset, 
1076                             REGFI_ENCODING output_encoding, bool strict)
1077{
1078  REGFI_NK_REC* nk;
1079  uint32_t off;
1080  int32_t max_size, tmp_size;
1081  REGFI_ENCODING from_encoding;
1082
1083  max_size = regfi_calc_maxsize(file, offset);
1084  if (max_size < 0) 
1085    return NULL;
1086
1087  /* get the initial nk record */
1088  if((nk = regfi_parse_nk(file, offset, max_size, true)) == NULL)
1089  {
1090    regfi_add_message(file, REGFI_MSG_ERROR, "Could not load NK record at"
1091                      " offset 0x%.8X.", offset);
1092    return NULL;
1093  }
1094
1095  /* XXX: Registry key names are supposedly limited to 255 characters according to:
1096   *      http://msdn.microsoft.com/en-us/library/ms724872%28VS.85%29.aspx
1097   *      Might want to emit a warning if this is exceeded. 
1098   *      It is expected that "characters" could be variable width.
1099   *      Also, it may be useful to use this information to limit false positives
1100   *      when recovering deleted NK records.
1101   */
1102  from_encoding = (nk->flags & REGFI_NK_FLAG_ASCIINAME) 
1103    ? REGFI_ENCODING_ASCII : REGFI_ENCODING_UTF16LE;
1104
1105  if(from_encoding == output_encoding)
1106  {
1107    nk->keyname_raw = talloc_realloc(nk, nk->keyname_raw, uint8_t, nk->name_length+1);
1108    nk->keyname_raw[nk->name_length] = '\0';
1109    nk->keyname = (char*)nk->keyname_raw;
1110  }
1111  else
1112  {
1113    nk->keyname = talloc_array(nk, char, nk->name_length+1);
1114    if(nk->keyname == NULL)
1115    {
1116      regfi_free_key(nk);
1117      return NULL;
1118    }
1119
1120    tmp_size = regfi_conv_charset(regfi_encoding_int2str(from_encoding),
1121                                  regfi_encoding_int2str(output_encoding),
1122                                  nk->keyname_raw, nk->keyname,
1123                                  nk->name_length, nk->name_length+1);
1124    if(tmp_size < 0)
1125    {
1126      regfi_add_message(file, REGFI_MSG_WARN, "Error occurred while converting"
1127                        " keyname to encoding %s.  Error message: %s",
1128                        regfi_encoding_int2str(output_encoding), 
1129                        strerror(-tmp_size));
1130      talloc_free(nk->keyname);
1131      nk->keyname = NULL;
1132    }
1133  }
1134
1135
1136  /* get value list */
1137  if(nk->num_values && (nk->values_off!=REGFI_OFFSET_NONE)) 
1138  {
1139    off = nk->values_off + REGFI_REGF_SIZE;
1140    max_size = regfi_calc_maxsize(file, off);
1141    if(max_size < 0)
1142    {
1143      if(strict)
1144      {
1145        regfi_free_key(nk);
1146        return NULL;
1147      }
1148      else
1149        nk->values = NULL;
1150
1151    }
1152    else
1153    {
1154      nk->values = regfi_load_valuelist(file, off, nk->num_values, 
1155                                        max_size, true);
1156      if(nk->values == NULL)
1157      {
1158        regfi_add_message(file, REGFI_MSG_WARN, "Could not load value list"
1159                          " for NK record at offset 0x%.8X.", offset);
1160        if(strict)
1161        {
1162          regfi_free_key(nk);
1163          return NULL;
1164        }
1165      }
1166      talloc_steal(nk, nk->values);
1167    }
1168  }
1169
1170  /* now get subkey list */
1171  if(nk->num_subkeys && (nk->subkeys_off != REGFI_OFFSET_NONE)) 
1172  {
1173    off = nk->subkeys_off + REGFI_REGF_SIZE;
1174    max_size = regfi_calc_maxsize(file, off);
1175    if(max_size < 0) 
1176    {
1177      if(strict)
1178      {
1179        regfi_free_key(nk);
1180        return NULL;
1181      }
1182      else
1183        nk->subkeys = NULL;
1184    }
1185    else
1186    {
1187      nk->subkeys = regfi_load_subkeylist(file, off, nk->num_subkeys,
1188                                          max_size, true);
1189
1190      if(nk->subkeys == NULL)
1191      {
1192        regfi_add_message(file, REGFI_MSG_WARN, "Could not load subkey list"
1193                          " while parsing NK record at offset 0x%.8X.", offset);
1194        nk->num_subkeys = 0;
1195      }
1196      talloc_steal(nk, nk->subkeys);
1197    }
1198  }
1199
1200  return nk;
1201}
1202
1203
1204/******************************************************************************
1205 ******************************************************************************/
1206const REGFI_SK_REC* regfi_load_sk(REGFI_FILE* file, uint32_t offset, bool strict)
1207{
1208  REGFI_SK_REC* ret_val = NULL;
1209  int32_t max_size;
1210  void* failure_ptr = NULL;
1211 
1212  /* First look if we have already parsed it */
1213  ret_val = (REGFI_SK_REC*)lru_cache_find(file->sk_cache, &offset, 4);
1214
1215  /* Bail out if we have previously cached a parse failure at this offset. */
1216  if(ret_val == (void*)REGFI_OFFSET_NONE)
1217    return NULL;
1218
1219  if(ret_val == NULL)
1220  {
1221    max_size = regfi_calc_maxsize(file, offset);
1222    if(max_size < 0)
1223      return NULL;
1224
1225    ret_val = regfi_parse_sk(file, offset, max_size, strict);
1226    if(ret_val == NULL)
1227    { /* Cache the parse failure and bail out. */
1228      failure_ptr = talloc(NULL, uint32_t);
1229      if(failure_ptr == NULL)
1230        return NULL;
1231      *(uint32_t*)failure_ptr = REGFI_OFFSET_NONE;
1232      lru_cache_update(file->sk_cache, &offset, 4, failure_ptr);
1233      return NULL;
1234    }
1235
1236    lru_cache_update(file->sk_cache, &offset, 4, ret_val);
1237  }
1238
1239  return ret_val;
1240}
1241
1242
1243
1244/******************************************************************************
1245 ******************************************************************************/
1246REGFI_NK_REC* regfi_find_root_nk(REGFI_FILE* file, const REGFI_HBIN* hbin, 
1247                                 REGFI_ENCODING output_encoding)
1248{
1249  REGFI_NK_REC* nk = NULL;
1250  uint32_t cell_length;
1251  uint32_t cur_offset = hbin->file_off+REGFI_HBIN_HEADER_SIZE;
1252  uint32_t hbin_end = hbin->file_off+hbin->block_size;
1253  bool unalloc;
1254
1255  while(cur_offset < hbin_end)
1256  {
1257    if(!regfi_parse_cell(file->fd, cur_offset, NULL, 0, &cell_length, &unalloc))
1258    {
1259      regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell at offset"
1260                        " 0x%.8X while searching for root key.", cur_offset);
1261      return NULL;
1262    }
1263   
1264    if(!unalloc)
1265    {
1266      nk = regfi_load_key(file, cur_offset, output_encoding, true);
1267      if(nk != NULL)
1268      {
1269        if(nk->flags & REGFI_NK_FLAG_ROOT)
1270          return nk;
1271      }
1272    }
1273
1274    cur_offset += cell_length;
1275  }
1276
1277  return NULL;
1278}
1279
1280
1281/******************************************************************************
1282 ******************************************************************************/
1283REGFI_FILE* regfi_open(const char* filename)
1284{
1285  REGFI_FILE* ret_val;
1286  int fd;
1287
1288  /* open an existing file */
1289  if ((fd = open(filename, REGFI_OPEN_FLAGS)) == -1)
1290  {
1291    /* fprintf(stderr, "regfi_open: failure to open %s (%s)\n", filename, strerror(errno));*/
1292    return NULL;
1293  }
1294
1295  ret_val = regfi_alloc(fd);
1296
1297  if(ret_val == NULL)
1298    close(fd);
1299
1300  return ret_val;
1301}
1302
1303
1304/******************************************************************************
1305 ******************************************************************************/
1306REGFI_FILE* regfi_alloc(int fd)
1307{
1308  struct stat sbuf;
1309  REGFI_FILE* rb;
1310  REGFI_HBIN* hbin = NULL;
1311  uint32_t hbin_off, file_length, cache_secret;
1312  bool rla;
1313
1314  /* Determine file length.  Must be at least big enough
1315   * for the header and one hbin.
1316   */
1317  if (fstat(fd, &sbuf) == -1)
1318    return NULL;
1319  file_length = sbuf.st_size;
1320  if(file_length < REGFI_REGF_SIZE+REGFI_HBIN_ALLOC)
1321    return NULL;
1322
1323  /* Read file header */
1324  if ((rb = regfi_parse_regf(fd, true)) == NULL) 
1325  {
1326    /* fprintf(stderr, "regfi_alloc: Failed to read initial REGF block\n"); */
1327    return NULL;
1328  }
1329  rb->file_length = file_length; 
1330
1331  rb->hbins = range_list_new();
1332  if(rb->hbins == NULL)
1333  {
1334    /* fprintf(stderr, "regfi_alloc: Failed to create HBIN list.\n"); */
1335    talloc_free(rb);
1336    return NULL;
1337  }
1338  talloc_steal(rb, rb->hbins);
1339
1340  rla = true;
1341  hbin_off = REGFI_REGF_SIZE;
1342  hbin = regfi_parse_hbin(rb, hbin_off, true);
1343  while(hbin && rla)
1344  {
1345    rla = range_list_add(rb->hbins, hbin->file_off, hbin->block_size, hbin);
1346    if(rla)
1347      talloc_steal(rb->hbins, hbin);
1348    hbin_off = hbin->file_off + hbin->block_size;
1349    hbin = regfi_parse_hbin(rb, hbin_off, true);
1350  }
1351
1352  /* This secret isn't very secret, but we don't need a good one.  This
1353   * secret is just designed to prevent someone from trying to blow our
1354   * caching and make things slow.
1355   */
1356  cache_secret = 0x15DEAD05^time(NULL)^(getpid()<<16);
1357
1358  /* Cache an unlimited number of SK records.  Typically there are very few. */
1359  rb->sk_cache = lru_cache_create_ctx(rb, 0, cache_secret, true);
1360
1361  /* Default message mask */
1362  rb->msg_mask = REGFI_MSG_ERROR|REGFI_MSG_WARN;
1363
1364  /* success */
1365  return rb;
1366}
1367
1368
1369/******************************************************************************
1370 ******************************************************************************/
1371int regfi_close(REGFI_FILE* file)
1372{
1373  int fd;
1374
1375  /* nothing to do if there is no open file */
1376  if ((file == NULL) || (file->fd == -1))
1377    return 0;
1378
1379  fd = file->fd;
1380  file->fd = -1;
1381
1382  regfi_free(file);
1383
1384  return close(fd);
1385}
1386
1387
1388/******************************************************************************
1389 ******************************************************************************/
1390void regfi_free(REGFI_FILE *file)
1391{
1392  if(file->last_message != NULL)
1393    free(file->last_message);
1394
1395  talloc_free(file);
1396}
1397
1398
1399/******************************************************************************
1400 * First checks the offset given by the file header, then checks the
1401 * rest of the file if that fails.
1402 ******************************************************************************/
1403REGFI_NK_REC* regfi_rootkey(REGFI_FILE* file, REGFI_ENCODING output_encoding)
1404{
1405  REGFI_NK_REC* nk = NULL;
1406  REGFI_HBIN* hbin;
1407  uint32_t root_offset, i, num_hbins;
1408 
1409  if(!file)
1410    return NULL;
1411
1412  root_offset = file->root_cell+REGFI_REGF_SIZE;
1413  nk = regfi_load_key(file, root_offset, output_encoding, true);
1414  if(nk != NULL)
1415  {
1416    if(nk->flags & REGFI_NK_FLAG_ROOT)
1417      return nk;
1418  }
1419
1420  regfi_add_message(file, REGFI_MSG_WARN, "File header indicated root key at"
1421                    " location 0x%.8X, but no root key found."
1422                    " Searching rest of file...", root_offset);
1423 
1424  /* If the file header gives bad info, scan through the file one HBIN
1425   * block at a time looking for an NK record with a root key type.
1426   */
1427  num_hbins = range_list_size(file->hbins);
1428  for(i=0; i < num_hbins && nk == NULL; i++)
1429  {
1430    hbin = (REGFI_HBIN*)range_list_get(file->hbins, i)->data;
1431    nk = regfi_find_root_nk(file, hbin, output_encoding);
1432  }
1433
1434  return nk;
1435}
1436
1437
1438/******************************************************************************
1439 *****************************************************************************/
1440void regfi_free_key(REGFI_NK_REC* nk)
1441{
1442  regfi_subkeylist_free(nk->subkeys);
1443  talloc_free(nk);
1444}
1445
1446
1447/******************************************************************************
1448 *****************************************************************************/
1449void regfi_free_value(REGFI_VK_REC* vk)
1450{
1451  talloc_free(vk);
1452}
1453
1454
1455/******************************************************************************
1456 *****************************************************************************/
1457void regfi_subkeylist_free(REGFI_SUBKEY_LIST* list)
1458{
1459  if(list != NULL)
1460  {
1461    talloc_free(list);
1462  }
1463}
1464
1465
1466/******************************************************************************
1467 *****************************************************************************/
1468REGFI_ITERATOR* regfi_iterator_new(REGFI_FILE* file, 
1469                                   REGFI_ENCODING output_encoding)
1470{
1471  REGFI_NK_REC* root;
1472  REGFI_ITERATOR* ret_val;
1473
1474  if(output_encoding != REGFI_ENCODING_UTF8
1475     && output_encoding != REGFI_ENCODING_ASCII)
1476  { 
1477    regfi_add_message(file, REGFI_MSG_ERROR, "Invalid output_encoding supplied"
1478                      " in creation of regfi iterator.");
1479    return NULL;
1480  }
1481
1482  ret_val = talloc(NULL, REGFI_ITERATOR);
1483  if(ret_val == NULL)
1484    return NULL;
1485
1486  root = regfi_rootkey(file, output_encoding);
1487  if(root == NULL)
1488  {
1489    talloc_free(ret_val);
1490    return NULL;
1491  }
1492
1493  ret_val->key_positions = void_stack_new(REGFI_MAX_DEPTH);
1494  if(ret_val->key_positions == NULL)
1495  {
1496    talloc_free(ret_val);
1497    return NULL;
1498  }
1499  talloc_steal(ret_val, ret_val->key_positions);
1500
1501  ret_val->f = file;
1502  ret_val->cur_key = root;
1503  ret_val->cur_subkey = 0;
1504  ret_val->cur_value = 0;
1505  ret_val->string_encoding = output_encoding;
1506   
1507  return ret_val;
1508}
1509
1510
1511/******************************************************************************
1512 *****************************************************************************/
1513void regfi_iterator_free(REGFI_ITERATOR* i)
1514{
1515  talloc_free(i);
1516}
1517
1518
1519
1520/******************************************************************************
1521 *****************************************************************************/
1522/* XXX: some way of indicating reason for failure should be added. */
1523bool regfi_iterator_down(REGFI_ITERATOR* i)
1524{
1525  REGFI_NK_REC* subkey;
1526  REGFI_ITER_POSITION* pos;
1527
1528  pos = talloc(i->key_positions, REGFI_ITER_POSITION);
1529  if(pos == NULL)
1530    return false;
1531
1532  subkey = (REGFI_NK_REC*)regfi_iterator_cur_subkey(i);
1533  if(subkey == NULL)
1534  {
1535    talloc_free(pos);
1536    return false;
1537  }
1538
1539  pos->nk = i->cur_key;
1540  pos->cur_subkey = i->cur_subkey;
1541  if(!void_stack_push(i->key_positions, pos))
1542  {
1543    talloc_free(pos);
1544    regfi_free_key(subkey);
1545    return false;
1546  }
1547  talloc_steal(i, subkey);
1548
1549  i->cur_key = subkey;
1550  i->cur_subkey = 0;
1551  i->cur_value = 0;
1552
1553  return true;
1554}
1555
1556
1557/******************************************************************************
1558 *****************************************************************************/
1559bool regfi_iterator_up(REGFI_ITERATOR* i)
1560{
1561  REGFI_ITER_POSITION* pos;
1562
1563  pos = (REGFI_ITER_POSITION*)void_stack_pop(i->key_positions);
1564  if(pos == NULL)
1565    return false;
1566
1567  regfi_free_key(i->cur_key);
1568  i->cur_key = pos->nk;
1569  i->cur_subkey = pos->cur_subkey;
1570  i->cur_value = 0;
1571  talloc_free(pos);
1572
1573  return true;
1574}
1575
1576
1577/******************************************************************************
1578 *****************************************************************************/
1579bool regfi_iterator_to_root(REGFI_ITERATOR* i)
1580{
1581  while(regfi_iterator_up(i))
1582    continue;
1583
1584  return true;
1585}
1586
1587
1588/******************************************************************************
1589 *****************************************************************************/
1590bool regfi_iterator_find_subkey(REGFI_ITERATOR* i, const char* subkey_name)
1591{
1592  REGFI_NK_REC* subkey;
1593  bool found = false;
1594  uint32_t old_subkey = i->cur_subkey;
1595
1596  if(subkey_name == NULL)
1597    return false;
1598
1599  /* XXX: this alloc/free of each sub key might be a bit excessive */
1600  subkey = (REGFI_NK_REC*)regfi_iterator_first_subkey(i);
1601  while((subkey != NULL) && (found == false))
1602  {
1603    if(subkey->keyname != NULL 
1604       && strcasecmp(subkey->keyname, subkey_name) == 0)
1605      found = true;
1606    else
1607    {
1608      regfi_free_key(subkey);
1609      subkey = (REGFI_NK_REC*)regfi_iterator_next_subkey(i);
1610    }
1611  }
1612
1613  if(found == false)
1614  {
1615    i->cur_subkey = old_subkey;
1616    return false;
1617  }
1618
1619  regfi_free_key(subkey);
1620  return true;
1621}
1622
1623
1624/******************************************************************************
1625 *****************************************************************************/
1626bool regfi_iterator_walk_path(REGFI_ITERATOR* i, const char** path)
1627{
1628  uint32_t x;
1629  if(path == NULL)
1630    return false;
1631
1632  for(x=0; 
1633      ((path[x] != NULL) && regfi_iterator_find_subkey(i, path[x])
1634       && regfi_iterator_down(i));
1635      x++)
1636  { continue; }
1637
1638  if(path[x] == NULL)
1639    return true;
1640 
1641  /* XXX: is this the right number of times? */
1642  for(; x > 0; x--)
1643    regfi_iterator_up(i);
1644 
1645  return false;
1646}
1647
1648
1649/******************************************************************************
1650 *****************************************************************************/
1651const REGFI_NK_REC* regfi_iterator_cur_key(REGFI_ITERATOR* i)
1652{
1653  return i->cur_key;
1654}
1655
1656
1657/******************************************************************************
1658 *****************************************************************************/
1659const REGFI_SK_REC* regfi_iterator_cur_sk(REGFI_ITERATOR* i)
1660{
1661  if(i->cur_key == NULL || i->cur_key->sk_off == REGFI_OFFSET_NONE)
1662    return NULL;
1663
1664  return regfi_load_sk(i->f, i->cur_key->sk_off + REGFI_REGF_SIZE, true);
1665}
1666
1667
1668/******************************************************************************
1669 *****************************************************************************/
1670REGFI_NK_REC* regfi_iterator_first_subkey(REGFI_ITERATOR* i)
1671{
1672  i->cur_subkey = 0;
1673  return regfi_iterator_cur_subkey(i);
1674}
1675
1676
1677/******************************************************************************
1678 *****************************************************************************/
1679REGFI_NK_REC* regfi_iterator_cur_subkey(REGFI_ITERATOR* i)
1680{
1681  uint32_t nk_offset;
1682
1683  /* see if there is anything left to report */
1684  if (!(i->cur_key) || (i->cur_key->subkeys_off==REGFI_OFFSET_NONE)
1685      || (i->cur_subkey >= i->cur_key->num_subkeys))
1686    return NULL;
1687
1688  nk_offset = i->cur_key->subkeys->elements[i->cur_subkey].offset;
1689
1690  return regfi_load_key(i->f, nk_offset+REGFI_REGF_SIZE, i->string_encoding, 
1691                        true);
1692}
1693
1694
1695/******************************************************************************
1696 *****************************************************************************/
1697/* XXX: some way of indicating reason for failure should be added. */
1698REGFI_NK_REC* regfi_iterator_next_subkey(REGFI_ITERATOR* i)
1699{
1700  REGFI_NK_REC* subkey;
1701
1702  i->cur_subkey++;
1703  subkey = regfi_iterator_cur_subkey(i);
1704
1705  if(subkey == NULL)
1706    i->cur_subkey--;
1707
1708  return subkey;
1709}
1710
1711
1712/******************************************************************************
1713 *****************************************************************************/
1714bool regfi_iterator_find_value(REGFI_ITERATOR* i, const char* value_name)
1715{
1716  REGFI_VK_REC* cur;
1717  bool found = false;
1718  uint32_t old_value = i->cur_value;
1719
1720  /* XXX: cur->valuename can be NULL in the registry. 
1721   *      Should we allow for a way to search for that?
1722   */
1723  if(value_name == NULL)
1724    return false;
1725
1726  cur = regfi_iterator_first_value(i);
1727  while((cur != NULL) && (found == false))
1728  {
1729    if((cur->valuename != NULL)
1730       && (strcasecmp(cur->valuename, value_name) == 0))
1731      found = true;
1732    else
1733    {
1734      regfi_free_value(cur);
1735      cur = regfi_iterator_next_value(i);
1736    }
1737  }
1738 
1739  if(found == false)
1740  {
1741    i->cur_value = old_value;
1742    return false;
1743  }
1744
1745  regfi_free_value(cur);
1746  return true;
1747}
1748
1749
1750/******************************************************************************
1751 *****************************************************************************/
1752REGFI_VK_REC* regfi_iterator_first_value(REGFI_ITERATOR* i)
1753{
1754  i->cur_value = 0;
1755  return regfi_iterator_cur_value(i);
1756}
1757
1758
1759/******************************************************************************
1760 *****************************************************************************/
1761REGFI_VK_REC* regfi_iterator_cur_value(REGFI_ITERATOR* i)
1762{
1763  REGFI_VK_REC* ret_val = NULL;
1764  uint32_t voffset;
1765
1766  if(i->cur_key->values != NULL && i->cur_key->values->elements != NULL)
1767  {
1768    if(i->cur_value < i->cur_key->values->num_values)
1769    {
1770      voffset = i->cur_key->values->elements[i->cur_value];
1771      ret_val = regfi_load_value(i->f, voffset+REGFI_REGF_SIZE, 
1772                                 i->string_encoding, true);
1773    }
1774  }
1775
1776  return ret_val;
1777}
1778
1779
1780/******************************************************************************
1781 *****************************************************************************/
1782REGFI_VK_REC* regfi_iterator_next_value(REGFI_ITERATOR* i)
1783{
1784  REGFI_VK_REC* ret_val;
1785
1786  i->cur_value++;
1787  ret_val = regfi_iterator_cur_value(i);
1788  if(ret_val == NULL)
1789    i->cur_value--;
1790
1791  return ret_val;
1792}
1793
1794
1795/******************************************************************************
1796 *****************************************************************************/
1797REGFI_CLASSNAME* regfi_iterator_fetch_classname(REGFI_ITERATOR* i, 
1798                                                const REGFI_NK_REC* key)
1799{
1800  REGFI_CLASSNAME* ret_val;
1801  uint8_t* raw;
1802  char* interpreted;
1803  uint32_t offset;
1804  int32_t conv_size, max_size;
1805  uint16_t parse_length;
1806
1807  if(key->classname_off == REGFI_OFFSET_NONE || key->classname_length == 0)
1808    return NULL;
1809
1810  offset = key->classname_off + REGFI_REGF_SIZE;
1811  max_size = regfi_calc_maxsize(i->f, offset);
1812  if(max_size <= 0)
1813    return NULL;
1814
1815  parse_length = key->classname_length;
1816  raw = regfi_parse_classname(i->f, offset, &parse_length, max_size, true);
1817 
1818  if(raw == NULL)
1819  {
1820    regfi_add_message(i->f, REGFI_MSG_WARN, "Could not parse class"
1821                      " name at offset 0x%.8X for key record at offset 0x%.8X.",
1822                      offset, key->offset);
1823    return NULL;
1824  }
1825
1826  ret_val = talloc(NULL, REGFI_CLASSNAME);
1827  if(ret_val == NULL)
1828    return NULL;
1829
1830  ret_val->raw = raw;
1831  ret_val->size = parse_length;
1832  talloc_steal(ret_val, raw);
1833
1834  interpreted = talloc_array(NULL, char, parse_length);
1835
1836  conv_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
1837                                 regfi_encoding_int2str(i->string_encoding),
1838                                 raw, interpreted,
1839                                 parse_length, parse_length);
1840  if(conv_size < 0)
1841  {
1842    regfi_add_message(i->f, REGFI_MSG_WARN, "Error occurred while"
1843                      " converting classname to charset %s.  Error message: %s",
1844                      i->string_encoding, strerror(-conv_size));
1845    talloc_free(interpreted);
1846    ret_val->interpreted = NULL;
1847  }
1848  else
1849  {
1850    interpreted = talloc_realloc(NULL, interpreted, char, conv_size);
1851    ret_val->interpreted = interpreted;
1852    talloc_steal(ret_val, interpreted);
1853  }
1854
1855  return ret_val;
1856}
1857
1858
1859/******************************************************************************
1860 *****************************************************************************/
1861REGFI_DATA* regfi_iterator_fetch_data(REGFI_ITERATOR* i, 
1862                                      const REGFI_VK_REC* value)
1863{
1864  REGFI_DATA* ret_val = NULL;
1865  REGFI_BUFFER raw_data;
1866
1867  if(value->data_size != 0)
1868  {
1869    raw_data = regfi_load_data(i->f, value->data_off, value->data_size,
1870                              value->data_in_offset, true);
1871    if(raw_data.buf == NULL)
1872    {
1873      regfi_add_message(i->f, REGFI_MSG_WARN, "Could not parse data record"
1874                        " while parsing VK record at offset 0x%.8X.",
1875                        value->offset);
1876    }
1877    else
1878    {
1879      ret_val = regfi_buffer_to_data(raw_data);
1880
1881      if(ret_val == NULL)
1882      {
1883        regfi_add_message(i->f, REGFI_MSG_WARN, "Error occurred in converting"
1884                          " data buffer to data structure while interpreting "
1885                          "data for VK record at offset 0x%.8X.",
1886                          value->offset);
1887        talloc_free(raw_data.buf);
1888        return NULL;
1889      }
1890
1891      if(!regfi_interpret_data(i->f, i->string_encoding, value->type, ret_val))
1892      {
1893        regfi_add_message(i->f, REGFI_MSG_INFO, "Error occurred while"
1894                          " interpreting data for VK record at offset 0x%.8X.",
1895                          value->offset);
1896      }
1897    }
1898  }
1899 
1900  return ret_val;
1901}
1902
1903
1904/******************************************************************************
1905 *****************************************************************************/
1906void regfi_free_classname(REGFI_CLASSNAME* classname)
1907{
1908  talloc_free(classname);
1909}
1910
1911/******************************************************************************
1912 *****************************************************************************/
1913void regfi_free_data(REGFI_DATA* data)
1914{
1915  talloc_free(data);
1916}
1917
1918
1919/******************************************************************************
1920 *****************************************************************************/
1921REGFI_DATA* regfi_buffer_to_data(REGFI_BUFFER raw_data)
1922{
1923  REGFI_DATA* ret_val;
1924
1925  if(raw_data.buf == NULL)
1926    return NULL;
1927
1928  ret_val = talloc(NULL, REGFI_DATA);
1929  if(ret_val == NULL)
1930    return NULL;
1931 
1932  talloc_steal(ret_val, raw_data.buf);
1933  ret_val->raw = raw_data.buf;
1934  ret_val->size = raw_data.len;
1935  ret_val->interpreted_size = 0;
1936  ret_val->interpreted.qword = 0;
1937
1938  return ret_val;
1939}
1940
1941
1942/******************************************************************************
1943 *****************************************************************************/
1944bool regfi_interpret_data(REGFI_FILE* file, REGFI_ENCODING string_encoding,
1945                          uint32_t type, REGFI_DATA* data)
1946{
1947  uint8_t** tmp_array;
1948  uint8_t* tmp_str;
1949  int32_t tmp_size;
1950  uint32_t i, j, array_size;
1951
1952  if(data == NULL)
1953    return false;
1954
1955  switch (type)
1956  {
1957  case REG_SZ:
1958  case REG_EXPAND_SZ:
1959  /* REG_LINK is a symbolic link, stored as a unicode string. */
1960  case REG_LINK:
1961    tmp_str = talloc_array(NULL, uint8_t, data->size);
1962    if(tmp_str == NULL)
1963    {
1964      data->interpreted.string = NULL;
1965      data->interpreted_size = 0;
1966      return false;
1967    }
1968     
1969    tmp_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
1970                                  regfi_encoding_int2str(string_encoding),
1971                                  data->raw, (char*)tmp_str, 
1972                                  data->size, data->size);
1973    if(tmp_size < 0)
1974    {
1975      regfi_add_message(file, REGFI_MSG_INFO, "Error occurred while"
1976                        " converting data of type %d to %s.  Error message: %s",
1977                        type, string_encoding, strerror(-tmp_size));
1978      talloc_free(tmp_str);
1979      data->interpreted.string = NULL;
1980      data->interpreted_size = 0;
1981      return false;
1982    }
1983
1984    tmp_str = talloc_realloc(NULL, tmp_str, uint8_t, tmp_size);
1985    data->interpreted.string = tmp_str;
1986    data->interpreted_size = tmp_size;
1987    talloc_steal(data, tmp_str);
1988    break;
1989
1990  case REG_DWORD:
1991    if(data->size < 4)
1992    {
1993      data->interpreted.dword = 0;
1994      data->interpreted_size = 0;
1995      return false;
1996    }
1997    data->interpreted.dword = IVAL(data->raw, 0);
1998    data->interpreted_size = 4;
1999    break;
2000
2001  case REG_DWORD_BE:
2002    if(data->size < 4)
2003    {
2004      data->interpreted.dword_be = 0;
2005      data->interpreted_size = 0;
2006      return false;
2007    }
2008    data->interpreted.dword_be = RIVAL(data->raw, 0);
2009    data->interpreted_size = 4;
2010    break;
2011
2012  case REG_QWORD:
2013    if(data->size < 8)
2014    {
2015      data->interpreted.qword = 0;
2016      data->interpreted_size = 0;
2017      return false;
2018    }
2019    data->interpreted.qword = 
2020      (uint64_t)IVAL(data->raw, 0) + (((uint64_t)IVAL(data->raw, 4))<<32);
2021    data->interpreted_size = 8;
2022    break;
2023   
2024  case REG_MULTI_SZ:
2025    tmp_str = talloc_array(NULL, uint8_t, data->size);
2026    if(tmp_str == NULL)
2027    {
2028      data->interpreted.multiple_string = NULL;
2029      data->interpreted_size = 0;
2030      return false;
2031    }
2032
2033    /* Attempt to convert entire string from UTF-16LE to output encoding,
2034     * then parse and quote fields individually.
2035     */
2036    tmp_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
2037                                  regfi_encoding_int2str(string_encoding),
2038                                  data->raw, (char*)tmp_str,
2039                                  data->size, data->size);
2040    if(tmp_size < 0)
2041    {
2042      regfi_add_message(file, REGFI_MSG_INFO, "Error occurred while"
2043                        " converting data of type %d to %s.  Error message: %s",
2044                        type, string_encoding, strerror(-tmp_size));
2045      talloc_free(tmp_str);
2046      data->interpreted.multiple_string = NULL;
2047      data->interpreted_size = 0;
2048      return false;
2049    }
2050
2051    array_size = tmp_size+1;
2052    tmp_array = talloc_array(NULL, uint8_t*, array_size);
2053    if(tmp_array == NULL)
2054    {
2055      talloc_free(tmp_str);
2056      data->interpreted.string = NULL;
2057      data->interpreted_size = 0;
2058      return false;
2059    }
2060   
2061    tmp_array[0] = tmp_str;
2062    for(i=0,j=1; i < tmp_size && j < array_size-1; i++)
2063    {
2064      if(tmp_str[i] == '\0' && (i+1 < tmp_size))
2065        tmp_array[j++] = tmp_str+i+1;
2066    }
2067    tmp_array[j] = NULL;
2068    tmp_array = talloc_realloc(NULL, tmp_array, uint8_t*, j+1);
2069    data->interpreted.multiple_string = tmp_array;
2070    /* XXX: how meaningful is this?  should we store number of strings instead? */
2071    data->interpreted_size = tmp_size;
2072    talloc_steal(tmp_array, tmp_str);
2073    talloc_steal(data, tmp_array);
2074    break;
2075
2076  /* XXX: Dont know how to interpret these yet, just treat as binary */
2077  case REG_NONE:
2078    data->interpreted.none = data->raw;
2079    data->interpreted_size = data->size;
2080    break;
2081
2082  case REG_RESOURCE_LIST:
2083    data->interpreted.resource_list = data->raw;
2084    data->interpreted_size = data->size;
2085    break;
2086
2087  case REG_FULL_RESOURCE_DESCRIPTOR:
2088    data->interpreted.full_resource_descriptor = data->raw;
2089    data->interpreted_size = data->size;
2090    break;
2091
2092  case REG_RESOURCE_REQUIREMENTS_LIST:
2093    data->interpreted.resource_requirements_list = data->raw;
2094    data->interpreted_size = data->size;
2095    break;
2096
2097  case REG_BINARY:
2098    data->interpreted.binary = data->raw;
2099    data->interpreted_size = data->size;
2100    break;
2101
2102  default:
2103    data->interpreted.qword = 0;
2104    data->interpreted_size = 0;
2105    return false;
2106  }
2107
2108  data->type = type;
2109  return true;
2110}
2111
2112
2113/******************************************************************************
2114 * Convert from UTF-16LE to specified character set.
2115 * On error, returns a negative errno code.
2116 *****************************************************************************/
2117int32_t regfi_conv_charset(const char* input_charset, const char* output_charset,
2118                         uint8_t* input, char* output, 
2119                         uint32_t input_len, uint32_t output_max)
2120{
2121  iconv_t conv_desc;
2122  char* inbuf = (char*)input;
2123  char* outbuf = output;
2124  size_t in_len = (size_t)input_len;
2125  size_t out_len = (size_t)(output_max-1);
2126  int ret;
2127
2128  /* XXX: Consider creating a couple of conversion descriptors earlier,
2129   *      storing them on an iterator so they don't have to be recreated
2130   *      each time.
2131   */
2132
2133  /* Set up conversion descriptor. */
2134  conv_desc = iconv_open(output_charset, input_charset);
2135
2136  ret = iconv(conv_desc, &inbuf, &in_len, &outbuf, &out_len);
2137  if(ret == -1)
2138  {
2139    iconv_close(conv_desc);
2140    return -errno;
2141  }
2142  *outbuf = '\0';
2143
2144  iconv_close(conv_desc); 
2145  return output_max-out_len-1;
2146}
2147
2148
2149
2150/*******************************************************************
2151 * Computes the checksum of the registry file header.
2152 * buffer must be at least the size of a regf header (4096 bytes).
2153 *******************************************************************/
2154static uint32_t regfi_compute_header_checksum(uint8_t* buffer)
2155{
2156  uint32_t checksum, x;
2157  int i;
2158
2159  /* XOR of all bytes 0x0000 - 0x01FB */
2160
2161  checksum = x = 0;
2162 
2163  for ( i=0; i<0x01FB; i+=4 ) {
2164    x = IVAL(buffer, i );
2165    checksum ^= x;
2166  }
2167 
2168  return checksum;
2169}
2170
2171
2172/*******************************************************************
2173 * XXX: Add way to return more detailed error information.
2174 *******************************************************************/
2175REGFI_FILE* regfi_parse_regf(int fd, bool strict)
2176{
2177  uint8_t file_header[REGFI_REGF_SIZE];
2178  uint32_t length;
2179  REGFI_FILE* ret_val;
2180
2181  ret_val = talloc(NULL, REGFI_FILE);
2182  if(ret_val == NULL)
2183    return NULL;
2184
2185  ret_val->fd = fd;
2186  ret_val->sk_cache = NULL;
2187  ret_val->last_message = NULL;
2188  ret_val->hbins = NULL;
2189 
2190  length = REGFI_REGF_SIZE;
2191  if((regfi_read(fd, file_header, &length)) != 0 || length != REGFI_REGF_SIZE)
2192    goto fail;
2193 
2194  ret_val->checksum = IVAL(file_header, 0x1FC);
2195  ret_val->computed_checksum = regfi_compute_header_checksum(file_header);
2196  if (strict && (ret_val->checksum != ret_val->computed_checksum))
2197    goto fail;
2198
2199  memcpy(ret_val->magic, file_header, REGFI_REGF_MAGIC_SIZE);
2200  if(memcmp(ret_val->magic, "regf", REGFI_REGF_MAGIC_SIZE) != 0)
2201  {
2202    if(strict)
2203      goto fail;
2204    regfi_add_message(ret_val, REGFI_MSG_WARN, "Magic number mismatch "
2205                      "(%.2X %.2X %.2X %.2X) while parsing hive header",
2206                      ret_val->magic[0], ret_val->magic[1], 
2207                      ret_val->magic[2], ret_val->magic[3]);
2208  }
2209  ret_val->sequence1 = IVAL(file_header, 0x4);
2210  ret_val->sequence2 = IVAL(file_header, 0x8);
2211  ret_val->mtime.low = IVAL(file_header, 0xC);
2212  ret_val->mtime.high = IVAL(file_header, 0x10);
2213  ret_val->major_version = IVAL(file_header, 0x14);
2214  ret_val->minor_version = IVAL(file_header, 0x18);
2215  ret_val->type = IVAL(file_header, 0x1C);
2216  ret_val->format = IVAL(file_header, 0x20);
2217  ret_val->root_cell = IVAL(file_header, 0x24);
2218  ret_val->last_block = IVAL(file_header, 0x28);
2219
2220  ret_val->cluster = IVAL(file_header, 0x2C);
2221
2222  memcpy(ret_val->file_name, file_header+0x30,  REGFI_REGF_NAME_SIZE);
2223
2224  /* XXX: Should we add a warning if these uuid parsers fail?  Can they? */
2225  ret_val->rm_id = winsec_parse_uuid(ret_val, file_header+0x70, 16);
2226  ret_val->log_id = winsec_parse_uuid(ret_val, file_header+0x80, 16);
2227  ret_val->flags = IVAL(file_header, 0x90);
2228  ret_val->tm_id = winsec_parse_uuid(ret_val, file_header+0x94, 16);
2229  ret_val->guid_signature = IVAL(file_header, 0xa4);
2230
2231  memcpy(ret_val->reserved1, file_header+0xa8, REGFI_REGF_RESERVED1_SIZE);
2232  memcpy(ret_val->reserved2, file_header+0x200, REGFI_REGF_RESERVED2_SIZE);
2233
2234  ret_val->thaw_tm_id = winsec_parse_uuid(ret_val, file_header+0xFC8, 16);
2235  ret_val->thaw_rm_id = winsec_parse_uuid(ret_val, file_header+0xFD8, 16);
2236  ret_val->thaw_log_id = winsec_parse_uuid(ret_val, file_header+0xFE8, 16);
2237  ret_val->boot_type = IVAL(file_header, 0xFF8);
2238  ret_val->boot_recover = IVAL(file_header, 0xFFC);
2239
2240  return ret_val;
2241
2242 fail:
2243  talloc_free(ret_val);
2244  return NULL;
2245}
2246
2247
2248
2249/******************************************************************************
2250 * Given real file offset, read and parse the hbin at that location
2251 * along with it's associated cells.
2252 ******************************************************************************/
2253REGFI_HBIN* regfi_parse_hbin(REGFI_FILE* file, uint32_t offset, bool strict)
2254{
2255  REGFI_HBIN *hbin;
2256  uint8_t hbin_header[REGFI_HBIN_HEADER_SIZE];
2257  uint32_t length;
2258 
2259  if(offset >= file->file_length)
2260    return NULL;
2261
2262  if(lseek(file->fd, offset, SEEK_SET) == -1)
2263  {
2264    regfi_add_message(file, REGFI_MSG_ERROR, "Seek failed"
2265                      " while parsing hbin at offset 0x%.8X.", offset);
2266    return NULL;
2267  }
2268
2269  length = REGFI_HBIN_HEADER_SIZE;
2270  if((regfi_read(file->fd, hbin_header, &length) != 0) 
2271     || length != REGFI_HBIN_HEADER_SIZE)
2272    return NULL;
2273
2274  if(lseek(file->fd, offset, SEEK_SET) == -1)
2275  {
2276    regfi_add_message(file, REGFI_MSG_ERROR, "Seek failed"
2277                      " while parsing hbin at offset 0x%.8X.", offset);
2278    return NULL;
2279  }
2280
2281  hbin = talloc(NULL, REGFI_HBIN);
2282  if(hbin == NULL)
2283    return NULL;
2284  hbin->file_off = offset;
2285
2286  memcpy(hbin->magic, hbin_header, 4);
2287  if(strict && (memcmp(hbin->magic, "hbin", 4) != 0))
2288  {
2289    regfi_add_message(file, REGFI_MSG_INFO, "Magic number mismatch "
2290                      "(%.2X %.2X %.2X %.2X) while parsing hbin at offset"
2291                      " 0x%.8X.", hbin->magic[0], hbin->magic[1], 
2292                      hbin->magic[2], hbin->magic[3], offset);
2293    talloc_free(hbin);
2294    return NULL;
2295  }
2296
2297  hbin->first_hbin_off = IVAL(hbin_header, 0x4);
2298  hbin->block_size = IVAL(hbin_header, 0x8);
2299  /* this should be the same thing as hbin->block_size but just in case */
2300  hbin->next_block = IVAL(hbin_header, 0x1C);
2301
2302
2303  /* Ensure the block size is a multiple of 0x1000 and doesn't run off
2304   * the end of the file.
2305   */
2306  /* XXX: This may need to be relaxed for dealing with
2307   *      partial or corrupt files.
2308   */
2309  if((offset + hbin->block_size > file->file_length)
2310     || (hbin->block_size & 0xFFFFF000) != hbin->block_size)
2311  {
2312    regfi_add_message(file, REGFI_MSG_ERROR, "The hbin offset is not aligned"
2313                      " or runs off the end of the file"
2314                      " while parsing hbin at offset 0x%.8X.", offset);
2315    talloc_free(hbin);
2316    return NULL;
2317  }
2318
2319  return hbin;
2320}
2321
2322
2323/*******************************************************************
2324 *******************************************************************/
2325REGFI_NK_REC* regfi_parse_nk(REGFI_FILE* file, uint32_t offset, 
2326                             uint32_t max_size, bool strict)
2327{
2328  uint8_t nk_header[REGFI_NK_MIN_LENGTH];
2329  REGFI_NK_REC* ret_val;
2330  uint32_t length,cell_length;
2331  bool unalloc = false;
2332
2333  if(!regfi_parse_cell(file->fd, offset, nk_header, REGFI_NK_MIN_LENGTH,
2334                       &cell_length, &unalloc))
2335  {
2336    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell header"
2337                      " while parsing NK record at offset 0x%.8X.", offset);
2338    return NULL;
2339  }
2340
2341  /* A bit of validation before bothering to allocate memory */
2342  if((nk_header[0x0] != 'n') || (nk_header[0x1] != 'k'))
2343  {
2344    regfi_add_message(file, REGFI_MSG_WARN, "Magic number mismatch in parsing"
2345                      " NK record at offset 0x%.8X.", offset);
2346    return NULL;
2347  }
2348
2349  ret_val = talloc(NULL, REGFI_NK_REC);
2350  if(ret_val == NULL)
2351  {
2352    regfi_add_message(file, REGFI_MSG_ERROR, "Failed to allocate memory while"
2353                      " parsing NK record at offset 0x%.8X.", offset);
2354    return NULL;
2355  }
2356
2357  ret_val->values = NULL;
2358  ret_val->subkeys = NULL;
2359  ret_val->offset = offset;
2360  ret_val->cell_size = cell_length;
2361
2362  if(ret_val->cell_size > max_size)
2363    ret_val->cell_size = max_size & 0xFFFFFFF8;
2364  if((ret_val->cell_size < REGFI_NK_MIN_LENGTH) 
2365     || (strict && (ret_val->cell_size & 0x00000007) != 0))
2366  {
2367    regfi_add_message(file, REGFI_MSG_WARN, "A length check failed while"
2368                      " parsing NK record at offset 0x%.8X.", offset);
2369    talloc_free(ret_val);
2370    return NULL;
2371  }
2372
2373  ret_val->magic[0] = nk_header[0x0];
2374  ret_val->magic[1] = nk_header[0x1];
2375  ret_val->flags = SVAL(nk_header, 0x2);
2376 
2377  if((ret_val->flags & ~REGFI_NK_KNOWN_FLAGS) != 0)
2378  {
2379    regfi_add_message(file, REGFI_MSG_WARN, "Unknown key flags (0x%.4X) while"
2380                      " parsing NK record at offset 0x%.8X.", 
2381                      (ret_val->flags & ~REGFI_NK_KNOWN_FLAGS), offset);
2382  }
2383
2384  ret_val->mtime.low = IVAL(nk_header, 0x4);
2385  ret_val->mtime.high = IVAL(nk_header, 0x8);
2386  /* If the key is unallocated and the MTIME is earlier than Jan 1, 1990
2387   * or later than Jan 1, 2290, we consider this a bad key.  This helps
2388   * weed out some false positives during deleted data recovery.
2389   */
2390  if(unalloc
2391     && ((ret_val->mtime.high < REGFI_MTIME_MIN_HIGH
2392          && ret_val->mtime.low < REGFI_MTIME_MIN_LOW)
2393         || (ret_val->mtime.high > REGFI_MTIME_MAX_HIGH
2394             && ret_val->mtime.low > REGFI_MTIME_MAX_LOW)))
2395    return NULL;
2396
2397  ret_val->unknown1 = IVAL(nk_header, 0xC);
2398  ret_val->parent_off = IVAL(nk_header, 0x10);
2399  ret_val->num_subkeys = IVAL(nk_header, 0x14);
2400  ret_val->unknown2 = IVAL(nk_header, 0x18);
2401  ret_val->subkeys_off = IVAL(nk_header, 0x1C);
2402  ret_val->unknown3 = IVAL(nk_header, 0x20);
2403  ret_val->num_values = IVAL(nk_header, 0x24);
2404  ret_val->values_off = IVAL(nk_header, 0x28);
2405  ret_val->sk_off = IVAL(nk_header, 0x2C);
2406  ret_val->classname_off = IVAL(nk_header, 0x30);
2407
2408  ret_val->max_bytes_subkeyname = IVAL(nk_header, 0x34);
2409  ret_val->max_bytes_subkeyclassname = IVAL(nk_header, 0x38);
2410  ret_val->max_bytes_valuename = IVAL(nk_header, 0x3C);
2411  ret_val->max_bytes_value = IVAL(nk_header, 0x40);
2412  ret_val->unk_index = IVAL(nk_header, 0x44);
2413
2414  ret_val->name_length = SVAL(nk_header, 0x48);
2415  ret_val->classname_length = SVAL(nk_header, 0x4A);
2416  ret_val->keyname = NULL;
2417
2418  if(ret_val->name_length + REGFI_NK_MIN_LENGTH > ret_val->cell_size)
2419  {
2420    if(strict)
2421    {
2422      regfi_add_message(file, REGFI_MSG_ERROR, "Contents too large for cell"
2423                        " while parsing NK record at offset 0x%.8X.", offset);
2424      talloc_free(ret_val);
2425      return NULL;
2426    }
2427    else
2428      ret_val->name_length = ret_val->cell_size - REGFI_NK_MIN_LENGTH;
2429  }
2430  else if (unalloc)
2431  { /* Truncate cell_size if it's much larger than the apparent total record length. */
2432    /* Round up to the next multiple of 8 */
2433    length = (ret_val->name_length + REGFI_NK_MIN_LENGTH) & 0xFFFFFFF8;
2434    if(length < ret_val->name_length + REGFI_NK_MIN_LENGTH)
2435      length+=8;
2436
2437    /* If cell_size is still greater, truncate. */
2438    if(length < ret_val->cell_size)
2439      ret_val->cell_size = length;
2440  }
2441
2442  ret_val->keyname_raw = talloc_array(ret_val, uint8_t, ret_val->name_length);
2443  if(ret_val->keyname_raw == NULL)
2444  {
2445    talloc_free(ret_val);
2446    return NULL;
2447  }
2448
2449  /* Don't need to seek, should be at the right offset */
2450  length = ret_val->name_length;
2451  if((regfi_read(file->fd, (uint8_t*)ret_val->keyname_raw, &length) != 0)
2452     || length != ret_val->name_length)
2453  {
2454    regfi_add_message(file, REGFI_MSG_ERROR, "Failed to read key name"
2455                      " while parsing NK record at offset 0x%.8X.", offset);
2456    talloc_free(ret_val);
2457    return NULL;
2458  }
2459
2460  return ret_val;
2461}
2462
2463
2464uint8_t* regfi_parse_classname(REGFI_FILE* file, uint32_t offset, 
2465                             uint16_t* name_length, uint32_t max_size, bool strict)
2466{
2467  uint8_t* ret_val = NULL;
2468  uint32_t length;
2469  uint32_t cell_length;
2470  bool unalloc = false;
2471
2472  if(*name_length > 0 && offset != REGFI_OFFSET_NONE
2473     && (offset & 0x00000007) == 0)
2474  {
2475    if(!regfi_parse_cell(file->fd, offset, NULL, 0, &cell_length, &unalloc))
2476    {
2477      regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell header"
2478                        " while parsing class name at offset 0x%.8X.", offset);
2479        return NULL;
2480    }
2481
2482    if((cell_length & 0x0000007) != 0)
2483    {
2484      regfi_add_message(file, REGFI_MSG_ERROR, "Cell length not a multiple of 8"
2485                        " while parsing class name at offset 0x%.8X.", offset);
2486      return NULL;
2487    }
2488
2489    if(cell_length > max_size)
2490    {
2491      regfi_add_message(file, REGFI_MSG_WARN, "Cell stretches past hbin "
2492                        "boundary while parsing class name at offset 0x%.8X.",
2493                        offset);
2494      if(strict)
2495        return NULL;
2496      cell_length = max_size;
2497    }
2498
2499    if((cell_length - 4) < *name_length)
2500    {
2501      regfi_add_message(file, REGFI_MSG_WARN, "Class name is larger than"
2502                        " cell_length while parsing class name at offset"
2503                        " 0x%.8X.", offset);
2504      if(strict)
2505        return NULL;
2506      *name_length = cell_length - 4;
2507    }
2508   
2509    ret_val = talloc_array(NULL, uint8_t, *name_length);
2510    if(ret_val != NULL)
2511    {
2512      length = *name_length;
2513      if((regfi_read(file->fd, ret_val, &length) != 0)
2514         || length != *name_length)
2515      {
2516        regfi_add_message(file, REGFI_MSG_ERROR, "Could not read class name"
2517                          " while parsing class name at offset 0x%.8X.", offset);
2518        talloc_free(ret_val);
2519        return NULL;
2520      }
2521    }
2522  }
2523
2524  return ret_val;
2525}
2526
2527
2528/******************************************************************************
2529*******************************************************************************/
2530REGFI_VK_REC* regfi_parse_vk(REGFI_FILE* file, uint32_t offset, 
2531                             uint32_t max_size, bool strict)
2532{
2533  REGFI_VK_REC* ret_val;
2534  uint8_t vk_header[REGFI_VK_MIN_LENGTH];
2535  uint32_t raw_data_size, length, cell_length;
2536  bool unalloc = false;
2537
2538  if(!regfi_parse_cell(file->fd, offset, vk_header, REGFI_VK_MIN_LENGTH,
2539                       &cell_length, &unalloc))
2540  {
2541    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell header"
2542                      " while parsing VK record at offset 0x%.8X.", offset);
2543    return NULL;
2544  }
2545
2546  ret_val = talloc(NULL, REGFI_VK_REC);
2547  if(ret_val == NULL)
2548    return NULL;
2549
2550  ret_val->offset = offset;
2551  ret_val->cell_size = cell_length;
2552  ret_val->valuename = NULL;
2553  ret_val->valuename_raw = NULL;
2554 
2555  if(ret_val->cell_size > max_size)
2556    ret_val->cell_size = max_size & 0xFFFFFFF8;
2557  if((ret_val->cell_size < REGFI_VK_MIN_LENGTH) 
2558     || (ret_val->cell_size & 0x00000007) != 0)
2559  {
2560    regfi_add_message(file, REGFI_MSG_WARN, "Invalid cell size encountered"
2561                      " while parsing VK record at offset 0x%.8X.", offset);
2562    talloc_free(ret_val);
2563    return NULL;
2564  }
2565
2566  ret_val->magic[0] = vk_header[0x0];
2567  ret_val->magic[1] = vk_header[0x1];
2568  if((ret_val->magic[0] != 'v') || (ret_val->magic[1] != 'k'))
2569  {
2570    /* XXX: This does not account for deleted keys under Win2K which
2571     *      often have this (and the name length) overwritten with
2572     *      0xFFFF.
2573     */
2574    regfi_add_message(file, REGFI_MSG_WARN, "Magic number mismatch"
2575                      " while parsing VK record at offset 0x%.8X.", offset);
2576    talloc_free(ret_val);
2577    return NULL;
2578  }
2579
2580  ret_val->name_length = SVAL(vk_header, 0x2);
2581  raw_data_size = IVAL(vk_header, 0x4);
2582  ret_val->data_size = raw_data_size & ~REGFI_VK_DATA_IN_OFFSET;
2583  /* The data is typically stored in the offset if the size <= 4,
2584   * in which case this flag is set.
2585   */
2586  ret_val->data_in_offset = (bool)(raw_data_size & REGFI_VK_DATA_IN_OFFSET);
2587  ret_val->data_off = IVAL(vk_header, 0x8);
2588  ret_val->type = IVAL(vk_header, 0xC);
2589  ret_val->flags = SVAL(vk_header, 0x10);
2590  ret_val->unknown1 = SVAL(vk_header, 0x12);
2591
2592  if(ret_val->name_length > 0)
2593  {
2594    if(ret_val->name_length + REGFI_VK_MIN_LENGTH + 4 > ret_val->cell_size)
2595    {
2596      regfi_add_message(file, REGFI_MSG_WARN, "Name too long for remaining cell"
2597                        " space while parsing VK record at offset 0x%.8X.",
2598                        offset);
2599      if(strict)
2600      {
2601        talloc_free(ret_val);
2602        return NULL;
2603      }
2604      else
2605        ret_val->name_length = ret_val->cell_size - REGFI_VK_MIN_LENGTH - 4;
2606    }
2607
2608    /* Round up to the next multiple of 8 */
2609    cell_length = (ret_val->name_length + REGFI_VK_MIN_LENGTH + 4) & 0xFFFFFFF8;
2610    if(cell_length < ret_val->name_length + REGFI_VK_MIN_LENGTH + 4)
2611      cell_length+=8;
2612
2613    ret_val->valuename_raw = talloc_array(ret_val, uint8_t, ret_val->name_length);
2614    if(ret_val->valuename_raw == NULL)
2615    {
2616      talloc_free(ret_val);
2617      return NULL;
2618    }
2619
2620    length = ret_val->name_length;
2621    if((regfi_read(file->fd, (uint8_t*)ret_val->valuename_raw, &length) != 0)
2622       || length != ret_val->name_length)
2623    {
2624      regfi_add_message(file, REGFI_MSG_ERROR, "Could not read value name"
2625                        " while parsing VK record at offset 0x%.8X.", offset);
2626      talloc_free(ret_val);
2627      return NULL;
2628    }
2629  }
2630  else
2631    cell_length = REGFI_VK_MIN_LENGTH + 4;
2632
2633  if(unalloc)
2634  {
2635    /* If cell_size is still greater, truncate. */
2636    if(cell_length < ret_val->cell_size)
2637      ret_val->cell_size = cell_length;
2638  }
2639
2640  return ret_val;
2641}
2642
2643
2644/******************************************************************************
2645 *
2646 ******************************************************************************/
2647REGFI_BUFFER regfi_load_data(REGFI_FILE* file, uint32_t voffset,
2648                             uint32_t length, bool data_in_offset,
2649                             bool strict)
2650{
2651  REGFI_BUFFER ret_val;
2652  uint32_t cell_length, offset;
2653  int32_t max_size;
2654  bool unalloc;
2655 
2656  /* Microsoft's documentation indicates that "available memory" is
2657   * the limit on value sizes for the more recent registry format version.
2658   * This is not only annoying, but it's probably also incorrect, since clearly
2659   * value data sizes are limited to 2^31 (high bit used as a flag) and even
2660   * with big data records, the apparent max size is:
2661   *   16344 * 2^16 = 1071104040 (~1GB).
2662   *
2663   * We choose to limit it to 1M which was the limit in older versions and
2664   * should rarely be exceeded unless the file is corrupt or malicious.
2665   * For more info, see:
2666   *   http://msdn.microsoft.com/en-us/library/ms724872%28VS.85%29.aspx
2667   */
2668  /* XXX: add way to skip this check at user discression. */
2669  if(length > REGFI_VK_MAX_DATA_LENGTH)
2670  {
2671    regfi_add_message(file, REGFI_MSG_WARN, "Value data size %d larger than "
2672                      "%d, truncating...", length, REGFI_VK_MAX_DATA_LENGTH);
2673    length = REGFI_VK_MAX_DATA_LENGTH;
2674  }
2675
2676  if(data_in_offset)
2677    return regfi_parse_little_data(file, voffset, length, strict);
2678  else
2679  {
2680    offset = voffset + REGFI_REGF_SIZE;
2681    max_size = regfi_calc_maxsize(file, offset);
2682    if(max_size < 0)
2683    {
2684      regfi_add_message(file, REGFI_MSG_WARN, "Could not find HBIN for data"
2685                        " at offset 0x%.8X.", offset);
2686      goto fail;
2687    }
2688   
2689    if(!regfi_parse_cell(file->fd, offset, NULL, 0,
2690                         &cell_length, &unalloc))
2691    {
2692      regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell while"
2693                        " parsing data record at offset 0x%.8X.", offset);
2694      goto fail;
2695    }
2696
2697    if((cell_length & 0x00000007) != 0)
2698    {
2699      regfi_add_message(file, REGFI_MSG_WARN, "Cell length not multiple of 8"
2700                        " while parsing data record at offset 0x%.8X.",
2701                        offset);
2702      goto fail;
2703    }
2704
2705    if(cell_length > max_size)
2706    {
2707      regfi_add_message(file, REGFI_MSG_WARN, "Cell extends past HBIN boundary"
2708                        " while parsing data record at offset 0x%.8X.",
2709                        offset);
2710      goto fail;
2711    }
2712
2713    if(cell_length - 4 < length)
2714    {
2715      /* XXX: All big data records thus far have been 16 bytes long. 
2716       *      Should we check for this precise size instead of just
2717       *      relying upon the above check?
2718       */
2719      if (file->major_version >= 1 && file->minor_version >= 5)
2720      {
2721        /* Attempt to parse a big data record */
2722        return regfi_load_big_data(file, offset, length, cell_length, 
2723                                   NULL, strict);
2724      }
2725      else
2726      {
2727        regfi_add_message(file, REGFI_MSG_WARN, "Data length (0x%.8X) larger than"
2728                          " remaining cell length (0x%.8X)"
2729                          " while parsing data record at offset 0x%.8X.", 
2730                          length, cell_length - 4, offset);
2731        if(strict)
2732          goto fail;
2733        else
2734          length = cell_length - 4;
2735      }
2736    }
2737
2738    ret_val = regfi_parse_data(file, offset, length, strict);
2739  }
2740
2741  return ret_val;
2742
2743 fail:
2744  ret_val.buf = NULL;
2745  ret_val.len = 0;
2746  return ret_val;
2747}
2748
2749
2750/******************************************************************************
2751 * Parses the common case data records stored in a single cell.
2752 ******************************************************************************/
2753REGFI_BUFFER regfi_parse_data(REGFI_FILE* file, uint32_t offset,
2754                              uint32_t length, bool strict)
2755{
2756  REGFI_BUFFER ret_val;
2757  uint32_t read_length;
2758
2759  ret_val.buf = NULL;
2760  ret_val.len = 0;
2761 
2762  if(lseek(file->fd, offset+4, SEEK_SET) == -1)
2763  {
2764    regfi_add_message(file, REGFI_MSG_WARN, "Could not seek while "
2765                      "reading data at offset 0x%.8X.", offset);
2766    return ret_val;
2767  }
2768
2769  if((ret_val.buf = talloc_array(NULL, uint8_t, length)) == NULL)
2770    return ret_val;
2771  ret_val.len = length;
2772 
2773  read_length = length;
2774  if((regfi_read(file->fd, ret_val.buf, &read_length) != 0)
2775     || read_length != length)
2776  {
2777    regfi_add_message(file, REGFI_MSG_ERROR, "Could not read data block while"
2778                      " parsing data record at offset 0x%.8X.", offset);
2779    talloc_free(ret_val.buf);
2780    ret_val.buf = NULL;
2781    ret_val.buf = 0;
2782  }
2783
2784  return ret_val;
2785}
2786
2787
2788
2789/******************************************************************************
2790 *
2791 ******************************************************************************/
2792REGFI_BUFFER regfi_parse_little_data(REGFI_FILE* file, uint32_t voffset,
2793                                     uint32_t length, bool strict)
2794{
2795  REGFI_BUFFER ret_val;
2796  uint8_t i;
2797
2798  ret_val.buf = NULL;
2799  ret_val.len = 0;
2800
2801  if(length > 4)
2802  {
2803    regfi_add_message(file, REGFI_MSG_ERROR, "Data in offset but length > 4"
2804                      " while parsing data record. (voffset=0x%.8X, length=%d)",
2805                      voffset, length);
2806    return ret_val;
2807  }
2808
2809  if((ret_val.buf = talloc_array(NULL, uint8_t, length)) == NULL)
2810    return ret_val;
2811  ret_val.len = length;
2812 
2813  for(i = 0; i < length; i++)
2814    ret_val.buf[i] = (uint8_t)((voffset >> i*8) & 0xFF);
2815
2816  return ret_val;
2817}
2818
2819/******************************************************************************
2820*******************************************************************************/
2821REGFI_BUFFER regfi_parse_big_data_header(REGFI_FILE* file, uint32_t offset, 
2822                                         uint32_t max_size, bool strict)
2823{
2824  REGFI_BUFFER ret_val;
2825  uint32_t cell_length;
2826  bool unalloc;
2827
2828  /* XXX: do something with unalloc? */
2829  ret_val.buf = (uint8_t*)talloc_array(NULL, uint8_t, REGFI_BIG_DATA_MIN_LENGTH);
2830  if(ret_val.buf == NULL)
2831    goto fail;
2832
2833  if(REGFI_BIG_DATA_MIN_LENGTH > max_size)
2834  {
2835    regfi_add_message(file, REGFI_MSG_WARN, "Big data header exceeded max_size "
2836                      "while parsing big data header at offset 0x%.8X.",offset);
2837    goto fail;
2838  }
2839
2840  if(!regfi_parse_cell(file->fd, offset, ret_val.buf, REGFI_BIG_DATA_MIN_LENGTH,
2841                       &cell_length, &unalloc))
2842  {
2843    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell while"
2844                      " parsing big data header at offset 0x%.8X.", offset);
2845    goto fail;
2846  }
2847
2848  if((ret_val.buf[0] != 'd') || (ret_val.buf[1] != 'b'))
2849  {
2850    regfi_add_message(file, REGFI_MSG_WARN, "Unknown magic number"
2851                      " (0x%.2X, 0x%.2X) encountered while parsing"
2852                      " big data header at offset 0x%.8X.", 
2853                      ret_val.buf[0], ret_val.buf[1], offset);
2854    goto fail;
2855  }
2856
2857  ret_val.len = REGFI_BIG_DATA_MIN_LENGTH;
2858  return ret_val;
2859
2860 fail:
2861  if(ret_val.buf != NULL)
2862  {
2863    talloc_free(ret_val.buf);
2864    ret_val.buf = NULL;
2865  }
2866  ret_val.len = 0;
2867  return ret_val;
2868}
2869
2870
2871
2872/******************************************************************************
2873 *
2874 ******************************************************************************/
2875uint32_t* regfi_parse_big_data_indirect(REGFI_FILE* file, uint32_t offset,
2876                                      uint16_t num_chunks, bool strict)
2877{
2878  uint32_t* ret_val;
2879  uint32_t indirect_length;
2880  int32_t max_size;
2881  uint16_t i;
2882  bool unalloc;
2883
2884  /* XXX: do something with unalloc? */
2885
2886  max_size = regfi_calc_maxsize(file, offset);
2887  if((max_size < 0) || (num_chunks*sizeof(uint32_t) + 4 > max_size))
2888    return NULL;
2889
2890  ret_val = (uint32_t*)talloc_array(NULL, uint32_t, num_chunks);
2891  if(ret_val == NULL)
2892    goto fail;
2893
2894  if(!regfi_parse_cell(file->fd, offset, (uint8_t*)ret_val,
2895                       num_chunks*sizeof(uint32_t),
2896                       &indirect_length, &unalloc))
2897  {
2898    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell while"
2899                      " parsing big data indirect record at offset 0x%.8X.", 
2900                      offset);
2901    goto fail;
2902  }
2903
2904  /* Convert pointers to proper endianess, verify they are aligned. */
2905  for(i=0; i<num_chunks; i++)
2906  {
2907    ret_val[i] = IVAL(ret_val, i*sizeof(uint32_t));
2908    if((ret_val[i] & 0x00000007) != 0)
2909      goto fail;
2910  }
2911 
2912  return ret_val;
2913
2914 fail:
2915  if(ret_val != NULL)
2916    talloc_free(ret_val);
2917  return NULL;
2918}
2919
2920
2921/******************************************************************************
2922 * Arguments:
2923 *  file       --
2924 *  offsets    -- list of virtual offsets.
2925 *  num_chunks --
2926 *  strict     --
2927 *
2928 * Returns:
2929 *  A range_list with physical offsets and complete lengths
2930 *  (including cell headers) of associated cells. 
2931 *  No data in range_list elements.
2932 ******************************************************************************/
2933range_list* regfi_parse_big_data_cells(REGFI_FILE* file, uint32_t* offsets,
2934                                       uint16_t num_chunks, bool strict)
2935{
2936  uint32_t cell_length, chunk_offset;
2937  range_list* ret_val;
2938  uint16_t i;
2939  bool unalloc;
2940 
2941  /* XXX: do something with unalloc? */
2942  ret_val = range_list_new();
2943  if(ret_val == NULL)
2944    goto fail;
2945 
2946  for(i=0; i<num_chunks; i++)
2947  {
2948    chunk_offset = offsets[i]+REGFI_REGF_SIZE;
2949    if(!regfi_parse_cell(file->fd, chunk_offset, NULL, 0,
2950                         &cell_length, &unalloc))
2951    {
2952      regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell while"
2953                        " parsing big data chunk at offset 0x%.8X.", 
2954                        chunk_offset);
2955      goto fail;
2956    }
2957
2958    if(!range_list_add(ret_val, chunk_offset, cell_length, NULL))
2959      goto fail;
2960  }
2961
2962  return ret_val;
2963
2964 fail:
2965  if(ret_val != NULL)
2966    range_list_free(ret_val);
2967  return NULL;
2968}
2969
2970
2971/******************************************************************************
2972*******************************************************************************/
2973REGFI_BUFFER regfi_load_big_data(REGFI_FILE* file, 
2974                                 uint32_t offset, uint32_t data_length, 
2975                                 uint32_t cell_length, range_list* used_ranges,
2976                                 bool strict)
2977{
2978  REGFI_BUFFER ret_val;
2979  uint16_t num_chunks, i;
2980  uint32_t read_length, data_left, tmp_len, indirect_offset;
2981  uint32_t* indirect_ptrs = NULL;
2982  REGFI_BUFFER bd_header;
2983  range_list* bd_cells = NULL;
2984  const range_list_element* cell_info;
2985
2986  ret_val.buf = NULL;
2987
2988  /* XXX: Add better error/warning messages */
2989
2990  bd_header = regfi_parse_big_data_header(file, offset, cell_length, strict);
2991  if(bd_header.buf == NULL)
2992    goto fail;
2993
2994  /* Keep track of used space for use by reglookup-recover */
2995  if(used_ranges != NULL)
2996    if(!range_list_add(used_ranges, offset, cell_length, NULL))
2997      goto fail;
2998
2999  num_chunks = SVAL(bd_header.buf, 0x2);
3000  indirect_offset = IVAL(bd_header.buf, 0x4) + REGFI_REGF_SIZE;
3001  talloc_free(bd_header.buf);
3002
3003  indirect_ptrs = regfi_parse_big_data_indirect(file, indirect_offset,
3004                                                num_chunks, strict);
3005  if(indirect_ptrs == NULL)
3006    goto fail;
3007
3008  if(used_ranges != NULL)
3009    if(!range_list_add(used_ranges, indirect_offset, num_chunks*4+4, NULL))
3010      goto fail;
3011 
3012  if((ret_val.buf = talloc_array(NULL, uint8_t, data_length)) == NULL)
3013    goto fail;
3014  data_left = data_length;
3015
3016  bd_cells = regfi_parse_big_data_cells(file, indirect_ptrs, num_chunks, strict);
3017  if(bd_cells == NULL)
3018    goto fail;
3019
3020  talloc_free(indirect_ptrs);
3021  indirect_ptrs = NULL;
3022 
3023  for(i=0; (i<num_chunks) && (data_left>0); i++)
3024  {
3025    cell_info = range_list_get(bd_cells, i);
3026    if(cell_info == NULL)
3027      goto fail;
3028
3029    /* XXX: This should be "cell_info->length-4" to account for the 4 byte cell
3030     *      length.  However, it has been observed that some (all?) chunks
3031     *      have an additional 4 bytes of 0 at the end of their cells that
3032     *      isn't part of the data, so we're trimming that off too.
3033     *      Perhaps it's just an 8 byte alignment requirement...
3034     */
3035    if(cell_info->length - 8 >= data_left)
3036    {
3037      if(i+1 != num_chunks)
3038      {
3039        regfi_add_message(file, REGFI_MSG_WARN, "Left over chunks detected "
3040                          "while constructing big data at offset 0x%.8X "
3041                          "(chunk offset 0x%.8X).", offset, cell_info->offset);
3042      }
3043      read_length = data_left;
3044    }
3045    else
3046      read_length = cell_info->length - 8;
3047
3048
3049    if(read_length > regfi_calc_maxsize(file, cell_info->offset))
3050    {
3051      regfi_add_message(file, REGFI_MSG_WARN, "A chunk exceeded the maxsize "
3052                        "while constructing big data at offset 0x%.8X "
3053                        "(chunk offset 0x%.8X).", offset, cell_info->offset);
3054      goto fail;
3055    }
3056
3057    if(lseek(file->fd, cell_info->offset+sizeof(uint32_t), SEEK_SET) == -1)
3058    {
3059      regfi_add_message(file, REGFI_MSG_WARN, "Could not seek to chunk while "
3060                        "constructing big data at offset 0x%.8X "
3061                        "(chunk offset 0x%.8X).", offset, cell_info->offset);
3062      goto fail;
3063    }
3064
3065    tmp_len = read_length;
3066    if(regfi_read(file->fd, ret_val.buf+(data_length-data_left), 
3067                  &read_length) != 0 || (read_length != tmp_len))
3068    {
3069      regfi_add_message(file, REGFI_MSG_WARN, "Could not read data chunk while"
3070                        " constructing big data at offset 0x%.8X"
3071                        " (chunk offset 0x%.8X).", offset, cell_info->offset);
3072      goto fail;
3073    }
3074
3075    if(used_ranges != NULL)
3076      if(!range_list_add(used_ranges, cell_info->offset,cell_info->length,NULL))
3077        goto fail;
3078
3079    data_left -= read_length;
3080  }
3081  range_list_free(bd_cells);
3082
3083  ret_val.len = data_length-data_left;
3084  return ret_val;
3085
3086 fail:
3087  if(ret_val.buf != NULL)
3088    talloc_free(ret_val.buf);
3089  if(indirect_ptrs != NULL)
3090    talloc_free(indirect_ptrs);
3091  if(bd_cells != NULL)
3092    range_list_free(bd_cells);
3093  ret_val.buf = NULL;
3094  ret_val.len = 0;
3095  return ret_val;
3096}
3097
3098
3099range_list* regfi_parse_unalloc_cells(REGFI_FILE* file)
3100{
3101  range_list* ret_val;
3102  REGFI_HBIN* hbin;
3103  const range_list_element* hbins_elem;
3104  uint32_t i, num_hbins, curr_off, cell_len;
3105  bool is_unalloc;
3106
3107  ret_val = range_list_new();
3108  if(ret_val == NULL)
3109    return NULL;
3110
3111  num_hbins = range_list_size(file->hbins);
3112  for(i=0; i<num_hbins; i++)
3113  {
3114    hbins_elem = range_list_get(file->hbins, i);
3115    if(hbins_elem == NULL)
3116      break;
3117    hbin = (REGFI_HBIN*)hbins_elem->data;
3118
3119    curr_off = REGFI_HBIN_HEADER_SIZE;
3120    while(curr_off < hbin->block_size)
3121    {
3122      if(!regfi_parse_cell(file->fd, hbin->file_off+curr_off, NULL, 0,
3123                           &cell_len, &is_unalloc))
3124        break;
3125     
3126      if((cell_len == 0) || ((cell_len & 0x00000007) != 0))
3127      {
3128        regfi_add_message(file, REGFI_MSG_ERROR, "Bad cell length encountered"
3129                          " while parsing unallocated cells at offset 0x%.8X.",
3130                          hbin->file_off+curr_off);
3131        break;
3132      }
3133
3134      /* for some reason the record_size of the last record in
3135         an hbin block can extend past the end of the block
3136         even though the record fits within the remaining
3137         space....aaarrrgggghhhhhh */ 
3138      if(curr_off + cell_len >= hbin->block_size)
3139        cell_len = hbin->block_size - curr_off;
3140     
3141      if(is_unalloc)
3142        range_list_add(ret_val, hbin->file_off+curr_off, 
3143                       cell_len, NULL);
3144     
3145      curr_off = curr_off+cell_len;
3146    }
3147  }
3148
3149  return ret_val;
3150}
3151
3152
3153/* From lib/time.c */
3154
3155/****************************************************************************
3156 Put a 8 byte filetime from a time_t
3157 This takes real GMT as input and converts to kludge-GMT
3158****************************************************************************/
3159void regfi_unix2nt_time(REGFI_NTTIME *nt, time_t t)
3160{
3161  double d;
3162 
3163  if (t==0) 
3164  {
3165    nt->low = 0;
3166    nt->high = 0;
3167    return;
3168  }
3169 
3170  if (t == TIME_T_MAX) 
3171  {
3172    nt->low = 0xffffffff;
3173    nt->high = 0x7fffffff;
3174    return;
3175  }             
3176 
3177  if (t == -1) 
3178  {
3179    nt->low = 0xffffffff;
3180    nt->high = 0xffffffff;
3181    return;
3182  }             
3183 
3184  /* this converts GMT to kludge-GMT */
3185  /* XXX: This was removed due to difficult dependency requirements. 
3186   *      So far, times appear to be correct without this adjustment, but
3187   *      that may be proven wrong with adequate testing.
3188   */
3189  /* t -= TimeDiff(t) - get_serverzone(); */
3190 
3191  d = (double)(t);
3192  d += TIME_FIXUP_CONSTANT;
3193  d *= 1.0e7;
3194 
3195  nt->high = (uint32_t)(d * (1.0/(4.0*(double)(1<<30))));
3196  nt->low  = (uint32_t)(d - ((double)nt->high)*4.0*(double)(1<<30));
3197}
3198
3199
3200/****************************************************************************
3201 Interpret an 8 byte "filetime" structure to a time_t
3202 It's originally in "100ns units since jan 1st 1601"
3203
3204 An 8 byte value of 0xffffffffffffffff will be returned as (time_t)0.
3205
3206 It appears to be kludge-GMT (at least for file listings). This means
3207 its the GMT you get by taking a localtime and adding the
3208 serverzone. This is NOT the same as GMT in some cases. This routine
3209 converts this to real GMT.
3210****************************************************************************/
3211time_t regfi_nt2unix_time(const REGFI_NTTIME* nt)
3212{
3213  double d;
3214  time_t ret;
3215  /* The next two lines are a fix needed for the
3216     broken SCO compiler. JRA. */
3217  time_t l_time_min = TIME_T_MIN;
3218  time_t l_time_max = TIME_T_MAX;
3219 
3220  if (nt->high == 0 || (nt->high == 0xffffffff && nt->low == 0xffffffff))
3221    return(0);
3222 
3223  d = ((double)nt->high)*4.0*(double)(1<<30);
3224  d += (nt->low&0xFFF00000);
3225  d *= 1.0e-7;
3226 
3227  /* now adjust by 369 years to make the secs since 1970 */
3228  d -= TIME_FIXUP_CONSTANT;
3229 
3230  if (d <= l_time_min)
3231    return (l_time_min);
3232 
3233  if (d >= l_time_max)
3234    return (l_time_max);
3235 
3236  ret = (time_t)(d+0.5);
3237 
3238  /* this takes us from kludge-GMT to real GMT */
3239  /* XXX: This was removed due to difficult dependency requirements. 
3240   *      So far, times appear to be correct without this adjustment, but
3241   *      that may be proven wrong with adequate testing.
3242   */
3243  /*
3244    ret -= get_serverzone();
3245    ret += LocTimeDiff(ret);
3246  */
3247
3248  return(ret);
3249}
3250
3251/* End of stuff from lib/time.c */
Note: See TracBrowser for help on using the repository browser.