source: trunk/lib/regfi.c @ 182

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

redesigned regfi logging API to utilize thread-local storage

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