Complete the space allocation code for HBIN blocks ...
[Samba/gbeck.git] / source3 / utils / editreg.c
blobbdfb3dc83266455fcc07c93d3571cd0579929b6f
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 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)&0xFF))
346 static int verbose = 0;
347 static int print_security = 0;
348 static int full_print = 0;
349 static 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 } REG_KEY;
387 * The KEY_LIST struct lists sub-keys.
390 typedef struct key_list_s {
391 int key_count;
392 int max_keys;
393 REG_KEY *keys[1];
394 } KEY_LIST;
396 typedef struct val_key_s {
397 char *name;
398 int has_name;
399 int data_type;
400 int data_len;
401 void *data_blk; /* Might want a separate block */
402 } VAL_KEY;
404 typedef struct val_list_s {
405 int val_count;
406 int max_vals;
407 VAL_KEY *vals[1];
408 } VAL_LIST;
410 #ifndef MAXSUBAUTHS
411 #define MAXSUBAUTHS 15
412 #endif
414 typedef struct dom_sid_s {
415 unsigned char ver, auths;
416 unsigned char auth[6];
417 unsigned int sub_auths[MAXSUBAUTHS];
418 } DOM_SID;
420 typedef struct ace_struct_s {
421 unsigned char type, flags;
422 unsigned int perms; /* Perhaps a better def is in order */
423 DOM_SID *trustee;
424 } ACE;
426 typedef struct acl_struct_s {
427 unsigned short rev, refcnt;
428 unsigned short num_aces;
429 ACE *aces[1];
430 } ACL;
432 typedef struct sec_desc_s {
433 unsigned int rev, type;
434 DOM_SID *owner, *group;
435 ACL *sacl, *dacl;
436 } SEC_DESC;
438 #define SEC_DESC_NON 0
439 #define SEC_DESC_RES 1
440 #define SEC_DESC_OCU 2
441 #define SEC_DESC_NBK 3
442 struct key_sec_desc_s {
443 struct key_sec_desc_s *prev, *next;
444 int ref_cnt;
445 int state;
446 SEC_DESC *sec_desc;
450 * All of the structures below actually have a four-byte lenght before them
451 * which always seems to be negative. The following macro retrieves that
452 * size as an integer
455 #define BLK_SIZE(b) ((int)*(int *)(((int *)b)-1))
457 typedef unsigned int DWORD;
458 typedef unsigned short WORD;
460 #define REG_REGF_ID 0x66676572
462 typedef struct regf_block {
463 DWORD REGF_ID; /* regf */
464 DWORD uk1;
465 DWORD uk2;
466 DWORD tim1, tim2;
467 DWORD uk3; /* 1 */
468 DWORD uk4; /* 3 */
469 DWORD uk5; /* 0 */
470 DWORD uk6; /* 1 */
471 DWORD first_key; /* offset */
472 unsigned int dblk_size;
473 DWORD uk7[116]; /* 1 */
474 DWORD chksum;
475 } REGF_HDR;
477 typedef struct hbin_sub_struct {
478 DWORD dblocksize;
479 char data[1];
480 } HBIN_SUB_HDR;
482 #define REG_HBIN_ID 0x6E696268
484 typedef struct hbin_struct {
485 DWORD HBIN_ID; /* hbin */
486 DWORD prev_off;
487 DWORD next_off;
488 DWORD uk1;
489 DWORD uk2;
490 DWORD uk3;
491 DWORD uk4;
492 DWORD blk_size;
493 HBIN_SUB_HDR hbin_sub_hdr;
494 } HBIN_HDR;
496 #define REG_NK_ID 0x6B6E
498 typedef struct nk_struct {
499 WORD NK_ID;
500 WORD type;
501 DWORD t1, t2;
502 DWORD uk1;
503 DWORD own_off;
504 DWORD subk_num;
505 DWORD uk2;
506 DWORD lf_off;
507 DWORD uk3;
508 DWORD val_cnt;
509 DWORD val_off;
510 DWORD sk_off;
511 DWORD clsnam_off;
512 DWORD unk4[4];
513 DWORD unk5;
514 WORD nam_len;
515 WORD clsnam_len;
516 char key_nam[1]; /* Actual length determined by nam_len */
517 } NK_HDR;
519 #define REG_SK_ID 0x6B73
521 typedef struct sk_struct {
522 WORD SK_ID;
523 WORD uk1;
524 DWORD prev_off;
525 DWORD next_off;
526 DWORD ref_cnt;
527 DWORD rec_size;
528 char sec_desc[1];
529 } SK_HDR;
531 typedef struct ace_struct {
532 unsigned char type;
533 unsigned char flags;
534 unsigned short length;
535 unsigned int perms;
536 DOM_SID trustee;
537 } REG_ACE;
539 typedef struct acl_struct {
540 WORD rev;
541 WORD size;
542 DWORD num_aces;
543 REG_ACE *aces; /* One or more ACEs */
544 } REG_ACL;
546 typedef struct sec_desc_rec {
547 WORD rev;
548 WORD type;
549 DWORD owner_off;
550 DWORD group_off;
551 DWORD sacl_off;
552 DWORD dacl_off;
553 } REG_SEC_DESC;
555 typedef struct hash_struct {
556 DWORD nk_off;
557 char hash[4];
558 } HASH_REC;
560 #define REG_LF_ID 0x666C
562 typedef struct lf_struct {
563 WORD LF_ID;
564 WORD key_count;
565 struct hash_struct hr[1]; /* Array of hash records, depending on key_count */
566 } LF_HDR;
568 typedef DWORD VL_TYPE[1]; /* Value list is an array of vk rec offsets */
570 #define REG_VK_ID 0x6B76
572 typedef struct vk_struct {
573 WORD VK_ID;
574 WORD nam_len;
575 DWORD dat_len; /* If top-bit set, offset contains the data */
576 DWORD dat_off;
577 DWORD dat_type;
578 WORD flag; /* =1, has name, else no name (=Default). */
579 WORD unk1;
580 char dat_name[1]; /* Name starts here ... */
581 } VK_HDR;
583 #define REG_TYPE_DELETE -1
584 #define REG_TYPE_NONE 0
585 #define REG_TYPE_REGSZ 1
586 #define REG_TYPE_EXPANDSZ 2
587 #define REG_TYPE_BIN 3
588 #define REG_TYPE_DWORD 4
589 #define REG_TYPE_MULTISZ 7
591 typedef struct _val_str {
592 unsigned int val;
593 const char * str;
594 } VAL_STR;
596 /* A map of sk offsets in the regf to KEY_SEC_DESCs for quick lookup etc */
597 typedef struct sk_map_s {
598 int sk_off;
599 KEY_SEC_DESC *key_sec_desc;
600 } SK_MAP;
603 * This structure keeps track of the output format of the registry
605 #define REG_OUTBLK_HDR 1
606 #define REG_OUTBLK_HBIN 2
608 typedef struct hbin_blk_s {
609 int type, size;
610 struct hbin_blk_s *next;
611 char *data; /* The data block */
612 unsigned int file_offset; /* Offset in file */
613 unsigned int free_space; /* Amount of free space in block */
614 unsigned int fsp_off; /* Start of free space in block */
615 int complete, stored;
616 } HBIN_BLK;
619 * This structure keeps all the registry stuff in one place
621 typedef struct regf_struct_s {
622 int reg_type;
623 char *regfile_name, *outfile_name;
624 int fd;
625 struct stat sbuf;
626 char *base;
627 int modified;
628 NTTIME last_mod_time;
629 REG_KEY *root; /* Root of the tree for this file */
630 int sk_count, sk_map_size;
631 SK_MAP *sk_map;
632 char *owner_sid_str;
633 SEC_DESC *def_sec_desc;
635 * These next pointers point to the blocks used to contain the
636 * keys when we are preparing to write them to a file
638 HBIN_BLK *blk_head, *blk_tail, *free_space;
639 } REGF;
642 * An API for accessing/creating/destroying items above
646 * Iterate over the keys, depth first, calling a function for each key
647 * and indicating if it is terminal or non-terminal and if it has values.
649 * In addition, for each value in the list, call a value list function
652 typedef int (*key_print_f)(const char *path, char *key_name, char *class_name,
653 int root, int terminal, int values);
655 typedef int (*val_print_f)(const char *path, char *val_name, int val_type,
656 int data_len, void *data_blk, int terminal,
657 int first, int last);
659 typedef int (*sec_print_f)(SEC_DESC *sec_desc);
661 int nt_key_iterator(REGF *regf, REG_KEY *key_tree, int bf, const char *path,
662 key_print_f key_print, sec_print_f sec_print,
663 val_print_f val_print);
665 int nt_val_list_iterator(REGF *regf, VAL_LIST *val_list, int bf, char *path,
666 int terminal, val_print_f val_print)
668 int i;
670 if (!val_list) return 1;
672 if (!val_print) return 1;
674 for (i=0; i<val_list->val_count; i++) {
675 if (!val_print(path, val_list->vals[i]->name, val_list->vals[i]->data_type,
676 val_list->vals[i]->data_len, val_list->vals[i]->data_blk,
677 terminal,
678 (i == 0),
679 (i == val_list->val_count))) {
681 return 0;
686 return 1;
689 int nt_key_list_iterator(REGF *regf, KEY_LIST *key_list, int bf,
690 const char *path,
691 key_print_f key_print, sec_print_f sec_print,
692 val_print_f val_print)
694 int i;
696 if (!key_list) return 1;
698 for (i=0; i< key_list->key_count; i++) {
699 if (!nt_key_iterator(regf, key_list->keys[i], bf, path, key_print,
700 sec_print, val_print)) {
701 return 0;
704 return 1;
707 int nt_key_iterator(REGF *regf, REG_KEY *key_tree, int bf, const char *path,
708 key_print_f key_print, sec_print_f sec_print,
709 val_print_f val_print)
711 int path_len = strlen(path);
712 char *new_path;
714 if (!regf || !key_tree)
715 return -1;
717 /* List the key first, then the values, then the sub-keys */
719 if (key_print) {
721 if (!(*key_print)(path, key_tree->name,
722 key_tree->class_name,
723 (key_tree->type == REG_ROOT_KEY),
724 (key_tree->sub_keys == NULL),
725 (key_tree->values?(key_tree->values->val_count):0)))
726 return 0;
730 * If we have a security print routine, call it
731 * If the security print routine returns false, stop.
733 if (sec_print) {
734 if (key_tree->security && !(*sec_print)(key_tree->security->sec_desc))
735 return 0;
738 new_path = (char *)malloc(path_len + 1 + strlen(key_tree->name) + 1);
739 if (!new_path) return 0; /* Errors? */
740 new_path[0] = '\0';
741 strcat(new_path, path);
742 strcat(new_path, key_tree->name);
743 strcat(new_path, "\\");
746 * Now, iterate through the values in the val_list
749 if (key_tree->values &&
750 !nt_val_list_iterator(regf, key_tree->values, bf, new_path,
751 (key_tree->values!=NULL),
752 val_print)) {
754 free(new_path);
755 return 0;
759 * Now, iterate through the keys in the key list
762 if (key_tree->sub_keys &&
763 !nt_key_list_iterator(regf, key_tree->sub_keys, bf, new_path, key_print,
764 sec_print, val_print)) {
765 free(new_path);
766 return 0;
769 free(new_path);
770 return 1;
773 REG_KEY *nt_find_key_by_name(REG_KEY *tree, char *key);
776 * Find key by name in a list ...
777 * Take the first component and search for that in the list
779 REG_KEY *nt_find_key_in_list_by_name(KEY_LIST *list, char *key)
781 int i;
782 REG_KEY *res = NULL;
784 if (!list || !key || !*key) return NULL;
786 for (i = 0; i < list->key_count; i++)
787 if ((res = nt_find_key_by_name(list->keys[i], key)))
788 return res;
790 return NULL;
794 * Find key by name in a tree ... We will assume absolute names here, but we
795 * need the root of the tree ...
797 REG_KEY *nt_find_key_by_name(REG_KEY *tree, char *key)
799 char *lname = NULL, *c1, *c2;
800 REG_KEY *tmp;
802 if (!tree || !key || !*key) return NULL;
804 lname = strdup(key);
805 if (!lname) return NULL;
808 * Make sure that the first component is correct ...
810 c1 = lname;
811 c2 = strchr(c1, '\\');
812 if (c2) { /* Split here ... */
813 *c2 = 0;
814 c2++;
816 if (strcmp(c1, tree->name) != 0) goto error;
818 if (c2) {
819 tmp = nt_find_key_in_list_by_name(tree->sub_keys, c2);
820 free(lname);
821 return tmp;
823 else {
824 if (lname) free(lname);
825 return tree;
827 error:
828 if (lname) free(lname);
829 return NULL;
832 /* Make, delete keys */
834 int nt_delete_val_key(VAL_KEY *val_key)
837 if (val_key) {
838 if (val_key->name) free(val_key->name);
839 if (val_key->data_blk) free(val_key->data_blk);
840 free(val_key);
842 return 1;
845 int nt_delete_val_list(VAL_LIST *vl)
847 int i;
849 if (vl) {
850 for (i=0; i<vl->val_count; i++)
851 nt_delete_val_key(vl->vals[i]);
852 free(vl);
854 return 1;
857 int nt_delete_reg_key(REG_KEY *key, int delete_name);
858 int nt_delete_key_list(KEY_LIST *key_list, int delete_name)
860 int i;
862 if (key_list) {
863 for (i=0; i<key_list->key_count; i++)
864 nt_delete_reg_key(key_list->keys[i], False);
865 free(key_list);
867 return 1;
871 * Find the key, and if it exists, delete it ...
873 int nt_delete_key_by_name(REGF *regf, char *name)
875 REG_KEY *key;
877 if (!name || !*name) return 0;
879 key = nt_find_key_by_name(regf->root, name);
881 if (key) {
882 if (key == regf->root) regf->root = NULL;
883 return nt_delete_reg_key(key, True);
886 return 0;
890 int nt_delete_sid(DOM_SID *sid)
893 if (sid) free(sid);
894 return 1;
898 int nt_delete_ace(ACE *ace)
901 if (ace) {
902 nt_delete_sid(ace->trustee);
903 free(ace);
905 return 1;
909 int nt_delete_acl(ACL *acl)
912 if (acl) {
913 int i;
915 for (i=0; i<acl->num_aces; i++)
916 nt_delete_ace(acl->aces[i]);
918 free(acl);
920 return 1;
923 int nt_delete_sec_desc(SEC_DESC *sec_desc)
926 if (sec_desc) {
928 nt_delete_sid(sec_desc->owner);
929 nt_delete_sid(sec_desc->group);
930 nt_delete_acl(sec_desc->sacl);
931 nt_delete_acl(sec_desc->dacl);
932 free(sec_desc);
935 return 1;
938 int nt_delete_key_sec_desc(KEY_SEC_DESC *key_sec_desc)
941 if (key_sec_desc) {
942 key_sec_desc->ref_cnt--;
943 if (key_sec_desc->ref_cnt<=0) {
945 * There should always be a next and prev, even if they point to us
947 key_sec_desc->next->prev = key_sec_desc->prev;
948 key_sec_desc->prev->next = key_sec_desc->next;
949 nt_delete_sec_desc(key_sec_desc->sec_desc);
952 return 1;
955 int nt_delete_reg_key(REG_KEY *key, int delete_name)
958 if (key) {
959 if (key->name) free(key->name);
960 if (key->class_name) free(key->class_name);
963 * We will delete the owner if we are not the root and told to ...
966 if (key->owner && key->owner->sub_keys && delete_name) {
967 REG_KEY *own;
968 KEY_LIST *kl;
969 int i;
970 /* Find our owner, look in keylist for us and shuffle up */
971 /* Perhaps should be a function */
973 own = key->owner;
974 kl = own->sub_keys;
976 for (i=0; i < kl->key_count && kl->keys[i] != key ; i++) {
977 /* Just find the entry ... */
980 if (i == kl->key_count) {
981 fprintf(stderr, "Bad data structure. Key not found in key list of owner\n");
983 else {
984 int j;
987 * Shuffle up. Works for the last one also
989 for (j = i + 1; j < kl->key_count; j++) {
990 kl->keys[j - 1] = kl->keys[j];
993 kl->key_count--;
997 if (key->sub_keys) nt_delete_key_list(key->sub_keys, False);
998 if (key->values) nt_delete_val_list(key->values);
999 if (key->security) nt_delete_key_sec_desc(key->security);
1000 free(key);
1002 return 1;
1006 * Convert a string to a value ...
1007 * FIXME: Error handling and convert this at command parse time ...
1009 void *str_to_val(int type, char *val, int *len)
1011 unsigned int *dwordp = NULL;
1013 if (!len || !val) return NULL;
1015 switch (type) {
1016 case REG_TYPE_REGSZ:
1017 *len = strlen(val);
1018 return (void *)val;
1020 case REG_TYPE_DWORD:
1021 dwordp = (unsigned int *)malloc(sizeof(unsigned int));
1022 if (!dwordp) return NULL;
1023 /* Allow for ddddd and 0xhhhhh and 0ooooo */
1024 if (strncmp(val, "0x", 2) == 0 || strncmp(val, "0X", 2) == 0) {
1025 sscanf(&val[2], "%X", dwordp);
1027 else if (*val == '0') {
1028 sscanf(&val[1], "%o", dwordp);
1030 else {
1031 sscanf(val, "%d", dwordp);
1033 *len = sizeof(unsigned int);
1034 return (void *)dwordp;
1036 /* FIXME: Implement more of these */
1038 default:
1039 return NULL;
1040 break;
1043 return NULL;
1047 * Add a value to the key specified ... We have to parse the value some more
1048 * based on the type to get it in the correct internal form
1049 * An empty name will be converted to "<No Name>" before here
1050 * Hmmm, maybe not. has_name is for that
1052 VAL_KEY *nt_add_reg_value(REG_KEY *key, char *name, int type, char *value)
1054 int i;
1055 VAL_KEY *tmp = NULL;
1057 if (!key || !key->values || !name || !*name) return NULL;
1059 assert(type != REG_TYPE_DELETE); /* We never process deletes here */
1061 for (i = 0; i < key->values->val_count; i++) {
1062 if ((!key->values->vals[i]->has_name && !*name) ||
1063 (key->values->vals[i]->has_name &&
1064 strcmp(name, key->values->vals[i]->name) == 0)){ /* Change the value */
1065 free(key->values->vals[i]->data_blk);
1066 key->values->vals[i]->data_blk = str_to_val(type, value, &
1067 key->values->vals[i]->data_len);
1068 return key->values->vals[i];
1073 * If we get here, the name was not found, so insert it
1076 tmp = (VAL_KEY *)malloc(sizeof(VAL_KEY));
1077 if (!tmp) goto error;
1079 bzero(tmp, sizeof(VAL_KEY));
1080 tmp->name = strdup(name);
1081 tmp->has_name = True;
1082 if (!tmp->name) goto error;
1083 tmp->data_type = type;
1084 tmp->data_blk = str_to_val(type, value, &tmp->data_len);
1086 /* Now, add to val list */
1088 if (key->values->val_count >= key->values->max_vals) {
1090 * Allocate some more space
1093 if ((key->values = (VAL_LIST *)realloc(key->values, sizeof(VAL_LIST) +
1094 key->values->val_count - 1 +
1095 REG_KEY_LIST_SIZE))) {
1096 key->values->max_vals += REG_KEY_LIST_SIZE;
1098 else goto error;
1101 i = key->values->val_count;
1102 key->values->val_count++;
1103 key->values->vals[i] = tmp;
1104 return tmp;
1106 error:
1107 if (tmp) nt_delete_val_key(tmp);
1108 return NULL;
1112 * Delete a value. We return the value and let the caller deal with it.
1114 VAL_KEY *nt_delete_reg_value(REG_KEY *key, char *name)
1116 int i, j;
1118 if (!key || !key->values || !name || !*name) return NULL;
1120 /* FIXME: Allow empty value name */
1121 for (i = 0; i< key->values->val_count; i++) {
1122 if ((!key->values->vals[i]->has_name && !*name) ||
1123 (key->values->vals[i]->has_name &&
1124 strcmp(name, key->values->vals[i]->name) == 0)) {
1125 VAL_KEY *val;
1127 val = key->values->vals[i];
1129 /* Shuffle down */
1130 for (j = i + 1; j < key->values->val_count; j++)
1131 key->values->vals[j - 1] = key->values->vals[j];
1133 key->values->val_count--;
1135 return val;
1138 return NULL;
1142 * Add a key to the tree ... We walk down the components matching until
1143 * we don't find any. There must be a match on the first component ...
1144 * We return the key structure for the final component as that is
1145 * often where we want to add values ...
1149 * Create a 1 component key name and set its parent to parent
1151 REG_KEY *nt_create_reg_key1(char *name, REG_KEY *parent)
1153 REG_KEY *tmp;
1155 if (!name || !*name) return NULL; /* A key's name cannot be empty */
1157 /* There should not be more than one component */
1158 if (strchr(name, '\\')) return NULL;
1160 if (!(tmp = (REG_KEY *)malloc(sizeof(REG_KEY)))) return NULL;
1162 bzero(tmp, sizeof(REG_KEY));
1164 if (!(tmp->name = strdup(name))) goto error;
1166 error:
1167 if (tmp) free(tmp);
1168 return NULL;
1172 * Convert a string of the form S-1-5-x[-y-z-r] to a SID
1174 int string_to_sid(DOM_SID **sid, char *sid_str)
1176 int i = 0, auth;
1177 char *lstr;
1179 *sid = (DOM_SID *)malloc(sizeof(DOM_SID));
1180 if (!*sid) return 0;
1182 bzero(*sid, sizeof(DOM_SID));
1184 if (strncmp(sid_str, "S-1-5", 5)) {
1185 fprintf(stderr, "Does not conform to S-1-5...: %s\n", sid_str);
1186 return 0;
1189 /* We only allow strings of form S-1-5... */
1191 (*sid)->ver = 1;
1192 (*sid)->auth[5] = 5;
1194 lstr = sid_str + 5;
1196 while (1) {
1197 if (!lstr || !lstr[0] || sscanf(lstr, "-%u", &auth) == 0) {
1198 if (i < 1) {
1199 fprintf(stderr, "Not of form -d-d...: %s, %u\n", lstr, i);
1200 return 0;
1202 (*sid)->auths=i;
1203 return 1;
1206 (*sid)->sub_auths[i] = auth;
1207 i++;
1208 lstr = strchr(lstr + 1, '-');
1211 return 1;
1215 * Create an ACE
1217 ACE *nt_create_ace(int type, int flags, unsigned int perms, char *sid)
1219 ACE *ace;
1221 ace = (ACE *)malloc(sizeof(ACE));
1222 if (!ace) goto error;
1223 ace->type = type;
1224 ace->flags = flags;
1225 ace->perms = perms;
1226 if (!string_to_sid(&ace->trustee, sid))
1227 goto error;
1228 return ace;
1230 error:
1231 if (ace) nt_delete_ace(ace);
1232 return NULL;
1236 * Create a default ACL
1238 ACL *nt_create_default_acl(REGF *regf)
1240 ACL *acl;
1242 acl = (ACL *)malloc(sizeof(ACL) + 7*sizeof(ACE *));
1243 if (!acl) goto error;
1245 acl->rev = 2;
1246 acl->refcnt = 1;
1247 acl->num_aces = 8;
1249 acl->aces[0] = nt_create_ace(0x00, 0x0, 0xF003F, regf->owner_sid_str);
1250 if (!acl->aces[0]) goto error;
1251 acl->aces[1] = nt_create_ace(0x00, 0x0, 0xF003F, "S-1-5-18");
1252 if (!acl->aces[1]) goto error;
1253 acl->aces[2] = nt_create_ace(0x00, 0x0, 0xF003F, "S-1-5-32-544");
1254 if (!acl->aces[2]) goto error;
1255 acl->aces[3] = nt_create_ace(0x00, 0x0, 0x20019, "S-1-5-12");
1256 if (!acl->aces[3]) goto error;
1257 acl->aces[4] = nt_create_ace(0x00, 0x0B, 0x10000000, regf->owner_sid_str);
1258 if (!acl->aces[4]) goto error;
1259 acl->aces[5] = nt_create_ace(0x00, 0x0B, 0x10000000, "S-1-5-18");
1260 if (!acl->aces[5]) goto error;
1261 acl->aces[6] = nt_create_ace(0x00, 0x0B, 0x10000000, "S-1-5-32-544");
1262 if (!acl->aces[6]) goto error;
1263 acl->aces[7] = nt_create_ace(0x00, 0x0B, 0x80000000, "S-1-5-12");
1264 if (!acl->aces[7]) goto error;
1265 return acl;
1267 error:
1268 if (acl) nt_delete_acl(acl);
1269 return NULL;
1273 * Create a default security descriptor. We pull in things from env
1274 * if need be
1276 SEC_DESC *nt_create_def_sec_desc(REGF *regf)
1278 SEC_DESC *tmp;
1280 tmp = (SEC_DESC *)malloc(sizeof(SEC_DESC));
1281 if (!tmp) return NULL;
1283 tmp->rev = 1;
1284 tmp->type = 0x8004;
1285 if (!string_to_sid(&tmp->owner, "S-1-5-32-544")) goto error;
1286 if (!string_to_sid(&tmp->group, "S-1-5-18")) goto error;
1287 tmp->sacl = NULL;
1288 tmp->dacl = nt_create_default_acl(regf);
1290 return tmp;
1292 error:
1293 if (tmp) nt_delete_sec_desc(tmp);
1294 return NULL;
1298 * We will implement inheritence that is based on what the parent's SEC_DESC
1299 * says, but the Owner and Group SIDs can be overwridden from the command line
1300 * and additional ACEs can be applied from the command line etc.
1302 KEY_SEC_DESC *nt_inherit_security(REG_KEY *key)
1305 if (!key) return NULL;
1306 return key->security;
1310 * Create an initial security descriptor and init other structures, if needed
1311 * We assume that the initial security stuff is empty ...
1313 KEY_SEC_DESC *nt_create_init_sec(REGF *regf)
1315 KEY_SEC_DESC *tsec = NULL;
1317 tsec = (KEY_SEC_DESC *)malloc(sizeof(KEY_SEC_DESC));
1318 if (!tsec) return NULL;
1320 tsec->ref_cnt = 1;
1321 tsec->state = SEC_DESC_NBK;
1323 tsec->sec_desc = regf->def_sec_desc;
1325 return tsec;
1329 * Add a sub-key
1331 REG_KEY *nt_add_reg_key_list(REGF *regf, REG_KEY *key, char * name, int create)
1333 int i;
1334 REG_KEY *ret = NULL, *tmp = NULL;
1335 KEY_LIST *list;
1336 char *lname, *c1, *c2;
1338 if (!key || !name || !*name) return NULL;
1340 list = key->sub_keys;
1341 if (!list) { /* Create an empty list */
1343 list = (KEY_LIST *)malloc(sizeof(KEY_LIST) + (REG_KEY_LIST_SIZE - 1) * sizeof(REG_KEY *));
1344 list->key_count = 0;
1345 list->max_keys = REG_KEY_LIST_SIZE;
1349 lname = strdup(name);
1350 if (!lname) return NULL;
1352 c1 = lname;
1353 c2 = strchr(c1, '\\');
1354 if (c2) { /* Split here ... */
1355 *c2 = 0;
1356 c2++;
1359 for (i = 0; i < list->key_count; i++) {
1360 if (strcmp(list->keys[i]->name, c1) == 0) {
1361 ret = nt_add_reg_key_list(regf, list->keys[i], c2, create);
1362 free(lname);
1363 return ret;
1368 * If we reach here we could not find the the first component
1369 * so create it ...
1372 if (list->key_count < list->max_keys){
1373 list->key_count++;
1375 else { /* Create more space in the list ... */
1376 if (!(list = (KEY_LIST *)realloc(list, sizeof(KEY_LIST) +
1377 (list->max_keys + REG_KEY_LIST_SIZE - 1)
1378 * sizeof(REG_KEY *))));
1379 goto error;
1381 list->max_keys += REG_KEY_LIST_SIZE;
1382 list->key_count++;
1386 * add the new key at the new slot
1387 * FIXME: Sort the list someday
1391 * We want to create the key, and then do the rest
1394 tmp = (REG_KEY *)malloc(sizeof(REG_KEY));
1396 bzero(tmp, sizeof(REG_KEY));
1398 tmp->name = strdup(c1);
1399 if (!tmp->name) goto error;
1400 tmp->owner = key;
1401 tmp->type = REG_SUB_KEY;
1403 * Next, pull security from the parent, but override with
1404 * anything passed in on the command line
1406 tmp->security = nt_inherit_security(key);
1408 list->keys[list->key_count - 1] = tmp;
1410 if (c2) {
1411 ret = nt_add_reg_key_list(regf, key, c2, True);
1414 if (lname) free(lname);
1416 return ret;
1418 error:
1419 if (tmp) free(tmp);
1420 if (lname) free(lname);
1421 return NULL;
1425 * This routine only adds a key from the root down.
1426 * It calls helper functions to handle sub-key lists and sub-keys
1428 REG_KEY *nt_add_reg_key(REGF *regf, char *name, int create)
1430 char *lname = NULL, *c1, *c2;
1431 REG_KEY * tmp = NULL;
1434 * Look until we hit the first component that does not exist, and
1435 * then add from there. However, if the first component does not
1436 * match and the path we are given is the root, then it must match
1438 if (!regf || !name || !*name) return NULL;
1440 lname = strdup(name);
1441 if (!lname) return NULL;
1443 c1 = lname;
1444 c2 = strchr(c1, '\\');
1445 if (c2) { /* Split here ... */
1446 *c2 = 0;
1447 c2++;
1451 * If the root does not exist, create it and make it equal to the
1452 * first component ...
1455 if (!regf->root) {
1457 tmp = (REG_KEY *)malloc(sizeof(REG_KEY));
1458 if (!tmp) goto error;
1459 bzero(tmp, sizeof(REG_KEY));
1460 tmp->name = strdup(c1);
1461 if (!tmp->name) goto error;
1462 tmp->security = nt_create_init_sec(regf);
1463 if (!tmp->security) goto error;
1464 regf->root = tmp;
1467 else {
1469 * If we don't match, then we have to return error ...
1470 * If we do match on this component, check the next one in the
1471 * list, and if not found, add it ... short circuit, add all the
1472 * way down
1475 if (strcmp(c1, regf->root->name) != 0)
1476 goto error;
1479 tmp = nt_add_reg_key_list(regf, regf->root, c2, True);
1480 free(lname);
1481 return tmp;
1483 error:
1484 if (tmp) free(tmp);
1485 if (lname) free(lname);
1486 return NULL;
1490 * Load and unload a registry file.
1492 * Load, loads it into memory as a tree, while unload sealizes/flattens it
1496 * Get the starting record for NT Registry file
1500 * Where we keep all the regf stuff for one registry.
1501 * This is the structure that we use to tie the in memory tree etc
1502 * together. By keeping separate structs, we can operate on different
1503 * registries at the same time.
1504 * Currently, the SK_MAP is an array of mapping structure.
1505 * Since we only need this on input and output, we fill in the structure
1506 * as we go on input. On output, we know how many SK items we have, so
1507 * we can allocate the structure as we need to.
1508 * If you add stuff here that is dynamically allocated, add the
1509 * appropriate free statements below.
1512 #define REGF_REGTYPE_NONE 0
1513 #define REGF_REGTYPE_NT 1
1514 #define REGF_REGTYPE_W9X 2
1516 #define TTTONTTIME(r, t1, t2) (r)->last_mod_time.low = (t1); \
1517 (r)->last_mod_time.high = (t2);
1519 #define REGF_HDR_BLKSIZ 0x1000
1521 #define OFF(f) ((f) + REGF_HDR_BLKSIZ + 4)
1522 #define LOCN(base, f) ((base) + OFF(f))
1524 const VAL_STR reg_type_names[] = {
1525 { REG_TYPE_REGSZ, "REG_SZ" },
1526 { REG_TYPE_EXPANDSZ, "REG_EXPAND_SZ" },
1527 { REG_TYPE_BIN, "REG_BIN" },
1528 { REG_TYPE_DWORD, "REG_DWORD" },
1529 { REG_TYPE_MULTISZ, "REG_MULTI_SZ" },
1530 { 0, NULL },
1533 const char *val_to_str(unsigned int val, const VAL_STR *val_array)
1535 int i = 0;
1537 if (!val_array) return NULL;
1539 while (val_array[i].val && val_array[i].str) {
1541 if (val_array[i].val == val) return val_array[i].str;
1542 i++;
1546 return NULL;
1551 * Convert from UniCode to Ascii ... Does not take into account other lang
1552 * Restrict by ascii_max if > 0
1554 int uni_to_ascii(unsigned char *uni, unsigned char *ascii, int ascii_max,
1555 int uni_max)
1557 int i = 0;
1559 while (i < ascii_max && !(!uni[i*2] && !uni[i*2+1])) {
1560 if (uni_max > 0 && (i*2) >= uni_max) break;
1561 ascii[i] = uni[i*2];
1562 i++;
1566 ascii[i] = '\0';
1568 return i;
1572 * Convert a data value to a string for display
1574 int data_to_ascii(unsigned char *datap, int len, int type, char *ascii, int ascii_max)
1576 unsigned char *asciip;
1577 int i;
1579 switch (type) {
1580 case REG_TYPE_REGSZ:
1581 if (verbose) fprintf(stderr, "Len: %d\n", len);
1582 /* FIXME. This has to be fixed. It has to be UNICODE */
1583 return uni_to_ascii(datap, ascii, len, ascii_max);
1584 break;
1586 case REG_TYPE_EXPANDSZ:
1587 return uni_to_ascii(datap, ascii, len, ascii_max);
1588 break;
1590 case REG_TYPE_BIN:
1591 asciip = ascii;
1592 for (i=0; (i<len)&&(i+1)*3<ascii_max; i++) {
1593 int str_rem = ascii_max - ((int)asciip - (int)ascii);
1594 asciip += snprintf(asciip, str_rem, "%02x", *(unsigned char *)(datap+i));
1595 if (i < len && str_rem > 0)
1596 *asciip = ' '; asciip++;
1598 *asciip = '\0';
1599 return ((int)asciip - (int)ascii);
1600 break;
1602 case REG_TYPE_DWORD:
1603 if (*(int *)datap == 0)
1604 return snprintf(ascii, ascii_max, "0");
1605 else
1606 return snprintf(ascii, ascii_max, "0x%x", *(int *)datap);
1607 break;
1609 case REG_TYPE_MULTISZ:
1611 break;
1613 default:
1614 return 0;
1615 break;
1618 return len;
1622 REG_KEY *nt_get_key_tree(REGF *regf, NK_HDR *nk_hdr, int size, REG_KEY *parent);
1624 int nt_set_regf_input_file(REGF *regf, char *filename)
1626 return ((regf->regfile_name = strdup(filename)) != NULL);
1629 int nt_set_regf_output_file(REGF *regf, char *filename)
1631 return ((regf->outfile_name = strdup(filename)) != NULL);
1634 /* Create a regf structure and init it */
1636 REGF *nt_create_regf(void)
1638 REGF *tmp = (REGF *)malloc(sizeof(REGF));
1639 if (!tmp) return tmp;
1640 bzero(tmp, sizeof(REGF));
1641 tmp->owner_sid_str = def_owner_sid_str;
1642 return tmp;
1645 /* Free all the bits and pieces ... Assumes regf was malloc'd */
1646 /* If you add stuff to REGF, add the relevant free bits here */
1647 int nt_free_regf(REGF *regf)
1649 if (!regf) return 0;
1651 if (regf->regfile_name) free(regf->regfile_name);
1652 if (regf->outfile_name) free(regf->outfile_name);
1654 nt_delete_reg_key(regf->root, False); /* Free the tree */
1655 free(regf->sk_map);
1656 regf->sk_count = regf->sk_map_size = 0;
1658 free(regf);
1660 return 1;
1663 /* Get the header of the registry. Return a pointer to the structure
1664 * If the mmap'd area has not been allocated, then mmap the input file
1666 REGF_HDR *nt_get_regf_hdr(REGF *regf)
1668 if (!regf)
1669 return NULL; /* What about errors */
1671 if (!regf->regfile_name)
1672 return NULL; /* What about errors */
1674 if (!regf->base) { /* Try to mmap etc the file */
1676 if ((regf->fd = open(regf->regfile_name, O_RDONLY, 0000)) <0) {
1677 return NULL; /* What about errors? */
1680 if (fstat(regf->fd, &regf->sbuf) < 0) {
1681 return NULL;
1684 regf->base = mmap(0, regf->sbuf.st_size, PROT_READ, MAP_SHARED, regf->fd, 0);
1686 if ((int)regf->base == 1) {
1687 fprintf(stderr, "Could not mmap file: %s, %s\n", regf->regfile_name,
1688 strerror(errno));
1689 return NULL;
1694 * At this point, regf->base != NULL, and we should be able to read the
1695 * header
1698 assert(regf->base != NULL);
1700 return (REGF_HDR *)regf->base;
1704 * Validate a regf header
1705 * For now, do nothing, but we should check the checksum
1707 int valid_regf_hdr(REGF_HDR *regf_hdr)
1709 if (!regf_hdr) return 0;
1711 return 1;
1715 * Process an SK header ...
1716 * Every time we see a new one, add it to the map. Otherwise, just look it up.
1717 * We will do a simple linear search for the moment, since many KEYs have the
1718 * same security descriptor.
1719 * We allocate the map in increments of 10 entries.
1723 * Create a new entry in the map, and increase the size of the map if needed
1726 SK_MAP *alloc_sk_map_entry(REGF *regf, KEY_SEC_DESC *tmp, int sk_off)
1728 if (!regf->sk_map) { /* Allocate a block of 10 */
1729 regf->sk_map = (SK_MAP *)malloc(sizeof(SK_MAP) * 10);
1730 if (!regf->sk_map) {
1731 free(tmp);
1732 return NULL;
1734 regf->sk_map_size = 10;
1735 regf->sk_count = 1;
1736 (regf->sk_map)[0].sk_off = sk_off;
1737 (regf->sk_map)[0].key_sec_desc = tmp;
1739 else { /* Simply allocate a new slot, unless we have to expand the list */
1740 int ndx = regf->sk_count;
1741 if (regf->sk_count >= regf->sk_map_size) {
1742 regf->sk_map = (SK_MAP *)realloc(regf->sk_map,
1743 (regf->sk_map_size + 10)*sizeof(SK_MAP));
1744 if (!regf->sk_map) {
1745 free(tmp);
1746 return NULL;
1749 * ndx already points at the first entry of the new block
1751 regf->sk_map_size += 10;
1753 (regf->sk_map)[ndx].sk_off = sk_off;
1754 (regf->sk_map)[ndx].key_sec_desc = tmp;
1755 regf->sk_count++;
1757 return regf->sk_map;
1761 * Search for a KEY_SEC_DESC in the sk_map, but don't create one if not
1762 * found
1765 KEY_SEC_DESC *lookup_sec_key(SK_MAP *sk_map, int count, int sk_off)
1767 int i;
1769 if (!sk_map) return NULL;
1771 for (i = 0; i < count; i++) {
1773 if (sk_map[i].sk_off == sk_off)
1774 return sk_map[i].key_sec_desc;
1778 return NULL;
1783 * Allocate a KEY_SEC_DESC if we can't find one in the map
1786 KEY_SEC_DESC *lookup_create_sec_key(REGF *regf, SK_MAP *sk_map, int sk_off)
1788 KEY_SEC_DESC *tmp = lookup_sec_key(regf->sk_map, regf->sk_count, sk_off);
1790 if (tmp) {
1791 return tmp;
1793 else { /* Allocate a new one */
1794 tmp = (KEY_SEC_DESC *)malloc(sizeof(KEY_SEC_DESC));
1795 if (!tmp) {
1796 return NULL;
1798 tmp->state = SEC_DESC_RES;
1799 if (!alloc_sk_map_entry(regf, tmp, sk_off)) {
1800 return NULL;
1802 return tmp;
1807 * Allocate storage and duplicate a SID
1808 * We could allocate the SID to be only the size needed, but I am too lazy.
1810 DOM_SID *dup_sid(DOM_SID *sid)
1812 DOM_SID *tmp = (DOM_SID *)malloc(sizeof(DOM_SID));
1813 int i;
1815 if (!tmp) return NULL;
1816 tmp->ver = sid->ver;
1817 tmp->auths = sid->auths;
1818 for (i=0; i<6; i++) {
1819 tmp->auth[i] = sid->auth[i];
1821 for (i=0; i<tmp->auths&&i<MAXSUBAUTHS; i++) {
1822 tmp->sub_auths[i] = sid->sub_auths[i];
1824 return tmp;
1828 * Allocate space for an ACE and duplicate the registry encoded one passed in
1830 ACE *dup_ace(REG_ACE *ace)
1832 ACE *tmp = NULL;
1834 tmp = (ACE *)malloc(sizeof(ACE));
1836 if (!tmp) return NULL;
1838 tmp->type = CVAL(&ace->type);
1839 tmp->flags = CVAL(&ace->flags);
1840 tmp->perms = IVAL(&ace->perms);
1841 tmp->trustee = dup_sid(&ace->trustee);
1842 return tmp;
1846 * Allocate space for an ACL and duplicate the registry encoded one passed in
1848 ACL *dup_acl(REG_ACL *acl)
1850 ACL *tmp = NULL;
1851 REG_ACE* ace;
1852 int i, num_aces;
1854 num_aces = IVAL(&acl->num_aces);
1856 tmp = (ACL *)malloc(sizeof(ACL) + (num_aces - 1)*sizeof(ACE *));
1857 if (!tmp) return NULL;
1859 tmp->num_aces = num_aces;
1860 tmp->refcnt = 1;
1861 tmp->rev = SVAL(&acl->rev);
1862 if (verbose) fprintf(stdout, "ACL: refcnt: %u, rev: %u\n", tmp->refcnt,
1863 tmp->rev);
1864 ace = (REG_ACE *)&acl->aces;
1865 for (i=0; i<num_aces; i++) {
1866 tmp->aces[i] = dup_ace(ace);
1867 ace = (REG_ACE *)((char *)ace + SVAL(&ace->length));
1868 /* XXX: FIXME, should handle malloc errors */
1871 return tmp;
1874 SEC_DESC *process_sec_desc(REGF *regf, REG_SEC_DESC *sec_desc)
1876 SEC_DESC *tmp = NULL;
1878 tmp = (SEC_DESC *)malloc(sizeof(SEC_DESC));
1880 if (!tmp) {
1881 return NULL;
1884 tmp->rev = SVAL(&sec_desc->rev);
1885 tmp->type = SVAL(&sec_desc->type);
1886 if (verbose) fprintf(stdout, "SEC_DESC Rev: %0X, Type: %0X\n",
1887 tmp->rev, tmp->type);
1888 tmp->owner = dup_sid((DOM_SID *)((char *)sec_desc + IVAL(&sec_desc->owner_off)));
1889 if (!tmp->owner) {
1890 free(tmp);
1891 return NULL;
1893 tmp->group = dup_sid((DOM_SID *)((char *)sec_desc + IVAL(&sec_desc->group_off)));
1894 if (!tmp->group) {
1895 free(tmp);
1896 return NULL;
1899 /* Now pick up the SACL and DACL */
1901 if (sec_desc->sacl_off)
1902 tmp->sacl = dup_acl((REG_ACL *)((char *)sec_desc + IVAL(&sec_desc->sacl_off)));
1903 else
1904 tmp->sacl = NULL;
1906 if (sec_desc->dacl_off)
1907 tmp->dacl = dup_acl((REG_ACL *)((char *)sec_desc + IVAL(&sec_desc->dacl_off)));
1908 else
1909 tmp->dacl = NULL;
1911 return tmp;
1914 KEY_SEC_DESC *process_sk(REGF *regf, SK_HDR *sk_hdr, int sk_off, int size)
1916 KEY_SEC_DESC *tmp = NULL;
1917 int sk_next_off, sk_prev_off, sk_size;
1918 REG_SEC_DESC *sec_desc;
1920 if (!sk_hdr) return NULL;
1922 if (SVAL(&sk_hdr->SK_ID) != REG_SK_ID) {
1923 fprintf(stderr, "Unrecognized SK Header ID: %08X, %s\n", (int)sk_hdr,
1924 regf->regfile_name);
1925 return NULL;
1928 if (-size < (sk_size = IVAL(&sk_hdr->rec_size))) {
1929 fprintf(stderr, "Incorrect SK record size: %d vs %d. %s\n",
1930 -size, sk_size, regf->regfile_name);
1931 return NULL;
1935 * Now, we need to look up the SK Record in the map, and return it
1936 * Since the map contains the SK_OFF mapped to KEY_SEC_DESC, we can
1937 * use that
1940 if (regf->sk_map &&
1941 ((tmp = lookup_sec_key(regf->sk_map, regf->sk_count, sk_off)) != NULL)
1942 && (tmp->state == SEC_DESC_OCU)) {
1943 tmp->ref_cnt++;
1944 return tmp;
1947 /* Here, we have an item in the map that has been reserved, or tmp==NULL. */
1949 assert(tmp == NULL || (tmp && tmp->state != SEC_DESC_NON));
1952 * Now, allocate a KEY_SEC_DESC, and parse the structure here, and add the
1953 * new KEY_SEC_DESC to the mapping structure, since the offset supplied is
1954 * the actual offset of structure. The same offset will be used by
1955 * all future references to this structure
1956 * We could put all this unpleasantness in a function.
1959 if (!tmp) {
1960 tmp = (KEY_SEC_DESC *)malloc(sizeof(KEY_SEC_DESC));
1961 if (!tmp) return NULL;
1962 bzero(tmp, sizeof(KEY_SEC_DESC));
1965 * Allocate an entry in the SK_MAP ...
1966 * We don't need to free tmp, because that is done for us if the
1967 * sm_map entry can't be expanded when we need more space in the map.
1970 if (!alloc_sk_map_entry(regf, tmp, sk_off)) {
1971 return NULL;
1975 tmp->ref_cnt++;
1976 tmp->state = SEC_DESC_OCU;
1979 * Now, process the actual sec desc and plug the values in
1982 sec_desc = (REG_SEC_DESC *)&sk_hdr->sec_desc[0];
1983 tmp->sec_desc = process_sec_desc(regf, sec_desc);
1986 * Now forward and back links. Here we allocate an entry in the sk_map
1987 * if it does not exist, and mark it reserved
1990 sk_prev_off = IVAL(&sk_hdr->prev_off);
1991 tmp->prev = lookup_create_sec_key(regf, regf->sk_map, sk_prev_off);
1992 assert(tmp->prev != NULL);
1993 sk_next_off = IVAL(&sk_hdr->next_off);
1994 tmp->next = lookup_create_sec_key(regf, regf->sk_map, sk_next_off);
1995 assert(tmp->next != NULL);
1997 return tmp;
2001 * Process a VK header and return a value
2003 VAL_KEY *process_vk(REGF *regf, VK_HDR *vk_hdr, int size)
2005 char val_name[1024];
2006 int nam_len, dat_len, flag, dat_type, dat_off, vk_id;
2007 const char *val_type;
2008 VAL_KEY *tmp = NULL;
2010 if (!vk_hdr) return NULL;
2012 if ((vk_id = SVAL(&vk_hdr->VK_ID)) != REG_VK_ID) {
2013 fprintf(stderr, "Unrecognized VK header ID: %0X, block: %0X, %s\n",
2014 vk_id, (int)vk_hdr, regf->regfile_name);
2015 return NULL;
2018 nam_len = SVAL(&vk_hdr->nam_len);
2019 val_name[nam_len] = '\0';
2020 flag = SVAL(&vk_hdr->flag);
2021 dat_type = IVAL(&vk_hdr->dat_type);
2022 dat_len = IVAL(&vk_hdr->dat_len); /* If top bit, offset contains data */
2023 dat_off = IVAL(&vk_hdr->dat_off);
2025 tmp = (VAL_KEY *)malloc(sizeof(VAL_KEY));
2026 if (!tmp) {
2027 goto error;
2029 bzero(tmp, sizeof(VAL_KEY));
2030 tmp->has_name = flag;
2031 tmp->data_type = dat_type;
2033 if (flag & 0x01) {
2034 strncpy(val_name, vk_hdr->dat_name, nam_len);
2035 tmp->name = strdup(val_name);
2036 if (!tmp->name) {
2037 goto error;
2040 else
2041 strncpy(val_name, "<No Name>", 10);
2044 * Allocate space and copy the data as a BLOB
2047 if (dat_len) {
2049 char *dtmp = (char *)malloc(dat_len&0x7FFFFFFF);
2051 if (!dtmp) {
2052 goto error;
2055 tmp->data_blk = dtmp;
2057 if ((dat_len&0x80000000) == 0) { /* The data is pointed to by the offset */
2058 char *dat_ptr = LOCN(regf->base, dat_off);
2059 bcopy(dat_ptr, dtmp, dat_len);
2061 else { /* The data is in the offset or type */
2063 * FIXME.
2064 * Some registry files seem to have wierd fields. If top bit is set,
2065 * but len is 0, the type seems to be the value ...
2066 * Not sure how to handle this last type for the moment ...
2068 dat_len = dat_len & 0x7FFFFFFF;
2069 bcopy(&dat_off, dtmp, dat_len);
2072 tmp->data_len = dat_len;
2075 val_type = val_to_str(dat_type, reg_type_names);
2078 * We need to save the data area as well
2081 if (verbose) fprintf(stdout, " %s : %s : \n", val_name, val_type);
2083 return tmp;
2085 error:
2086 if (tmp) nt_delete_val_key(tmp);
2087 return NULL;
2092 * Process a VL Header and return a list of values
2094 VAL_LIST *process_vl(REGF *regf, VL_TYPE vl, int count, int size)
2096 int i, vk_off;
2097 VK_HDR *vk_hdr;
2098 VAL_LIST *tmp = NULL;
2100 if (!vl) return NULL;
2102 if (-size < (count+1)*sizeof(int)){
2103 fprintf(stderr, "Error in VL header format. Size less than space required. %d\n", -size);
2104 return NULL;
2107 tmp = (VAL_LIST *)malloc(sizeof(VAL_LIST) + (count - 1) * sizeof(VAL_KEY *));
2108 if (!tmp) {
2109 goto error;
2112 for (i=0; i<count; i++) {
2113 vk_off = IVAL(&vl[i]);
2114 vk_hdr = (VK_HDR *)LOCN(regf->base, vk_off);
2115 tmp->vals[i] = process_vk(regf, vk_hdr, BLK_SIZE(vk_hdr));
2116 if (!tmp->vals[i]){
2117 goto error;
2121 tmp->val_count = count;
2122 tmp->max_vals = count;
2124 return tmp;
2126 error:
2127 /* XXX: FIXME, free the partially allocated structure */
2128 return NULL;
2132 * Process an LF Header and return a list of sub-keys
2134 KEY_LIST *process_lf(REGF *regf, LF_HDR *lf_hdr, int size, REG_KEY *parent)
2136 int count, i, nk_off;
2137 unsigned int lf_id;
2138 KEY_LIST *tmp;
2140 if (!lf_hdr) return NULL;
2142 if ((lf_id = SVAL(&lf_hdr->LF_ID)) != REG_LF_ID) {
2143 fprintf(stderr, "Unrecognized LF Header format: %0X, Block: %0X, %s.\n",
2144 lf_id, (int)lf_hdr, regf->regfile_name);
2145 return NULL;
2148 assert(size < 0);
2150 count = SVAL(&lf_hdr->key_count);
2151 if (verbose) fprintf(stdout, "Key Count: %u\n", count);
2152 if (count <= 0) return NULL;
2154 /* Now, we should allocate a KEY_LIST struct and fill it in ... */
2156 tmp = (KEY_LIST *)malloc(sizeof(KEY_LIST) + (count - 1) * sizeof(REG_KEY *));
2157 if (!tmp) {
2158 goto error;
2161 tmp->key_count = count;
2162 tmp->max_keys = count;
2164 for (i=0; i<count; i++) {
2165 NK_HDR *nk_hdr;
2167 nk_off = IVAL(&lf_hdr->hr[i].nk_off);
2168 if (verbose) fprintf(stdout, "NK Offset: %0X\n", nk_off);
2169 nk_hdr = (NK_HDR *)LOCN(regf->base, nk_off);
2170 tmp->keys[i] = nt_get_key_tree(regf, nk_hdr, BLK_SIZE(nk_hdr), parent);
2171 if (!tmp->keys[i]) {
2172 goto error;
2176 return tmp;
2178 error:
2179 if (tmp) nt_delete_key_list(tmp, False);
2180 return NULL;
2184 * This routine is passed an NK_HDR pointer and retrieves the entire tree
2185 * from there down. It returns a REG_KEY *.
2187 REG_KEY *nt_get_key_tree(REGF *regf, NK_HDR *nk_hdr, int size, REG_KEY *parent)
2189 REG_KEY *tmp = NULL, *own;
2190 int name_len, clsname_len, lf_off, val_off, val_count, sk_off, own_off;
2191 unsigned int nk_id;
2192 LF_HDR *lf_hdr;
2193 VL_TYPE *vl;
2194 SK_HDR *sk_hdr;
2195 char key_name[1024], cls_name[1024];
2197 if (!nk_hdr) return NULL;
2199 if ((nk_id = SVAL(&nk_hdr->NK_ID)) != REG_NK_ID) {
2200 fprintf(stderr, "Unrecognized NK Header format: %08X, Block: %0X. %s\n",
2201 nk_id, (int)nk_hdr, regf->regfile_name);
2202 return NULL;
2205 assert(size < 0);
2207 name_len = SVAL(&nk_hdr->nam_len);
2208 clsname_len = SVAL(&nk_hdr->clsnam_len);
2211 * The value of -size should be ge
2212 * (sizeof(NK_HDR) - 1 + name_len)
2213 * The -1 accounts for the fact that we included the first byte of
2214 * the name in the structure. clsname_len is the length of the thing
2215 * pointed to by clsnam_off
2218 if (-size < (sizeof(NK_HDR) - 1 + name_len)) {
2219 fprintf(stderr, "Incorrect NK_HDR size: %d, %0X\n", -size, (int)nk_hdr);
2220 fprintf(stderr, "Sizeof NK_HDR: %d, name_len %d, clsname_len %d\n",
2221 sizeof(NK_HDR), name_len, clsname_len);
2222 /*return NULL;*/
2225 if (verbose) fprintf(stdout, "NK HDR: Name len: %d, class name len: %d\n",
2226 name_len, clsname_len);
2228 /* Fish out the key name and process the LF list */
2230 assert(name_len < sizeof(key_name));
2232 /* Allocate the key struct now */
2233 tmp = (REG_KEY *)malloc(sizeof(REG_KEY));
2234 if (!tmp) return tmp;
2235 bzero(tmp, sizeof(REG_KEY));
2237 tmp->type = (SVAL(&nk_hdr->type)==0x2C?REG_ROOT_KEY:REG_SUB_KEY);
2239 strncpy(key_name, nk_hdr->key_nam, name_len);
2240 key_name[name_len] = '\0';
2242 if (verbose) fprintf(stdout, "Key name: %s\n", key_name);
2244 tmp->name = strdup(key_name);
2245 if (!tmp->name) {
2246 goto error;
2250 * Fish out the class name, it is in UNICODE, while the key name is
2251 * ASCII :-)
2254 if (clsname_len) { /* Just print in Ascii for now */
2255 char *clsnamep;
2256 int clsnam_off;
2258 clsnam_off = IVAL(&nk_hdr->clsnam_off);
2259 clsnamep = LOCN(regf->base, clsnam_off);
2260 if (verbose) fprintf(stdout, "Class Name Offset: %0X\n", clsnam_off);
2262 bzero(cls_name, clsname_len);
2263 uni_to_ascii(clsnamep, cls_name, sizeof(cls_name), clsname_len);
2266 * I am keeping class name as an ascii string for the moment.
2267 * That means it needs to be converted on output.
2268 * It will also piss off people who need Unicode/UTF-8 strings. Sorry.
2269 * XXX: FIXME
2272 tmp->class_name = strdup(cls_name);
2273 if (!tmp->class_name) {
2274 goto error;
2277 if (verbose) fprintf(stdout, " Class Name: %s\n", cls_name);
2282 * Process the owner offset ...
2285 own_off = IVAL(&nk_hdr->own_off);
2286 own = (REG_KEY *)LOCN(regf->base, own_off);
2287 if (verbose) fprintf(stdout, "Owner Offset: %0X\n", own_off);
2289 if (verbose) fprintf(stdout, " Owner locn: %0X, Our locn: %0X\n",
2290 (unsigned int)own, (unsigned int)nk_hdr);
2293 * We should verify that the owner field is correct ...
2294 * for now, we don't worry ...
2297 tmp->owner = parent;
2300 * If there are any values, process them here
2303 val_count = IVAL(&nk_hdr->val_cnt);
2304 if (verbose) fprintf(stdout, "Val Count: %d\n", val_count);
2305 if (val_count) {
2307 val_off = IVAL(&nk_hdr->val_off);
2308 vl = (VL_TYPE *)LOCN(regf->base, val_off);
2309 if (verbose) fprintf(stdout, "Val List Offset: %0X\n", val_off);
2311 tmp->values = process_vl(regf, *vl, val_count, BLK_SIZE(vl));
2312 if (!tmp->values) {
2313 goto error;
2319 * Also handle the SK header ...
2322 sk_off = IVAL(&nk_hdr->sk_off);
2323 sk_hdr = (SK_HDR *)LOCN(regf->base, sk_off);
2324 if (verbose) fprintf(stdout, "SK Offset: %0X\n", sk_off);
2326 if (sk_off != -1) {
2328 tmp->security = process_sk(regf, sk_hdr, sk_off, BLK_SIZE(sk_hdr));
2332 lf_off = IVAL(&nk_hdr->lf_off);
2333 if (verbose) fprintf(stdout, "SubKey list offset: %0X\n", lf_off);
2336 * No more subkeys if lf_off == -1
2339 if (lf_off != -1) {
2341 lf_hdr = (LF_HDR *)LOCN(regf->base, lf_off);
2343 tmp->sub_keys = process_lf(regf, lf_hdr, BLK_SIZE(lf_hdr), tmp);
2344 if (!tmp->sub_keys){
2345 goto error;
2350 return tmp;
2352 error:
2353 if (tmp) nt_delete_reg_key(tmp, False);
2354 return NULL;
2357 int nt_load_registry(REGF *regf)
2359 REGF_HDR *regf_hdr;
2360 unsigned int regf_id, hbin_id;
2361 HBIN_HDR *hbin_hdr;
2362 NK_HDR *first_key;
2364 /* Get the header */
2366 if ((regf_hdr = nt_get_regf_hdr(regf)) == NULL) {
2367 return -1;
2370 /* Now process that header and start to read the rest in */
2372 if ((regf_id = IVAL(&regf_hdr->REGF_ID)) != REG_REGF_ID) {
2373 fprintf(stderr, "Unrecognized NT registry header id: %0X, %s\n",
2374 regf_id, regf->regfile_name);
2375 return -1;
2379 * Validate the header ...
2381 if (!valid_regf_hdr(regf_hdr)) {
2382 fprintf(stderr, "Registry file header does not validate: %s\n",
2383 regf->regfile_name);
2384 return -1;
2387 /* Update the last mod date, and then go get the first NK record and on */
2389 TTTONTTIME(regf, IVAL(&regf_hdr->tim1), IVAL(&regf_hdr->tim2));
2392 * The hbin hdr seems to be just uninteresting garbage. Check that
2393 * it is there, but that is all.
2396 hbin_hdr = (HBIN_HDR *)(regf->base + REGF_HDR_BLKSIZ);
2398 if ((hbin_id = IVAL(&hbin_hdr->HBIN_ID)) != REG_HBIN_ID) {
2399 fprintf(stderr, "Unrecognized registry hbin hdr ID: %0X, %s\n",
2400 hbin_id, regf->regfile_name);
2401 return -1;
2405 * Get a pointer to the first key from the hreg_hdr
2408 if (verbose) fprintf(stdout, "First Key: %0X\n",
2409 IVAL(&regf_hdr->first_key));
2411 first_key = (NK_HDR *)LOCN(regf->base, IVAL(&regf_hdr->first_key));
2412 if (verbose) fprintf(stdout, "First Key Offset: %0X\n",
2413 IVAL(&regf_hdr->first_key));
2415 if (verbose) fprintf(stdout, "Data Block Size: %d\n",
2416 IVAL(&regf_hdr->dblk_size));
2418 if (verbose) fprintf(stdout, "Offset to next hbin block: %0X\n",
2419 IVAL(&hbin_hdr->next_off));
2421 if (verbose) fprintf(stdout, "HBIN block size: %0X\n",
2422 IVAL(&hbin_hdr->blk_size));
2425 * Now, get the registry tree by processing that NK recursively
2428 regf->root = nt_get_key_tree(regf, first_key, BLK_SIZE(first_key), NULL);
2430 assert(regf->root != NULL);
2433 * Unmap the registry file, as we might want to read in another
2434 * tree etc.
2437 if (regf->base) munmap(regf->base, regf->sbuf.st_size);
2438 regf->base = NULL;
2439 close(regf->fd); /* Ignore the error :-) */
2441 return 1;
2445 * Allocate a new hbin block, set up the header for the block etc
2447 HBIN_BLK *nt_create_hbin_blk(REGF *regf, int size)
2449 HBIN_BLK *tmp;
2451 if (!regf || !size) return NULL;
2453 /* Round size up to multiple of REGF_HDR_BLKSIZ */
2455 size = (size + (REGF_HDR_BLKSIZ - 1)) & ~(REGF_HDR_BLKSIZ - 1);
2457 tmp = (HBIN_BLK *)malloc(sizeof(HBIN_BLK));
2458 bzero(tmp, sizeof(HBIN_BLK));
2460 tmp->data = malloc(size);
2461 if (!tmp->data) goto error;
2463 bzero(tmp->data, size); /* Make it pristine */
2465 tmp->size = size;
2466 tmp->file_offset = regf->blk_tail->file_offset + regf->blk_tail->size;
2468 tmp->free_space = size - (sizeof(HBIN_HDR) - sizeof(HBIN_SUB_HDR));
2469 tmp->fsp_off = size - tmp->free_space;
2472 * Now link it in
2475 regf->blk_tail->next = tmp;
2476 regf->blk_tail = tmp;
2477 if (!regf->free_space) regf->free_space = tmp;
2479 return tmp;
2480 error:
2481 if (tmp) free(tmp);
2482 return NULL;
2486 * Allocate a unit of space ... and return a pointer as function param
2487 * and the block's offset as a side effect
2489 void *nt_alloc_regf_space(REGF *regf, int size, int *off)
2491 int tmp = 0;
2492 void *ret = NULL;
2493 HBIN_BLK *blk;
2495 if (!regf || !size || !off) return NULL;
2497 assert(regf->blk_head != NULL);
2500 * round up size to include header and then to 8-byte boundary
2502 size = (size + 4 + 7) & ~7;
2505 * Check if there is space, if none, grab a block
2507 if (!regf->free_space) {
2508 if (!nt_create_hbin_blk(regf, REGF_HDR_BLKSIZ))
2509 return NULL;
2513 * Now, chain down the list of blocks looking for free space
2516 for (blk = regf->free_space; blk != NULL; blk = blk->next) {
2517 if (blk->free_space <= size) {
2518 tmp = blk->file_offset + blk->fsp_off;
2519 ret = blk->data + blk->fsp_off;
2520 blk->free_space -= size;
2521 blk->fsp_off += size;
2524 * Fix up the free space ptr
2525 * If it is NULL, we fix it up next time
2528 if (!blk->free_space)
2529 regf->free_space = blk->next;
2531 *off = tmp;
2532 return ret;
2537 * If we got here, we need to add another block, which might be
2538 * larger than one block -- deal with that later
2540 if (nt_create_hbin_blk(regf, REGF_HDR_BLKSIZ)) {
2541 blk = regf->free_space;
2542 tmp = blk->file_offset + blk->fsp_off;
2543 ret = blk->data + blk->fsp_off;
2544 blk->free_space -= size;
2545 blk->fsp_off += 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 ret;
2559 return NULL;
2563 * Store a KEY in the file ...
2565 * We store this depth first, and defer storing the lf struct until
2566 * all the sub-keys have been stored.
2568 * We store the NK hdr, any SK header, class name, and VK structure, then
2569 * recurse down the LF structures ...
2571 int nt_store_reg_key(REGF *regf, REG_KEY *key)
2573 NK_HDR *nk_hdr;
2575 return 0;
2579 * Store the registry header ...
2580 * We actually create the registry header block and link it to the chain
2581 * of output blocks.
2583 REGF_HDR *nt_get_reg_header(REGF *regf)
2585 HBIN_BLK *tmp = NULL;
2587 tmp = (HBIN_BLK *)malloc(sizeof(HBIN_BLK));
2588 if (!tmp) return 0;
2590 bzero(tmp, sizeof(HBIN_BLK));
2591 tmp->type = REG_OUTBLK_HDR;
2592 tmp->size = REGF_HDR_BLKSIZ;
2593 tmp->data = malloc(REGF_HDR_BLKSIZ);
2594 if (!tmp->data) goto error;
2596 bzero(tmp->data, REGF_HDR_BLKSIZ); /* Make it pristine, unlike Windows */
2597 regf->blk_head = regf->blk_tail = tmp;
2599 return (REGF_HDR *)tmp->data;
2601 error:
2602 if (tmp) free(tmp);
2603 return NULL;
2607 * Store the registry in the output file
2608 * We write out the header and then each of the keys etc into the file
2609 * We have to flatten the data structure ...
2611 * The structures are stored in a depth-first fashion, with all records
2612 * aligned on 8-byte boundaries, with sub-keys and values layed down before
2613 * the lists that contain them. SK records are layed down first, however.
2614 * The lf fields are layed down after all sub-keys have been layed down, it
2615 * seems, including the whole tree associated with each sub-key.
2617 int nt_store_registry(REGF *regf)
2619 REGF_HDR *reg;
2620 NK_HDR *fkey;
2623 * Get a header ... and partially fill it in ...
2625 reg = nt_get_reg_header(regf);
2629 return 1;
2633 * Routines to parse a REGEDIT4 file
2635 * The file consists of:
2637 * REGEDIT4
2638 * \[[-]key-path\]\n
2639 * <value-spec>*
2641 * Format:
2642 * [cmd:]name=type:value
2644 * cmd = a|d|c|add|delete|change|as|ds|cs
2646 * There can be more than one key-path and value-spec.
2648 * Since we want to support more than one type of file format, we
2649 * construct a command-file structure that keeps info about the command file
2652 #define FMT_UNREC -1
2653 #define FMT_REGEDIT4 0
2654 #define FMT_EDITREG1_1 1
2656 #define FMT_STRING_REGEDIT4 "REGEDIT4"
2657 #define FMT_STRING_EDITREG1_0 "EDITREG1.0"
2659 #define CMD_NONE 0
2660 #define CMD_ADD_KEY 1
2661 #define CMD_DEL_KEY 2
2663 #define CMD_KEY 1
2664 #define CMD_VAL 2
2666 typedef struct val_spec_list {
2667 struct val_spec_list *next;
2668 char *name;
2669 int type;
2670 char *val; /* Kept as a char string, really? */
2671 } VAL_SPEC_LIST;
2673 typedef struct command_s {
2674 int cmd;
2675 char *key;
2676 int val_count;
2677 VAL_SPEC_LIST *val_spec_list, *val_spec_last;
2678 } CMD;
2680 typedef struct cmd_line {
2681 int len, line_len;
2682 char *line;
2683 } CMD_LINE;
2685 void free_val_spec_list(VAL_SPEC_LIST *vl)
2687 if (!vl) return;
2688 if (vl->name) free(vl->name);
2689 if (vl->val) free(vl->val);
2690 free(vl);
2695 * Some routines to handle lines of info in the command files
2697 void skip_to_eol(int fd)
2699 int rc;
2700 char ch = 0;
2702 while ((rc = read(fd, &ch, 1)) == 1) {
2703 if (ch == 0x0A) return;
2705 if (rc < 0) {
2706 fprintf(stderr, "Could not read file descriptor: %d, %s\n",
2707 fd, strerror(errno));
2708 exit(1);
2712 void free_cmd(CMD *cmd)
2714 if (!cmd) return;
2716 while (cmd->val_spec_list) {
2717 VAL_SPEC_LIST *tmp;
2719 tmp = cmd->val_spec_list;
2720 cmd->val_spec_list = tmp->next;
2721 free(tmp);
2724 free(cmd);
2728 void free_cmd_line(CMD_LINE *cmd_line)
2730 if (cmd_line) {
2731 if (cmd_line->line) free(cmd_line->line);
2732 free(cmd_line);
2736 void print_line(struct cmd_line *cl)
2738 char *pl;
2740 if (!cl) return;
2742 if ((pl = malloc(cl->line_len + 1)) == NULL) {
2743 fprintf(stderr, "Unable to allocate space to print line: %s\n",
2744 strerror(errno));
2745 exit(1);
2748 strncpy(pl, cl->line, cl->line_len);
2749 pl[cl->line_len] = 0;
2751 fprintf(stdout, "%s\n", pl);
2752 free(pl);
2755 #define INIT_ALLOC 10
2758 * Read a line from the input file.
2759 * NULL returned when EOF and no chars read
2760 * Otherwise we return a cmd_line *
2761 * Exit if other errors
2763 struct cmd_line *get_cmd_line(int fd)
2765 struct cmd_line *cl = (CMD_LINE *)malloc(sizeof(CMD_LINE));
2766 int i = 0, rc;
2767 unsigned char ch;
2769 if (!cl) {
2770 fprintf(stderr, "Unable to allocate structure for command line: %s\n",
2771 strerror(errno));
2772 exit(1);
2775 cl->len = INIT_ALLOC;
2778 * Allocate some space for the line. We extend later if needed.
2781 if ((cl->line = (char *)malloc(INIT_ALLOC)) == NULL) {
2782 fprintf(stderr, "Unable to allocate initial space for line: %s\n",
2783 strerror(errno));
2784 exit(1);
2788 * Now read in the chars to EOL. Don't store the EOL in the
2789 * line. What about CR?
2792 while ((rc = read(fd, &ch, 1)) == 1 && ch != '\n') {
2793 if (ch == '\r') continue; /* skip CR */
2794 if (i == cl->len) {
2796 * Allocate some more memory
2798 if ((cl->line = realloc(cl->line, cl->len + INIT_ALLOC)) == NULL) {
2799 fprintf(stderr, "Unable to realloc space for line: %s\n",
2800 strerror(errno));
2801 exit(1);
2803 cl->len += INIT_ALLOC;
2805 cl->line[i] = ch;
2806 i++;
2809 /* read 0 and we were at loc'n 0, return NULL */
2810 if (rc == 0 && i == 0) {
2811 free_cmd_line(cl);
2812 return NULL;
2815 cl->line_len = i;
2817 return cl;
2822 * parse_value: parse out a value. We pull it apart as:
2824 * <value> ::= <value-name>=<type>:<value-string>
2826 * <value-name> ::= char-string-without-spaces | '"' char-string '"'
2828 * If it parsed OK, return the <value-name> as a string, and the
2829 * value type and value-string in parameters.
2831 * The value name can be empty. There can only be one empty name in
2832 * a list of values. A value of - removes the value entirely.
2835 char *dup_str(char *s, int len)
2837 char *nstr;
2838 nstr = (char *)malloc(len + 1);
2839 if (nstr) {
2840 memcpy(nstr, s, len);
2841 nstr[len] = 0;
2843 return nstr;
2846 char *parse_name(char *nstr)
2848 int len = 0, start = 0;
2849 if (!nstr) return NULL;
2851 len = strlen(nstr);
2853 while (len && nstr[len - 1] == ' ') len--;
2855 nstr[len] = 0; /* Trim any spaces ... if there were none, doesn't matter */
2858 * Beginning and end should be '"' or neither should be so
2860 if ((nstr[0] == '"' && nstr[len - 1] != '"') ||
2861 (nstr[0] != '"' && nstr[len - 1] == '"'))
2862 return NULL;
2864 if (nstr[0] == '"') {
2865 start = 1;
2866 len -= 2;
2869 return dup_str(&nstr[start], len);
2872 int parse_value_type(char *tstr)
2874 int len = strlen(tstr);
2876 while (len && tstr[len - 1] == ' ') len--;
2877 tstr[len] = 0;
2879 if (strcmp(tstr, "REG_DWORD") == 0)
2880 return REG_TYPE_DWORD;
2881 else if (strcmp(tstr, "dword") == 0)
2882 return REG_TYPE_DWORD;
2883 else if (strcmp(tstr, "REG_EXPAND_SZ") == 0)
2884 return REG_TYPE_EXPANDSZ;
2885 else if (strcmp(tstr, "REG_BIN") == 0)
2886 return REG_TYPE_BIN;
2887 else if (strcmp(tstr, "REG_SZ") == 0)
2888 return REG_TYPE_REGSZ;
2889 else if (strcmp(tstr, "REG_MULTI_SZ") == 0)
2890 return REG_TYPE_MULTISZ;
2891 else if (strcmp(tstr, "-") == 0)
2892 return REG_TYPE_DELETE;
2894 return 0;
2897 char *parse_val_str(char *vstr)
2900 return dup_str(vstr, strlen(vstr));
2904 char *parse_value(struct cmd_line *cl, int *vtype, char **val)
2906 char *p1 = NULL, *p2 = NULL, *nstr = NULL, *tstr = NULL, *vstr = NULL;
2908 if (!cl || !vtype || !val) return NULL;
2909 if (!cl->line_len) return NULL;
2911 p1 = dup_str(cl->line, cl->line_len);
2912 /* FIXME: Better return codes etc ... */
2913 if (!p1) return NULL;
2914 p2 = strchr(p1, '=');
2915 if (!p2) return NULL;
2917 *p2 = 0; p2++; /* Split into two strings at p2 */
2919 /* Now, parse the name ... */
2921 nstr = parse_name(p1);
2922 if (!nstr) goto error;
2924 /* Now, split the remainder and parse on type and val ... */
2926 tstr = p2;
2927 while (*tstr == ' ') tstr++; /* Skip leading white space */
2928 p2 = strchr(p2, ':');
2930 if (p2) {
2931 *p2 = 0; p2++; /* split on the : */
2934 *vtype = parse_value_type(tstr);
2936 if (!vtype) goto error;
2938 if (!p2 || !*p2) return nstr;
2940 /* Now, parse the value string. It should return a newly malloc'd string */
2942 while (*p2 == ' ') p2++; /* Skip leading space */
2943 vstr = parse_val_str(p2);
2945 if (!vstr) goto error;
2947 *val = vstr;
2949 return nstr;
2951 error:
2952 if (p1) free(p1);
2953 if (nstr) free(nstr);
2954 if (vstr) free(vstr);
2955 return NULL;
2959 * Parse out a key. Look for a correctly formatted key [...]
2960 * and whether it is a delete or add? A delete is signalled
2961 * by a - in front of the key.
2962 * Assumes that there are no leading and trailing spaces
2965 char *parse_key(struct cmd_line *cl, int *cmd)
2967 int start = 1;
2968 char *tmp;
2970 if (cl->line[0] != '[' ||
2971 cl->line[cl->line_len - 1] != ']') return NULL;
2972 if (cl->line_len == 2) return NULL;
2973 *cmd = CMD_ADD_KEY;
2974 if (cl->line[1] == '-') {
2975 if (cl->line_len == 3) return NULL;
2976 start = 2;
2977 *cmd = CMD_DEL_KEY;
2979 tmp = malloc(cl->line_len - 1 - start + 1);
2980 if (!tmp) return tmp; /* Bail out on no mem ... FIXME */
2981 strncpy(tmp, &cl->line[start], cl->line_len - 1 - start);
2982 tmp[cl->line_len - 1 - start] = 0;
2983 return tmp;
2987 * Parse a line to determine if we have a key or a value
2988 * We only check for key or val ...
2991 int parse_line(struct cmd_line *cl)
2994 if (!cl || cl->len == 0) return 0;
2996 if (cl->line[0] == '[') /* No further checking for now */
2997 return CMD_KEY;
2998 else
2999 return CMD_VAL;
3003 * We seek to offset 0, read in the required number of bytes,
3004 * and compare to the correct value.
3005 * We then seek back to the original location
3007 int regedit4_file_type(int fd)
3009 int cur_ofs = 0;
3010 char desc[9];
3012 cur_ofs = lseek(fd, 0, SEEK_CUR); /* Get current offset */
3013 if (cur_ofs < 0) {
3014 fprintf(stderr, "Unable to get current offset: %s\n", strerror(errno));
3015 exit(1); /* FIXME */
3018 if (cur_ofs) {
3019 lseek(fd, 0, SEEK_SET);
3022 if (read(fd, desc, 8) < 8) {
3023 fprintf(stderr, "Unable to read command file format\n");
3024 exit(2); /* FIXME */
3027 desc[8] = 0;
3029 if (strcmp(desc, FMT_STRING_REGEDIT4) == 0) {
3030 if (cur_ofs) {
3031 lseek(fd, cur_ofs, SEEK_SET);
3033 else {
3034 skip_to_eol(fd);
3036 return FMT_REGEDIT4;
3039 return FMT_UNREC;
3043 * Run though the data in the line and strip anything after a comment
3044 * char.
3046 void strip_comment(struct cmd_line *cl)
3048 int i;
3050 if (!cl) return;
3052 for (i = 0; i < cl->line_len; i++) {
3053 if (cl->line[i] == ';') {
3054 cl->line_len = i;
3055 return;
3061 * trim leading space
3064 void trim_leading_spaces(struct cmd_line *cl)
3066 int i;
3068 if (!cl) return;
3070 for (i = 0; i < cl->line_len; i++) {
3071 if (cl->line[i] != ' '){
3072 if (i) memcpy(cl->line, &cl->line[i], cl->line_len - i);
3073 return;
3079 * trim trailing spaces
3081 void trim_trailing_spaces(struct cmd_line *cl)
3083 int i;
3085 if (!cl) return;
3087 for (i = cl->line_len; i == 0; i--) {
3088 if (cl->line[i-1] != ' ' &&
3089 cl->line[i-1] != '\t') {
3090 cl->line_len = i;
3096 * Get a command ... This consists of possibly multiple lines:
3097 * [key]
3098 * values*
3099 * possibly Empty line
3101 * value ::= <value-name>=<value-type>':'<value-string>
3102 * <value-name> is some path, possibly enclosed in quotes ...
3103 * We alctually look for the next key to terminate a previous key
3104 * if <value-type> == '-', then it is a delete type.
3106 CMD *regedit4_get_cmd(int fd)
3108 struct command_s *cmd = NULL;
3109 struct cmd_line *cl = NULL;
3110 struct val_spec_list *vl = NULL;
3112 if ((cmd = (struct command_s *)malloc(sizeof(struct command_s))) == NULL) {
3113 fprintf(stderr, "Unable to malloc space for command: %s\n",
3114 strerror(errno));
3115 exit(1);
3118 cmd->cmd = CMD_NONE;
3119 cmd->key = NULL;
3120 cmd->val_count = 0;
3121 cmd->val_spec_list = cmd->val_spec_last = NULL;
3122 while ((cl = get_cmd_line(fd))) {
3125 * If it is an empty command line, and we already have a key
3126 * then exit from here ... FIXME: Clean up the parser
3129 if (cl->line_len == 0 && cmd->key) {
3130 free_cmd_line(cl);
3131 break;
3134 strip_comment(cl); /* remove anything beyond a comment char */
3135 trim_trailing_spaces(cl);
3136 trim_leading_spaces(cl);
3138 if (cl->line_len == 0) { /* An empty line */
3139 free_cmd_line(cl);
3141 else { /* Else, non-empty ... */
3143 * Parse out the bits ...
3145 switch (parse_line(cl)) {
3146 case CMD_KEY:
3147 if ((cmd->key = parse_key(cl, &cmd->cmd)) == NULL) {
3148 fprintf(stderr, "Error parsing key from line: ");
3149 print_line(cl);
3150 fprintf(stderr, "\n");
3152 break;
3154 case CMD_VAL:
3156 * We need to add the value stuff to the list
3157 * There could be a \ on the end which we need to
3158 * handle at some time
3160 vl = (struct val_spec_list *)malloc(sizeof(struct val_spec_list));
3161 if (!vl) goto error;
3162 vl->next = NULL;
3163 vl->val = NULL;
3164 vl->name = parse_value(cl, &vl->type, &vl->val);
3165 if (!vl->name) goto error;
3166 if (cmd->val_spec_list == NULL) {
3167 cmd->val_spec_list = cmd->val_spec_last = vl;
3169 else {
3170 cmd->val_spec_last->next = vl;
3171 cmd->val_spec_last = vl;
3173 cmd->val_count++;
3174 break;
3176 default:
3177 fprintf(stderr, "Unrecognized line in command file: \n");
3178 print_line(cl);
3179 break;
3184 if (!cmd->cmd) goto error; /* End of file ... */
3186 return cmd;
3188 error:
3189 if (vl) free(vl);
3190 if (cmd) free_cmd(cmd);
3191 return NULL;
3194 int regedit4_exec_cmd(CMD *cmd)
3197 return 0;
3200 int editreg_1_0_file_type(int fd)
3202 int cur_ofs = 0;
3203 char desc[11];
3205 cur_ofs = lseek(fd, 0, SEEK_CUR); /* Get current offset */
3206 if (cur_ofs < 0) {
3207 fprintf(stderr, "Unable to get current offset: %s\n", strerror(errno));
3208 exit(1); /* FIXME */
3211 if (cur_ofs) {
3212 lseek(fd, 0, SEEK_SET);
3215 if (read(fd, desc, 10) < 10) {
3216 fprintf(stderr, "Unable to read command file format\n");
3217 exit(2); /* FIXME */
3220 desc[10] = 0;
3222 if (strcmp(desc, FMT_STRING_EDITREG1_0) == 0) {
3223 lseek(fd, cur_ofs, SEEK_SET);
3224 return FMT_REGEDIT4;
3227 return FMT_UNREC;
3230 CMD *editreg_1_0_get_cmd(int fd)
3232 return NULL;
3235 int editreg_1_0_exec_cmd(CMD *cmd)
3238 return -1;
3241 typedef struct command_ops_s {
3242 int type;
3243 int (*file_type)(int fd);
3244 CMD *(*get_cmd)(int fd);
3245 int (*exec_cmd)(CMD *cmd);
3246 } CMD_OPS;
3248 CMD_OPS default_cmd_ops[] = {
3249 {0, regedit4_file_type, regedit4_get_cmd, regedit4_exec_cmd},
3250 {1, editreg_1_0_file_type, editreg_1_0_get_cmd, editreg_1_0_exec_cmd},
3251 {-1, NULL, NULL, NULL}
3254 typedef struct command_file_s {
3255 char *name;
3256 int type, fd;
3257 CMD_OPS cmd_ops;
3258 } CMD_FILE;
3261 * Create a new command file structure
3264 CMD_FILE *cmd_file_create(char *file)
3266 CMD_FILE *tmp;
3267 struct stat sbuf;
3268 int i = 0;
3271 * Let's check if the file exists ...
3272 * No use creating the cmd_file structure if the file does not exist
3275 if (stat(file, &sbuf) < 0) { /* Not able to access file */
3277 return NULL;
3280 tmp = (CMD_FILE *)malloc(sizeof(CMD_FILE));
3281 if (!tmp) {
3282 return NULL;
3286 * Let's fill in some of the fields;
3289 tmp->name = strdup(file);
3291 if ((tmp->fd = open(file, O_RDONLY, 666)) < 0) {
3292 free(tmp);
3293 return NULL;
3297 * Now, try to find the format by indexing through the table
3299 while (default_cmd_ops[i].type != -1) {
3300 if ((tmp->type = default_cmd_ops[i].file_type(tmp->fd)) >= 0) {
3301 tmp->cmd_ops = default_cmd_ops[i];
3302 return tmp;
3304 i++;
3308 * If we got here, return NULL, as we could not figure out the type
3309 * of command file.
3311 * What about errors?
3314 free(tmp);
3315 return NULL;
3319 * Extract commands from the command file, and execute them.
3320 * We pass a table of command callbacks for that
3324 * Main code from here on ...
3328 * key print function here ...
3331 int print_key(const char *path, char *name, char *class_name, int root,
3332 int terminal, int vals)
3335 if (full_print || terminal) fprintf(stdout, "[%s%s]\n", path, name);
3337 return 1;
3341 * Sec Desc print functions
3344 void print_type(unsigned char type)
3346 switch (type) {
3347 case 0x00:
3348 fprintf(stdout, " ALLOW");
3349 break;
3350 case 0x01:
3351 fprintf(stdout, " DENY");
3352 break;
3353 case 0x02:
3354 fprintf(stdout, " AUDIT");
3355 break;
3356 case 0x03:
3357 fprintf(stdout, " ALARM");
3358 break;
3359 case 0x04:
3360 fprintf(stdout, "ALLOW CPD");
3361 break;
3362 case 0x05:
3363 fprintf(stdout, "OBJ ALLOW");
3364 break;
3365 case 0x06:
3366 fprintf(stdout, " OBJ DENY");
3367 default:
3368 fprintf(stdout, " UNKNOWN");
3369 break;
3373 void print_flags(unsigned char flags)
3375 char flg_output[21];
3376 int some = 0;
3378 flg_output[0] = 0;
3379 if (!flags) {
3380 fprintf(stdout, " ");
3381 return;
3383 if (flags & 0x01) {
3384 if (some) strcat(flg_output, ",");
3385 some = 1;
3386 strcat(flg_output, "OI");
3388 if (flags & 0x02) {
3389 if (some) strcat(flg_output, ",");
3390 some = 1;
3391 strcat(flg_output, "CI");
3393 if (flags & 0x04) {
3394 if (some) strcat(flg_output, ",");
3395 some = 1;
3396 strcat(flg_output, "NP");
3398 if (flags & 0x08) {
3399 if (some) strcat(flg_output, ",");
3400 some = 1;
3401 strcat(flg_output, "IO");
3403 if (flags & 0x10) {
3404 if (some) strcat(flg_output, ",");
3405 some = 1;
3406 strcat(flg_output, "IA");
3408 if (flags == 0xF) {
3409 if (some) strcat(flg_output, ",");
3410 some = 1;
3411 strcat(flg_output, "VI");
3413 fprintf(stdout, " %s", flg_output);
3416 void print_perms(int perms)
3418 fprintf(stdout, " %8X", perms);
3421 void print_sid(DOM_SID *sid)
3423 int i, comps = sid->auths;
3424 fprintf(stdout, "S-%u-%u", sid->ver, sid->auth[5]);
3426 for (i = 0; i < comps; i++) {
3428 fprintf(stdout, "-%u", sid->sub_auths[i]);
3431 fprintf(stdout, "\n");
3434 void print_acl(ACL *acl, char *prefix)
3436 int i;
3438 for (i = 0; i < acl->num_aces; i++) {
3439 fprintf(stdout, ";;%s", prefix);
3440 print_type(acl->aces[i]->type);
3441 print_flags(acl->aces[i]->flags);
3442 print_perms(acl->aces[i]->perms);
3443 fprintf(stdout, " ");
3444 print_sid(acl->aces[i]->trustee);
3448 int print_sec(SEC_DESC *sec_desc)
3450 if (!print_security) return 1;
3451 fprintf(stdout, ";; SECURITY\n");
3452 fprintf(stdout, ";; Owner: ");
3453 print_sid(sec_desc->owner);
3454 fprintf(stdout, ";; Group: ");
3455 print_sid(sec_desc->group);
3456 if (sec_desc->sacl) {
3457 fprintf(stdout, ";; SACL:\n");
3458 print_acl(sec_desc->sacl, " ");
3460 if (sec_desc->dacl) {
3461 fprintf(stdout, ";; DACL:\n");
3462 print_acl(sec_desc->dacl, " ");
3464 return 1;
3468 * Value print function here ...
3470 int print_val(const char *path, char *val_name, int val_type, int data_len,
3471 void *data_blk, int terminal, int first, int last)
3473 char data_asc[1024];
3475 bzero(data_asc, sizeof(data_asc));
3476 if (!terminal && first)
3477 fprintf(stdout, "%s\n", path);
3478 data_to_ascii((unsigned char *)data_blk, data_len, val_type, data_asc,
3479 sizeof(data_asc) - 1);
3480 fprintf(stdout, " %s = %s : %s\n", (val_name?val_name:"<No Name>"),
3481 val_to_str(val_type, reg_type_names), data_asc);
3482 return 1;
3485 void usage(void)
3487 fprintf(stderr, "Usage: editreg [-f] [-v] [-p] [-k] [-s] [-c <command-file>] <registryfile>\n");
3488 fprintf(stderr, "Version: 0.1\n\n");
3489 fprintf(stderr, "\n\t-v\t sets verbose mode");
3490 fprintf(stderr, "\n\t-f\t sets full print mode where non-terminals are printed");
3491 fprintf(stderr, "\n\t-p\t prints the registry");
3492 fprintf(stderr, "\n\t-s\t prints security descriptors");
3493 fprintf(stderr, "\n\t-c <command-file>\t specifies a command file");
3494 fprintf(stderr, "\n");
3497 int main(int argc, char *argv[])
3499 REGF *regf;
3500 extern char *optarg;
3501 extern int optind;
3502 int opt, print_keys = 0;
3503 int regf_opt = 1; /* Command name */
3504 int commands = 0;
3505 char *cmd_file_name = NULL;
3506 char *out_file_name = NULL;
3507 CMD_FILE *cmd_file = NULL;
3508 DOM_SID *lsid;
3510 if (argc < 2) {
3511 usage();
3512 exit(1);
3516 * Now, process the arguments
3519 while ((opt = getopt(argc, argv, "fspvko:O:c:")) != EOF) {
3520 switch (opt) {
3521 case 'c':
3522 commands = 1;
3523 cmd_file_name = optarg;
3524 regf_opt += 2;
3525 break;
3527 case 'f':
3528 full_print = 1;
3529 regf_opt++;
3530 break;
3532 case 'o':
3533 out_file_name = optarg;
3534 regf_opt += 2;
3535 break;
3537 case 'O':
3538 def_owner_sid_str = strdup(optarg);
3539 regf_opt += 2;
3540 if (!string_to_sid(&lsid, def_owner_sid_str)) {
3541 fprintf(stderr, "Default Owner SID: %s is incorrectly formatted\n",
3542 def_owner_sid_str);
3543 free(def_owner_sid_str);
3544 def_owner_sid_str = NULL;
3546 else
3547 nt_delete_sid(lsid);
3548 break;
3550 case 'p':
3551 print_keys++;
3552 regf_opt++;
3553 break;
3555 case 's':
3556 print_security++;
3557 full_print++;
3558 regf_opt++;
3559 break;
3561 case 'v':
3562 verbose++;
3563 regf_opt++;
3564 break;
3566 case 'k':
3567 regf_opt++;
3568 break;
3570 default:
3571 usage();
3572 exit(1);
3573 break;
3578 * We only want to complain about the lack of a default owner SID if
3579 * we need one. This approximates that need
3581 if (!def_owner_sid_str) {
3582 def_owner_sid_str = "S-1-5-21-1-2-3-4";
3583 if (out_file_name || verbose)
3584 fprintf(stderr, "Warning, default owner SID not set. Setting to %s\n",
3585 def_owner_sid_str);
3588 if ((regf = nt_create_regf()) == NULL) {
3589 fprintf(stderr, "Could not create registry object: %s\n", strerror(errno));
3590 exit(2);
3593 if (regf_opt < argc) { /* We have a registry file */
3594 if (!nt_set_regf_input_file(regf, argv[regf_opt])) {
3595 fprintf(stderr, "Could not set name of registry file: %s, %s\n",
3596 argv[regf_opt], strerror(errno));
3597 exit(3);
3600 /* Now, open it, and bring it into memory :-) */
3602 if (nt_load_registry(regf) < 0) {
3603 fprintf(stderr, "Could not load registry: %s\n", argv[1]);
3604 exit(4);
3608 if (out_file_name) {
3609 if (!nt_set_regf_output_file(regf, out_file_name)) {
3610 fprintf(stderr, "Could not set name of output registry file: %s, %s\n",
3611 out_file_name, strerror(errno));
3612 exit(3);
3617 if (commands) {
3618 CMD *cmd;
3620 cmd_file = cmd_file_create(cmd_file_name);
3622 while ((cmd = cmd_file->cmd_ops.get_cmd(cmd_file->fd)) != NULL) {
3625 * Now, apply the requests to the tree ...
3627 switch (cmd->cmd) {
3628 case CMD_ADD_KEY: {
3629 REG_KEY *tmp = NULL;
3631 tmp = nt_find_key_by_name(regf->root, cmd->key);
3633 /* If we found it, apply the other bits, else create such a key */
3635 if (!tmp)
3636 tmp = nt_add_reg_key(regf, cmd->key, True);
3638 if (tmp) {
3642 while (cmd->val_count) {
3643 VAL_SPEC_LIST *val = cmd->val_spec_list;
3644 VAL_KEY *reg_val = NULL;
3646 if (val->type == REG_TYPE_DELETE) {
3647 reg_val = nt_delete_reg_value(tmp, val -> name);
3648 if (reg_val) nt_delete_val_key(reg_val);
3650 else {
3651 reg_val = nt_add_reg_value(tmp, val->name, val->type,
3652 val->val);
3655 cmd->val_spec_list = val->next;
3656 free_val_spec_list(val);
3657 cmd->val_count--;
3660 break;
3663 case CMD_DEL_KEY:
3665 * Any value does not matter ...
3666 * Find the key if it exists, and delete it ...
3669 nt_delete_key_by_name(regf, cmd->key);
3670 break;
3673 free_cmd(cmd);
3677 * At this point, we should have a registry in memory and should be able
3678 * to iterate over it.
3681 if (print_keys) {
3682 nt_key_iterator(regf, regf->root, 0, "", print_key, print_sec, print_val);
3685 return 0;