source: trunk/lib/regfi.c @ 158

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

simplified root key search

moved classname parsing up to regfi_load_key

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