source: trunk/lib/regfi.c @ 160

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

reorganized classname parsing and interpretation code

  • Property svn:keywords set to Id
File size: 81.1 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 160 2009-12-07 01:00:58Z 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  int32 max_size;
961
962  max_size = regfi_calc_maxsize(file, offset);
963  if(max_size < 0)
964    return NULL;
965 
966  ret_val = regfi_parse_vk(file, offset, max_size, strict);
967  if(ret_val == NULL)
968    return NULL;
969
970  /* XXX: convert valuename to proper encoding if necessary */
971
972  return ret_val;
973}
974
975
976/******************************************************************************
977 * If !strict, the list may contain NULLs, VK records may point to NULL.
978 ******************************************************************************/
979REGFI_VALUE_LIST* regfi_load_valuelist(REGFI_FILE* file, uint32 offset, 
980                                       uint32 num_values, uint32 max_size,
981                                       bool strict)
982{
983  uint32 usable_num_values;
984
985  if((num_values+1) * sizeof(uint32) > max_size)
986  {
987    regfi_add_message(file, REGFI_MSG_WARN, "Number of values indicated by"
988                      " parent key (%d) would cause cell to straddle HBIN"
989                      " boundary while loading value list at offset"
990                      " 0x%.8X.", num_values, offset);
991    if(strict)
992      return NULL;
993    usable_num_values = max_size/sizeof(uint32) - sizeof(uint32);
994  }
995  else
996    usable_num_values = num_values;
997
998  return regfi_parse_valuelist(file, offset, usable_num_values, strict);
999}
1000
1001
1002
1003/******************************************************************************
1004 *
1005 ******************************************************************************/
1006REGFI_NK_REC* regfi_load_key(REGFI_FILE* file, uint32 offset, bool strict)
1007{
1008  REGFI_NK_REC* nk;
1009  uint32 off;
1010  int32 max_size;
1011
1012  max_size = regfi_calc_maxsize(file, offset);
1013  if (max_size < 0) 
1014    return NULL;
1015
1016  /* get the initial nk record */
1017  if((nk = regfi_parse_nk(file, offset, max_size, true)) == NULL)
1018  {
1019    regfi_add_message(file, REGFI_MSG_ERROR, "Could not load NK record at"
1020                      " offset 0x%.8X.", offset);
1021    return NULL;
1022  }
1023
1024  /* get value list */
1025  if(nk->num_values && (nk->values_off!=REGFI_OFFSET_NONE)) 
1026  {
1027    off = nk->values_off + REGFI_REGF_SIZE;
1028    max_size = regfi_calc_maxsize(file, off);
1029    if(max_size < 0)
1030    {
1031      if(strict)
1032      {
1033        regfi_free_key(nk);
1034        return NULL;
1035      }
1036      else
1037        nk->values = NULL;
1038
1039    }
1040    else
1041    {
1042      nk->values = regfi_load_valuelist(file, off, nk->num_values, 
1043                                        max_size, true);
1044      if(nk->values == NULL)
1045      {
1046        regfi_add_message(file, REGFI_MSG_WARN, "Could not load value list"
1047                          " for NK record at offset 0x%.8X.", offset);
1048        if(strict)
1049        {
1050          regfi_free_key(nk);
1051          return NULL;
1052        }
1053      }
1054      talloc_steal(nk, nk->values);
1055    }
1056  }
1057
1058  /* now get subkey list */
1059  if(nk->num_subkeys && (nk->subkeys_off != REGFI_OFFSET_NONE)) 
1060  {
1061    off = nk->subkeys_off + REGFI_REGF_SIZE;
1062    max_size = regfi_calc_maxsize(file, off);
1063    if(max_size < 0) 
1064    {
1065      if(strict)
1066      {
1067        regfi_free_key(nk);
1068        return NULL;
1069      }
1070      else
1071        nk->subkeys = NULL;
1072    }
1073    else
1074    {
1075      nk->subkeys = regfi_load_subkeylist(file, off, nk->num_subkeys,
1076                                          max_size, true);
1077
1078      if(nk->subkeys == NULL)
1079      {
1080        regfi_add_message(file, REGFI_MSG_WARN, "Could not load subkey list"
1081                          " while parsing NK record at offset 0x%.8X.", offset);
1082        nk->num_subkeys = 0;
1083      }
1084      talloc_steal(nk, nk->subkeys);
1085    }
1086  }
1087
1088  return nk;
1089}
1090
1091
1092/******************************************************************************
1093 ******************************************************************************/
1094const REGFI_SK_REC* regfi_load_sk(REGFI_FILE* file, uint32 offset, bool strict)
1095{
1096  REGFI_SK_REC* ret_val = NULL;
1097  int32 max_size;
1098  void* failure_ptr = NULL;
1099 
1100  /* First look if we have already parsed it */
1101  ret_val = (REGFI_SK_REC*)lru_cache_find(file->sk_cache, &offset, 4);
1102
1103  /* Bail out if we have previously cached a parse failure at this offset. */
1104  if(ret_val == (void*)REGFI_OFFSET_NONE)
1105    return NULL;
1106
1107  if(ret_val == NULL)
1108  {
1109    max_size = regfi_calc_maxsize(file, offset);
1110    if(max_size < 0)
1111      return NULL;
1112
1113    ret_val = regfi_parse_sk(file, offset, max_size, strict);
1114    if(ret_val == NULL)
1115    { /* Cache the parse failure and bail out. */
1116      failure_ptr = talloc(NULL, uint32_t);
1117      if(failure_ptr == NULL)
1118        return NULL;
1119      *(uint32_t*)failure_ptr = REGFI_OFFSET_NONE;
1120      lru_cache_update(file->sk_cache, &offset, 4, failure_ptr);
1121      return NULL;
1122    }
1123
1124    lru_cache_update(file->sk_cache, &offset, 4, ret_val);
1125  }
1126
1127  return ret_val;
1128}
1129
1130
1131
1132/******************************************************************************
1133 ******************************************************************************/
1134REGFI_NK_REC* regfi_find_root_nk(REGFI_FILE* file, const REGFI_HBIN* hbin)
1135{
1136  REGFI_NK_REC* nk = NULL;
1137  uint32 cell_length;
1138  uint32 cur_offset = hbin->file_off+REGFI_HBIN_HEADER_SIZE;
1139  uint32 hbin_end = hbin->file_off+hbin->block_size;
1140  bool unalloc;
1141
1142  while(cur_offset < hbin_end)
1143  {
1144    if(!regfi_parse_cell(file->fd, cur_offset, NULL, 0, &cell_length, &unalloc))
1145    {
1146      regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell at offset"
1147                        " 0x%.8X while searching for root key.", cur_offset);
1148      return NULL;
1149    }
1150   
1151    if(!unalloc)
1152    {
1153      nk = regfi_load_key(file, cur_offset, true);
1154      if(nk != NULL)
1155      {
1156        if(nk->key_type & REGFI_NK_FLAG_ROOT)
1157          return nk;
1158      }
1159    }
1160
1161    cur_offset += cell_length;
1162  }
1163
1164  return NULL;
1165}
1166
1167
1168/*******************************************************************
1169 * Open the registry file and then read in the REGF block to get the
1170 * first hbin offset.
1171 *******************************************************************/
1172REGFI_FILE* regfi_open(const char* filename)
1173{
1174  struct stat sbuf;
1175  REGFI_FILE* rb;
1176  REGFI_HBIN* hbin = NULL;
1177  uint32 hbin_off, file_length, cache_secret;
1178  int fd;
1179  bool rla;
1180
1181  /* open an existing file */
1182  if ((fd = open(filename, REGFI_OPEN_FLAGS)) == -1)
1183  {
1184    /* fprintf(stderr, "regfi_open: failure to open %s (%s)\n", filename, strerror(errno));*/
1185    return NULL;
1186  }
1187 
1188  /* Determine file length.  Must be at least big enough
1189   * for the header and one hbin.
1190   */
1191  if (fstat(fd, &sbuf) == -1)
1192    return NULL;
1193  file_length = sbuf.st_size;
1194  if(file_length < REGFI_REGF_SIZE+REGFI_HBIN_ALLOC)
1195    return NULL;
1196
1197  /* read in an existing file */
1198  if ((rb = regfi_parse_regf(fd, true)) == NULL) 
1199  {
1200    /* fprintf(stderr, "regfi_open: Failed to read initial REGF block\n"); */
1201    close(fd);
1202    return NULL;
1203  }
1204  rb->file_length = file_length; 
1205
1206  rb->hbins = range_list_new();
1207  if(rb->hbins == NULL)
1208  {
1209    /* fprintf(stderr, "regfi_open: Failed to create HBIN list.\n"); */
1210    close(fd);
1211    talloc_free(rb);
1212    return NULL;
1213  }
1214  talloc_steal(rb, rb->hbins);
1215
1216  rla = true;
1217  hbin_off = REGFI_REGF_SIZE;
1218  hbin = regfi_parse_hbin(rb, hbin_off, true);
1219  while(hbin && rla)
1220  {
1221    rla = range_list_add(rb->hbins, hbin->file_off, hbin->block_size, hbin);
1222    if(rla)
1223      talloc_steal(rb->hbins, hbin);
1224    hbin_off = hbin->file_off + hbin->block_size;
1225    hbin = regfi_parse_hbin(rb, hbin_off, true);
1226  }
1227
1228  /* This secret isn't very secret, but we don't need a good one.  This
1229   * secret is just designed to prevent someone from trying to blow our
1230   * caching and make things slow.
1231   */
1232  cache_secret = 0x15DEAD05^time(NULL)^(getpid()<<16);
1233
1234  /* Cache an unlimited number of SK records.  Typically there are very few. */
1235  rb->sk_cache = lru_cache_create_ctx(rb, 0, cache_secret, true);
1236
1237  /* Default message mask */
1238  rb->msg_mask = REGFI_MSG_ERROR|REGFI_MSG_WARN;
1239
1240  /* success */
1241  return rb;
1242}
1243
1244
1245/******************************************************************************
1246 ******************************************************************************/
1247int regfi_close(REGFI_FILE *file)
1248{
1249  int fd;
1250
1251  /* nothing to do if there is no open file */
1252  if ((file == NULL) || (file->fd == -1))
1253    return 0;
1254
1255  fd = file->fd;
1256  file->fd = -1;
1257
1258  range_list_free(file->hbins);
1259
1260  if(file->sk_cache != NULL)
1261    lru_cache_destroy(file->sk_cache);
1262
1263  talloc_free(file);
1264  return close(fd);
1265}
1266
1267
1268/******************************************************************************
1269 * First checks the offset given by the file header, then checks the
1270 * rest of the file if that fails.
1271 ******************************************************************************/
1272REGFI_NK_REC* regfi_rootkey(REGFI_FILE *file)
1273{
1274  REGFI_NK_REC* nk = NULL;
1275  REGFI_HBIN* hbin;
1276  uint32 root_offset, i, num_hbins;
1277 
1278  if(!file)
1279    return NULL;
1280
1281  root_offset = file->root_cell+REGFI_REGF_SIZE;
1282  nk = regfi_load_key(file, root_offset, true);
1283  if(nk != NULL)
1284  {
1285    if(nk->key_type & REGFI_NK_FLAG_ROOT)
1286      return nk;
1287  }
1288
1289  regfi_add_message(file, REGFI_MSG_WARN, "File header indicated root key at"
1290                    " location 0x%.8X, but no root key found."
1291                    " Searching rest of file...", root_offset);
1292 
1293  /* If the file header gives bad info, scan through the file one HBIN
1294   * block at a time looking for an NK record with a root key type.
1295   */
1296  num_hbins = range_list_size(file->hbins);
1297  for(i=0; i < num_hbins && nk == NULL; i++)
1298  {
1299    hbin = (REGFI_HBIN*)range_list_get(file->hbins, i)->data;
1300    nk = regfi_find_root_nk(file, hbin);
1301  }
1302
1303  return nk;
1304}
1305
1306
1307/******************************************************************************
1308 *****************************************************************************/
1309void regfi_free_key(REGFI_NK_REC* nk)
1310{
1311  regfi_subkeylist_free(nk->subkeys);
1312  talloc_free(nk);
1313}
1314
1315
1316/******************************************************************************
1317 *****************************************************************************/
1318void regfi_free_value(REGFI_VK_REC* vk)
1319{
1320  talloc_free(vk);
1321}
1322
1323
1324/******************************************************************************
1325 *****************************************************************************/
1326void regfi_subkeylist_free(REGFI_SUBKEY_LIST* list)
1327{
1328  if(list != NULL)
1329  {
1330    talloc_free(list);
1331  }
1332}
1333
1334
1335/******************************************************************************
1336 *****************************************************************************/
1337REGFI_ITERATOR* regfi_iterator_new(REGFI_FILE* file, uint32 output_encoding)
1338{
1339  REGFI_NK_REC* root;
1340  REGFI_ITERATOR* ret_val = talloc(NULL, REGFI_ITERATOR);
1341  if(ret_val == NULL)
1342    return NULL;
1343
1344  root = regfi_rootkey(file);
1345  if(root == NULL)
1346  {
1347    talloc_free(ret_val);
1348    return NULL;
1349  }
1350
1351  ret_val->key_positions = void_stack_new(REGFI_MAX_DEPTH);
1352  if(ret_val->key_positions == NULL)
1353  {
1354    talloc_free(ret_val);
1355    return NULL;
1356  }
1357  talloc_steal(ret_val, ret_val->key_positions);
1358
1359  ret_val->f = file;
1360  ret_val->cur_key = root;
1361  ret_val->cur_subkey = 0;
1362  ret_val->cur_value = 0;
1363 
1364  switch (output_encoding)
1365  {
1366  case 0:
1367  case 1:
1368    ret_val->string_encoding = "US-ASCII//TRANSLIT";
1369    break;
1370  case 2:
1371    ret_val->string_encoding = "UTF-8//TRANSLIT";
1372    break;
1373  default:
1374    talloc_free(ret_val);
1375    return NULL;
1376  }
1377 
1378  return ret_val;
1379}
1380
1381
1382/******************************************************************************
1383 *****************************************************************************/
1384void regfi_iterator_free(REGFI_ITERATOR* i)
1385{
1386  talloc_free(i);
1387}
1388
1389
1390
1391/******************************************************************************
1392 *****************************************************************************/
1393/* XXX: some way of indicating reason for failure should be added. */
1394bool regfi_iterator_down(REGFI_ITERATOR* i)
1395{
1396  REGFI_NK_REC* subkey;
1397  REGFI_ITER_POSITION* pos;
1398
1399  pos = talloc(i->key_positions, REGFI_ITER_POSITION);
1400  if(pos == NULL)
1401    return false;
1402
1403  subkey = (REGFI_NK_REC*)regfi_iterator_cur_subkey(i);
1404  if(subkey == NULL)
1405  {
1406    talloc_free(pos);
1407    return false;
1408  }
1409
1410  pos->nk = i->cur_key;
1411  pos->cur_subkey = i->cur_subkey;
1412  if(!void_stack_push(i->key_positions, pos))
1413  {
1414    talloc_free(pos);
1415    regfi_free_key(subkey);
1416    return false;
1417  }
1418  talloc_steal(i, subkey);
1419
1420  i->cur_key = subkey;
1421  i->cur_subkey = 0;
1422  i->cur_value = 0;
1423
1424  return true;
1425}
1426
1427
1428/******************************************************************************
1429 *****************************************************************************/
1430bool regfi_iterator_up(REGFI_ITERATOR* i)
1431{
1432  REGFI_ITER_POSITION* pos;
1433
1434  pos = (REGFI_ITER_POSITION*)void_stack_pop(i->key_positions);
1435  if(pos == NULL)
1436    return false;
1437
1438  regfi_free_key(i->cur_key);
1439  i->cur_key = pos->nk;
1440  i->cur_subkey = pos->cur_subkey;
1441  i->cur_value = 0;
1442  talloc_free(pos);
1443
1444  return true;
1445}
1446
1447
1448/******************************************************************************
1449 *****************************************************************************/
1450bool regfi_iterator_to_root(REGFI_ITERATOR* i)
1451{
1452  while(regfi_iterator_up(i))
1453    continue;
1454
1455  return true;
1456}
1457
1458
1459/******************************************************************************
1460 *****************************************************************************/
1461bool regfi_iterator_find_subkey(REGFI_ITERATOR* i, const char* subkey_name)
1462{
1463  REGFI_NK_REC* subkey;
1464  bool found = false;
1465  uint32 old_subkey = i->cur_subkey;
1466
1467  if(subkey_name == NULL)
1468    return false;
1469
1470  /* XXX: this alloc/free of each sub key might be a bit excessive */
1471  subkey = (REGFI_NK_REC*)regfi_iterator_first_subkey(i);
1472  while((subkey != NULL) && (found == false))
1473  {
1474    if(subkey->keyname != NULL 
1475       && strcasecmp(subkey->keyname, subkey_name) == 0)
1476      found = true;
1477    else
1478    {
1479      regfi_free_key(subkey);
1480      subkey = (REGFI_NK_REC*)regfi_iterator_next_subkey(i);
1481    }
1482  }
1483
1484  if(found == false)
1485  {
1486    i->cur_subkey = old_subkey;
1487    return false;
1488  }
1489
1490  regfi_free_key(subkey);
1491  return true;
1492}
1493
1494
1495/******************************************************************************
1496 *****************************************************************************/
1497bool regfi_iterator_walk_path(REGFI_ITERATOR* i, const char** path)
1498{
1499  uint32 x;
1500  if(path == NULL)
1501    return false;
1502
1503  for(x=0; 
1504      ((path[x] != NULL) && regfi_iterator_find_subkey(i, path[x])
1505       && regfi_iterator_down(i));
1506      x++)
1507  { continue; }
1508
1509  if(path[x] == NULL)
1510    return true;
1511 
1512  /* XXX: is this the right number of times? */
1513  for(; x > 0; x--)
1514    regfi_iterator_up(i);
1515 
1516  return false;
1517}
1518
1519
1520/******************************************************************************
1521 *****************************************************************************/
1522const REGFI_NK_REC* regfi_iterator_cur_key(REGFI_ITERATOR* i)
1523{
1524  return i->cur_key;
1525}
1526
1527
1528/******************************************************************************
1529 *****************************************************************************/
1530const REGFI_SK_REC* regfi_iterator_cur_sk(REGFI_ITERATOR* i)
1531{
1532  if(i->cur_key == NULL || i->cur_key->sk_off == REGFI_OFFSET_NONE)
1533    return NULL;
1534
1535  return regfi_load_sk(i->f, i->cur_key->sk_off + REGFI_REGF_SIZE, true);
1536}
1537
1538
1539/******************************************************************************
1540 *****************************************************************************/
1541REGFI_NK_REC* regfi_iterator_first_subkey(REGFI_ITERATOR* i)
1542{
1543  i->cur_subkey = 0;
1544  return regfi_iterator_cur_subkey(i);
1545}
1546
1547
1548/******************************************************************************
1549 *****************************************************************************/
1550REGFI_NK_REC* regfi_iterator_cur_subkey(REGFI_ITERATOR* i)
1551{
1552  uint32 nk_offset;
1553
1554  /* see if there is anything left to report */
1555  if (!(i->cur_key) || (i->cur_key->subkeys_off==REGFI_OFFSET_NONE)
1556      || (i->cur_subkey >= i->cur_key->num_subkeys))
1557    return NULL;
1558
1559  nk_offset = i->cur_key->subkeys->elements[i->cur_subkey].offset;
1560
1561  return regfi_load_key(i->f, nk_offset+REGFI_REGF_SIZE, true);
1562}
1563
1564
1565/******************************************************************************
1566 *****************************************************************************/
1567/* XXX: some way of indicating reason for failure should be added. */
1568REGFI_NK_REC* regfi_iterator_next_subkey(REGFI_ITERATOR* i)
1569{
1570  REGFI_NK_REC* subkey;
1571
1572  i->cur_subkey++;
1573  subkey = regfi_iterator_cur_subkey(i);
1574
1575  if(subkey == NULL)
1576    i->cur_subkey--;
1577
1578  return subkey;
1579}
1580
1581
1582/******************************************************************************
1583 *****************************************************************************/
1584bool regfi_iterator_find_value(REGFI_ITERATOR* i, const char* value_name)
1585{
1586  REGFI_VK_REC* cur;
1587  bool found = false;
1588
1589  /* XXX: cur->valuename can be NULL in the registry. 
1590   *      Should we allow for a way to search for that?
1591   */
1592  if(value_name == NULL)
1593    return false;
1594
1595  cur = regfi_iterator_first_value(i);
1596  while((cur != NULL) && (found == false))
1597  {
1598    if((cur->valuename != NULL)
1599       && (strcasecmp(cur->valuename, value_name) == 0))
1600      found = true;
1601    else
1602    {
1603      regfi_free_value(cur);
1604      cur = regfi_iterator_next_value(i);
1605    }
1606  }
1607
1608  return found;
1609}
1610
1611
1612/******************************************************************************
1613 *****************************************************************************/
1614REGFI_VK_REC* regfi_iterator_first_value(REGFI_ITERATOR* i)
1615{
1616  i->cur_value = 0;
1617  return regfi_iterator_cur_value(i);
1618}
1619
1620
1621/******************************************************************************
1622 *****************************************************************************/
1623REGFI_VK_REC* regfi_iterator_cur_value(REGFI_ITERATOR* i)
1624{
1625  REGFI_VK_REC* ret_val = NULL;
1626  uint32 voffset;
1627
1628  if(i->cur_key->values != NULL && i->cur_key->values->elements != NULL)
1629  {
1630    if(i->cur_value < i->cur_key->values->num_values)
1631    {
1632      voffset = i->cur_key->values->elements[i->cur_value];
1633      ret_val = regfi_load_value(i->f, voffset+REGFI_REGF_SIZE, true);
1634    }
1635  }
1636
1637  return ret_val;
1638}
1639
1640
1641/******************************************************************************
1642 *****************************************************************************/
1643REGFI_VK_REC* regfi_iterator_next_value(REGFI_ITERATOR* i)
1644{
1645  REGFI_VK_REC* ret_val;
1646
1647  i->cur_value++;
1648  ret_val = regfi_iterator_cur_value(i);
1649  if(ret_val == NULL)
1650    i->cur_value--;
1651
1652  return ret_val;
1653}
1654
1655
1656/******************************************************************************
1657 *****************************************************************************/
1658REGFI_CLASSNAME* regfi_iterator_fetch_classname(REGFI_ITERATOR* i, 
1659                                                const REGFI_NK_REC* key)
1660{
1661  REGFI_CLASSNAME* ret_val;
1662  uint8* raw;
1663  char* interpreted;
1664  uint32 offset;
1665  int32 conv_size, max_size;
1666  uint16 parse_length;
1667
1668  if(key->classname_off == REGFI_OFFSET_NONE || key->classname_length == 0)
1669    return NULL;
1670
1671  offset = key->classname_off + REGFI_REGF_SIZE;
1672  max_size = regfi_calc_maxsize(i->f, offset);
1673  if(max_size <= 0)
1674    return NULL;
1675
1676  parse_length = key->classname_length;
1677  raw = regfi_parse_classname(i->f, offset, &parse_length, max_size, true);
1678 
1679  if(raw == NULL)
1680  {
1681    regfi_add_message(i->f, REGFI_MSG_WARN, "Could not parse class"
1682                      " name at offset 0x%.8X for key record at offset 0x%.8X.",
1683                      offset, key->offset);
1684    return NULL;
1685  }
1686
1687  ret_val = talloc(NULL, REGFI_CLASSNAME);
1688  if(ret_val == NULL)
1689    return NULL;
1690
1691  ret_val->raw = raw;
1692  ret_val->size = parse_length;
1693  talloc_steal(ret_val, raw);
1694
1695  interpreted = talloc_array(NULL, char, parse_length);
1696
1697  conv_size = regfi_conv_charset(i->string_encoding, 
1698                                 raw, interpreted,
1699                                 parse_length, parse_length);
1700  if(conv_size < 0)
1701  {
1702    regfi_add_message(i->f, REGFI_MSG_WARN, "Error occurred while"
1703                      " converting classname to charset %s.  Error message: %s",
1704                      i->string_encoding, strerror(-conv_size));
1705    talloc_free(interpreted);
1706    ret_val->interpreted = NULL;
1707  }
1708  else
1709  {
1710    interpreted = talloc_realloc(NULL, interpreted, char, conv_size);
1711    ret_val->interpreted = interpreted;
1712    talloc_steal(ret_val, interpreted);
1713  }
1714
1715  return ret_val;
1716}
1717
1718
1719/******************************************************************************
1720 *****************************************************************************/
1721REGFI_DATA* regfi_iterator_fetch_data(REGFI_ITERATOR* i, 
1722                                      const REGFI_VK_REC* value)
1723{
1724  REGFI_DATA* ret_val = NULL;
1725  REGFI_BUFFER raw_data;
1726
1727  if(value->data_size != 0)
1728  {
1729    raw_data = regfi_load_data(i->f, value->data_off, value->data_size,
1730                              value->data_in_offset, true);
1731    if(raw_data.buf == NULL)
1732    {
1733      regfi_add_message(i->f, REGFI_MSG_WARN, "Could not parse data record"
1734                        " while parsing VK record at offset 0x%.8X.",
1735                        value->offset);
1736    }
1737    else
1738    {
1739      ret_val = regfi_buffer_to_data(raw_data);
1740
1741      if(ret_val == NULL)
1742      {
1743        regfi_add_message(i->f, REGFI_MSG_WARN, "Error occurred in converting"
1744                          " data buffer to data structure while interpreting "
1745                          "data for VK record at offset 0x%.8X.",
1746                          value->offset);
1747        talloc_free(raw_data.buf);
1748        return NULL;
1749      }
1750
1751      if(!regfi_interpret_data(i->f, i->string_encoding, value->type, ret_val))
1752      {
1753        regfi_add_message(i->f, REGFI_MSG_INFO, "Error occurred while"
1754                          " interpreting data for VK record at offset 0x%.8X.",
1755                          value->offset);
1756      }
1757    }
1758  }
1759 
1760  return ret_val;
1761}
1762
1763
1764/******************************************************************************
1765 *****************************************************************************/
1766void regfi_free_classname(REGFI_CLASSNAME* classname)
1767{
1768  talloc_free(classname);
1769}
1770
1771/******************************************************************************
1772 *****************************************************************************/
1773void regfi_free_data(REGFI_DATA* data)
1774{
1775  talloc_free(data);
1776}
1777
1778
1779/******************************************************************************
1780 *****************************************************************************/
1781REGFI_DATA* regfi_buffer_to_data(REGFI_BUFFER raw_data)
1782{
1783  REGFI_DATA* ret_val;
1784
1785  if(raw_data.buf == NULL)
1786    return NULL;
1787
1788  ret_val = talloc(NULL, REGFI_DATA);
1789  if(ret_val == NULL)
1790    return NULL;
1791 
1792  talloc_steal(ret_val, raw_data.buf);
1793  ret_val->raw = raw_data.buf;
1794  ret_val->size = raw_data.len;
1795  ret_val->interpreted_size = 0;
1796  ret_val->interpreted.qword = 0;
1797
1798  return ret_val;
1799}
1800
1801
1802/******************************************************************************
1803 *****************************************************************************/
1804bool regfi_interpret_data(REGFI_FILE* file, const char* string_encoding,
1805                          uint32 type, REGFI_DATA* data)
1806{
1807  uint8** tmp_array;
1808  uint8* tmp_str;
1809  int32 tmp_size;
1810  uint32 i, j, array_size;
1811
1812  if(data == NULL)
1813    return false;
1814
1815  switch (type)
1816  {
1817  case REG_SZ:
1818  case REG_EXPAND_SZ:
1819  /* REG_LINK is a symbolic link, stored as a unicode string. */
1820  case REG_LINK:
1821    tmp_str = talloc_array(NULL, uint8, data->size);
1822    if(tmp_str == NULL)
1823    {
1824      data->interpreted.string = NULL;
1825      data->interpreted_size = 0;
1826      return false;
1827    }
1828     
1829    tmp_size = regfi_conv_charset(string_encoding, 
1830                                  data->raw, (char*)tmp_str, 
1831                                  data->size, data->size);
1832    if(tmp_size < 0)
1833    {
1834      regfi_add_message(file, REGFI_MSG_INFO, "Error occurred while"
1835                        " converting data of type %d to %s.  Error message: %s",
1836                        type, string_encoding, strerror(-tmp_size));
1837      talloc_free(tmp_str);
1838      data->interpreted.string = NULL;
1839      data->interpreted_size = 0;
1840      return false;
1841    }
1842
1843    tmp_str = talloc_realloc(NULL, tmp_str, uint8, tmp_size);
1844    data->interpreted.string = tmp_str;
1845    data->interpreted_size = tmp_size;
1846    talloc_steal(data, tmp_str);
1847    break;
1848
1849  case REG_DWORD:
1850    if(data->size < 4)
1851    {
1852      data->interpreted.dword = 0;
1853      data->interpreted_size = 0;
1854      return false;
1855    }
1856    data->interpreted.dword = IVAL(data->raw, 0);
1857    data->interpreted_size = 4;
1858    break;
1859
1860  case REG_DWORD_BE:
1861    if(data->size < 4)
1862    {
1863      data->interpreted.dword_be = 0;
1864      data->interpreted_size = 0;
1865      return false;
1866    }
1867    data->interpreted.dword_be = RIVAL(data->raw, 0);
1868    data->interpreted_size = 4;
1869    break;
1870
1871  case REG_QWORD:
1872    if(data->size < 8)
1873    {
1874      data->interpreted.qword = 0;
1875      data->interpreted_size = 0;
1876      return false;
1877    }
1878    data->interpreted.qword = 
1879      (uint64)IVAL(data->raw, 0) + (((uint64)IVAL(data->raw, 4))<<32);
1880    data->interpreted_size = 8;
1881    break;
1882   
1883  case REG_MULTI_SZ:
1884    tmp_str = talloc_array(NULL, uint8, data->size);
1885    if(tmp_str == NULL)
1886    {
1887      data->interpreted.multiple_string = NULL;
1888      data->interpreted_size = 0;
1889      return false;
1890    }
1891
1892    /* Attempt to convert entire string from UTF-16LE to output encoding,
1893     * then parse and quote fields individually.
1894     */
1895    tmp_size = regfi_conv_charset(string_encoding, 
1896                                  data->raw, (char*)tmp_str,
1897                                  data->size, data->size);
1898    if(tmp_size < 0)
1899    {
1900      regfi_add_message(file, REGFI_MSG_INFO, "Error occurred while"
1901                        " converting data of type %d to %s.  Error message: %s",
1902                        type, string_encoding, strerror(-tmp_size));
1903      talloc_free(tmp_str);
1904      data->interpreted.multiple_string = NULL;
1905      data->interpreted_size = 0;
1906      return false;
1907    }
1908
1909    array_size = tmp_size+1;
1910    tmp_array = talloc_array(NULL, uint8*, array_size);
1911    if(tmp_array == NULL)
1912    {
1913      talloc_free(tmp_str);
1914      data->interpreted.string = NULL;
1915      data->interpreted_size = 0;
1916      return false;
1917    }
1918   
1919    tmp_array[0] = tmp_str;
1920    for(i=0,j=1; i < tmp_size && j < array_size-1; i++)
1921    {
1922      if(tmp_str[i] == '\0' && (i+1 < tmp_size))
1923        tmp_array[j++] = tmp_str+i+1;
1924    }
1925    tmp_array[j] = NULL;
1926    tmp_array = talloc_realloc(NULL, tmp_array, uint8*, j+1);
1927    data->interpreted.multiple_string = tmp_array;
1928    /* XXX: how meaningful is this?  should we store number of strings instead? */
1929    data->interpreted_size = tmp_size;
1930    talloc_steal(tmp_array, tmp_str);
1931    talloc_steal(data, tmp_array);
1932    break;
1933
1934  /* XXX: Dont know how to interpret these yet, just treat as binary */
1935  case REG_NONE:
1936    data->interpreted.none = data->raw;
1937    data->interpreted_size = data->size;
1938    break;
1939
1940  case REG_RESOURCE_LIST:
1941    data->interpreted.resource_list = data->raw;
1942    data->interpreted_size = data->size;
1943    break;
1944
1945  case REG_FULL_RESOURCE_DESCRIPTOR:
1946    data->interpreted.full_resource_descriptor = data->raw;
1947    data->interpreted_size = data->size;
1948    break;
1949
1950  case REG_RESOURCE_REQUIREMENTS_LIST:
1951    data->interpreted.resource_requirements_list = data->raw;
1952    data->interpreted_size = data->size;
1953    break;
1954
1955  case REG_BINARY:
1956    data->interpreted.binary = data->raw;
1957    data->interpreted_size = data->size;
1958    break;
1959
1960  default:
1961    data->interpreted.qword = 0;
1962    data->interpreted_size = 0;
1963    return false;
1964  }
1965
1966  data->type = type;
1967  return true;
1968}
1969
1970
1971
1972/*******************************************************************
1973 * Convert from UTF-16LE to specified character set.
1974 * On error, returns a negative errno code.
1975 *******************************************************************/
1976int32 regfi_conv_charset(const char* output_charset, 
1977                         uint8* input, char* output, 
1978                         uint32 input_len, uint32 output_max)
1979{
1980  iconv_t conv_desc;
1981  char* inbuf = (char*)input;
1982  char* outbuf = output;
1983  size_t in_len = (size_t)input_len;
1984  size_t out_len = (size_t)(output_max-1);
1985  int ret;
1986
1987  /* Set up conversion descriptor. */
1988  conv_desc = iconv_open(output_charset, "UTF-16LE");
1989
1990  ret = iconv(conv_desc, &inbuf, &in_len, &outbuf, &out_len);
1991  if(ret == -1)
1992  {
1993    iconv_close(conv_desc);
1994    return -errno;
1995  }
1996  *outbuf = '\0';
1997
1998  iconv_close(conv_desc); 
1999  return output_max-out_len-1;
2000}
2001
2002
2003
2004/*******************************************************************
2005 * Computes the checksum of the registry file header.
2006 * buffer must be at least the size of a regf header (4096 bytes).
2007 *******************************************************************/
2008static uint32 regfi_compute_header_checksum(uint8* buffer)
2009{
2010  uint32 checksum, x;
2011  int i;
2012
2013  /* XOR of all bytes 0x0000 - 0x01FB */
2014
2015  checksum = x = 0;
2016 
2017  for ( i=0; i<0x01FB; i+=4 ) {
2018    x = IVAL(buffer, i );
2019    checksum ^= x;
2020  }
2021 
2022  return checksum;
2023}
2024
2025
2026/*******************************************************************
2027 * XXX: Add way to return more detailed error information.
2028 *******************************************************************/
2029REGFI_FILE* regfi_parse_regf(int fd, bool strict)
2030{
2031  uint8 file_header[REGFI_REGF_SIZE];
2032  uint32 length;
2033  REGFI_FILE* ret_val;
2034
2035  ret_val = talloc(NULL, REGFI_FILE);
2036  if(ret_val == NULL)
2037    return NULL;
2038
2039  ret_val->fd = fd;
2040  ret_val->sk_cache = NULL;
2041  ret_val->last_message = NULL;
2042  ret_val->hbins = NULL;
2043 
2044  length = REGFI_REGF_SIZE;
2045  if((regfi_read(fd, file_header, &length)) != 0 || length != REGFI_REGF_SIZE)
2046    goto fail;
2047 
2048  ret_val->checksum = IVAL(file_header, 0x1FC);
2049  ret_val->computed_checksum = regfi_compute_header_checksum(file_header);
2050  if (strict && (ret_val->checksum != ret_val->computed_checksum))
2051    goto fail;
2052
2053  memcpy(ret_val->magic, file_header, REGFI_REGF_MAGIC_SIZE);
2054  if(memcmp(ret_val->magic, "regf", REGFI_REGF_MAGIC_SIZE) != 0)
2055  {
2056    if(strict)
2057      goto fail;
2058    regfi_add_message(ret_val, REGFI_MSG_WARN, "Magic number mismatch "
2059                      "(%.2X %.2X %.2X %.2X) while parsing hive header",
2060                      ret_val->magic[0], ret_val->magic[1], 
2061                      ret_val->magic[2], ret_val->magic[3]);
2062  }
2063  ret_val->sequence1 = IVAL(file_header, 0x4);
2064  ret_val->sequence2 = IVAL(file_header, 0x8);
2065  ret_val->mtime.low = IVAL(file_header, 0xC);
2066  ret_val->mtime.high = IVAL(file_header, 0x10);
2067  ret_val->major_version = IVAL(file_header, 0x14);
2068  ret_val->minor_version = IVAL(file_header, 0x18);
2069  ret_val->type = IVAL(file_header, 0x1C);
2070  ret_val->format = IVAL(file_header, 0x20);
2071  ret_val->root_cell = IVAL(file_header, 0x24);
2072  ret_val->last_block = IVAL(file_header, 0x28);
2073
2074  ret_val->cluster = IVAL(file_header, 0x2C);
2075
2076  memcpy(ret_val->file_name, file_header+0x30,  REGFI_REGF_NAME_SIZE);
2077
2078  /* XXX: Should we add a warning if these uuid parsers fail?  Can they? */
2079  ret_val->rm_id = winsec_parse_uuid(ret_val, file_header+0x70, 16);
2080  ret_val->log_id = winsec_parse_uuid(ret_val, file_header+0x80, 16);
2081  ret_val->flags = IVAL(file_header, 0x90);
2082  ret_val->tm_id = winsec_parse_uuid(ret_val, file_header+0x94, 16);
2083  ret_val->guid_signature = IVAL(file_header, 0xa4);
2084
2085  memcpy(ret_val->reserved1, file_header+0xa8, REGFI_REGF_RESERVED1_SIZE);
2086  memcpy(ret_val->reserved2, file_header+0x200, REGFI_REGF_RESERVED2_SIZE);
2087
2088  ret_val->thaw_tm_id = winsec_parse_uuid(ret_val, file_header+0xFC8, 16);
2089  ret_val->thaw_rm_id = winsec_parse_uuid(ret_val, file_header+0xFD8, 16);
2090  ret_val->thaw_log_id = winsec_parse_uuid(ret_val, file_header+0xFE8, 16);
2091  ret_val->boot_type = IVAL(file_header, 0xFF8);
2092  ret_val->boot_recover = IVAL(file_header, 0xFFC);
2093
2094  return ret_val;
2095
2096 fail:
2097  talloc_free(ret_val);
2098  return NULL;
2099}
2100
2101
2102
2103/******************************************************************************
2104 * Given real file offset, read and parse the hbin at that location
2105 * along with it's associated cells.
2106 ******************************************************************************/
2107REGFI_HBIN* regfi_parse_hbin(REGFI_FILE* file, uint32 offset, bool strict)
2108{
2109  REGFI_HBIN *hbin;
2110  uint8 hbin_header[REGFI_HBIN_HEADER_SIZE];
2111  uint32 length;
2112 
2113  if(offset >= file->file_length)
2114    return NULL;
2115
2116  if(lseek(file->fd, offset, SEEK_SET) == -1)
2117  {
2118    regfi_add_message(file, REGFI_MSG_ERROR, "Seek failed"
2119                      " while parsing hbin at offset 0x%.8X.", offset);
2120    return NULL;
2121  }
2122
2123  length = REGFI_HBIN_HEADER_SIZE;
2124  if((regfi_read(file->fd, hbin_header, &length) != 0) 
2125     || length != REGFI_HBIN_HEADER_SIZE)
2126    return NULL;
2127
2128  if(lseek(file->fd, offset, SEEK_SET) == -1)
2129  {
2130    regfi_add_message(file, REGFI_MSG_ERROR, "Seek failed"
2131                      " while parsing hbin at offset 0x%.8X.", offset);
2132    return NULL;
2133  }
2134
2135  hbin = talloc(NULL, REGFI_HBIN);
2136  if(hbin == NULL)
2137    return NULL;
2138  hbin->file_off = offset;
2139
2140  memcpy(hbin->magic, hbin_header, 4);
2141  if(strict && (memcmp(hbin->magic, "hbin", 4) != 0))
2142  {
2143    regfi_add_message(file, REGFI_MSG_INFO, "Magic number mismatch "
2144                      "(%.2X %.2X %.2X %.2X) while parsing hbin at offset"
2145                      " 0x%.8X.", hbin->magic[0], hbin->magic[1], 
2146                      hbin->magic[2], hbin->magic[3], offset);
2147    talloc_free(hbin);
2148    return NULL;
2149  }
2150
2151  hbin->first_hbin_off = IVAL(hbin_header, 0x4);
2152  hbin->block_size = IVAL(hbin_header, 0x8);
2153  /* this should be the same thing as hbin->block_size but just in case */
2154  hbin->next_block = IVAL(hbin_header, 0x1C);
2155
2156
2157  /* Ensure the block size is a multiple of 0x1000 and doesn't run off
2158   * the end of the file.
2159   */
2160  /* XXX: This may need to be relaxed for dealing with
2161   *      partial or corrupt files.
2162   */
2163  if((offset + hbin->block_size > file->file_length)
2164     || (hbin->block_size & 0xFFFFF000) != hbin->block_size)
2165  {
2166    regfi_add_message(file, REGFI_MSG_ERROR, "The hbin offset is not aligned"
2167                      " or runs off the end of the file"
2168                      " while parsing hbin at offset 0x%.8X.", offset);
2169    talloc_free(hbin);
2170    return NULL;
2171  }
2172
2173  return hbin;
2174}
2175
2176
2177/*******************************************************************
2178 *******************************************************************/
2179REGFI_NK_REC* regfi_parse_nk(REGFI_FILE* file, uint32 offset, 
2180                             uint32 max_size, bool strict)
2181{
2182  uint8 nk_header[REGFI_NK_MIN_LENGTH];
2183  REGFI_NK_REC* ret_val;
2184  uint32 length,cell_length;
2185  bool unalloc = false;
2186
2187  if(!regfi_parse_cell(file->fd, offset, nk_header, REGFI_NK_MIN_LENGTH,
2188                       &cell_length, &unalloc))
2189  {
2190    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell header"
2191                      " while parsing NK record at offset 0x%.8X.", offset);
2192    return NULL;
2193  }
2194
2195  /* A bit of validation before bothering to allocate memory */
2196  if((nk_header[0x0] != 'n') || (nk_header[0x1] != 'k'))
2197  {
2198    regfi_add_message(file, REGFI_MSG_WARN, "Magic number mismatch in parsing"
2199                      " NK record at offset 0x%.8X.", offset);
2200    return NULL;
2201  }
2202
2203  ret_val = talloc(NULL, REGFI_NK_REC);
2204  if(ret_val == NULL)
2205  {
2206    regfi_add_message(file, REGFI_MSG_ERROR, "Failed to allocate memory while"
2207                      " parsing NK record at offset 0x%.8X.", offset);
2208    return NULL;
2209  }
2210
2211  ret_val->values = NULL;
2212  ret_val->subkeys = NULL;
2213  ret_val->offset = offset;
2214  ret_val->cell_size = cell_length;
2215
2216  if(ret_val->cell_size > max_size)
2217    ret_val->cell_size = max_size & 0xFFFFFFF8;
2218  if((ret_val->cell_size < REGFI_NK_MIN_LENGTH) 
2219     || (strict && (ret_val->cell_size & 0x00000007) != 0))
2220  {
2221    regfi_add_message(file, REGFI_MSG_WARN, "A length check failed while"
2222                      " parsing NK record at offset 0x%.8X.", offset);
2223    talloc_free(ret_val);
2224    return NULL;
2225  }
2226
2227  ret_val->magic[0] = nk_header[0x0];
2228  ret_val->magic[1] = nk_header[0x1];
2229  ret_val->key_type = SVAL(nk_header, 0x2);
2230 
2231  if((ret_val->key_type & ~REGFI_NK_KNOWN_FLAGS) != 0)
2232  {
2233    regfi_add_message(file, REGFI_MSG_WARN, "Unknown key flags (0x%.4X) while"
2234                      " parsing NK record at offset 0x%.8X.", 
2235                      (ret_val->key_type & ~REGFI_NK_KNOWN_FLAGS), offset);
2236  }
2237
2238  ret_val->mtime.low = IVAL(nk_header, 0x4);
2239  ret_val->mtime.high = IVAL(nk_header, 0x8);
2240  /* If the key is unallocated and the MTIME is earlier than Jan 1, 1990
2241   * or later than Jan 1, 2290, we consider this a bad key.  This helps
2242   * weed out some false positives during deleted data recovery.
2243   */
2244  if(unalloc
2245     && ((ret_val->mtime.high < REGFI_MTIME_MIN_HIGH
2246          && ret_val->mtime.low < REGFI_MTIME_MIN_LOW)
2247         || (ret_val->mtime.high > REGFI_MTIME_MAX_HIGH
2248             && ret_val->mtime.low > REGFI_MTIME_MAX_LOW)))
2249    return NULL;
2250
2251  ret_val->unknown1 = IVAL(nk_header, 0xC);
2252  ret_val->parent_off = IVAL(nk_header, 0x10);
2253  ret_val->num_subkeys = IVAL(nk_header, 0x14);
2254  ret_val->unknown2 = IVAL(nk_header, 0x18);
2255  ret_val->subkeys_off = IVAL(nk_header, 0x1C);
2256  ret_val->unknown3 = IVAL(nk_header, 0x20);
2257  ret_val->num_values = IVAL(nk_header, 0x24);
2258  ret_val->values_off = IVAL(nk_header, 0x28);
2259  ret_val->sk_off = IVAL(nk_header, 0x2C);
2260  ret_val->classname_off = IVAL(nk_header, 0x30);
2261
2262  ret_val->max_bytes_subkeyname = IVAL(nk_header, 0x34);
2263  ret_val->max_bytes_subkeyclassname = IVAL(nk_header, 0x38);
2264  ret_val->max_bytes_valuename = IVAL(nk_header, 0x3C);
2265  ret_val->max_bytes_value = IVAL(nk_header, 0x40);
2266  ret_val->unk_index = IVAL(nk_header, 0x44);
2267
2268  ret_val->name_length = SVAL(nk_header, 0x48);
2269  ret_val->classname_length = SVAL(nk_header, 0x4A);
2270
2271  if(ret_val->name_length + REGFI_NK_MIN_LENGTH > ret_val->cell_size)
2272  {
2273    if(strict)
2274    {
2275      regfi_add_message(file, REGFI_MSG_ERROR, "Contents too large for cell"
2276                        " while parsing NK record at offset 0x%.8X.", offset);
2277      talloc_free(ret_val);
2278      return NULL;
2279    }
2280    else
2281      ret_val->name_length = ret_val->cell_size - REGFI_NK_MIN_LENGTH;
2282  }
2283  else if (unalloc)
2284  { /* Truncate cell_size if it's much larger than the apparent total record length. */
2285    /* Round up to the next multiple of 8 */
2286    length = (ret_val->name_length + REGFI_NK_MIN_LENGTH) & 0xFFFFFFF8;
2287    if(length < ret_val->name_length + REGFI_NK_MIN_LENGTH)
2288      length+=8;
2289
2290    /* If cell_size is still greater, truncate. */
2291    if(length < ret_val->cell_size)
2292      ret_val->cell_size = length;
2293  }
2294
2295  ret_val->keyname = talloc_array(ret_val, char, ret_val->name_length+1);
2296  if(ret_val->keyname == NULL)
2297  {
2298    talloc_free(ret_val);
2299    return NULL;
2300  }
2301
2302  /* Don't need to seek, should be at the right offset */
2303  length = ret_val->name_length;
2304  if((regfi_read(file->fd, (uint8*)ret_val->keyname, &length) != 0)
2305     || length != ret_val->name_length)
2306  {
2307    regfi_add_message(file, REGFI_MSG_ERROR, "Failed to read key name"
2308                      " while parsing NK record at offset 0x%.8X.", offset);
2309    talloc_free(ret_val);
2310    return NULL;
2311  }
2312  ret_val->keyname[ret_val->name_length] = '\0';
2313
2314  return ret_val;
2315}
2316
2317
2318uint8* regfi_parse_classname(REGFI_FILE* file, uint32 offset, 
2319                             uint16* name_length, uint32 max_size, bool strict)
2320{
2321  uint8* ret_val = NULL;
2322  uint32 length;
2323  uint32 cell_length;
2324  bool unalloc = false;
2325
2326  if(*name_length > 0 && offset != REGFI_OFFSET_NONE
2327     && (offset & 0x00000007) == 0)
2328  {
2329    if(!regfi_parse_cell(file->fd, offset, NULL, 0, &cell_length, &unalloc))
2330    {
2331      regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell header"
2332                        " while parsing class name at offset 0x%.8X.", offset);
2333        return NULL;
2334    }
2335
2336    if((cell_length & 0x0000007) != 0)
2337    {
2338      regfi_add_message(file, REGFI_MSG_ERROR, "Cell length not a multiple of 8"
2339                        " while parsing class name at offset 0x%.8X.", offset);
2340      return NULL;
2341    }
2342
2343    if(cell_length > max_size)
2344    {
2345      regfi_add_message(file, REGFI_MSG_WARN, "Cell stretches past hbin "
2346                        "boundary while parsing class name at offset 0x%.8X.",
2347                        offset);
2348      if(strict)
2349        return NULL;
2350      cell_length = max_size;
2351    }
2352
2353    if((cell_length - 4) < *name_length)
2354    {
2355      regfi_add_message(file, REGFI_MSG_WARN, "Class name is larger than"
2356                        " cell_length while parsing class name at offset"
2357                        " 0x%.8X.", offset);
2358      if(strict)
2359        return NULL;
2360      *name_length = cell_length - 4;
2361    }
2362   
2363    ret_val = talloc_array(NULL, uint8, *name_length);
2364    if(ret_val != NULL)
2365    {
2366      length = *name_length;
2367      if((regfi_read(file->fd, ret_val, &length) != 0)
2368         || length != *name_length)
2369      {
2370        regfi_add_message(file, REGFI_MSG_ERROR, "Could not read class name"
2371                          " while parsing class name at offset 0x%.8X.", offset);
2372        talloc_free(ret_val);
2373        return NULL;
2374      }
2375    }
2376  }
2377
2378  return ret_val;
2379}
2380
2381
2382/******************************************************************************
2383*******************************************************************************/
2384REGFI_VK_REC* regfi_parse_vk(REGFI_FILE* file, uint32 offset, 
2385                             uint32 max_size, bool strict)
2386{
2387  REGFI_VK_REC* ret_val;
2388  uint8 vk_header[REGFI_VK_MIN_LENGTH];
2389  uint32 raw_data_size, length, cell_length;
2390  bool unalloc = false;
2391
2392  if(!regfi_parse_cell(file->fd, offset, vk_header, REGFI_VK_MIN_LENGTH,
2393                       &cell_length, &unalloc))
2394  {
2395    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell header"
2396                      " while parsing VK record at offset 0x%.8X.", offset);
2397    return NULL;
2398  }
2399
2400  ret_val = talloc(NULL, REGFI_VK_REC);
2401  if(ret_val == NULL)
2402    return NULL;
2403
2404  ret_val->offset = offset;
2405  ret_val->cell_size = cell_length;
2406  ret_val->data = NULL;
2407  ret_val->valuename = NULL;
2408 
2409  if(ret_val->cell_size > max_size)
2410    ret_val->cell_size = max_size & 0xFFFFFFF8;
2411  if((ret_val->cell_size < REGFI_VK_MIN_LENGTH) 
2412     || (ret_val->cell_size & 0x00000007) != 0)
2413  {
2414    regfi_add_message(file, REGFI_MSG_WARN, "Invalid cell size encountered"
2415                      " while parsing VK record at offset 0x%.8X.", offset);
2416    talloc_free(ret_val);
2417    return NULL;
2418  }
2419
2420  ret_val->magic[0] = vk_header[0x0];
2421  ret_val->magic[1] = vk_header[0x1];
2422  if((ret_val->magic[0] != 'v') || (ret_val->magic[1] != 'k'))
2423  {
2424    /* XXX: This does not account for deleted keys under Win2K which
2425     *      often have this (and the name length) overwritten with
2426     *      0xFFFF.
2427     */
2428    regfi_add_message(file, REGFI_MSG_WARN, "Magic number mismatch"
2429                      " while parsing VK record at offset 0x%.8X.", offset);
2430    talloc_free(ret_val);
2431    return NULL;
2432  }
2433
2434  ret_val->name_length = SVAL(vk_header, 0x2);
2435  raw_data_size = IVAL(vk_header, 0x4);
2436  ret_val->data_size = raw_data_size & ~REGFI_VK_DATA_IN_OFFSET;
2437  /* The data is typically stored in the offset if the size <= 4,
2438   * in which case this flag is set.
2439   */
2440  ret_val->data_in_offset = (bool)(raw_data_size & REGFI_VK_DATA_IN_OFFSET);
2441  ret_val->data_off = IVAL(vk_header, 0x8);
2442  ret_val->type = IVAL(vk_header, 0xC);
2443  ret_val->flag = SVAL(vk_header, 0x10);
2444  ret_val->unknown1 = SVAL(vk_header, 0x12);
2445
2446  if(ret_val->flag & REGFI_VK_FLAG_NAME_PRESENT)
2447  {
2448    if(ret_val->name_length + REGFI_VK_MIN_LENGTH + 4 > ret_val->cell_size)
2449    {
2450      regfi_add_message(file, REGFI_MSG_WARN, "Name too long for remaining cell"
2451                        " space while parsing VK record at offset 0x%.8X.",
2452                        offset);
2453      if(strict)
2454      {
2455        talloc_free(ret_val);
2456        return NULL;
2457      }
2458      else
2459        ret_val->name_length = ret_val->cell_size - REGFI_VK_MIN_LENGTH - 4;
2460    }
2461
2462    /* Round up to the next multiple of 8 */
2463    cell_length = (ret_val->name_length + REGFI_VK_MIN_LENGTH + 4) & 0xFFFFFFF8;
2464    if(cell_length < ret_val->name_length + REGFI_VK_MIN_LENGTH + 4)
2465      cell_length+=8;
2466
2467    ret_val->valuename = talloc_array(ret_val, char, ret_val->name_length+1);
2468    if(ret_val->valuename == NULL)
2469    {
2470      talloc_free(ret_val);
2471      return NULL;
2472    }
2473
2474    length = ret_val->name_length;
2475    if((regfi_read(file->fd, (uint8*)ret_val->valuename, &length) != 0)
2476       || length != ret_val->name_length)
2477    {
2478      regfi_add_message(file, REGFI_MSG_ERROR, "Could not read value name"
2479                        " while parsing VK record at offset 0x%.8X.", offset);
2480      talloc_free(ret_val);
2481      return NULL;
2482    }
2483    ret_val->valuename[ret_val->name_length] = '\0';
2484
2485  }
2486  else
2487    cell_length = REGFI_VK_MIN_LENGTH + 4;
2488
2489  if(unalloc)
2490  {
2491    /* If cell_size is still greater, truncate. */
2492    if(cell_length < ret_val->cell_size)
2493      ret_val->cell_size = cell_length;
2494  }
2495
2496  return ret_val;
2497}
2498
2499
2500/******************************************************************************
2501 *
2502 ******************************************************************************/
2503REGFI_BUFFER regfi_load_data(REGFI_FILE* file, uint32 voffset,
2504                             uint32 length, bool data_in_offset,
2505                             bool strict)
2506{
2507  REGFI_BUFFER ret_val;
2508  uint32 cell_length, offset;
2509  int32 max_size;
2510  bool unalloc;
2511 
2512  /* Microsoft's documentation indicates that "available memory" is
2513   * the limit on value sizes.  Annoying.  We limit it to 1M which
2514   * should rarely be exceeded, unless the file is corrupt or
2515   * malicious. For more info, see:
2516   *   http://msdn2.microsoft.com/en-us/library/ms724872.aspx
2517   */
2518  /* XXX: add way to skip this check at user discression. */
2519  if(length > REGFI_VK_MAX_DATA_LENGTH)
2520  {
2521    regfi_add_message(file, REGFI_MSG_WARN, "Value data size %d larger than "
2522                      "%d, truncating...", length, REGFI_VK_MAX_DATA_LENGTH);
2523    length = REGFI_VK_MAX_DATA_LENGTH;
2524  }
2525
2526  if(data_in_offset)
2527    return regfi_parse_little_data(file, voffset, length, strict);
2528  else
2529  {
2530    offset = voffset + REGFI_REGF_SIZE;
2531    max_size = regfi_calc_maxsize(file, offset);
2532    if(max_size < 0)
2533    {
2534      regfi_add_message(file, REGFI_MSG_WARN, "Could not find HBIN for data"
2535                        " at offset 0x%.8X.", offset);
2536      goto fail;
2537    }
2538   
2539    if(!regfi_parse_cell(file->fd, offset, NULL, 0,
2540                         &cell_length, &unalloc))
2541    {
2542      regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell while"
2543                        " parsing data record at offset 0x%.8X.", offset);
2544      goto fail;
2545    }
2546
2547    if((cell_length & 0x00000007) != 0)
2548    {
2549      regfi_add_message(file, REGFI_MSG_WARN, "Cell length not multiple of 8"
2550                        " while parsing data record at offset 0x%.8X.",
2551                        offset);
2552      goto fail;
2553    }
2554
2555    if(cell_length > max_size)
2556    {
2557      regfi_add_message(file, REGFI_MSG_WARN, "Cell extends past HBIN boundary"
2558                        " while parsing data record at offset 0x%.8X.",
2559                        offset);
2560      goto fail;
2561    }
2562
2563    if(cell_length - 4 < length)
2564    {
2565      /* XXX: All big data records thus far have been 16 bytes long. 
2566       *      Should we check for this precise size instead of just
2567       *      relying upon the above check?
2568       */
2569      if (file->major_version >= 1 && file->minor_version >= 5)
2570      {
2571        /* Attempt to parse a big data record */
2572        return regfi_load_big_data(file, offset, length, cell_length, 
2573                                   NULL, strict);
2574      }
2575      else
2576      {
2577        regfi_add_message(file, REGFI_MSG_WARN, "Data length (0x%.8X) larger than"
2578                          " remaining cell length (0x%.8X)"
2579                          " while parsing data record at offset 0x%.8X.", 
2580                          length, cell_length - 4, offset);
2581        if(strict)
2582          goto fail;
2583        else
2584          length = cell_length - 4;
2585      }
2586    }
2587
2588    ret_val = regfi_parse_data(file, offset, length, strict);
2589  }
2590
2591  return ret_val;
2592
2593 fail:
2594  ret_val.buf = NULL;
2595  ret_val.len = 0;
2596  return ret_val;
2597}
2598
2599
2600/******************************************************************************
2601 * Parses the common case data records stored in a single cell.
2602 ******************************************************************************/
2603REGFI_BUFFER regfi_parse_data(REGFI_FILE* file, uint32 offset,
2604                              uint32 length, bool strict)
2605{
2606  REGFI_BUFFER ret_val;
2607  uint32 read_length;
2608
2609  ret_val.buf = NULL;
2610  ret_val.len = 0;
2611 
2612  if(lseek(file->fd, offset+4, SEEK_SET) == -1)
2613  {
2614    regfi_add_message(file, REGFI_MSG_WARN, "Could not seek while "
2615                      "reading data at offset 0x%.8X.", offset);
2616    return ret_val;
2617  }
2618
2619  if((ret_val.buf = talloc_array(NULL, uint8, length)) == NULL)
2620    return ret_val;
2621  ret_val.len = length;
2622 
2623  read_length = length;
2624  if((regfi_read(file->fd, ret_val.buf, &read_length) != 0)
2625     || read_length != length)
2626  {
2627    regfi_add_message(file, REGFI_MSG_ERROR, "Could not read data block while"
2628                      " parsing data record at offset 0x%.8X.", offset);
2629    talloc_free(ret_val.buf);
2630    ret_val.buf = NULL;
2631    ret_val.buf = 0;
2632  }
2633
2634  return ret_val;
2635}
2636
2637
2638
2639/******************************************************************************
2640 *
2641 ******************************************************************************/
2642REGFI_BUFFER regfi_parse_little_data(REGFI_FILE* file, uint32 voffset,
2643                                     uint32 length, bool strict)
2644{
2645  REGFI_BUFFER ret_val;
2646  uint8 i;
2647
2648  ret_val.buf = NULL;
2649  ret_val.len = 0;
2650
2651  if(length > 4)
2652  {
2653    regfi_add_message(file, REGFI_MSG_ERROR, "Data in offset but length > 4"
2654                      " while parsing data record. (voffset=0x%.8X, length=%d)",
2655                      voffset, length);
2656    return ret_val;
2657  }
2658
2659  if((ret_val.buf = talloc_array(NULL, uint8, length)) == NULL)
2660    return ret_val;
2661  ret_val.len = length;
2662 
2663  for(i = 0; i < length; i++)
2664    ret_val.buf[i] = (uint8)((voffset >> i*8) & 0xFF);
2665
2666  return ret_val;
2667}
2668
2669/******************************************************************************
2670*******************************************************************************/
2671REGFI_BUFFER regfi_parse_big_data_header(REGFI_FILE* file, uint32 offset, 
2672                                         uint32 max_size, bool strict)
2673{
2674  REGFI_BUFFER ret_val;
2675  uint32 cell_length;
2676  bool unalloc;
2677
2678  /* XXX: do something with unalloc? */
2679  ret_val.buf = (uint8*)talloc_array(NULL, uint8, REGFI_BIG_DATA_MIN_LENGTH);
2680  if(ret_val.buf == NULL)
2681    goto fail;
2682
2683  if(REGFI_BIG_DATA_MIN_LENGTH > max_size)
2684  {
2685    regfi_add_message(file, REGFI_MSG_WARN, "Big data header exceeded max_size "
2686                      "while parsing big data header at offset 0x%.8X.",offset);
2687    goto fail;
2688  }
2689
2690  if(!regfi_parse_cell(file->fd, offset, ret_val.buf, REGFI_BIG_DATA_MIN_LENGTH,
2691                       &cell_length, &unalloc))
2692  {
2693    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell while"
2694                      " parsing big data header at offset 0x%.8X.", offset);
2695    goto fail;
2696  }
2697
2698  if((ret_val.buf[0] != 'd') || (ret_val.buf[1] != 'b'))
2699  {
2700    regfi_add_message(file, REGFI_MSG_WARN, "Unknown magic number"
2701                      " (0x%.2X, 0x%.2X) encountered while parsing"
2702                      " big data header at offset 0x%.8X.", 
2703                      ret_val.buf[0], ret_val.buf[1], offset);
2704    goto fail;
2705  }
2706
2707  ret_val.len = REGFI_BIG_DATA_MIN_LENGTH;
2708  return ret_val;
2709
2710 fail:
2711  if(ret_val.buf != NULL)
2712  {
2713    talloc_free(ret_val.buf);
2714    ret_val.buf = NULL;
2715  }
2716  ret_val.len = 0;
2717  return ret_val;
2718}
2719
2720
2721
2722/******************************************************************************
2723 *
2724 ******************************************************************************/
2725uint32* regfi_parse_big_data_indirect(REGFI_FILE* file, uint32 offset,
2726                                      uint16 num_chunks, bool strict)
2727{
2728  uint32* ret_val;
2729  uint32 indirect_length;
2730  int32 max_size;
2731  uint16 i;
2732  bool unalloc;
2733
2734  /* XXX: do something with unalloc? */
2735
2736  max_size = regfi_calc_maxsize(file, offset);
2737  if((max_size < 0) || (num_chunks*sizeof(uint32) + 4 > max_size))
2738    return NULL;
2739
2740  ret_val = (uint32*)talloc_array(NULL, uint32, num_chunks);
2741  if(ret_val == NULL)
2742    goto fail;
2743
2744  if(!regfi_parse_cell(file->fd, offset, (uint8*)ret_val,
2745                       num_chunks*sizeof(uint32),
2746                       &indirect_length, &unalloc))
2747  {
2748    regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell while"
2749                      " parsing big data indirect record at offset 0x%.8X.", 
2750                      offset);
2751    goto fail;
2752  }
2753
2754  /* Convert pointers to proper endianess, verify they are aligned. */
2755  for(i=0; i<num_chunks; i++)
2756  {
2757    ret_val[i] = IVAL(ret_val, i*sizeof(uint32));
2758    if((ret_val[i] & 0x00000007) != 0)
2759      goto fail;
2760  }
2761 
2762  return ret_val;
2763
2764 fail:
2765  if(ret_val != NULL)
2766    talloc_free(ret_val);
2767  return NULL;
2768}
2769
2770
2771/******************************************************************************
2772 * Arguments:
2773 *  file       --
2774 *  offsets    -- list of virtual offsets.
2775 *  num_chunks --
2776 *  strict     --
2777 *
2778 * Returns:
2779 *  A range_list with physical offsets and complete lengths
2780 *  (including cell headers) of associated cells. 
2781 *  No data in range_list elements.
2782 ******************************************************************************/
2783range_list* regfi_parse_big_data_cells(REGFI_FILE* file, uint32* offsets,
2784                                       uint16 num_chunks, bool strict)
2785{
2786  uint32 cell_length, chunk_offset, data_left;
2787  range_list* ret_val;
2788  uint16 i;
2789  bool unalloc;
2790 
2791  /* XXX: do something with unalloc? */
2792  ret_val = range_list_new();
2793  if(ret_val == NULL)
2794    goto fail;
2795 
2796  for(i=0; (i<num_chunks) && (data_left>0); i++)
2797  {
2798    chunk_offset = offsets[i]+REGFI_REGF_SIZE;
2799    if(!regfi_parse_cell(file->fd, chunk_offset, NULL, 0,
2800                         &cell_length, &unalloc))
2801    {
2802      regfi_add_message(file, REGFI_MSG_WARN, "Could not parse cell while"
2803                        " parsing big data chunk at offset 0x%.8X.", 
2804                        chunk_offset);
2805      goto fail;
2806    }
2807
2808    if(!range_list_add(ret_val, chunk_offset, cell_length, NULL))
2809      goto fail;
2810  }
2811
2812  return ret_val;
2813
2814 fail:
2815  if(ret_val != NULL)
2816    range_list_free(ret_val);
2817  return NULL;
2818}
2819
2820
2821/******************************************************************************
2822*******************************************************************************/
2823REGFI_BUFFER regfi_load_big_data(REGFI_FILE* file, 
2824                                 uint32 offset, uint32 data_length, 
2825                                 uint32 cell_length, range_list* used_ranges,
2826                                 bool strict)
2827{
2828  REGFI_BUFFER ret_val;
2829  uint16 num_chunks, i;
2830  uint32 read_length, data_left, tmp_len, indirect_offset;
2831  uint32* indirect_ptrs = NULL;
2832  REGFI_BUFFER bd_header;
2833  range_list* bd_cells = NULL;
2834  const range_list_element* cell_info;
2835
2836  ret_val.buf = NULL;
2837
2838  /* XXX: Add better error/warning messages */
2839
2840  bd_header = regfi_parse_big_data_header(file, offset, cell_length, strict);
2841  if(bd_header.buf == NULL)
2842    goto fail;
2843
2844  /* Keep track of used space for use by reglookup-recover */
2845  if(used_ranges != NULL)
2846    if(!range_list_add(used_ranges, offset, cell_length, NULL))
2847      goto fail;
2848
2849  num_chunks = SVAL(bd_header.buf, 0x2);
2850  indirect_offset = IVAL(bd_header.buf, 0x4) + REGFI_REGF_SIZE;
2851  talloc_free(bd_header.buf);
2852
2853  indirect_ptrs = regfi_parse_big_data_indirect(file, indirect_offset,
2854                                                num_chunks, strict);
2855  if(indirect_ptrs == NULL)
2856    goto fail;
2857
2858  if(used_ranges != NULL)
2859    if(!range_list_add(used_ranges, indirect_offset, num_chunks*4+4, NULL))
2860      goto fail;
2861 
2862  if((ret_val.buf = talloc_array(NULL, uint8_t, data_length)) == NULL)
2863    goto fail;
2864  data_left = data_length;
2865
2866  bd_cells = regfi_parse_big_data_cells(file, indirect_ptrs, num_chunks, strict);
2867  if(bd_cells == NULL)
2868    goto fail;
2869
2870  talloc_free(indirect_ptrs);
2871  indirect_ptrs = NULL;
2872 
2873  for(i=0; (i<num_chunks) && (data_left>0); i++)
2874  {
2875    cell_info = range_list_get(bd_cells, i);
2876    if(cell_info == NULL)
2877      goto fail;
2878
2879    /* XXX: This should be "cell_info->length-4" to account for the 4 byte cell
2880     *      length.  However, it has been observed that some (all?) chunks
2881     *      have an additional 4 bytes of 0 at the end of their cells that
2882     *      isn't part of the data, so we're trimming that off too.
2883     *      Perhaps it's just an 8 byte alignment requirement...
2884     */
2885    if(cell_info->length - 8 >= data_left)
2886    {
2887      if(i+1 != num_chunks)
2888      {
2889        regfi_add_message(file, REGFI_MSG_WARN, "Left over chunks detected "
2890                          "while constructing big data at offset 0x%.8X "
2891                          "(chunk offset 0x%.8X).", offset, cell_info->offset);
2892      }
2893      read_length = data_left;
2894    }
2895    else
2896      read_length = cell_info->length - 8;
2897
2898
2899    if(read_length > regfi_calc_maxsize(file, cell_info->offset))
2900    {
2901      regfi_add_message(file, REGFI_MSG_WARN, "A chunk exceeded the maxsize "
2902                        "while constructing big data at offset 0x%.8X "
2903                        "(chunk offset 0x%.8X).", offset, cell_info->offset);
2904      goto fail;
2905    }
2906
2907    if(lseek(file->fd, cell_info->offset+sizeof(uint32), SEEK_SET) == -1)
2908    {
2909      regfi_add_message(file, REGFI_MSG_WARN, "Could not seek to chunk while "
2910                        "constructing big data at offset 0x%.8X "
2911                        "(chunk offset 0x%.8X).", offset, cell_info->offset);
2912      goto fail;
2913    }
2914
2915    tmp_len = read_length;
2916    if(regfi_read(file->fd, ret_val.buf+(data_length-data_left), 
2917                  &read_length) != 0 || (read_length != tmp_len))
2918    {
2919      regfi_add_message(file, REGFI_MSG_WARN, "Could not read data chunk while"
2920                        " constructing big data at offset 0x%.8X"
2921                        " (chunk offset 0x%.8X).", offset, cell_info->offset);
2922      goto fail;
2923    }
2924
2925    if(used_ranges != NULL)
2926      if(!range_list_add(used_ranges, cell_info->offset,cell_info->length,NULL))
2927        goto fail;
2928
2929    data_left -= read_length;
2930  }
2931  range_list_free(bd_cells);
2932
2933  ret_val.len = data_length-data_left;
2934  return ret_val;
2935
2936 fail:
2937  if(ret_val.buf != NULL)
2938    talloc_free(ret_val.buf);
2939  if(indirect_ptrs != NULL)
2940    talloc_free(indirect_ptrs);
2941  if(bd_cells != NULL)
2942    range_list_free(bd_cells);
2943  ret_val.buf = NULL;
2944  ret_val.len = 0;
2945  return ret_val;
2946}
2947
2948
2949range_list* regfi_parse_unalloc_cells(REGFI_FILE* file)
2950{
2951  range_list* ret_val;
2952  REGFI_HBIN* hbin;
2953  const range_list_element* hbins_elem;
2954  uint32 i, num_hbins, curr_off, cell_len;
2955  bool is_unalloc;
2956
2957  ret_val = range_list_new();
2958  if(ret_val == NULL)
2959    return NULL;
2960
2961  num_hbins = range_list_size(file->hbins);
2962  for(i=0; i<num_hbins; i++)
2963  {
2964    hbins_elem = range_list_get(file->hbins, i);
2965    if(hbins_elem == NULL)
2966      break;
2967    hbin = (REGFI_HBIN*)hbins_elem->data;
2968
2969    curr_off = REGFI_HBIN_HEADER_SIZE;
2970    while(curr_off < hbin->block_size)
2971    {
2972      if(!regfi_parse_cell(file->fd, hbin->file_off+curr_off, NULL, 0,
2973                           &cell_len, &is_unalloc))
2974        break;
2975     
2976      if((cell_len == 0) || ((cell_len & 0x00000007) != 0))
2977      {
2978        regfi_add_message(file, REGFI_MSG_ERROR, "Bad cell length encountered"
2979                          " while parsing unallocated cells at offset 0x%.8X.",
2980                          hbin->file_off+curr_off);
2981        break;
2982      }
2983
2984      /* for some reason the record_size of the last record in
2985         an hbin block can extend past the end of the block
2986         even though the record fits within the remaining
2987         space....aaarrrgggghhhhhh */ 
2988      if(curr_off + cell_len >= hbin->block_size)
2989        cell_len = hbin->block_size - curr_off;
2990     
2991      if(is_unalloc)
2992        range_list_add(ret_val, hbin->file_off+curr_off, 
2993                       cell_len, NULL);
2994     
2995      curr_off = curr_off+cell_len;
2996    }
2997  }
2998
2999  return ret_val;
3000}
Note: See TracBrowser for help on using the repository browser.