source: trunk/lib/regfi.c @ 200

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

redesigned python key iterator and test script
updated documentation

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