source: trunk/lib/regfi.c @ 178

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

reworked I/O to use callback functions

fixed a bug in mtime validation and consolidated time formatting code

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