source: trunk/lib/regfi.c @ 203

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

misc fixes

stripped _REC from some data type names

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