1 /* hivex - Windows Registry "hive" extraction library.
2 * Copyright (C) 2009-2011 Red Hat Inc.
3 * Derived from code by Petter Nordahl-Hagen under a compatible license:
4 * Copyright (c) 1997-2007 Petter Nordahl-Hagen.
5 * Derived from code by Markus Stephany under a compatible license:
6 * Copyright (c) 2000-2004, Markus Stephany.
8 * This library is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU Lesser General Public
10 * License as published by the Free Software Foundation;
11 * version 2.1 of the License.
13 * This library is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * Lesser General Public License for more details.
18 * See file LICENSE for the full license.
38 #include "full-read.h"
39 #include "full-write.h"
42 #include "hivex-internal.h"
43 #include "byte_conversions.h"
45 /* These limits are in place to stop really stupid stuff and/or exploits. */
46 #define HIVEX_MAX_SUBKEYS 15000
47 #define HIVEX_MAX_VALUES 10000
48 #define HIVEX_MAX_VALUE_LEN 1000000
49 #define HIVEX_MAX_ALLOCATION 1000000
51 static char *windows_utf16_to_utf8 (/* const */ char *input, size_t len);
52 static size_t utf16_string_len_in_bytes_max (const char *str, size_t len);
54 /* NB. All fields are little endian. */
56 char magic[4]; /* "regf" */
59 int64_t last_modified;
60 uint32_t major_ver; /* 1 */
61 uint32_t minor_ver; /* 3 */
62 uint32_t unknown5; /* 0 */
63 uint32_t unknown6; /* 1 */
64 uint32_t offset; /* offset of root key record - 4KB */
65 uint32_t blocks; /* pointer AFTER last hbin in file - 4KB */
66 uint32_t unknown7; /* 1 */
68 char name[64]; /* original file name of hive */
69 char unknown_guid1[16];
70 char unknown_guid2[16];
73 char unknown_guid3[16];
78 uint32_t csum; /* checksum: xor of dwords 0-0x1fb. */
82 char unknown_guid4[16];
83 char unknown_guid5[16];
84 char unknown_guid6[16];
88 } __attribute__((__packed__));
90 struct ntreg_hbin_page {
91 char magic[4]; /* "hbin" */
92 uint32_t offset_first; /* offset from 1st block */
93 uint32_t page_size; /* size of this page (multiple of 4KB) */
95 /* Linked list of blocks follows here. */
96 } __attribute__((__packed__));
98 struct ntreg_hbin_block {
99 int32_t seg_len; /* length of this block (-ve for used block) */
100 char id[2]; /* the block type (eg. "nk" for nk record) */
101 /* Block data follows here. */
102 } __attribute__((__packed__));
104 #define BLOCK_ID_EQ(h,offs,eqid) \
105 (STREQLEN (((struct ntreg_hbin_block *)((h)->addr + (offs)))->id, (eqid), 2))
108 block_len (hive_h *h, size_t blkoff, int *used)
110 struct ntreg_hbin_block *block;
111 block = (struct ntreg_hbin_block *) (h->addr + blkoff);
113 int32_t len = le32toh (block->seg_len);
124 struct ntreg_nk_record {
125 int32_t seg_len; /* length (always -ve because used) */
126 char id[2]; /* "nk" */
130 uint32_t parent; /* offset of owner/parent */
131 uint32_t nr_subkeys; /* number of subkeys */
132 uint32_t nr_subkeys_volatile;
133 uint32_t subkey_lf; /* lf record containing list of subkeys */
134 uint32_t subkey_lf_volatile;
135 uint32_t nr_values; /* number of values */
136 uint32_t vallist; /* value-list record */
137 uint32_t sk; /* offset of sk-record */
138 uint32_t classname; /* offset of classname record */
139 uint16_t max_subkey_name_len; /* maximum length of a subkey name in bytes
140 if the subkey was reencoded as UTF-16LE */
143 uint32_t max_vk_name_len; /* maximum length of any vk name in bytes
144 if the name was reencoded as UTF-16LE */
145 uint32_t max_vk_data_len; /* maximum length of any vk data in bytes */
147 uint16_t name_len; /* length of name */
148 uint16_t classname_len; /* length of classname */
149 char name[1]; /* name follows here */
150 } __attribute__((__packed__));
152 struct ntreg_lf_record {
154 char id[2]; /* "lf"|"lh" */
155 uint16_t nr_keys; /* number of keys in this record */
157 uint32_t offset; /* offset of nk-record for this subkey */
158 char hash[4]; /* hash of subkey name */
160 } __attribute__((__packed__));
162 struct ntreg_ri_record {
164 char id[2]; /* "ri" */
165 uint16_t nr_offsets; /* number of pointers to lh records */
166 uint32_t offset[1]; /* list of pointers to lh records */
167 } __attribute__((__packed__));
169 /* This has no ID header. */
170 struct ntreg_value_list {
172 uint32_t offset[1]; /* list of pointers to vk records */
173 } __attribute__((__packed__));
175 struct ntreg_vk_record {
176 int32_t seg_len; /* length (always -ve because used) */
177 char id[2]; /* "vk" */
178 uint16_t name_len; /* length of name */
179 /* length of the data:
180 * If data_len is <= 4, then it's stored inline.
181 * Top bit is set to indicate inline.
184 uint32_t data_offset; /* pointer to the data (or data if inline) */
185 uint32_t data_type; /* type of the data */
186 uint16_t flags; /* bit 0 set => key name ASCII,
187 bit 0 clr => key name UTF-16.
188 Only seen ASCII here in the wild.
189 NB: this is CLEAR for default key. */
191 char name[1]; /* key name follows here */
192 } __attribute__((__packed__));
194 struct ntreg_sk_record {
195 int32_t seg_len; /* length (always -ve because used) */
196 char id[2]; /* "sk" */
198 uint32_t sk_next; /* linked into a circular list */
200 uint32_t refcount; /* reference count */
201 uint32_t sec_len; /* length of security info */
202 char sec_desc[1]; /* security info follows */
203 } __attribute__((__packed__));
206 header_checksum (const hive_h *h)
208 uint32_t *daddr = (uint32_t *) h->addr;
212 for (i = 0; i < 0x1fc / 4; ++i) {
213 sum ^= le32toh (*daddr);
220 #define HIVEX_OPEN_MSGLVL_MASK (HIVEX_OPEN_VERBOSE|HIVEX_OPEN_DEBUG)
223 hivex_open (const char *filename, int flags)
227 assert (sizeof (struct ntreg_header) == 0x1000);
228 assert (offsetof (struct ntreg_header, csum) == 0x1fc);
230 h = calloc (1, sizeof *h);
234 h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK;
236 const char *debug = getenv ("HIVEX_DEBUG");
237 if (debug && STREQ (debug, "1"))
241 fprintf (stderr, "hivex_open: created handle %p\n", h);
243 h->writable = !!(flags & HIVEX_OPEN_WRITE);
244 h->filename = strdup (filename);
245 if (h->filename == NULL)
249 h->fd = open (filename, O_RDONLY | O_CLOEXEC);
251 h->fd = open (filename, O_RDONLY);
256 fcntl (h->fd, F_SETFD, FD_CLOEXEC);
260 if (fstat (h->fd, &statbuf) == -1)
263 h->size = statbuf.st_size;
266 h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0);
267 if (h->addr == MAP_FAILED)
271 fprintf (stderr, "hivex_open: mapped file at %p\n", h->addr);
273 h->addr = malloc (h->size);
277 if (full_read (h->fd, h->addr, h->size) < h->size)
280 /* We don't need the file descriptor along this path, since we
281 * have read all the data.
283 if (close (h->fd) == -1)
289 if (h->hdr->magic[0] != 'r' ||
290 h->hdr->magic[1] != 'e' ||
291 h->hdr->magic[2] != 'g' ||
292 h->hdr->magic[3] != 'f') {
293 fprintf (stderr, "hivex: %s: not a Windows NT Registry hive file\n",
299 /* Check major version. */
300 uint32_t major_ver = le32toh (h->hdr->major_ver);
301 if (major_ver != 1) {
303 "hivex: %s: hive file major version %" PRIu32 " (expected 1)\n",
304 filename, major_ver);
309 h->bitmap = calloc (1 + h->size / 32, 1);
310 if (h->bitmap == NULL)
313 /* Header checksum. */
314 uint32_t sum = header_checksum (h);
315 if (sum != le32toh (h->hdr->csum)) {
316 fprintf (stderr, "hivex: %s: bad checksum in hive header\n", filename);
321 /* Last modified time. */
322 h->last_modified = le64toh ((int64_t) h->hdr->last_modified);
324 if (h->msglvl >= 2) {
325 char *name = windows_utf16_to_utf8 (h->hdr->name, 64);
328 "hivex_open: header fields:\n"
329 " file version %" PRIu32 ".%" PRIu32 "\n"
330 " sequence nos %" PRIu32 " %" PRIu32 "\n"
331 " (sequences nos should match if hive was synched at shutdown)\n"
332 " last modified %" PRIu64 "\n"
333 " (Windows filetime, x 100 ns since 1601-01-01)\n"
334 " original file name %s\n"
335 " (only 32 chars are stored, name is probably truncated)\n"
336 " root offset 0x%x + 0x1000\n"
337 " end of last page 0x%x + 0x1000 (total file size 0x%zx)\n"
338 " checksum 0x%x (calculated 0x%x)\n",
339 major_ver, le32toh (h->hdr->minor_ver),
340 le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2),
342 name ? name : "(conversion failed)",
343 le32toh (h->hdr->offset),
344 le32toh (h->hdr->blocks), h->size,
345 le32toh (h->hdr->csum), sum);
349 h->rootoffs = le32toh (h->hdr->offset) + 0x1000;
350 h->endpages = le32toh (h->hdr->blocks) + 0x1000;
353 fprintf (stderr, "hivex_open: root offset = 0x%zx\n", h->rootoffs);
355 /* We'll set this flag when we see a block with the root offset (ie.
358 int seen_root_block = 0, bad_root_block = 0;
360 /* Collect some stats. */
361 size_t pages = 0; /* Number of hbin pages read. */
362 size_t smallest_page = SIZE_MAX, largest_page = 0;
363 size_t blocks = 0; /* Total number of blocks found. */
364 size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0;
365 size_t used_blocks = 0; /* Total number of used blocks found. */
366 size_t used_size = 0; /* Total size (bytes) of used blocks. */
368 /* Read the pages and blocks. The aim here is to be robust against
369 * corrupt or malicious registries. So we make sure the loops
370 * always make forward progress. We add the address of each block
371 * we read to a hash table so pointers will only reference the start
375 struct ntreg_hbin_page *page;
376 for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) {
377 if (off >= h->endpages)
380 page = (struct ntreg_hbin_page *) (h->addr + off);
381 if (page->magic[0] != 'h' ||
382 page->magic[1] != 'b' ||
383 page->magic[2] != 'i' ||
384 page->magic[3] != 'n') {
385 fprintf (stderr, "hivex: %s: trailing garbage at end of file "
386 "(at 0x%zx, after %zu pages)\n",
387 filename, off, pages);
392 size_t page_size = le32toh (page->page_size);
394 fprintf (stderr, "hivex_open: page at 0x%zx, size %zu\n", off, page_size);
396 if (page_size < smallest_page) smallest_page = page_size;
397 if (page_size > largest_page) largest_page = page_size;
399 if (page_size <= sizeof (struct ntreg_hbin_page) ||
400 (page_size & 0x0fff) != 0) {
401 fprintf (stderr, "hivex: %s: page size %zu at 0x%zx, bad registry\n",
402 filename, page_size, off);
407 /* Read the blocks in this page. */
409 struct ntreg_hbin_block *block;
411 for (blkoff = off + 0x20;
412 blkoff < off + page_size;
416 int is_root = blkoff == h->rootoffs;
420 block = (struct ntreg_hbin_block *) (h->addr + blkoff);
422 seg_len = block_len (h, blkoff, &used);
423 if (seg_len <= 4 || (seg_len & 3) != 0) {
424 fprintf (stderr, "hivex: %s: block size %" PRIu32 " at 0x%zx,"
426 filename, le32toh (block->seg_len), blkoff);
432 fprintf (stderr, "hivex_open: %s block id %d,%d at 0x%zx size %zu%s\n",
433 used ? "used" : "free", block->id[0], block->id[1], blkoff,
434 seg_len, is_root ? " (root)" : "");
436 blocks_bytes += seg_len;
437 if (seg_len < smallest_block) smallest_block = seg_len;
438 if (seg_len > largest_block) largest_block = seg_len;
440 if (is_root && !used)
445 used_size += seg_len;
447 /* Root block must be an nk-block. */
448 if (is_root && (block->id[0] != 'n' || block->id[1] != 'k'))
451 /* Note this blkoff is a valid address. */
452 BITMAP_SET (h->bitmap, blkoff);
457 if (!seen_root_block) {
458 fprintf (stderr, "hivex: %s: no root block found\n", filename);
463 if (bad_root_block) {
464 fprintf (stderr, "hivex: %s: bad root block (free or not nk)\n", filename);
471 "hivex_open: successfully read Windows Registry hive file:\n"
472 " pages: %zu [sml: %zu, lge: %zu]\n"
473 " blocks: %zu [sml: %zu, avg: %zu, lge: %zu]\n"
474 " blocks used: %zu\n"
475 " bytes used: %zu\n",
476 pages, smallest_page, largest_page,
477 blocks, smallest_block, blocks_bytes / blocks, largest_block,
478 used_blocks, used_size);
486 if (h->addr && h->size && h->addr != MAP_FAILED) {
488 munmap (h->addr, h->size);
502 hivex_close (hive_h *h)
507 fprintf (stderr, "hivex_close\n");
511 munmap (h->addr, h->size);
524 /*----------------------------------------------------------------------
529 hivex_root (hive_h *h)
531 hive_node_h ret = h->rootoffs;
532 if (!IS_VALID_BLOCK (h, ret)) {
533 errno = HIVEX_NO_KEY;
540 hivex_node_struct_length (hive_h *h, hive_node_h node)
542 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
547 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
548 size_t name_len = le16toh (nk->name_len);
549 /* -1 to avoid double-counting the first name character */
550 size_t ret = name_len + sizeof (struct ntreg_nk_record) - 1;
552 size_t seg_len = block_len (h, node, &used);
555 fprintf (stderr, "hivex_node_struct_length: returning EFAULT because"
556 " node name is too long (%zu, %zu)\n", name_len, seg_len);
564 hivex_node_name (hive_h *h, hive_node_h node)
566 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
571 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
573 /* AFAIK the node name is always plain ASCII, so no conversion
574 * to UTF-8 is necessary. However we do need to nul-terminate
578 /* nk->name_len is unsigned, 16 bit, so this is safe ... However
579 * we have to make sure the length doesn't exceed the block length.
581 size_t len = le16toh (nk->name_len);
582 size_t seg_len = block_len (h, node, NULL);
583 if (sizeof (struct ntreg_nk_record) + len - 1 > seg_len) {
585 fprintf (stderr, "hivex_node_name: returning EFAULT because node name"
586 " is too long (%zu, %zu)\n",
592 char *ret = malloc (len + 1);
595 memcpy (ret, nk->name, len);
601 timestamp_check (hive_h *h, hive_node_h node, int64_t timestamp)
605 fprintf (stderr, "hivex: timestamp_check: "
606 "negative time reported at %zu: %" PRIi64 "\n",
616 hivex_last_modified (hive_h *h)
618 return timestamp_check (h, 0, h->last_modified);
622 hivex_node_timestamp (hive_h *h, hive_node_h node)
626 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
631 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
633 ret = le64toh (nk->timestamp);
634 return timestamp_check (h, node, ret);
638 /* I think the documentation for the sk and classname fields in the nk
639 * record is wrong, or else the offset field is in the wrong place.
640 * Otherwise this makes no sense. Disabled this for now -- it's not
641 * useful for reading the registry anyway.
645 hivex_node_security (hive_h *h, hive_node_h node)
647 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
652 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
654 hive_node_h ret = le32toh (nk->sk);
656 if (!IS_VALID_BLOCK (h, ret)) {
664 hivex_node_classname (hive_h *h, hive_node_h node)
666 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
671 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
673 hive_node_h ret = le32toh (nk->classname);
675 if (!IS_VALID_BLOCK (h, ret)) {
683 /* Structure for returning 0-terminated lists of offsets (nodes,
693 init_offset_list (struct offset_list *list)
697 list->offsets = NULL;
700 #define INIT_OFFSET_LIST(name) \
701 struct offset_list name; \
702 init_offset_list (&name)
704 /* Preallocates the offset_list, but doesn't make the contents longer. */
706 grow_offset_list (struct offset_list *list, size_t alloc)
708 assert (alloc >= list->len);
709 size_t *p = realloc (list->offsets, alloc * sizeof (size_t));
718 add_to_offset_list (struct offset_list *list, size_t offset)
720 if (list->len >= list->alloc) {
721 if (grow_offset_list (list, list->alloc ? list->alloc * 2 : 4) == -1)
724 list->offsets[list->len] = offset;
730 free_offset_list (struct offset_list *list)
732 free (list->offsets);
736 return_offset_list (struct offset_list *list)
738 if (add_to_offset_list (list, 0) == -1)
740 return list->offsets; /* caller frees */
743 /* Iterate over children, returning child nodes and intermediate blocks. */
744 #define GET_CHILDREN_NO_CHECK_NK 1
747 get_children (hive_h *h, hive_node_h node,
748 hive_node_h **children_ret, size_t **blocks_ret,
751 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
756 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
758 size_t nr_subkeys_in_nk = le32toh (nk->nr_subkeys);
760 INIT_OFFSET_LIST (children);
761 INIT_OFFSET_LIST (blocks);
763 /* Deal with the common "no subkeys" case quickly. */
764 if (nr_subkeys_in_nk == 0)
767 /* Arbitrarily limit the number of subkeys we will ever deal with. */
768 if (nr_subkeys_in_nk > HIVEX_MAX_SUBKEYS) {
770 fprintf (stderr, "hivex: get_children: returning ERANGE because "
771 "nr_subkeys_in_nk > HIVEX_MAX_SUBKEYS (%zu > %d)\n",
772 nr_subkeys_in_nk, HIVEX_MAX_SUBKEYS);
777 /* Preallocate space for the children. */
778 if (grow_offset_list (&children, nr_subkeys_in_nk) == -1)
781 /* The subkey_lf field can point either to an lf-record, which is
782 * the common case, or if there are lots of subkeys, to an
785 size_t subkey_lf = le32toh (nk->subkey_lf);
787 if (!IS_VALID_BLOCK (h, subkey_lf)) {
789 fprintf (stderr, "hivex_node_children: returning EFAULT"
790 " because subkey_lf is not a valid block (0x%zx)\n",
796 if (add_to_offset_list (&blocks, subkey_lf) == -1)
799 struct ntreg_hbin_block *block =
800 (struct ntreg_hbin_block *) (h->addr + subkey_lf);
802 /* Points to lf-record? (Note, also "lh" but that is basically the
803 * same as "lf" as far as we are concerned here).
805 if (block->id[0] == 'l' && (block->id[1] == 'f' || block->id[1] == 'h')) {
806 struct ntreg_lf_record *lf = (struct ntreg_lf_record *) block;
808 /* Check number of subkeys in the nk-record matches number of subkeys
811 size_t nr_subkeys_in_lf = le16toh (lf->nr_keys);
814 fprintf (stderr, "hivex_node_children: nr_subkeys_in_nk = %zu,"
815 " nr_subkeys_in_lf = %zu\n",
816 nr_subkeys_in_nk, nr_subkeys_in_lf);
818 if (nr_subkeys_in_nk != nr_subkeys_in_lf) {
823 size_t len = block_len (h, subkey_lf, NULL);
824 if (8 + nr_subkeys_in_lf * 8 > len) {
826 fprintf (stderr, "hivex_node_children: returning EFAULT"
827 " because too many subkeys (%zu, %zu)\n",
828 nr_subkeys_in_lf, len);
834 for (i = 0; i < nr_subkeys_in_lf; ++i) {
835 hive_node_h subkey = le32toh (lf->keys[i].offset);
837 if (!(flags & GET_CHILDREN_NO_CHECK_NK)) {
838 if (!IS_VALID_BLOCK (h, subkey)) {
840 fprintf (stderr, "hivex_node_children: returning EFAULT"
841 " because subkey is not a valid block (0x%zx)\n",
847 if (add_to_offset_list (&children, subkey) == -1)
852 /* Points to ri-record? */
853 else if (block->id[0] == 'r' && block->id[1] == 'i') {
854 struct ntreg_ri_record *ri = (struct ntreg_ri_record *) block;
856 size_t nr_offsets = le16toh (ri->nr_offsets);
858 /* Count total number of children. */
860 for (i = 0; i < nr_offsets; ++i) {
861 hive_node_h offset = le32toh (ri->offset[i]);
863 if (!IS_VALID_BLOCK (h, offset)) {
865 fprintf (stderr, "hivex_node_children: returning EFAULT"
866 " because ri-offset is not a valid block (0x%zx)\n",
871 if (!BLOCK_ID_EQ (h, offset, "lf") && !BLOCK_ID_EQ (h, offset, "lh")) {
873 fprintf (stderr, "get_children: returning ENOTSUP"
874 " because ri-record offset does not point to lf/lh (0x%zx)\n",
880 if (add_to_offset_list (&blocks, offset) == -1)
883 struct ntreg_lf_record *lf =
884 (struct ntreg_lf_record *) (h->addr + offset);
886 count += le16toh (lf->nr_keys);
890 fprintf (stderr, "hivex_node_children: nr_subkeys_in_nk = %zu,"
892 nr_subkeys_in_nk, count);
894 if (nr_subkeys_in_nk != count) {
899 /* Copy list of children. Note nr_subkeys_in_nk is limited to
900 * something reasonable above.
902 for (i = 0; i < nr_offsets; ++i) {
903 hive_node_h offset = le32toh (ri->offset[i]);
905 if (!IS_VALID_BLOCK (h, offset)) {
907 fprintf (stderr, "hivex_node_children: returning EFAULT"
908 " because ri-offset is not a valid block (0x%zx)\n",
913 if (!BLOCK_ID_EQ (h, offset, "lf") && !BLOCK_ID_EQ (h, offset, "lh")) {
915 fprintf (stderr, "get_children: returning ENOTSUP"
916 " because ri-record offset does not point to lf/lh (0x%zx)\n",
922 struct ntreg_lf_record *lf =
923 (struct ntreg_lf_record *) (h->addr + offset);
926 for (j = 0; j < le16toh (lf->nr_keys); ++j) {
927 hive_node_h subkey = le32toh (lf->keys[j].offset);
929 if (!(flags & GET_CHILDREN_NO_CHECK_NK)) {
930 if (!IS_VALID_BLOCK (h, subkey)) {
932 fprintf (stderr, "hivex_node_children: returning EFAULT"
933 " because indirect subkey is not a valid block (0x%zx)\n",
939 if (add_to_offset_list (&children, subkey) == -1)
945 /* else not supported, set errno and fall through */
947 fprintf (stderr, "get_children: returning ENOTSUP"
948 " because subkey block is not lf/lh/ri (0x%zx, %d, %d)\n",
949 subkey_lf, block->id[0], block->id[1]);
952 free_offset_list (&children);
953 free_offset_list (&blocks);
957 *children_ret = return_offset_list (&children);
958 *blocks_ret = return_offset_list (&blocks);
959 if (!*children_ret || !*blocks_ret)
965 hivex_node_children (hive_h *h, hive_node_h node)
967 hive_node_h *children;
970 if (get_children (h, node, &children, &blocks, 0) == -1)
977 /* Very inefficient, but at least having a separate API call
978 * allows us to make it more efficient in future.
981 hivex_node_get_child (hive_h *h, hive_node_h node, const char *nname)
983 hive_node_h *children = NULL;
987 children = hivex_node_children (h, node);
988 if (!children) goto error;
991 for (i = 0; children[i] != 0; ++i) {
992 name = hivex_node_name (h, children[i]);
993 if (!name) goto error;
994 if (STRCASEEQ (name, nname)) {
998 free (name); name = NULL;
1008 hivex_node_parent (hive_h *h, hive_node_h node)
1010 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
1015 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
1017 hive_node_h ret = le32toh (nk->parent);
1019 if (!IS_VALID_BLOCK (h, ret)) {
1021 fprintf (stderr, "hivex_node_parent: returning EFAULT"
1022 " because parent is not a valid block (0x%zx)\n",
1031 get_values (hive_h *h, hive_node_h node,
1032 hive_value_h **values_ret, size_t **blocks_ret)
1034 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
1039 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
1041 size_t nr_values = le32toh (nk->nr_values);
1044 fprintf (stderr, "hivex_node_values: nr_values = %zu\n", nr_values);
1046 INIT_OFFSET_LIST (values);
1047 INIT_OFFSET_LIST (blocks);
1049 /* Deal with the common "no values" case quickly. */
1053 /* Arbitrarily limit the number of values we will ever deal with. */
1054 if (nr_values > HIVEX_MAX_VALUES) {
1056 fprintf (stderr, "hivex: get_values: returning ERANGE"
1057 " because nr_values > HIVEX_MAX_VALUES (%zu > %d)\n",
1058 nr_values, HIVEX_MAX_VALUES);
1063 /* Preallocate space for the values. */
1064 if (grow_offset_list (&values, nr_values) == -1)
1067 /* Get the value list and check it looks reasonable. */
1068 size_t vlist_offset = le32toh (nk->vallist);
1069 vlist_offset += 0x1000;
1070 if (!IS_VALID_BLOCK (h, vlist_offset)) {
1072 fprintf (stderr, "hivex_node_values: returning EFAULT"
1073 " because value list is not a valid block (0x%zx)\n",
1079 if (add_to_offset_list (&blocks, vlist_offset) == -1)
1082 struct ntreg_value_list *vlist =
1083 (struct ntreg_value_list *) (h->addr + vlist_offset);
1085 size_t len = block_len (h, vlist_offset, NULL);
1086 if (4 + nr_values * 4 > len) {
1088 fprintf (stderr, "hivex_node_values: returning EFAULT"
1089 " because value list is too long (%zu, %zu)\n",
1096 for (i = 0; i < nr_values; ++i) {
1097 hive_node_h value = le32toh (vlist->offset[i]);
1099 if (!IS_VALID_BLOCK (h, value)) {
1101 fprintf (stderr, "hivex_node_values: returning EFAULT"
1102 " because value is not a valid block (0x%zx)\n",
1107 if (add_to_offset_list (&values, value) == -1)
1112 *values_ret = return_offset_list (&values);
1113 *blocks_ret = return_offset_list (&blocks);
1114 if (!*values_ret || !*blocks_ret)
1119 free_offset_list (&values);
1120 free_offset_list (&blocks);
1125 hivex_node_values (hive_h *h, hive_node_h node)
1127 hive_value_h *values;
1130 if (get_values (h, node, &values, &blocks) == -1)
1137 /* Very inefficient, but at least having a separate API call
1138 * allows us to make it more efficient in future.
1141 hivex_node_get_value (hive_h *h, hive_node_h node, const char *key)
1143 hive_value_h *values = NULL;
1145 hive_value_h ret = 0;
1147 values = hivex_node_values (h, node);
1148 if (!values) goto error;
1151 for (i = 0; values[i] != 0; ++i) {
1152 name = hivex_value_key (h, values[i]);
1153 if (!name) goto error;
1154 if (STRCASEEQ (name, key)) {
1158 free (name); name = NULL;
1168 hivex_value_struct_length (hive_h *h, hive_value_h value)
1173 key_len = hivex_value_key_len (h, value);
1174 if (key_len == 0 && errno != 0)
1177 /* -1 to avoid double-counting the first name character */
1178 return key_len + sizeof (struct ntreg_vk_record) - 1;
1182 hivex_value_key_len (hive_h *h, hive_value_h value)
1184 if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1189 struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1191 /* vk->name_len is unsigned, 16 bit, so this is safe ... However
1192 * we have to make sure the length doesn't exceed the block length.
1194 size_t ret = le16toh (vk->name_len);
1195 size_t seg_len = block_len (h, value, NULL);
1196 if (sizeof (struct ntreg_vk_record) + ret - 1 > seg_len) {
1198 fprintf (stderr, "hivex_value_key_len: returning EFAULT"
1199 " because key length is too long (%zu, %zu)\n",
1208 hivex_value_key (hive_h *h, hive_value_h value)
1210 if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1215 struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1217 /* AFAIK the key is always plain ASCII, so no conversion to UTF-8 is
1218 * necessary. However we do need to nul-terminate the string.
1221 size_t len = hivex_value_key_len (h, value);
1222 if (len == 0 && errno != 0)
1225 char *ret = malloc (len + 1);
1228 memcpy (ret, vk->name, len);
1234 hivex_value_type (hive_h *h, hive_value_h value, hive_type *t, size_t *len)
1236 if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1241 struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1244 *t = le32toh (vk->data_type);
1247 *len = le32toh (vk->data_len);
1248 *len &= 0x7fffffff; /* top bit indicates if data is stored inline */
1255 hivex_value_value (hive_h *h, hive_value_h value,
1256 hive_type *t_rtn, size_t *len_rtn)
1258 if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1263 struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1269 t = le32toh (vk->data_type);
1271 len = le32toh (vk->data_len);
1272 is_inline = !!(len & 0x80000000);
1276 fprintf (stderr, "hivex_value_value: value=0x%zx, t=%d, len=%zu, inline=%d\n",
1277 value, t, len, is_inline);
1284 if (is_inline && len > 4) {
1289 /* Arbitrarily limit the length that we will read. */
1290 if (len > HIVEX_MAX_VALUE_LEN) {
1292 fprintf (stderr, "hivex_value_value: returning ERANGE because data "
1293 "length > HIVEX_MAX_VALUE_LEN (%zu > %d)\n",
1294 len, HIVEX_MAX_SUBKEYS);
1299 char *ret = malloc (len);
1304 memcpy (ret, (char *) &vk->data_offset, len);
1308 size_t data_offset = le32toh (vk->data_offset);
1309 data_offset += 0x1000;
1310 if (!IS_VALID_BLOCK (h, data_offset)) {
1312 fprintf (stderr, "hivex_value_value: returning EFAULT because data "
1313 "offset is not a valid block (0x%zx)\n",
1320 /* Check that the declared size isn't larger than the block its in.
1322 * XXX Some apparently valid registries are seen to have this,
1323 * so turn this into a warning and substitute the smaller length
1326 size_t blen = block_len (h, data_offset, NULL);
1327 if (len > blen - 4 /* subtract 4 for block header */) {
1329 fprintf (stderr, "hivex_value_value: warning: declared data length "
1330 "is longer than the block it is in "
1331 "(data 0x%zx, data len %zu, block len %zu)\n",
1332 data_offset, len, blen);
1335 /* Return the smaller length to the caller too. */
1340 char *data = h->addr + data_offset + 4;
1341 memcpy (ret, data, len);
1346 windows_utf16_to_utf8 (/* const */ char *input, size_t len)
1348 iconv_t ic = iconv_open ("UTF-8", "UTF-16");
1349 if (ic == (iconv_t) -1)
1352 /* iconv(3) has an insane interface ... */
1354 /* Mostly UTF-8 will be smaller, so this is a good initial guess. */
1355 size_t outalloc = len;
1359 size_t outlen = outalloc;
1360 char *out = malloc (outlen + 1);
1370 size_t r = iconv (ic, &inp, &inlen, &outp, &outlen);
1371 if (r == (size_t) -1) {
1372 if (errno == E2BIG) {
1374 size_t prev = outalloc;
1375 /* Try again with a larger output buffer. */
1378 if (outalloc < prev) {
1386 /* Else some conversion failure, eg. EILSEQ, EINVAL. */
1402 hivex_value_string (hive_h *h, hive_value_h value)
1406 char *data = hivex_value_value (h, value, &t, &len);
1411 if (t != hive_t_string && t != hive_t_expand_string && t != hive_t_link) {
1417 /* Deal with the case where Windows has allocated a large buffer
1418 * full of random junk, and only the first few bytes of the buffer
1419 * contain a genuine UTF-16 string.
1421 * In this case, iconv would try to process the junk bytes as UTF-16
1422 * and inevitably find an illegal sequence (EILSEQ). Instead, stop
1423 * after we find the first \0\0.
1425 * (Found by Hilko Bengen in a fresh Windows XP SOFTWARE hive).
1427 size_t slen = utf16_string_len_in_bytes_max (data, len);
1431 char *ret = windows_utf16_to_utf8 (data, len);
1440 free_strings (char **argv)
1445 for (i = 0; argv[i] != NULL; ++i)
1451 /* Get the length of a UTF-16 format string. Handle the string as
1452 * pairs of bytes, looking for the first \0\0 pair. Only read up to
1453 * 'len' maximum bytes.
1456 utf16_string_len_in_bytes_max (const char *str, size_t len)
1460 while (len >= 2 && (str[0] || str[1])) {
1469 /* http://blogs.msdn.com/oldnewthing/archive/2009/10/08/9904646.aspx */
1471 hivex_value_multiple_strings (hive_h *h, hive_value_h value)
1475 char *data = hivex_value_value (h, value, &t, &len);
1480 if (t != hive_t_multiple_strings) {
1486 size_t nr_strings = 0;
1487 char **ret = malloc ((1 + nr_strings) * sizeof (char *));
1497 while (p < data + len &&
1498 (plen = utf16_string_len_in_bytes_max (p, data + len - p)) > 0) {
1500 char **ret2 = realloc (ret, (1 + nr_strings) * sizeof (char *));
1508 ret[nr_strings-1] = windows_utf16_to_utf8 (p, plen);
1509 ret[nr_strings] = NULL;
1510 if (ret[nr_strings-1] == NULL) {
1516 p += plen + 2 /* skip over UTF-16 \0\0 at the end of this string */;
1524 hivex_value_dword (hive_h *h, hive_value_h value)
1528 char *data = hivex_value_value (h, value, &t, &len);
1533 if ((t != hive_t_dword && t != hive_t_dword_be) || len != 4) {
1539 int32_t ret = *(int32_t*)data;
1541 if (t == hive_t_dword) /* little endian */
1542 ret = le32toh (ret);
1544 ret = be32toh (ret);
1550 hivex_value_qword (hive_h *h, hive_value_h value)
1554 char *data = hivex_value_value (h, value, &t, &len);
1559 if (t != hive_t_qword || len != 8) {
1565 int64_t ret = *(int64_t*)data;
1567 ret = le64toh (ret); /* always little endian */
1572 /*----------------------------------------------------------------------
1577 hivex_visit (hive_h *h, const struct hivex_visitor *visitor, size_t len,
1578 void *opaque, int flags)
1580 return hivex_visit_node (h, hivex_root (h), visitor, len, opaque, flags);
1583 static int hivex__visit_node (hive_h *h, hive_node_h node,
1584 const struct hivex_visitor *vtor,
1585 char *unvisited, void *opaque, int flags);
1588 hivex_visit_node (hive_h *h, hive_node_h node,
1589 const struct hivex_visitor *visitor, size_t len, void *opaque,
1592 struct hivex_visitor vtor;
1593 memset (&vtor, 0, sizeof vtor);
1595 /* Note that len might be larger *or smaller* than the expected size. */
1596 size_t copysize = len <= sizeof vtor ? len : sizeof vtor;
1597 memcpy (&vtor, visitor, copysize);
1599 /* This bitmap records unvisited nodes, so we don't loop if the
1600 * registry contains cycles.
1602 char *unvisited = malloc (1 + h->size / 32);
1603 if (unvisited == NULL)
1605 memcpy (unvisited, h->bitmap, 1 + h->size / 32);
1607 int r = hivex__visit_node (h, node, &vtor, unvisited, opaque, flags);
1613 hivex__visit_node (hive_h *h, hive_node_h node,
1614 const struct hivex_visitor *vtor, char *unvisited,
1615 void *opaque, int flags)
1617 int skip_bad = flags & HIVEX_VISIT_SKIP_BAD;
1619 hive_value_h *values = NULL;
1620 hive_node_h *children = NULL;
1626 /* Return -1 on all callback errors. However on internal errors,
1627 * check if skip_bad is set and suppress those errors if so.
1631 if (!BITMAP_TST (unvisited, node)) {
1633 fprintf (stderr, "hivex__visit_node: contains cycle:"
1634 " visited node 0x%zx already\n",
1638 return skip_bad ? 0 : -1;
1640 BITMAP_CLR (unvisited, node);
1642 name = hivex_node_name (h, node);
1643 if (!name) return skip_bad ? 0 : -1;
1644 if (vtor->node_start && vtor->node_start (h, opaque, node, name) == -1)
1647 values = hivex_node_values (h, node);
1649 ret = skip_bad ? 0 : -1;
1653 for (i = 0; values[i] != 0; ++i) {
1657 if (hivex_value_type (h, values[i], &t, &len) == -1) {
1658 ret = skip_bad ? 0 : -1;
1662 key = hivex_value_key (h, values[i]);
1664 ret = skip_bad ? 0 : -1;
1668 if (vtor->value_any) {
1669 str = hivex_value_value (h, values[i], &t, &len);
1671 ret = skip_bad ? 0 : -1;
1674 if (vtor->value_any (h, opaque, node, values[i], t, len, key, str) == -1)
1676 free (str); str = NULL;
1681 str = hivex_value_value (h, values[i], &t, &len);
1683 ret = skip_bad ? 0 : -1;
1686 if (t != hive_t_none) {
1687 ret = skip_bad ? 0 : -1;
1690 if (vtor->value_none &&
1691 vtor->value_none (h, opaque, node, values[i], t, len, key, str) == -1)
1693 free (str); str = NULL;
1697 case hive_t_expand_string:
1699 str = hivex_value_string (h, values[i]);
1701 if (errno != EILSEQ && errno != EINVAL) {
1702 ret = skip_bad ? 0 : -1;
1705 if (vtor->value_string_invalid_utf16) {
1706 str = hivex_value_value (h, values[i], &t, &len);
1707 if (vtor->value_string_invalid_utf16 (h, opaque, node, values[i],
1708 t, len, key, str) == -1)
1710 free (str); str = NULL;
1714 if (vtor->value_string &&
1715 vtor->value_string (h, opaque, node, values[i],
1716 t, len, key, str) == -1)
1718 free (str); str = NULL;
1722 case hive_t_dword_be: {
1723 int32_t i32 = hivex_value_dword (h, values[i]);
1724 if (vtor->value_dword &&
1725 vtor->value_dword (h, opaque, node, values[i],
1726 t, len, key, i32) == -1)
1731 case hive_t_qword: {
1732 int64_t i64 = hivex_value_qword (h, values[i]);
1733 if (vtor->value_qword &&
1734 vtor->value_qword (h, opaque, node, values[i],
1735 t, len, key, i64) == -1)
1741 str = hivex_value_value (h, values[i], &t, &len);
1743 ret = skip_bad ? 0 : -1;
1746 if (t != hive_t_binary) {
1747 ret = skip_bad ? 0 : -1;
1750 if (vtor->value_binary &&
1751 vtor->value_binary (h, opaque, node, values[i],
1752 t, len, key, str) == -1)
1754 free (str); str = NULL;
1757 case hive_t_multiple_strings:
1758 strs = hivex_value_multiple_strings (h, values[i]);
1760 if (errno != EILSEQ && errno != EINVAL) {
1761 ret = skip_bad ? 0 : -1;
1764 if (vtor->value_string_invalid_utf16) {
1765 str = hivex_value_value (h, values[i], &t, &len);
1766 if (vtor->value_string_invalid_utf16 (h, opaque, node, values[i],
1767 t, len, key, str) == -1)
1769 free (str); str = NULL;
1773 if (vtor->value_multiple_strings &&
1774 vtor->value_multiple_strings (h, opaque, node, values[i],
1775 t, len, key, strs) == -1)
1777 free_strings (strs); strs = NULL;
1780 case hive_t_resource_list:
1781 case hive_t_full_resource_description:
1782 case hive_t_resource_requirements_list:
1784 str = hivex_value_value (h, values[i], &t, &len);
1786 ret = skip_bad ? 0 : -1;
1789 if (vtor->value_other &&
1790 vtor->value_other (h, opaque, node, values[i],
1791 t, len, key, str) == -1)
1793 free (str); str = NULL;
1798 free (key); key = NULL;
1801 children = hivex_node_children (h, node);
1802 if (children == NULL) {
1803 ret = skip_bad ? 0 : -1;
1807 for (i = 0; children[i] != 0; ++i) {
1809 fprintf (stderr, "hivex__visit_node: %s: visiting subkey %d (0x%zx)\n",
1810 name, i, children[i]);
1812 if (hivex__visit_node (h, children[i], vtor, unvisited, opaque, flags) == -1)
1816 if (vtor->node_end && vtor->node_end (h, opaque, node, name) == -1)
1827 free_strings (strs);
1831 /*----------------------------------------------------------------------
1835 /* Allocate an hbin (page), extending the malloc'd space if necessary,
1836 * and updating the hive handle fields (but NOT the hive disk header
1837 * -- the hive disk header is updated when we commit). This function
1838 * also extends the bitmap if necessary.
1840 * 'allocation_hint' is the size of the block allocation we would like
1841 * to make. Normally registry blocks are very small (avg 50 bytes)
1842 * and are contained in standard-sized pages (4KB), but the registry
1843 * can support blocks which are larger than a standard page, in which
1844 * case it creates a page of 8KB, 12KB etc.
1847 * > 0 : offset of first usable byte of new page (after page header)
1848 * 0 : error (errno set)
1851 allocate_page (hive_h *h, size_t allocation_hint)
1853 /* In almost all cases this will be 1. */
1854 size_t nr_4k_pages =
1855 1 + (allocation_hint + sizeof (struct ntreg_hbin_page) - 1) / 4096;
1856 assert (nr_4k_pages >= 1);
1858 /* 'extend' is the number of bytes to extend the file by. Note that
1859 * hives found in the wild often contain slack between 'endpages'
1860 * and the actual end of the file, so we don't always need to make
1863 ssize_t extend = h->endpages + nr_4k_pages * 4096 - h->size;
1865 if (h->msglvl >= 2) {
1866 fprintf (stderr, "allocate_page: current endpages = 0x%zx,"
1867 " current size = 0x%zx\n",
1868 h->endpages, h->size);
1869 fprintf (stderr, "allocate_page: extending file by %zd bytes"
1870 " (<= 0 if no extension)\n",
1875 size_t oldsize = h->size;
1876 size_t newsize = h->size + extend;
1877 char *newaddr = realloc (h->addr, newsize);
1878 if (newaddr == NULL)
1881 size_t oldbitmapsize = 1 + oldsize / 32;
1882 size_t newbitmapsize = 1 + newsize / 32;
1883 char *newbitmap = realloc (h->bitmap, newbitmapsize);
1884 if (newbitmap == NULL) {
1891 h->bitmap = newbitmap;
1893 memset (h->addr + oldsize, 0, newsize - oldsize);
1894 memset (h->bitmap + oldbitmapsize, 0, newbitmapsize - oldbitmapsize);
1897 size_t offset = h->endpages;
1898 h->endpages += nr_4k_pages * 4096;
1901 fprintf (stderr, "allocate_page: new endpages = 0x%zx, new size = 0x%zx\n",
1902 h->endpages, h->size);
1904 /* Write the hbin header. */
1905 struct ntreg_hbin_page *page =
1906 (struct ntreg_hbin_page *) (h->addr + offset);
1907 page->magic[0] = 'h';
1908 page->magic[1] = 'b';
1909 page->magic[2] = 'i';
1910 page->magic[3] = 'n';
1911 page->offset_first = htole32 (offset - 0x1000);
1912 page->page_size = htole32 (nr_4k_pages * 4096);
1913 memset (page->unknown, 0, sizeof (page->unknown));
1916 fprintf (stderr, "allocate_page: new page at 0x%zx\n", offset);
1918 /* Offset of first usable byte after the header. */
1919 return offset + sizeof (struct ntreg_hbin_page);
1922 /* Allocate a single block, first allocating an hbin (page) at the end
1923 * of the current file if necessary. NB. To keep the implementation
1924 * simple and more likely to be correct, we do not reuse existing free
1927 * seg_len is the size of the block (this INCLUDES the block header).
1928 * The header of the block is initialized to -seg_len (negative to
1929 * indicate used). id[2] is the block ID (type), eg. "nk" for nk-
1930 * record. The block bitmap is updated to show this block as valid.
1931 * The rest of the contents of the block will be zero.
1933 * **NB** Because allocate_block may reallocate the memory, all
1934 * pointers into the memory become potentially invalid. I really
1935 * love writing in C, can't you tell?
1938 * > 0 : offset of new block
1939 * 0 : error (errno set)
1942 allocate_block (hive_h *h, size_t seg_len, const char id[2])
1950 /* The caller probably forgot to include the header. Note that
1951 * value lists have no ID field, so seg_len == 4 would be possible
1952 * for them, albeit unusual.
1955 fprintf (stderr, "allocate_block: refusing too small allocation (%zu),"
1956 " returning ERANGE\n", seg_len);
1961 /* Refuse really large allocations. */
1962 if (seg_len > HIVEX_MAX_ALLOCATION) {
1964 fprintf (stderr, "allocate_block: refusing large allocation (%zu),"
1965 " returning ERANGE\n", seg_len);
1970 /* Round up allocation to multiple of 8 bytes. All blocks must be
1971 * on an 8 byte boundary.
1973 seg_len = (seg_len + 7) & ~7;
1975 /* Allocate a new page if necessary. */
1976 if (h->endblocks == 0 || h->endblocks + seg_len > h->endpages) {
1977 size_t newendblocks = allocate_page (h, seg_len);
1978 if (newendblocks == 0)
1980 h->endblocks = newendblocks;
1983 size_t offset = h->endblocks;
1986 fprintf (stderr, "allocate_block: new block at 0x%zx, size %zu\n",
1989 struct ntreg_hbin_block *blockhdr =
1990 (struct ntreg_hbin_block *) (h->addr + offset);
1992 memset (blockhdr, 0, seg_len);
1994 blockhdr->seg_len = htole32 (- (int32_t) seg_len);
1995 if (id[0] && id[1] && seg_len >= sizeof (struct ntreg_hbin_block)) {
1996 blockhdr->id[0] = id[0];
1997 blockhdr->id[1] = id[1];
2000 BITMAP_SET (h->bitmap, offset);
2002 h->endblocks += seg_len;
2004 /* If there is space after the last block in the last page, then we
2005 * have to put a dummy free block header here to mark the rest of
2008 ssize_t rem = h->endpages - h->endblocks;
2011 fprintf (stderr, "allocate_block: marking remainder of page free"
2012 " starting at 0x%zx, size %zd\n", h->endblocks, rem);
2016 blockhdr = (struct ntreg_hbin_block *) (h->addr + h->endblocks);
2017 blockhdr->seg_len = htole32 ((int32_t) rem);
2023 /* 'offset' must point to a valid, used block. This function marks
2024 * the block unused (by updating the seg_len field) and invalidates
2025 * the bitmap. It does NOT do this recursively, so to avoid creating
2026 * unreachable used blocks, callers may have to recurse over the hive
2027 * structures. Also callers must ensure there are no references to
2028 * this block from other parts of the hive.
2031 mark_block_unused (hive_h *h, size_t offset)
2033 assert (h->writable);
2034 assert (IS_VALID_BLOCK (h, offset));
2037 fprintf (stderr, "mark_block_unused: marking 0x%zx unused\n", offset);
2039 struct ntreg_hbin_block *blockhdr =
2040 (struct ntreg_hbin_block *) (h->addr + offset);
2042 size_t seg_len = block_len (h, offset, NULL);
2043 blockhdr->seg_len = htole32 (seg_len);
2045 BITMAP_CLR (h->bitmap, offset);
2048 /* Delete all existing values at this node. */
2050 delete_values (hive_h *h, hive_node_h node)
2052 assert (h->writable);
2054 hive_value_h *values;
2056 if (get_values (h, node, &values, &blocks) == -1)
2060 for (i = 0; blocks[i] != 0; ++i)
2061 mark_block_unused (h, blocks[i]);
2065 for (i = 0; values[i] != 0; ++i) {
2066 struct ntreg_vk_record *vk =
2067 (struct ntreg_vk_record *) (h->addr + values[i]);
2071 len = le32toh (vk->data_len);
2072 is_inline = !!(len & 0x80000000); /* top bit indicates is inline */
2075 if (!is_inline) { /* non-inline, so remove data block */
2076 size_t data_offset = le32toh (vk->data_offset);
2077 data_offset += 0x1000;
2078 mark_block_unused (h, data_offset);
2081 /* remove vk record */
2082 mark_block_unused (h, values[i]);
2087 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
2088 nk->nr_values = htole32 (0);
2089 nk->vallist = htole32 (0xffffffff);
2095 hivex_commit (hive_h *h, const char *filename, int flags)
2107 filename = filename ? : h->filename;
2108 int fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
2112 /* Update the header fields. */
2113 uint32_t sequence = le32toh (h->hdr->sequence1);
2115 h->hdr->sequence1 = htole32 (sequence);
2116 h->hdr->sequence2 = htole32 (sequence);
2117 /* XXX Ought to update h->hdr->last_modified. */
2118 h->hdr->blocks = htole32 (h->endpages - 0x1000);
2120 /* Recompute header checksum. */
2121 uint32_t sum = header_checksum (h);
2122 h->hdr->csum = htole32 (sum);
2125 fprintf (stderr, "hivex_commit: new header checksum: 0x%x\n", sum);
2127 if (full_write (fd, h->addr, h->size) != h->size) {
2134 if (close (fd) == -1)
2140 /* Calculate the hash for a lf or lh record offset.
2143 calc_hash (const char *type, const char *name, char *ret)
2145 size_t len = strlen (name);
2147 if (STRPREFIX (type, "lf"))
2148 /* Old-style, not used in current registries. */
2149 memcpy (ret, name, len < 4 ? len : 4);
2151 /* New-style for lh-records. */
2154 for (i = 0; i < len; ++i) {
2155 c = c_toupper (name[i]);
2159 *((uint32_t *) ret) = htole32 (h);
2163 /* Create a completely new lh-record containing just the single node. */
2165 new_lh_record (hive_h *h, const char *name, hive_node_h node)
2167 static const char id[2] = { 'l', 'h' };
2168 size_t seg_len = sizeof (struct ntreg_lf_record);
2169 size_t offset = allocate_block (h, seg_len, id);
2173 struct ntreg_lf_record *lh = (struct ntreg_lf_record *) (h->addr + offset);
2174 lh->nr_keys = htole16 (1);
2175 lh->keys[0].offset = htole32 (node - 0x1000);
2176 calc_hash ("lh", name, lh->keys[0].hash);
2181 /* Insert node into existing lf/lh-record at position.
2182 * This allocates a new record and marks the old one as unused.
2185 insert_lf_record (hive_h *h, size_t old_offs, size_t posn,
2186 const char *name, hive_node_h node)
2188 assert (IS_VALID_BLOCK (h, old_offs));
2190 /* Work around C stupidity.
2191 * http://www.redhat.com/archives/libguestfs/2010-February/msg00056.html
2193 int test = BLOCK_ID_EQ (h, old_offs, "lf") || BLOCK_ID_EQ (h, old_offs, "lh");
2196 struct ntreg_lf_record *old_lf =
2197 (struct ntreg_lf_record *) (h->addr + old_offs);
2198 size_t nr_keys = le16toh (old_lf->nr_keys);
2200 nr_keys++; /* in new record ... */
2202 size_t seg_len = sizeof (struct ntreg_lf_record) + (nr_keys-1) * 8;
2204 /* Copy the old_lf->id in case it moves during allocate_block. */
2206 memcpy (id, old_lf->id, sizeof id);
2208 size_t new_offs = allocate_block (h, seg_len, id);
2212 /* old_lf could have been invalidated by allocate_block. */
2213 old_lf = (struct ntreg_lf_record *) (h->addr + old_offs);
2215 struct ntreg_lf_record *new_lf =
2216 (struct ntreg_lf_record *) (h->addr + new_offs);
2217 new_lf->nr_keys = htole16 (nr_keys);
2219 /* Copy the keys until we reach posn, insert the new key there, then
2220 * copy the remaining keys.
2223 for (i = 0; i < posn; ++i)
2224 new_lf->keys[i] = old_lf->keys[i];
2226 new_lf->keys[i].offset = htole32 (node - 0x1000);
2227 calc_hash (new_lf->id, name, new_lf->keys[i].hash);
2229 for (i = posn+1; i < nr_keys; ++i)
2230 new_lf->keys[i] = old_lf->keys[i-1];
2232 /* Old block is unused, return new block. */
2233 mark_block_unused (h, old_offs);
2237 /* Compare name with name in nk-record. */
2239 compare_name_with_nk_name (hive_h *h, const char *name, hive_node_h nk_offs)
2241 assert (IS_VALID_BLOCK (h, nk_offs));
2242 assert (BLOCK_ID_EQ (h, nk_offs, "nk"));
2244 /* Name in nk is not necessarily nul-terminated. */
2245 char *nname = hivex_node_name (h, nk_offs);
2247 /* Unfortunately we don't have a way to return errors here. */
2249 perror ("compare_name_with_nk_name");
2253 int r = strcasecmp (name, nname);
2260 hivex_node_add_child (hive_h *h, hive_node_h parent, const char *name)
2267 if (!IS_VALID_BLOCK (h, parent) || !BLOCK_ID_EQ (h, parent, "nk")) {
2272 if (name == NULL || strlen (name) == 0) {
2277 if (hivex_node_get_child (h, parent, name) != 0) {
2282 /* Create the new nk-record. */
2283 static const char nk_id[2] = { 'n', 'k' };
2284 size_t seg_len = sizeof (struct ntreg_nk_record) + strlen (name);
2285 hive_node_h node = allocate_block (h, seg_len, nk_id);
2290 fprintf (stderr, "hivex_node_add_child: allocated new nk-record"
2291 " for child at 0x%zx\n", node);
2293 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
2294 nk->flags = htole16 (0x0020); /* key is ASCII. */
2295 nk->parent = htole32 (parent - 0x1000);
2296 nk->subkey_lf = htole32 (0xffffffff);
2297 nk->subkey_lf_volatile = htole32 (0xffffffff);
2298 nk->vallist = htole32 (0xffffffff);
2299 nk->classname = htole32 (0xffffffff);
2300 nk->name_len = htole16 (strlen (name));
2301 strcpy (nk->name, name);
2303 /* Inherit parent sk. */
2304 struct ntreg_nk_record *parent_nk =
2305 (struct ntreg_nk_record *) (h->addr + parent);
2306 size_t parent_sk_offset = le32toh (parent_nk->sk);
2307 parent_sk_offset += 0x1000;
2308 if (!IS_VALID_BLOCK (h, parent_sk_offset) ||
2309 !BLOCK_ID_EQ (h, parent_sk_offset, "sk")) {
2311 fprintf (stderr, "hivex_node_add_child: returning EFAULT"
2312 " because parent sk is not a valid block (%zu)\n",
2317 struct ntreg_sk_record *sk =
2318 (struct ntreg_sk_record *) (h->addr + parent_sk_offset);
2319 sk->refcount = htole32 (le32toh (sk->refcount) + 1);
2320 nk->sk = htole32 (parent_sk_offset - 0x1000);
2322 /* Inherit parent timestamp. */
2323 nk->timestamp = parent_nk->timestamp;
2325 /* What I found out the hard way (not documented anywhere): the
2326 * subkeys in lh-records must be kept sorted. If you just add a
2327 * subkey in a non-sorted position (eg. just add it at the end) then
2328 * Windows won't see the subkey _and_ Windows will corrupt the hive
2329 * itself when it modifies or saves it.
2331 * So use get_children() to get a list of intermediate
2332 * lf/lh-records. get_children() returns these in reading order
2333 * (which is sorted), so we look for the lf/lh-records in sequence
2334 * until we find the key name just after the one we are inserting,
2335 * and we insert the subkey just before it.
2337 * The only other case is the no-subkeys case, where we have to
2338 * create a brand new lh-record.
2340 hive_node_h *unused;
2343 if (get_children (h, parent, &unused, &blocks, 0) == -1)
2348 size_t nr_subkeys_in_parent_nk = le32toh (parent_nk->nr_subkeys);
2349 if (nr_subkeys_in_parent_nk == 0) { /* No subkeys case. */
2350 /* Free up any existing intermediate blocks. */
2351 for (i = 0; blocks[i] != 0; ++i)
2352 mark_block_unused (h, blocks[i]);
2353 size_t lh_offs = new_lh_record (h, name, node);
2359 /* Recalculate pointers that could have been invalidated by
2360 * previous call to allocate_block (via new_lh_record).
2362 nk = (struct ntreg_nk_record *) (h->addr + node);
2363 parent_nk = (struct ntreg_nk_record *) (h->addr + parent);
2366 fprintf (stderr, "hivex_node_add_child: no keys, allocated new"
2367 " lh-record at 0x%zx\n", lh_offs);
2369 parent_nk->subkey_lf = htole32 (lh_offs - 0x1000);
2371 else { /* Insert subkeys case. */
2372 size_t old_offs = 0, new_offs = 0;
2373 struct ntreg_lf_record *old_lf = NULL;
2375 /* Find lf/lh key name just after the one we are inserting. */
2376 for (i = 0; blocks[i] != 0; ++i) {
2377 if (BLOCK_ID_EQ (h, blocks[i], "lf") ||
2378 BLOCK_ID_EQ (h, blocks[i], "lh")) {
2379 old_offs = blocks[i];
2380 old_lf = (struct ntreg_lf_record *) (h->addr + old_offs);
2381 for (j = 0; j < le16toh (old_lf->nr_keys); ++j) {
2382 hive_node_h nk_offs = le32toh (old_lf->keys[j].offset);
2384 if (compare_name_with_nk_name (h, name, nk_offs) < 0)
2390 /* Insert it at the end.
2391 * old_offs points to the last lf record, set j.
2393 assert (old_offs != 0); /* should never happen if nr_subkeys > 0 */
2394 j = le16toh (old_lf->nr_keys);
2399 fprintf (stderr, "hivex_node_add_child: insert key in existing"
2400 " lh-record at 0x%zx, posn %zu\n", old_offs, j);
2402 new_offs = insert_lf_record (h, old_offs, j, name, node);
2403 if (new_offs == 0) {
2408 /* Recalculate pointers that could have been invalidated by
2409 * previous call to allocate_block (via insert_lf_record).
2411 nk = (struct ntreg_nk_record *) (h->addr + node);
2412 parent_nk = (struct ntreg_nk_record *) (h->addr + parent);
2415 fprintf (stderr, "hivex_node_add_child: new lh-record at 0x%zx\n",
2418 /* If the lf/lh-record was directly referenced by the parent nk,
2419 * then update the parent nk.
2421 if (le32toh (parent_nk->subkey_lf) + 0x1000 == old_offs)
2422 parent_nk->subkey_lf = htole32 (new_offs - 0x1000);
2423 /* Else we have to look for the intermediate ri-record and update
2427 for (i = 0; blocks[i] != 0; ++i) {
2428 if (BLOCK_ID_EQ (h, blocks[i], "ri")) {
2429 struct ntreg_ri_record *ri =
2430 (struct ntreg_ri_record *) (h->addr + blocks[i]);
2431 for (j = 0; j < le16toh (ri->nr_offsets); ++j)
2432 if (le32toh (ri->offset[j] + 0x1000) == old_offs) {
2433 ri->offset[j] = htole32 (new_offs - 0x1000);
2439 /* Not found .. This is an internal error. */
2441 fprintf (stderr, "hivex_node_add_child: returning ENOTSUP"
2442 " because could not find ri->lf link\n");
2454 /* Update nr_subkeys in parent nk. */
2455 nr_subkeys_in_parent_nk++;
2456 parent_nk->nr_subkeys = htole32 (nr_subkeys_in_parent_nk);
2458 /* Update max_subkey_name_len in parent nk. */
2459 uint16_t max = le16toh (parent_nk->max_subkey_name_len);
2460 if (max < strlen (name) * 2) /* *2 because "recoded" in UTF16-LE. */
2461 parent_nk->max_subkey_name_len = htole16 (strlen (name) * 2);
2466 /* Decrement the refcount of an sk-record, and if it reaches zero,
2467 * unlink it from the chain and delete it.
2470 delete_sk (hive_h *h, size_t sk_offset)
2472 if (!IS_VALID_BLOCK (h, sk_offset) || !BLOCK_ID_EQ (h, sk_offset, "sk")) {
2474 fprintf (stderr, "delete_sk: not an sk record: 0x%zx\n", sk_offset);
2479 struct ntreg_sk_record *sk = (struct ntreg_sk_record *) (h->addr + sk_offset);
2481 if (sk->refcount == 0) {
2483 fprintf (stderr, "delete_sk: sk record already has refcount 0: 0x%zx\n",
2491 if (sk->refcount == 0) {
2492 size_t sk_prev_offset = sk->sk_prev;
2493 sk_prev_offset += 0x1000;
2495 size_t sk_next_offset = sk->sk_next;
2496 sk_next_offset += 0x1000;
2498 /* Update sk_prev/sk_next SKs, unless they both point back to this
2499 * cell in which case we are deleting the last SK.
2501 if (sk_prev_offset != sk_offset && sk_next_offset != sk_offset) {
2502 struct ntreg_sk_record *sk_prev =
2503 (struct ntreg_sk_record *) (h->addr + sk_prev_offset);
2504 struct ntreg_sk_record *sk_next =
2505 (struct ntreg_sk_record *) (h->addr + sk_next_offset);
2507 sk_prev->sk_next = htole32 (sk_next_offset - 0x1000);
2508 sk_next->sk_prev = htole32 (sk_prev_offset - 0x1000);
2511 /* Refcount is zero so really delete this block. */
2512 mark_block_unused (h, sk_offset);
2518 /* Callback from hivex_node_delete_child which is called to delete a
2519 * node AFTER its subnodes have been visited. The subnodes have been
2520 * deleted but we still have to delete any lf/lh/li/ri records and the
2521 * value list block and values, followed by deleting the node itself.
2524 delete_node (hive_h *h, void *opaque, hive_node_h node, const char *name)
2526 /* Get the intermediate blocks. The subkeys have already been
2527 * deleted by this point, so tell get_children() not to check for
2528 * validity of the nk-records.
2530 hive_node_h *unused;
2532 if (get_children (h, node, &unused, &blocks, GET_CHILDREN_NO_CHECK_NK) == -1)
2536 /* We don't care what's in these intermediate blocks, so we can just
2537 * delete them unconditionally.
2540 for (i = 0; blocks[i] != 0; ++i)
2541 mark_block_unused (h, blocks[i]);
2545 /* Delete the values in the node. */
2546 if (delete_values (h, node) == -1)
2549 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
2551 /* If the NK references an SK, delete it. */
2552 size_t sk_offs = le32toh (nk->sk);
2553 if (sk_offs != 0xffffffff) {
2555 if (delete_sk (h, sk_offs) == -1)
2557 nk->sk = htole32 (0xffffffff);
2560 /* If the NK references a classname, delete it. */
2561 size_t cl_offs = le32toh (nk->classname);
2562 if (cl_offs != 0xffffffff) {
2564 mark_block_unused (h, cl_offs);
2565 nk->classname = htole32 (0xffffffff);
2568 /* Delete the node itself. */
2569 mark_block_unused (h, node);
2575 hivex_node_delete_child (hive_h *h, hive_node_h node)
2582 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
2587 if (node == hivex_root (h)) {
2589 fprintf (stderr, "hivex_node_delete_child: cannot delete root node\n");
2594 hive_node_h parent = hivex_node_parent (h, node);
2598 /* Delete node and all its children and values recursively. */
2599 static const struct hivex_visitor visitor = { .node_end = delete_node };
2600 if (hivex_visit_node (h, node, &visitor, sizeof visitor, NULL, 0) == -1)
2603 /* Delete the link from parent to child. We need to find the lf/lh
2604 * record which contains the offset and remove the offset from that
2605 * record, then decrement the element count in that record, and
2606 * decrement the overall number of subkeys stored in the parent
2609 hive_node_h *unused;
2611 if (get_children (h, parent, &unused, &blocks, GET_CHILDREN_NO_CHECK_NK)== -1)
2616 for (i = 0; blocks[i] != 0; ++i) {
2617 struct ntreg_hbin_block *block =
2618 (struct ntreg_hbin_block *) (h->addr + blocks[i]);
2620 if (block->id[0] == 'l' && (block->id[1] == 'f' || block->id[1] == 'h')) {
2621 struct ntreg_lf_record *lf = (struct ntreg_lf_record *) block;
2623 size_t nr_subkeys_in_lf = le16toh (lf->nr_keys);
2625 for (j = 0; j < nr_subkeys_in_lf; ++j)
2626 if (le32toh (lf->keys[j].offset) + 0x1000 == node) {
2627 for (; j < nr_subkeys_in_lf - 1; ++j)
2628 memcpy (&lf->keys[j], &lf->keys[j+1], sizeof (lf->keys[j]));
2629 lf->nr_keys = htole16 (nr_subkeys_in_lf - 1);
2635 fprintf (stderr, "hivex_node_delete_child: could not find parent"
2636 " to child link\n");
2641 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + parent);
2642 size_t nr_subkeys_in_nk = le32toh (nk->nr_subkeys);
2643 nk->nr_subkeys = htole32 (nr_subkeys_in_nk - 1);
2646 fprintf (stderr, "hivex_node_delete_child: updating nr_subkeys"
2647 " in parent 0x%zx to %zu\n", parent, nr_subkeys_in_nk);
2653 hivex_node_set_values (hive_h *h, hive_node_h node,
2654 size_t nr_values, const hive_set_value *values,
2662 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
2667 /* Delete all existing values. */
2668 if (delete_values (h, node) == -1)
2674 /* Allocate value list node. Value lists have no id field. */
2675 static const char nul_id[2] = { 0, 0 };
2677 sizeof (struct ntreg_value_list) + (nr_values - 1) * sizeof (uint32_t);
2678 size_t vallist_offs = allocate_block (h, seg_len, nul_id);
2679 if (vallist_offs == 0)
2682 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
2683 nk->nr_values = htole32 (nr_values);
2684 nk->vallist = htole32 (vallist_offs - 0x1000);
2686 struct ntreg_value_list *vallist =
2687 (struct ntreg_value_list *) (h->addr + vallist_offs);
2690 for (i = 0; i < nr_values; ++i) {
2691 /* Allocate vk record to store this (key, value) pair. */
2692 static const char vk_id[2] = { 'v', 'k' };
2693 seg_len = sizeof (struct ntreg_vk_record) + strlen (values[i].key);
2694 size_t vk_offs = allocate_block (h, seg_len, vk_id);
2698 /* Recalculate pointers that could have been invalidated by
2699 * previous call to allocate_block.
2701 nk = (struct ntreg_nk_record *) (h->addr + node);
2702 vallist = (struct ntreg_value_list *) (h->addr + vallist_offs);
2704 vallist->offset[i] = htole32 (vk_offs - 0x1000);
2706 struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + vk_offs);
2707 size_t name_len = strlen (values[i].key);
2708 vk->name_len = htole16 (name_len);
2709 strcpy (vk->name, values[i].key);
2710 vk->data_type = htole32 (values[i].t);
2711 uint32_t len = values[i].len;
2712 if (len <= 4) /* store it inline => set MSB flag */
2714 vk->data_len = htole32 (len);
2715 vk->flags = name_len == 0 ? 0 : 1;
2717 if (values[i].len <= 4) /* store it inline */
2718 memcpy (&vk->data_offset, values[i].value, values[i].len);
2720 size_t offs = allocate_block (h, values[i].len + 4, nul_id);
2724 /* Recalculate pointers that could have been invalidated by
2725 * previous call to allocate_block.
2727 nk = (struct ntreg_nk_record *) (h->addr + node);
2728 vallist = (struct ntreg_value_list *) (h->addr + vallist_offs);
2729 vk = (struct ntreg_vk_record *) (h->addr + vk_offs);
2731 memcpy (h->addr + offs + 4, values[i].value, values[i].len);
2732 vk->data_offset = htole32 (offs - 0x1000);
2735 if (name_len * 2 > le32toh (nk->max_vk_name_len))
2736 /* * 2 for UTF16-LE "reencoding" */
2737 nk->max_vk_name_len = htole32 (name_len * 2);
2738 if (values[i].len > le32toh (nk->max_vk_data_len))
2739 nk->max_vk_data_len = htole32 (values[i].len);
2746 hivex_node_set_value (hive_h *h, hive_node_h node,
2747 const hive_set_value *val, int flags)
2749 hive_value_h *prev_values = hivex_node_values (h, node);
2750 if (prev_values == NULL)
2755 size_t nr_values = 0;
2756 for (hive_value_h *itr = prev_values; *itr != 0; ++itr)
2759 hive_set_value *values = malloc ((nr_values + 1) * (sizeof (hive_set_value)));
2761 goto leave_prev_values;
2764 int idx_of_val = -1;
2765 hive_value_h *prev_val;
2766 for (prev_val = prev_values; *prev_val != 0; ++prev_val) {
2770 hive_set_value *value = &values[prev_val - prev_values];
2772 char *valval = hivex_value_value (h, *prev_val, &t, &len);
2773 if (valval == NULL) goto leave_partial;
2776 value->value = valval;
2780 char *valkey = hivex_value_key (h, *prev_val);
2781 if (valkey == NULL) goto leave_partial;
2784 value->key = valkey;
2786 if (STRCASEEQ (valkey, val->key))
2787 idx_of_val = prev_val - prev_values;
2790 if (idx_of_val > -1) {
2791 free (values[idx_of_val].key);
2792 free (values[idx_of_val].value);
2794 idx_of_val = nr_values;
2798 hive_set_value *value = &values[idx_of_val];
2799 *value = (hive_set_value){
2800 .key = strdup (val->key),
2801 .value = malloc (val->len),
2806 if (value->key == NULL || value->value == NULL) goto leave_partial;
2807 memcpy (value->value, val->value, val->len);
2809 retval = hivex_node_set_values (h, node, nr_values, values, 0);
2812 for (int i = 0; i < alloc_ct; i += 2) {
2813 free (values[i / 2].value);
2814 if (i + 1 < alloc_ct && values[i / 2].key != NULL)
2815 free (values[i / 2].key);