source: trunk/lib/regfi.c @ 172

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

reorganized name interpretation code to correct issues in reglookup-recover

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