source: trunk/lib/regfi.c @ 191

Last change on this file since 191 was 186, checked in by tim, 15 years ago

minor changes based on suggestions from Michael Cohen

  • Property svn:keywords set to Id
File size: 97.6 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 186 2010-04-19 21:55:26Z 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')
[168]835    elem_size = sizeof(uint32_t);
[134]836  else if((buf[0] == 'l') && (buf[1] == 'f' || buf[1] == 'h'))
[135]837    elem_size = sizeof(REGFI_SUBKEY_LIST_ELEM);
[134]838  else
839  {
[182]840    regfi_log_add(REGFI_LOG_ERROR, "Unknown magic number"
[139]841                      " (0x%.2X, 0x%.2X) encountered while parsing"
842                      " subkey-list at offset 0x%.8X.", buf[0], buf[1], offset);
[180]843    goto fail_locked;
[134]844  }
845
[150]846  ret_val = talloc(NULL, REGFI_SUBKEY_LIST);
[127]847  if(ret_val == NULL)
[180]848    goto fail_locked;
[127]849
850  ret_val->offset = offset;
851  ret_val->cell_size = cell_length;
[104]852  ret_val->magic[0] = buf[0];
853  ret_val->magic[1] = buf[1];
[139]854  ret_val->recursive_type = recursive_type;
855  ret_val->num_children = SVAL(buf, 0x2);
[101]856
[139]857  if(!recursive_type)
858    ret_val->num_keys = ret_val->num_children;
[101]859
[139]860  length = elem_size*ret_val->num_children;
[168]861  if(cell_length - REGFI_SUBKEY_LIST_MIN_LEN - sizeof(uint32_t) < length)
[134]862  {
[182]863    regfi_log_add(REGFI_LOG_WARN, "Number of elements too large for"
[139]864                      " cell while parsing subkey-list at offset 0x%.8X.", 
865                      offset);
866    if(strict)
[180]867      goto fail_locked;
[168]868    length = cell_length - REGFI_SUBKEY_LIST_MIN_LEN - sizeof(uint32_t);
[134]869  }
[30]870
[150]871  ret_val->elements = talloc_array(ret_val, REGFI_SUBKEY_LIST_ELEM, 
872                                   ret_val->num_children);
[127]873  if(ret_val->elements == NULL)
[180]874    goto fail_locked;
[30]875
[168]876  elements = (uint8_t*)malloc(length);
[139]877  if(elements == NULL)
[180]878    goto fail_locked;
[30]879
[150]880  read_len = length;
[178]881  if(regfi_read(file->cb, elements, &read_len) != 0 || read_len!=length)
[180]882    goto fail_locked;
[30]883
[186]884  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_subkeylist"))
[180]885     goto fail;
886
[168]887  if(elem_size == sizeof(uint32_t))
[104]888  {
[139]889    for (i=0; i < ret_val->num_children; i++)
[134]890    {
[139]891      ret_val->elements[i].offset = IVAL(elements, i*elem_size);
[134]892      ret_val->elements[i].hash = 0;
893    }
[104]894  }
[134]895  else
896  {
[139]897    for (i=0; i < ret_val->num_children; i++)
[134]898    {
[139]899      ret_val->elements[i].offset = IVAL(elements, i*elem_size);
900      ret_val->elements[i].hash = IVAL(elements, i*elem_size+4);
[134]901    }
902  }
[139]903  free(elements);
[30]904
[104]905  return ret_val;
[150]906
[180]907 fail_locked:
[186]908  regfi_unlock(file, &file->cb_lock, "regfi_parse_subkeylist");
[150]909 fail:
910  if(elements != NULL)
911    free(elements);
912  talloc_free(ret_val);
913  return NULL;
[30]914}
915
916
[139]917/*******************************************************************
918 *******************************************************************/
[168]919REGFI_SUBKEY_LIST* regfi_merge_subkeylists(uint16_t num_lists, 
[139]920                                           REGFI_SUBKEY_LIST** lists,
921                                           bool strict)
922{
[168]923  uint32_t i,j,k;
[139]924  REGFI_SUBKEY_LIST* ret_val;
[102]925
[139]926  if(lists == NULL)
927    return NULL;
[150]928  ret_val = talloc(NULL, REGFI_SUBKEY_LIST);
[139]929
930  if(ret_val == NULL)
931    return NULL;
932 
933  /* Obtain total number of elements */
934  ret_val->num_keys = 0;
935  for(i=0; i < num_lists; i++)
936  {
937    if(lists[i] != NULL)
938      ret_val->num_keys += lists[i]->num_children;
939  }
940  ret_val->num_children = ret_val->num_keys;
941
942  if(ret_val->num_keys > 0)
943  {
[150]944    ret_val->elements = talloc_array(ret_val, REGFI_SUBKEY_LIST_ELEM,
945                                     ret_val->num_keys);
[139]946    k=0;
947
948    if(ret_val->elements != NULL)
949    {
950      for(i=0; i < num_lists; i++)
951      {
952        if(lists[i] != NULL)
953        {
954          for(j=0; j < lists[i]->num_keys; j++)
955          {
[150]956            ret_val->elements[k].hash = lists[i]->elements[j].hash;
957            ret_val->elements[k++].offset = lists[i]->elements[j].offset;
[139]958          }
959        }
960      }
961    }
962  }
963 
964  for(i=0; i < num_lists; i++)
[184]965    talloc_free(lists[i]);
[139]966  free(lists);
967
968  return ret_val;
969}
970
971
[147]972/******************************************************************************
973 *
974 ******************************************************************************/
[168]975REGFI_SK_REC* regfi_parse_sk(REGFI_FILE* file, uint32_t offset, uint32_t max_size, 
[147]976                             bool strict)
[30]977{
[180]978  REGFI_SK_REC* ret_val = NULL;
[168]979  uint8_t* sec_desc_buf = NULL;
980  uint32_t cell_length, length;
981  uint8_t sk_header[REGFI_SK_MIN_LENGTH];
[102]982  bool unalloc = false;
[30]983
[186]984  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_sk"))
[180]985     goto fail;
986
[178]987  if(!regfi_parse_cell(file->cb, offset, sk_header, REGFI_SK_MIN_LENGTH,
[102]988                       &cell_length, &unalloc))
[137]989  {
[182]990    regfi_log_add(REGFI_LOG_WARN, "Could not parse SK record cell"
[137]991                      " at offset 0x%.8X.", offset);
[180]992    goto fail_locked;
[137]993  }
[102]994   
995  if(sk_header[0] != 's' || sk_header[1] != 'k')
[137]996  {
[182]997    regfi_log_add(REGFI_LOG_WARN, "Magic number mismatch in parsing"
[138]998                      " SK record at offset 0x%.8X.", offset);
[180]999    goto fail_locked;
[137]1000  }
1001
[147]1002  ret_val = talloc(NULL, REGFI_SK_REC);
[102]1003  if(ret_val == NULL)
[180]1004    goto fail_locked;
[30]1005
[102]1006  ret_val->offset = offset;
[116]1007  /* XXX: Is there a way to be more conservative (shorter) with
1008   *      cell length when cell is unallocated?
[111]1009   */
[102]1010  ret_val->cell_size = cell_length;
[30]1011
[102]1012  if(ret_val->cell_size > max_size)
1013    ret_val->cell_size = max_size & 0xFFFFFFF8;
1014  if((ret_val->cell_size < REGFI_SK_MIN_LENGTH) 
[157]1015     || (strict && (ret_val->cell_size & 0x00000007) != 0))
[102]1016  {
[182]1017    regfi_log_add(REGFI_LOG_WARN, "Invalid cell size found while"
[138]1018                      " parsing SK record at offset 0x%.8X.", offset);
[180]1019    goto fail_locked;
[102]1020  }
[30]1021
[102]1022  ret_val->magic[0] = sk_header[0];
1023  ret_val->magic[1] = sk_header[1];
[30]1024
[102]1025  ret_val->unknown_tag = SVAL(sk_header, 0x2);
1026  ret_val->prev_sk_off = IVAL(sk_header, 0x4);
1027  ret_val->next_sk_off = IVAL(sk_header, 0x8);
1028  ret_val->ref_count = IVAL(sk_header, 0xC);
1029  ret_val->desc_size = IVAL(sk_header, 0x10);
[30]1030
[157]1031  if((ret_val->prev_sk_off & 0x00000007) != 0
1032     || (ret_val->next_sk_off & 0x00000007) != 0)
[140]1033  {
[182]1034    regfi_log_add(REGFI_LOG_WARN, "SK record's next/previous offsets"
[140]1035                      " are not a multiple of 8 while parsing SK record at"
1036                      " offset 0x%.8X.", offset);
[180]1037    goto fail_locked;
[140]1038  }
1039
[102]1040  if(ret_val->desc_size + REGFI_SK_MIN_LENGTH > ret_val->cell_size)
1041  {
[182]1042    regfi_log_add(REGFI_LOG_WARN, "Security descriptor too large for"
[138]1043                      " cell while parsing SK record at offset 0x%.8X.", 
1044                      offset);
[180]1045    goto fail_locked;
[102]1046  }
[30]1047
[168]1048  sec_desc_buf = (uint8_t*)malloc(ret_val->desc_size);
[147]1049  if(sec_desc_buf == NULL)
[180]1050    goto fail_locked;
[102]1051
[134]1052  length = ret_val->desc_size;
[178]1053  if(regfi_read(file->cb, sec_desc_buf, &length) != 0 
[134]1054     || length != ret_val->desc_size)
1055  {
[182]1056    regfi_log_add(REGFI_LOG_ERROR, "Failed to read security"
[138]1057                      " descriptor while parsing SK record at offset 0x%.8X.",
1058                      offset);
[180]1059    goto fail_locked;
[134]1060  }
[102]1061
[186]1062  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_sk"))
[180]1063     goto fail;
1064
[147]1065  if(!(ret_val->sec_desc = winsec_parse_desc(ret_val, sec_desc_buf, 
1066                                                   ret_val->desc_size)))
[134]1067  {
[182]1068    regfi_log_add(REGFI_LOG_ERROR, "Failed to parse security"
[138]1069                      " descriptor while parsing SK record at offset 0x%.8X.",
1070                      offset);
[147]1071    goto fail;
[134]1072  }
[147]1073
[134]1074  free(sec_desc_buf);
[147]1075  return ret_val;
[134]1076
[180]1077 fail_locked:
[186]1078  regfi_unlock(file, &file->cb_lock, "regfi_parse_sk");
[147]1079 fail:
1080  if(sec_desc_buf != NULL)
1081    free(sec_desc_buf);
1082  talloc_free(ret_val);
1083  return NULL;
[30]1084}
1085
1086
[168]1087REGFI_VALUE_LIST* regfi_parse_valuelist(REGFI_FILE* file, uint32_t offset, 
1088                                        uint32_t num_values, bool strict)
[111]1089{
[145]1090  REGFI_VALUE_LIST* ret_val;
[168]1091  uint32_t i, cell_length, length, read_len;
[111]1092  bool unalloc;
[30]1093
[186]1094  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_valuelist"))
[180]1095     goto fail;
1096
[178]1097  if(!regfi_parse_cell(file->cb, offset, NULL, 0, &cell_length, &unalloc))
[137]1098  {
[182]1099    regfi_log_add(REGFI_LOG_ERROR, "Failed to read cell header"
[137]1100                      " while parsing value list at offset 0x%.8X.", offset);
[180]1101    goto fail_locked;
[137]1102  }
[111]1103
[157]1104  if((cell_length & 0x00000007) != 0)
[111]1105  {
[182]1106    regfi_log_add(REGFI_LOG_WARN, "Cell length not a multiple of 8"
[145]1107                      " while parsing value list at offset 0x%.8X.", offset);
[111]1108    if(strict)
[180]1109      goto fail_locked;
[111]1110    cell_length = cell_length & 0xFFFFFFF8;
1111  }
[145]1112
[168]1113  if((num_values * sizeof(uint32_t)) > cell_length-sizeof(uint32_t))
[137]1114  {
[182]1115    regfi_log_add(REGFI_LOG_WARN, "Too many values found"
[137]1116                      " while parsing value list at offset 0x%.8X.", offset);
[145]1117    if(strict)
[180]1118      goto fail_locked;
[168]1119    num_values = cell_length/sizeof(uint32_t) - sizeof(uint32_t);
[137]1120  }
[111]1121
[168]1122  read_len = num_values*sizeof(uint32_t);
[150]1123  ret_val = talloc(NULL, REGFI_VALUE_LIST);
[111]1124  if(ret_val == NULL)
[180]1125    goto fail_locked;
[111]1126
[150]1127  ret_val->elements = (REGFI_VALUE_LIST_ELEM*)talloc_size(ret_val, read_len);
[145]1128  if(ret_val->elements == NULL)
[180]1129    goto fail_locked;
1130
[145]1131  ret_val->num_values = num_values;
1132
[111]1133  length = read_len;
[178]1134  if((regfi_read(file->cb, (uint8_t*)ret_val->elements, &length) != 0) 
[145]1135     || length != read_len)
[111]1136  {
[182]1137    regfi_log_add(REGFI_LOG_ERROR, "Failed to read value pointers"
[137]1138                      " while parsing value list at offset 0x%.8X.", offset);
[180]1139    goto fail_locked;
[111]1140  }
1141 
[186]1142  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_valuelist"))
[180]1143     goto fail;
1144
[111]1145  for(i=0; i < num_values; i++)
1146  {
1147    /* Fix endianness */
[145]1148    ret_val->elements[i] = IVAL(&ret_val->elements[i], 0);
[111]1149
1150    /* Validate the first num_values values to ensure they make sense */
1151    if(strict)
1152    {
[145]1153      /* XXX: Need to revisit this file length check when we start dealing
1154       *      with partial files. */
1155      if((ret_val->elements[i] + REGFI_REGF_SIZE > file->file_length)
[157]1156         || ((ret_val->elements[i] & 0x00000007) != 0))
[111]1157      {
[182]1158        regfi_log_add(REGFI_LOG_WARN, "Invalid value pointer"
[138]1159                          " (0x%.8X) found while parsing value list at offset"
[145]1160                          " 0x%.8X.", ret_val->elements[i], offset);
[180]1161        goto fail;
[111]1162      }
1163    }
1164  }
1165
1166  return ret_val;
[180]1167
1168 fail_locked:
[186]1169  regfi_unlock(file, &file->cb_lock, "regfi_parse_valuelist");
[180]1170 fail:
1171  talloc_free(ret_val);
1172  return NULL;
[111]1173}
1174
1175
[172]1176void regfi_interpret_valuename(REGFI_FILE* file, REGFI_VK_REC* vk, 
[162]1177                               REGFI_ENCODING output_encoding, bool strict)
[30]1178{
[165]1179  /* XXX: Registry value names are supposedly limited to 16383 characters
1180   *      according to:
1181   *      http://msdn.microsoft.com/en-us/library/ms724872%28VS.85%29.aspx
1182   *      Might want to emit a warning if this is exceeded. 
1183   *      It is expected that "characters" could be variable width.
1184   *      Also, it may be useful to use this information to limit false positives
1185   *      when recovering deleted VK records.
1186   */
[172]1187  int32_t tmp_size;
1188  REGFI_ENCODING from_encoding = (vk->flags & REGFI_VK_FLAG_ASCIINAME)
[162]1189    ? REGFI_ENCODING_ASCII : REGFI_ENCODING_UTF16LE;
[151]1190
[162]1191  if(from_encoding == output_encoding)
1192  {
[172]1193    vk->valuename_raw = talloc_realloc(vk, vk->valuename_raw,
1194                                            uint8_t, vk->name_length+1);
1195    vk->valuename_raw[vk->name_length] = '\0';
1196    vk->valuename = (char*)vk->valuename_raw;
[162]1197  }
1198  else
1199  {
[172]1200    vk->valuename = talloc_array(vk, char, vk->name_length+1);
1201    if(vk->valuename == NULL)
[162]1202    {
[184]1203      talloc_free(vk);
[172]1204      return;
[162]1205    }
1206
1207    tmp_size = regfi_conv_charset(regfi_encoding_int2str(from_encoding),
1208                                  regfi_encoding_int2str(output_encoding),
[172]1209                                  vk->valuename_raw, vk->valuename,
1210                                  vk->name_length, vk->name_length+1);
[162]1211    if(tmp_size < 0)
1212    {
[182]1213      regfi_log_add(REGFI_LOG_WARN, "Error occurred while converting"
[162]1214                        " valuename to encoding %s.  Error message: %s",
1215                        regfi_encoding_int2str(output_encoding), 
1216                        strerror(-tmp_size));
[172]1217      talloc_free(vk->valuename);
1218      vk->valuename = NULL;
[162]1219    }
1220  }
[172]1221}
[162]1222
[172]1223
1224/******************************************************************************
1225 ******************************************************************************/
1226REGFI_VK_REC* regfi_load_value(REGFI_FILE* file, uint32_t offset, 
1227                               REGFI_ENCODING output_encoding, bool strict)
1228{
1229  REGFI_VK_REC* ret_val = NULL;
1230  int32_t max_size;
1231
1232  max_size = regfi_calc_maxsize(file, offset);
1233  if(max_size < 0)
1234    return NULL;
1235 
1236  ret_val = regfi_parse_vk(file, offset, max_size, strict);
1237  if(ret_val == NULL)
1238    return NULL;
1239
1240  regfi_interpret_valuename(file, ret_val, output_encoding, strict);
1241
[103]1242  return ret_val;
[30]1243}
1244
1245
[145]1246/******************************************************************************
1247 * If !strict, the list may contain NULLs, VK records may point to NULL.
1248 ******************************************************************************/
[168]1249REGFI_VALUE_LIST* regfi_load_valuelist(REGFI_FILE* file, uint32_t offset, 
1250                                       uint32_t num_values, uint32_t max_size,
[145]1251                                       bool strict)
1252{
[168]1253  uint32_t usable_num_values;
[30]1254
[168]1255  if((num_values+1) * sizeof(uint32_t) > max_size)
[145]1256  {
[182]1257    regfi_log_add(REGFI_LOG_WARN, "Number of values indicated by"
[145]1258                      " parent key (%d) would cause cell to straddle HBIN"
1259                      " boundary while loading value list at offset"
1260                      " 0x%.8X.", num_values, offset);
1261    if(strict)
1262      return NULL;
[168]1263    usable_num_values = max_size/sizeof(uint32_t) - sizeof(uint32_t);
[145]1264  }
1265  else
1266    usable_num_values = num_values;
1267
1268  return regfi_parse_valuelist(file, offset, usable_num_values, strict);
1269}
1270
1271
[172]1272void regfi_interpret_keyname(REGFI_FILE* file, REGFI_NK_REC* nk, 
[161]1273                             REGFI_ENCODING output_encoding, bool strict)
[30]1274{
[165]1275  /* XXX: Registry key names are supposedly limited to 255 characters according to:
1276   *      http://msdn.microsoft.com/en-us/library/ms724872%28VS.85%29.aspx
1277   *      Might want to emit a warning if this is exceeded. 
1278   *      It is expected that "characters" could be variable width.
1279   *      Also, it may be useful to use this information to limit false positives
1280   *      when recovering deleted NK records.
1281   */
[172]1282  int32_t tmp_size;
1283  REGFI_ENCODING from_encoding = (nk->flags & REGFI_NK_FLAG_ASCIINAME) 
[161]1284    ? REGFI_ENCODING_ASCII : REGFI_ENCODING_UTF16LE;
[172]1285 
[161]1286  if(from_encoding == output_encoding)
1287  {
[168]1288    nk->keyname_raw = talloc_realloc(nk, nk->keyname_raw, uint8_t, nk->name_length+1);
[161]1289    nk->keyname_raw[nk->name_length] = '\0';
1290    nk->keyname = (char*)nk->keyname_raw;
1291  }
1292  else
1293  {
1294    nk->keyname = talloc_array(nk, char, nk->name_length+1);
1295    if(nk->keyname == NULL)
1296    {
[184]1297      talloc_free(nk);
[172]1298      return;
[161]1299    }
1300
1301    tmp_size = regfi_conv_charset(regfi_encoding_int2str(from_encoding),
1302                                  regfi_encoding_int2str(output_encoding),
1303                                  nk->keyname_raw, nk->keyname,
1304                                  nk->name_length, nk->name_length+1);
1305    if(tmp_size < 0)
1306    {
[182]1307      regfi_log_add(REGFI_LOG_WARN, "Error occurred while converting"
[161]1308                        " keyname to encoding %s.  Error message: %s",
1309                        regfi_encoding_int2str(output_encoding), 
1310                        strerror(-tmp_size));
1311      talloc_free(nk->keyname);
1312      nk->keyname = NULL;
1313    }
1314  }
[172]1315}
[161]1316
1317
[172]1318/******************************************************************************
1319 *
1320 ******************************************************************************/
1321REGFI_NK_REC* regfi_load_key(REGFI_FILE* file, uint32_t offset, 
1322                             REGFI_ENCODING output_encoding, bool strict)
1323{
1324  REGFI_NK_REC* nk;
1325  uint32_t off;
1326  int32_t max_size;
1327
1328  max_size = regfi_calc_maxsize(file, offset);
1329  if (max_size < 0) 
1330    return NULL;
1331
1332  /* get the initial nk record */
1333  if((nk = regfi_parse_nk(file, offset, max_size, true)) == NULL)
1334  {
[182]1335    regfi_log_add(REGFI_LOG_ERROR, "Could not load NK record at"
1336                  " offset 0x%.8X.", offset);
[172]1337    return NULL;
1338  }
1339
1340  regfi_interpret_keyname(file, nk, output_encoding, strict);
1341
[146]1342  /* get value list */
[135]1343  if(nk->num_values && (nk->values_off!=REGFI_OFFSET_NONE)) 
[32]1344  {
[157]1345    off = nk->values_off + REGFI_REGF_SIZE;
1346    max_size = regfi_calc_maxsize(file, off);
1347    if(max_size < 0)
[32]1348    {
[105]1349      if(strict)
[32]1350      {
[184]1351        talloc_free(nk);
[99]1352        return NULL;
[31]1353      }
[105]1354      else
1355        nk->values = NULL;
[133]1356
[31]1357    }
[105]1358    else
[103]1359    {
[157]1360      nk->values = regfi_load_valuelist(file, off, nk->num_values, 
1361                                        max_size, true);
[145]1362      if(nk->values == NULL)
[105]1363      {
[182]1364        regfi_log_add(REGFI_LOG_WARN, "Could not load value list"
1365                      " for NK record at offset 0x%.8X.", offset);
[145]1366        if(strict)
1367        {
[184]1368          talloc_free(nk);
[145]1369          return NULL;
1370        }
[105]1371      }
[181]1372      talloc_steal(nk, nk->values);
[103]1373    }
[31]1374  }
[105]1375
[146]1376  /* now get subkey list */
[135]1377  if(nk->num_subkeys && (nk->subkeys_off != REGFI_OFFSET_NONE)) 
[32]1378  {
[157]1379    off = nk->subkeys_off + REGFI_REGF_SIZE;
1380    max_size = regfi_calc_maxsize(file, off);
1381    if(max_size < 0) 
[32]1382    {
[105]1383      if(strict)
[32]1384      {
[184]1385        talloc_free(nk);
[99]1386        return NULL;
[31]1387      }
[105]1388      else
1389        nk->subkeys = NULL;
[31]1390    }
[105]1391    else
[104]1392    {
[134]1393      nk->subkeys = regfi_load_subkeylist(file, off, nk->num_subkeys,
[157]1394                                          max_size, true);
[134]1395
[105]1396      if(nk->subkeys == NULL)
1397      {
[182]1398        regfi_log_add(REGFI_LOG_WARN, "Could not load subkey list"
1399                      " while parsing NK record at offset 0x%.8X.", offset);
[105]1400        nk->num_subkeys = 0;
1401      }
[181]1402      talloc_steal(nk, nk->subkeys);
[104]1403    }
[31]1404  }
[30]1405
[99]1406  return nk;
[30]1407}
1408
[32]1409
[102]1410/******************************************************************************
1411 ******************************************************************************/
[168]1412const REGFI_SK_REC* regfi_load_sk(REGFI_FILE* file, uint32_t offset, bool strict)
[146]1413{
1414  REGFI_SK_REC* ret_val = NULL;
[168]1415  int32_t max_size;
[147]1416  void* failure_ptr = NULL;
1417 
[184]1418  max_size = regfi_calc_maxsize(file, offset);
1419  if(max_size < 0)
1420    return NULL;
1421
1422  if(file->sk_cache == NULL)
1423    return regfi_parse_sk(file, offset, max_size, strict);
1424
[186]1425  if(!regfi_lock(file, &file->sk_lock, "regfi_load_sk"))
[180]1426    return NULL;
1427
[146]1428  /* First look if we have already parsed it */
1429  ret_val = (REGFI_SK_REC*)lru_cache_find(file->sk_cache, &offset, 4);
1430
1431  /* Bail out if we have previously cached a parse failure at this offset. */
1432  if(ret_val == (void*)REGFI_OFFSET_NONE)
1433    return NULL;
1434
1435  if(ret_val == NULL)
1436  {
[157]1437    ret_val = regfi_parse_sk(file, offset, max_size, strict);
[146]1438    if(ret_val == NULL)
1439    { /* Cache the parse failure and bail out. */
[147]1440      failure_ptr = talloc(NULL, uint32_t);
1441      if(failure_ptr == NULL)
1442        return NULL;
1443      *(uint32_t*)failure_ptr = REGFI_OFFSET_NONE;
1444      lru_cache_update(file->sk_cache, &offset, 4, failure_ptr);
[184]1445
1446      /* Let the cache be the only owner of this */
1447      talloc_unlink(NULL, failure_ptr);
[146]1448      return NULL;
1449    }
1450  }
1451
[186]1452  if(!regfi_unlock(file, &file->sk_lock, "regfi_load_sk"))
[184]1453  {
1454    talloc_unlink(NULL, ret_val);
[180]1455    return NULL;
[184]1456  }
[180]1457
[146]1458  return ret_val;
1459}
1460
1461
1462
1463/******************************************************************************
1464 ******************************************************************************/
[161]1465REGFI_NK_REC* regfi_find_root_nk(REGFI_FILE* file, const REGFI_HBIN* hbin, 
1466                                 REGFI_ENCODING output_encoding)
[30]1467{
[135]1468  REGFI_NK_REC* nk = NULL;
[168]1469  uint32_t cell_length;
1470  uint32_t cur_offset = hbin->file_off+REGFI_HBIN_HEADER_SIZE;
1471  uint32_t hbin_end = hbin->file_off+hbin->block_size;
[158]1472  bool unalloc;
[30]1473
[158]1474  while(cur_offset < hbin_end)
[32]1475  {
[180]1476
[186]1477    if(!regfi_lock(file, &file->cb_lock, "regfi_find_root_nk"))
[180]1478      return NULL;
1479
[178]1480    if(!regfi_parse_cell(file->cb, cur_offset, NULL, 0, &cell_length, &unalloc))
[158]1481    {
[182]1482      regfi_log_add(REGFI_LOG_WARN, "Could not parse cell at offset"
1483                    " 0x%.8X while searching for root key.", cur_offset);
[158]1484      return NULL;
1485    }
[180]1486
[186]1487    if(!regfi_unlock(file, &file->cb_lock, "regfi_find_root_nk"))
[180]1488      return NULL;
1489
[158]1490    if(!unalloc)
[102]1491    {
[161]1492      nk = regfi_load_key(file, cur_offset, output_encoding, true);
[102]1493      if(nk != NULL)
1494      {
[161]1495        if(nk->flags & REGFI_NK_FLAG_ROOT)
[158]1496          return nk;
[102]1497      }
[31]1498    }
[30]1499
[158]1500    cur_offset += cell_length;
[31]1501  }
[32]1502
[158]1503  return NULL;
[30]1504}
1505
1506
[178]1507
[166]1508/******************************************************************************
1509 ******************************************************************************/
[178]1510REGFI_FILE* regfi_alloc(int fd)
[30]1511{
[166]1512  REGFI_FILE* ret_val;
[178]1513  REGFI_RAW_FILE* file_cb = talloc(NULL, REGFI_RAW_FILE);
1514  if(file_cb == NULL) 
[31]1515    return NULL;
[166]1516
[178]1517  file_cb->state = (void*)talloc(file_cb, int);
1518  if(file_cb->state == NULL)
1519    goto fail;
1520  *(int*)file_cb->state = fd;
1521 
1522  file_cb->cur_off = 0;
1523  file_cb->size = 0;
1524  file_cb->read = &regfi_raw_read;
1525  file_cb->seek = &regfi_raw_seek;
1526 
1527  ret_val = regfi_alloc_cb(file_cb);
[166]1528  if(ret_val == NULL)
[178]1529    goto fail;
[166]1530
[178]1531  /* In this case, we want file_cb to be freed when ret_val is */
[181]1532  talloc_steal(ret_val, file_cb);
[166]1533  return ret_val;
[178]1534
1535 fail:
1536    talloc_free(file_cb);
1537    return NULL;
[166]1538}
1539
1540
[186]1541/******************************************************************************
1542 ******************************************************************************/
1543int regfi_free_cb(void* f)
1544{
1545  REGFI_FILE* file = (REGFI_FILE*)f;
[178]1546
[186]1547  pthread_mutex_destroy(&file->cb_lock);
1548  pthread_rwlock_destroy(&file->hbins_lock);
1549  pthread_mutex_destroy(&file->sk_lock);
1550
1551  return 0;
1552}
1553
1554
1555/******************************************************************************
1556 ******************************************************************************/
[178]1557REGFI_FILE* regfi_alloc_cb(REGFI_RAW_FILE* file_cb)
[166]1558{
1559  REGFI_FILE* rb;
1560  REGFI_HBIN* hbin = NULL;
[178]1561  uint32_t hbin_off, cache_secret;
1562  int32_t file_length;
[166]1563  bool rla;
1564
[178]1565  /* Determine file length.  Must be at least big enough for the header
1566   * and one hbin.
[137]1567   */
[178]1568  file_length = file_cb->seek(file_cb, 0, SEEK_END);
[137]1569  if(file_length < REGFI_REGF_SIZE+REGFI_HBIN_ALLOC)
[182]1570  {
1571    regfi_log_add(REGFI_LOG_ERROR, "File length (%d) too short to contain a"
1572                  " header and at least one HBIN.", file_length);
[137]1573    return NULL;
[182]1574  }
[178]1575  file_cb->seek(file_cb, 0, SEEK_SET);
[137]1576
[166]1577  /* Read file header */
[182]1578  if ((rb = regfi_parse_regf(file_cb, false)) == NULL) 
[97]1579  {
[182]1580    regfi_log_add(REGFI_LOG_ERROR, "Failed to read REGF block.");
[31]1581    return NULL;
1582  }
[137]1583  rb->file_length = file_length; 
[178]1584  rb->cb = file_cb;
[137]1585
[186]1586  if(pthread_mutex_init(&rb->cb_lock, NULL) != 0)
[182]1587  {
1588    regfi_log_add(REGFI_LOG_ERROR, "Failed to create cb_lock mutex.");
[180]1589    goto fail;
[182]1590  }
[180]1591
[186]1592  if(pthread_rwlock_init(&rb->hbins_lock, NULL) != 0)
[182]1593  {
1594    regfi_log_add(REGFI_LOG_ERROR, "Failed to create hbins_lock rwlock.");
[180]1595    goto fail;
[182]1596  }
[180]1597
[186]1598  if(pthread_mutex_init(&rb->sk_lock, NULL) != 0)
[182]1599  {
1600    regfi_log_add(REGFI_LOG_ERROR, "Failed to create sk_lock mutex.");
[180]1601    goto fail;
[182]1602  }
[180]1603
[99]1604  rb->hbins = range_list_new();
[110]1605  if(rb->hbins == NULL)
[182]1606  {
1607    regfi_log_add(REGFI_LOG_ERROR, "Failed to create HBIN range_list.");
[180]1608    goto fail;
[182]1609  }
[181]1610  talloc_steal(rb, rb->hbins);
[150]1611
[106]1612  rla = true;
[135]1613  hbin_off = REGFI_REGF_SIZE;
[110]1614  hbin = regfi_parse_hbin(rb, hbin_off, true);
[106]1615  while(hbin && rla)
1616  {
[137]1617    rla = range_list_add(rb->hbins, hbin->file_off, hbin->block_size, hbin);
[148]1618    if(rla)
[181]1619      talloc_steal(rb->hbins, hbin);
[180]1620
[106]1621    hbin_off = hbin->file_off + hbin->block_size;
[110]1622    hbin = regfi_parse_hbin(rb, hbin_off, true);
[106]1623  }
1624
[146]1625  /* This secret isn't very secret, but we don't need a good one.  This
1626   * secret is just designed to prevent someone from trying to blow our
1627   * caching and make things slow.
1628   */
1629  cache_secret = 0x15DEAD05^time(NULL)^(getpid()<<16);
1630
[184]1631  if(REGFI_CACHE_SK)
1632    rb->sk_cache = lru_cache_create_ctx(rb, 64, cache_secret, true);
1633  else
1634    rb->sk_cache = NULL;
[146]1635
[31]1636  /* success */
[186]1637  talloc_set_destructor(rb, regfi_free_cb);
[31]1638  return rb;
[180]1639
1640 fail:
[186]1641  pthread_mutex_destroy(&rb->cb_lock);
1642  pthread_rwlock_destroy(&rb->hbins_lock);
1643  pthread_mutex_destroy(&rb->sk_lock);
[180]1644
1645  range_list_free(rb->hbins);
1646  talloc_free(rb);
1647  return NULL;
[30]1648}
1649
1650
[148]1651/******************************************************************************
1652 ******************************************************************************/
[186]1653void regfi_free(REGFI_FILE* file)
[166]1654{
[186]1655  /* Callback handles cleanup side effects */
[150]1656  talloc_free(file);
[30]1657}
1658
1659
[80]1660/******************************************************************************
[158]1661 * First checks the offset given by the file header, then checks the
1662 * rest of the file if that fails.
[148]1663 ******************************************************************************/
[161]1664REGFI_NK_REC* regfi_rootkey(REGFI_FILE* file, REGFI_ENCODING output_encoding)
[30]1665{
[135]1666  REGFI_NK_REC* nk = NULL;
[146]1667  REGFI_HBIN* hbin;
[168]1668  uint32_t root_offset, i, num_hbins;
[99]1669 
1670  if(!file)
[31]1671    return NULL;
[99]1672
[158]1673  root_offset = file->root_cell+REGFI_REGF_SIZE;
[161]1674  nk = regfi_load_key(file, root_offset, output_encoding, true);
[158]1675  if(nk != NULL)
1676  {
[161]1677    if(nk->flags & REGFI_NK_FLAG_ROOT)
[158]1678      return nk;
1679  }
1680
[182]1681  regfi_log_add(REGFI_LOG_WARN, "File header indicated root key at"
1682                " location 0x%.8X, but no root key found."
1683                " Searching rest of file...", root_offset);
[158]1684 
1685  /* If the file header gives bad info, scan through the file one HBIN
1686   * block at a time looking for an NK record with a root key type.
[146]1687   */
[180]1688 
[186]1689  if(!regfi_read_lock(file, &file->hbins_lock, "regfi_rootkey"))
[180]1690    return NULL;
1691
[107]1692  num_hbins = range_list_size(file->hbins);
[158]1693  for(i=0; i < num_hbins && nk == NULL; i++)
[99]1694  {
[135]1695    hbin = (REGFI_HBIN*)range_list_get(file->hbins, i)->data;
[161]1696    nk = regfi_find_root_nk(file, hbin, output_encoding);
[31]1697  }
[30]1698
[186]1699  if(!regfi_rw_unlock(file, &file->hbins_lock, "regfi_rootkey"))
[180]1700    return NULL;
1701
[80]1702  return nk;
[30]1703}
1704
1705
[80]1706/******************************************************************************
1707 *****************************************************************************/
[184]1708void regfi_free_record(const void* record)
[30]1709{
[184]1710  talloc_unlink(NULL, (void*)record);
[150]1711}
[127]1712
[80]1713
1714
1715/******************************************************************************
1716 *****************************************************************************/
[161]1717REGFI_ITERATOR* regfi_iterator_new(REGFI_FILE* file, 
1718                                   REGFI_ENCODING output_encoding)
[80]1719{
[135]1720  REGFI_NK_REC* root;
[161]1721  REGFI_ITERATOR* ret_val;
1722
1723  if(output_encoding != REGFI_ENCODING_UTF8
1724     && output_encoding != REGFI_ENCODING_ASCII)
1725  { 
[182]1726    regfi_log_add(REGFI_LOG_ERROR, "Invalid output_encoding supplied"
1727                  " in creation of regfi iterator.");
[161]1728    return NULL;
1729  }
1730
1731  ret_val = talloc(NULL, REGFI_ITERATOR);
[80]1732  if(ret_val == NULL)
1733    return NULL;
1734
[161]1735  root = regfi_rootkey(file, output_encoding);
[80]1736  if(root == NULL)
1737  {
[150]1738    talloc_free(ret_val);
[80]1739    return NULL;
1740  }
[181]1741  ret_val->cur_key = root;
[184]1742  talloc_reference(ret_val, root);
[80]1743
[135]1744  ret_val->key_positions = void_stack_new(REGFI_MAX_DEPTH);
[80]1745  if(ret_val->key_positions == NULL)
1746  {
[150]1747    talloc_free(ret_val);
[80]1748    return NULL;
1749  }
[181]1750  talloc_steal(ret_val, ret_val->key_positions);
[80]1751
[159]1752  ret_val->f = file;
[80]1753  ret_val->cur_subkey = 0;
1754  ret_val->cur_value = 0;
[161]1755  ret_val->string_encoding = output_encoding;
1756   
[80]1757  return ret_val;
1758}
1759
1760
1761/******************************************************************************
1762 *****************************************************************************/
1763void regfi_iterator_free(REGFI_ITERATOR* i)
1764{
[150]1765  talloc_free(i);
[80]1766}
1767
1768
1769
1770/******************************************************************************
1771 *****************************************************************************/
1772/* XXX: some way of indicating reason for failure should be added. */
1773bool regfi_iterator_down(REGFI_ITERATOR* i)
1774{
[135]1775  REGFI_NK_REC* subkey;
[80]1776  REGFI_ITER_POSITION* pos;
1777
[150]1778  pos = talloc(i->key_positions, REGFI_ITER_POSITION);
[80]1779  if(pos == NULL)
1780    return false;
1781
[135]1782  subkey = (REGFI_NK_REC*)regfi_iterator_cur_subkey(i);
[80]1783  if(subkey == NULL)
1784  {
[150]1785    talloc_free(pos);
[80]1786    return false;
1787  }
1788
1789  pos->nk = i->cur_key;
1790  pos->cur_subkey = i->cur_subkey;
1791  if(!void_stack_push(i->key_positions, pos))
1792  {
[150]1793    talloc_free(pos);
[184]1794    talloc_unlink(NULL, subkey);
[80]1795    return false;
1796  }
[184]1797  talloc_reference(i, subkey);
[80]1798
1799  i->cur_key = subkey;
1800  i->cur_subkey = 0;
1801  i->cur_value = 0;
1802
1803  return true;
1804}
1805
1806
1807/******************************************************************************
1808 *****************************************************************************/
1809bool regfi_iterator_up(REGFI_ITERATOR* i)
1810{
1811  REGFI_ITER_POSITION* pos;
1812
1813  pos = (REGFI_ITER_POSITION*)void_stack_pop(i->key_positions);
1814  if(pos == NULL)
1815    return false;
1816
[184]1817  talloc_unlink(i, i->cur_key);
[80]1818  i->cur_key = pos->nk;
1819  i->cur_subkey = pos->cur_subkey;
1820  i->cur_value = 0;
[150]1821  talloc_free(pos);
[80]1822
1823  return true;
1824}
1825
1826
1827/******************************************************************************
1828 *****************************************************************************/
1829bool regfi_iterator_to_root(REGFI_ITERATOR* i)
1830{
1831  while(regfi_iterator_up(i))
1832    continue;
1833
1834  return true;
1835}
1836
1837
1838/******************************************************************************
1839 *****************************************************************************/
1840bool regfi_iterator_find_subkey(REGFI_ITERATOR* i, const char* subkey_name)
1841{
[135]1842  REGFI_NK_REC* subkey;
[80]1843  bool found = false;
[168]1844  uint32_t old_subkey = i->cur_subkey;
[133]1845
[80]1846  if(subkey_name == NULL)
1847    return false;
1848
1849  /* XXX: this alloc/free of each sub key might be a bit excessive */
[135]1850  subkey = (REGFI_NK_REC*)regfi_iterator_first_subkey(i);
[80]1851  while((subkey != NULL) && (found == false))
1852  {
1853    if(subkey->keyname != NULL 
1854       && strcasecmp(subkey->keyname, subkey_name) == 0)
1855      found = true;
[82]1856    else
1857    {
[184]1858      talloc_unlink(NULL, subkey);
[135]1859      subkey = (REGFI_NK_REC*)regfi_iterator_next_subkey(i);
[82]1860    }
[80]1861  }
1862
1863  if(found == false)
1864  {
1865    i->cur_subkey = old_subkey;
1866    return false;
1867  }
1868
[184]1869  talloc_unlink(NULL, subkey);
[80]1870  return true;
1871}
1872
1873
1874/******************************************************************************
1875 *****************************************************************************/
1876bool regfi_iterator_walk_path(REGFI_ITERATOR* i, const char** path)
1877{
[168]1878  uint32_t x;
[80]1879  if(path == NULL)
1880    return false;
1881
1882  for(x=0; 
1883      ((path[x] != NULL) && regfi_iterator_find_subkey(i, path[x])
1884       && regfi_iterator_down(i));
1885      x++)
1886  { continue; }
1887
1888  if(path[x] == NULL)
1889    return true;
1890 
1891  /* XXX: is this the right number of times? */
1892  for(; x > 0; x--)
1893    regfi_iterator_up(i);
1894 
1895  return false;
1896}
1897
1898
1899/******************************************************************************
1900 *****************************************************************************/
[135]1901const REGFI_NK_REC* regfi_iterator_cur_key(REGFI_ITERATOR* i)
[80]1902{
1903  return i->cur_key;
1904}
1905
1906
1907/******************************************************************************
1908 *****************************************************************************/
[135]1909const REGFI_SK_REC* regfi_iterator_cur_sk(REGFI_ITERATOR* i)
[109]1910{
[146]1911  if(i->cur_key == NULL || i->cur_key->sk_off == REGFI_OFFSET_NONE)
[109]1912    return NULL;
1913
[146]1914  return regfi_load_sk(i->f, i->cur_key->sk_off + REGFI_REGF_SIZE, true);
[109]1915}
1916
1917
1918/******************************************************************************
1919 *****************************************************************************/
[184]1920const REGFI_NK_REC* regfi_iterator_first_subkey(REGFI_ITERATOR* i)
[80]1921{
1922  i->cur_subkey = 0;
1923  return regfi_iterator_cur_subkey(i);
1924}
1925
1926
1927/******************************************************************************
1928 *****************************************************************************/
[184]1929const REGFI_NK_REC* regfi_iterator_cur_subkey(REGFI_ITERATOR* i)
[80]1930{
[168]1931  uint32_t nk_offset;
[80]1932
[31]1933  /* see if there is anything left to report */
[135]1934  if (!(i->cur_key) || (i->cur_key->subkeys_off==REGFI_OFFSET_NONE)
[80]1935      || (i->cur_subkey >= i->cur_key->num_subkeys))
[31]1936    return NULL;
[30]1937
[139]1938  nk_offset = i->cur_key->subkeys->elements[i->cur_subkey].offset;
[133]1939
[184]1940  return regfi_load_key(i->f, nk_offset+REGFI_REGF_SIZE, 
1941                        i->string_encoding, true);
[30]1942}
[80]1943
1944
1945/******************************************************************************
1946 *****************************************************************************/
1947/* XXX: some way of indicating reason for failure should be added. */
[184]1948const REGFI_NK_REC* regfi_iterator_next_subkey(REGFI_ITERATOR* i)
[80]1949{
[184]1950  const REGFI_NK_REC* subkey;
[80]1951
1952  i->cur_subkey++;
1953  subkey = regfi_iterator_cur_subkey(i);
1954
1955  if(subkey == NULL)
1956    i->cur_subkey--;
1957
1958  return subkey;
1959}
1960
1961
1962/******************************************************************************
1963 *****************************************************************************/
1964bool regfi_iterator_find_value(REGFI_ITERATOR* i, const char* value_name)
1965{
[184]1966  const REGFI_VK_REC* cur;
[80]1967  bool found = false;
[168]1968  uint32_t old_value = i->cur_value;
[80]1969
1970  /* XXX: cur->valuename can be NULL in the registry. 
1971   *      Should we allow for a way to search for that?
1972   */
1973  if(value_name == NULL)
1974    return false;
1975
1976  cur = regfi_iterator_first_value(i);
1977  while((cur != NULL) && (found == false))
1978  {
1979    if((cur->valuename != NULL)
1980       && (strcasecmp(cur->valuename, value_name) == 0))
1981      found = true;
[95]1982    else
[150]1983    {
[184]1984      regfi_free_record(cur);
[95]1985      cur = regfi_iterator_next_value(i);
[150]1986    }
[80]1987  }
[167]1988 
1989  if(found == false)
1990  {
1991    i->cur_value = old_value;
1992    return false;
1993  }
[80]1994
[184]1995  regfi_free_record(cur);
[167]1996  return true;
[80]1997}
1998
1999
2000/******************************************************************************
2001 *****************************************************************************/
[184]2002const REGFI_VK_REC* regfi_iterator_first_value(REGFI_ITERATOR* i)
[80]2003{
2004  i->cur_value = 0;
2005  return regfi_iterator_cur_value(i);
2006}
2007
2008
2009/******************************************************************************
2010 *****************************************************************************/
[184]2011const REGFI_VK_REC* regfi_iterator_cur_value(REGFI_ITERATOR* i)
[80]2012{
[150]2013  REGFI_VK_REC* ret_val = NULL;
[168]2014  uint32_t voffset;
[80]2015
[145]2016  if(i->cur_key->values != NULL && i->cur_key->values->elements != NULL)
2017  {
2018    if(i->cur_value < i->cur_key->values->num_values)
2019    {
2020      voffset = i->cur_key->values->elements[i->cur_value];
[162]2021      ret_val = regfi_load_value(i->f, voffset+REGFI_REGF_SIZE, 
2022                                 i->string_encoding, true);
[145]2023    }
2024  }
2025
[80]2026  return ret_val;
2027}
2028
2029
2030/******************************************************************************
2031 *****************************************************************************/
[184]2032const REGFI_VK_REC* regfi_iterator_next_value(REGFI_ITERATOR* i)
[80]2033{
[184]2034  const REGFI_VK_REC* ret_val;
[80]2035
2036  i->cur_value++;
2037  ret_val = regfi_iterator_cur_value(i);
2038  if(ret_val == NULL)
2039    i->cur_value--;
2040
2041  return ret_val;
2042}
[97]2043
2044
[159]2045/******************************************************************************
2046 *****************************************************************************/
[184]2047const REGFI_CLASSNAME* regfi_iterator_fetch_classname(REGFI_ITERATOR* i,
2048                                                      const REGFI_NK_REC* key)
[160]2049{
2050  REGFI_CLASSNAME* ret_val;
[168]2051  uint8_t* raw;
[160]2052  char* interpreted;
[168]2053  uint32_t offset;
2054  int32_t conv_size, max_size;
2055  uint16_t parse_length;
[160]2056
2057  if(key->classname_off == REGFI_OFFSET_NONE || key->classname_length == 0)
2058    return NULL;
2059
2060  offset = key->classname_off + REGFI_REGF_SIZE;
2061  max_size = regfi_calc_maxsize(i->f, offset);
2062  if(max_size <= 0)
2063    return NULL;
2064
2065  parse_length = key->classname_length;
2066  raw = regfi_parse_classname(i->f, offset, &parse_length, max_size, true);
2067 
2068  if(raw == NULL)
2069  {
[182]2070    regfi_log_add(REGFI_LOG_WARN, "Could not parse class"
2071                  " name at offset 0x%.8X for key record at offset 0x%.8X.",
2072                  offset, key->offset);
[160]2073    return NULL;
2074  }
2075
2076  ret_val = talloc(NULL, REGFI_CLASSNAME);
2077  if(ret_val == NULL)
2078    return NULL;
2079
2080  ret_val->raw = raw;
2081  ret_val->size = parse_length;
[181]2082  talloc_steal(ret_val, raw);
[160]2083
2084  interpreted = talloc_array(NULL, char, parse_length);
2085
[161]2086  conv_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
2087                                 regfi_encoding_int2str(i->string_encoding),
[160]2088                                 raw, interpreted,
2089                                 parse_length, parse_length);
2090  if(conv_size < 0)
2091  {
[182]2092    regfi_log_add(REGFI_LOG_WARN, "Error occurred while"
2093                  " converting classname to charset %s.  Error message: %s",
2094                  i->string_encoding, strerror(-conv_size));
[160]2095    talloc_free(interpreted);
2096    ret_val->interpreted = NULL;
2097  }
2098  else
2099  {
2100    interpreted = talloc_realloc(NULL, interpreted, char, conv_size);
2101    ret_val->interpreted = interpreted;
[181]2102    talloc_steal(ret_val, interpreted);
[160]2103  }
2104
2105  return ret_val;
2106}
2107
2108
2109/******************************************************************************
2110 *****************************************************************************/
[184]2111const REGFI_DATA* regfi_iterator_fetch_data(REGFI_ITERATOR* i, 
2112                                            const REGFI_VK_REC* value)
[159]2113{
2114  REGFI_DATA* ret_val = NULL;
2115  REGFI_BUFFER raw_data;
2116
2117  if(value->data_size != 0)
2118  {
2119    raw_data = regfi_load_data(i->f, value->data_off, value->data_size,
2120                              value->data_in_offset, true);
2121    if(raw_data.buf == NULL)
2122    {
[182]2123      regfi_log_add(REGFI_LOG_WARN, "Could not parse data record"
2124                    " while parsing VK record at offset 0x%.8X.",
2125                    value->offset);
[159]2126    }
2127    else
2128    {
2129      ret_val = regfi_buffer_to_data(raw_data);
2130
2131      if(ret_val == NULL)
2132      {
[182]2133        regfi_log_add(REGFI_LOG_WARN, "Error occurred in converting"
2134                      " data buffer to data structure while interpreting "
2135                      "data for VK record at offset 0x%.8X.",
2136                      value->offset);
[159]2137        talloc_free(raw_data.buf);
2138        return NULL;
2139      }
2140
2141      if(!regfi_interpret_data(i->f, i->string_encoding, value->type, ret_val))
2142      {
[182]2143        regfi_log_add(REGFI_LOG_INFO, "Error occurred while"
2144                      " interpreting data for VK record at offset 0x%.8X.",
2145                      value->offset);
[159]2146      }
2147    }
2148  }
2149 
2150  return ret_val;
2151}
2152
2153
2154/******************************************************************************
2155 *****************************************************************************/
2156REGFI_DATA* regfi_buffer_to_data(REGFI_BUFFER raw_data)
2157{
2158  REGFI_DATA* ret_val;
2159
2160  if(raw_data.buf == NULL)
2161    return NULL;
2162
2163  ret_val = talloc(NULL, REGFI_DATA);
2164  if(ret_val == NULL)
2165    return NULL;
2166 
[181]2167  talloc_steal(ret_val, raw_data.buf);
[159]2168  ret_val->raw = raw_data.buf;
2169  ret_val->size = raw_data.len;
2170  ret_val->interpreted_size = 0;
2171  ret_val->interpreted.qword = 0;
2172
2173  return ret_val;
2174}
2175
2176
2177/******************************************************************************
2178 *****************************************************************************/
[161]2179bool regfi_interpret_data(REGFI_FILE* file, REGFI_ENCODING string_encoding,
[168]2180                          uint32_t type, REGFI_DATA* data)
[159]2181{
[168]2182  uint8_t** tmp_array;
2183  uint8_t* tmp_str;
2184  int32_t tmp_size;
2185  uint32_t i, j, array_size;
[159]2186
2187  if(data == NULL)
2188    return false;
2189
2190  switch (type)
2191  {
2192  case REG_SZ:
2193  case REG_EXPAND_SZ:
2194  /* REG_LINK is a symbolic link, stored as a unicode string. */
2195  case REG_LINK:
[168]2196    tmp_str = talloc_array(NULL, uint8_t, data->size);
[159]2197    if(tmp_str == NULL)
2198    {
2199      data->interpreted.string = NULL;
2200      data->interpreted_size = 0;
2201      return false;
2202    }
2203     
[161]2204    tmp_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
2205                                  regfi_encoding_int2str(string_encoding),
[159]2206                                  data->raw, (char*)tmp_str, 
2207                                  data->size, data->size);
2208    if(tmp_size < 0)
2209    {
[182]2210      regfi_log_add(REGFI_LOG_INFO, "Error occurred while"
2211                    " converting data of type %d to %s.  Error message: %s",
2212                    type, string_encoding, strerror(-tmp_size));
[159]2213      talloc_free(tmp_str);
2214      data->interpreted.string = NULL;
2215      data->interpreted_size = 0;
2216      return false;
2217    }
2218
[168]2219    tmp_str = talloc_realloc(NULL, tmp_str, uint8_t, tmp_size);
[159]2220    data->interpreted.string = tmp_str;
2221    data->interpreted_size = tmp_size;
[181]2222    talloc_steal(data, tmp_str);
[159]2223    break;
2224
2225  case REG_DWORD:
2226    if(data->size < 4)
2227    {
2228      data->interpreted.dword = 0;
2229      data->interpreted_size = 0;
2230      return false;
2231    }
2232    data->interpreted.dword = IVAL(data->raw, 0);
2233    data->interpreted_size = 4;
2234    break;
2235
2236  case REG_DWORD_BE:
2237    if(data->size < 4)
2238    {
2239      data->interpreted.dword_be = 0;
2240      data->interpreted_size = 0;
2241      return false;
2242    }
2243    data->interpreted.dword_be = RIVAL(data->raw, 0);
2244    data->interpreted_size = 4;
2245    break;
2246
2247  case REG_QWORD:
2248    if(data->size < 8)
2249    {
2250      data->interpreted.qword = 0;
2251      data->interpreted_size = 0;
2252      return false;
2253    }
2254    data->interpreted.qword = 
[168]2255      (uint64_t)IVAL(data->raw, 0) + (((uint64_t)IVAL(data->raw, 4))<<32);
[159]2256    data->interpreted_size = 8;
2257    break;
2258   
2259  case REG_MULTI_SZ:
[168]2260    tmp_str = talloc_array(NULL, uint8_t, data->size);
[159]2261    if(tmp_str == NULL)
2262    {
2263      data->interpreted.multiple_string = NULL;
2264      data->interpreted_size = 0;
2265      return false;
2266    }
2267
2268    /* Attempt to convert entire string from UTF-16LE to output encoding,
2269     * then parse and quote fields individually.
2270     */
[161]2271    tmp_size = regfi_conv_charset(regfi_encoding_int2str(REGFI_ENCODING_UTF16LE),
2272                                  regfi_encoding_int2str(string_encoding),
[159]2273                                  data->raw, (char*)tmp_str,
2274                                  data->size, data->size);
2275    if(tmp_size < 0)
2276    {
[182]2277      regfi_log_add(REGFI_LOG_INFO, "Error occurred while"
2278                    " converting data of type %d to %s.  Error message: %s",
2279                    type, string_encoding, strerror(-tmp_size));
[159]2280      talloc_free(tmp_str);
2281      data->interpreted.multiple_string = NULL;
2282      data->interpreted_size = 0;
2283      return false;
2284    }
2285
2286    array_size = tmp_size+1;
[168]2287    tmp_array = talloc_array(NULL, uint8_t*, array_size);
[159]2288    if(tmp_array == NULL)
2289    {
2290      talloc_free(tmp_str);
2291      data->interpreted.string = NULL;
2292      data->interpreted_size = 0;
2293      return false;
2294    }
2295   
2296    tmp_array[0] = tmp_str;
2297    for(i=0,j=1; i < tmp_size && j < array_size-1; i++)
2298    {
2299      if(tmp_str[i] == '\0' && (i+1 < tmp_size))
2300        tmp_array[j++] = tmp_str+i+1;
2301    }
2302    tmp_array[j] = NULL;
[168]2303    tmp_array = talloc_realloc(NULL, tmp_array, uint8_t*, j+1);
[159]2304    data->interpreted.multiple_string = tmp_array;
2305    /* XXX: how meaningful is this?  should we store number of strings instead? */
2306    data->interpreted_size = tmp_size;
[181]2307    talloc_steal(tmp_array, tmp_str);
2308    talloc_steal(data, tmp_array);
[159]2309    break;
2310
2311  /* XXX: Dont know how to interpret these yet, just treat as binary */
2312  case REG_NONE:
2313    data->interpreted.none = data->raw;
2314    data->interpreted_size = data->size;
2315    break;
2316
2317  case REG_RESOURCE_LIST:
2318    data->interpreted.resource_list = data->raw;
2319    data->interpreted_size = data->size;
2320    break;
2321
2322  case REG_FULL_RESOURCE_DESCRIPTOR:
2323    data->interpreted.full_resource_descriptor = data->raw;
2324    data->interpreted_size = data->size;
2325    break;
2326
2327  case REG_RESOURCE_REQUIREMENTS_LIST:
2328    data->interpreted.resource_requirements_list = data->raw;
2329    data->interpreted_size = data->size;
2330    break;
2331
2332  case REG_BINARY:
2333    data->interpreted.binary = data->raw;
2334    data->interpreted_size = data->size;
2335    break;
2336
2337  default:
2338    data->interpreted.qword = 0;
2339    data->interpreted_size = 0;
2340    return false;
2341  }
2342
2343  data->type = type;
2344  return true;
2345}
2346
2347
[166]2348/******************************************************************************
[159]2349 * Convert from UTF-16LE to specified character set.
2350 * On error, returns a negative errno code.
[166]2351 *****************************************************************************/
[168]2352int32_t regfi_conv_charset(const char* input_charset, const char* output_charset,
2353                         uint8_t* input, char* output, 
2354                         uint32_t input_len, uint32_t output_max)
[159]2355{
2356  iconv_t conv_desc;
2357  char* inbuf = (char*)input;
2358  char* outbuf = output;
2359  size_t in_len = (size_t)input_len;
2360  size_t out_len = (size_t)(output_max-1);
2361  int ret;
2362
[161]2363  /* XXX: Consider creating a couple of conversion descriptors earlier,
2364   *      storing them on an iterator so they don't have to be recreated
2365   *      each time.
2366   */
2367
[159]2368  /* Set up conversion descriptor. */
[161]2369  conv_desc = iconv_open(output_charset, input_charset);
[159]2370
2371  ret = iconv(conv_desc, &inbuf, &in_len, &outbuf, &out_len);
2372  if(ret == -1)
2373  {
2374    iconv_close(conv_desc);
2375    return -errno;
2376  }
2377  *outbuf = '\0';
2378
2379  iconv_close(conv_desc); 
2380  return output_max-out_len-1;
2381}
2382
2383
2384
2385/*******************************************************************
[97]2386 * Computes the checksum of the registry file header.
[159]2387 * buffer must be at least the size of a regf header (4096 bytes).
[97]2388 *******************************************************************/
[168]2389static uint32_t regfi_compute_header_checksum(uint8_t* buffer)
[97]2390{
[168]2391  uint32_t checksum, x;
[97]2392  int i;
2393
2394  /* XOR of all bytes 0x0000 - 0x01FB */
2395
2396  checksum = x = 0;
2397 
2398  for ( i=0; i<0x01FB; i+=4 ) {
2399    x = IVAL(buffer, i );
2400    checksum ^= x;
2401  }
2402 
2403  return checksum;
2404}
2405
2406
2407/*******************************************************************
2408 *******************************************************************/
[178]2409REGFI_FILE* regfi_parse_regf(REGFI_RAW_FILE* file_cb, bool strict)
[97]2410{
[168]2411  uint8_t file_header[REGFI_REGF_SIZE];
2412  uint32_t length;
[135]2413  REGFI_FILE* ret_val;
[97]2414
[150]2415  ret_val = talloc(NULL, REGFI_FILE);
[97]2416  if(ret_val == NULL)
2417    return NULL;
2418
[150]2419  ret_val->sk_cache = NULL;
2420  ret_val->hbins = NULL;
[178]2421
[135]2422  length = REGFI_REGF_SIZE;
[178]2423  if((regfi_read(file_cb, file_header, &length)) != 0 
2424     || length != REGFI_REGF_SIZE)
[182]2425  {
2426    regfi_log_add(REGFI_LOG_WARN, "Read failed while parsing REGF structure.");
[150]2427    goto fail;
[182]2428  }
2429
[97]2430  ret_val->checksum = IVAL(file_header, 0x1FC);
2431  ret_val->computed_checksum = regfi_compute_header_checksum(file_header);
2432  if (strict && (ret_val->checksum != ret_val->computed_checksum))
[182]2433  {
2434    regfi_log_add(REGFI_LOG_WARN, "Stored header checksum (%.8X) did not equal"
2435                  " computed checksum (%.8X).",
2436                  ret_val->checksum, ret_val->computed_checksum);
2437    if(strict)
2438      goto fail;
2439  }
[97]2440
[135]2441  memcpy(ret_val->magic, file_header, REGFI_REGF_MAGIC_SIZE);
[150]2442  if(memcmp(ret_val->magic, "regf", REGFI_REGF_MAGIC_SIZE) != 0)
[97]2443  {
[182]2444    regfi_log_add(REGFI_LOG_ERROR, "Magic number mismatch "
2445                  "(%.2X %.2X %.2X %.2X) while parsing hive header",
2446                  ret_val->magic[0], ret_val->magic[1], 
2447                  ret_val->magic[2], ret_val->magic[3]);
2448    goto fail;
[97]2449  }
[178]2450
[151]2451  ret_val->sequence1 = IVAL(file_header, 0x4);
2452  ret_val->sequence2 = IVAL(file_header, 0x8);
[97]2453  ret_val->mtime.low = IVAL(file_header, 0xC);
2454  ret_val->mtime.high = IVAL(file_header, 0x10);
[151]2455  ret_val->major_version = IVAL(file_header, 0x14);
2456  ret_val->minor_version = IVAL(file_header, 0x18);
2457  ret_val->type = IVAL(file_header, 0x1C);
2458  ret_val->format = IVAL(file_header, 0x20);
2459  ret_val->root_cell = IVAL(file_header, 0x24);
[97]2460  ret_val->last_block = IVAL(file_header, 0x28);
[151]2461  ret_val->cluster = IVAL(file_header, 0x2C);
[97]2462
[151]2463  memcpy(ret_val->file_name, file_header+0x30,  REGFI_REGF_NAME_SIZE);
2464
2465  /* XXX: Should we add a warning if these uuid parsers fail?  Can they? */
2466  ret_val->rm_id = winsec_parse_uuid(ret_val, file_header+0x70, 16);
2467  ret_val->log_id = winsec_parse_uuid(ret_val, file_header+0x80, 16);
2468  ret_val->flags = IVAL(file_header, 0x90);
2469  ret_val->tm_id = winsec_parse_uuid(ret_val, file_header+0x94, 16);
2470  ret_val->guid_signature = IVAL(file_header, 0xa4);
2471
2472  memcpy(ret_val->reserved1, file_header+0xa8, REGFI_REGF_RESERVED1_SIZE);
2473  memcpy(ret_val->reserved2, file_header+0x200, REGFI_REGF_RESERVED2_SIZE);
2474
2475  ret_val->thaw_tm_id = winsec_parse_uuid(ret_val, file_header+0xFC8, 16);
2476  ret_val->thaw_rm_id = winsec_parse_uuid(ret_val, file_header+0xFD8, 16);
2477  ret_val->thaw_log_id = winsec_parse_uuid(ret_val, file_header+0xFE8, 16);
[152]2478  ret_val->boot_type = IVAL(file_header, 0xFF8);
2479  ret_val->boot_recover = IVAL(file_header, 0xFFC);
[151]2480
[97]2481  return ret_val;
[150]2482
2483 fail:
2484  talloc_free(ret_val);
2485  return NULL;
[97]2486}
2487
2488
2489
[148]2490/******************************************************************************
[97]2491 * Given real file offset, read and parse the hbin at that location
[110]2492 * along with it's associated cells.
[148]2493 ******************************************************************************/
[168]2494REGFI_HBIN* regfi_parse_hbin(REGFI_FILE* file, uint32_t offset, bool strict)
[97]2495{
[181]2496  REGFI_HBIN* hbin = NULL;
[168]2497  uint8_t hbin_header[REGFI_HBIN_HEADER_SIZE];
2498  uint32_t length;
[99]2499 
2500  if(offset >= file->file_length)
[180]2501    goto fail;
2502 
[186]2503  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_hbin"))
[180]2504    goto fail;
[97]2505
[178]2506  if(regfi_seek(file->cb, offset, SEEK_SET) == -1)
[137]2507  {
[182]2508    regfi_log_add(REGFI_LOG_ERROR, "Seek failed"
2509                  " while parsing hbin at offset 0x%.8X.", offset);
[180]2510    goto fail_locked;
[137]2511  }
[97]2512
[135]2513  length = REGFI_HBIN_HEADER_SIZE;
[178]2514  if((regfi_read(file->cb, hbin_header, &length) != 0) 
[135]2515     || length != REGFI_HBIN_HEADER_SIZE)
[182]2516  {
2517    regfi_log_add(REGFI_LOG_ERROR, "Read failed"
2518                  " while parsing hbin at offset 0x%.8X.", offset);
[180]2519    goto fail_locked;
[182]2520  }
[97]2521
[186]2522  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_hbin"))
[180]2523    goto fail;
[97]2524
[148]2525  hbin = talloc(NULL, REGFI_HBIN);
2526  if(hbin == NULL)
[180]2527    goto fail;
[99]2528  hbin->file_off = offset;
2529
[97]2530  memcpy(hbin->magic, hbin_header, 4);
2531  if(strict && (memcmp(hbin->magic, "hbin", 4) != 0))
[99]2532  {
[182]2533    /* This always seems to happen at the end of a file, so we make it an INFO
2534     * message, rather than something more serious.
2535     */
2536    regfi_log_add(REGFI_LOG_INFO, "Magic number mismatch "
2537                  "(%.2X %.2X %.2X %.2X) while parsing hbin at offset"
2538                  " 0x%.8X.", hbin->magic[0], hbin->magic[1], 
2539                  hbin->magic[2], hbin->magic[3], offset);
[180]2540    goto fail;
[99]2541  }
[97]2542
2543  hbin->first_hbin_off = IVAL(hbin_header, 0x4);
2544  hbin->block_size = IVAL(hbin_header, 0x8);
[182]2545  /* this should be the same thing as hbin->block_size, but just in case */
[97]2546  hbin->next_block = IVAL(hbin_header, 0x1C);
2547
2548
2549  /* Ensure the block size is a multiple of 0x1000 and doesn't run off
2550   * the end of the file.
2551   */
[116]2552  /* XXX: This may need to be relaxed for dealing with
2553   *      partial or corrupt files.
2554   */
[97]2555  if((offset + hbin->block_size > file->file_length)
2556     || (hbin->block_size & 0xFFFFF000) != hbin->block_size)
[99]2557  {
[182]2558    regfi_log_add(REGFI_LOG_ERROR, "The hbin offset is not aligned"
2559                  " or runs off the end of the file"
2560                  " while parsing hbin at offset 0x%.8X.", offset);
[180]2561    goto fail;
[99]2562  }
[97]2563
2564  return hbin;
[180]2565
2566 fail_locked:
[186]2567  regfi_unlock(file, &file->cb_lock, "regfi_parse_hbin");
[180]2568 fail:
2569  talloc_free(hbin);
2570  return NULL;
[97]2571}
2572
2573
[126]2574/*******************************************************************
2575 *******************************************************************/
[168]2576REGFI_NK_REC* regfi_parse_nk(REGFI_FILE* file, uint32_t offset, 
2577                             uint32_t max_size, bool strict)
[99]2578{
[168]2579  uint8_t nk_header[REGFI_NK_MIN_LENGTH];
[135]2580  REGFI_NK_REC* ret_val;
[168]2581  uint32_t length,cell_length;
[101]2582  bool unalloc = false;
[99]2583
[180]2584  ret_val = talloc(NULL, REGFI_NK_REC);
2585  if(ret_val == NULL)
2586  {
[182]2587    regfi_log_add(REGFI_LOG_ERROR, "Failed to allocate memory while"
2588                  " parsing NK record at offset 0x%.8X.", offset);
[180]2589    goto fail;
2590  }
2591
[186]2592  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_nk"))
[180]2593    goto fail;
2594
[178]2595  if(!regfi_parse_cell(file->cb, offset, nk_header, REGFI_NK_MIN_LENGTH,
[101]2596                       &cell_length, &unalloc))
[137]2597  {
[182]2598    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell header"
2599                  " while parsing NK record at offset 0x%.8X.", offset);
[180]2600    goto fail_locked;
[137]2601  }
2602
[101]2603  if((nk_header[0x0] != 'n') || (nk_header[0x1] != 'k'))
[135]2604  {
[182]2605    regfi_log_add(REGFI_LOG_WARN, "Magic number mismatch in parsing"
2606                  " NK record at offset 0x%.8X.", offset);
[180]2607    goto fail_locked;
[135]2608  }
[99]2609
[150]2610  ret_val->values = NULL;
2611  ret_val->subkeys = NULL;
[99]2612  ret_val->offset = offset;
[101]2613  ret_val->cell_size = cell_length;
2614
[99]2615  if(ret_val->cell_size > max_size)
2616    ret_val->cell_size = max_size & 0xFFFFFFF8;
2617  if((ret_val->cell_size < REGFI_NK_MIN_LENGTH) 
[157]2618     || (strict && (ret_val->cell_size & 0x00000007) != 0))
[99]2619  {
[182]2620    regfi_log_add(REGFI_LOG_WARN, "A length check failed while"
2621                  " parsing NK record at offset 0x%.8X.", offset);
[180]2622    goto fail_locked;
[99]2623  }
2624
[101]2625  ret_val->magic[0] = nk_header[0x0];
2626  ret_val->magic[1] = nk_header[0x1];
[161]2627  ret_val->flags = SVAL(nk_header, 0x2);
[152]2628 
[161]2629  if((ret_val->flags & ~REGFI_NK_KNOWN_FLAGS) != 0)
[99]2630  {
[182]2631    regfi_log_add(REGFI_LOG_WARN, "Unknown key flags (0x%.4X) while"
2632                  " parsing NK record at offset 0x%.8X.", 
2633                  (ret_val->flags & ~REGFI_NK_KNOWN_FLAGS), offset);
[99]2634  }
[101]2635
2636  ret_val->mtime.low = IVAL(nk_header, 0x4);
2637  ret_val->mtime.high = IVAL(nk_header, 0x8);
[116]2638  /* If the key is unallocated and the MTIME is earlier than Jan 1, 1990
2639   * or later than Jan 1, 2290, we consider this a bad key.  This helps
2640   * weed out some false positives during deleted data recovery.
2641   */
2642  if(unalloc
[178]2643     && (ret_val->mtime.high < REGFI_MTIME_MIN_HIGH
2644         || ret_val->mtime.high > REGFI_MTIME_MAX_HIGH))
[180]2645  { goto fail_locked; }
[116]2646
[101]2647  ret_val->unknown1 = IVAL(nk_header, 0xC);
2648  ret_val->parent_off = IVAL(nk_header, 0x10);
2649  ret_val->num_subkeys = IVAL(nk_header, 0x14);
2650  ret_val->unknown2 = IVAL(nk_header, 0x18);
2651  ret_val->subkeys_off = IVAL(nk_header, 0x1C);
2652  ret_val->unknown3 = IVAL(nk_header, 0x20);
2653  ret_val->num_values = IVAL(nk_header, 0x24);
2654  ret_val->values_off = IVAL(nk_header, 0x28);
2655  ret_val->sk_off = IVAL(nk_header, 0x2C);
2656  ret_val->classname_off = IVAL(nk_header, 0x30);
[99]2657
[101]2658  ret_val->max_bytes_subkeyname = IVAL(nk_header, 0x34);
2659  ret_val->max_bytes_subkeyclassname = IVAL(nk_header, 0x38);
2660  ret_val->max_bytes_valuename = IVAL(nk_header, 0x3C);
2661  ret_val->max_bytes_value = IVAL(nk_header, 0x40);
2662  ret_val->unk_index = IVAL(nk_header, 0x44);
[99]2663
[101]2664  ret_val->name_length = SVAL(nk_header, 0x48);
2665  ret_val->classname_length = SVAL(nk_header, 0x4A);
[161]2666  ret_val->keyname = NULL;
[99]2667
2668  if(ret_val->name_length + REGFI_NK_MIN_LENGTH > ret_val->cell_size)
[101]2669  {
2670    if(strict)
2671    {
[182]2672      regfi_log_add(REGFI_LOG_ERROR, "Contents too large for cell"
2673                    " while parsing NK record at offset 0x%.8X.", offset);
[180]2674      goto fail_locked;
[101]2675    }
2676    else
2677      ret_val->name_length = ret_val->cell_size - REGFI_NK_MIN_LENGTH;
2678  }
2679  else if (unalloc)
2680  { /* Truncate cell_size if it's much larger than the apparent total record length. */
2681    /* Round up to the next multiple of 8 */
2682    length = (ret_val->name_length + REGFI_NK_MIN_LENGTH) & 0xFFFFFFF8;
2683    if(length < ret_val->name_length + REGFI_NK_MIN_LENGTH)
2684      length+=8;
[99]2685
[101]2686    /* If cell_size is still greater, truncate. */
2687    if(length < ret_val->cell_size)
2688      ret_val->cell_size = length;
2689  }
2690
[168]2691  ret_val->keyname_raw = talloc_array(ret_val, uint8_t, ret_val->name_length);
[161]2692  if(ret_val->keyname_raw == NULL)
[180]2693    goto fail_locked;
[99]2694
2695  /* Don't need to seek, should be at the right offset */
2696  length = ret_val->name_length;
[178]2697  if((regfi_read(file->cb, (uint8_t*)ret_val->keyname_raw, &length) != 0)
[99]2698     || length != ret_val->name_length)
2699  {
[182]2700    regfi_log_add(REGFI_LOG_ERROR, "Failed to read key name"
2701                  " while parsing NK record at offset 0x%.8X.", offset);
[180]2702    goto fail_locked;
[99]2703  }
2704
[186]2705  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_nk"))
[180]2706    goto fail;
2707
[126]2708  return ret_val;
[180]2709
2710 fail_locked:
[186]2711  regfi_unlock(file, &file->cb_lock, "regfi_parse_nk");
[180]2712 fail:
2713  talloc_free(ret_val);
2714  return NULL;
[126]2715}
2716
2717
[168]2718uint8_t* regfi_parse_classname(REGFI_FILE* file, uint32_t offset, 
2719                             uint16_t* name_length, uint32_t max_size, bool strict)
[126]2720{
[168]2721  uint8_t* ret_val = NULL;
2722  uint32_t length;
2723  uint32_t cell_length;
[126]2724  bool unalloc = false;
2725
[180]2726  if(*name_length <= 0 || offset == REGFI_OFFSET_NONE 
2727     || (offset & 0x00000007) != 0)
2728  { goto fail; }
2729
[186]2730  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_classname"))
[180]2731    goto fail;
2732
2733  if(!regfi_parse_cell(file->cb, offset, NULL, 0, &cell_length, &unalloc))
[131]2734  {
[182]2735    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell header"
2736                  " while parsing class name at offset 0x%.8X.", offset);
[180]2737    goto fail_locked;
2738  }
2739 
2740  if((cell_length & 0x0000007) != 0)
2741  {
[182]2742    regfi_log_add(REGFI_LOG_ERROR, "Cell length not a multiple of 8"
2743                  " while parsing class name at offset 0x%.8X.", offset);
[180]2744    goto fail_locked;
2745  }
2746 
2747  if(cell_length > max_size)
2748  {
[182]2749    regfi_log_add(REGFI_LOG_WARN, "Cell stretches past hbin "
2750                  "boundary while parsing class name at offset 0x%.8X.",
2751                  offset);
[180]2752    if(strict)
2753      goto fail_locked;
2754    cell_length = max_size;
2755  }
2756 
2757  if((cell_length - 4) < *name_length)
2758  {
[182]2759    regfi_log_add(REGFI_LOG_WARN, "Class name is larger than"
2760                  " cell_length while parsing class name at offset"
2761                  " 0x%.8X.", offset);
[180]2762    if(strict)
2763      goto fail_locked;
2764    *name_length = cell_length - 4;
2765  }
2766 
2767  ret_val = talloc_array(NULL, uint8_t, *name_length);
2768  if(ret_val != NULL)
2769  {
2770    length = *name_length;
2771    if((regfi_read(file->cb, ret_val, &length) != 0)
2772       || length != *name_length)
[137]2773    {
[182]2774      regfi_log_add(REGFI_LOG_ERROR, "Could not read class name"
2775                    " while parsing class name at offset 0x%.8X.", offset);
[180]2776      goto fail_locked;
[137]2777    }
[180]2778  }
[126]2779
[186]2780  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_classname"))
[180]2781    goto fail;
[137]2782
[180]2783  return ret_val;
[131]2784
[180]2785 fail_locked:
[186]2786  regfi_unlock(file, &file->cb_lock, "regfi_parse_classname");
[180]2787 fail:
2788  talloc_free(ret_val);
2789  return NULL;
[99]2790}
2791
2792
[152]2793/******************************************************************************
2794*******************************************************************************/
[168]2795REGFI_VK_REC* regfi_parse_vk(REGFI_FILE* file, uint32_t offset, 
2796                             uint32_t max_size, bool strict)
[97]2797{
[135]2798  REGFI_VK_REC* ret_val;
[168]2799  uint8_t vk_header[REGFI_VK_MIN_LENGTH];
2800  uint32_t raw_data_size, length, cell_length;
[101]2801  bool unalloc = false;
[97]2802
[180]2803  ret_val = talloc(NULL, REGFI_VK_REC);
2804  if(ret_val == NULL)
2805    goto fail;
2806
[186]2807  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_nk"))
[180]2808    goto fail;
2809
[178]2810  if(!regfi_parse_cell(file->cb, offset, vk_header, REGFI_VK_MIN_LENGTH,
[101]2811                       &cell_length, &unalloc))
[137]2812  {
[182]2813    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell header"
2814                  " while parsing VK record at offset 0x%.8X.", offset);
[180]2815    goto fail_locked;
[137]2816  }
[111]2817
[101]2818  ret_val->offset = offset;
2819  ret_val->cell_size = cell_length;
[150]2820  ret_val->valuename = NULL;
[162]2821  ret_val->valuename_raw = NULL;
[150]2822 
[101]2823  if(ret_val->cell_size > max_size)
2824    ret_val->cell_size = max_size & 0xFFFFFFF8;
2825  if((ret_val->cell_size < REGFI_VK_MIN_LENGTH) 
[157]2826     || (ret_val->cell_size & 0x00000007) != 0)
[97]2827  {
[182]2828    regfi_log_add(REGFI_LOG_WARN, "Invalid cell size encountered"
2829                  " while parsing VK record at offset 0x%.8X.", offset);
[180]2830    goto fail_locked;
[101]2831  }
[97]2832
[101]2833  ret_val->magic[0] = vk_header[0x0];
2834  ret_val->magic[1] = vk_header[0x1];
2835  if((ret_val->magic[0] != 'v') || (ret_val->magic[1] != 'k'))
2836  {
[124]2837    /* XXX: This does not account for deleted keys under Win2K which
2838     *      often have this (and the name length) overwritten with
2839     *      0xFFFF.
2840     */
[182]2841    regfi_log_add(REGFI_LOG_WARN, "Magic number mismatch"
2842                  " while parsing VK record at offset 0x%.8X.", offset);
[180]2843    goto fail_locked;
[101]2844  }
2845
2846  ret_val->name_length = SVAL(vk_header, 0x2);
2847  raw_data_size = IVAL(vk_header, 0x4);
[135]2848  ret_val->data_size = raw_data_size & ~REGFI_VK_DATA_IN_OFFSET;
[157]2849  /* The data is typically stored in the offset if the size <= 4,
2850   * in which case this flag is set.
2851   */
[135]2852  ret_val->data_in_offset = (bool)(raw_data_size & REGFI_VK_DATA_IN_OFFSET);
[101]2853  ret_val->data_off = IVAL(vk_header, 0x8);
2854  ret_val->type = IVAL(vk_header, 0xC);
[162]2855  ret_val->flags = SVAL(vk_header, 0x10);
[101]2856  ret_val->unknown1 = SVAL(vk_header, 0x12);
2857
[162]2858  if(ret_val->name_length > 0)
[101]2859  {
[113]2860    if(ret_val->name_length + REGFI_VK_MIN_LENGTH + 4 > ret_val->cell_size)
[101]2861    {
[182]2862      regfi_log_add(REGFI_LOG_WARN, "Name too long for remaining cell"
2863                    " space while parsing VK record at offset 0x%.8X.",
2864                    offset);
[101]2865      if(strict)
[180]2866        goto fail_locked;
[101]2867      else
[113]2868        ret_val->name_length = ret_val->cell_size - REGFI_VK_MIN_LENGTH - 4;
[101]2869    }
2870
2871    /* Round up to the next multiple of 8 */
[113]2872    cell_length = (ret_val->name_length + REGFI_VK_MIN_LENGTH + 4) & 0xFFFFFFF8;
2873    if(cell_length < ret_val->name_length + REGFI_VK_MIN_LENGTH + 4)
2874      cell_length+=8;
[101]2875
[168]2876    ret_val->valuename_raw = talloc_array(ret_val, uint8_t, ret_val->name_length);
[162]2877    if(ret_val->valuename_raw == NULL)
[180]2878      goto fail_locked;
[113]2879
[101]2880    length = ret_val->name_length;
[178]2881    if((regfi_read(file->cb, (uint8_t*)ret_val->valuename_raw, &length) != 0)
[101]2882       || length != ret_val->name_length)
2883    {
[182]2884      regfi_log_add(REGFI_LOG_ERROR, "Could not read value name"
2885                    " while parsing VK record at offset 0x%.8X.", offset);
[180]2886      goto fail_locked;
[101]2887    }
2888  }
2889  else
[113]2890    cell_length = REGFI_VK_MIN_LENGTH + 4;
[101]2891
[186]2892  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_nk"))
[180]2893    goto fail;
2894
[101]2895  if(unalloc)
2896  {
2897    /* If cell_size is still greater, truncate. */
[113]2898    if(cell_length < ret_val->cell_size)
2899      ret_val->cell_size = cell_length;
[101]2900  }
2901
2902  return ret_val;
[180]2903 
2904 fail_locked:
[186]2905  regfi_unlock(file, &file->cb_lock, "regfi_parse_vk");
[180]2906 fail:
2907  talloc_free(ret_val);
2908  return NULL;
[97]2909}
[101]2910
2911
[152]2912/******************************************************************************
[157]2913 *
2914 ******************************************************************************/
[168]2915REGFI_BUFFER regfi_load_data(REGFI_FILE* file, uint32_t voffset,
2916                             uint32_t length, bool data_in_offset,
[157]2917                             bool strict)
[101]2918{
[151]2919  REGFI_BUFFER ret_val;
[168]2920  uint32_t cell_length, offset;
2921  int32_t max_size;
[101]2922  bool unalloc;
[151]2923 
[159]2924  /* Microsoft's documentation indicates that "available memory" is
[165]2925   * the limit on value sizes for the more recent registry format version.
2926   * This is not only annoying, but it's probably also incorrect, since clearly
2927   * value data sizes are limited to 2^31 (high bit used as a flag) and even
2928   * with big data records, the apparent max size is:
2929   *   16344 * 2^16 = 1071104040 (~1GB).
2930   *
2931   * We choose to limit it to 1M which was the limit in older versions and
2932   * should rarely be exceeded unless the file is corrupt or malicious.
2933   * For more info, see:
2934   *   http://msdn.microsoft.com/en-us/library/ms724872%28VS.85%29.aspx
[159]2935   */
[160]2936  /* XXX: add way to skip this check at user discression. */
2937  if(length > REGFI_VK_MAX_DATA_LENGTH)
[159]2938  {
[182]2939    regfi_log_add(REGFI_LOG_WARN, "Value data size %d larger than "
2940                  "%d, truncating...", length, REGFI_VK_MAX_DATA_LENGTH);
[160]2941    length = REGFI_VK_MAX_DATA_LENGTH;
[159]2942  }
2943
[145]2944  if(data_in_offset)
[157]2945    return regfi_parse_little_data(file, voffset, length, strict);
2946  else
[101]2947  {
[157]2948    offset = voffset + REGFI_REGF_SIZE;
2949    max_size = regfi_calc_maxsize(file, offset);
2950    if(max_size < 0)
[137]2951    {
[182]2952      regfi_log_add(REGFI_LOG_WARN, "Could not find HBIN for data"
2953                    " at offset 0x%.8X.", offset);
[151]2954      goto fail;
[137]2955    }
[157]2956   
[186]2957    if(!regfi_lock(file, &file->cb_lock, "regfi_load_data"))
[180]2958      goto fail;
2959
[178]2960    if(!regfi_parse_cell(file->cb, offset, NULL, 0,
[101]2961                         &cell_length, &unalloc))
[137]2962    {
[182]2963      regfi_log_add(REGFI_LOG_WARN, "Could not parse cell while"
2964                    " parsing data record at offset 0x%.8X.", offset);
[180]2965      goto fail_locked;
[137]2966    }
[111]2967
[186]2968    if(!regfi_unlock(file, &file->cb_lock, "regfi_load_data"))
[180]2969      goto fail;
2970
[157]2971    if((cell_length & 0x00000007) != 0)
[137]2972    {
[182]2973      regfi_log_add(REGFI_LOG_WARN, "Cell length not multiple of 8"
2974                    " while parsing data record at offset 0x%.8X.",
2975                    offset);
[151]2976      goto fail;
[137]2977    }
[101]2978
[131]2979    if(cell_length > max_size)
2980    {
[182]2981      regfi_log_add(REGFI_LOG_WARN, "Cell extends past HBIN boundary"
2982                    " while parsing data record at offset 0x%.8X.",
2983                    offset);
[157]2984      goto fail;
[131]2985    }
2986
[101]2987    if(cell_length - 4 < length)
2988    {
[155]2989      /* XXX: All big data records thus far have been 16 bytes long. 
2990       *      Should we check for this precise size instead of just
2991       *      relying upon the above check?
2992       */
[152]2993      if (file->major_version >= 1 && file->minor_version >= 5)
2994      {
2995        /* Attempt to parse a big data record */
[157]2996        return regfi_load_big_data(file, offset, length, cell_length, 
2997                                   NULL, strict);
[152]2998      }
[101]2999      else
[152]3000      {
[182]3001        regfi_log_add(REGFI_LOG_WARN, "Data length (0x%.8X) larger than"
3002                      " remaining cell length (0x%.8X)"
3003                      " while parsing data record at offset 0x%.8X.", 
3004                      length, cell_length - 4, offset);
[152]3005        if(strict)
3006          goto fail;
3007        else
3008          length = cell_length - 4;
3009      }
[101]3010    }
3011
[157]3012    ret_val = regfi_parse_data(file, offset, length, strict);
[101]3013  }
3014
3015  return ret_val;
[151]3016
[180]3017 fail_locked:
[186]3018  regfi_unlock(file, &file->cb_lock, "regfi_load_data");
[151]3019 fail:
3020  ret_val.buf = NULL;
3021  ret_val.len = 0;
3022  return ret_val;
[101]3023}
[110]3024
3025
[152]3026/******************************************************************************
[157]3027 * Parses the common case data records stored in a single cell.
3028 ******************************************************************************/
[168]3029REGFI_BUFFER regfi_parse_data(REGFI_FILE* file, uint32_t offset,
3030                              uint32_t length, bool strict)
[157]3031{
3032  REGFI_BUFFER ret_val;
[168]3033  uint32_t read_length;
[157]3034
3035  ret_val.buf = NULL;
3036  ret_val.len = 0;
3037 
[180]3038  if((ret_val.buf = talloc_array(NULL, uint8_t, length)) == NULL)
3039    goto fail;
3040  ret_val.len = length;
3041
[186]3042  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_data"))
[180]3043    goto fail;
3044
[178]3045  if(regfi_seek(file->cb, offset+4, SEEK_SET) == -1)
[157]3046  {
[182]3047    regfi_log_add(REGFI_LOG_WARN, "Could not seek while "
3048                  "reading data at offset 0x%.8X.", offset);
[180]3049    goto fail_locked;
[157]3050  }
3051 
3052  read_length = length;
[178]3053  if((regfi_read(file->cb, ret_val.buf, &read_length) != 0)
[157]3054     || read_length != length)
3055  {
[182]3056    regfi_log_add(REGFI_LOG_ERROR, "Could not read data block while"
3057                  " parsing data record at offset 0x%.8X.", offset);
[180]3058    goto fail_locked;
[157]3059  }
3060
[186]3061  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_data"))
[180]3062    goto fail;
3063
[157]3064  return ret_val;
[180]3065
3066 fail_locked:
[186]3067  regfi_unlock(file, &file->cb_lock, "regfi_parse_data");
[180]3068 fail:
3069  talloc_free(ret_val.buf);
3070  ret_val.buf = NULL;
3071  ret_val.buf = 0;
3072  return ret_val;
[157]3073}
3074
3075
3076
3077/******************************************************************************
3078 *
3079 ******************************************************************************/
[168]3080REGFI_BUFFER regfi_parse_little_data(REGFI_FILE* file, uint32_t voffset,
3081                                     uint32_t length, bool strict)
[157]3082{
[173]3083  uint8_t i;
[157]3084  REGFI_BUFFER ret_val;
3085
3086  ret_val.buf = NULL;
3087  ret_val.len = 0;
3088
3089  if(length > 4)
3090  {
[182]3091    regfi_log_add(REGFI_LOG_ERROR, "Data in offset but length > 4"
3092                  " while parsing data record. (voffset=0x%.8X, length=%d)",
3093                  voffset, length);
[157]3094    return ret_val;
3095  }
3096
[168]3097  if((ret_val.buf = talloc_array(NULL, uint8_t, length)) == NULL)
[157]3098    return ret_val;
3099  ret_val.len = length;
3100 
3101  for(i = 0; i < length; i++)
[168]3102    ret_val.buf[i] = (uint8_t)((voffset >> i*8) & 0xFF);
[157]3103
3104  return ret_val;
3105}
3106
3107/******************************************************************************
[152]3108*******************************************************************************/
[168]3109REGFI_BUFFER regfi_parse_big_data_header(REGFI_FILE* file, uint32_t offset, 
3110                                         uint32_t max_size, bool strict)
[152]3111{
3112  REGFI_BUFFER ret_val;
[168]3113  uint32_t cell_length;
[152]3114  bool unalloc;
[157]3115
3116  /* XXX: do something with unalloc? */
[168]3117  ret_val.buf = (uint8_t*)talloc_array(NULL, uint8_t, REGFI_BIG_DATA_MIN_LENGTH);
[157]3118  if(ret_val.buf == NULL)
[152]3119    goto fail;
3120
[157]3121  if(REGFI_BIG_DATA_MIN_LENGTH > max_size)
3122  {
[182]3123    regfi_log_add(REGFI_LOG_WARN, "Big data header exceeded max_size "
3124                  "while parsing big data header at offset 0x%.8X.",offset);
[157]3125    goto fail;
3126  }
3127
[186]3128  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_big_data_header"))
[180]3129    goto fail;
3130
3131
[178]3132  if(!regfi_parse_cell(file->cb, offset, ret_val.buf, REGFI_BIG_DATA_MIN_LENGTH,
[152]3133                       &cell_length, &unalloc))
3134  {
[182]3135    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell while"
3136                  " parsing big data header at offset 0x%.8X.", offset);
[180]3137    goto fail_locked;
[152]3138  }
[157]3139
[186]3140  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_big_data_header"))
[180]3141    goto fail;
3142
[157]3143  if((ret_val.buf[0] != 'd') || (ret_val.buf[1] != 'b'))
[152]3144  {
[182]3145    regfi_log_add(REGFI_LOG_WARN, "Unknown magic number"
3146                  " (0x%.2X, 0x%.2X) encountered while parsing"
3147                  " big data header at offset 0x%.8X.", 
3148                  ret_val.buf[0], ret_val.buf[1], offset);
[152]3149    goto fail;
3150  }
3151
[157]3152  ret_val.len = REGFI_BIG_DATA_MIN_LENGTH;
3153  return ret_val;
3154
[180]3155 fail_locked:
[186]3156  regfi_unlock(file, &file->cb_lock, "regfi_parse_big_data_header");
[157]3157 fail:
[180]3158  talloc_free(ret_val.buf);
3159  ret_val.buf = NULL;
[157]3160  ret_val.len = 0;
3161  return ret_val;
3162}
3163
3164
3165
3166/******************************************************************************
3167 *
3168 ******************************************************************************/
[168]3169uint32_t* regfi_parse_big_data_indirect(REGFI_FILE* file, uint32_t offset,
3170                                      uint16_t num_chunks, bool strict)
[157]3171{
[168]3172  uint32_t* ret_val;
3173  uint32_t indirect_length;
3174  int32_t max_size;
3175  uint16_t i;
[157]3176  bool unalloc;
3177
3178  /* XXX: do something with unalloc? */
3179
3180  max_size = regfi_calc_maxsize(file, offset);
[168]3181  if((max_size < 0) || (num_chunks*sizeof(uint32_t) + 4 > max_size))
[157]3182    return NULL;
3183
[168]3184  ret_val = (uint32_t*)talloc_array(NULL, uint32_t, num_chunks);
[157]3185  if(ret_val == NULL)
[152]3186    goto fail;
3187
[186]3188  if(!regfi_lock(file, &file->cb_lock, "regfi_parse_big_data_indirect"))
[180]3189    goto fail;
3190
[178]3191  if(!regfi_parse_cell(file->cb, offset, (uint8_t*)ret_val,
[168]3192                       num_chunks*sizeof(uint32_t),
[152]3193                       &indirect_length, &unalloc))
3194  {
[182]3195    regfi_log_add(REGFI_LOG_WARN, "Could not parse cell while"
3196                  " parsing big data indirect record at offset 0x%.8X.", 
3197                  offset);
[180]3198    goto fail_locked;
[152]3199  }
[157]3200
[186]3201  if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_big_data_indirect"))
[180]3202    goto fail;
3203
[157]3204  /* Convert pointers to proper endianess, verify they are aligned. */
3205  for(i=0; i<num_chunks; i++)
[152]3206  {
[168]3207    ret_val[i] = IVAL(ret_val, i*sizeof(uint32_t));
[157]3208    if((ret_val[i] & 0x00000007) != 0)
3209      goto fail;
[152]3210  }
[157]3211 
3212  return ret_val;
[152]3213
[180]3214 fail_locked:
[186]3215  regfi_unlock(file, &file->cb_lock, "regfi_parse_big_data_indirect");
[157]3216 fail:
[180]3217  talloc_free(ret_val);
[157]3218  return NULL;
3219}
3220
3221
3222/******************************************************************************
3223 * Arguments:
3224 *  file       --
3225 *  offsets    -- list of virtual offsets.
3226 *  num_chunks --
3227 *  strict     --
3228 *
3229 * Returns:
3230 *  A range_list with physical offsets and complete lengths
3231 *  (including cell headers) of associated cells. 
3232 *  No data in range_list elements.
3233 ******************************************************************************/
[168]3234range_list* regfi_parse_big_data_cells(REGFI_FILE* file, uint32_t* offsets,
3235                                       uint16_t num_chunks, bool strict)
[157]3236{
[168]3237  uint32_t cell_length, chunk_offset;
[157]3238  range_list* ret_val;
[168]3239  uint16_t i;
[157]3240  bool unalloc;
3241 
3242  /* XXX: do something with unalloc? */
3243  ret_val = range_list_new();
3244  if(ret_val == NULL)
3245    goto fail;
3246 
[166]3247  for(i=0; i<num_chunks; i++)
[152]3248  {
[186]3249    if(!regfi_lock(file, &file->cb_lock, "regfi_parse_big_data_cells"))
[180]3250      goto fail;
3251
[157]3252    chunk_offset = offsets[i]+REGFI_REGF_SIZE;
[178]3253    if(!regfi_parse_cell(file->cb, chunk_offset, NULL, 0,
[157]3254                         &cell_length, &unalloc))
[152]3255    {
[182]3256      regfi_log_add(REGFI_LOG_WARN, "Could not parse cell while"
3257                    " parsing big data chunk at offset 0x%.8X.", 
3258                    chunk_offset);
[180]3259      goto fail_locked;
[152]3260    }
3261
[186]3262    if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_big_data_cells"))
[180]3263      goto fail;
3264
[157]3265    if(!range_list_add(ret_val, chunk_offset, cell_length, NULL))
3266      goto fail;
3267  }
3268
3269  return ret_val;
3270
[180]3271 fail_locked:
[186]3272  regfi_unlock(file, &file->cb_lock, "regfi_parse_big_data_cells");
[157]3273 fail:
3274  if(ret_val != NULL)
3275    range_list_free(ret_val);
3276  return NULL;
3277}
3278
3279
3280/******************************************************************************
3281*******************************************************************************/
3282REGFI_BUFFER regfi_load_big_data(REGFI_FILE* file, 
[168]3283                                 uint32_t offset, uint32_t data_length, 
3284                                 uint32_t cell_length, range_list* used_ranges,
[157]3285                                 bool strict)
3286{
3287  REGFI_BUFFER ret_val;
[168]3288  uint16_t num_chunks, i;
3289  uint32_t read_length, data_left, tmp_len, indirect_offset;
3290  uint32_t* indirect_ptrs = NULL;
[157]3291  REGFI_BUFFER bd_header;
3292  range_list* bd_cells = NULL;
3293  const range_list_element* cell_info;
3294
3295  ret_val.buf = NULL;
3296
3297  /* XXX: Add better error/warning messages */
3298
3299  bd_header = regfi_parse_big_data_header(file, offset, cell_length, strict);
3300  if(bd_header.buf == NULL)
3301    goto fail;
3302
3303  /* Keep track of used space for use by reglookup-recover */
3304  if(used_ranges != NULL)
3305    if(!range_list_add(used_ranges, offset, cell_length, NULL))
3306      goto fail;
3307
3308  num_chunks = SVAL(bd_header.buf, 0x2);
3309  indirect_offset = IVAL(bd_header.buf, 0x4) + REGFI_REGF_SIZE;
3310  talloc_free(bd_header.buf);
3311
3312  indirect_ptrs = regfi_parse_big_data_indirect(file, indirect_offset,
3313                                                num_chunks, strict);
3314  if(indirect_ptrs == NULL)
3315    goto fail;
3316
3317  if(used_ranges != NULL)
3318    if(!range_list_add(used_ranges, indirect_offset, num_chunks*4+4, NULL))
3319      goto fail;
3320 
3321  if((ret_val.buf = talloc_array(NULL, uint8_t, data_length)) == NULL)
3322    goto fail;
3323  data_left = data_length;
3324
3325  bd_cells = regfi_parse_big_data_cells(file, indirect_ptrs, num_chunks, strict);
3326  if(bd_cells == NULL)
3327    goto fail;
3328
3329  talloc_free(indirect_ptrs);
3330  indirect_ptrs = NULL;
3331 
3332  for(i=0; (i<num_chunks) && (data_left>0); i++)
3333  {
3334    cell_info = range_list_get(bd_cells, i);
3335    if(cell_info == NULL)
3336      goto fail;
3337
3338    /* XXX: This should be "cell_info->length-4" to account for the 4 byte cell
[154]3339     *      length.  However, it has been observed that some (all?) chunks
3340     *      have an additional 4 bytes of 0 at the end of their cells that
3341     *      isn't part of the data, so we're trimming that off too.
[157]3342     *      Perhaps it's just an 8 byte alignment requirement...
[154]3343     */
[157]3344    if(cell_info->length - 8 >= data_left)
3345    {
3346      if(i+1 != num_chunks)
3347      {
[182]3348        regfi_log_add(REGFI_LOG_WARN, "Left over chunks detected "
3349                      "while constructing big data at offset 0x%.8X "
3350                      "(chunk offset 0x%.8X).", offset, cell_info->offset);
[157]3351      }
[152]3352      read_length = data_left;
[157]3353    }
[152]3354    else
[157]3355      read_length = cell_info->length - 8;
[152]3356
[157]3357
3358    if(read_length > regfi_calc_maxsize(file, cell_info->offset))
3359    {
[182]3360      regfi_log_add(REGFI_LOG_WARN, "A chunk exceeded the maxsize "
3361                    "while constructing big data at offset 0x%.8X "
3362                    "(chunk offset 0x%.8X).", offset, cell_info->offset);
[157]3363      goto fail;
3364    }
3365
[186]3366    if(!regfi_lock(file, &file->cb_lock, "regfi_load_big_data"))
[180]3367      goto fail;
3368
[178]3369    if(regfi_seek(file->cb, cell_info->offset+sizeof(uint32_t), SEEK_SET) == -1)
[157]3370    {
[182]3371      regfi_log_add(REGFI_LOG_WARN, "Could not seek to chunk while "
3372                    "constructing big data at offset 0x%.8X "
3373                    "(chunk offset 0x%.8X).", offset, cell_info->offset);
[180]3374      goto fail_locked;
[157]3375    }
3376
3377    tmp_len = read_length;
[178]3378    if(regfi_read(file->cb, ret_val.buf+(data_length-data_left), 
[157]3379                  &read_length) != 0 || (read_length != tmp_len))
[152]3380    {
[182]3381      regfi_log_add(REGFI_LOG_WARN, "Could not read data chunk while"
3382                    " constructing big data at offset 0x%.8X"
3383                    " (chunk offset 0x%.8X).", offset, cell_info->offset);
[180]3384      goto fail_locked;
[152]3385    }
3386
[186]3387    if(!regfi_unlock(file, &file->cb_lock, "regfi_load_big_data"))
[180]3388      goto fail;
3389
[157]3390    if(used_ranges != NULL)
3391      if(!range_list_add(used_ranges, cell_info->offset,cell_info->length,NULL))
3392        goto fail;
3393
[152]3394    data_left -= read_length;
3395  }
[157]3396  range_list_free(bd_cells);
3397
[152]3398  ret_val.len = data_length-data_left;
3399  return ret_val;
3400
[180]3401 fail_locked:
[186]3402  regfi_unlock(file, &file->cb_lock, "regfi_load_big_data");
[152]3403 fail:
[180]3404  talloc_free(ret_val.buf);
3405  talloc_free(indirect_ptrs);
[157]3406  if(bd_cells != NULL)
3407    range_list_free(bd_cells);
[152]3408  ret_val.buf = NULL;
3409  ret_val.len = 0;
3410  return ret_val;
3411}
3412
3413
[135]3414range_list* regfi_parse_unalloc_cells(REGFI_FILE* file)
[110]3415{
3416  range_list* ret_val;
[135]3417  REGFI_HBIN* hbin;
[110]3418  const range_list_element* hbins_elem;
[168]3419  uint32_t i, num_hbins, curr_off, cell_len;
[110]3420  bool is_unalloc;
3421
3422  ret_val = range_list_new();
3423  if(ret_val == NULL)
3424    return NULL;
3425
[186]3426  if(!regfi_read_lock(file, &file->hbins_lock, "regfi_parse_unalloc_cells"))
[180]3427  {
3428    range_list_free(ret_val);
3429    return NULL;
3430  }
3431
[110]3432  num_hbins = range_list_size(file->hbins);
3433  for(i=0; i<num_hbins; i++)
3434  {
3435    hbins_elem = range_list_get(file->hbins, i);
3436    if(hbins_elem == NULL)
3437      break;
[135]3438    hbin = (REGFI_HBIN*)hbins_elem->data;
[110]3439
[135]3440    curr_off = REGFI_HBIN_HEADER_SIZE;
[110]3441    while(curr_off < hbin->block_size)
3442    {
[186]3443      if(!regfi_lock(file, &file->cb_lock, "regfi_parse_unalloc_cells"))
[180]3444        break;
3445
[178]3446      if(!regfi_parse_cell(file->cb, hbin->file_off+curr_off, NULL, 0,
[110]3447                           &cell_len, &is_unalloc))
[180]3448      {
[186]3449        regfi_unlock(file, &file->cb_lock, "regfi_parse_unalloc_cells");
[110]3450        break;
[180]3451      }
3452
[186]3453      if(!regfi_unlock(file, &file->cb_lock, "regfi_parse_unalloc_cells"))
[180]3454        break;
3455
[157]3456      if((cell_len == 0) || ((cell_len & 0x00000007) != 0))
[140]3457      {
[182]3458        regfi_log_add(REGFI_LOG_ERROR, "Bad cell length encountered"
3459                      " while parsing unallocated cells at offset 0x%.8X.",
3460                      hbin->file_off+curr_off);
[110]3461        break;
[140]3462      }
3463
[110]3464      /* for some reason the record_size of the last record in
3465         an hbin block can extend past the end of the block
3466         even though the record fits within the remaining
3467         space....aaarrrgggghhhhhh */ 
3468      if(curr_off + cell_len >= hbin->block_size)
3469        cell_len = hbin->block_size - curr_off;
3470     
3471      if(is_unalloc)
3472        range_list_add(ret_val, hbin->file_off+curr_off, 
3473                       cell_len, NULL);
3474     
3475      curr_off = curr_off+cell_len;
3476    }
3477  }
3478
[186]3479  if(!regfi_rw_unlock(file, &file->hbins_lock, "regfi_parse_unalloc_cells"))
[180]3480  {
3481    range_list_free(ret_val);
3482    return NULL;
3483  }
3484
[110]3485  return ret_val;
3486}
[168]3487
3488
3489/* From lib/time.c */
3490
3491/****************************************************************************
3492 Put a 8 byte filetime from a time_t
3493 This takes real GMT as input and converts to kludge-GMT
3494****************************************************************************/
3495void regfi_unix2nt_time(REGFI_NTTIME *nt, time_t t)
3496{
3497  double d;
3498 
3499  if (t==0) 
3500  {
3501    nt->low = 0;
3502    nt->high = 0;
3503    return;
3504  }
3505 
3506  if (t == TIME_T_MAX) 
3507  {
3508    nt->low = 0xffffffff;
3509    nt->high = 0x7fffffff;
3510    return;
3511  }             
3512 
3513  if (t == -1) 
3514  {
3515    nt->low = 0xffffffff;
3516    nt->high = 0xffffffff;
3517    return;
3518  }             
3519 
3520  /* this converts GMT to kludge-GMT */
3521  /* XXX: This was removed due to difficult dependency requirements. 
3522   *      So far, times appear to be correct without this adjustment, but
3523   *      that may be proven wrong with adequate testing.
3524   */
3525  /* t -= TimeDiff(t) - get_serverzone(); */
3526 
3527  d = (double)(t);
3528  d += TIME_FIXUP_CONSTANT;
3529  d *= 1.0e7;
3530 
3531  nt->high = (uint32_t)(d * (1.0/(4.0*(double)(1<<30))));
3532  nt->low  = (uint32_t)(d - ((double)nt->high)*4.0*(double)(1<<30));
3533}
3534
3535
3536/****************************************************************************
3537 Interpret an 8 byte "filetime" structure to a time_t
3538 It's originally in "100ns units since jan 1st 1601"
3539
3540 An 8 byte value of 0xffffffffffffffff will be returned as (time_t)0.
3541
3542 It appears to be kludge-GMT (at least for file listings). This means
3543 its the GMT you get by taking a localtime and adding the
3544 serverzone. This is NOT the same as GMT in some cases. This routine
3545 converts this to real GMT.
3546****************************************************************************/
3547time_t regfi_nt2unix_time(const REGFI_NTTIME* nt)
3548{
3549  double d;
3550  time_t ret;
3551  /* The next two lines are a fix needed for the
3552     broken SCO compiler. JRA. */
3553  time_t l_time_min = TIME_T_MIN;
3554  time_t l_time_max = TIME_T_MAX;
3555 
3556  if (nt->high == 0 || (nt->high == 0xffffffff && nt->low == 0xffffffff))
3557    return(0);
3558 
3559  d = ((double)nt->high)*4.0*(double)(1<<30);
3560  d += (nt->low&0xFFF00000);
3561  d *= 1.0e-7;
3562 
3563  /* now adjust by 369 years to make the secs since 1970 */
3564  d -= TIME_FIXUP_CONSTANT;
3565 
3566  if (d <= l_time_min)
3567    return (l_time_min);
3568 
3569  if (d >= l_time_max)
3570    return (l_time_max);
3571 
3572  ret = (time_t)(d+0.5);
3573 
3574  /* this takes us from kludge-GMT to real GMT */
3575  /* XXX: This was removed due to difficult dependency requirements. 
3576   *      So far, times appear to be correct without this adjustment, but
3577   *      that may be proven wrong with adequate testing.
3578   */
3579  /*
3580    ret -= get_serverzone();
3581    ret += LocTimeDiff(ret);
3582  */
3583
3584  return(ret);
3585}
3586
3587/* End of stuff from lib/time.c */
Note: See TracBrowser for help on using the repository browser.