source: trunk/lib/regfi.c @ 249

Last change on this file since 249 was 249, checked in by tim, 13 years ago

reorganized iterator code for simpler locking and easier future key caching

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