1 /* hivex - Windows Registry "hive" extraction library.
2 * Copyright (C) 2009-2010 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"
45 #define STREQ(a,b) (strcmp((a),(b)) == 0)
46 #define STRCASEEQ(a,b) (strcasecmp((a),(b)) == 0)
47 //#define STRNEQ(a,b) (strcmp((a),(b)) != 0)
48 //#define STRCASENEQ(a,b) (strcasecmp((a),(b)) != 0)
49 #define STREQLEN(a,b,n) (strncmp((a),(b),(n)) == 0)
50 //#define STRCASEEQLEN(a,b,n) (strncasecmp((a),(b),(n)) == 0)
51 //#define STRNEQLEN(a,b,n) (strncmp((a),(b),(n)) != 0)
52 //#define STRCASENEQLEN(a,b,n) (strncasecmp((a),(b),(n)) != 0)
53 #define STRPREFIX(a,b) (strncmp((a),(b),strlen((b))) == 0)
56 #include "byte_conversions.h"
58 /* These limits are in place to stop really stupid stuff and/or exploits. */
59 #define HIVEX_MAX_SUBKEYS 15000
60 #define HIVEX_MAX_VALUES 10000
61 #define HIVEX_MAX_VALUE_LEN 1000000
62 #define HIVEX_MAX_ALLOCATION 1000000
64 static char *windows_utf16_to_utf8 (/* const */ char *input, size_t len);
73 /* Registry file, memory mapped if read-only, or malloc'd if writing. */
76 struct ntreg_header *hdr;
79 /* Use a bitmap to store which file offsets are valid (point to a
80 * used block). We only need to store 1 bit per 32 bits of the file
81 * (because blocks are 4-byte aligned). We found that the average
82 * block size in a registry file is ~50 bytes. So roughly 1 in 12
83 * bits in the bitmap will be set, making it likely a more efficient
84 * structure than a hash table.
87 #define BITMAP_SET(bitmap,off) (bitmap[(off)>>5] |= 1 << (((off)>>2)&7))
88 #define BITMAP_CLR(bitmap,off) (bitmap[(off)>>5] &= ~ (1 << (((off)>>2)&7)))
89 #define BITMAP_TST(bitmap,off) (bitmap[(off)>>5] & (1 << (((off)>>2)&7)))
90 #define IS_VALID_BLOCK(h,off) \
91 (((off) & 3) == 0 && \
93 (off) < (h)->size && \
94 BITMAP_TST((h)->bitmap,(off)))
96 /* Fields from the header, extracted from little-endianness hell. */
97 size_t rootoffs; /* Root key offset (always an nk-block). */
98 size_t endpages; /* Offset of end of pages. */
101 size_t endblocks; /* Offset to next block allocation (0
102 if not allocated anything yet). */
105 /* NB. All fields are little endian. */
106 struct ntreg_header {
107 char magic[4]; /* "regf" */
110 char last_modified[8];
111 uint32_t major_ver; /* 1 */
112 uint32_t minor_ver; /* 3 */
113 uint32_t unknown5; /* 0 */
114 uint32_t unknown6; /* 1 */
115 uint32_t offset; /* offset of root key record - 4KB */
116 uint32_t blocks; /* pointer AFTER last hbin in file - 4KB */
117 uint32_t unknown7; /* 1 */
119 char name[64]; /* original file name of hive */
120 char unknown_guid1[16];
121 char unknown_guid2[16];
124 char unknown_guid3[16];
129 uint32_t csum; /* checksum: xor of dwords 0-0x1fb. */
131 char unknown11[3528];
133 char unknown_guid4[16];
134 char unknown_guid5[16];
135 char unknown_guid6[16];
139 } __attribute__((__packed__));
141 struct ntreg_hbin_page {
142 char magic[4]; /* "hbin" */
143 uint32_t offset_first; /* offset from 1st block */
144 uint32_t page_size; /* size of this page (multiple of 4KB) */
146 /* Linked list of blocks follows here. */
147 } __attribute__((__packed__));
149 struct ntreg_hbin_block {
150 int32_t seg_len; /* length of this block (-ve for used block) */
151 char id[2]; /* the block type (eg. "nk" for nk record) */
152 /* Block data follows here. */
153 } __attribute__((__packed__));
155 #define BLOCK_ID_EQ(h,offs,eqid) \
156 (STREQLEN (((struct ntreg_hbin_block *)((h)->addr + (offs)))->id, (eqid), 2))
159 block_len (hive_h *h, size_t blkoff, int *used)
161 struct ntreg_hbin_block *block;
162 block = (struct ntreg_hbin_block *) (h->addr + blkoff);
164 int32_t len = le32toh (block->seg_len);
175 struct ntreg_nk_record {
176 int32_t seg_len; /* length (always -ve because used) */
177 char id[2]; /* "nk" */
181 uint32_t parent; /* offset of owner/parent */
182 uint32_t nr_subkeys; /* number of subkeys */
183 uint32_t nr_subkeys_volatile;
184 uint32_t subkey_lf; /* lf record containing list of subkeys */
185 uint32_t subkey_lf_volatile;
186 uint32_t nr_values; /* number of values */
187 uint32_t vallist; /* value-list record */
188 uint32_t sk; /* offset of sk-record */
189 uint32_t classname; /* offset of classname record */
190 uint16_t max_subkey_name_len; /* maximum length of a subkey name in bytes
191 if the subkey was reencoded as UTF-16LE */
194 uint32_t max_vk_name_len; /* maximum length of any vk name in bytes
195 if the name was reencoded as UTF-16LE */
196 uint32_t max_vk_data_len; /* maximum length of any vk data in bytes */
198 uint16_t name_len; /* length of name */
199 uint16_t classname_len; /* length of classname */
200 char name[1]; /* name follows here */
201 } __attribute__((__packed__));
203 struct ntreg_lf_record {
205 char id[2]; /* "lf"|"lh" */
206 uint16_t nr_keys; /* number of keys in this record */
208 uint32_t offset; /* offset of nk-record for this subkey */
209 char hash[4]; /* hash of subkey name */
211 } __attribute__((__packed__));
213 struct ntreg_ri_record {
215 char id[2]; /* "ri" */
216 uint16_t nr_offsets; /* number of pointers to lh records */
217 uint32_t offset[1]; /* list of pointers to lh records */
218 } __attribute__((__packed__));
220 /* This has no ID header. */
221 struct ntreg_value_list {
223 uint32_t offset[1]; /* list of pointers to vk records */
224 } __attribute__((__packed__));
226 struct ntreg_vk_record {
227 int32_t seg_len; /* length (always -ve because used) */
228 char id[2]; /* "vk" */
229 uint16_t name_len; /* length of name */
230 /* length of the data:
231 * If data_len is <= 4, then it's stored inline.
232 * Top bit is set to indicate inline.
235 uint32_t data_offset; /* pointer to the data (or data if inline) */
236 uint32_t data_type; /* type of the data */
237 uint16_t flags; /* bit 0 set => key name ASCII,
238 bit 0 clr => key name UTF-16.
239 Only seen ASCII here in the wild.
240 NB: this is CLEAR for default key. */
242 char name[1]; /* key name follows here */
243 } __attribute__((__packed__));
245 struct ntreg_sk_record {
246 int32_t seg_len; /* length (always -ve because used) */
247 char id[2]; /* "sk" */
249 uint32_t sk_next; /* linked into a circular list */
251 uint32_t refcount; /* reference count */
252 uint32_t sec_len; /* length of security info */
253 char sec_desc[1]; /* security info follows */
254 } __attribute__((__packed__));
257 header_checksum (const hive_h *h)
259 uint32_t *daddr = (uint32_t *) h->addr;
263 for (i = 0; i < 0x1fc / 4; ++i) {
264 sum ^= le32toh (*daddr);
271 #define HIVEX_OPEN_MSGLVL_MASK (HIVEX_OPEN_VERBOSE|HIVEX_OPEN_DEBUG)
274 hivex_open (const char *filename, int flags)
278 assert (sizeof (struct ntreg_header) == 0x1000);
279 assert (offsetof (struct ntreg_header, csum) == 0x1fc);
281 h = calloc (1, sizeof *h);
285 h->msglvl = flags & HIVEX_OPEN_MSGLVL_MASK;
287 const char *debug = getenv ("HIVEX_DEBUG");
288 if (debug && STREQ (debug, "1"))
292 fprintf (stderr, "hivex_open: created handle %p\n", h);
294 h->writable = !!(flags & HIVEX_OPEN_WRITE);
295 h->filename = strdup (filename);
296 if (h->filename == NULL)
299 h->fd = open (filename, O_RDONLY | O_CLOEXEC);
304 if (fstat (h->fd, &statbuf) == -1)
307 h->size = statbuf.st_size;
310 h->addr = mmap (NULL, h->size, PROT_READ, MAP_SHARED, h->fd, 0);
311 if (h->addr == MAP_FAILED)
315 fprintf (stderr, "hivex_open: mapped file at %p\n", h->addr);
317 h->addr = malloc (h->size);
321 if (full_read (h->fd, h->addr, h->size) < h->size)
326 if (h->hdr->magic[0] != 'r' ||
327 h->hdr->magic[1] != 'e' ||
328 h->hdr->magic[2] != 'g' ||
329 h->hdr->magic[3] != 'f') {
330 fprintf (stderr, "hivex: %s: not a Windows NT Registry hive file\n",
336 /* Check major version. */
337 uint32_t major_ver = le32toh (h->hdr->major_ver);
338 if (major_ver != 1) {
340 "hivex: %s: hive file major version %" PRIu32 " (expected 1)\n",
341 filename, major_ver);
346 h->bitmap = calloc (1 + h->size / 32, 1);
347 if (h->bitmap == NULL)
350 /* Header checksum. */
351 uint32_t sum = header_checksum (h);
352 if (sum != le32toh (h->hdr->csum)) {
353 fprintf (stderr, "hivex: %s: bad checksum in hive header\n", filename);
358 if (h->msglvl >= 2) {
359 char *name = windows_utf16_to_utf8 (h->hdr->name, 64);
362 "hivex_open: header fields:\n"
363 " file version %" PRIu32 ".%" PRIu32 "\n"
364 " sequence nos %" PRIu32 " %" PRIu32 "\n"
365 " (sequences nos should match if hive was synched at shutdown)\n"
366 " original file name %s\n"
367 " (only 32 chars are stored, name is probably truncated)\n"
368 " root offset 0x%x + 0x1000\n"
369 " end of last page 0x%x + 0x1000 (total file size 0x%zx)\n"
370 " checksum 0x%x (calculated 0x%x)\n",
371 major_ver, le32toh (h->hdr->minor_ver),
372 le32toh (h->hdr->sequence1), le32toh (h->hdr->sequence2),
373 name ? name : "(conversion failed)",
374 le32toh (h->hdr->offset),
375 le32toh (h->hdr->blocks), h->size,
376 le32toh (h->hdr->csum), sum);
380 h->rootoffs = le32toh (h->hdr->offset) + 0x1000;
381 h->endpages = le32toh (h->hdr->blocks) + 0x1000;
384 fprintf (stderr, "hivex_open: root offset = 0x%zx\n", h->rootoffs);
386 /* We'll set this flag when we see a block with the root offset (ie.
389 int seen_root_block = 0, bad_root_block = 0;
391 /* Collect some stats. */
392 size_t pages = 0; /* Number of hbin pages read. */
393 size_t smallest_page = SIZE_MAX, largest_page = 0;
394 size_t blocks = 0; /* Total number of blocks found. */
395 size_t smallest_block = SIZE_MAX, largest_block = 0, blocks_bytes = 0;
396 size_t used_blocks = 0; /* Total number of used blocks found. */
397 size_t used_size = 0; /* Total size (bytes) of used blocks. */
399 /* Read the pages and blocks. The aim here is to be robust against
400 * corrupt or malicious registries. So we make sure the loops
401 * always make forward progress. We add the address of each block
402 * we read to a hash table so pointers will only reference the start
406 struct ntreg_hbin_page *page;
407 for (off = 0x1000; off < h->size; off += le32toh (page->page_size)) {
408 if (off >= h->endpages)
411 page = (struct ntreg_hbin_page *) (h->addr + off);
412 if (page->magic[0] != 'h' ||
413 page->magic[1] != 'b' ||
414 page->magic[2] != 'i' ||
415 page->magic[3] != 'n') {
416 fprintf (stderr, "hivex: %s: trailing garbage at end of file (at 0x%zx, after %zu pages)\n",
417 filename, off, pages);
422 size_t page_size = le32toh (page->page_size);
424 fprintf (stderr, "hivex_open: page at 0x%zx, size %zu\n", off, page_size);
426 if (page_size < smallest_page) smallest_page = page_size;
427 if (page_size > largest_page) largest_page = page_size;
429 if (page_size <= sizeof (struct ntreg_hbin_page) ||
430 (page_size & 0x0fff) != 0) {
431 fprintf (stderr, "hivex: %s: page size %zu at 0x%zx, bad registry\n",
432 filename, page_size, off);
437 /* Read the blocks in this page. */
439 struct ntreg_hbin_block *block;
441 for (blkoff = off + 0x20;
442 blkoff < off + page_size;
446 int is_root = blkoff == h->rootoffs;
450 block = (struct ntreg_hbin_block *) (h->addr + blkoff);
452 seg_len = block_len (h, blkoff, &used);
453 if (seg_len <= 4 || (seg_len & 3) != 0) {
454 fprintf (stderr, "hivex: %s: block size %" PRIu32 " at 0x%zx, bad registry\n",
455 filename, le32toh (block->seg_len), blkoff);
461 fprintf (stderr, "hivex_open: %s block id %d,%d at 0x%zx size %zu%s\n",
462 used ? "used" : "free", block->id[0], block->id[1], blkoff,
463 seg_len, is_root ? " (root)" : "");
465 blocks_bytes += seg_len;
466 if (seg_len < smallest_block) smallest_block = seg_len;
467 if (seg_len > largest_block) largest_block = seg_len;
469 if (is_root && !used)
474 used_size += seg_len;
476 /* Root block must be an nk-block. */
477 if (is_root && (block->id[0] != 'n' || block->id[1] != 'k'))
480 /* Note this blkoff is a valid address. */
481 BITMAP_SET (h->bitmap, blkoff);
486 if (!seen_root_block) {
487 fprintf (stderr, "hivex: %s: no root block found\n", filename);
492 if (bad_root_block) {
493 fprintf (stderr, "hivex: %s: bad root block (free or not nk)\n", filename);
500 "hivex_open: successfully read Windows Registry hive file:\n"
501 " pages: %zu [sml: %zu, lge: %zu]\n"
502 " blocks: %zu [sml: %zu, avg: %zu, lge: %zu]\n"
503 " blocks used: %zu\n"
504 " bytes used: %zu\n",
505 pages, smallest_page, largest_page,
506 blocks, smallest_block, blocks_bytes / blocks, largest_block,
507 used_blocks, used_size);
515 if (h->addr && h->size && h->addr != MAP_FAILED) {
517 munmap (h->addr, h->size);
531 hivex_close (hive_h *h)
537 munmap (h->addr, h->size);
547 /*----------------------------------------------------------------------
552 hivex_root (hive_h *h)
554 hive_node_h ret = h->rootoffs;
555 if (!IS_VALID_BLOCK (h, ret)) {
563 hivex_node_name (hive_h *h, hive_node_h node)
565 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
570 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
572 /* AFAIK the node name is always plain ASCII, so no conversion
573 * to UTF-8 is necessary. However we do need to nul-terminate
577 /* nk->name_len is unsigned, 16 bit, so this is safe ... However
578 * we have to make sure the length doesn't exceed the block length.
580 size_t len = le16toh (nk->name_len);
581 size_t seg_len = block_len (h, node, NULL);
582 if (sizeof (struct ntreg_nk_record) + len - 1 > seg_len) {
584 fprintf (stderr, "hivex_node_name: returning EFAULT because node name is too long (%zu, %zu)\n",
590 char *ret = malloc (len + 1);
593 memcpy (ret, nk->name, len);
599 /* I think the documentation for the sk and classname fields in the nk
600 * record is wrong, or else the offset field is in the wrong place.
601 * Otherwise this makes no sense. Disabled this for now -- it's not
602 * useful for reading the registry anyway.
606 hivex_node_security (hive_h *h, hive_node_h node)
608 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
613 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
615 hive_node_h ret = le32toh (nk->sk);
617 if (!IS_VALID_BLOCK (h, ret)) {
625 hivex_node_classname (hive_h *h, hive_node_h node)
627 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
632 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
634 hive_node_h ret = le32toh (nk->classname);
636 if (!IS_VALID_BLOCK (h, ret)) {
644 /* Structure for returning 0-terminated lists of offsets (nodes,
654 init_offset_list (struct offset_list *list)
658 list->offsets = NULL;
661 #define INIT_OFFSET_LIST(name) \
662 struct offset_list name; \
663 init_offset_list (&name)
665 /* Preallocates the offset_list, but doesn't make the contents longer. */
667 grow_offset_list (struct offset_list *list, size_t alloc)
669 assert (alloc >= list->len);
670 size_t *p = realloc (list->offsets, alloc * sizeof (size_t));
679 add_to_offset_list (struct offset_list *list, size_t offset)
681 if (list->len >= list->alloc) {
682 if (grow_offset_list (list, list->alloc ? list->alloc * 2 : 4) == -1)
685 list->offsets[list->len] = offset;
691 free_offset_list (struct offset_list *list)
693 free (list->offsets);
697 return_offset_list (struct offset_list *list)
699 if (add_to_offset_list (list, 0) == -1)
701 return list->offsets; /* caller frees */
704 /* Iterate over children, returning child nodes and intermediate blocks. */
705 #define GET_CHILDREN_NO_CHECK_NK 1
708 get_children (hive_h *h, hive_node_h node,
709 hive_node_h **children_ret, size_t **blocks_ret,
712 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
717 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
719 size_t nr_subkeys_in_nk = le32toh (nk->nr_subkeys);
721 INIT_OFFSET_LIST (children);
722 INIT_OFFSET_LIST (blocks);
724 /* Deal with the common "no subkeys" case quickly. */
725 if (nr_subkeys_in_nk == 0)
728 /* Arbitrarily limit the number of subkeys we will ever deal with. */
729 if (nr_subkeys_in_nk > HIVEX_MAX_SUBKEYS) {
731 fprintf (stderr, "hivex: get_children: returning ERANGE because nr_subkeys_in_nk > HIVEX_MAX_SUBKEYS (%zu > %d)\n",
732 nr_subkeys_in_nk, HIVEX_MAX_SUBKEYS);
737 /* Preallocate space for the children. */
738 if (grow_offset_list (&children, nr_subkeys_in_nk) == -1)
741 /* The subkey_lf field can point either to an lf-record, which is
742 * the common case, or if there are lots of subkeys, to an
745 size_t subkey_lf = le32toh (nk->subkey_lf);
747 if (!IS_VALID_BLOCK (h, subkey_lf)) {
749 fprintf (stderr, "hivex_node_children: returning EFAULT because subkey_lf is not a valid block (0x%zx)\n",
755 if (add_to_offset_list (&blocks, subkey_lf) == -1)
758 struct ntreg_hbin_block *block =
759 (struct ntreg_hbin_block *) (h->addr + subkey_lf);
761 /* Points to lf-record? (Note, also "lh" but that is basically the
762 * same as "lf" as far as we are concerned here).
764 if (block->id[0] == 'l' && (block->id[1] == 'f' || block->id[1] == 'h')) {
765 struct ntreg_lf_record *lf = (struct ntreg_lf_record *) block;
767 /* Check number of subkeys in the nk-record matches number of subkeys
770 size_t nr_subkeys_in_lf = le16toh (lf->nr_keys);
773 fprintf (stderr, "hivex_node_children: nr_subkeys_in_nk = %zu, nr_subkeys_in_lf = %zu\n",
774 nr_subkeys_in_nk, nr_subkeys_in_lf);
776 if (nr_subkeys_in_nk != nr_subkeys_in_lf) {
781 size_t len = block_len (h, subkey_lf, NULL);
782 if (8 + nr_subkeys_in_lf * 8 > len) {
784 fprintf (stderr, "hivex_node_children: returning EFAULT because too many subkeys (%zu, %zu)\n",
785 nr_subkeys_in_lf, len);
791 for (i = 0; i < nr_subkeys_in_lf; ++i) {
792 hive_node_h subkey = le32toh (lf->keys[i].offset);
794 if (!(flags & GET_CHILDREN_NO_CHECK_NK)) {
795 if (!IS_VALID_BLOCK (h, subkey)) {
797 fprintf (stderr, "hivex_node_children: returning EFAULT because subkey is not a valid block (0x%zx)\n",
803 if (add_to_offset_list (&children, subkey) == -1)
808 /* Points to ri-record? */
809 else if (block->id[0] == 'r' && block->id[1] == 'i') {
810 struct ntreg_ri_record *ri = (struct ntreg_ri_record *) block;
812 size_t nr_offsets = le16toh (ri->nr_offsets);
814 /* Count total number of children. */
816 for (i = 0; i < nr_offsets; ++i) {
817 hive_node_h offset = le32toh (ri->offset[i]);
819 if (!IS_VALID_BLOCK (h, offset)) {
821 fprintf (stderr, "hivex_node_children: returning EFAULT because ri-offset is not a valid block (0x%zx)\n",
826 if (!BLOCK_ID_EQ (h, offset, "lf") && !BLOCK_ID_EQ (h, offset, "lh")) {
828 fprintf (stderr, "get_children: returning ENOTSUP because ri-record offset does not point to lf/lh (0x%zx)\n",
834 if (add_to_offset_list (&blocks, offset) == -1)
837 struct ntreg_lf_record *lf =
838 (struct ntreg_lf_record *) (h->addr + offset);
840 count += le16toh (lf->nr_keys);
844 fprintf (stderr, "hivex_node_children: nr_subkeys_in_nk = %zu, counted = %zu\n",
845 nr_subkeys_in_nk, count);
847 if (nr_subkeys_in_nk != count) {
852 /* Copy list of children. Note nr_subkeys_in_nk is limited to
853 * something reasonable above.
855 for (i = 0; i < nr_offsets; ++i) {
856 hive_node_h offset = le32toh (ri->offset[i]);
858 if (!IS_VALID_BLOCK (h, offset)) {
860 fprintf (stderr, "hivex_node_children: returning EFAULT because ri-offset is not a valid block (0x%zx)\n",
865 if (!BLOCK_ID_EQ (h, offset, "lf") && !BLOCK_ID_EQ (h, offset, "lh")) {
867 fprintf (stderr, "get_children: returning ENOTSUP because ri-record offset does not point to lf/lh (0x%zx)\n",
873 struct ntreg_lf_record *lf =
874 (struct ntreg_lf_record *) (h->addr + offset);
877 for (j = 0; j < le16toh (lf->nr_keys); ++j) {
878 hive_node_h subkey = le32toh (lf->keys[j].offset);
880 if (!(flags & GET_CHILDREN_NO_CHECK_NK)) {
881 if (!IS_VALID_BLOCK (h, subkey)) {
883 fprintf (stderr, "hivex_node_children: returning EFAULT because indirect subkey is not a valid block (0x%zx)\n",
889 if (add_to_offset_list (&children, subkey) == -1)
895 /* else not supported, set errno and fall through */
897 fprintf (stderr, "get_children: returning ENOTSUP because subkey block is not lf/lh/ri (0x%zx, %d, %d)\n",
898 subkey_lf, block->id[0], block->id[1]);
901 free_offset_list (&children);
902 free_offset_list (&blocks);
906 *children_ret = return_offset_list (&children);
907 *blocks_ret = return_offset_list (&blocks);
908 if (!*children_ret || !*blocks_ret)
914 hivex_node_children (hive_h *h, hive_node_h node)
916 hive_node_h *children;
919 if (get_children (h, node, &children, &blocks, 0) == -1)
926 /* Very inefficient, but at least having a separate API call
927 * allows us to make it more efficient in future.
930 hivex_node_get_child (hive_h *h, hive_node_h node, const char *nname)
932 hive_node_h *children = NULL;
936 children = hivex_node_children (h, node);
937 if (!children) goto error;
940 for (i = 0; children[i] != 0; ++i) {
941 name = hivex_node_name (h, children[i]);
942 if (!name) goto error;
943 if (STRCASEEQ (name, nname)) {
947 free (name); name = NULL;
957 hivex_node_parent (hive_h *h, hive_node_h node)
959 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
964 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
966 hive_node_h ret = le32toh (nk->parent);
968 if (!IS_VALID_BLOCK (h, ret)) {
970 fprintf (stderr, "hivex_node_parent: returning EFAULT because parent is not a valid block (0x%zx)\n",
979 get_values (hive_h *h, hive_node_h node,
980 hive_value_h **values_ret, size_t **blocks_ret)
982 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
987 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
989 size_t nr_values = le32toh (nk->nr_values);
992 fprintf (stderr, "hivex_node_values: nr_values = %zu\n", nr_values);
994 INIT_OFFSET_LIST (values);
995 INIT_OFFSET_LIST (blocks);
997 /* Deal with the common "no values" case quickly. */
1001 /* Arbitrarily limit the number of values we will ever deal with. */
1002 if (nr_values > HIVEX_MAX_VALUES) {
1004 fprintf (stderr, "hivex: get_values: returning ERANGE because nr_values > HIVEX_MAX_VALUES (%zu > %d)\n",
1005 nr_values, HIVEX_MAX_VALUES);
1010 /* Preallocate space for the values. */
1011 if (grow_offset_list (&values, nr_values) == -1)
1014 /* Get the value list and check it looks reasonable. */
1015 size_t vlist_offset = le32toh (nk->vallist);
1016 vlist_offset += 0x1000;
1017 if (!IS_VALID_BLOCK (h, vlist_offset)) {
1019 fprintf (stderr, "hivex_node_values: returning EFAULT because value list is not a valid block (0x%zx)\n",
1025 if (add_to_offset_list (&blocks, vlist_offset) == -1)
1028 struct ntreg_value_list *vlist =
1029 (struct ntreg_value_list *) (h->addr + vlist_offset);
1031 size_t len = block_len (h, vlist_offset, NULL);
1032 if (4 + nr_values * 4 > len) {
1034 fprintf (stderr, "hivex_node_values: returning EFAULT because value list is too long (%zu, %zu)\n",
1041 for (i = 0; i < nr_values; ++i) {
1042 hive_node_h value = vlist->offset[i];
1044 if (!IS_VALID_BLOCK (h, value)) {
1046 fprintf (stderr, "hivex_node_values: returning EFAULT because value is not a valid block (0x%zx)\n",
1051 if (add_to_offset_list (&values, value) == -1)
1056 *values_ret = return_offset_list (&values);
1057 *blocks_ret = return_offset_list (&blocks);
1058 if (!*values_ret || !*blocks_ret)
1063 free_offset_list (&values);
1064 free_offset_list (&blocks);
1069 hivex_node_values (hive_h *h, hive_node_h node)
1071 hive_value_h *values;
1074 if (get_values (h, node, &values, &blocks) == -1)
1081 /* Very inefficient, but at least having a separate API call
1082 * allows us to make it more efficient in future.
1085 hivex_node_get_value (hive_h *h, hive_node_h node, const char *key)
1087 hive_value_h *values = NULL;
1089 hive_value_h ret = 0;
1091 values = hivex_node_values (h, node);
1092 if (!values) goto error;
1095 for (i = 0; values[i] != 0; ++i) {
1096 name = hivex_value_key (h, values[i]);
1097 if (!name) goto error;
1098 if (STRCASEEQ (name, key)) {
1102 free (name); name = NULL;
1112 hivex_value_key (hive_h *h, hive_value_h value)
1114 if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1119 struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1121 /* AFAIK the key is always plain ASCII, so no conversion to UTF-8 is
1122 * necessary. However we do need to nul-terminate the string.
1125 /* vk->name_len is unsigned, 16 bit, so this is safe ... However
1126 * we have to make sure the length doesn't exceed the block length.
1128 size_t len = le16toh (vk->name_len);
1129 size_t seg_len = block_len (h, value, NULL);
1130 if (sizeof (struct ntreg_vk_record) + len - 1 > seg_len) {
1132 fprintf (stderr, "hivex_value_key: returning EFAULT because key length is too long (%zu, %zu)\n",
1138 char *ret = malloc (len + 1);
1141 memcpy (ret, vk->name, len);
1147 hivex_value_type (hive_h *h, hive_value_h value, hive_type *t, size_t *len)
1149 if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1154 struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1157 *t = le32toh (vk->data_type);
1160 *len = le32toh (vk->data_len);
1161 *len &= 0x7fffffff; /* top bit indicates if data is stored inline */
1168 hivex_value_value (hive_h *h, hive_value_h value,
1169 hive_type *t_rtn, size_t *len_rtn)
1171 if (!IS_VALID_BLOCK (h, value) || !BLOCK_ID_EQ (h, value, "vk")) {
1176 struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + value);
1182 t = le32toh (vk->data_type);
1184 len = le32toh (vk->data_len);
1185 is_inline = !!(len & 0x80000000);
1189 fprintf (stderr, "hivex_value_value: value=0x%zx, t=%d, len=%zu, inline=%d\n",
1190 value, t, len, is_inline);
1197 if (is_inline && len > 4) {
1202 /* Arbitrarily limit the length that we will read. */
1203 if (len > HIVEX_MAX_VALUE_LEN) {
1205 fprintf (stderr, "hivex_value_value: returning ERANGE because data length > HIVEX_MAX_VALUE_LEN (%zu > %d)\n",
1206 len, HIVEX_MAX_SUBKEYS);
1211 char *ret = malloc (len);
1216 memcpy (ret, (char *) &vk->data_offset, len);
1220 size_t data_offset = le32toh (vk->data_offset);
1221 data_offset += 0x1000;
1222 if (!IS_VALID_BLOCK (h, data_offset)) {
1224 fprintf (stderr, "hivex_value_value: returning EFAULT because data offset is not a valid block (0x%zx)\n",
1231 /* Check that the declared size isn't larger than the block its in.
1233 * XXX Some apparently valid registries are seen to have this,
1234 * so turn this into a warning and substitute the smaller length
1237 size_t blen = block_len (h, data_offset, NULL);
1238 if (len > blen - 4 /* subtract 4 for block header */) {
1240 fprintf (stderr, "hivex_value_value: warning: declared data length is longer than the block it is in (data 0x%zx, data len %zu, block len %zu)\n",
1241 data_offset, len, blen);
1245 char *data = h->addr + data_offset + 4;
1246 memcpy (ret, data, len);
1251 windows_utf16_to_utf8 (/* const */ char *input, size_t len)
1253 iconv_t ic = iconv_open ("UTF-8", "UTF-16");
1254 if (ic == (iconv_t) -1)
1257 /* iconv(3) has an insane interface ... */
1259 /* Mostly UTF-8 will be smaller, so this is a good initial guess. */
1260 size_t outalloc = len;
1264 size_t outlen = outalloc;
1265 char *out = malloc (outlen + 1);
1275 size_t r = iconv (ic, &inp, &inlen, &outp, &outlen);
1276 if (r == (size_t) -1) {
1277 if (errno == E2BIG) {
1278 size_t prev = outalloc;
1279 /* Try again with a larger output buffer. */
1282 if (outalloc < prev)
1287 /* Else some conversion failure, eg. EILSEQ, EINVAL. */
1303 hivex_value_string (hive_h *h, hive_value_h value)
1307 char *data = hivex_value_value (h, value, &t, &len);
1312 if (t != hive_t_string && t != hive_t_expand_string && t != hive_t_link) {
1318 char *ret = windows_utf16_to_utf8 (data, len);
1327 free_strings (char **argv)
1332 for (i = 0; argv[i] != NULL; ++i)
1338 /* Get the length of a UTF-16 format string. Handle the string as
1339 * pairs of bytes, looking for the first \0\0 pair.
1342 utf16_string_len_in_bytes (const char *str)
1346 while (str[0] || str[1]) {
1354 /* http://blogs.msdn.com/oldnewthing/archive/2009/10/08/9904646.aspx */
1356 hivex_value_multiple_strings (hive_h *h, hive_value_h value)
1360 char *data = hivex_value_value (h, value, &t, &len);
1365 if (t != hive_t_multiple_strings) {
1371 size_t nr_strings = 0;
1372 char **ret = malloc ((1 + nr_strings) * sizeof (char *));
1382 while (p < data + len && (plen = utf16_string_len_in_bytes (p)) > 0) {
1384 char **ret2 = realloc (ret, (1 + nr_strings) * sizeof (char *));
1392 ret[nr_strings-1] = windows_utf16_to_utf8 (p, plen);
1393 ret[nr_strings] = NULL;
1394 if (ret[nr_strings-1] == NULL) {
1400 p += plen + 2 /* skip over UTF-16 \0\0 at the end of this string */;
1408 hivex_value_dword (hive_h *h, hive_value_h value)
1412 char *data = hivex_value_value (h, value, &t, &len);
1417 if ((t != hive_t_dword && t != hive_t_dword_be) || len != 4) {
1423 int32_t ret = *(int32_t*)data;
1425 if (t == hive_t_dword) /* little endian */
1426 ret = le32toh (ret);
1428 ret = be32toh (ret);
1434 hivex_value_qword (hive_h *h, hive_value_h value)
1438 char *data = hivex_value_value (h, value, &t, &len);
1443 if (t != hive_t_qword || len != 8) {
1449 int64_t ret = *(int64_t*)data;
1451 ret = le64toh (ret); /* always little endian */
1456 /*----------------------------------------------------------------------
1461 hivex_visit (hive_h *h, const struct hivex_visitor *visitor, size_t len,
1462 void *opaque, int flags)
1464 return hivex_visit_node (h, hivex_root (h), visitor, len, opaque, flags);
1467 static int hivex__visit_node (hive_h *h, hive_node_h node, const struct hivex_visitor *vtor, char *unvisited, void *opaque, int flags);
1470 hivex_visit_node (hive_h *h, hive_node_h node,
1471 const struct hivex_visitor *visitor, size_t len, void *opaque,
1474 struct hivex_visitor vtor;
1475 memset (&vtor, 0, sizeof vtor);
1477 /* Note that len might be larger *or smaller* than the expected size. */
1478 size_t copysize = len <= sizeof vtor ? len : sizeof vtor;
1479 memcpy (&vtor, visitor, copysize);
1481 /* This bitmap records unvisited nodes, so we don't loop if the
1482 * registry contains cycles.
1484 char *unvisited = malloc (1 + h->size / 32);
1485 if (unvisited == NULL)
1487 memcpy (unvisited, h->bitmap, 1 + h->size / 32);
1489 int r = hivex__visit_node (h, node, &vtor, unvisited, opaque, flags);
1495 hivex__visit_node (hive_h *h, hive_node_h node,
1496 const struct hivex_visitor *vtor, char *unvisited,
1497 void *opaque, int flags)
1499 int skip_bad = flags & HIVEX_VISIT_SKIP_BAD;
1501 hive_value_h *values = NULL;
1502 hive_node_h *children = NULL;
1508 /* Return -1 on all callback errors. However on internal errors,
1509 * check if skip_bad is set and suppress those errors if so.
1513 if (!BITMAP_TST (unvisited, node)) {
1515 fprintf (stderr, "hivex__visit_node: contains cycle: visited node 0x%zx already\n",
1519 return skip_bad ? 0 : -1;
1521 BITMAP_CLR (unvisited, node);
1523 name = hivex_node_name (h, node);
1524 if (!name) return skip_bad ? 0 : -1;
1525 if (vtor->node_start && vtor->node_start (h, opaque, node, name) == -1)
1528 values = hivex_node_values (h, node);
1530 ret = skip_bad ? 0 : -1;
1534 for (i = 0; values[i] != 0; ++i) {
1538 if (hivex_value_type (h, values[i], &t, &len) == -1) {
1539 ret = skip_bad ? 0 : -1;
1543 key = hivex_value_key (h, values[i]);
1545 ret = skip_bad ? 0 : -1;
1549 if (vtor->value_any) {
1550 str = hivex_value_value (h, values[i], &t, &len);
1552 ret = skip_bad ? 0 : -1;
1555 if (vtor->value_any (h, opaque, node, values[i], t, len, key, str) == -1)
1557 free (str); str = NULL;
1562 str = hivex_value_value (h, values[i], &t, &len);
1564 ret = skip_bad ? 0 : -1;
1567 if (t != hive_t_none) {
1568 ret = skip_bad ? 0 : -1;
1571 if (vtor->value_none &&
1572 vtor->value_none (h, opaque, node, values[i], t, len, key, str) == -1)
1574 free (str); str = NULL;
1578 case hive_t_expand_string:
1580 str = hivex_value_string (h, values[i]);
1582 if (errno != EILSEQ && errno != EINVAL) {
1583 ret = skip_bad ? 0 : -1;
1586 if (vtor->value_string_invalid_utf16) {
1587 str = hivex_value_value (h, values[i], &t, &len);
1588 if (vtor->value_string_invalid_utf16 (h, opaque, node, values[i], t, len, key, str) == -1)
1590 free (str); str = NULL;
1594 if (vtor->value_string &&
1595 vtor->value_string (h, opaque, node, values[i], t, len, key, str) == -1)
1597 free (str); str = NULL;
1601 case hive_t_dword_be: {
1602 int32_t i32 = hivex_value_dword (h, values[i]);
1603 if (vtor->value_dword &&
1604 vtor->value_dword (h, opaque, node, values[i], t, len, key, i32) == -1)
1609 case hive_t_qword: {
1610 int64_t i64 = hivex_value_qword (h, values[i]);
1611 if (vtor->value_qword &&
1612 vtor->value_qword (h, opaque, node, values[i], t, len, key, i64) == -1)
1618 str = hivex_value_value (h, values[i], &t, &len);
1620 ret = skip_bad ? 0 : -1;
1623 if (t != hive_t_binary) {
1624 ret = skip_bad ? 0 : -1;
1627 if (vtor->value_binary &&
1628 vtor->value_binary (h, opaque, node, values[i], t, len, key, str) == -1)
1630 free (str); str = NULL;
1633 case hive_t_multiple_strings:
1634 strs = hivex_value_multiple_strings (h, values[i]);
1636 if (errno != EILSEQ && errno != EINVAL) {
1637 ret = skip_bad ? 0 : -1;
1640 if (vtor->value_string_invalid_utf16) {
1641 str = hivex_value_value (h, values[i], &t, &len);
1642 if (vtor->value_string_invalid_utf16 (h, opaque, node, values[i], t, len, key, str) == -1)
1644 free (str); str = NULL;
1648 if (vtor->value_multiple_strings &&
1649 vtor->value_multiple_strings (h, opaque, node, values[i], t, len, key, strs) == -1)
1651 free_strings (strs); strs = NULL;
1654 case hive_t_resource_list:
1655 case hive_t_full_resource_description:
1656 case hive_t_resource_requirements_list:
1658 str = hivex_value_value (h, values[i], &t, &len);
1660 ret = skip_bad ? 0 : -1;
1663 if (vtor->value_other &&
1664 vtor->value_other (h, opaque, node, values[i], t, len, key, str) == -1)
1666 free (str); str = NULL;
1671 free (key); key = NULL;
1674 children = hivex_node_children (h, node);
1675 if (children == NULL) {
1676 ret = skip_bad ? 0 : -1;
1680 for (i = 0; children[i] != 0; ++i) {
1682 fprintf (stderr, "hivex__visit_node: %s: visiting subkey %d (0x%zx)\n",
1683 name, i, children[i]);
1685 if (hivex__visit_node (h, children[i], vtor, unvisited, opaque, flags) == -1)
1689 if (vtor->node_end && vtor->node_end (h, opaque, node, name) == -1)
1700 free_strings (strs);
1704 /*----------------------------------------------------------------------
1708 /* Allocate an hbin (page), extending the malloc'd space if necessary,
1709 * and updating the hive handle fields (but NOT the hive disk header
1710 * -- the hive disk header is updated when we commit). This function
1711 * also extends the bitmap if necessary.
1713 * 'allocation_hint' is the size of the block allocation we would like
1714 * to make. Normally registry blocks are very small (avg 50 bytes)
1715 * and are contained in standard-sized pages (4KB), but the registry
1716 * can support blocks which are larger than a standard page, in which
1717 * case it creates a page of 8KB, 12KB etc.
1720 * > 0 : offset of first usable byte of new page (after page header)
1721 * 0 : error (errno set)
1724 allocate_page (hive_h *h, size_t allocation_hint)
1726 /* In almost all cases this will be 1. */
1727 size_t nr_4k_pages =
1728 1 + (allocation_hint + sizeof (struct ntreg_hbin_page) - 1) / 4096;
1729 assert (nr_4k_pages >= 1);
1731 /* 'extend' is the number of bytes to extend the file by. Note that
1732 * hives found in the wild often contain slack between 'endpages'
1733 * and the actual end of the file, so we don't always need to make
1736 ssize_t extend = h->endpages + nr_4k_pages * 4096 - h->size;
1738 if (h->msglvl >= 2) {
1739 fprintf (stderr, "allocate_page: current endpages = 0x%zx, current size = 0x%zx\n",
1740 h->endpages, h->size);
1741 fprintf (stderr, "allocate_page: extending file by %zd bytes (<= 0 if no extension)\n",
1746 size_t oldsize = h->size;
1747 size_t newsize = h->size + extend;
1748 char *newaddr = realloc (h->addr, newsize);
1749 if (newaddr == NULL)
1752 size_t oldbitmapsize = 1 + oldsize / 32;
1753 size_t newbitmapsize = 1 + newsize / 32;
1754 char *newbitmap = realloc (h->bitmap, newbitmapsize);
1755 if (newbitmap == NULL) {
1762 h->bitmap = newbitmap;
1764 memset (h->addr + oldsize, 0, newsize - oldsize);
1765 memset (h->bitmap + oldbitmapsize, 0, newbitmapsize - oldbitmapsize);
1768 size_t offset = h->endpages;
1769 h->endpages += nr_4k_pages * 4096;
1772 fprintf (stderr, "allocate_page: new endpages = 0x%zx, new size = 0x%zx\n",
1773 h->endpages, h->size);
1775 /* Write the hbin header. */
1776 struct ntreg_hbin_page *page =
1777 (struct ntreg_hbin_page *) (h->addr + offset);
1778 page->magic[0] = 'h';
1779 page->magic[1] = 'b';
1780 page->magic[2] = 'i';
1781 page->magic[3] = 'n';
1782 page->offset_first = htole32 (offset - 0x1000);
1783 page->page_size = htole32 (nr_4k_pages * 4096);
1784 memset (page->unknown, 0, sizeof (page->unknown));
1787 fprintf (stderr, "allocate_page: new page at 0x%zx\n", offset);
1789 /* Offset of first usable byte after the header. */
1790 return offset + sizeof (struct ntreg_hbin_page);
1793 /* Allocate a single block, first allocating an hbin (page) at the end
1794 * of the current file if necessary. NB. To keep the implementation
1795 * simple and more likely to be correct, we do not reuse existing free
1798 * seg_len is the size of the block (this INCLUDES the block header).
1799 * The header of the block is initialized to -seg_len (negative to
1800 * indicate used). id[2] is the block ID (type), eg. "nk" for nk-
1801 * record. The block bitmap is updated to show this block as valid.
1802 * The rest of the contents of the block will be zero.
1804 * **NB** Because allocate_block may reallocate the memory, all
1805 * pointers into the memory become potentially invalid. I really
1806 * love writing in C, can't you tell?
1809 * > 0 : offset of new block
1810 * 0 : error (errno set)
1813 allocate_block (hive_h *h, size_t seg_len, const char id[2])
1821 /* The caller probably forgot to include the header. Note that
1822 * value lists have no ID field, so seg_len == 4 would be possible
1823 * for them, albeit unusual.
1826 fprintf (stderr, "allocate_block: refusing too small allocation (%zu), returning ERANGE\n",
1832 /* Refuse really large allocations. */
1833 if (seg_len > HIVEX_MAX_ALLOCATION) {
1835 fprintf (stderr, "allocate_block: refusing large allocation (%zu), returning ERANGE\n",
1841 /* Round up allocation to multiple of 8 bytes. All blocks must be
1842 * on an 8 byte boundary.
1844 seg_len = (seg_len + 7) & ~7;
1846 /* Allocate a new page if necessary. */
1847 if (h->endblocks == 0 || h->endblocks + seg_len > h->endpages) {
1848 size_t newendblocks = allocate_page (h, seg_len);
1849 if (newendblocks == 0)
1851 h->endblocks = newendblocks;
1854 size_t offset = h->endblocks;
1857 fprintf (stderr, "allocate_block: new block at 0x%zx, size %zu\n",
1860 struct ntreg_hbin_block *blockhdr =
1861 (struct ntreg_hbin_block *) (h->addr + offset);
1863 memset (blockhdr, 0, seg_len);
1865 blockhdr->seg_len = htole32 (- (int32_t) seg_len);
1866 if (id[0] && id[1] && seg_len >= sizeof (struct ntreg_hbin_block)) {
1867 blockhdr->id[0] = id[0];
1868 blockhdr->id[1] = id[1];
1871 BITMAP_SET (h->bitmap, offset);
1873 h->endblocks += seg_len;
1875 /* If there is space after the last block in the last page, then we
1876 * have to put a dummy free block header here to mark the rest of
1879 ssize_t rem = h->endpages - h->endblocks;
1882 fprintf (stderr, "allocate_block: marking remainder of page free starting at 0x%zx, size %zd\n",
1887 blockhdr = (struct ntreg_hbin_block *) (h->addr + h->endblocks);
1888 blockhdr->seg_len = htole32 ((int32_t) rem);
1894 /* 'offset' must point to a valid, used block. This function marks
1895 * the block unused (by updating the seg_len field) and invalidates
1896 * the bitmap. It does NOT do this recursively, so to avoid creating
1897 * unreachable used blocks, callers may have to recurse over the hive
1898 * structures. Also callers must ensure there are no references to
1899 * this block from other parts of the hive.
1902 mark_block_unused (hive_h *h, size_t offset)
1904 assert (h->writable);
1905 assert (IS_VALID_BLOCK (h, offset));
1908 fprintf (stderr, "mark_block_unused: marking 0x%zx unused\n", offset);
1910 struct ntreg_hbin_block *blockhdr =
1911 (struct ntreg_hbin_block *) (h->addr + offset);
1913 size_t seg_len = block_len (h, offset, NULL);
1914 blockhdr->seg_len = htole32 (seg_len);
1916 BITMAP_CLR (h->bitmap, offset);
1919 /* Delete all existing values at this node. */
1921 delete_values (hive_h *h, hive_node_h node)
1923 assert (h->writable);
1925 hive_value_h *values;
1927 if (get_values (h, node, &values, &blocks) == -1)
1931 for (i = 0; blocks[i] != 0; ++i)
1932 mark_block_unused (h, blocks[i]);
1936 for (i = 0; values[i] != 0; ++i) {
1937 struct ntreg_vk_record *vk =
1938 (struct ntreg_vk_record *) (h->addr + values[i]);
1942 len = le32toh (vk->data_len);
1943 is_inline = !!(len & 0x80000000); /* top bit indicates is inline */
1946 if (!is_inline) { /* non-inline, so remove data block */
1947 size_t data_offset = le32toh (vk->data_offset);
1948 data_offset += 0x1000;
1949 mark_block_unused (h, data_offset);
1952 /* remove vk record */
1953 mark_block_unused (h, values[i]);
1958 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
1959 nk->nr_values = htole32 (0);
1960 nk->vallist = htole32 (0xffffffff);
1966 hivex_commit (hive_h *h, const char *filename, int flags)
1978 filename = filename ? : h->filename;
1979 int fd = open (filename, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666);
1983 /* Update the header fields. */
1984 uint32_t sequence = le32toh (h->hdr->sequence1);
1986 h->hdr->sequence1 = htole32 (sequence);
1987 h->hdr->sequence2 = htole32 (sequence);
1988 /* XXX Ought to update h->hdr->last_modified. */
1989 h->hdr->blocks = htole32 (h->endpages - 0x1000);
1991 /* Recompute header checksum. */
1992 uint32_t sum = header_checksum (h);
1993 h->hdr->csum = htole32 (sum);
1996 fprintf (stderr, "hivex_commit: new header checksum: 0x%x\n", sum);
1998 if (full_write (fd, h->addr, h->size) != h->size) {
2005 if (close (fd) == -1)
2011 /* Calculate the hash for a lf or lh record offset.
2014 calc_hash (const char *type, const char *name, char *ret)
2016 size_t len = strlen (name);
2018 if (STRPREFIX (type, "lf"))
2019 /* Old-style, not used in current registries. */
2020 memcpy (ret, name, len < 4 ? len : 4);
2022 /* New-style for lh-records. */
2025 for (i = 0; i < len; ++i) {
2026 c = c_toupper (name[i]);
2030 *((uint32_t *) ret) = htole32 (h);
2034 /* Create a completely new lh-record containing just the single node. */
2036 new_lh_record (hive_h *h, const char *name, hive_node_h node)
2038 static const char id[2] = { 'l', 'h' };
2039 size_t seg_len = sizeof (struct ntreg_lf_record);
2040 size_t offset = allocate_block (h, seg_len, id);
2044 struct ntreg_lf_record *lh = (struct ntreg_lf_record *) (h->addr + offset);
2045 lh->nr_keys = htole16 (1);
2046 lh->keys[0].offset = htole32 (node - 0x1000);
2047 calc_hash ("lh", name, lh->keys[0].hash);
2052 /* Insert node into existing lf/lh-record at position.
2053 * This allocates a new record and marks the old one as unused.
2056 insert_lf_record (hive_h *h, size_t old_offs, size_t posn,
2057 const char *name, hive_node_h node)
2059 assert (IS_VALID_BLOCK (h, old_offs));
2061 /* Work around C stupidity.
2062 * http://www.redhat.com/archives/libguestfs/2010-February/msg00056.html
2064 int test = BLOCK_ID_EQ (h, old_offs, "lf") || BLOCK_ID_EQ (h, old_offs, "lh");
2067 struct ntreg_lf_record *old_lf =
2068 (struct ntreg_lf_record *) (h->addr + old_offs);
2069 size_t nr_keys = le16toh (old_lf->nr_keys);
2071 nr_keys++; /* in new record ... */
2073 size_t seg_len = sizeof (struct ntreg_lf_record) + (nr_keys-1) * 8;
2075 /* Copy the old_lf->id in case it moves during allocate_block. */
2077 memcpy (id, old_lf->id, sizeof id);
2079 size_t new_offs = allocate_block (h, seg_len, id);
2083 /* old_lf could have been invalidated by allocate_block. */
2084 old_lf = (struct ntreg_lf_record *) (h->addr + old_offs);
2086 struct ntreg_lf_record *new_lf =
2087 (struct ntreg_lf_record *) (h->addr + new_offs);
2088 new_lf->nr_keys = htole16 (nr_keys);
2090 /* Copy the keys until we reach posn, insert the new key there, then
2091 * copy the remaining keys.
2094 for (i = 0; i < posn; ++i)
2095 new_lf->keys[i] = old_lf->keys[i];
2097 new_lf->keys[i].offset = htole32 (node - 0x1000);
2098 calc_hash (new_lf->id, name, new_lf->keys[i].hash);
2100 for (i = posn+1; i < nr_keys; ++i)
2101 new_lf->keys[i] = old_lf->keys[i-1];
2103 /* Old block is unused, return new block. */
2104 mark_block_unused (h, old_offs);
2108 /* Compare name with name in nk-record. */
2110 compare_name_with_nk_name (hive_h *h, const char *name, hive_node_h nk_offs)
2112 assert (IS_VALID_BLOCK (h, nk_offs));
2113 assert (BLOCK_ID_EQ (h, nk_offs, "nk"));
2115 /* Name in nk is not necessarily nul-terminated. */
2116 char *nname = hivex_node_name (h, nk_offs);
2118 /* Unfortunately we don't have a way to return errors here. */
2120 perror ("compare_name_with_nk_name");
2124 int r = strcasecmp (name, nname);
2131 hivex_node_add_child (hive_h *h, hive_node_h parent, const char *name)
2138 if (!IS_VALID_BLOCK (h, parent) || !BLOCK_ID_EQ (h, parent, "nk")) {
2143 if (name == NULL || strlen (name) == 0) {
2148 if (hivex_node_get_child (h, parent, name) != 0) {
2153 /* Create the new nk-record. */
2154 static const char nk_id[2] = { 'n', 'k' };
2155 size_t seg_len = sizeof (struct ntreg_nk_record) + strlen (name);
2156 hive_node_h node = allocate_block (h, seg_len, nk_id);
2161 fprintf (stderr, "hivex_node_add_child: allocated new nk-record for child at 0x%zx\n", node);
2163 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
2164 nk->flags = htole16 (0x0020); /* key is ASCII. */
2165 nk->parent = htole32 (parent - 0x1000);
2166 nk->subkey_lf = htole32 (0xffffffff);
2167 nk->subkey_lf_volatile = htole32 (0xffffffff);
2168 nk->vallist = htole32 (0xffffffff);
2169 nk->classname = htole32 (0xffffffff);
2170 nk->name_len = htole16 (strlen (name));
2171 strcpy (nk->name, name);
2173 /* Inherit parent sk. */
2174 struct ntreg_nk_record *parent_nk =
2175 (struct ntreg_nk_record *) (h->addr + parent);
2176 size_t parent_sk_offset = le32toh (parent_nk->sk);
2177 parent_sk_offset += 0x1000;
2178 if (!IS_VALID_BLOCK (h, parent_sk_offset) ||
2179 !BLOCK_ID_EQ (h, parent_sk_offset, "sk")) {
2181 fprintf (stderr, "hivex_node_add_child: returning EFAULT because parent sk is not a valid block (%zu)\n",
2186 struct ntreg_sk_record *sk =
2187 (struct ntreg_sk_record *) (h->addr + parent_sk_offset);
2188 sk->refcount = htole32 (le32toh (sk->refcount) + 1);
2189 nk->sk = htole32 (parent_sk_offset - 0x1000);
2191 /* Inherit parent timestamp. */
2192 memcpy (nk->timestamp, parent_nk->timestamp, sizeof (parent_nk->timestamp));
2194 /* What I found out the hard way (not documented anywhere): the
2195 * subkeys in lh-records must be kept sorted. If you just add a
2196 * subkey in a non-sorted position (eg. just add it at the end) then
2197 * Windows won't see the subkey _and_ Windows will corrupt the hive
2198 * itself when it modifies or saves it.
2200 * So use get_children() to get a list of intermediate
2201 * lf/lh-records. get_children() returns these in reading order
2202 * (which is sorted), so we look for the lf/lh-records in sequence
2203 * until we find the key name just after the one we are inserting,
2204 * and we insert the subkey just before it.
2206 * The only other case is the no-subkeys case, where we have to
2207 * create a brand new lh-record.
2209 hive_node_h *unused;
2212 if (get_children (h, parent, &unused, &blocks, 0) == -1)
2217 size_t nr_subkeys_in_parent_nk = le32toh (parent_nk->nr_subkeys);
2218 if (nr_subkeys_in_parent_nk == 0) { /* No subkeys case. */
2219 /* Free up any existing intermediate blocks. */
2220 for (i = 0; blocks[i] != 0; ++i)
2221 mark_block_unused (h, blocks[i]);
2222 size_t lh_offs = new_lh_record (h, name, node);
2228 /* Recalculate pointers that could have been invalidated by
2229 * previous call to allocate_block (via new_lh_record).
2231 nk = (struct ntreg_nk_record *) (h->addr + node);
2232 parent_nk = (struct ntreg_nk_record *) (h->addr + parent);
2235 fprintf (stderr, "hivex_node_add_child: no keys, allocated new lh-record at 0x%zx\n", lh_offs);
2237 parent_nk->subkey_lf = htole32 (lh_offs - 0x1000);
2239 else { /* Insert subkeys case. */
2240 size_t old_offs = 0, new_offs = 0;
2241 struct ntreg_lf_record *old_lf = NULL;
2243 /* Find lf/lh key name just after the one we are inserting. */
2244 for (i = 0; blocks[i] != 0; ++i) {
2245 if (BLOCK_ID_EQ (h, blocks[i], "lf") ||
2246 BLOCK_ID_EQ (h, blocks[i], "lh")) {
2247 old_offs = blocks[i];
2248 old_lf = (struct ntreg_lf_record *) (h->addr + old_offs);
2249 for (j = 0; j < le16toh (old_lf->nr_keys); ++j) {
2250 hive_node_h nk_offs = le32toh (old_lf->keys[j].offset);
2252 if (compare_name_with_nk_name (h, name, nk_offs) < 0)
2258 /* Insert it at the end.
2259 * old_offs points to the last lf record, set j.
2261 assert (old_offs != 0); /* should never happen if nr_subkeys > 0 */
2262 j = le16toh (old_lf->nr_keys);
2267 fprintf (stderr, "hivex_node_add_child: insert key in existing lh-record at 0x%zx, posn %zu\n", old_offs, j);
2269 new_offs = insert_lf_record (h, old_offs, j, name, node);
2270 if (new_offs == 0) {
2275 /* Recalculate pointers that could have been invalidated by
2276 * previous call to allocate_block (via insert_lf_record).
2278 nk = (struct ntreg_nk_record *) (h->addr + node);
2279 parent_nk = (struct ntreg_nk_record *) (h->addr + parent);
2282 fprintf (stderr, "hivex_node_add_child: new lh-record at 0x%zx\n",
2285 /* If the lf/lh-record was directly referenced by the parent nk,
2286 * then update the parent nk.
2288 if (le32toh (parent_nk->subkey_lf) + 0x1000 == old_offs)
2289 parent_nk->subkey_lf = htole32 (new_offs - 0x1000);
2290 /* Else we have to look for the intermediate ri-record and update
2294 for (i = 0; blocks[i] != 0; ++i) {
2295 if (BLOCK_ID_EQ (h, blocks[i], "ri")) {
2296 struct ntreg_ri_record *ri =
2297 (struct ntreg_ri_record *) (h->addr + blocks[i]);
2298 for (j = 0; j < le16toh (ri->nr_offsets); ++j)
2299 if (le32toh (ri->offset[j] + 0x1000) == old_offs) {
2300 ri->offset[j] = htole32 (new_offs - 0x1000);
2306 /* Not found .. This is an internal error. */
2308 fprintf (stderr, "hivex_node_add_child: returning ENOTSUP because could not find ri->lf link\n");
2320 /* Update nr_subkeys in parent nk. */
2321 nr_subkeys_in_parent_nk++;
2322 parent_nk->nr_subkeys = htole32 (nr_subkeys_in_parent_nk);
2324 /* Update max_subkey_name_len in parent nk. */
2325 uint16_t max = le16toh (parent_nk->max_subkey_name_len);
2326 if (max < strlen (name) * 2) /* *2 because "recoded" in UTF16-LE. */
2327 parent_nk->max_subkey_name_len = htole16 (strlen (name) * 2);
2332 /* Decrement the refcount of an sk-record, and if it reaches zero,
2333 * unlink it from the chain and delete it.
2336 delete_sk (hive_h *h, size_t sk_offset)
2338 if (!IS_VALID_BLOCK (h, sk_offset) || !BLOCK_ID_EQ (h, sk_offset, "sk")) {
2340 fprintf (stderr, "delete_sk: not an sk record: 0x%zx\n", sk_offset);
2345 struct ntreg_sk_record *sk = (struct ntreg_sk_record *) (h->addr + sk_offset);
2347 if (sk->refcount == 0) {
2349 fprintf (stderr, "delete_sk: sk record already has refcount 0: 0x%zx\n",
2357 if (sk->refcount == 0) {
2358 size_t sk_prev_offset = sk->sk_prev;
2359 sk_prev_offset += 0x1000;
2361 size_t sk_next_offset = sk->sk_next;
2362 sk_next_offset += 0x1000;
2364 /* Update sk_prev/sk_next SKs, unless they both point back to this
2365 * cell in which case we are deleting the last SK.
2367 if (sk_prev_offset != sk_offset && sk_next_offset != sk_offset) {
2368 struct ntreg_sk_record *sk_prev =
2369 (struct ntreg_sk_record *) (h->addr + sk_prev_offset);
2370 struct ntreg_sk_record *sk_next =
2371 (struct ntreg_sk_record *) (h->addr + sk_next_offset);
2373 sk_prev->sk_next = htole32 (sk_next_offset - 0x1000);
2374 sk_next->sk_prev = htole32 (sk_prev_offset - 0x1000);
2377 /* Refcount is zero so really delete this block. */
2378 mark_block_unused (h, sk_offset);
2384 /* Callback from hivex_node_delete_child which is called to delete a
2385 * node AFTER its subnodes have been visited. The subnodes have been
2386 * deleted but we still have to delete any lf/lh/li/ri records and the
2387 * value list block and values, followed by deleting the node itself.
2390 delete_node (hive_h *h, void *opaque, hive_node_h node, const char *name)
2392 /* Get the intermediate blocks. The subkeys have already been
2393 * deleted by this point, so tell get_children() not to check for
2394 * validity of the nk-records.
2396 hive_node_h *unused;
2398 if (get_children (h, node, &unused, &blocks, GET_CHILDREN_NO_CHECK_NK) == -1)
2402 /* We don't care what's in these intermediate blocks, so we can just
2403 * delete them unconditionally.
2406 for (i = 0; blocks[i] != 0; ++i)
2407 mark_block_unused (h, blocks[i]);
2411 /* Delete the values in the node. */
2412 if (delete_values (h, node) == -1)
2415 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
2417 /* If the NK references an SK, delete it. */
2418 size_t sk_offs = le32toh (nk->sk);
2419 if (sk_offs != 0xffffffff) {
2421 if (delete_sk (h, sk_offs) == -1)
2423 nk->sk = htole32 (0xffffffff);
2426 /* If the NK references a classname, delete it. */
2427 size_t cl_offs = le32toh (nk->classname);
2428 if (cl_offs != 0xffffffff) {
2430 mark_block_unused (h, cl_offs);
2431 nk->classname = htole32 (0xffffffff);
2434 /* Delete the node itself. */
2435 mark_block_unused (h, node);
2441 hivex_node_delete_child (hive_h *h, hive_node_h node)
2448 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
2453 if (node == hivex_root (h)) {
2455 fprintf (stderr, "hivex_node_delete_child: cannot delete root node\n");
2460 hive_node_h parent = hivex_node_parent (h, node);
2464 /* Delete node and all its children and values recursively. */
2465 static const struct hivex_visitor visitor = { .node_end = delete_node };
2466 if (hivex_visit_node (h, node, &visitor, sizeof visitor, NULL, 0) == -1)
2469 /* Delete the link from parent to child. We need to find the lf/lh
2470 * record which contains the offset and remove the offset from that
2471 * record, then decrement the element count in that record, and
2472 * decrement the overall number of subkeys stored in the parent
2475 hive_node_h *unused;
2477 if (get_children (h, parent, &unused, &blocks, GET_CHILDREN_NO_CHECK_NK)== -1)
2482 for (i = 0; blocks[i] != 0; ++i) {
2483 struct ntreg_hbin_block *block =
2484 (struct ntreg_hbin_block *) (h->addr + blocks[i]);
2486 if (block->id[0] == 'l' && (block->id[1] == 'f' || block->id[1] == 'h')) {
2487 struct ntreg_lf_record *lf = (struct ntreg_lf_record *) block;
2489 size_t nr_subkeys_in_lf = le16toh (lf->nr_keys);
2491 for (j = 0; j < nr_subkeys_in_lf; ++j)
2492 if (le32toh (lf->keys[j].offset) + 0x1000 == node) {
2493 for (; j < nr_subkeys_in_lf - 1; ++j)
2494 memcpy (&lf->keys[j], &lf->keys[j+1], sizeof (lf->keys[j]));
2495 lf->nr_keys = htole16 (nr_subkeys_in_lf - 1);
2501 fprintf (stderr, "hivex_node_delete_child: could not find parent to child link\n");
2506 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + parent);
2507 size_t nr_subkeys_in_nk = le32toh (nk->nr_subkeys);
2508 nk->nr_subkeys = htole32 (nr_subkeys_in_nk - 1);
2511 fprintf (stderr, "hivex_node_delete_child: updating nr_subkeys in parent 0x%zx to %zu\n",
2512 parent, nr_subkeys_in_nk);
2518 hivex_node_set_values (hive_h *h, hive_node_h node,
2519 size_t nr_values, const hive_set_value *values,
2527 if (!IS_VALID_BLOCK (h, node) || !BLOCK_ID_EQ (h, node, "nk")) {
2532 /* Delete all existing values. */
2533 if (delete_values (h, node) == -1)
2539 /* Allocate value list node. Value lists have no id field. */
2540 static const char nul_id[2] = { 0, 0 };
2542 sizeof (struct ntreg_value_list) + (nr_values - 1) * sizeof (uint32_t);
2543 size_t vallist_offs = allocate_block (h, seg_len, nul_id);
2544 if (vallist_offs == 0)
2547 struct ntreg_nk_record *nk = (struct ntreg_nk_record *) (h->addr + node);
2548 nk->nr_values = htole32 (nr_values);
2549 nk->vallist = htole32 (vallist_offs - 0x1000);
2551 struct ntreg_value_list *vallist =
2552 (struct ntreg_value_list *) (h->addr + vallist_offs);
2555 for (i = 0; i < nr_values; ++i) {
2556 /* Allocate vk record to store this (key, value) pair. */
2557 static const char vk_id[2] = { 'v', 'k' };
2558 seg_len = sizeof (struct ntreg_vk_record) + strlen (values[i].key);
2559 size_t vk_offs = allocate_block (h, seg_len, vk_id);
2563 /* Recalculate pointers that could have been invalidated by
2564 * previous call to allocate_block.
2566 nk = (struct ntreg_nk_record *) (h->addr + node);
2567 vallist = (struct ntreg_value_list *) (h->addr + vallist_offs);
2569 vallist->offset[i] = htole32 (vk_offs - 0x1000);
2571 struct ntreg_vk_record *vk = (struct ntreg_vk_record *) (h->addr + vk_offs);
2572 size_t name_len = strlen (values[i].key);
2573 vk->name_len = htole16 (name_len);
2574 strcpy (vk->name, values[i].key);
2575 vk->data_type = htole32 (values[i].t);
2576 uint32_t len = values[i].len;
2577 if (len <= 4) /* store it inline => set MSB flag */
2579 vk->data_len = htole32 (len);
2580 vk->flags = name_len == 0 ? 0 : 1;
2582 if (values[i].len <= 4) /* store it inline */
2583 memcpy (&vk->data_offset, values[i].value, values[i].len);
2585 size_t offs = allocate_block (h, values[i].len + 4, nul_id);
2589 /* Recalculate pointers that could have been invalidated by
2590 * previous call to allocate_block.
2592 nk = (struct ntreg_nk_record *) (h->addr + node);
2593 vallist = (struct ntreg_value_list *) (h->addr + vallist_offs);
2594 vk = (struct ntreg_vk_record *) (h->addr + vk_offs);
2596 memcpy (h->addr + offs + 4, values[i].value, values[i].len);
2597 vk->data_offset = htole32 (offs - 0x1000);
2600 if (name_len * 2 > le32toh (nk->max_vk_name_len))
2601 /* * 2 for UTF16-LE "reencoding" */
2602 nk->max_vk_name_len = htole32 (name_len * 2);
2603 if (values[i].len > le32toh (nk->max_vk_data_len))
2604 nk->max_vk_data_len = htole32 (values[i].len);