source: trunk/lib/regfi.c @ 182

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

redesigned regfi logging API to utilize thread-local storage

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