Sync to the changes in head ...
[Samba.git] / source3 / utils / editreg.c
blob08561dd868772797ee422f12b37531ce894b1dfc
1 /*
2 Samba Unix/Linux SMB client utility editreg.c
3 Copyright (C) 2002 Richard Sharpe, rsharpe@richardsharpe.com
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
19 /*************************************************************************
21 A utility to edit a Windows NT/2K etc registry file.
23 Many of the ideas in here come from other people and software.
24 I first looked in Wine in misc/registry.c and was also influenced by
25 http://www.wednesday.demon.co.uk/dosreg.html
27 Which seems to contain comments from someone else. I reproduce them here
28 incase the site above disappears. It actually comes from
29 http://home.eunet.no/~pnordahl/ntpasswd/WinReg.txt.
31 The goal here is to read the registry into memory, manipulate it, and then
32 write it out if it was changed by any actions of the user.
34 The windows NT registry has 2 different blocks, where one can occur many
35 times...
37 the "regf"-Block
38 ================
40 "regf" is obviosly the abbreviation for "Registry file". "regf" is the
41 signature of the header-block which is always 4kb in size, although only
42 the first 64 bytes seem to be used and a checksum is calculated over
43 the first 0x200 bytes only!
45 Offset Size Contents
46 0x00000000 D-Word ID: ASCII-"regf" = 0x66676572
47 0x00000004 D-Word ???? //see struct REGF
48 0x00000008 D-Word ???? Always the same value as at 0x00000004
49 0x0000000C Q-Word last modify date in WinNT date-format
50 0x00000014 D-Word 1
51 0x00000018 D-Word 3
52 0x0000001C D-Word 0
53 0x00000020 D-Word 1
54 0x00000024 D-Word Offset of 1st key record
55 0x00000028 D-Word Size of the data-blocks (Filesize-4kb)
56 0x0000002C D-Word 1
57 0x000001FC D-Word Sum of all D-Words from 0x00000000 to
58 0x000001FB //XOR of all words. Nigel
60 I have analyzed more registry files (from multiple machines running
61 NT 4.0 german version) and could not find an explanation for the values
62 marked with ???? the rest of the first 4kb page is not important...
64 the "hbin"-Block
65 ================
66 I don't know what "hbin" stands for, but this block is always a multiple
67 of 4kb in size.
69 Inside these hbin-blocks the different records are placed. The memory-
70 management looks like a C-compiler heap management to me...
72 hbin-Header
73 ===========
74 Offset Size Contents
75 0x0000 D-Word ID: ASCII-"hbin" = 0x6E696268
76 0x0004 D-Word Offset from the 1st hbin-Block
77 0x0008 D-Word Offset to the next hbin-Block
78 0x001C D-Word Block-size
80 The values in 0x0008 and 0x001C should be the same, so I don't know
81 if they are correct or swapped...
83 From offset 0x0020 inside a hbin-block data is stored with the following
84 format:
86 Offset Size Contents
87 0x0000 D-Word Data-block size //this size must be a
88 multiple of 8. Nigel
89 0x0004 ???? Data
91 If the size field is negative (bit 31 set), the corresponding block
92 is free and has a size of -blocksize!
94 That does not seem to be true. All block lengths seem to be negative!
95 (Richard Sharpe)
97 The data is stored as one record per block. Block size is a multiple
98 of 4 and the last block reaches the next hbin-block, leaving no room.
100 (That also seems incorrect, in that the block size if a multiple of 8.
101 That is, the block, including the 4 byte header, is always a multiple of
102 8 bytes. Richard Sharpe.)
104 Records in the hbin-blocks
105 ==========================
107 nk-Record
109 The nk-record can be treated as a kombination of tree-record and
110 key-record of the win 95 registry.
112 lf-Record
114 The lf-record is the counterpart to the RGKN-record (the
115 hash-function)
117 vk-Record
119 The vk-record consists information to a single value.
121 sk-Record
123 sk (? Security Key ?) is the ACL of the registry.
125 Value-Lists
127 The value-lists contain information about which values are inside a
128 sub-key and don't have a header.
130 Datas
132 The datas of the registry are (like the value-list) stored without a
133 header.
135 All offset-values are relative to the first hbin-block and point to the
136 block-size field of the record-entry. to get the file offset, you have to add
137 the header size (4kb) and the size field (4 bytes)...
139 the nk-Record
140 =============
141 Offset Size Contents
142 0x0000 Word ID: ASCII-"nk" = 0x6B6E
143 0x0002 Word for the root-key: 0x2C, otherwise 0x20 //key symbolic links 0x10. Nigel
144 0x0004 Q-Word write-date/time in windows nt notation
145 0x0010 D-Word Offset of Owner/Parent key
146 0x0014 D-Word number of sub-Keys
147 0x001C D-Word Offset of the sub-key lf-Records
148 0x0024 D-Word number of values
149 0x0028 D-Word Offset of the Value-List
150 0x002C D-Word Offset of the sk-Record
152 0x0030 D-Word Offset of the Class-Name //see NK structure for the use of these fields. Nigel
153 0x0044 D-Word Unused (data-trash) //some kind of run time index. Does not appear to be important. Nigel
154 0x0048 Word name-length
155 0x004A Word class-name length
156 0x004C ???? key-name
158 the Value-List
159 ==============
160 Offset Size Contents
161 0x0000 D-Word Offset 1st Value
162 0x0004 D-Word Offset 2nd Value
163 0x???? D-Word Offset nth Value
165 To determine the number of values, you have to look at the owner-nk-record!
167 Der vk-Record
168 =============
169 Offset Size Contents
170 0x0000 Word ID: ASCII-"vk" = 0x6B76
171 0x0002 Word name length
172 0x0004 D-Word length of the data //if top bit is set when offset contains data. Nigel
173 0x0008 D-Word Offset of Data
174 0x000C D-Word Type of value
175 0x0010 Word Flag
176 0x0012 Word Unused (data-trash)
177 0x0014 ???? Name
179 If bit 0 of the flag-word is set, a name is present, otherwise the value has no name (=default)
181 If the data-size is lower 5, the data-offset value is used to store the data itself!
183 The data-types
184 ==============
185 Wert Beteutung
186 0x0001 RegSZ: character string (in UNICODE!)
187 0x0002 ExpandSZ: string with "%var%" expanding (UNICODE!)
188 0x0003 RegBin: raw-binary value
189 0x0004 RegDWord: Dword
190 0x0007 RegMultiSZ: multiple strings, seperated with 0
191 (UNICODE!)
193 The "lf"-record
194 ===============
195 Offset Size Contents
196 0x0000 Word ID: ASCII-"lf" = 0x666C
197 0x0002 Word number of keys
198 0x0004 ???? Hash-Records
200 Hash-Record
201 ===========
202 Offset Size Contents
203 0x0000 D-Word Offset of corresponding "nk"-Record
204 0x0004 D-Word ASCII: the first 4 characters of the key-name, padded with 0's. Case sensitiv!
206 Keep in mind, that the value at 0x0004 is used for checking the data-consistency! If you change the
207 key-name you have to change the hash-value too!
209 //These hashrecords must be sorted low to high within the lf record. Nigel.
211 The "sk"-block
212 ==============
213 (due to the complexity of the SAM-info, not clear jet)
214 (This is just a self-relative security descriptor in the data. R Sharpe.)
217 Offset Size Contents
218 0x0000 Word ID: ASCII-"sk" = 0x6B73
219 0x0002 Word Unused
220 0x0004 D-Word Offset of previous "sk"-Record
221 0x0008 D-Word Offset of next "sk"-Record
222 0x000C D-Word usage-counter
223 0x0010 D-Word Size of "sk"-record in bytes
224 ???? //standard self
225 relative security desciptor. Nigel
226 ???? ???? Security and auditing settings...
227 ????
229 The usage counter counts the number of references to this
230 "sk"-record. You can use one "sk"-record for the entire registry!
232 Windows nt date/time format
233 ===========================
234 The time-format is a 64-bit integer which is incremented every
235 0,0000001 seconds by 1 (I don't know how accurate it realy is!)
236 It starts with 0 at the 1st of january 1601 0:00! All values are
237 stored in GMT time! The time-zone is important to get the real
238 time!
240 Common values for win95 and win-nt
241 ==================================
242 Offset values marking an "end of list", are either 0 or -1 (0xFFFFFFFF).
243 If a value has no name (length=0, flag(bit 0)=0), it is treated as the
244 "Default" entry...
245 If a value has no data (length=0), it is displayed as empty.
247 simplyfied win-3.?? registry:
248 =============================
250 +-----------+
251 | next rec. |---+ +----->+------------+
252 | first sub | | | | Usage cnt. |
253 | name | | +-->+------------+ | | length |
254 | value | | | | next rec. | | | text |------->+-------+
255 +-----------+ | | | name rec. |--+ +------------+ | xxxxx |
256 +------------+ | | value rec. |-------->+------------+ +-------+
257 v | +------------+ | Usage cnt. |
258 +-----------+ | | length |
259 | next rec. | | | text |------->+-------+
260 | first sub |------+ +------------+ | xxxxx |
261 | name | +-------+
262 | value |
263 +-----------+
265 Greatly simplyfied structure of the nt-registry:
266 ================================================
268 +---------------------------------------------------------------+
271 +---------+ +---------->+-----------+ +----->+---------+ |
272 | "nk" | | | lf-rec. | | | nk-rec. | |
273 | ID | | | # of keys | | | parent |---+
274 | Date | | | 1st key |--+ | .... |
275 | parent | | +-----------+ +---------+
276 | suk-keys|-----+
277 | values |--------------------->+----------+
278 | SK-rec. |---------------+ | 1. value |--> +----------+
279 | class |--+ | +----------+ | vk-rec. |
280 +---------+ | | | .... |
281 v | | data |--> +-------+
282 +------------+ | +----------+ | xxxxx |
283 | Class name | | +-------+
284 +------------+ |
286 +---------+ +---------+
287 +----->| next sk |--->| Next sk |--+
288 | +---| prev sk |<---| prev sk | |
289 | | | .... | | ... | |
290 | | +---------+ +---------+ |
291 | | ^ |
292 | | | |
293 | +--------------------+ |
294 +----------------------------------+
296 ---------------------------------------------------------------------------
298 Hope this helps.... (Although it was "fun" for me to uncover this things,
299 it took me several sleepless nights ;)
301 B.D.
303 *************************************************************************/
305 #include <stdio.h>
306 #include <stdlib.h>
307 #include <errno.h>
308 #include <assert.h>
309 #include <sys/types.h>
310 #include <sys/stat.h>
311 #include <unistd.h>
312 #include <sys/mman.h>
313 #include <string.h>
314 #include <fcntl.h>
316 #define False 0
317 #define True 1
318 #define REG_KEY_LIST_SIZE 10
321 * Structures for dealing with the on-disk format of the registry
324 #define IVAL(buf) ((unsigned int) \
325 (unsigned int)*((unsigned char *)(buf)+3)<<24| \
326 (unsigned int)*((unsigned char *)(buf)+2)<<16| \
327 (unsigned int)*((unsigned char *)(buf)+1)<<8| \
328 (unsigned int)*((unsigned char *)(buf)+0))
330 #define SVAL(buf) ((unsigned short) \
331 (unsigned short)*((unsigned char *)(buf)+1)<<8| \
332 (unsigned short)*((unsigned char *)(buf)+0))
334 #define CVAL(buf) ((unsigned char)*((unsigned char *)(buf)))
336 #define SIVAL(buf, val) \
337 ((((unsigned char *)(buf))[0])=(unsigned char)((val)&0xFF),\
338 (((unsigned char *)(buf))[1])=(unsigned char)(((val)>>8)&0xFF),\
339 (((unsigned char *)(buf))[2])=(unsigned char)(((val)>>16)&0xFF),\
340 (((unsigned char *)(buf))[3])=(unsigned char)((val)>>24))
342 #define SSVAL(buf, val) \
343 ((((unsigned char *)(buf))[0])=(unsigned char)((val)&0xFF),\
344 (((unsigned char *)(buf))[1])=(unsigned char)((val)>>8))
346 static int verbose = 0;
347 static int print_security = 0;
348 static int full_print = 0;
349 static const char *def_owner_sid_str = NULL;
352 * These definitions are for the in-memory registry structure.
353 * It is a tree structure that mimics what you see with tools like regedit
357 * DateTime struct for Windows
360 typedef struct date_time_s {
361 unsigned int low, high;
362 } NTTIME;
365 * Definition of a Key. It has a name, classname, date/time last modified,
366 * sub-keys, values, and a security descriptor
369 #define REG_ROOT_KEY 1
370 #define REG_SUB_KEY 2
371 #define REG_SYM_LINK 3
373 typedef struct key_sec_desc_s KEY_SEC_DESC;
375 typedef struct reg_key_s {
376 char *name; /* Name of the key */
377 char *class_name;
378 int type; /* One of REG_ROOT_KEY or REG_SUB_KEY */
379 NTTIME last_mod; /* Time last modified */
380 struct reg_key_s *owner;
381 struct key_list_s *sub_keys;
382 struct val_list_s *values;
383 KEY_SEC_DESC *security;
384 unsigned int offset; /* Offset of the record in the file */
385 } REG_KEY;
388 * The KEY_LIST struct lists sub-keys.
391 typedef struct key_list_s {
392 int key_count;
393 int max_keys;
394 REG_KEY *keys[1];
395 } KEY_LIST;
397 typedef struct val_key_s {
398 char *name;
399 int has_name;
400 int data_type;
401 int data_len;
402 void *data_blk; /* Might want a separate block */
403 } VAL_KEY;
405 typedef struct val_list_s {
406 int val_count;
407 int max_vals;
408 VAL_KEY *vals[1];
409 } VAL_LIST;
411 #ifndef MAXSUBAUTHS
412 #define MAXSUBAUTHS 15
413 #endif
415 typedef struct dom_sid_s {
416 unsigned char ver, auths;
417 unsigned char auth[6];
418 unsigned int sub_auths[MAXSUBAUTHS];
419 } DOM_SID;
421 typedef struct ace_struct_s {
422 unsigned char type, flags;
423 unsigned int perms; /* Perhaps a better def is in order */
424 DOM_SID *trustee;
425 } ACE;
427 typedef struct acl_struct_s {
428 unsigned short rev, refcnt;
429 unsigned short num_aces;
430 ACE *aces[1];
431 } ACL;
433 typedef struct sec_desc_s {
434 unsigned int rev, type;
435 DOM_SID *owner, *group;
436 ACL *sacl, *dacl;
437 } SEC_DESC;
439 #define SEC_DESC_NON 0
440 #define SEC_DESC_RES 1
441 #define SEC_DESC_OCU 2
442 #define SEC_DESC_NBK 3
443 typedef struct sk_struct SK_HDR;
444 struct key_sec_desc_s {
445 struct key_sec_desc_s *prev, *next;
446 int ref_cnt;
447 int state;
448 int offset;
449 SK_HDR *sk_hdr; /* This means we must keep the registry in memory */
450 SEC_DESC *sec_desc;
454 * All of the structures below actually have a four-byte length before them
455 * which always seems to be negative. The following macro retrieves that
456 * size as an integer
459 #define BLK_SIZE(b) ((int)*(int *)(((int *)b)-1))
461 typedef unsigned int DWORD;
462 typedef unsigned short WORD;
464 #define REG_REGF_ID 0x66676572
466 typedef struct regf_block {
467 DWORD REGF_ID; /* regf */
468 DWORD uk1;
469 DWORD uk2;
470 DWORD tim1, tim2;
471 DWORD uk3; /* 1 */
472 DWORD uk4; /* 3 */
473 DWORD uk5; /* 0 */
474 DWORD uk6; /* 1 */
475 DWORD first_key; /* offset */
476 unsigned int dblk_size;
477 DWORD uk7[116]; /* 1 */
478 DWORD chksum;
479 } REGF_HDR;
481 typedef struct hbin_sub_struct {
482 DWORD dblocksize;
483 char data[1];
484 } HBIN_SUB_HDR;
486 #define REG_HBIN_ID 0x6E696268
488 typedef struct hbin_struct {
489 DWORD HBIN_ID; /* hbin */
490 DWORD off_from_first;
491 DWORD off_to_next;
492 DWORD uk1;
493 DWORD uk2;
494 DWORD uk3;
495 DWORD uk4;
496 DWORD blk_size;
497 HBIN_SUB_HDR hbin_sub_hdr;
498 } HBIN_HDR;
500 #define REG_NK_ID 0x6B6E
502 typedef struct nk_struct {
503 WORD NK_ID;
504 WORD type;
505 DWORD t1, t2;
506 DWORD uk1;
507 DWORD own_off;
508 DWORD subk_num;
509 DWORD uk2;
510 DWORD lf_off;
511 DWORD uk3;
512 DWORD val_cnt;
513 DWORD val_off;
514 DWORD sk_off;
515 DWORD clsnam_off;
516 DWORD unk4[4];
517 DWORD unk5;
518 WORD nam_len;
519 WORD clsnam_len;
520 char key_nam[1]; /* Actual length determined by nam_len */
521 } NK_HDR;
523 #define REG_SK_ID 0x6B73
525 struct sk_struct {
526 WORD SK_ID;
527 WORD uk1;
528 DWORD prev_off;
529 DWORD next_off;
530 DWORD ref_cnt;
531 DWORD rec_size;
532 char sec_desc[1];
535 typedef struct ace_struct {
536 unsigned char type;
537 unsigned char flags;
538 unsigned short length;
539 unsigned int perms;
540 DOM_SID trustee;
541 } REG_ACE;
543 typedef struct acl_struct {
544 WORD rev;
545 WORD size;
546 DWORD num_aces;
547 REG_ACE *aces; /* One or more ACEs */
548 } REG_ACL;
550 typedef struct sec_desc_rec {
551 WORD rev;
552 WORD type;
553 DWORD owner_off;
554 DWORD group_off;
555 DWORD sacl_off;
556 DWORD dacl_off;
557 } REG_SEC_DESC;
559 typedef struct hash_struct {
560 DWORD nk_off;
561 char hash[4];
562 } HASH_REC;
564 #define REG_LF_ID 0x666C
566 typedef struct lf_struct {
567 WORD LF_ID;
568 WORD key_count;
569 struct hash_struct hr[1]; /* Array of hash records, depending on key_count */
570 } LF_HDR;
572 typedef DWORD VL_TYPE[1]; /* Value list is an array of vk rec offsets */
574 #define REG_VK_ID 0x6B76
576 typedef struct vk_struct {
577 WORD VK_ID;
578 WORD nam_len;
579 DWORD dat_len; /* If top-bit set, offset contains the data */
580 DWORD dat_off;
581 DWORD dat_type;
582 WORD flag; /* =1, has name, else no name (=Default). */
583 WORD unk1;
584 char dat_name[1]; /* Name starts here ... */
585 } VK_HDR;
587 #define REG_TYPE_DELETE -1
588 #define REG_TYPE_NONE 0
589 #define REG_TYPE_REGSZ 1
590 #define REG_TYPE_EXPANDSZ 2
591 #define REG_TYPE_BIN 3
592 #define REG_TYPE_DWORD 4
593 #define REG_TYPE_MULTISZ 7
595 typedef struct _val_str {
596 unsigned int val;
597 const char * str;
598 } VAL_STR;
600 /* A map of sk offsets in the regf to KEY_SEC_DESCs for quick lookup etc */
601 typedef struct sk_map_s {
602 int sk_off;
603 KEY_SEC_DESC *key_sec_desc;
604 } SK_MAP;
607 * This structure keeps track of the output format of the registry
609 #define REG_OUTBLK_HDR 1
610 #define REG_OUTBLK_HBIN 2
612 typedef struct hbin_blk_s {
613 int type, size;
614 struct hbin_blk_s *next;
615 char *data; /* The data block */
616 unsigned int file_offset; /* Offset in file */
617 unsigned int free_space; /* Amount of free space in block */
618 unsigned int fsp_off; /* Start of free space in block */
619 int complete, stored;
620 } HBIN_BLK;
623 * This structure keeps all the registry stuff in one place
625 typedef struct regf_struct_s {
626 int reg_type;
627 char *regfile_name, *outfile_name;
628 int fd;
629 struct stat sbuf;
630 char *base;
631 int modified;
632 NTTIME last_mod_time;
633 REG_KEY *root; /* Root of the tree for this file */
634 int sk_count, sk_map_size;
635 SK_MAP *sk_map;
636 const char *owner_sid_str;
637 SEC_DESC *def_sec_desc;
639 * These next pointers point to the blocks used to contain the
640 * keys when we are preparing to write them to a file
642 HBIN_BLK *blk_head, *blk_tail, *free_space;
643 } REGF;
646 * An API for accessing/creating/destroying items above
650 * Iterate over the keys, depth first, calling a function for each key
651 * and indicating if it is terminal or non-terminal and if it has values.
653 * In addition, for each value in the list, call a value list function
656 typedef int (*key_print_f)(const char *path, char *key_name, char *class_name,
657 int root, int terminal, int values);
659 typedef int (*val_print_f)(const char *path, char *val_name, int val_type,
660 int data_len, void *data_blk, int terminal,
661 int first, int last);
663 typedef int (*sec_print_f)(SEC_DESC *sec_desc);
665 int nt_key_iterator(REGF *regf, REG_KEY *key_tree, int bf, const char *path,
666 key_print_f key_print, sec_print_f sec_print,
667 val_print_f val_print);
669 int nt_val_list_iterator(REGF *regf, VAL_LIST *val_list, int bf, char *path,
670 int terminal, val_print_f val_print)
672 int i;
674 if (!val_list) return 1;
676 if (!val_print) return 1;
678 for (i=0; i<val_list->val_count; i++) {
679 if (!val_print(path, val_list->vals[i]->name, val_list->vals[i]->data_type,
680 val_list->vals[i]->data_len, val_list->vals[i]->data_blk,
681 terminal,
682 (i == 0),
683 (i == val_list->val_count))) {
685 return 0;
690 return 1;
693 int nt_key_list_iterator(REGF *regf, KEY_LIST *key_list, int bf,
694 const char *path,
695 key_print_f key_print, sec_print_f sec_print,
696 val_print_f val_print)
698 int i;
700 if (!key_list) return 1;
702 for (i=0; i< key_list->key_count; i++) {
703 if (!nt_key_iterator(regf, key_list->keys[i], bf, path, key_print,
704 sec_print, val_print)) {
705 return 0;
708 return 1;
711 int nt_key_iterator(REGF *regf, REG_KEY *key_tree, int bf, const char *path,
712 key_print_f key_print, sec_print_f sec_print,
713 val_print_f val_print)
715 int path_len = strlen(path);
716 char *new_path;
718 if (!regf || !key_tree)
719 return -1;
721 /* List the key first, then the values, then the sub-keys */
723 if (key_print) {
725 if (!(*key_print)(path, key_tree->name,
726 key_tree->class_name,
727 (key_tree->type == REG_ROOT_KEY),
728 (key_tree->sub_keys == NULL),
729 (key_tree->values?(key_tree->values->val_count):0)))
730 return 0;
734 * If we have a security print routine, call it
735 * If the security print routine returns false, stop.
737 if (sec_print) {
738 if (key_tree->security && !(*sec_print)(key_tree->security->sec_desc))
739 return 0;
742 new_path = (char *)malloc(path_len + 1 + strlen(key_tree->name) + 1);
743 if (!new_path) return 0; /* Errors? */
744 new_path[0] = '\0';
745 strcat(new_path, path);
746 strcat(new_path, key_tree->name);
747 strcat(new_path, "\\");
750 * Now, iterate through the values in the val_list
753 if (key_tree->values &&
754 !nt_val_list_iterator(regf, key_tree->values, bf, new_path,
755 (key_tree->values!=NULL),
756 val_print)) {
758 free(new_path);
759 return 0;
763 * Now, iterate through the keys in the key list
766 if (key_tree->sub_keys &&
767 !nt_key_list_iterator(regf, key_tree->sub_keys, bf, new_path, key_print,
768 sec_print, val_print)) {
769 free(new_path);
770 return 0;
773 free(new_path);
774 return 1;
777 REG_KEY *nt_find_key_by_name(REG_KEY *tree, char *key);
780 * Find key by name in a list ...
781 * Take the first component and search for that in the list
783 REG_KEY *nt_find_key_in_list_by_name(KEY_LIST *list, char *key)
785 int i;
786 REG_KEY *res = NULL;
788 if (!list || !key || !*key) return NULL;
790 for (i = 0; i < list->key_count; i++)
791 if ((res = nt_find_key_by_name(list->keys[i], key)))
792 return res;
794 return NULL;
798 * Find key by name in a tree ... We will assume absolute names here, but we
799 * need the root of the tree ...
801 REG_KEY *nt_find_key_by_name(REG_KEY *tree, char *key)
803 char *lname = NULL, *c1, *c2;
804 REG_KEY *tmp;
806 if (!tree || !key || !*key) return NULL;
808 lname = strdup(key);
809 if (!lname) return NULL;
812 * Make sure that the first component is correct ...
814 c1 = lname;
815 c2 = strchr(c1, '\\');
816 if (c2) { /* Split here ... */
817 *c2 = 0;
818 c2++;
820 if (strcmp(c1, tree->name) != 0) goto error;
822 if (c2) {
823 tmp = nt_find_key_in_list_by_name(tree->sub_keys, c2);
824 free(lname);
825 return tmp;
827 else {
828 if (lname) free(lname);
829 return tree;
831 error:
832 if (lname) free(lname);
833 return NULL;
836 /* Make, delete keys */
838 int nt_delete_val_key(VAL_KEY *val_key)
841 if (val_key) {
842 if (val_key->name) free(val_key->name);
843 if (val_key->data_blk) free(val_key->data_blk);
844 free(val_key);
846 return 1;
849 int nt_delete_val_list(VAL_LIST *vl)
851 int i;
853 if (vl) {
854 for (i=0; i<vl->val_count; i++)
855 nt_delete_val_key(vl->vals[i]);
856 free(vl);
858 return 1;
861 int nt_delete_reg_key(REG_KEY *key, int delete_name);
862 int nt_delete_key_list(KEY_LIST *key_list, int delete_name)
864 int i;
866 if (key_list) {
867 for (i=0; i<key_list->key_count; i++)
868 nt_delete_reg_key(key_list->keys[i], False);
869 free(key_list);
871 return 1;
875 * Find the key, and if it exists, delete it ...
877 int nt_delete_key_by_name(REGF *regf, char *name)
879 REG_KEY *key;
881 if (!name || !*name) return 0;
883 key = nt_find_key_by_name(regf->root, name);
885 if (key) {
886 if (key == regf->root) regf->root = NULL;
887 return nt_delete_reg_key(key, True);
890 return 0;
894 int nt_delete_sid(DOM_SID *sid)
897 if (sid) free(sid);
898 return 1;
902 int nt_delete_ace(ACE *ace)
905 if (ace) {
906 nt_delete_sid(ace->trustee);
907 free(ace);
909 return 1;
913 int nt_delete_acl(ACL *acl)
916 if (acl) {
917 int i;
919 for (i=0; i<acl->num_aces; i++)
920 nt_delete_ace(acl->aces[i]);
922 free(acl);
924 return 1;
927 int nt_delete_sec_desc(SEC_DESC *sec_desc)
930 if (sec_desc) {
932 nt_delete_sid(sec_desc->owner);
933 nt_delete_sid(sec_desc->group);
934 nt_delete_acl(sec_desc->sacl);
935 nt_delete_acl(sec_desc->dacl);
936 free(sec_desc);
939 return 1;
942 int nt_delete_key_sec_desc(KEY_SEC_DESC *key_sec_desc)
945 if (key_sec_desc) {
946 key_sec_desc->ref_cnt--;
947 if (key_sec_desc->ref_cnt<=0) {
949 * There should always be a next and prev, even if they point to us
951 key_sec_desc->next->prev = key_sec_desc->prev;
952 key_sec_desc->prev->next = key_sec_desc->next;
953 nt_delete_sec_desc(key_sec_desc->sec_desc);
956 return 1;
959 int nt_delete_reg_key(REG_KEY *key, int delete_name)
962 if (key) {
963 if (key->name) free(key->name);
964 if (key->class_name) free(key->class_name);
967 * We will delete the owner if we are not the root and told to ...
970 if (key->owner && key->owner->sub_keys && delete_name) {
971 REG_KEY *own;
972 KEY_LIST *kl;
973 int i;
974 /* Find our owner, look in keylist for us and shuffle up */
975 /* Perhaps should be a function */
977 own = key->owner;
978 kl = own->sub_keys;
980 for (i=0; i < kl->key_count && kl->keys[i] != key ; i++) {
981 /* Just find the entry ... */
984 if (i == kl->key_count) {
985 fprintf(stderr, "Bad data structure. Key not found in key list of owner\n");
987 else {
988 int j;
991 * Shuffle up. Works for the last one also
993 for (j = i + 1; j < kl->key_count; j++) {
994 kl->keys[j - 1] = kl->keys[j];
997 kl->key_count--;
1001 if (key->sub_keys) nt_delete_key_list(key->sub_keys, False);
1002 if (key->values) nt_delete_val_list(key->values);
1003 if (key->security) nt_delete_key_sec_desc(key->security);
1004 free(key);
1006 return 1;
1010 * Convert a string to a value ...
1011 * FIXME: Error handling and convert this at command parse time ...
1013 void *str_to_val(int type, char *val, int *len)
1015 unsigned int *dwordp = NULL;
1017 if (!len || !val) return NULL;
1019 switch (type) {
1020 case REG_TYPE_REGSZ:
1021 *len = strlen(val);
1022 return (void *)val;
1024 case REG_TYPE_DWORD:
1025 dwordp = (unsigned int *)malloc(sizeof(unsigned int));
1026 if (!dwordp) return NULL;
1027 /* Allow for ddddd and 0xhhhhh and 0ooooo */
1028 if (strncmp(val, "0x", 2) == 0 || strncmp(val, "0X", 2) == 0) {
1029 sscanf(&val[2], "%X", dwordp);
1031 else if (*val == '0') {
1032 sscanf(&val[1], "%o", dwordp);
1034 else {
1035 sscanf(val, "%d", dwordp);
1037 *len = sizeof(unsigned int);
1038 return (void *)dwordp;
1040 /* FIXME: Implement more of these */
1042 default:
1043 return NULL;
1046 return NULL;
1050 * Add a value to the key specified ... We have to parse the value some more
1051 * based on the type to get it in the correct internal form
1052 * An empty name will be converted to "<No Name>" before here
1053 * Hmmm, maybe not. has_name is for that
1055 VAL_KEY *nt_add_reg_value(REG_KEY *key, char *name, int type, char *value)
1057 int i;
1058 VAL_KEY *tmp = NULL;
1060 if (!key || !key->values || !name || !*name) return NULL;
1062 assert(type != REG_TYPE_DELETE); /* We never process deletes here */
1064 for (i = 0; i < key->values->val_count; i++) {
1065 if ((!key->values->vals[i]->has_name && !*name) ||
1066 (key->values->vals[i]->has_name &&
1067 strcmp(name, key->values->vals[i]->name) == 0)){ /* Change the value */
1068 free(key->values->vals[i]->data_blk);
1069 key->values->vals[i]->data_blk = str_to_val(type, value, &
1070 key->values->vals[i]->data_len);
1071 return key->values->vals[i];
1076 * If we get here, the name was not found, so insert it
1079 tmp = (VAL_KEY *)malloc(sizeof(VAL_KEY));
1080 if (!tmp) goto error;
1082 bzero(tmp, sizeof(VAL_KEY));
1083 tmp->name = strdup(name);
1084 tmp->has_name = True;
1085 if (!tmp->name) goto error;
1086 tmp->data_type = type;
1087 tmp->data_blk = str_to_val(type, value, &tmp->data_len);
1089 /* Now, add to val list */
1091 if (key->values->val_count >= key->values->max_vals) {
1093 * Allocate some more space
1096 if ((key->values = (VAL_LIST *)realloc(key->values, sizeof(VAL_LIST) +
1097 key->values->val_count - 1 +
1098 REG_KEY_LIST_SIZE))) {
1099 key->values->max_vals += REG_KEY_LIST_SIZE;
1101 else goto error;
1104 i = key->values->val_count;
1105 key->values->val_count++;
1106 key->values->vals[i] = tmp;
1107 return tmp;
1109 error:
1110 if (tmp) nt_delete_val_key(tmp);
1111 return NULL;
1115 * Delete a value. We return the value and let the caller deal with it.
1117 VAL_KEY *nt_delete_reg_value(REG_KEY *key, char *name)
1119 int i, j;
1121 if (!key || !key->values || !name || !*name) return NULL;
1123 /* FIXME: Allow empty value name */
1124 for (i = 0; i< key->values->val_count; i++) {
1125 if ((!key->values->vals[i]->has_name && !*name) ||
1126 (key->values->vals[i]->has_name &&
1127 strcmp(name, key->values->vals[i]->name) == 0)) {
1128 VAL_KEY *val;
1130 val = key->values->vals[i];
1132 /* Shuffle down */
1133 for (j = i + 1; j < key->values->val_count; j++)
1134 key->values->vals[j - 1] = key->values->vals[j];
1136 key->values->val_count--;
1138 return val;
1141 return NULL;
1145 * Add a key to the tree ... We walk down the components matching until
1146 * we don't find any. There must be a match on the first component ...
1147 * We return the key structure for the final component as that is
1148 * often where we want to add values ...
1152 * Create a 1 component key name and set its parent to parent
1154 REG_KEY *nt_create_reg_key1(char *name, REG_KEY *parent)
1156 REG_KEY *tmp;
1158 if (!name || !*name) return NULL; /* A key's name cannot be empty */
1160 /* There should not be more than one component */
1161 if (strchr(name, '\\')) return NULL;
1163 if (!(tmp = (REG_KEY *)malloc(sizeof(REG_KEY)))) return NULL;
1165 bzero(tmp, sizeof(REG_KEY));
1167 if (!(tmp->name = strdup(name))) goto error;
1169 error:
1170 if (tmp) free(tmp);
1171 return NULL;
1175 * Convert a string of the form S-1-5-x[-y-z-r] to a SID
1177 int string_to_sid(DOM_SID **sid, const char *sid_str)
1179 int i = 0, auth;
1180 const char *lstr;
1182 *sid = (DOM_SID *)malloc(sizeof(DOM_SID));
1183 if (!*sid) return 0;
1185 bzero(*sid, sizeof(DOM_SID));
1187 if (strncmp(sid_str, "S-1-5", 5)) {
1188 fprintf(stderr, "Does not conform to S-1-5...: %s\n", sid_str);
1189 return 0;
1192 /* We only allow strings of form S-1-5... */
1194 (*sid)->ver = 1;
1195 (*sid)->auth[5] = 5;
1197 lstr = sid_str + 5;
1199 while (1) {
1200 if (!lstr || !lstr[0] || sscanf(lstr, "-%u", &auth) == 0) {
1201 if (i < 1) {
1202 fprintf(stderr, "Not of form -d-d...: %s, %u\n", lstr, i);
1203 return 0;
1205 (*sid)->auths=i;
1206 return 1;
1209 (*sid)->sub_auths[i] = auth;
1210 i++;
1211 lstr = strchr(lstr + 1, '-');
1214 /*return 1; */ /* Not Reached ... */
1218 * Create an ACE
1220 ACE *nt_create_ace(int type, int flags, unsigned int perms, const char *sid)
1222 ACE *ace;
1224 ace = (ACE *)malloc(sizeof(ACE));
1225 if (!ace) goto error;
1226 ace->type = type;
1227 ace->flags = flags;
1228 ace->perms = perms;
1229 if (!string_to_sid(&ace->trustee, sid))
1230 goto error;
1231 return ace;
1233 error:
1234 if (ace) nt_delete_ace(ace);
1235 return NULL;
1239 * Create a default ACL
1241 ACL *nt_create_default_acl(REGF *regf)
1243 ACL *acl;
1245 acl = (ACL *)malloc(sizeof(ACL) + 7*sizeof(ACE *));
1246 if (!acl) goto error;
1248 acl->rev = 2;
1249 acl->refcnt = 1;
1250 acl->num_aces = 8;
1252 acl->aces[0] = nt_create_ace(0x00, 0x0, 0xF003F, regf->owner_sid_str);
1253 if (!acl->aces[0]) goto error;
1254 acl->aces[1] = nt_create_ace(0x00, 0x0, 0xF003F, "S-1-5-18");
1255 if (!acl->aces[1]) goto error;
1256 acl->aces[2] = nt_create_ace(0x00, 0x0, 0xF003F, "S-1-5-32-544");
1257 if (!acl->aces[2]) goto error;
1258 acl->aces[3] = nt_create_ace(0x00, 0x0, 0x20019, "S-1-5-12");
1259 if (!acl->aces[3]) goto error;
1260 acl->aces[4] = nt_create_ace(0x00, 0x0B, 0x10000000, regf->owner_sid_str);
1261 if (!acl->aces[4]) goto error;
1262 acl->aces[5] = nt_create_ace(0x00, 0x0B, 0x10000000, "S-1-5-18");
1263 if (!acl->aces[5]) goto error;
1264 acl->aces[6] = nt_create_ace(0x00, 0x0B, 0x10000000, "S-1-5-32-544");
1265 if (!acl->aces[6]) goto error;
1266 acl->aces[7] = nt_create_ace(0x00, 0x0B, 0x80000000, "S-1-5-12");
1267 if (!acl->aces[7]) goto error;
1268 return acl;
1270 error:
1271 if (acl) nt_delete_acl(acl);
1272 return NULL;
1276 * Create a default security descriptor. We pull in things from env
1277 * if need be
1279 SEC_DESC *nt_create_def_sec_desc(REGF *regf)
1281 SEC_DESC *tmp;
1283 tmp = (SEC_DESC *)malloc(sizeof(SEC_DESC));
1284 if (!tmp) return NULL;
1286 tmp->rev = 1;
1287 tmp->type = 0x8004;
1288 if (!string_to_sid(&tmp->owner, "S-1-5-32-544")) goto error;
1289 if (!string_to_sid(&tmp->group, "S-1-5-18")) goto error;
1290 tmp->sacl = NULL;
1291 tmp->dacl = nt_create_default_acl(regf);
1293 return tmp;
1295 error:
1296 if (tmp) nt_delete_sec_desc(tmp);
1297 return NULL;
1301 * We will implement inheritence that is based on what the parent's SEC_DESC
1302 * says, but the Owner and Group SIDs can be overwridden from the command line
1303 * and additional ACEs can be applied from the command line etc.
1305 KEY_SEC_DESC *nt_inherit_security(REG_KEY *key)
1308 if (!key) return NULL;
1309 return key->security;
1313 * Create an initial security descriptor and init other structures, if needed
1314 * We assume that the initial security stuff is empty ...
1316 KEY_SEC_DESC *nt_create_init_sec(REGF *regf)
1318 KEY_SEC_DESC *tsec = NULL;
1320 tsec = (KEY_SEC_DESC *)malloc(sizeof(KEY_SEC_DESC));
1321 if (!tsec) return NULL;
1323 tsec->ref_cnt = 1;
1324 tsec->state = SEC_DESC_NBK;
1325 tsec->offset = 0;
1327 tsec->sec_desc = regf->def_sec_desc;
1329 return tsec;
1333 * Add a sub-key
1335 REG_KEY *nt_add_reg_key_list(REGF *regf, REG_KEY *key, char * name, int create)
1337 int i;
1338 REG_KEY *ret = NULL, *tmp = NULL;
1339 KEY_LIST *list;
1340 char *lname, *c1, *c2;
1342 if (!key || !name || !*name) return NULL;
1344 list = key->sub_keys;
1345 if (!list) { /* Create an empty list */
1347 list = (KEY_LIST *)malloc(sizeof(KEY_LIST) + (REG_KEY_LIST_SIZE - 1) * sizeof(REG_KEY *));
1348 list->key_count = 0;
1349 list->max_keys = REG_KEY_LIST_SIZE;
1353 lname = strdup(name);
1354 if (!lname) return NULL;
1356 c1 = lname;
1357 c2 = strchr(c1, '\\');
1358 if (c2) { /* Split here ... */
1359 *c2 = 0;
1360 c2++;
1363 for (i = 0; i < list->key_count; i++) {
1364 if (strcmp(list->keys[i]->name, c1) == 0) {
1365 ret = nt_add_reg_key_list(regf, list->keys[i], c2, create);
1366 free(lname);
1367 return ret;
1372 * If we reach here we could not find the the first component
1373 * so create it ...
1376 if (list->key_count < list->max_keys){
1377 list->key_count++;
1379 else { /* Create more space in the list ... */
1380 if (!(list = (KEY_LIST *)realloc(list, sizeof(KEY_LIST) +
1381 (list->max_keys + REG_KEY_LIST_SIZE - 1)
1382 * sizeof(REG_KEY *))))
1383 goto error;
1385 list->max_keys += REG_KEY_LIST_SIZE;
1386 list->key_count++;
1390 * add the new key at the new slot
1391 * FIXME: Sort the list someday
1395 * We want to create the key, and then do the rest
1398 tmp = (REG_KEY *)malloc(sizeof(REG_KEY));
1400 bzero(tmp, sizeof(REG_KEY));
1402 tmp->name = strdup(c1);
1403 if (!tmp->name) goto error;
1404 tmp->owner = key;
1405 tmp->type = REG_SUB_KEY;
1407 * Next, pull security from the parent, but override with
1408 * anything passed in on the command line
1410 tmp->security = nt_inherit_security(key);
1412 list->keys[list->key_count - 1] = tmp;
1414 if (c2) {
1415 ret = nt_add_reg_key_list(regf, key, c2, True);
1418 if (lname) free(lname);
1420 return ret;
1422 error:
1423 if (tmp) free(tmp);
1424 if (lname) free(lname);
1425 return NULL;
1429 * This routine only adds a key from the root down.
1430 * It calls helper functions to handle sub-key lists and sub-keys
1432 REG_KEY *nt_add_reg_key(REGF *regf, char *name, int create)
1434 char *lname = NULL, *c1, *c2;
1435 REG_KEY * tmp = NULL;
1438 * Look until we hit the first component that does not exist, and
1439 * then add from there. However, if the first component does not
1440 * match and the path we are given is the root, then it must match
1442 if (!regf || !name || !*name) return NULL;
1444 lname = strdup(name);
1445 if (!lname) return NULL;
1447 c1 = lname;
1448 c2 = strchr(c1, '\\');
1449 if (c2) { /* Split here ... */
1450 *c2 = 0;
1451 c2++;
1455 * If the root does not exist, create it and make it equal to the
1456 * first component ...
1459 if (!regf->root) {
1461 tmp = (REG_KEY *)malloc(sizeof(REG_KEY));
1462 if (!tmp) goto error;
1463 bzero(tmp, sizeof(REG_KEY));
1464 tmp->name = strdup(c1);
1465 if (!tmp->name) goto error;
1466 tmp->security = nt_create_init_sec(regf);
1467 if (!tmp->security) goto error;
1468 regf->root = tmp;
1471 else {
1473 * If we don't match, then we have to return error ...
1474 * If we do match on this component, check the next one in the
1475 * list, and if not found, add it ... short circuit, add all the
1476 * way down
1479 if (strcmp(c1, regf->root->name) != 0)
1480 goto error;
1483 tmp = nt_add_reg_key_list(regf, regf->root, c2, True);
1484 free(lname);
1485 return tmp;
1487 error:
1488 if (tmp) free(tmp);
1489 if (lname) free(lname);
1490 return NULL;
1494 * Load and unload a registry file.
1496 * Load, loads it into memory as a tree, while unload sealizes/flattens it
1500 * Get the starting record for NT Registry file
1504 * Where we keep all the regf stuff for one registry.
1505 * This is the structure that we use to tie the in memory tree etc
1506 * together. By keeping separate structs, we can operate on different
1507 * registries at the same time.
1508 * Currently, the SK_MAP is an array of mapping structure.
1509 * Since we only need this on input and output, we fill in the structure
1510 * as we go on input. On output, we know how many SK items we have, so
1511 * we can allocate the structure as we need to.
1512 * If you add stuff here that is dynamically allocated, add the
1513 * appropriate free statements below.
1516 #define REGF_REGTYPE_NONE 0
1517 #define REGF_REGTYPE_NT 1
1518 #define REGF_REGTYPE_W9X 2
1520 #define TTTONTTIME(r, t1, t2) (r)->last_mod_time.low = (t1); \
1521 (r)->last_mod_time.high = (t2);
1523 #define REGF_HDR_BLKSIZ 0x1000
1525 #define OFF(f) ((f) + REGF_HDR_BLKSIZ + 4)
1526 #define LOCN(base, f) ((base) + OFF(f))
1528 const VAL_STR reg_type_names[] = {
1529 { REG_TYPE_REGSZ, "REG_SZ" },
1530 { REG_TYPE_EXPANDSZ, "REG_EXPAND_SZ" },
1531 { REG_TYPE_BIN, "REG_BIN" },
1532 { REG_TYPE_DWORD, "REG_DWORD" },
1533 { REG_TYPE_MULTISZ, "REG_MULTI_SZ" },
1534 { 0, NULL },
1537 const char *val_to_str(unsigned int val, const VAL_STR *val_array)
1539 int i = 0;
1541 if (!val_array) return NULL;
1543 while (val_array[i].val && val_array[i].str) {
1545 if (val_array[i].val == val) return val_array[i].str;
1546 i++;
1550 return NULL;
1555 * Convert from UniCode to Ascii ... Does not take into account other lang
1556 * Restrict by ascii_max if > 0
1558 int uni_to_ascii(unsigned char *uni, unsigned char *ascii, int ascii_max,
1559 int uni_max)
1561 int i = 0;
1563 while (i < ascii_max && !(!uni[i*2] && !uni[i*2+1])) {
1564 if (uni_max > 0 && (i*2) >= uni_max) break;
1565 ascii[i] = uni[i*2];
1566 i++;
1570 ascii[i] = '\0';
1572 return i;
1576 * Convert a data value to a string for display
1578 int data_to_ascii(unsigned char *datap, int len, int type, char *ascii, int ascii_max)
1580 unsigned char *asciip;
1581 int i;
1583 switch (type) {
1584 case REG_TYPE_REGSZ:
1585 if (verbose) fprintf(stderr, "Len: %d\n", len);
1586 /* FIXME. This has to be fixed. It has to be UNICODE */
1587 return uni_to_ascii(datap, ascii, len, ascii_max);
1588 break; /*NOTREACHED*/
1590 case REG_TYPE_EXPANDSZ:
1591 return uni_to_ascii(datap, ascii, len, ascii_max);
1592 break;
1594 case REG_TYPE_BIN:
1595 asciip = ascii;
1596 for (i=0; (i<len)&&(i+1)*3<ascii_max; i++) {
1597 int str_rem = ascii_max - ((int)asciip - (int)ascii);
1598 asciip += snprintf(asciip, str_rem, "%02x", *(unsigned char *)(datap+i));
1599 if (i < len && str_rem > 0)
1600 *asciip = ' '; asciip++;
1602 *asciip = '\0';
1603 return ((int)asciip - (int)ascii);
1604 break;
1606 case REG_TYPE_DWORD:
1607 if (*(int *)datap == 0)
1608 return snprintf(ascii, ascii_max, "0");
1609 else
1610 return snprintf(ascii, ascii_max, "0x%x", *(int *)datap);
1611 break;
1613 case REG_TYPE_MULTISZ:
1615 break;
1617 default:
1618 return 0;
1619 break;
1622 return len;
1626 REG_KEY *nt_get_key_tree(REGF *regf, NK_HDR *nk_hdr, int size, REG_KEY *parent);
1628 int nt_set_regf_input_file(REGF *regf, char *filename)
1630 return ((regf->regfile_name = strdup(filename)) != NULL);
1633 int nt_set_regf_output_file(REGF *regf, char *filename)
1635 return ((regf->outfile_name = strdup(filename)) != NULL);
1638 /* Create a regf structure and init it */
1640 REGF *nt_create_regf(void)
1642 REGF *tmp = (REGF *)malloc(sizeof(REGF));
1643 if (!tmp) return tmp;
1644 bzero(tmp, sizeof(REGF));
1645 tmp->owner_sid_str = def_owner_sid_str;
1646 return tmp;
1649 /* Free all the bits and pieces ... Assumes regf was malloc'd */
1650 /* If you add stuff to REGF, add the relevant free bits here */
1651 int nt_free_regf(REGF *regf)
1653 if (!regf) return 0;
1655 if (regf->regfile_name) free(regf->regfile_name);
1656 if (regf->outfile_name) free(regf->outfile_name);
1658 nt_delete_reg_key(regf->root, False); /* Free the tree */
1659 free(regf->sk_map);
1660 regf->sk_count = regf->sk_map_size = 0;
1662 free(regf);
1664 return 1;
1667 /* Get the header of the registry. Return a pointer to the structure
1668 * If the mmap'd area has not been allocated, then mmap the input file
1670 REGF_HDR *nt_get_regf_hdr(REGF *regf)
1672 if (!regf)
1673 return NULL; /* What about errors */
1675 if (!regf->regfile_name)
1676 return NULL; /* What about errors */
1678 if (!regf->base) { /* Try to mmap etc the file */
1680 if ((regf->fd = open(regf->regfile_name, O_RDONLY, 0000)) <0) {
1681 return NULL; /* What about errors? */
1684 if (fstat(regf->fd, &regf->sbuf) < 0) {
1685 return NULL;
1688 regf->base = mmap(0, regf->sbuf.st_size, PROT_READ, MAP_SHARED, regf->fd, 0);
1690 if ((int)regf->base == 1) {
1691 fprintf(stderr, "Could not mmap file: %s, %s\n", regf->regfile_name,
1692 strerror(errno));
1693 return NULL;
1698 * At this point, regf->base != NULL, and we should be able to read the
1699 * header
1702 assert(regf->base != NULL);
1704 return (REGF_HDR *)regf->base;
1708 * Validate a regf header
1709 * For now, do nothing, but we should check the checksum
1711 int valid_regf_hdr(REGF_HDR *regf_hdr)
1713 if (!regf_hdr) return 0;
1715 return 1;
1719 * Process an SK header ...
1720 * Every time we see a new one, add it to the map. Otherwise, just look it up.
1721 * We will do a simple linear search for the moment, since many KEYs have the
1722 * same security descriptor.
1723 * We allocate the map in increments of 10 entries.
1727 * Create a new entry in the map, and increase the size of the map if needed
1730 SK_MAP *alloc_sk_map_entry(REGF *regf, KEY_SEC_DESC *tmp, int sk_off)
1732 if (!regf->sk_map) { /* Allocate a block of 10 */
1733 regf->sk_map = (SK_MAP *)malloc(sizeof(SK_MAP) * 10);
1734 if (!regf->sk_map) {
1735 free(tmp);
1736 return NULL;
1738 regf->sk_map_size = 10;
1739 regf->sk_count = 1;
1740 (regf->sk_map)[0].sk_off = sk_off;
1741 (regf->sk_map)[0].key_sec_desc = tmp;
1743 else { /* Simply allocate a new slot, unless we have to expand the list */
1744 int ndx = regf->sk_count;
1745 if (regf->sk_count >= regf->sk_map_size) {
1746 regf->sk_map = (SK_MAP *)realloc(regf->sk_map,
1747 (regf->sk_map_size + 10)*sizeof(SK_MAP));
1748 if (!regf->sk_map) {
1749 free(tmp);
1750 return NULL;
1753 * ndx already points at the first entry of the new block
1755 regf->sk_map_size += 10;
1757 (regf->sk_map)[ndx].sk_off = sk_off;
1758 (regf->sk_map)[ndx].key_sec_desc = tmp;
1759 regf->sk_count++;
1761 return regf->sk_map;
1765 * Search for a KEY_SEC_DESC in the sk_map, but don't create one if not
1766 * found
1769 KEY_SEC_DESC *lookup_sec_key(SK_MAP *sk_map, int count, int sk_off)
1771 int i;
1773 if (!sk_map) return NULL;
1775 for (i = 0; i < count; i++) {
1777 if (sk_map[i].sk_off == sk_off)
1778 return sk_map[i].key_sec_desc;
1782 return NULL;
1787 * Allocate a KEY_SEC_DESC if we can't find one in the map
1790 KEY_SEC_DESC *lookup_create_sec_key(REGF *regf, SK_MAP *sk_map, int sk_off)
1792 KEY_SEC_DESC *tmp = lookup_sec_key(regf->sk_map, regf->sk_count, sk_off);
1794 if (tmp) {
1795 return tmp;
1797 else { /* Allocate a new one */
1798 tmp = (KEY_SEC_DESC *)malloc(sizeof(KEY_SEC_DESC));
1799 if (!tmp) {
1800 return NULL;
1802 bzero(tmp, sizeof(KEY_SEC_DESC)); /* Neatly sets offset to 0 */
1803 tmp->state = SEC_DESC_RES;
1804 if (!alloc_sk_map_entry(regf, tmp, sk_off)) {
1805 return NULL;
1807 return tmp;
1812 * Allocate storage and duplicate a SID
1813 * We could allocate the SID to be only the size needed, but I am too lazy.
1815 DOM_SID *dup_sid(DOM_SID *sid)
1817 DOM_SID *tmp = (DOM_SID *)malloc(sizeof(DOM_SID));
1818 int i;
1820 if (!tmp) return NULL;
1821 tmp->ver = sid->ver;
1822 tmp->auths = sid->auths;
1823 for (i=0; i<6; i++) {
1824 tmp->auth[i] = sid->auth[i];
1826 for (i=0; i<tmp->auths&&i<MAXSUBAUTHS; i++) {
1827 tmp->sub_auths[i] = sid->sub_auths[i];
1829 return tmp;
1833 * Allocate space for an ACE and duplicate the registry encoded one passed in
1835 ACE *dup_ace(REG_ACE *ace)
1837 ACE *tmp = NULL;
1839 tmp = (ACE *)malloc(sizeof(ACE));
1841 if (!tmp) return NULL;
1843 tmp->type = CVAL(&ace->type);
1844 tmp->flags = CVAL(&ace->flags);
1845 tmp->perms = IVAL(&ace->perms);
1846 tmp->trustee = dup_sid(&ace->trustee);
1847 return tmp;
1851 * Allocate space for an ACL and duplicate the registry encoded one passed in
1853 ACL *dup_acl(REG_ACL *acl)
1855 ACL *tmp = NULL;
1856 REG_ACE* ace;
1857 int i, num_aces;
1859 num_aces = IVAL(&acl->num_aces);
1861 tmp = (ACL *)malloc(sizeof(ACL) + (num_aces - 1)*sizeof(ACE *));
1862 if (!tmp) return NULL;
1864 tmp->num_aces = num_aces;
1865 tmp->refcnt = 1;
1866 tmp->rev = SVAL(&acl->rev);
1867 if (verbose) fprintf(stdout, "ACL: refcnt: %u, rev: %u\n", tmp->refcnt,
1868 tmp->rev);
1869 ace = (REG_ACE *)&acl->aces;
1870 for (i=0; i<num_aces; i++) {
1871 tmp->aces[i] = dup_ace(ace);
1872 ace = (REG_ACE *)((char *)ace + SVAL(&ace->length));
1873 /* XXX: FIXME, should handle malloc errors */
1876 return tmp;
1879 SEC_DESC *process_sec_desc(REGF *regf, REG_SEC_DESC *sec_desc)
1881 SEC_DESC *tmp = NULL;
1883 tmp = (SEC_DESC *)malloc(sizeof(SEC_DESC));
1885 if (!tmp) {
1886 return NULL;
1889 tmp->rev = SVAL(&sec_desc->rev);
1890 tmp->type = SVAL(&sec_desc->type);
1891 if (verbose) fprintf(stdout, "SEC_DESC Rev: %0X, Type: %0X\n",
1892 tmp->rev, tmp->type);
1893 if (verbose) fprintf(stdout, "SEC_DESC Owner Off: %0X\n",
1894 IVAL(&sec_desc->owner_off));
1895 if (verbose) fprintf(stdout, "SEC_DESC Group Off: %0X\n",
1896 IVAL(&sec_desc->group_off));
1897 if (verbose) fprintf(stdout, "SEC_DESC DACL Off: %0X\n",
1898 IVAL(&sec_desc->dacl_off));
1899 tmp->owner = dup_sid((DOM_SID *)((char *)sec_desc + IVAL(&sec_desc->owner_off)));
1900 if (!tmp->owner) {
1901 free(tmp);
1902 return NULL;
1904 tmp->group = dup_sid((DOM_SID *)((char *)sec_desc + IVAL(&sec_desc->group_off)));
1905 if (!tmp->group) {
1906 free(tmp);
1907 return NULL;
1910 /* Now pick up the SACL and DACL */
1912 if (sec_desc->sacl_off)
1913 tmp->sacl = dup_acl((REG_ACL *)((char *)sec_desc + IVAL(&sec_desc->sacl_off)));
1914 else
1915 tmp->sacl = NULL;
1917 if (sec_desc->dacl_off)
1918 tmp->dacl = dup_acl((REG_ACL *)((char *)sec_desc + IVAL(&sec_desc->dacl_off)));
1919 else
1920 tmp->dacl = NULL;
1922 return tmp;
1925 KEY_SEC_DESC *process_sk(REGF *regf, SK_HDR *sk_hdr, int sk_off, int size)
1927 KEY_SEC_DESC *tmp = NULL;
1928 int sk_next_off, sk_prev_off, sk_size;
1929 REG_SEC_DESC *sec_desc;
1931 if (!sk_hdr) return NULL;
1933 if (SVAL(&sk_hdr->SK_ID) != REG_SK_ID) {
1934 fprintf(stderr, "Unrecognized SK Header ID: %08X, %s\n", (int)sk_hdr,
1935 regf->regfile_name);
1936 return NULL;
1939 if (-size < (sk_size = IVAL(&sk_hdr->rec_size))) {
1940 fprintf(stderr, "Incorrect SK record size: %d vs %d. %s\n",
1941 -size, sk_size, regf->regfile_name);
1942 return NULL;
1946 * Now, we need to look up the SK Record in the map, and return it
1947 * Since the map contains the SK_OFF mapped to KEY_SEC_DESC, we can
1948 * use that
1951 if (regf->sk_map &&
1952 ((tmp = lookup_sec_key(regf->sk_map, regf->sk_count, sk_off)) != NULL)
1953 && (tmp->state == SEC_DESC_OCU)) {
1954 tmp->ref_cnt++;
1955 return tmp;
1958 /* Here, we have an item in the map that has been reserved, or tmp==NULL. */
1960 assert(tmp == NULL || (tmp && tmp->state != SEC_DESC_NON));
1963 * Now, allocate a KEY_SEC_DESC, and parse the structure here, and add the
1964 * new KEY_SEC_DESC to the mapping structure, since the offset supplied is
1965 * the actual offset of structure. The same offset will be used by
1966 * all future references to this structure
1967 * We could put all this unpleasantness in a function.
1970 if (!tmp) {
1971 tmp = (KEY_SEC_DESC *)malloc(sizeof(KEY_SEC_DESC));
1972 if (!tmp) return NULL;
1973 bzero(tmp, sizeof(KEY_SEC_DESC));
1976 * Allocate an entry in the SK_MAP ...
1977 * We don't need to free tmp, because that is done for us if the
1978 * sm_map entry can't be expanded when we need more space in the map.
1981 if (!alloc_sk_map_entry(regf, tmp, sk_off)) {
1982 return NULL;
1986 tmp->ref_cnt++;
1987 tmp->state = SEC_DESC_OCU;
1990 * Now, process the actual sec desc and plug the values in
1993 sec_desc = (REG_SEC_DESC *)&sk_hdr->sec_desc[0];
1994 tmp->sec_desc = process_sec_desc(regf, sec_desc);
1997 * Now forward and back links. Here we allocate an entry in the sk_map
1998 * if it does not exist, and mark it reserved
2001 sk_prev_off = IVAL(&sk_hdr->prev_off);
2002 tmp->prev = lookup_create_sec_key(regf, regf->sk_map, sk_prev_off);
2003 assert(tmp->prev != NULL);
2004 sk_next_off = IVAL(&sk_hdr->next_off);
2005 tmp->next = lookup_create_sec_key(regf, regf->sk_map, sk_next_off);
2006 assert(tmp->next != NULL);
2008 return tmp;
2012 * Process a VK header and return a value
2014 VAL_KEY *process_vk(REGF *regf, VK_HDR *vk_hdr, int size)
2016 char val_name[1024];
2017 int nam_len, dat_len, flag, dat_type, dat_off, vk_id;
2018 const char *val_type;
2019 VAL_KEY *tmp = NULL;
2021 if (!vk_hdr) return NULL;
2023 if ((vk_id = SVAL(&vk_hdr->VK_ID)) != REG_VK_ID) {
2024 fprintf(stderr, "Unrecognized VK header ID: %0X, block: %0X, %s\n",
2025 vk_id, (int)vk_hdr, regf->regfile_name);
2026 return NULL;
2029 nam_len = SVAL(&vk_hdr->nam_len);
2030 val_name[nam_len] = '\0';
2031 flag = SVAL(&vk_hdr->flag);
2032 dat_type = IVAL(&vk_hdr->dat_type);
2033 dat_len = IVAL(&vk_hdr->dat_len); /* If top bit, offset contains data */
2034 dat_off = IVAL(&vk_hdr->dat_off);
2036 tmp = (VAL_KEY *)malloc(sizeof(VAL_KEY));
2037 if (!tmp) {
2038 goto error;
2040 bzero(tmp, sizeof(VAL_KEY));
2041 tmp->has_name = flag;
2042 tmp->data_type = dat_type;
2044 if (flag & 0x01) {
2045 strncpy(val_name, vk_hdr->dat_name, nam_len);
2046 tmp->name = strdup(val_name);
2047 if (!tmp->name) {
2048 goto error;
2051 else
2052 strncpy(val_name, "<No Name>", 10);
2055 * Allocate space and copy the data as a BLOB
2058 if (dat_len) {
2060 char *dtmp = (char *)malloc(dat_len&0x7FFFFFFF);
2062 if (!dtmp) {
2063 goto error;
2066 tmp->data_blk = dtmp;
2068 if ((dat_len&0x80000000) == 0) { /* The data is pointed to by the offset */
2069 char *dat_ptr = LOCN(regf->base, dat_off);
2070 bcopy(dat_ptr, dtmp, dat_len);
2072 else { /* The data is in the offset or type */
2074 * FIXME.
2075 * Some registry files seem to have wierd fields. If top bit is set,
2076 * but len is 0, the type seems to be the value ...
2077 * Not sure how to handle this last type for the moment ...
2079 dat_len = dat_len & 0x7FFFFFFF;
2080 bcopy(&dat_off, dtmp, dat_len);
2083 tmp->data_len = dat_len;
2086 val_type = val_to_str(dat_type, reg_type_names);
2089 * We need to save the data area as well
2092 if (verbose) fprintf(stdout, " %s : %s : \n", val_name, val_type);
2094 return tmp;
2096 error:
2097 if (tmp) nt_delete_val_key(tmp);
2098 return NULL;
2103 * Process a VL Header and return a list of values
2105 VAL_LIST *process_vl(REGF *regf, VL_TYPE vl, int count, int size)
2107 int i, vk_off;
2108 VK_HDR *vk_hdr;
2109 VAL_LIST *tmp = NULL;
2111 if (!vl) return NULL;
2113 if (-size < (count+1)*sizeof(int)){
2114 fprintf(stderr, "Error in VL header format. Size less than space required. %d\n", -size);
2115 return NULL;
2118 tmp = (VAL_LIST *)malloc(sizeof(VAL_LIST) + (count - 1) * sizeof(VAL_KEY *));
2119 if (!tmp) {
2120 goto error;
2123 for (i=0; i<count; i++) {
2124 vk_off = IVAL(&vl[i]);
2125 vk_hdr = (VK_HDR *)LOCN(regf->base, vk_off);
2126 tmp->vals[i] = process_vk(regf, vk_hdr, BLK_SIZE(vk_hdr));
2127 if (!tmp->vals[i]){
2128 goto error;
2132 tmp->val_count = count;
2133 tmp->max_vals = count;
2135 return tmp;
2137 error:
2138 /* XXX: FIXME, free the partially allocated structure */
2139 return NULL;
2143 * Process an LF Header and return a list of sub-keys
2145 KEY_LIST *process_lf(REGF *regf, LF_HDR *lf_hdr, int size, REG_KEY *parent)
2147 int count, i, nk_off;
2148 unsigned int lf_id;
2149 KEY_LIST *tmp;
2151 if (!lf_hdr) return NULL;
2153 if ((lf_id = SVAL(&lf_hdr->LF_ID)) != REG_LF_ID) {
2154 fprintf(stderr, "Unrecognized LF Header format: %0X, Block: %0X, %s.\n",
2155 lf_id, (int)lf_hdr, regf->regfile_name);
2156 return NULL;
2159 assert(size < 0);
2161 count = SVAL(&lf_hdr->key_count);
2162 if (verbose) fprintf(stdout, "Key Count: %u\n", count);
2163 if (count <= 0) return NULL;
2165 /* Now, we should allocate a KEY_LIST struct and fill it in ... */
2167 tmp = (KEY_LIST *)malloc(sizeof(KEY_LIST) + (count - 1) * sizeof(REG_KEY *));
2168 if (!tmp) {
2169 goto error;
2172 tmp->key_count = count;
2173 tmp->max_keys = count;
2175 for (i=0; i<count; i++) {
2176 NK_HDR *nk_hdr;
2178 nk_off = IVAL(&lf_hdr->hr[i].nk_off);
2179 if (verbose) fprintf(stdout, "NK Offset: %0X\n", nk_off);
2180 nk_hdr = (NK_HDR *)LOCN(regf->base, nk_off);
2181 tmp->keys[i] = nt_get_key_tree(regf, nk_hdr, BLK_SIZE(nk_hdr), parent);
2182 if (!tmp->keys[i]) {
2183 goto error;
2187 return tmp;
2189 error:
2190 if (tmp) nt_delete_key_list(tmp, False);
2191 return NULL;
2195 * This routine is passed an NK_HDR pointer and retrieves the entire tree
2196 * from there down. It returns a REG_KEY *.
2198 REG_KEY *nt_get_key_tree(REGF *regf, NK_HDR *nk_hdr, int size, REG_KEY *parent)
2200 REG_KEY *tmp = NULL, *own;
2201 int name_len, clsname_len, lf_off, val_off, val_count, sk_off, own_off;
2202 unsigned int nk_id;
2203 LF_HDR *lf_hdr;
2204 VL_TYPE *vl;
2205 SK_HDR *sk_hdr;
2206 char key_name[1024], cls_name[1024];
2208 if (!nk_hdr) return NULL;
2210 if ((nk_id = SVAL(&nk_hdr->NK_ID)) != REG_NK_ID) {
2211 fprintf(stderr, "Unrecognized NK Header format: %08X, Block: %0X. %s\n",
2212 nk_id, (int)nk_hdr, regf->regfile_name);
2213 return NULL;
2216 assert(size < 0);
2218 name_len = SVAL(&nk_hdr->nam_len);
2219 clsname_len = SVAL(&nk_hdr->clsnam_len);
2222 * The value of -size should be ge
2223 * (sizeof(NK_HDR) - 1 + name_len)
2224 * The -1 accounts for the fact that we included the first byte of
2225 * the name in the structure. clsname_len is the length of the thing
2226 * pointed to by clsnam_off
2229 if (-size < (sizeof(NK_HDR) - 1 + name_len)) {
2230 fprintf(stderr, "Incorrect NK_HDR size: %d, %0X\n", -size, (int)nk_hdr);
2231 fprintf(stderr, "Sizeof NK_HDR: %d, name_len %d, clsname_len %d\n",
2232 sizeof(NK_HDR), name_len, clsname_len);
2233 /*return NULL;*/
2236 if (verbose) fprintf(stdout, "NK HDR: Name len: %d, class name len: %d\n",
2237 name_len, clsname_len);
2239 /* Fish out the key name and process the LF list */
2241 assert(name_len < sizeof(key_name));
2243 /* Allocate the key struct now */
2244 tmp = (REG_KEY *)malloc(sizeof(REG_KEY));
2245 if (!tmp) return tmp;
2246 bzero(tmp, sizeof(REG_KEY));
2248 tmp->type = (SVAL(&nk_hdr->type)==0x2C?REG_ROOT_KEY:REG_SUB_KEY);
2250 strncpy(key_name, nk_hdr->key_nam, name_len);
2251 key_name[name_len] = '\0';
2253 if (verbose) fprintf(stdout, "Key name: %s\n", key_name);
2255 tmp->name = strdup(key_name);
2256 if (!tmp->name) {
2257 goto error;
2261 * Fish out the class name, it is in UNICODE, while the key name is
2262 * ASCII :-)
2265 if (clsname_len) { /* Just print in Ascii for now */
2266 char *clsnamep;
2267 int clsnam_off;
2269 clsnam_off = IVAL(&nk_hdr->clsnam_off);
2270 clsnamep = LOCN(regf->base, clsnam_off);
2271 if (verbose) fprintf(stdout, "Class Name Offset: %0X\n", clsnam_off);
2273 bzero(cls_name, clsname_len);
2274 uni_to_ascii(clsnamep, cls_name, sizeof(cls_name), clsname_len);
2277 * I am keeping class name as an ascii string for the moment.
2278 * That means it needs to be converted on output.
2279 * It will also piss off people who need Unicode/UTF-8 strings. Sorry.
2280 * XXX: FIXME
2283 tmp->class_name = strdup(cls_name);
2284 if (!tmp->class_name) {
2285 goto error;
2288 if (verbose) fprintf(stdout, " Class Name: %s\n", cls_name);
2293 * Process the owner offset ...
2296 own_off = IVAL(&nk_hdr->own_off);
2297 own = (REG_KEY *)LOCN(regf->base, own_off);
2298 if (verbose) fprintf(stdout, "Owner Offset: %0X\n", own_off);
2300 if (verbose) fprintf(stdout, " Owner locn: %0X, Our locn: %0X\n",
2301 (unsigned int)own, (unsigned int)nk_hdr);
2304 * We should verify that the owner field is correct ...
2305 * for now, we don't worry ...
2308 tmp->owner = parent;
2311 * If there are any values, process them here
2314 val_count = IVAL(&nk_hdr->val_cnt);
2315 if (verbose) fprintf(stdout, "Val Count: %d\n", val_count);
2316 if (val_count) {
2318 val_off = IVAL(&nk_hdr->val_off);
2319 vl = (VL_TYPE *)LOCN(regf->base, val_off);
2320 if (verbose) fprintf(stdout, "Val List Offset: %0X\n", val_off);
2322 tmp->values = process_vl(regf, *vl, val_count, BLK_SIZE(vl));
2323 if (!tmp->values) {
2324 goto error;
2330 * Also handle the SK header ...
2333 sk_off = IVAL(&nk_hdr->sk_off);
2334 sk_hdr = (SK_HDR *)LOCN(regf->base, sk_off);
2335 if (verbose) fprintf(stdout, "SK Offset: %0X\n", sk_off);
2337 if (sk_off != -1) {
2339 tmp->security = process_sk(regf, sk_hdr, sk_off, BLK_SIZE(sk_hdr));
2343 lf_off = IVAL(&nk_hdr->lf_off);
2344 if (verbose) fprintf(stdout, "SubKey list offset: %0X\n", lf_off);
2347 * No more subkeys if lf_off == -1
2350 if (lf_off != -1) {
2352 lf_hdr = (LF_HDR *)LOCN(regf->base, lf_off);
2354 tmp->sub_keys = process_lf(regf, lf_hdr, BLK_SIZE(lf_hdr), tmp);
2355 if (!tmp->sub_keys){
2356 goto error;
2361 return tmp;
2363 error:
2364 if (tmp) nt_delete_reg_key(tmp, False);
2365 return NULL;
2368 int nt_load_registry(REGF *regf)
2370 REGF_HDR *regf_hdr;
2371 unsigned int regf_id, hbin_id;
2372 HBIN_HDR *hbin_hdr;
2373 NK_HDR *first_key;
2375 /* Get the header */
2377 if ((regf_hdr = nt_get_regf_hdr(regf)) == NULL) {
2378 return -1;
2381 /* Now process that header and start to read the rest in */
2383 if ((regf_id = IVAL(&regf_hdr->REGF_ID)) != REG_REGF_ID) {
2384 fprintf(stderr, "Unrecognized NT registry header id: %0X, %s\n",
2385 regf_id, regf->regfile_name);
2386 return -1;
2390 * Validate the header ...
2392 if (!valid_regf_hdr(regf_hdr)) {
2393 fprintf(stderr, "Registry file header does not validate: %s\n",
2394 regf->regfile_name);
2395 return -1;
2398 /* Update the last mod date, and then go get the first NK record and on */
2400 TTTONTTIME(regf, IVAL(&regf_hdr->tim1), IVAL(&regf_hdr->tim2));
2403 * The hbin hdr seems to be just uninteresting garbage. Check that
2404 * it is there, but that is all.
2407 hbin_hdr = (HBIN_HDR *)(regf->base + REGF_HDR_BLKSIZ);
2409 if ((hbin_id = IVAL(&hbin_hdr->HBIN_ID)) != REG_HBIN_ID) {
2410 fprintf(stderr, "Unrecognized registry hbin hdr ID: %0X, %s\n",
2411 hbin_id, regf->regfile_name);
2412 return -1;
2416 * Get a pointer to the first key from the hreg_hdr
2419 if (verbose) fprintf(stdout, "First Key: %0X\n",
2420 IVAL(&regf_hdr->first_key));
2422 first_key = (NK_HDR *)LOCN(regf->base, IVAL(&regf_hdr->first_key));
2423 if (verbose) fprintf(stdout, "First Key Offset: %0X\n",
2424 IVAL(&regf_hdr->first_key));
2426 if (verbose) fprintf(stdout, "Data Block Size: %d\n",
2427 IVAL(&regf_hdr->dblk_size));
2429 if (verbose) fprintf(stdout, "Offset to next hbin block: %0X\n",
2430 IVAL(&hbin_hdr->off_to_next));
2432 if (verbose) fprintf(stdout, "HBIN block size: %0X\n",
2433 IVAL(&hbin_hdr->blk_size));
2436 * Now, get the registry tree by processing that NK recursively
2439 regf->root = nt_get_key_tree(regf, first_key, BLK_SIZE(first_key), NULL);
2441 assert(regf->root != NULL);
2444 * Unmap the registry file, as we might want to read in another
2445 * tree etc.
2448 if (regf->base) munmap(regf->base, regf->sbuf.st_size);
2449 regf->base = NULL;
2450 close(regf->fd); /* Ignore the error :-) */
2452 return 1;
2456 * Allocate a new hbin block, set up the header for the block etc
2458 HBIN_BLK *nt_create_hbin_blk(REGF *regf, int size)
2460 HBIN_BLK *tmp;
2461 HBIN_HDR *hdr;
2463 if (!regf || !size) return NULL;
2465 /* Round size up to multiple of REGF_HDR_BLKSIZ */
2467 size = (size + (REGF_HDR_BLKSIZ - 1)) & ~(REGF_HDR_BLKSIZ - 1);
2469 tmp = (HBIN_BLK *)malloc(sizeof(HBIN_BLK));
2470 bzero(tmp, sizeof(HBIN_BLK));
2472 tmp->data = malloc(size);
2473 if (!tmp->data) goto error;
2475 bzero(tmp->data, size); /* Make it pristine */
2477 tmp->size = size;
2478 tmp->file_offset = regf->blk_tail->file_offset + regf->blk_tail->size;
2480 tmp->free_space = size - (sizeof(HBIN_HDR) - sizeof(HBIN_SUB_HDR));
2481 tmp->fsp_off = size - tmp->free_space;
2484 * Now, build the header in the data block
2486 hdr = (HBIN_HDR *)tmp->data;
2487 hdr->HBIN_ID = REG_HBIN_ID;
2488 hdr->off_from_first = tmp->file_offset - REGF_HDR_BLKSIZ;
2489 hdr->off_to_next = tmp->size;
2490 hdr->blk_size = tmp->size;
2493 * Now link it in
2496 regf->blk_tail->next = tmp;
2497 regf->blk_tail = tmp;
2498 if (!regf->free_space) regf->free_space = tmp;
2500 return tmp;
2501 error:
2502 if (tmp) free(tmp);
2503 return NULL;
2507 * Allocate a unit of space ... and return a pointer as function param
2508 * and the block's offset as a side effect
2510 void *nt_alloc_regf_space(REGF *regf, int size, unsigned int *off)
2512 int tmp = 0;
2513 void *ret = NULL;
2514 HBIN_BLK *blk;
2516 if (!regf || !size || !off) return NULL;
2518 assert(regf->blk_head != NULL);
2521 * round up size to include header and then to 8-byte boundary
2523 size = (size + 4 + 7) & ~7;
2526 * Check if there is space, if none, grab a block
2528 if (!regf->free_space) {
2529 if (!nt_create_hbin_blk(regf, REGF_HDR_BLKSIZ))
2530 return NULL;
2534 * Now, chain down the list of blocks looking for free space
2537 for (blk = regf->free_space; blk != NULL; blk = blk->next) {
2538 if (blk->free_space <= size) {
2539 tmp = blk->file_offset + blk->fsp_off - REGF_HDR_BLKSIZ;
2540 ret = blk->data + blk->fsp_off;
2541 blk->free_space -= size;
2542 blk->fsp_off += size;
2544 /* Insert the header */
2545 ((HBIN_SUB_HDR *)ret)->dblocksize = -size;
2548 * Fix up the free space ptr
2549 * If it is NULL, we fix it up next time
2552 if (!blk->free_space)
2553 regf->free_space = blk->next;
2555 *off = tmp;
2556 return (((char *)ret)+4);/* The pointer needs to be to the data struct */
2561 * If we got here, we need to add another block, which might be
2562 * larger than one block -- deal with that later
2564 if (nt_create_hbin_blk(regf, REGF_HDR_BLKSIZ)) {
2565 blk = regf->free_space;
2566 tmp = blk->file_offset + blk->fsp_off - REGF_HDR_BLKSIZ;
2567 ret = blk->data + blk->fsp_off;
2568 blk->free_space -= size;
2569 blk->fsp_off += size;
2571 /* Insert the header */
2572 ((HBIN_SUB_HDR *)ret)->dblocksize = -size;
2575 * Fix up the free space ptr
2576 * If it is NULL, we fix it up next time
2579 if (!blk->free_space)
2580 regf->free_space = blk->next;
2582 *off = tmp;
2583 return (((char *)ret) + 4);/* The pointer needs to be to the data struct */
2586 return NULL;
2590 * Compute the size of a SID stored ...
2593 unsigned int sid_size(DOM_SID *sid)
2595 unsigned int size;
2597 if (!sid) return 0;
2599 size = 8 + (sid->auths * sizeof(unsigned int));
2601 return size;
2605 * Compute the size of an ACE on disk from its components
2608 unsigned int ace_size(ACE *ace)
2610 unsigned int size;
2612 if (!ace) return 0;
2614 size = 8 + sid_size(ace->trustee);
2616 return size;
2620 * Compute the size of an ACL from its components ...
2622 unsigned int acl_size(ACL *acl)
2624 unsigned int size;
2625 int i;
2627 if (!acl) return 0;
2629 size = 8;
2630 for (i = 0; i < acl->num_aces; i++)
2631 size += ace_size(acl->aces[i]);
2633 return size;
2637 * Compute the size of the sec desc as a self-relative SD
2639 unsigned int sec_desc_size(SEC_DESC *sd)
2641 unsigned int size;
2643 if (!sd) return 0;
2645 size = 20;
2647 if (sd->owner) size += sid_size(sd->owner);
2648 if (sd->group) size += sid_size(sd->group);
2649 if (sd->sacl) size += acl_size(sd->sacl);
2650 if (sd->dacl) size += acl_size(sd->dacl);
2652 return size;
2656 * Store a SID at the location provided
2659 int nt_store_SID(REGF *regf, DOM_SID *sid, unsigned char *locn)
2661 int i;
2662 unsigned char *p = locn;
2664 if (!regf || !sid || !locn) return 0;
2666 *p = sid->ver; p++;
2667 *p = sid->auths; p++;
2669 for (i=0; i < 6; i++) {
2670 *p = sid->auth[i]; p++;
2673 for (i=0; i < sid->auths; i++) {
2674 SIVAL(p, sid->sub_auths[i]); p+=4;
2677 return p - locn;
2681 int nt_store_ace(REGF *regf, ACE *ace, unsigned char *locn)
2683 int size = 0;
2684 REG_ACE *reg_ace = (REG_ACE *)locn;
2685 unsigned char *p;
2687 if (!regf || !ace || !locn) return 0;
2689 reg_ace->type = ace->type;
2690 reg_ace->flags = ace->flags;
2692 /* Deal with the length when we have stored the SID */
2694 p = (unsigned char *)&reg_ace->perms;
2696 SIVAL(p, ace->perms); p += 4;
2698 size = nt_store_SID(regf, ace->trustee, p);
2700 size += 8; /* Size of the fixed header */
2702 p = (unsigned char *)&reg_ace->length;
2704 SSVAL(p, size);
2706 return size;
2710 * Store an ACL at the location provided
2713 int nt_store_acl(REGF *regf, ACL *acl, unsigned char *locn)
2715 int size = 0, i;
2716 unsigned char *p = locn, *s;
2718 if (!regf || !acl || !locn) return 0;
2721 * Now store the header and then the ACEs ...
2724 SSVAL(p, acl->rev);
2726 p += 2; s = p; /* Save this for the size field */
2728 p += 2;
2730 SIVAL(p, acl->num_aces);
2732 p += 4;
2734 for (i = 0; i < acl->num_aces; i++) {
2735 size = nt_store_ace(regf, acl->aces[i], p);
2736 p += size;
2739 size = s - locn;
2740 SSVAL(s, size);
2741 return size;
2745 * Flatten and store the Sec Desc
2746 * Windows lays out the DACL first, but since there is no SACL, it might be
2747 * that first, then the owner, then the group SID. So, we do it that way
2748 * too.
2750 unsigned int nt_store_sec_desc(REGF *regf, SEC_DESC *sd, char *locn)
2752 REG_SEC_DESC *rsd = (REG_SEC_DESC *)locn;
2753 unsigned int size = 0, off = 0;
2755 if (!regf || !sd || !locn) return 0;
2758 * Now, fill in the first two fields, then lay out the various fields
2759 * as needed
2762 rsd->rev = 0x01;
2763 /* Self relative, DACL pres, owner and group not defaulted */
2764 rsd->type = 0x8004;
2766 off = 4 * sizeof(DWORD) + 4;
2768 if (sd->sacl){
2769 size = nt_store_acl(regf, sd->sacl, (char *)(locn + off));
2770 rsd->sacl_off = off;
2772 else
2773 rsd->sacl_off = 0;
2775 off += size;
2777 if (sd->dacl) {
2778 rsd->dacl_off = off;
2779 size = nt_store_acl(regf, sd->dacl, (char *)(locn + off));
2781 else {
2782 rsd->dacl_off = 0;
2785 off += size;
2787 /* Now the owner and group SIDs */
2789 if (sd->owner) {
2790 rsd->owner_off = off;
2791 size = nt_store_SID(regf, sd->owner, (char *)(locn + off));
2793 else {
2794 rsd->owner_off = 0;
2797 off += size;
2799 if (sd->group) {
2800 rsd->group_off = off;
2801 size = nt_store_SID(regf, sd->group, (char *)(locn + off));
2803 else {
2804 rsd->group_off = 0;
2807 off += size;
2809 return size;
2813 * Store the security information
2815 * If it has already been stored, just get its offset from record
2816 * otherwise, store it and record its offset
2819 unsigned int nt_store_security(REGF *regf, KEY_SEC_DESC *sec)
2821 int size = 0;
2822 unsigned int sk_off;
2823 SK_HDR *sk_hdr;
2825 if (sec->offset) return sec->offset;
2828 * OK, we don't have this one in the file yet. We must compute the
2829 * size taken by the security descriptor as a self-relative SD, which
2830 * means making one pass over each structure and figuring it out
2833 size = sec_desc_size(sec->sec_desc);
2835 /* Allocate that much space */
2837 sk_hdr = nt_alloc_regf_space(regf, size, &sk_off);
2838 sec->sk_hdr = sk_hdr;
2840 if (!sk_hdr) return 0;
2842 /* Now, lay out the sec_desc in the space provided */
2844 sk_hdr->SK_ID = REG_SK_ID;
2847 * We can't deal with the next and prev offset in the SK_HDRs until the
2848 * whole tree has been stored, then we can go and deal with them
2851 sk_hdr->ref_cnt = sec->ref_cnt;
2852 sk_hdr->rec_size = size; /* Is this correct */
2854 /* Now, lay out the sec_desc */
2856 if (!nt_store_sec_desc(regf, sec->sec_desc, (char *)&sk_hdr->sec_desc))
2857 return 0;
2859 return sk_off;
2864 * Store a VAL LIST
2867 int nt_store_val_list(REGF *regf, VAL_LIST * values)
2870 return 0;
2874 * Store a KEY in the file ...
2876 * We store this depth first, and defer storing the lf struct until
2877 * all the sub-keys have been stored.
2879 * We store the NK hdr, any SK header, class name, and VK structure, then
2880 * recurse down the LF structures ...
2882 * We return the offset of the NK struct
2883 * FIXME, FIXME, FIXME: Convert to using SIVAL and SSVAL ...
2885 int nt_store_reg_key(REGF *regf, REG_KEY *key)
2887 NK_HDR *nk_hdr;
2888 unsigned int nk_off, sk_off, size;
2890 if (!regf || !key) return 0;
2892 size = sizeof(NK_HDR) + strlen(key->name) - 1;
2893 nk_hdr = nt_alloc_regf_space(regf, size, &nk_off);
2894 if (!nk_hdr) goto error;
2896 key->offset = nk_off; /* We will need this later */
2899 * Now fill in each field etc ...
2902 nk_hdr->NK_ID = REG_NK_ID;
2903 if (key->type == REG_ROOT_KEY)
2904 nk_hdr->type = 0x2C;
2905 else
2906 nk_hdr->type = 0x20;
2908 /* FIXME: Fill in the time of last update */
2910 if (key->type != REG_ROOT_KEY)
2911 nk_hdr->own_off = key->owner->offset;
2913 if (key->sub_keys)
2914 nk_hdr->subk_num = key->sub_keys->key_count;
2917 * Now, process the Sec Desc and then store its offset
2920 sk_off = nt_store_security(regf, key->security);
2921 nk_hdr->sk_off = sk_off;
2924 * Then, store the val list and store its offset
2926 if (key->values) {
2927 nk_hdr->val_cnt = key->values->val_count;
2928 nk_hdr->val_off = nt_store_val_list(regf, key->values);
2930 else {
2931 nk_hdr->val_off = -1;
2932 nk_hdr->val_cnt = 0;
2936 * Finally, store the subkeys, and their offsets
2939 error:
2940 return 0;
2944 * Store the registry header ...
2945 * We actually create the registry header block and link it to the chain
2946 * of output blocks.
2948 REGF_HDR *nt_get_reg_header(REGF *regf)
2950 HBIN_BLK *tmp = NULL;
2952 tmp = (HBIN_BLK *)malloc(sizeof(HBIN_BLK));
2953 if (!tmp) return 0;
2955 bzero(tmp, sizeof(HBIN_BLK));
2956 tmp->type = REG_OUTBLK_HDR;
2957 tmp->size = REGF_HDR_BLKSIZ;
2958 tmp->data = malloc(REGF_HDR_BLKSIZ);
2959 if (!tmp->data) goto error;
2961 bzero(tmp->data, REGF_HDR_BLKSIZ); /* Make it pristine, unlike Windows */
2962 regf->blk_head = regf->blk_tail = tmp;
2964 return (REGF_HDR *)tmp->data;
2966 error:
2967 if (tmp) free(tmp);
2968 return NULL;
2972 * Store the registry in the output file
2973 * We write out the header and then each of the keys etc into the file
2974 * We have to flatten the data structure ...
2976 * The structures are stored in a depth-first fashion, with all records
2977 * aligned on 8-byte boundaries, with sub-keys and values layed down before
2978 * the lists that contain them. SK records are layed down first, however.
2979 * The lf fields are layed down after all sub-keys have been layed down, it
2980 * seems, including the whole tree associated with each sub-key.
2982 int nt_store_registry(REGF *regf)
2984 REGF_HDR *reg;
2985 int fkey, fd;
2988 * Get a header ... and partially fill it in ...
2990 reg = nt_get_reg_header(regf);
2993 * Store the first key, which will store the whole thing
2995 fkey = nt_store_reg_key(regf, regf->root);
2998 * At this point we have the registry as a series of blocks, so
2999 * run down that series of blocks and save them ...
3002 if (!regf->outfile_name) {
3003 fprintf(stderr, "Cannot write file without a name!\n");
3004 return 0;
3007 if ((fd = open(regf->outfile_name, O_WRONLY, 0666)) < 0) {
3008 fprintf(stderr, "Unable to create file %s: %s\n", regf->outfile_name,
3009 strerror(errno));
3010 return 0;
3013 return 1;
3017 * Routines to parse a REGEDIT4 file
3019 * The file consists of:
3021 * REGEDIT4
3022 * \[[-]key-path\]\n
3023 * <value-spec>*
3025 * Format:
3026 * [cmd:]name=type:value
3028 * cmd = a|d|c|add|delete|change|as|ds|cs
3030 * There can be more than one key-path and value-spec.
3032 * Since we want to support more than one type of file format, we
3033 * construct a command-file structure that keeps info about the command file
3036 #define FMT_UNREC -1
3037 #define FMT_REGEDIT4 0
3038 #define FMT_EDITREG1_1 1
3040 #define FMT_STRING_REGEDIT4 "REGEDIT4"
3041 #define FMT_STRING_EDITREG1_0 "EDITREG1.0"
3043 #define CMD_NONE 0
3044 #define CMD_ADD_KEY 1
3045 #define CMD_DEL_KEY 2
3047 #define CMD_KEY 1
3048 #define CMD_VAL 2
3050 typedef struct val_spec_list {
3051 struct val_spec_list *next;
3052 char *name;
3053 int type;
3054 char *val; /* Kept as a char string, really? */
3055 } VAL_SPEC_LIST;
3057 typedef struct command_s {
3058 int cmd;
3059 char *key;
3060 int val_count;
3061 VAL_SPEC_LIST *val_spec_list, *val_spec_last;
3062 } CMD;
3064 typedef struct cmd_line {
3065 int len, line_len;
3066 char *line;
3067 } CMD_LINE;
3069 void free_val_spec_list(VAL_SPEC_LIST *vl)
3071 if (!vl) return;
3072 if (vl->name) free(vl->name);
3073 if (vl->val) free(vl->val);
3074 free(vl);
3079 * Some routines to handle lines of info in the command files
3081 void skip_to_eol(int fd)
3083 int rc;
3084 char ch = 0;
3086 while ((rc = read(fd, &ch, 1)) == 1) {
3087 if (ch == 0x0A) return;
3089 if (rc < 0) {
3090 fprintf(stderr, "Could not read file descriptor: %d, %s\n",
3091 fd, strerror(errno));
3092 exit(1);
3096 void free_cmd(CMD *cmd)
3098 if (!cmd) return;
3100 while (cmd->val_spec_list) {
3101 VAL_SPEC_LIST *tmp;
3103 tmp = cmd->val_spec_list;
3104 cmd->val_spec_list = tmp->next;
3105 free(tmp);
3108 free(cmd);
3112 void free_cmd_line(CMD_LINE *cmd_line)
3114 if (cmd_line) {
3115 if (cmd_line->line) free(cmd_line->line);
3116 free(cmd_line);
3120 void print_line(struct cmd_line *cl)
3122 char *pl;
3124 if (!cl) return;
3126 if ((pl = malloc(cl->line_len + 1)) == NULL) {
3127 fprintf(stderr, "Unable to allocate space to print line: %s\n",
3128 strerror(errno));
3129 exit(1);
3132 strncpy(pl, cl->line, cl->line_len);
3133 pl[cl->line_len] = 0;
3135 fprintf(stdout, "%s\n", pl);
3136 free(pl);
3139 #define INIT_ALLOC 10
3142 * Read a line from the input file.
3143 * NULL returned when EOF and no chars read
3144 * Otherwise we return a cmd_line *
3145 * Exit if other errors
3147 struct cmd_line *get_cmd_line(int fd)
3149 struct cmd_line *cl = (CMD_LINE *)malloc(sizeof(CMD_LINE));
3150 int i = 0, rc;
3151 unsigned char ch;
3153 if (!cl) {
3154 fprintf(stderr, "Unable to allocate structure for command line: %s\n",
3155 strerror(errno));
3156 exit(1);
3159 cl->len = INIT_ALLOC;
3162 * Allocate some space for the line. We extend later if needed.
3165 if ((cl->line = (char *)malloc(INIT_ALLOC)) == NULL) {
3166 fprintf(stderr, "Unable to allocate initial space for line: %s\n",
3167 strerror(errno));
3168 exit(1);
3172 * Now read in the chars to EOL. Don't store the EOL in the
3173 * line. What about CR?
3176 while ((rc = read(fd, &ch, 1)) == 1 && ch != '\n') {
3177 if (ch == '\r') continue; /* skip CR */
3178 if (i == cl->len) {
3180 * Allocate some more memory
3182 if ((cl->line = realloc(cl->line, cl->len + INIT_ALLOC)) == NULL) {
3183 fprintf(stderr, "Unable to realloc space for line: %s\n",
3184 strerror(errno));
3185 exit(1);
3187 cl->len += INIT_ALLOC;
3189 cl->line[i] = ch;
3190 i++;
3193 /* read 0 and we were at loc'n 0, return NULL */
3194 if (rc == 0 && i == 0) {
3195 free_cmd_line(cl);
3196 return NULL;
3199 cl->line_len = i;
3201 return cl;
3206 * parse_value: parse out a value. We pull it apart as:
3208 * <value> ::= <value-name>=<type>:<value-string>
3210 * <value-name> ::= char-string-without-spaces | '"' char-string '"'
3212 * If it parsed OK, return the <value-name> as a string, and the
3213 * value type and value-string in parameters.
3215 * The value name can be empty. There can only be one empty name in
3216 * a list of values. A value of - removes the value entirely.
3219 char *dup_str(char *s, int len)
3221 char *nstr;
3222 nstr = (char *)malloc(len + 1);
3223 if (nstr) {
3224 memcpy(nstr, s, len);
3225 nstr[len] = 0;
3227 return nstr;
3230 char *parse_name(char *nstr)
3232 int len = 0, start = 0;
3233 if (!nstr) return NULL;
3235 len = strlen(nstr);
3237 while (len && nstr[len - 1] == ' ') len--;
3239 nstr[len] = 0; /* Trim any spaces ... if there were none, doesn't matter */
3242 * Beginning and end should be '"' or neither should be so
3244 if ((nstr[0] == '"' && nstr[len - 1] != '"') ||
3245 (nstr[0] != '"' && nstr[len - 1] == '"'))
3246 return NULL;
3248 if (nstr[0] == '"') {
3249 start = 1;
3250 len -= 2;
3253 return dup_str(&nstr[start], len);
3256 int parse_value_type(char *tstr)
3258 int len = strlen(tstr);
3260 while (len && tstr[len - 1] == ' ') len--;
3261 tstr[len] = 0;
3263 if (strcmp(tstr, "REG_DWORD") == 0)
3264 return REG_TYPE_DWORD;
3265 else if (strcmp(tstr, "dword") == 0)
3266 return REG_TYPE_DWORD;
3267 else if (strcmp(tstr, "REG_EXPAND_SZ") == 0)
3268 return REG_TYPE_EXPANDSZ;
3269 else if (strcmp(tstr, "REG_BIN") == 0)
3270 return REG_TYPE_BIN;
3271 else if (strcmp(tstr, "REG_SZ") == 0)
3272 return REG_TYPE_REGSZ;
3273 else if (strcmp(tstr, "REG_MULTI_SZ") == 0)
3274 return REG_TYPE_MULTISZ;
3275 else if (strcmp(tstr, "-") == 0)
3276 return REG_TYPE_DELETE;
3278 return 0;
3281 char *parse_val_str(char *vstr)
3284 return dup_str(vstr, strlen(vstr));
3288 char *parse_value(struct cmd_line *cl, int *vtype, char **val)
3290 char *p1 = NULL, *p2 = NULL, *nstr = NULL, *tstr = NULL, *vstr = NULL;
3292 if (!cl || !vtype || !val) return NULL;
3293 if (!cl->line_len) return NULL;
3295 p1 = dup_str(cl->line, cl->line_len);
3296 /* FIXME: Better return codes etc ... */
3297 if (!p1) return NULL;
3298 p2 = strchr(p1, '=');
3299 if (!p2) return NULL;
3301 *p2 = 0; p2++; /* Split into two strings at p2 */
3303 /* Now, parse the name ... */
3305 nstr = parse_name(p1);
3306 if (!nstr) goto error;
3308 /* Now, split the remainder and parse on type and val ... */
3310 tstr = p2;
3311 while (*tstr == ' ') tstr++; /* Skip leading white space */
3312 p2 = strchr(p2, ':');
3314 if (p2) {
3315 *p2 = 0; p2++; /* split on the : */
3318 *vtype = parse_value_type(tstr);
3320 if (!vtype) goto error;
3322 if (!p2 || !*p2) return nstr;
3324 /* Now, parse the value string. It should return a newly malloc'd string */
3326 while (*p2 == ' ') p2++; /* Skip leading space */
3327 vstr = parse_val_str(p2);
3329 if (!vstr) goto error;
3331 *val = vstr;
3333 return nstr;
3335 error:
3336 if (p1) free(p1);
3337 if (nstr) free(nstr);
3338 if (vstr) free(vstr);
3339 return NULL;
3343 * Parse out a key. Look for a correctly formatted key [...]
3344 * and whether it is a delete or add? A delete is signalled
3345 * by a - in front of the key.
3346 * Assumes that there are no leading and trailing spaces
3349 char *parse_key(struct cmd_line *cl, int *cmd)
3351 int start = 1;
3352 char *tmp;
3354 if (cl->line[0] != '[' ||
3355 cl->line[cl->line_len - 1] != ']') return NULL;
3356 if (cl->line_len == 2) return NULL;
3357 *cmd = CMD_ADD_KEY;
3358 if (cl->line[1] == '-') {
3359 if (cl->line_len == 3) return NULL;
3360 start = 2;
3361 *cmd = CMD_DEL_KEY;
3363 tmp = malloc(cl->line_len - 1 - start + 1);
3364 if (!tmp) return tmp; /* Bail out on no mem ... FIXME */
3365 strncpy(tmp, &cl->line[start], cl->line_len - 1 - start);
3366 tmp[cl->line_len - 1 - start] = 0;
3367 return tmp;
3371 * Parse a line to determine if we have a key or a value
3372 * We only check for key or val ...
3375 int parse_line(struct cmd_line *cl)
3378 if (!cl || cl->len == 0) return 0;
3380 if (cl->line[0] == '[') /* No further checking for now */
3381 return CMD_KEY;
3382 else
3383 return CMD_VAL;
3387 * We seek to offset 0, read in the required number of bytes,
3388 * and compare to the correct value.
3389 * We then seek back to the original location
3391 int regedit4_file_type(int fd)
3393 int cur_ofs = 0;
3394 char desc[9];
3396 cur_ofs = lseek(fd, 0, SEEK_CUR); /* Get current offset */
3397 if (cur_ofs < 0) {
3398 fprintf(stderr, "Unable to get current offset: %s\n", strerror(errno));
3399 exit(1); /* FIXME */
3402 if (cur_ofs) {
3403 lseek(fd, 0, SEEK_SET);
3406 if (read(fd, desc, 8) < 8) {
3407 fprintf(stderr, "Unable to read command file format\n");
3408 exit(2); /* FIXME */
3411 desc[8] = 0;
3413 if (strcmp(desc, FMT_STRING_REGEDIT4) == 0) {
3414 if (cur_ofs) {
3415 lseek(fd, cur_ofs, SEEK_SET);
3417 else {
3418 skip_to_eol(fd);
3420 return FMT_REGEDIT4;
3423 return FMT_UNREC;
3427 * Run though the data in the line and strip anything after a comment
3428 * char.
3430 void strip_comment(struct cmd_line *cl)
3432 int i;
3434 if (!cl) return;
3436 for (i = 0; i < cl->line_len; i++) {
3437 if (cl->line[i] == ';') {
3438 cl->line_len = i;
3439 return;
3445 * trim leading space
3448 void trim_leading_spaces(struct cmd_line *cl)
3450 int i;
3452 if (!cl) return;
3454 for (i = 0; i < cl->line_len; i++) {
3455 if (cl->line[i] != ' '){
3456 if (i) memcpy(cl->line, &cl->line[i], cl->line_len - i);
3457 return;
3463 * trim trailing spaces
3465 void trim_trailing_spaces(struct cmd_line *cl)
3467 int i;
3469 if (!cl) return;
3471 for (i = cl->line_len; i == 0; i--) {
3472 if (cl->line[i-1] != ' ' &&
3473 cl->line[i-1] != '\t') {
3474 cl->line_len = i;
3480 * Get a command ... This consists of possibly multiple lines:
3481 * [key]
3482 * values*
3483 * possibly Empty line
3485 * value ::= <value-name>=<value-type>':'<value-string>
3486 * <value-name> is some path, possibly enclosed in quotes ...
3487 * We alctually look for the next key to terminate a previous key
3488 * if <value-type> == '-', then it is a delete type.
3490 CMD *regedit4_get_cmd(int fd)
3492 struct command_s *cmd = NULL;
3493 struct cmd_line *cl = NULL;
3494 struct val_spec_list *vl = NULL;
3496 if ((cmd = (struct command_s *)malloc(sizeof(struct command_s))) == NULL) {
3497 fprintf(stderr, "Unable to malloc space for command: %s\n",
3498 strerror(errno));
3499 exit(1);
3502 cmd->cmd = CMD_NONE;
3503 cmd->key = NULL;
3504 cmd->val_count = 0;
3505 cmd->val_spec_list = cmd->val_spec_last = NULL;
3506 while ((cl = get_cmd_line(fd))) {
3509 * If it is an empty command line, and we already have a key
3510 * then exit from here ... FIXME: Clean up the parser
3513 if (cl->line_len == 0 && cmd->key) {
3514 free_cmd_line(cl);
3515 break;
3518 strip_comment(cl); /* remove anything beyond a comment char */
3519 trim_trailing_spaces(cl);
3520 trim_leading_spaces(cl);
3522 if (cl->line_len == 0) { /* An empty line */
3523 free_cmd_line(cl);
3525 else { /* Else, non-empty ... */
3527 * Parse out the bits ...
3529 switch (parse_line(cl)) {
3530 case CMD_KEY:
3531 if ((cmd->key = parse_key(cl, &cmd->cmd)) == NULL) {
3532 fprintf(stderr, "Error parsing key from line: ");
3533 print_line(cl);
3534 fprintf(stderr, "\n");
3536 break;
3538 case CMD_VAL:
3540 * We need to add the value stuff to the list
3541 * There could be a \ on the end which we need to
3542 * handle at some time
3544 vl = (struct val_spec_list *)malloc(sizeof(struct val_spec_list));
3545 if (!vl) goto error;
3546 vl->next = NULL;
3547 vl->val = NULL;
3548 vl->name = parse_value(cl, &vl->type, &vl->val);
3549 if (!vl->name) goto error;
3550 if (cmd->val_spec_list == NULL) {
3551 cmd->val_spec_list = cmd->val_spec_last = vl;
3553 else {
3554 cmd->val_spec_last->next = vl;
3555 cmd->val_spec_last = vl;
3557 cmd->val_count++;
3558 break;
3560 default:
3561 fprintf(stderr, "Unrecognized line in command file: \n");
3562 print_line(cl);
3563 break;
3568 if (!cmd->cmd) goto error; /* End of file ... */
3570 return cmd;
3572 error:
3573 if (vl) free(vl);
3574 if (cmd) free_cmd(cmd);
3575 return NULL;
3578 int regedit4_exec_cmd(CMD *cmd)
3581 return 0;
3584 int editreg_1_0_file_type(int fd)
3586 int cur_ofs = 0;
3587 char desc[11];
3589 cur_ofs = lseek(fd, 0, SEEK_CUR); /* Get current offset */
3590 if (cur_ofs < 0) {
3591 fprintf(stderr, "Unable to get current offset: %s\n", strerror(errno));
3592 exit(1); /* FIXME */
3595 if (cur_ofs) {
3596 lseek(fd, 0, SEEK_SET);
3599 if (read(fd, desc, 10) < 10) {
3600 fprintf(stderr, "Unable to read command file format\n");
3601 exit(2); /* FIXME */
3604 desc[10] = 0;
3606 if (strcmp(desc, FMT_STRING_EDITREG1_0) == 0) {
3607 lseek(fd, cur_ofs, SEEK_SET);
3608 return FMT_REGEDIT4;
3611 return FMT_UNREC;
3614 CMD *editreg_1_0_get_cmd(int fd)
3616 return NULL;
3619 int editreg_1_0_exec_cmd(CMD *cmd)
3622 return -1;
3625 typedef struct command_ops_s {
3626 int type;
3627 int (*file_type)(int fd);
3628 CMD *(*get_cmd)(int fd);
3629 int (*exec_cmd)(CMD *cmd);
3630 } CMD_OPS;
3632 CMD_OPS default_cmd_ops[] = {
3633 {0, regedit4_file_type, regedit4_get_cmd, regedit4_exec_cmd},
3634 {1, editreg_1_0_file_type, editreg_1_0_get_cmd, editreg_1_0_exec_cmd},
3635 {-1, NULL, NULL, NULL}
3638 typedef struct command_file_s {
3639 char *name;
3640 int type, fd;
3641 CMD_OPS cmd_ops;
3642 } CMD_FILE;
3645 * Create a new command file structure
3648 CMD_FILE *cmd_file_create(char *file)
3650 CMD_FILE *tmp;
3651 struct stat sbuf;
3652 int i = 0;
3655 * Let's check if the file exists ...
3656 * No use creating the cmd_file structure if the file does not exist
3659 if (stat(file, &sbuf) < 0) { /* Not able to access file */
3661 return NULL;
3664 tmp = (CMD_FILE *)malloc(sizeof(CMD_FILE));
3665 if (!tmp) {
3666 return NULL;
3670 * Let's fill in some of the fields;
3673 tmp->name = strdup(file);
3675 if ((tmp->fd = open(file, O_RDONLY, 666)) < 0) {
3676 free(tmp);
3677 return NULL;
3681 * Now, try to find the format by indexing through the table
3683 while (default_cmd_ops[i].type != -1) {
3684 if ((tmp->type = default_cmd_ops[i].file_type(tmp->fd)) >= 0) {
3685 tmp->cmd_ops = default_cmd_ops[i];
3686 return tmp;
3688 i++;
3692 * If we got here, return NULL, as we could not figure out the type
3693 * of command file.
3695 * What about errors?
3698 free(tmp);
3699 return NULL;
3703 * Extract commands from the command file, and execute them.
3704 * We pass a table of command callbacks for that
3708 * Main code from here on ...
3712 * key print function here ...
3715 int print_key(const char *path, char *name, char *class_name, int root,
3716 int terminal, int vals)
3719 if (full_print || terminal) fprintf(stdout, "[%s%s]\n", path, name);
3721 return 1;
3725 * Sec Desc print functions
3728 void print_type(unsigned char type)
3730 switch (type) {
3731 case 0x00:
3732 fprintf(stdout, " ALLOW");
3733 break;
3734 case 0x01:
3735 fprintf(stdout, " DENY");
3736 break;
3737 case 0x02:
3738 fprintf(stdout, " AUDIT");
3739 break;
3740 case 0x03:
3741 fprintf(stdout, " ALARM");
3742 break;
3743 case 0x04:
3744 fprintf(stdout, "ALLOW CPD");
3745 break;
3746 case 0x05:
3747 fprintf(stdout, "OBJ ALLOW");
3748 break;
3749 case 0x06:
3750 fprintf(stdout, " OBJ DENY");
3751 default:
3752 fprintf(stdout, " UNKNOWN");
3753 break;
3757 void print_flags(unsigned char flags)
3759 char flg_output[21];
3760 int some = 0;
3762 flg_output[0] = 0;
3763 if (!flags) {
3764 fprintf(stdout, " ");
3765 return;
3767 if (flags & 0x01) {
3768 if (some) strcat(flg_output, ",");
3769 some = 1;
3770 strcat(flg_output, "OI");
3772 if (flags & 0x02) {
3773 if (some) strcat(flg_output, ",");
3774 some = 1;
3775 strcat(flg_output, "CI");
3777 if (flags & 0x04) {
3778 if (some) strcat(flg_output, ",");
3779 some = 1;
3780 strcat(flg_output, "NP");
3782 if (flags & 0x08) {
3783 if (some) strcat(flg_output, ",");
3784 some = 1;
3785 strcat(flg_output, "IO");
3787 if (flags & 0x10) {
3788 if (some) strcat(flg_output, ",");
3789 some = 1;
3790 strcat(flg_output, "IA");
3792 if (flags == 0xF) {
3793 if (some) strcat(flg_output, ",");
3794 some = 1;
3795 strcat(flg_output, "VI");
3797 fprintf(stdout, " %s", flg_output);
3800 void print_perms(int perms)
3802 fprintf(stdout, " %8X", perms);
3805 void print_sid(DOM_SID *sid)
3807 int i, comps = sid->auths;
3808 fprintf(stdout, "S-%u-%u", sid->ver, sid->auth[5]);
3810 for (i = 0; i < comps; i++) {
3812 fprintf(stdout, "-%u", sid->sub_auths[i]);
3815 fprintf(stdout, "\n");
3818 void print_acl(ACL *acl, const char *prefix)
3820 int i;
3822 for (i = 0; i < acl->num_aces; i++) {
3823 fprintf(stdout, ";;%s", prefix);
3824 print_type(acl->aces[i]->type);
3825 print_flags(acl->aces[i]->flags);
3826 print_perms(acl->aces[i]->perms);
3827 fprintf(stdout, " ");
3828 print_sid(acl->aces[i]->trustee);
3832 int print_sec(SEC_DESC *sec_desc)
3834 if (!print_security) return 1;
3835 fprintf(stdout, ";; SECURITY\n");
3836 fprintf(stdout, ";; Owner: ");
3837 print_sid(sec_desc->owner);
3838 fprintf(stdout, ";; Group: ");
3839 print_sid(sec_desc->group);
3840 if (sec_desc->sacl) {
3841 fprintf(stdout, ";; SACL:\n");
3842 print_acl(sec_desc->sacl, " ");
3844 if (sec_desc->dacl) {
3845 fprintf(stdout, ";; DACL:\n");
3846 print_acl(sec_desc->dacl, " ");
3848 return 1;
3852 * Value print function here ...
3854 int print_val(const char *path, char *val_name, int val_type, int data_len,
3855 void *data_blk, int terminal, int first, int last)
3857 char data_asc[1024];
3859 bzero(data_asc, sizeof(data_asc));
3860 if (!terminal && first)
3861 fprintf(stdout, "%s\n", path);
3862 data_to_ascii((unsigned char *)data_blk, data_len, val_type, data_asc,
3863 sizeof(data_asc) - 1);
3864 fprintf(stdout, " %s = %s : %s\n", (val_name?val_name:"<No Name>"),
3865 val_to_str(val_type, reg_type_names), data_asc);
3866 return 1;
3869 void usage(void)
3871 fprintf(stderr, "Usage: editreg [-f] [-v] [-p] [-k] [-s] [-c <command-file>] <registryfile>\n");
3872 fprintf(stderr, "Version: 0.1\n\n");
3873 fprintf(stderr, "\n\t-v\t sets verbose mode");
3874 fprintf(stderr, "\n\t-f\t sets full print mode where non-terminals are printed");
3875 fprintf(stderr, "\n\t-p\t prints the registry");
3876 fprintf(stderr, "\n\t-s\t prints security descriptors");
3877 fprintf(stderr, "\n\t-c <command-file>\t specifies a command file");
3878 fprintf(stderr, "\n");
3881 int main(int argc, char *argv[])
3883 REGF *regf;
3884 extern char *optarg;
3885 extern int optind;
3886 int opt, print_keys = 0;
3887 int regf_opt = 1; /* Command name */
3888 int commands = 0, modified = 0;
3889 char *cmd_file_name = NULL;
3890 char *out_file_name = NULL;
3891 CMD_FILE *cmd_file = NULL;
3892 DOM_SID *lsid;
3894 if (argc < 2) {
3895 usage();
3896 exit(1);
3900 * Now, process the arguments
3903 while ((opt = getopt(argc, argv, "fspvko:O:c:")) != EOF) {
3904 switch (opt) {
3905 case 'c':
3906 commands = 1;
3907 cmd_file_name = optarg;
3908 regf_opt += 2;
3909 break;
3911 case 'f':
3912 full_print = 1;
3913 regf_opt++;
3914 break;
3916 case 'o':
3917 out_file_name = optarg;
3918 regf_opt += 2;
3919 break;
3921 case 'O':
3922 def_owner_sid_str = strdup(optarg);
3923 regf_opt += 2;
3924 if (!string_to_sid(&lsid, def_owner_sid_str)) {
3925 fprintf(stderr, "Default Owner SID: %s is incorrectly formatted\n",
3926 def_owner_sid_str);
3927 free(&def_owner_sid_str[0]);
3928 def_owner_sid_str = NULL;
3930 else
3931 nt_delete_sid(lsid);
3932 break;
3934 case 'p':
3935 print_keys++;
3936 regf_opt++;
3937 break;
3939 case 's':
3940 print_security++;
3941 full_print++;
3942 regf_opt++;
3943 break;
3945 case 'v':
3946 verbose++;
3947 regf_opt++;
3948 break;
3950 case 'k':
3951 regf_opt++;
3952 break;
3954 default:
3955 usage();
3956 exit(1);
3957 break;
3962 * We only want to complain about the lack of a default owner SID if
3963 * we need one. This approximates that need
3965 if (!def_owner_sid_str) {
3966 def_owner_sid_str = "S-1-5-21-1-2-3-4";
3967 if (out_file_name || verbose)
3968 fprintf(stderr, "Warning, default owner SID not set. Setting to %s\n",
3969 def_owner_sid_str);
3972 if ((regf = nt_create_regf()) == NULL) {
3973 fprintf(stderr, "Could not create registry object: %s\n", strerror(errno));
3974 exit(2);
3977 if (regf_opt < argc) { /* We have a registry file */
3978 if (!nt_set_regf_input_file(regf, argv[regf_opt])) {
3979 fprintf(stderr, "Could not set name of registry file: %s, %s\n",
3980 argv[regf_opt], strerror(errno));
3981 exit(3);
3984 /* Now, open it, and bring it into memory :-) */
3986 if (nt_load_registry(regf) < 0) {
3987 fprintf(stderr, "Could not load registry: %s\n", argv[1]);
3988 exit(4);
3992 if (out_file_name) {
3993 if (!nt_set_regf_output_file(regf, out_file_name)) {
3994 fprintf(stderr, "Could not set name of output registry file: %s, %s\n",
3995 out_file_name, strerror(errno));
3996 exit(3);
4001 if (commands) {
4002 CMD *cmd;
4004 cmd_file = cmd_file_create(cmd_file_name);
4006 while ((cmd = cmd_file->cmd_ops.get_cmd(cmd_file->fd)) != NULL) {
4009 * Now, apply the requests to the tree ...
4011 switch (cmd->cmd) {
4012 case CMD_ADD_KEY: {
4013 REG_KEY *tmp = NULL;
4015 tmp = nt_find_key_by_name(regf->root, cmd->key);
4017 /* If we found it, apply the other bits, else create such a key */
4019 if (!tmp) {
4020 tmp = nt_add_reg_key(regf, cmd->key, True);
4021 modified = 1;
4024 while (cmd->val_count) {
4025 VAL_SPEC_LIST *val = cmd->val_spec_list;
4026 VAL_KEY *reg_val = NULL;
4028 if (val->type == REG_TYPE_DELETE) {
4029 reg_val = nt_delete_reg_value(tmp, val -> name);
4030 if (reg_val) nt_delete_val_key(reg_val);
4031 modified = 1;
4033 else {
4034 reg_val = nt_add_reg_value(tmp, val->name, val->type,
4035 val->val);
4036 modified = 1;
4039 cmd->val_spec_list = val->next;
4040 free_val_spec_list(val);
4041 cmd->val_count--;
4044 break;
4047 case CMD_DEL_KEY:
4049 * Any value does not matter ...
4050 * Find the key if it exists, and delete it ...
4053 nt_delete_key_by_name(regf, cmd->key);
4054 modified = 1;
4055 break;
4058 free_cmd(cmd);
4062 * At this point, we should have a registry in memory and should be able
4063 * to iterate over it.
4066 if (print_keys) {
4067 nt_key_iterator(regf, regf->root, 0, "", print_key, print_sec, print_val);
4071 * If there was an out_file_name and the tree was modified, print it
4073 if (modified && out_file_name)
4074 if (!nt_store_registry(regf)) {
4075 fprintf(stdout, "Error storing registry\n");
4078 return 0;