More functions to compute the space taken up by SIDs, ACEs, ACLs, SEC
[Samba/gbeck.git] / source3 / utils / editreg.c
blob34a9eecf11226b690c30de75a07ed0cd43b10946
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 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 struct key_sec_desc_s {
444 struct key_sec_desc_s *prev, *next;
445 int ref_cnt;
446 int state;
447 int offset;
448 SEC_DESC *sec_desc;
452 * All of the structures below actually have a four-byte length before them
453 * which always seems to be negative. The following macro retrieves that
454 * size as an integer
457 #define BLK_SIZE(b) ((int)*(int *)(((int *)b)-1))
459 typedef unsigned int DWORD;
460 typedef unsigned short WORD;
462 #define REG_REGF_ID 0x66676572
464 typedef struct regf_block {
465 DWORD REGF_ID; /* regf */
466 DWORD uk1;
467 DWORD uk2;
468 DWORD tim1, tim2;
469 DWORD uk3; /* 1 */
470 DWORD uk4; /* 3 */
471 DWORD uk5; /* 0 */
472 DWORD uk6; /* 1 */
473 DWORD first_key; /* offset */
474 unsigned int dblk_size;
475 DWORD uk7[116]; /* 1 */
476 DWORD chksum;
477 } REGF_HDR;
479 typedef struct hbin_sub_struct {
480 DWORD dblocksize;
481 char data[1];
482 } HBIN_SUB_HDR;
484 #define REG_HBIN_ID 0x6E696268
486 typedef struct hbin_struct {
487 DWORD HBIN_ID; /* hbin */
488 DWORD off_from_first;
489 DWORD off_to_next;
490 DWORD uk1;
491 DWORD uk2;
492 DWORD uk3;
493 DWORD uk4;
494 DWORD blk_size;
495 HBIN_SUB_HDR hbin_sub_hdr;
496 } HBIN_HDR;
498 #define REG_NK_ID 0x6B6E
500 typedef struct nk_struct {
501 WORD NK_ID;
502 WORD type;
503 DWORD t1, t2;
504 DWORD uk1;
505 DWORD own_off;
506 DWORD subk_num;
507 DWORD uk2;
508 DWORD lf_off;
509 DWORD uk3;
510 DWORD val_cnt;
511 DWORD val_off;
512 DWORD sk_off;
513 DWORD clsnam_off;
514 DWORD unk4[4];
515 DWORD unk5;
516 WORD nam_len;
517 WORD clsnam_len;
518 char key_nam[1]; /* Actual length determined by nam_len */
519 } NK_HDR;
521 #define REG_SK_ID 0x6B73
523 typedef struct sk_struct {
524 WORD SK_ID;
525 WORD uk1;
526 DWORD prev_off;
527 DWORD next_off;
528 DWORD ref_cnt;
529 DWORD rec_size;
530 char sec_desc[1];
531 } SK_HDR;
533 typedef struct ace_struct {
534 unsigned char type;
535 unsigned char flags;
536 unsigned short length;
537 unsigned int perms;
538 DOM_SID trustee;
539 } REG_ACE;
541 typedef struct acl_struct {
542 WORD rev;
543 WORD size;
544 DWORD num_aces;
545 REG_ACE *aces; /* One or more ACEs */
546 } REG_ACL;
548 typedef struct sec_desc_rec {
549 WORD rev;
550 WORD type;
551 DWORD owner_off;
552 DWORD group_off;
553 DWORD sacl_off;
554 DWORD dacl_off;
555 } REG_SEC_DESC;
557 typedef struct hash_struct {
558 DWORD nk_off;
559 char hash[4];
560 } HASH_REC;
562 #define REG_LF_ID 0x666C
564 typedef struct lf_struct {
565 WORD LF_ID;
566 WORD key_count;
567 struct hash_struct hr[1]; /* Array of hash records, depending on key_count */
568 } LF_HDR;
570 typedef DWORD VL_TYPE[1]; /* Value list is an array of vk rec offsets */
572 #define REG_VK_ID 0x6B76
574 typedef struct vk_struct {
575 WORD VK_ID;
576 WORD nam_len;
577 DWORD dat_len; /* If top-bit set, offset contains the data */
578 DWORD dat_off;
579 DWORD dat_type;
580 WORD flag; /* =1, has name, else no name (=Default). */
581 WORD unk1;
582 char dat_name[1]; /* Name starts here ... */
583 } VK_HDR;
585 #define REG_TYPE_DELETE -1
586 #define REG_TYPE_NONE 0
587 #define REG_TYPE_REGSZ 1
588 #define REG_TYPE_EXPANDSZ 2
589 #define REG_TYPE_BIN 3
590 #define REG_TYPE_DWORD 4
591 #define REG_TYPE_MULTISZ 7
593 typedef struct _val_str {
594 unsigned int val;
595 const char * str;
596 } VAL_STR;
598 /* A map of sk offsets in the regf to KEY_SEC_DESCs for quick lookup etc */
599 typedef struct sk_map_s {
600 int sk_off;
601 KEY_SEC_DESC *key_sec_desc;
602 } SK_MAP;
605 * This structure keeps track of the output format of the registry
607 #define REG_OUTBLK_HDR 1
608 #define REG_OUTBLK_HBIN 2
610 typedef struct hbin_blk_s {
611 int type, size;
612 struct hbin_blk_s *next;
613 char *data; /* The data block */
614 unsigned int file_offset; /* Offset in file */
615 unsigned int free_space; /* Amount of free space in block */
616 unsigned int fsp_off; /* Start of free space in block */
617 int complete, stored;
618 } HBIN_BLK;
621 * This structure keeps all the registry stuff in one place
623 typedef struct regf_struct_s {
624 int reg_type;
625 char *regfile_name, *outfile_name;
626 int fd;
627 struct stat sbuf;
628 char *base;
629 int modified;
630 NTTIME last_mod_time;
631 REG_KEY *root; /* Root of the tree for this file */
632 int sk_count, sk_map_size;
633 SK_MAP *sk_map;
634 char *owner_sid_str;
635 SEC_DESC *def_sec_desc;
637 * These next pointers point to the blocks used to contain the
638 * keys when we are preparing to write them to a file
640 HBIN_BLK *blk_head, *blk_tail, *free_space;
641 } REGF;
644 * An API for accessing/creating/destroying items above
648 * Iterate over the keys, depth first, calling a function for each key
649 * and indicating if it is terminal or non-terminal and if it has values.
651 * In addition, for each value in the list, call a value list function
654 typedef int (*key_print_f)(const char *path, char *key_name, char *class_name,
655 int root, int terminal, int values);
657 typedef int (*val_print_f)(const char *path, char *val_name, int val_type,
658 int data_len, void *data_blk, int terminal,
659 int first, int last);
661 typedef int (*sec_print_f)(SEC_DESC *sec_desc);
663 int nt_key_iterator(REGF *regf, REG_KEY *key_tree, int bf, const char *path,
664 key_print_f key_print, sec_print_f sec_print,
665 val_print_f val_print);
667 int nt_val_list_iterator(REGF *regf, VAL_LIST *val_list, int bf, char *path,
668 int terminal, val_print_f val_print)
670 int i;
672 if (!val_list) return 1;
674 if (!val_print) return 1;
676 for (i=0; i<val_list->val_count; i++) {
677 if (!val_print(path, val_list->vals[i]->name, val_list->vals[i]->data_type,
678 val_list->vals[i]->data_len, val_list->vals[i]->data_blk,
679 terminal,
680 (i == 0),
681 (i == val_list->val_count))) {
683 return 0;
688 return 1;
691 int nt_key_list_iterator(REGF *regf, KEY_LIST *key_list, int bf,
692 const char *path,
693 key_print_f key_print, sec_print_f sec_print,
694 val_print_f val_print)
696 int i;
698 if (!key_list) return 1;
700 for (i=0; i< key_list->key_count; i++) {
701 if (!nt_key_iterator(regf, key_list->keys[i], bf, path, key_print,
702 sec_print, val_print)) {
703 return 0;
706 return 1;
709 int nt_key_iterator(REGF *regf, REG_KEY *key_tree, int bf, const char *path,
710 key_print_f key_print, sec_print_f sec_print,
711 val_print_f val_print)
713 int path_len = strlen(path);
714 char *new_path;
716 if (!regf || !key_tree)
717 return -1;
719 /* List the key first, then the values, then the sub-keys */
721 if (key_print) {
723 if (!(*key_print)(path, key_tree->name,
724 key_tree->class_name,
725 (key_tree->type == REG_ROOT_KEY),
726 (key_tree->sub_keys == NULL),
727 (key_tree->values?(key_tree->values->val_count):0)))
728 return 0;
732 * If we have a security print routine, call it
733 * If the security print routine returns false, stop.
735 if (sec_print) {
736 if (key_tree->security && !(*sec_print)(key_tree->security->sec_desc))
737 return 0;
740 new_path = (char *)malloc(path_len + 1 + strlen(key_tree->name) + 1);
741 if (!new_path) return 0; /* Errors? */
742 new_path[0] = '\0';
743 strcat(new_path, path);
744 strcat(new_path, key_tree->name);
745 strcat(new_path, "\\");
748 * Now, iterate through the values in the val_list
751 if (key_tree->values &&
752 !nt_val_list_iterator(regf, key_tree->values, bf, new_path,
753 (key_tree->values!=NULL),
754 val_print)) {
756 free(new_path);
757 return 0;
761 * Now, iterate through the keys in the key list
764 if (key_tree->sub_keys &&
765 !nt_key_list_iterator(regf, key_tree->sub_keys, bf, new_path, key_print,
766 sec_print, val_print)) {
767 free(new_path);
768 return 0;
771 free(new_path);
772 return 1;
775 REG_KEY *nt_find_key_by_name(REG_KEY *tree, char *key);
778 * Find key by name in a list ...
779 * Take the first component and search for that in the list
781 REG_KEY *nt_find_key_in_list_by_name(KEY_LIST *list, char *key)
783 int i;
784 REG_KEY *res = NULL;
786 if (!list || !key || !*key) return NULL;
788 for (i = 0; i < list->key_count; i++)
789 if ((res = nt_find_key_by_name(list->keys[i], key)))
790 return res;
792 return NULL;
796 * Find key by name in a tree ... We will assume absolute names here, but we
797 * need the root of the tree ...
799 REG_KEY *nt_find_key_by_name(REG_KEY *tree, char *key)
801 char *lname = NULL, *c1, *c2;
802 REG_KEY *tmp;
804 if (!tree || !key || !*key) return NULL;
806 lname = strdup(key);
807 if (!lname) return NULL;
810 * Make sure that the first component is correct ...
812 c1 = lname;
813 c2 = strchr(c1, '\\');
814 if (c2) { /* Split here ... */
815 *c2 = 0;
816 c2++;
818 if (strcmp(c1, tree->name) != 0) goto error;
820 if (c2) {
821 tmp = nt_find_key_in_list_by_name(tree->sub_keys, c2);
822 free(lname);
823 return tmp;
825 else {
826 if (lname) free(lname);
827 return tree;
829 error:
830 if (lname) free(lname);
831 return NULL;
834 /* Make, delete keys */
836 int nt_delete_val_key(VAL_KEY *val_key)
839 if (val_key) {
840 if (val_key->name) free(val_key->name);
841 if (val_key->data_blk) free(val_key->data_blk);
842 free(val_key);
844 return 1;
847 int nt_delete_val_list(VAL_LIST *vl)
849 int i;
851 if (vl) {
852 for (i=0; i<vl->val_count; i++)
853 nt_delete_val_key(vl->vals[i]);
854 free(vl);
856 return 1;
859 int nt_delete_reg_key(REG_KEY *key, int delete_name);
860 int nt_delete_key_list(KEY_LIST *key_list, int delete_name)
862 int i;
864 if (key_list) {
865 for (i=0; i<key_list->key_count; i++)
866 nt_delete_reg_key(key_list->keys[i], False);
867 free(key_list);
869 return 1;
873 * Find the key, and if it exists, delete it ...
875 int nt_delete_key_by_name(REGF *regf, char *name)
877 REG_KEY *key;
879 if (!name || !*name) return 0;
881 key = nt_find_key_by_name(regf->root, name);
883 if (key) {
884 if (key == regf->root) regf->root = NULL;
885 return nt_delete_reg_key(key, True);
888 return 0;
892 int nt_delete_sid(DOM_SID *sid)
895 if (sid) free(sid);
896 return 1;
900 int nt_delete_ace(ACE *ace)
903 if (ace) {
904 nt_delete_sid(ace->trustee);
905 free(ace);
907 return 1;
911 int nt_delete_acl(ACL *acl)
914 if (acl) {
915 int i;
917 for (i=0; i<acl->num_aces; i++)
918 nt_delete_ace(acl->aces[i]);
920 free(acl);
922 return 1;
925 int nt_delete_sec_desc(SEC_DESC *sec_desc)
928 if (sec_desc) {
930 nt_delete_sid(sec_desc->owner);
931 nt_delete_sid(sec_desc->group);
932 nt_delete_acl(sec_desc->sacl);
933 nt_delete_acl(sec_desc->dacl);
934 free(sec_desc);
937 return 1;
940 int nt_delete_key_sec_desc(KEY_SEC_DESC *key_sec_desc)
943 if (key_sec_desc) {
944 key_sec_desc->ref_cnt--;
945 if (key_sec_desc->ref_cnt<=0) {
947 * There should always be a next and prev, even if they point to us
949 key_sec_desc->next->prev = key_sec_desc->prev;
950 key_sec_desc->prev->next = key_sec_desc->next;
951 nt_delete_sec_desc(key_sec_desc->sec_desc);
954 return 1;
957 int nt_delete_reg_key(REG_KEY *key, int delete_name)
960 if (key) {
961 if (key->name) free(key->name);
962 if (key->class_name) free(key->class_name);
965 * We will delete the owner if we are not the root and told to ...
968 if (key->owner && key->owner->sub_keys && delete_name) {
969 REG_KEY *own;
970 KEY_LIST *kl;
971 int i;
972 /* Find our owner, look in keylist for us and shuffle up */
973 /* Perhaps should be a function */
975 own = key->owner;
976 kl = own->sub_keys;
978 for (i=0; i < kl->key_count && kl->keys[i] != key ; i++) {
979 /* Just find the entry ... */
982 if (i == kl->key_count) {
983 fprintf(stderr, "Bad data structure. Key not found in key list of owner\n");
985 else {
986 int j;
989 * Shuffle up. Works for the last one also
991 for (j = i + 1; j < kl->key_count; j++) {
992 kl->keys[j - 1] = kl->keys[j];
995 kl->key_count--;
999 if (key->sub_keys) nt_delete_key_list(key->sub_keys, False);
1000 if (key->values) nt_delete_val_list(key->values);
1001 if (key->security) nt_delete_key_sec_desc(key->security);
1002 free(key);
1004 return 1;
1008 * Convert a string to a value ...
1009 * FIXME: Error handling and convert this at command parse time ...
1011 void *str_to_val(int type, char *val, int *len)
1013 unsigned int *dwordp = NULL;
1015 if (!len || !val) return NULL;
1017 switch (type) {
1018 case REG_TYPE_REGSZ:
1019 *len = strlen(val);
1020 return (void *)val;
1022 case REG_TYPE_DWORD:
1023 dwordp = (unsigned int *)malloc(sizeof(unsigned int));
1024 if (!dwordp) return NULL;
1025 /* Allow for ddddd and 0xhhhhh and 0ooooo */
1026 if (strncmp(val, "0x", 2) == 0 || strncmp(val, "0X", 2) == 0) {
1027 sscanf(&val[2], "%X", dwordp);
1029 else if (*val == '0') {
1030 sscanf(&val[1], "%o", dwordp);
1032 else {
1033 sscanf(val, "%d", dwordp);
1035 *len = sizeof(unsigned int);
1036 return (void *)dwordp;
1038 /* FIXME: Implement more of these */
1040 default:
1041 return NULL;
1042 break;
1045 return NULL;
1049 * Add a value to the key specified ... We have to parse the value some more
1050 * based on the type to get it in the correct internal form
1051 * An empty name will be converted to "<No Name>" before here
1052 * Hmmm, maybe not. has_name is for that
1054 VAL_KEY *nt_add_reg_value(REG_KEY *key, char *name, int type, char *value)
1056 int i;
1057 VAL_KEY *tmp = NULL;
1059 if (!key || !key->values || !name || !*name) return NULL;
1061 assert(type != REG_TYPE_DELETE); /* We never process deletes here */
1063 for (i = 0; i < key->values->val_count; i++) {
1064 if ((!key->values->vals[i]->has_name && !*name) ||
1065 (key->values->vals[i]->has_name &&
1066 strcmp(name, key->values->vals[i]->name) == 0)){ /* Change the value */
1067 free(key->values->vals[i]->data_blk);
1068 key->values->vals[i]->data_blk = str_to_val(type, value, &
1069 key->values->vals[i]->data_len);
1070 return key->values->vals[i];
1075 * If we get here, the name was not found, so insert it
1078 tmp = (VAL_KEY *)malloc(sizeof(VAL_KEY));
1079 if (!tmp) goto error;
1081 bzero(tmp, sizeof(VAL_KEY));
1082 tmp->name = strdup(name);
1083 tmp->has_name = True;
1084 if (!tmp->name) goto error;
1085 tmp->data_type = type;
1086 tmp->data_blk = str_to_val(type, value, &tmp->data_len);
1088 /* Now, add to val list */
1090 if (key->values->val_count >= key->values->max_vals) {
1092 * Allocate some more space
1095 if ((key->values = (VAL_LIST *)realloc(key->values, sizeof(VAL_LIST) +
1096 key->values->val_count - 1 +
1097 REG_KEY_LIST_SIZE))) {
1098 key->values->max_vals += REG_KEY_LIST_SIZE;
1100 else goto error;
1103 i = key->values->val_count;
1104 key->values->val_count++;
1105 key->values->vals[i] = tmp;
1106 return tmp;
1108 error:
1109 if (tmp) nt_delete_val_key(tmp);
1110 return NULL;
1114 * Delete a value. We return the value and let the caller deal with it.
1116 VAL_KEY *nt_delete_reg_value(REG_KEY *key, char *name)
1118 int i, j;
1120 if (!key || !key->values || !name || !*name) return NULL;
1122 /* FIXME: Allow empty value name */
1123 for (i = 0; i< key->values->val_count; i++) {
1124 if ((!key->values->vals[i]->has_name && !*name) ||
1125 (key->values->vals[i]->has_name &&
1126 strcmp(name, key->values->vals[i]->name) == 0)) {
1127 VAL_KEY *val;
1129 val = key->values->vals[i];
1131 /* Shuffle down */
1132 for (j = i + 1; j < key->values->val_count; j++)
1133 key->values->vals[j - 1] = key->values->vals[j];
1135 key->values->val_count--;
1137 return val;
1140 return NULL;
1144 * Add a key to the tree ... We walk down the components matching until
1145 * we don't find any. There must be a match on the first component ...
1146 * We return the key structure for the final component as that is
1147 * often where we want to add values ...
1151 * Create a 1 component key name and set its parent to parent
1153 REG_KEY *nt_create_reg_key1(char *name, REG_KEY *parent)
1155 REG_KEY *tmp;
1157 if (!name || !*name) return NULL; /* A key's name cannot be empty */
1159 /* There should not be more than one component */
1160 if (strchr(name, '\\')) return NULL;
1162 if (!(tmp = (REG_KEY *)malloc(sizeof(REG_KEY)))) return NULL;
1164 bzero(tmp, sizeof(REG_KEY));
1166 if (!(tmp->name = strdup(name))) goto error;
1168 error:
1169 if (tmp) free(tmp);
1170 return NULL;
1174 * Convert a string of the form S-1-5-x[-y-z-r] to a SID
1176 int string_to_sid(DOM_SID **sid, char *sid_str)
1178 int i = 0, auth;
1179 char *lstr;
1181 *sid = (DOM_SID *)malloc(sizeof(DOM_SID));
1182 if (!*sid) return 0;
1184 bzero(*sid, sizeof(DOM_SID));
1186 if (strncmp(sid_str, "S-1-5", 5)) {
1187 fprintf(stderr, "Does not conform to S-1-5...: %s\n", sid_str);
1188 return 0;
1191 /* We only allow strings of form S-1-5... */
1193 (*sid)->ver = 1;
1194 (*sid)->auth[5] = 5;
1196 lstr = sid_str + 5;
1198 while (1) {
1199 if (!lstr || !lstr[0] || sscanf(lstr, "-%u", &auth) == 0) {
1200 if (i < 1) {
1201 fprintf(stderr, "Not of form -d-d...: %s, %u\n", lstr, i);
1202 return 0;
1204 (*sid)->auths=i;
1205 return 1;
1208 (*sid)->sub_auths[i] = auth;
1209 i++;
1210 lstr = strchr(lstr + 1, '-');
1213 return 1;
1217 * Create an ACE
1219 ACE *nt_create_ace(int type, int flags, unsigned int perms, char *sid)
1221 ACE *ace;
1223 ace = (ACE *)malloc(sizeof(ACE));
1224 if (!ace) goto error;
1225 ace->type = type;
1226 ace->flags = flags;
1227 ace->perms = perms;
1228 if (!string_to_sid(&ace->trustee, sid))
1229 goto error;
1230 return ace;
1232 error:
1233 if (ace) nt_delete_ace(ace);
1234 return NULL;
1238 * Create a default ACL
1240 ACL *nt_create_default_acl(REGF *regf)
1242 ACL *acl;
1244 acl = (ACL *)malloc(sizeof(ACL) + 7*sizeof(ACE *));
1245 if (!acl) goto error;
1247 acl->rev = 2;
1248 acl->refcnt = 1;
1249 acl->num_aces = 8;
1251 acl->aces[0] = nt_create_ace(0x00, 0x0, 0xF003F, regf->owner_sid_str);
1252 if (!acl->aces[0]) goto error;
1253 acl->aces[1] = nt_create_ace(0x00, 0x0, 0xF003F, "S-1-5-18");
1254 if (!acl->aces[1]) goto error;
1255 acl->aces[2] = nt_create_ace(0x00, 0x0, 0xF003F, "S-1-5-32-544");
1256 if (!acl->aces[2]) goto error;
1257 acl->aces[3] = nt_create_ace(0x00, 0x0, 0x20019, "S-1-5-12");
1258 if (!acl->aces[3]) goto error;
1259 acl->aces[4] = nt_create_ace(0x00, 0x0B, 0x10000000, regf->owner_sid_str);
1260 if (!acl->aces[4]) goto error;
1261 acl->aces[5] = nt_create_ace(0x00, 0x0B, 0x10000000, "S-1-5-18");
1262 if (!acl->aces[5]) goto error;
1263 acl->aces[6] = nt_create_ace(0x00, 0x0B, 0x10000000, "S-1-5-32-544");
1264 if (!acl->aces[6]) goto error;
1265 acl->aces[7] = nt_create_ace(0x00, 0x0B, 0x80000000, "S-1-5-12");
1266 if (!acl->aces[7]) goto error;
1267 return acl;
1269 error:
1270 if (acl) nt_delete_acl(acl);
1271 return NULL;
1275 * Create a default security descriptor. We pull in things from env
1276 * if need be
1278 SEC_DESC *nt_create_def_sec_desc(REGF *regf)
1280 SEC_DESC *tmp;
1282 tmp = (SEC_DESC *)malloc(sizeof(SEC_DESC));
1283 if (!tmp) return NULL;
1285 tmp->rev = 1;
1286 tmp->type = 0x8004;
1287 if (!string_to_sid(&tmp->owner, "S-1-5-32-544")) goto error;
1288 if (!string_to_sid(&tmp->group, "S-1-5-18")) goto error;
1289 tmp->sacl = NULL;
1290 tmp->dacl = nt_create_default_acl(regf);
1292 return tmp;
1294 error:
1295 if (tmp) nt_delete_sec_desc(tmp);
1296 return NULL;
1300 * We will implement inheritence that is based on what the parent's SEC_DESC
1301 * says, but the Owner and Group SIDs can be overwridden from the command line
1302 * and additional ACEs can be applied from the command line etc.
1304 KEY_SEC_DESC *nt_inherit_security(REG_KEY *key)
1307 if (!key) return NULL;
1308 return key->security;
1312 * Create an initial security descriptor and init other structures, if needed
1313 * We assume that the initial security stuff is empty ...
1315 KEY_SEC_DESC *nt_create_init_sec(REGF *regf)
1317 KEY_SEC_DESC *tsec = NULL;
1319 tsec = (KEY_SEC_DESC *)malloc(sizeof(KEY_SEC_DESC));
1320 if (!tsec) return NULL;
1322 tsec->ref_cnt = 1;
1323 tsec->state = SEC_DESC_NBK;
1324 tsec->offset = 0;
1326 tsec->sec_desc = regf->def_sec_desc;
1328 return tsec;
1332 * Add a sub-key
1334 REG_KEY *nt_add_reg_key_list(REGF *regf, REG_KEY *key, char * name, int create)
1336 int i;
1337 REG_KEY *ret = NULL, *tmp = NULL;
1338 KEY_LIST *list;
1339 char *lname, *c1, *c2;
1341 if (!key || !name || !*name) return NULL;
1343 list = key->sub_keys;
1344 if (!list) { /* Create an empty list */
1346 list = (KEY_LIST *)malloc(sizeof(KEY_LIST) + (REG_KEY_LIST_SIZE - 1) * sizeof(REG_KEY *));
1347 list->key_count = 0;
1348 list->max_keys = REG_KEY_LIST_SIZE;
1352 lname = strdup(name);
1353 if (!lname) return NULL;
1355 c1 = lname;
1356 c2 = strchr(c1, '\\');
1357 if (c2) { /* Split here ... */
1358 *c2 = 0;
1359 c2++;
1362 for (i = 0; i < list->key_count; i++) {
1363 if (strcmp(list->keys[i]->name, c1) == 0) {
1364 ret = nt_add_reg_key_list(regf, list->keys[i], c2, create);
1365 free(lname);
1366 return ret;
1371 * If we reach here we could not find the the first component
1372 * so create it ...
1375 if (list->key_count < list->max_keys){
1376 list->key_count++;
1378 else { /* Create more space in the list ... */
1379 if (!(list = (KEY_LIST *)realloc(list, sizeof(KEY_LIST) +
1380 (list->max_keys + REG_KEY_LIST_SIZE - 1)
1381 * sizeof(REG_KEY *))));
1382 goto error;
1384 list->max_keys += REG_KEY_LIST_SIZE;
1385 list->key_count++;
1389 * add the new key at the new slot
1390 * FIXME: Sort the list someday
1394 * We want to create the key, and then do the rest
1397 tmp = (REG_KEY *)malloc(sizeof(REG_KEY));
1399 bzero(tmp, sizeof(REG_KEY));
1401 tmp->name = strdup(c1);
1402 if (!tmp->name) goto error;
1403 tmp->owner = key;
1404 tmp->type = REG_SUB_KEY;
1406 * Next, pull security from the parent, but override with
1407 * anything passed in on the command line
1409 tmp->security = nt_inherit_security(key);
1411 list->keys[list->key_count - 1] = tmp;
1413 if (c2) {
1414 ret = nt_add_reg_key_list(regf, key, c2, True);
1417 if (lname) free(lname);
1419 return ret;
1421 error:
1422 if (tmp) free(tmp);
1423 if (lname) free(lname);
1424 return NULL;
1428 * This routine only adds a key from the root down.
1429 * It calls helper functions to handle sub-key lists and sub-keys
1431 REG_KEY *nt_add_reg_key(REGF *regf, char *name, int create)
1433 char *lname = NULL, *c1, *c2;
1434 REG_KEY * tmp = NULL;
1437 * Look until we hit the first component that does not exist, and
1438 * then add from there. However, if the first component does not
1439 * match and the path we are given is the root, then it must match
1441 if (!regf || !name || !*name) return NULL;
1443 lname = strdup(name);
1444 if (!lname) return NULL;
1446 c1 = lname;
1447 c2 = strchr(c1, '\\');
1448 if (c2) { /* Split here ... */
1449 *c2 = 0;
1450 c2++;
1454 * If the root does not exist, create it and make it equal to the
1455 * first component ...
1458 if (!regf->root) {
1460 tmp = (REG_KEY *)malloc(sizeof(REG_KEY));
1461 if (!tmp) goto error;
1462 bzero(tmp, sizeof(REG_KEY));
1463 tmp->name = strdup(c1);
1464 if (!tmp->name) goto error;
1465 tmp->security = nt_create_init_sec(regf);
1466 if (!tmp->security) goto error;
1467 regf->root = tmp;
1470 else {
1472 * If we don't match, then we have to return error ...
1473 * If we do match on this component, check the next one in the
1474 * list, and if not found, add it ... short circuit, add all the
1475 * way down
1478 if (strcmp(c1, regf->root->name) != 0)
1479 goto error;
1482 tmp = nt_add_reg_key_list(regf, regf->root, c2, True);
1483 free(lname);
1484 return tmp;
1486 error:
1487 if (tmp) free(tmp);
1488 if (lname) free(lname);
1489 return NULL;
1493 * Load and unload a registry file.
1495 * Load, loads it into memory as a tree, while unload sealizes/flattens it
1499 * Get the starting record for NT Registry file
1503 * Where we keep all the regf stuff for one registry.
1504 * This is the structure that we use to tie the in memory tree etc
1505 * together. By keeping separate structs, we can operate on different
1506 * registries at the same time.
1507 * Currently, the SK_MAP is an array of mapping structure.
1508 * Since we only need this on input and output, we fill in the structure
1509 * as we go on input. On output, we know how many SK items we have, so
1510 * we can allocate the structure as we need to.
1511 * If you add stuff here that is dynamically allocated, add the
1512 * appropriate free statements below.
1515 #define REGF_REGTYPE_NONE 0
1516 #define REGF_REGTYPE_NT 1
1517 #define REGF_REGTYPE_W9X 2
1519 #define TTTONTTIME(r, t1, t2) (r)->last_mod_time.low = (t1); \
1520 (r)->last_mod_time.high = (t2);
1522 #define REGF_HDR_BLKSIZ 0x1000
1524 #define OFF(f) ((f) + REGF_HDR_BLKSIZ + 4)
1525 #define LOCN(base, f) ((base) + OFF(f))
1527 const VAL_STR reg_type_names[] = {
1528 { REG_TYPE_REGSZ, "REG_SZ" },
1529 { REG_TYPE_EXPANDSZ, "REG_EXPAND_SZ" },
1530 { REG_TYPE_BIN, "REG_BIN" },
1531 { REG_TYPE_DWORD, "REG_DWORD" },
1532 { REG_TYPE_MULTISZ, "REG_MULTI_SZ" },
1533 { 0, NULL },
1536 const char *val_to_str(unsigned int val, const VAL_STR *val_array)
1538 int i = 0;
1540 if (!val_array) return NULL;
1542 while (val_array[i].val && val_array[i].str) {
1544 if (val_array[i].val == val) return val_array[i].str;
1545 i++;
1549 return NULL;
1554 * Convert from UniCode to Ascii ... Does not take into account other lang
1555 * Restrict by ascii_max if > 0
1557 int uni_to_ascii(unsigned char *uni, unsigned char *ascii, int ascii_max,
1558 int uni_max)
1560 int i = 0;
1562 while (i < ascii_max && !(!uni[i*2] && !uni[i*2+1])) {
1563 if (uni_max > 0 && (i*2) >= uni_max) break;
1564 ascii[i] = uni[i*2];
1565 i++;
1569 ascii[i] = '\0';
1571 return i;
1575 * Convert a data value to a string for display
1577 int data_to_ascii(unsigned char *datap, int len, int type, char *ascii, int ascii_max)
1579 unsigned char *asciip;
1580 int i;
1582 switch (type) {
1583 case REG_TYPE_REGSZ:
1584 if (verbose) fprintf(stderr, "Len: %d\n", len);
1585 /* FIXME. This has to be fixed. It has to be UNICODE */
1586 return uni_to_ascii(datap, ascii, len, ascii_max);
1587 break;
1589 case REG_TYPE_EXPANDSZ:
1590 return uni_to_ascii(datap, ascii, len, ascii_max);
1591 break;
1593 case REG_TYPE_BIN:
1594 asciip = ascii;
1595 for (i=0; (i<len)&&(i+1)*3<ascii_max; i++) {
1596 int str_rem = ascii_max - ((int)asciip - (int)ascii);
1597 asciip += snprintf(asciip, str_rem, "%02x", *(unsigned char *)(datap+i));
1598 if (i < len && str_rem > 0)
1599 *asciip = ' '; asciip++;
1601 *asciip = '\0';
1602 return ((int)asciip - (int)ascii);
1603 break;
1605 case REG_TYPE_DWORD:
1606 if (*(int *)datap == 0)
1607 return snprintf(ascii, ascii_max, "0");
1608 else
1609 return snprintf(ascii, ascii_max, "0x%x", *(int *)datap);
1610 break;
1612 case REG_TYPE_MULTISZ:
1614 break;
1616 default:
1617 return 0;
1618 break;
1621 return len;
1625 REG_KEY *nt_get_key_tree(REGF *regf, NK_HDR *nk_hdr, int size, REG_KEY *parent);
1627 int nt_set_regf_input_file(REGF *regf, char *filename)
1629 return ((regf->regfile_name = strdup(filename)) != NULL);
1632 int nt_set_regf_output_file(REGF *regf, char *filename)
1634 return ((regf->outfile_name = strdup(filename)) != NULL);
1637 /* Create a regf structure and init it */
1639 REGF *nt_create_regf(void)
1641 REGF *tmp = (REGF *)malloc(sizeof(REGF));
1642 if (!tmp) return tmp;
1643 bzero(tmp, sizeof(REGF));
1644 tmp->owner_sid_str = def_owner_sid_str;
1645 return tmp;
1648 /* Free all the bits and pieces ... Assumes regf was malloc'd */
1649 /* If you add stuff to REGF, add the relevant free bits here */
1650 int nt_free_regf(REGF *regf)
1652 if (!regf) return 0;
1654 if (regf->regfile_name) free(regf->regfile_name);
1655 if (regf->outfile_name) free(regf->outfile_name);
1657 nt_delete_reg_key(regf->root, False); /* Free the tree */
1658 free(regf->sk_map);
1659 regf->sk_count = regf->sk_map_size = 0;
1661 free(regf);
1663 return 1;
1666 /* Get the header of the registry. Return a pointer to the structure
1667 * If the mmap'd area has not been allocated, then mmap the input file
1669 REGF_HDR *nt_get_regf_hdr(REGF *regf)
1671 if (!regf)
1672 return NULL; /* What about errors */
1674 if (!regf->regfile_name)
1675 return NULL; /* What about errors */
1677 if (!regf->base) { /* Try to mmap etc the file */
1679 if ((regf->fd = open(regf->regfile_name, O_RDONLY, 0000)) <0) {
1680 return NULL; /* What about errors? */
1683 if (fstat(regf->fd, &regf->sbuf) < 0) {
1684 return NULL;
1687 regf->base = mmap(0, regf->sbuf.st_size, PROT_READ, MAP_SHARED, regf->fd, 0);
1689 if ((int)regf->base == 1) {
1690 fprintf(stderr, "Could not mmap file: %s, %s\n", regf->regfile_name,
1691 strerror(errno));
1692 return NULL;
1697 * At this point, regf->base != NULL, and we should be able to read the
1698 * header
1701 assert(regf->base != NULL);
1703 return (REGF_HDR *)regf->base;
1707 * Validate a regf header
1708 * For now, do nothing, but we should check the checksum
1710 int valid_regf_hdr(REGF_HDR *regf_hdr)
1712 if (!regf_hdr) return 0;
1714 return 1;
1718 * Process an SK header ...
1719 * Every time we see a new one, add it to the map. Otherwise, just look it up.
1720 * We will do a simple linear search for the moment, since many KEYs have the
1721 * same security descriptor.
1722 * We allocate the map in increments of 10 entries.
1726 * Create a new entry in the map, and increase the size of the map if needed
1729 SK_MAP *alloc_sk_map_entry(REGF *regf, KEY_SEC_DESC *tmp, int sk_off)
1731 if (!regf->sk_map) { /* Allocate a block of 10 */
1732 regf->sk_map = (SK_MAP *)malloc(sizeof(SK_MAP) * 10);
1733 if (!regf->sk_map) {
1734 free(tmp);
1735 return NULL;
1737 regf->sk_map_size = 10;
1738 regf->sk_count = 1;
1739 (regf->sk_map)[0].sk_off = sk_off;
1740 (regf->sk_map)[0].key_sec_desc = tmp;
1742 else { /* Simply allocate a new slot, unless we have to expand the list */
1743 int ndx = regf->sk_count;
1744 if (regf->sk_count >= regf->sk_map_size) {
1745 regf->sk_map = (SK_MAP *)realloc(regf->sk_map,
1746 (regf->sk_map_size + 10)*sizeof(SK_MAP));
1747 if (!regf->sk_map) {
1748 free(tmp);
1749 return NULL;
1752 * ndx already points at the first entry of the new block
1754 regf->sk_map_size += 10;
1756 (regf->sk_map)[ndx].sk_off = sk_off;
1757 (regf->sk_map)[ndx].key_sec_desc = tmp;
1758 regf->sk_count++;
1760 return regf->sk_map;
1764 * Search for a KEY_SEC_DESC in the sk_map, but don't create one if not
1765 * found
1768 KEY_SEC_DESC *lookup_sec_key(SK_MAP *sk_map, int count, int sk_off)
1770 int i;
1772 if (!sk_map) return NULL;
1774 for (i = 0; i < count; i++) {
1776 if (sk_map[i].sk_off == sk_off)
1777 return sk_map[i].key_sec_desc;
1781 return NULL;
1786 * Allocate a KEY_SEC_DESC if we can't find one in the map
1789 KEY_SEC_DESC *lookup_create_sec_key(REGF *regf, SK_MAP *sk_map, int sk_off)
1791 KEY_SEC_DESC *tmp = lookup_sec_key(regf->sk_map, regf->sk_count, sk_off);
1793 if (tmp) {
1794 return tmp;
1796 else { /* Allocate a new one */
1797 tmp = (KEY_SEC_DESC *)malloc(sizeof(KEY_SEC_DESC));
1798 if (!tmp) {
1799 return NULL;
1801 bzero(tmp, sizeof(KEY_SEC_DESC)); /* Neatly sets offset to 0 */
1802 tmp->state = SEC_DESC_RES;
1803 if (!alloc_sk_map_entry(regf, tmp, sk_off)) {
1804 return NULL;
1806 return tmp;
1811 * Allocate storage and duplicate a SID
1812 * We could allocate the SID to be only the size needed, but I am too lazy.
1814 DOM_SID *dup_sid(DOM_SID *sid)
1816 DOM_SID *tmp = (DOM_SID *)malloc(sizeof(DOM_SID));
1817 int i;
1819 if (!tmp) return NULL;
1820 tmp->ver = sid->ver;
1821 tmp->auths = sid->auths;
1822 for (i=0; i<6; i++) {
1823 tmp->auth[i] = sid->auth[i];
1825 for (i=0; i<tmp->auths&&i<MAXSUBAUTHS; i++) {
1826 tmp->sub_auths[i] = sid->sub_auths[i];
1828 return tmp;
1832 * Allocate space for an ACE and duplicate the registry encoded one passed in
1834 ACE *dup_ace(REG_ACE *ace)
1836 ACE *tmp = NULL;
1838 tmp = (ACE *)malloc(sizeof(ACE));
1840 if (!tmp) return NULL;
1842 tmp->type = CVAL(&ace->type);
1843 tmp->flags = CVAL(&ace->flags);
1844 tmp->perms = IVAL(&ace->perms);
1845 tmp->trustee = dup_sid(&ace->trustee);
1846 return tmp;
1850 * Allocate space for an ACL and duplicate the registry encoded one passed in
1852 ACL *dup_acl(REG_ACL *acl)
1854 ACL *tmp = NULL;
1855 REG_ACE* ace;
1856 int i, num_aces;
1858 num_aces = IVAL(&acl->num_aces);
1860 tmp = (ACL *)malloc(sizeof(ACL) + (num_aces - 1)*sizeof(ACE *));
1861 if (!tmp) return NULL;
1863 tmp->num_aces = num_aces;
1864 tmp->refcnt = 1;
1865 tmp->rev = SVAL(&acl->rev);
1866 if (verbose) fprintf(stdout, "ACL: refcnt: %u, rev: %u\n", tmp->refcnt,
1867 tmp->rev);
1868 ace = (REG_ACE *)&acl->aces;
1869 for (i=0; i<num_aces; i++) {
1870 tmp->aces[i] = dup_ace(ace);
1871 ace = (REG_ACE *)((char *)ace + SVAL(&ace->length));
1872 /* XXX: FIXME, should handle malloc errors */
1875 return tmp;
1878 SEC_DESC *process_sec_desc(REGF *regf, REG_SEC_DESC *sec_desc)
1880 SEC_DESC *tmp = NULL;
1882 tmp = (SEC_DESC *)malloc(sizeof(SEC_DESC));
1884 if (!tmp) {
1885 return NULL;
1888 tmp->rev = SVAL(&sec_desc->rev);
1889 tmp->type = SVAL(&sec_desc->type);
1890 if (verbose) fprintf(stdout, "SEC_DESC Rev: %0X, Type: %0X\n",
1891 tmp->rev, tmp->type);
1892 if (verbose) fprintf(stdout, "SEC_DESC Owner Off: %0X\n",
1893 IVAL(&sec_desc->owner_off));
1894 if (verbose) fprintf(stdout, "SEC_DESC Group Off: %0X\n",
1895 IVAL(&sec_desc->group_off));
1896 if (verbose) fprintf(stdout, "SEC_DESC DACL Off: %0X\n",
1897 IVAL(&sec_desc->dacl_off));
1898 tmp->owner = dup_sid((DOM_SID *)((char *)sec_desc + IVAL(&sec_desc->owner_off)));
1899 if (!tmp->owner) {
1900 free(tmp);
1901 return NULL;
1903 tmp->group = dup_sid((DOM_SID *)((char *)sec_desc + IVAL(&sec_desc->group_off)));
1904 if (!tmp->group) {
1905 free(tmp);
1906 return NULL;
1909 /* Now pick up the SACL and DACL */
1911 if (sec_desc->sacl_off)
1912 tmp->sacl = dup_acl((REG_ACL *)((char *)sec_desc + IVAL(&sec_desc->sacl_off)));
1913 else
1914 tmp->sacl = NULL;
1916 if (sec_desc->dacl_off)
1917 tmp->dacl = dup_acl((REG_ACL *)((char *)sec_desc + IVAL(&sec_desc->dacl_off)));
1918 else
1919 tmp->dacl = NULL;
1921 return tmp;
1924 KEY_SEC_DESC *process_sk(REGF *regf, SK_HDR *sk_hdr, int sk_off, int size)
1926 KEY_SEC_DESC *tmp = NULL;
1927 int sk_next_off, sk_prev_off, sk_size;
1928 REG_SEC_DESC *sec_desc;
1930 if (!sk_hdr) return NULL;
1932 if (SVAL(&sk_hdr->SK_ID) != REG_SK_ID) {
1933 fprintf(stderr, "Unrecognized SK Header ID: %08X, %s\n", (int)sk_hdr,
1934 regf->regfile_name);
1935 return NULL;
1938 if (-size < (sk_size = IVAL(&sk_hdr->rec_size))) {
1939 fprintf(stderr, "Incorrect SK record size: %d vs %d. %s\n",
1940 -size, sk_size, regf->regfile_name);
1941 return NULL;
1945 * Now, we need to look up the SK Record in the map, and return it
1946 * Since the map contains the SK_OFF mapped to KEY_SEC_DESC, we can
1947 * use that
1950 if (regf->sk_map &&
1951 ((tmp = lookup_sec_key(regf->sk_map, regf->sk_count, sk_off)) != NULL)
1952 && (tmp->state == SEC_DESC_OCU)) {
1953 tmp->ref_cnt++;
1954 return tmp;
1957 /* Here, we have an item in the map that has been reserved, or tmp==NULL. */
1959 assert(tmp == NULL || (tmp && tmp->state != SEC_DESC_NON));
1962 * Now, allocate a KEY_SEC_DESC, and parse the structure here, and add the
1963 * new KEY_SEC_DESC to the mapping structure, since the offset supplied is
1964 * the actual offset of structure. The same offset will be used by
1965 * all future references to this structure
1966 * We could put all this unpleasantness in a function.
1969 if (!tmp) {
1970 tmp = (KEY_SEC_DESC *)malloc(sizeof(KEY_SEC_DESC));
1971 if (!tmp) return NULL;
1972 bzero(tmp, sizeof(KEY_SEC_DESC));
1975 * Allocate an entry in the SK_MAP ...
1976 * We don't need to free tmp, because that is done for us if the
1977 * sm_map entry can't be expanded when we need more space in the map.
1980 if (!alloc_sk_map_entry(regf, tmp, sk_off)) {
1981 return NULL;
1985 tmp->ref_cnt++;
1986 tmp->state = SEC_DESC_OCU;
1989 * Now, process the actual sec desc and plug the values in
1992 sec_desc = (REG_SEC_DESC *)&sk_hdr->sec_desc[0];
1993 tmp->sec_desc = process_sec_desc(regf, sec_desc);
1996 * Now forward and back links. Here we allocate an entry in the sk_map
1997 * if it does not exist, and mark it reserved
2000 sk_prev_off = IVAL(&sk_hdr->prev_off);
2001 tmp->prev = lookup_create_sec_key(regf, regf->sk_map, sk_prev_off);
2002 assert(tmp->prev != NULL);
2003 sk_next_off = IVAL(&sk_hdr->next_off);
2004 tmp->next = lookup_create_sec_key(regf, regf->sk_map, sk_next_off);
2005 assert(tmp->next != NULL);
2007 return tmp;
2011 * Process a VK header and return a value
2013 VAL_KEY *process_vk(REGF *regf, VK_HDR *vk_hdr, int size)
2015 char val_name[1024];
2016 int nam_len, dat_len, flag, dat_type, dat_off, vk_id;
2017 const char *val_type;
2018 VAL_KEY *tmp = NULL;
2020 if (!vk_hdr) return NULL;
2022 if ((vk_id = SVAL(&vk_hdr->VK_ID)) != REG_VK_ID) {
2023 fprintf(stderr, "Unrecognized VK header ID: %0X, block: %0X, %s\n",
2024 vk_id, (int)vk_hdr, regf->regfile_name);
2025 return NULL;
2028 nam_len = SVAL(&vk_hdr->nam_len);
2029 val_name[nam_len] = '\0';
2030 flag = SVAL(&vk_hdr->flag);
2031 dat_type = IVAL(&vk_hdr->dat_type);
2032 dat_len = IVAL(&vk_hdr->dat_len); /* If top bit, offset contains data */
2033 dat_off = IVAL(&vk_hdr->dat_off);
2035 tmp = (VAL_KEY *)malloc(sizeof(VAL_KEY));
2036 if (!tmp) {
2037 goto error;
2039 bzero(tmp, sizeof(VAL_KEY));
2040 tmp->has_name = flag;
2041 tmp->data_type = dat_type;
2043 if (flag & 0x01) {
2044 strncpy(val_name, vk_hdr->dat_name, nam_len);
2045 tmp->name = strdup(val_name);
2046 if (!tmp->name) {
2047 goto error;
2050 else
2051 strncpy(val_name, "<No Name>", 10);
2054 * Allocate space and copy the data as a BLOB
2057 if (dat_len) {
2059 char *dtmp = (char *)malloc(dat_len&0x7FFFFFFF);
2061 if (!dtmp) {
2062 goto error;
2065 tmp->data_blk = dtmp;
2067 if ((dat_len&0x80000000) == 0) { /* The data is pointed to by the offset */
2068 char *dat_ptr = LOCN(regf->base, dat_off);
2069 bcopy(dat_ptr, dtmp, dat_len);
2071 else { /* The data is in the offset or type */
2073 * FIXME.
2074 * Some registry files seem to have wierd fields. If top bit is set,
2075 * but len is 0, the type seems to be the value ...
2076 * Not sure how to handle this last type for the moment ...
2078 dat_len = dat_len & 0x7FFFFFFF;
2079 bcopy(&dat_off, dtmp, dat_len);
2082 tmp->data_len = dat_len;
2085 val_type = val_to_str(dat_type, reg_type_names);
2088 * We need to save the data area as well
2091 if (verbose) fprintf(stdout, " %s : %s : \n", val_name, val_type);
2093 return tmp;
2095 error:
2096 if (tmp) nt_delete_val_key(tmp);
2097 return NULL;
2102 * Process a VL Header and return a list of values
2104 VAL_LIST *process_vl(REGF *regf, VL_TYPE vl, int count, int size)
2106 int i, vk_off;
2107 VK_HDR *vk_hdr;
2108 VAL_LIST *tmp = NULL;
2110 if (!vl) return NULL;
2112 if (-size < (count+1)*sizeof(int)){
2113 fprintf(stderr, "Error in VL header format. Size less than space required. %d\n", -size);
2114 return NULL;
2117 tmp = (VAL_LIST *)malloc(sizeof(VAL_LIST) + (count - 1) * sizeof(VAL_KEY *));
2118 if (!tmp) {
2119 goto error;
2122 for (i=0; i<count; i++) {
2123 vk_off = IVAL(&vl[i]);
2124 vk_hdr = (VK_HDR *)LOCN(regf->base, vk_off);
2125 tmp->vals[i] = process_vk(regf, vk_hdr, BLK_SIZE(vk_hdr));
2126 if (!tmp->vals[i]){
2127 goto error;
2131 tmp->val_count = count;
2132 tmp->max_vals = count;
2134 return tmp;
2136 error:
2137 /* XXX: FIXME, free the partially allocated structure */
2138 return NULL;
2142 * Process an LF Header and return a list of sub-keys
2144 KEY_LIST *process_lf(REGF *regf, LF_HDR *lf_hdr, int size, REG_KEY *parent)
2146 int count, i, nk_off;
2147 unsigned int lf_id;
2148 KEY_LIST *tmp;
2150 if (!lf_hdr) return NULL;
2152 if ((lf_id = SVAL(&lf_hdr->LF_ID)) != REG_LF_ID) {
2153 fprintf(stderr, "Unrecognized LF Header format: %0X, Block: %0X, %s.\n",
2154 lf_id, (int)lf_hdr, regf->regfile_name);
2155 return NULL;
2158 assert(size < 0);
2160 count = SVAL(&lf_hdr->key_count);
2161 if (verbose) fprintf(stdout, "Key Count: %u\n", count);
2162 if (count <= 0) return NULL;
2164 /* Now, we should allocate a KEY_LIST struct and fill it in ... */
2166 tmp = (KEY_LIST *)malloc(sizeof(KEY_LIST) + (count - 1) * sizeof(REG_KEY *));
2167 if (!tmp) {
2168 goto error;
2171 tmp->key_count = count;
2172 tmp->max_keys = count;
2174 for (i=0; i<count; i++) {
2175 NK_HDR *nk_hdr;
2177 nk_off = IVAL(&lf_hdr->hr[i].nk_off);
2178 if (verbose) fprintf(stdout, "NK Offset: %0X\n", nk_off);
2179 nk_hdr = (NK_HDR *)LOCN(regf->base, nk_off);
2180 tmp->keys[i] = nt_get_key_tree(regf, nk_hdr, BLK_SIZE(nk_hdr), parent);
2181 if (!tmp->keys[i]) {
2182 goto error;
2186 return tmp;
2188 error:
2189 if (tmp) nt_delete_key_list(tmp, False);
2190 return NULL;
2194 * This routine is passed an NK_HDR pointer and retrieves the entire tree
2195 * from there down. It returns a REG_KEY *.
2197 REG_KEY *nt_get_key_tree(REGF *regf, NK_HDR *nk_hdr, int size, REG_KEY *parent)
2199 REG_KEY *tmp = NULL, *own;
2200 int name_len, clsname_len, lf_off, val_off, val_count, sk_off, own_off;
2201 unsigned int nk_id;
2202 LF_HDR *lf_hdr;
2203 VL_TYPE *vl;
2204 SK_HDR *sk_hdr;
2205 char key_name[1024], cls_name[1024];
2207 if (!nk_hdr) return NULL;
2209 if ((nk_id = SVAL(&nk_hdr->NK_ID)) != REG_NK_ID) {
2210 fprintf(stderr, "Unrecognized NK Header format: %08X, Block: %0X. %s\n",
2211 nk_id, (int)nk_hdr, regf->regfile_name);
2212 return NULL;
2215 assert(size < 0);
2217 name_len = SVAL(&nk_hdr->nam_len);
2218 clsname_len = SVAL(&nk_hdr->clsnam_len);
2221 * The value of -size should be ge
2222 * (sizeof(NK_HDR) - 1 + name_len)
2223 * The -1 accounts for the fact that we included the first byte of
2224 * the name in the structure. clsname_len is the length of the thing
2225 * pointed to by clsnam_off
2228 if (-size < (sizeof(NK_HDR) - 1 + name_len)) {
2229 fprintf(stderr, "Incorrect NK_HDR size: %d, %0X\n", -size, (int)nk_hdr);
2230 fprintf(stderr, "Sizeof NK_HDR: %d, name_len %d, clsname_len %d\n",
2231 sizeof(NK_HDR), name_len, clsname_len);
2232 /*return NULL;*/
2235 if (verbose) fprintf(stdout, "NK HDR: Name len: %d, class name len: %d\n",
2236 name_len, clsname_len);
2238 /* Fish out the key name and process the LF list */
2240 assert(name_len < sizeof(key_name));
2242 /* Allocate the key struct now */
2243 tmp = (REG_KEY *)malloc(sizeof(REG_KEY));
2244 if (!tmp) return tmp;
2245 bzero(tmp, sizeof(REG_KEY));
2247 tmp->type = (SVAL(&nk_hdr->type)==0x2C?REG_ROOT_KEY:REG_SUB_KEY);
2249 strncpy(key_name, nk_hdr->key_nam, name_len);
2250 key_name[name_len] = '\0';
2252 if (verbose) fprintf(stdout, "Key name: %s\n", key_name);
2254 tmp->name = strdup(key_name);
2255 if (!tmp->name) {
2256 goto error;
2260 * Fish out the class name, it is in UNICODE, while the key name is
2261 * ASCII :-)
2264 if (clsname_len) { /* Just print in Ascii for now */
2265 char *clsnamep;
2266 int clsnam_off;
2268 clsnam_off = IVAL(&nk_hdr->clsnam_off);
2269 clsnamep = LOCN(regf->base, clsnam_off);
2270 if (verbose) fprintf(stdout, "Class Name Offset: %0X\n", clsnam_off);
2272 bzero(cls_name, clsname_len);
2273 uni_to_ascii(clsnamep, cls_name, sizeof(cls_name), clsname_len);
2276 * I am keeping class name as an ascii string for the moment.
2277 * That means it needs to be converted on output.
2278 * It will also piss off people who need Unicode/UTF-8 strings. Sorry.
2279 * XXX: FIXME
2282 tmp->class_name = strdup(cls_name);
2283 if (!tmp->class_name) {
2284 goto error;
2287 if (verbose) fprintf(stdout, " Class Name: %s\n", cls_name);
2292 * Process the owner offset ...
2295 own_off = IVAL(&nk_hdr->own_off);
2296 own = (REG_KEY *)LOCN(regf->base, own_off);
2297 if (verbose) fprintf(stdout, "Owner Offset: %0X\n", own_off);
2299 if (verbose) fprintf(stdout, " Owner locn: %0X, Our locn: %0X\n",
2300 (unsigned int)own, (unsigned int)nk_hdr);
2303 * We should verify that the owner field is correct ...
2304 * for now, we don't worry ...
2307 tmp->owner = parent;
2310 * If there are any values, process them here
2313 val_count = IVAL(&nk_hdr->val_cnt);
2314 if (verbose) fprintf(stdout, "Val Count: %d\n", val_count);
2315 if (val_count) {
2317 val_off = IVAL(&nk_hdr->val_off);
2318 vl = (VL_TYPE *)LOCN(regf->base, val_off);
2319 if (verbose) fprintf(stdout, "Val List Offset: %0X\n", val_off);
2321 tmp->values = process_vl(regf, *vl, val_count, BLK_SIZE(vl));
2322 if (!tmp->values) {
2323 goto error;
2329 * Also handle the SK header ...
2332 sk_off = IVAL(&nk_hdr->sk_off);
2333 sk_hdr = (SK_HDR *)LOCN(regf->base, sk_off);
2334 if (verbose) fprintf(stdout, "SK Offset: %0X\n", sk_off);
2336 if (sk_off != -1) {
2338 tmp->security = process_sk(regf, sk_hdr, sk_off, BLK_SIZE(sk_hdr));
2342 lf_off = IVAL(&nk_hdr->lf_off);
2343 if (verbose) fprintf(stdout, "SubKey list offset: %0X\n", lf_off);
2346 * No more subkeys if lf_off == -1
2349 if (lf_off != -1) {
2351 lf_hdr = (LF_HDR *)LOCN(regf->base, lf_off);
2353 tmp->sub_keys = process_lf(regf, lf_hdr, BLK_SIZE(lf_hdr), tmp);
2354 if (!tmp->sub_keys){
2355 goto error;
2360 return tmp;
2362 error:
2363 if (tmp) nt_delete_reg_key(tmp, False);
2364 return NULL;
2367 int nt_load_registry(REGF *regf)
2369 REGF_HDR *regf_hdr;
2370 unsigned int regf_id, hbin_id;
2371 HBIN_HDR *hbin_hdr;
2372 NK_HDR *first_key;
2374 /* Get the header */
2376 if ((regf_hdr = nt_get_regf_hdr(regf)) == NULL) {
2377 return -1;
2380 /* Now process that header and start to read the rest in */
2382 if ((regf_id = IVAL(&regf_hdr->REGF_ID)) != REG_REGF_ID) {
2383 fprintf(stderr, "Unrecognized NT registry header id: %0X, %s\n",
2384 regf_id, regf->regfile_name);
2385 return -1;
2389 * Validate the header ...
2391 if (!valid_regf_hdr(regf_hdr)) {
2392 fprintf(stderr, "Registry file header does not validate: %s\n",
2393 regf->regfile_name);
2394 return -1;
2397 /* Update the last mod date, and then go get the first NK record and on */
2399 TTTONTTIME(regf, IVAL(&regf_hdr->tim1), IVAL(&regf_hdr->tim2));
2402 * The hbin hdr seems to be just uninteresting garbage. Check that
2403 * it is there, but that is all.
2406 hbin_hdr = (HBIN_HDR *)(regf->base + REGF_HDR_BLKSIZ);
2408 if ((hbin_id = IVAL(&hbin_hdr->HBIN_ID)) != REG_HBIN_ID) {
2409 fprintf(stderr, "Unrecognized registry hbin hdr ID: %0X, %s\n",
2410 hbin_id, regf->regfile_name);
2411 return -1;
2415 * Get a pointer to the first key from the hreg_hdr
2418 if (verbose) fprintf(stdout, "First Key: %0X\n",
2419 IVAL(&regf_hdr->first_key));
2421 first_key = (NK_HDR *)LOCN(regf->base, IVAL(&regf_hdr->first_key));
2422 if (verbose) fprintf(stdout, "First Key Offset: %0X\n",
2423 IVAL(&regf_hdr->first_key));
2425 if (verbose) fprintf(stdout, "Data Block Size: %d\n",
2426 IVAL(&regf_hdr->dblk_size));
2428 if (verbose) fprintf(stdout, "Offset to next hbin block: %0X\n",
2429 IVAL(&hbin_hdr->off_to_next));
2431 if (verbose) fprintf(stdout, "HBIN block size: %0X\n",
2432 IVAL(&hbin_hdr->blk_size));
2435 * Now, get the registry tree by processing that NK recursively
2438 regf->root = nt_get_key_tree(regf, first_key, BLK_SIZE(first_key), NULL);
2440 assert(regf->root != NULL);
2443 * Unmap the registry file, as we might want to read in another
2444 * tree etc.
2447 if (regf->base) munmap(regf->base, regf->sbuf.st_size);
2448 regf->base = NULL;
2449 close(regf->fd); /* Ignore the error :-) */
2451 return 1;
2455 * Allocate a new hbin block, set up the header for the block etc
2457 HBIN_BLK *nt_create_hbin_blk(REGF *regf, int size)
2459 HBIN_BLK *tmp;
2460 HBIN_HDR *hdr;
2462 if (!regf || !size) return NULL;
2464 /* Round size up to multiple of REGF_HDR_BLKSIZ */
2466 size = (size + (REGF_HDR_BLKSIZ - 1)) & ~(REGF_HDR_BLKSIZ - 1);
2468 tmp = (HBIN_BLK *)malloc(sizeof(HBIN_BLK));
2469 bzero(tmp, sizeof(HBIN_BLK));
2471 tmp->data = malloc(size);
2472 if (!tmp->data) goto error;
2474 bzero(tmp->data, size); /* Make it pristine */
2476 tmp->size = size;
2477 tmp->file_offset = regf->blk_tail->file_offset + regf->blk_tail->size;
2479 tmp->free_space = size - (sizeof(HBIN_HDR) - sizeof(HBIN_SUB_HDR));
2480 tmp->fsp_off = size - tmp->free_space;
2483 * Now, build the header in the data block
2485 hdr = (HBIN_HDR *)tmp->data;
2486 hdr->HBIN_ID = REG_HBIN_ID;
2487 hdr->off_from_first = tmp->file_offset - REGF_HDR_BLKSIZ;
2488 hdr->off_to_next = tmp->size;
2489 hdr->blk_size = tmp->size;
2492 * Now link it in
2495 regf->blk_tail->next = tmp;
2496 regf->blk_tail = tmp;
2497 if (!regf->free_space) regf->free_space = tmp;
2499 return tmp;
2500 error:
2501 if (tmp) free(tmp);
2502 return NULL;
2506 * Allocate a unit of space ... and return a pointer as function param
2507 * and the block's offset as a side effect
2509 void *nt_alloc_regf_space(REGF *regf, int size, int *off)
2511 int tmp = 0;
2512 void *ret = NULL;
2513 HBIN_BLK *blk;
2515 if (!regf || !size || !off) return NULL;
2517 assert(regf->blk_head != NULL);
2520 * round up size to include header and then to 8-byte boundary
2522 size = (size + 4 + 7) & ~7;
2525 * Check if there is space, if none, grab a block
2527 if (!regf->free_space) {
2528 if (!nt_create_hbin_blk(regf, REGF_HDR_BLKSIZ))
2529 return NULL;
2533 * Now, chain down the list of blocks looking for free space
2536 for (blk = regf->free_space; blk != NULL; blk = blk->next) {
2537 if (blk->free_space <= size) {
2538 tmp = blk->file_offset + blk->fsp_off - REGF_HDR_BLKSIZ;
2539 ret = blk->data + blk->fsp_off;
2540 blk->free_space -= size;
2541 blk->fsp_off += size;
2543 /* Insert the header */
2544 ((HBIN_SUB_HDR *)ret)->dblocksize = -size;
2547 * Fix up the free space ptr
2548 * If it is NULL, we fix it up next time
2551 if (!blk->free_space)
2552 regf->free_space = blk->next;
2554 *off = tmp;
2555 return (((char *)ret)+4);/* The pointer needs to be to the data struct */
2560 * If we got here, we need to add another block, which might be
2561 * larger than one block -- deal with that later
2563 if (nt_create_hbin_blk(regf, REGF_HDR_BLKSIZ)) {
2564 blk = regf->free_space;
2565 tmp = blk->file_offset + blk->fsp_off - REGF_HDR_BLKSIZ;
2566 ret = blk->data + blk->fsp_off;
2567 blk->free_space -= size;
2568 blk->fsp_off += size;
2570 /* Insert the header */
2571 ((HBIN_SUB_HDR *)ret)->dblocksize = -size;
2574 * Fix up the free space ptr
2575 * If it is NULL, we fix it up next time
2578 if (!blk->free_space)
2579 regf->free_space = blk->next;
2581 *off = tmp;
2582 return (((char *)ret) + 4);/* The pointer needs to be to the data struct */
2585 return NULL;
2589 * Compute the size of a SID stored ...
2592 unsigned int sid_size(DOM_SID *sid)
2594 unsigned int size;
2596 if (!sid) return 0;
2598 size = 8 + (sid->auths * sizeof(unsigned int));
2600 return size;
2604 * Compute the size of an ACE on disk from its components
2607 unsigned int ace_size(ACE *ace)
2609 unsigned int size;
2611 if (!ace) return 0;
2613 size = 8 + sid_size(ace->trustee);
2615 return size;
2619 * Compute the size of an ACL from its components ...
2621 unsigned int acl_size(ACL *acl)
2623 unsigned int size;
2624 int i;
2626 if (!acl) return 0;
2628 size = 8;
2629 for (i = 0; i < acl->num_aces; i++)
2630 size += ace_size(acl->aces[i]);
2632 return size;
2636 * Compute the size of the sec desc as a self-relative SD
2638 unsigned int sec_desc_size(SEC_DESC *sd)
2640 unsigned int size;
2642 if (!sd) return 0;
2644 size = 20;
2646 if (sd->owner) size += sid_size(sd->owner);
2647 if (sd->group) size += sid_size(sd->group);
2648 if (sd->sacl) size += acl_size(sd->sacl);
2649 if (sd->dacl) size += acl_size(sd->dacl);
2651 return size;
2655 * Store the security information
2657 * If it has already been stored, just get its offset from record
2658 * otherwise, store it and record its offset
2661 unsigned int nt_store_security(REGF *regf, KEY_SEC_DESC *sec)
2663 int size = 0;
2664 unsigned int sk_off;
2665 SK_HDR *sk_hdr;
2667 if (sec->offset) return sec->offset;
2670 * OK, we don't have this one in the file yet. We must compute the
2671 * size taken by the security descriptor as a self-relative SD, which
2672 * means making one pass over each structure and figuring it out
2675 size = sec_desc_size(sec->sec_desc);
2677 /* Allocate that much space */
2679 sk_hdr = nt_alloc_regf_space(regf, size, &sk_off);
2681 if (!sk_hdr) return 0;
2683 /* Now, lay out the sec_desc in the space provided */
2685 return 0;
2690 * Store a KEY in the file ...
2692 * We store this depth first, and defer storing the lf struct until
2693 * all the sub-keys have been stored.
2695 * We store the NK hdr, any SK header, class name, and VK structure, then
2696 * recurse down the LF structures ...
2698 * We return the offset of the NK struct
2700 int nt_store_reg_key(REGF *regf, REG_KEY *key)
2702 NK_HDR *nk_hdr;
2703 unsigned int nk_off, sk_off, val_off, clsnam_off, size;
2705 if (!regf || !key) return 0;
2707 size = sizeof(NK_HDR) + strlen(key->name) - 1;
2708 nk_hdr = nt_alloc_regf_space(regf, size, &nk_off);
2709 if (!nk_hdr) goto error;
2711 key->offset = nk_off; /* We will need this later */
2714 * Now fill in each field etc ...
2717 nk_hdr->NK_ID = REG_NK_ID;
2718 if (key->type == REG_ROOT_KEY)
2719 nk_hdr->type = 0x2C;
2720 else
2721 nk_hdr->type = 0x20;
2723 /* FIXME: Fill in the time of last update */
2725 if (key->type != REG_ROOT_KEY)
2726 nk_hdr->own_off = key->owner->offset;
2728 if (key->sub_keys)
2729 nk_hdr->subk_num = key->sub_keys->key_count;
2732 * Now, process the Sec Desc and then store its offset
2735 sk_off = nt_store_security(regf, key->security);
2738 * Then, store the val list and store its offset
2743 * Finally, store the subkeys, and their offsets
2746 error:
2747 return 0;
2751 * Store the registry header ...
2752 * We actually create the registry header block and link it to the chain
2753 * of output blocks.
2755 REGF_HDR *nt_get_reg_header(REGF *regf)
2757 HBIN_BLK *tmp = NULL;
2759 tmp = (HBIN_BLK *)malloc(sizeof(HBIN_BLK));
2760 if (!tmp) return 0;
2762 bzero(tmp, sizeof(HBIN_BLK));
2763 tmp->type = REG_OUTBLK_HDR;
2764 tmp->size = REGF_HDR_BLKSIZ;
2765 tmp->data = malloc(REGF_HDR_BLKSIZ);
2766 if (!tmp->data) goto error;
2768 bzero(tmp->data, REGF_HDR_BLKSIZ); /* Make it pristine, unlike Windows */
2769 regf->blk_head = regf->blk_tail = tmp;
2771 return (REGF_HDR *)tmp->data;
2773 error:
2774 if (tmp) free(tmp);
2775 return NULL;
2779 * Store the registry in the output file
2780 * We write out the header and then each of the keys etc into the file
2781 * We have to flatten the data structure ...
2783 * The structures are stored in a depth-first fashion, with all records
2784 * aligned on 8-byte boundaries, with sub-keys and values layed down before
2785 * the lists that contain them. SK records are layed down first, however.
2786 * The lf fields are layed down after all sub-keys have been layed down, it
2787 * seems, including the whole tree associated with each sub-key.
2789 int nt_store_registry(REGF *regf)
2791 REGF_HDR *reg;
2792 int fkey;
2795 * Get a header ... and partially fill it in ...
2797 reg = nt_get_reg_header(regf);
2800 * Store the first key
2802 fkey = nt_store_reg_key(regf, regf->root);
2804 return 1;
2808 * Routines to parse a REGEDIT4 file
2810 * The file consists of:
2812 * REGEDIT4
2813 * \[[-]key-path\]\n
2814 * <value-spec>*
2816 * Format:
2817 * [cmd:]name=type:value
2819 * cmd = a|d|c|add|delete|change|as|ds|cs
2821 * There can be more than one key-path and value-spec.
2823 * Since we want to support more than one type of file format, we
2824 * construct a command-file structure that keeps info about the command file
2827 #define FMT_UNREC -1
2828 #define FMT_REGEDIT4 0
2829 #define FMT_EDITREG1_1 1
2831 #define FMT_STRING_REGEDIT4 "REGEDIT4"
2832 #define FMT_STRING_EDITREG1_0 "EDITREG1.0"
2834 #define CMD_NONE 0
2835 #define CMD_ADD_KEY 1
2836 #define CMD_DEL_KEY 2
2838 #define CMD_KEY 1
2839 #define CMD_VAL 2
2841 typedef struct val_spec_list {
2842 struct val_spec_list *next;
2843 char *name;
2844 int type;
2845 char *val; /* Kept as a char string, really? */
2846 } VAL_SPEC_LIST;
2848 typedef struct command_s {
2849 int cmd;
2850 char *key;
2851 int val_count;
2852 VAL_SPEC_LIST *val_spec_list, *val_spec_last;
2853 } CMD;
2855 typedef struct cmd_line {
2856 int len, line_len;
2857 char *line;
2858 } CMD_LINE;
2860 void free_val_spec_list(VAL_SPEC_LIST *vl)
2862 if (!vl) return;
2863 if (vl->name) free(vl->name);
2864 if (vl->val) free(vl->val);
2865 free(vl);
2870 * Some routines to handle lines of info in the command files
2872 void skip_to_eol(int fd)
2874 int rc;
2875 char ch = 0;
2877 while ((rc = read(fd, &ch, 1)) == 1) {
2878 if (ch == 0x0A) return;
2880 if (rc < 0) {
2881 fprintf(stderr, "Could not read file descriptor: %d, %s\n",
2882 fd, strerror(errno));
2883 exit(1);
2887 void free_cmd(CMD *cmd)
2889 if (!cmd) return;
2891 while (cmd->val_spec_list) {
2892 VAL_SPEC_LIST *tmp;
2894 tmp = cmd->val_spec_list;
2895 cmd->val_spec_list = tmp->next;
2896 free(tmp);
2899 free(cmd);
2903 void free_cmd_line(CMD_LINE *cmd_line)
2905 if (cmd_line) {
2906 if (cmd_line->line) free(cmd_line->line);
2907 free(cmd_line);
2911 void print_line(struct cmd_line *cl)
2913 char *pl;
2915 if (!cl) return;
2917 if ((pl = malloc(cl->line_len + 1)) == NULL) {
2918 fprintf(stderr, "Unable to allocate space to print line: %s\n",
2919 strerror(errno));
2920 exit(1);
2923 strncpy(pl, cl->line, cl->line_len);
2924 pl[cl->line_len] = 0;
2926 fprintf(stdout, "%s\n", pl);
2927 free(pl);
2930 #define INIT_ALLOC 10
2933 * Read a line from the input file.
2934 * NULL returned when EOF and no chars read
2935 * Otherwise we return a cmd_line *
2936 * Exit if other errors
2938 struct cmd_line *get_cmd_line(int fd)
2940 struct cmd_line *cl = (CMD_LINE *)malloc(sizeof(CMD_LINE));
2941 int i = 0, rc;
2942 unsigned char ch;
2944 if (!cl) {
2945 fprintf(stderr, "Unable to allocate structure for command line: %s\n",
2946 strerror(errno));
2947 exit(1);
2950 cl->len = INIT_ALLOC;
2953 * Allocate some space for the line. We extend later if needed.
2956 if ((cl->line = (char *)malloc(INIT_ALLOC)) == NULL) {
2957 fprintf(stderr, "Unable to allocate initial space for line: %s\n",
2958 strerror(errno));
2959 exit(1);
2963 * Now read in the chars to EOL. Don't store the EOL in the
2964 * line. What about CR?
2967 while ((rc = read(fd, &ch, 1)) == 1 && ch != '\n') {
2968 if (ch == '\r') continue; /* skip CR */
2969 if (i == cl->len) {
2971 * Allocate some more memory
2973 if ((cl->line = realloc(cl->line, cl->len + INIT_ALLOC)) == NULL) {
2974 fprintf(stderr, "Unable to realloc space for line: %s\n",
2975 strerror(errno));
2976 exit(1);
2978 cl->len += INIT_ALLOC;
2980 cl->line[i] = ch;
2981 i++;
2984 /* read 0 and we were at loc'n 0, return NULL */
2985 if (rc == 0 && i == 0) {
2986 free_cmd_line(cl);
2987 return NULL;
2990 cl->line_len = i;
2992 return cl;
2997 * parse_value: parse out a value. We pull it apart as:
2999 * <value> ::= <value-name>=<type>:<value-string>
3001 * <value-name> ::= char-string-without-spaces | '"' char-string '"'
3003 * If it parsed OK, return the <value-name> as a string, and the
3004 * value type and value-string in parameters.
3006 * The value name can be empty. There can only be one empty name in
3007 * a list of values. A value of - removes the value entirely.
3010 char *dup_str(char *s, int len)
3012 char *nstr;
3013 nstr = (char *)malloc(len + 1);
3014 if (nstr) {
3015 memcpy(nstr, s, len);
3016 nstr[len] = 0;
3018 return nstr;
3021 char *parse_name(char *nstr)
3023 int len = 0, start = 0;
3024 if (!nstr) return NULL;
3026 len = strlen(nstr);
3028 while (len && nstr[len - 1] == ' ') len--;
3030 nstr[len] = 0; /* Trim any spaces ... if there were none, doesn't matter */
3033 * Beginning and end should be '"' or neither should be so
3035 if ((nstr[0] == '"' && nstr[len - 1] != '"') ||
3036 (nstr[0] != '"' && nstr[len - 1] == '"'))
3037 return NULL;
3039 if (nstr[0] == '"') {
3040 start = 1;
3041 len -= 2;
3044 return dup_str(&nstr[start], len);
3047 int parse_value_type(char *tstr)
3049 int len = strlen(tstr);
3051 while (len && tstr[len - 1] == ' ') len--;
3052 tstr[len] = 0;
3054 if (strcmp(tstr, "REG_DWORD") == 0)
3055 return REG_TYPE_DWORD;
3056 else if (strcmp(tstr, "dword") == 0)
3057 return REG_TYPE_DWORD;
3058 else if (strcmp(tstr, "REG_EXPAND_SZ") == 0)
3059 return REG_TYPE_EXPANDSZ;
3060 else if (strcmp(tstr, "REG_BIN") == 0)
3061 return REG_TYPE_BIN;
3062 else if (strcmp(tstr, "REG_SZ") == 0)
3063 return REG_TYPE_REGSZ;
3064 else if (strcmp(tstr, "REG_MULTI_SZ") == 0)
3065 return REG_TYPE_MULTISZ;
3066 else if (strcmp(tstr, "-") == 0)
3067 return REG_TYPE_DELETE;
3069 return 0;
3072 char *parse_val_str(char *vstr)
3075 return dup_str(vstr, strlen(vstr));
3079 char *parse_value(struct cmd_line *cl, int *vtype, char **val)
3081 char *p1 = NULL, *p2 = NULL, *nstr = NULL, *tstr = NULL, *vstr = NULL;
3083 if (!cl || !vtype || !val) return NULL;
3084 if (!cl->line_len) return NULL;
3086 p1 = dup_str(cl->line, cl->line_len);
3087 /* FIXME: Better return codes etc ... */
3088 if (!p1) return NULL;
3089 p2 = strchr(p1, '=');
3090 if (!p2) return NULL;
3092 *p2 = 0; p2++; /* Split into two strings at p2 */
3094 /* Now, parse the name ... */
3096 nstr = parse_name(p1);
3097 if (!nstr) goto error;
3099 /* Now, split the remainder and parse on type and val ... */
3101 tstr = p2;
3102 while (*tstr == ' ') tstr++; /* Skip leading white space */
3103 p2 = strchr(p2, ':');
3105 if (p2) {
3106 *p2 = 0; p2++; /* split on the : */
3109 *vtype = parse_value_type(tstr);
3111 if (!vtype) goto error;
3113 if (!p2 || !*p2) return nstr;
3115 /* Now, parse the value string. It should return a newly malloc'd string */
3117 while (*p2 == ' ') p2++; /* Skip leading space */
3118 vstr = parse_val_str(p2);
3120 if (!vstr) goto error;
3122 *val = vstr;
3124 return nstr;
3126 error:
3127 if (p1) free(p1);
3128 if (nstr) free(nstr);
3129 if (vstr) free(vstr);
3130 return NULL;
3134 * Parse out a key. Look for a correctly formatted key [...]
3135 * and whether it is a delete or add? A delete is signalled
3136 * by a - in front of the key.
3137 * Assumes that there are no leading and trailing spaces
3140 char *parse_key(struct cmd_line *cl, int *cmd)
3142 int start = 1;
3143 char *tmp;
3145 if (cl->line[0] != '[' ||
3146 cl->line[cl->line_len - 1] != ']') return NULL;
3147 if (cl->line_len == 2) return NULL;
3148 *cmd = CMD_ADD_KEY;
3149 if (cl->line[1] == '-') {
3150 if (cl->line_len == 3) return NULL;
3151 start = 2;
3152 *cmd = CMD_DEL_KEY;
3154 tmp = malloc(cl->line_len - 1 - start + 1);
3155 if (!tmp) return tmp; /* Bail out on no mem ... FIXME */
3156 strncpy(tmp, &cl->line[start], cl->line_len - 1 - start);
3157 tmp[cl->line_len - 1 - start] = 0;
3158 return tmp;
3162 * Parse a line to determine if we have a key or a value
3163 * We only check for key or val ...
3166 int parse_line(struct cmd_line *cl)
3169 if (!cl || cl->len == 0) return 0;
3171 if (cl->line[0] == '[') /* No further checking for now */
3172 return CMD_KEY;
3173 else
3174 return CMD_VAL;
3178 * We seek to offset 0, read in the required number of bytes,
3179 * and compare to the correct value.
3180 * We then seek back to the original location
3182 int regedit4_file_type(int fd)
3184 int cur_ofs = 0;
3185 char desc[9];
3187 cur_ofs = lseek(fd, 0, SEEK_CUR); /* Get current offset */
3188 if (cur_ofs < 0) {
3189 fprintf(stderr, "Unable to get current offset: %s\n", strerror(errno));
3190 exit(1); /* FIXME */
3193 if (cur_ofs) {
3194 lseek(fd, 0, SEEK_SET);
3197 if (read(fd, desc, 8) < 8) {
3198 fprintf(stderr, "Unable to read command file format\n");
3199 exit(2); /* FIXME */
3202 desc[8] = 0;
3204 if (strcmp(desc, FMT_STRING_REGEDIT4) == 0) {
3205 if (cur_ofs) {
3206 lseek(fd, cur_ofs, SEEK_SET);
3208 else {
3209 skip_to_eol(fd);
3211 return FMT_REGEDIT4;
3214 return FMT_UNREC;
3218 * Run though the data in the line and strip anything after a comment
3219 * char.
3221 void strip_comment(struct cmd_line *cl)
3223 int i;
3225 if (!cl) return;
3227 for (i = 0; i < cl->line_len; i++) {
3228 if (cl->line[i] == ';') {
3229 cl->line_len = i;
3230 return;
3236 * trim leading space
3239 void trim_leading_spaces(struct cmd_line *cl)
3241 int i;
3243 if (!cl) return;
3245 for (i = 0; i < cl->line_len; i++) {
3246 if (cl->line[i] != ' '){
3247 if (i) memcpy(cl->line, &cl->line[i], cl->line_len - i);
3248 return;
3254 * trim trailing spaces
3256 void trim_trailing_spaces(struct cmd_line *cl)
3258 int i;
3260 if (!cl) return;
3262 for (i = cl->line_len; i == 0; i--) {
3263 if (cl->line[i-1] != ' ' &&
3264 cl->line[i-1] != '\t') {
3265 cl->line_len = i;
3271 * Get a command ... This consists of possibly multiple lines:
3272 * [key]
3273 * values*
3274 * possibly Empty line
3276 * value ::= <value-name>=<value-type>':'<value-string>
3277 * <value-name> is some path, possibly enclosed in quotes ...
3278 * We alctually look for the next key to terminate a previous key
3279 * if <value-type> == '-', then it is a delete type.
3281 CMD *regedit4_get_cmd(int fd)
3283 struct command_s *cmd = NULL;
3284 struct cmd_line *cl = NULL;
3285 struct val_spec_list *vl = NULL;
3287 if ((cmd = (struct command_s *)malloc(sizeof(struct command_s))) == NULL) {
3288 fprintf(stderr, "Unable to malloc space for command: %s\n",
3289 strerror(errno));
3290 exit(1);
3293 cmd->cmd = CMD_NONE;
3294 cmd->key = NULL;
3295 cmd->val_count = 0;
3296 cmd->val_spec_list = cmd->val_spec_last = NULL;
3297 while ((cl = get_cmd_line(fd))) {
3300 * If it is an empty command line, and we already have a key
3301 * then exit from here ... FIXME: Clean up the parser
3304 if (cl->line_len == 0 && cmd->key) {
3305 free_cmd_line(cl);
3306 break;
3309 strip_comment(cl); /* remove anything beyond a comment char */
3310 trim_trailing_spaces(cl);
3311 trim_leading_spaces(cl);
3313 if (cl->line_len == 0) { /* An empty line */
3314 free_cmd_line(cl);
3316 else { /* Else, non-empty ... */
3318 * Parse out the bits ...
3320 switch (parse_line(cl)) {
3321 case CMD_KEY:
3322 if ((cmd->key = parse_key(cl, &cmd->cmd)) == NULL) {
3323 fprintf(stderr, "Error parsing key from line: ");
3324 print_line(cl);
3325 fprintf(stderr, "\n");
3327 break;
3329 case CMD_VAL:
3331 * We need to add the value stuff to the list
3332 * There could be a \ on the end which we need to
3333 * handle at some time
3335 vl = (struct val_spec_list *)malloc(sizeof(struct val_spec_list));
3336 if (!vl) goto error;
3337 vl->next = NULL;
3338 vl->val = NULL;
3339 vl->name = parse_value(cl, &vl->type, &vl->val);
3340 if (!vl->name) goto error;
3341 if (cmd->val_spec_list == NULL) {
3342 cmd->val_spec_list = cmd->val_spec_last = vl;
3344 else {
3345 cmd->val_spec_last->next = vl;
3346 cmd->val_spec_last = vl;
3348 cmd->val_count++;
3349 break;
3351 default:
3352 fprintf(stderr, "Unrecognized line in command file: \n");
3353 print_line(cl);
3354 break;
3359 if (!cmd->cmd) goto error; /* End of file ... */
3361 return cmd;
3363 error:
3364 if (vl) free(vl);
3365 if (cmd) free_cmd(cmd);
3366 return NULL;
3369 int regedit4_exec_cmd(CMD *cmd)
3372 return 0;
3375 int editreg_1_0_file_type(int fd)
3377 int cur_ofs = 0;
3378 char desc[11];
3380 cur_ofs = lseek(fd, 0, SEEK_CUR); /* Get current offset */
3381 if (cur_ofs < 0) {
3382 fprintf(stderr, "Unable to get current offset: %s\n", strerror(errno));
3383 exit(1); /* FIXME */
3386 if (cur_ofs) {
3387 lseek(fd, 0, SEEK_SET);
3390 if (read(fd, desc, 10) < 10) {
3391 fprintf(stderr, "Unable to read command file format\n");
3392 exit(2); /* FIXME */
3395 desc[10] = 0;
3397 if (strcmp(desc, FMT_STRING_EDITREG1_0) == 0) {
3398 lseek(fd, cur_ofs, SEEK_SET);
3399 return FMT_REGEDIT4;
3402 return FMT_UNREC;
3405 CMD *editreg_1_0_get_cmd(int fd)
3407 return NULL;
3410 int editreg_1_0_exec_cmd(CMD *cmd)
3413 return -1;
3416 typedef struct command_ops_s {
3417 int type;
3418 int (*file_type)(int fd);
3419 CMD *(*get_cmd)(int fd);
3420 int (*exec_cmd)(CMD *cmd);
3421 } CMD_OPS;
3423 CMD_OPS default_cmd_ops[] = {
3424 {0, regedit4_file_type, regedit4_get_cmd, regedit4_exec_cmd},
3425 {1, editreg_1_0_file_type, editreg_1_0_get_cmd, editreg_1_0_exec_cmd},
3426 {-1, NULL, NULL, NULL}
3429 typedef struct command_file_s {
3430 char *name;
3431 int type, fd;
3432 CMD_OPS cmd_ops;
3433 } CMD_FILE;
3436 * Create a new command file structure
3439 CMD_FILE *cmd_file_create(char *file)
3441 CMD_FILE *tmp;
3442 struct stat sbuf;
3443 int i = 0;
3446 * Let's check if the file exists ...
3447 * No use creating the cmd_file structure if the file does not exist
3450 if (stat(file, &sbuf) < 0) { /* Not able to access file */
3452 return NULL;
3455 tmp = (CMD_FILE *)malloc(sizeof(CMD_FILE));
3456 if (!tmp) {
3457 return NULL;
3461 * Let's fill in some of the fields;
3464 tmp->name = strdup(file);
3466 if ((tmp->fd = open(file, O_RDONLY, 666)) < 0) {
3467 free(tmp);
3468 return NULL;
3472 * Now, try to find the format by indexing through the table
3474 while (default_cmd_ops[i].type != -1) {
3475 if ((tmp->type = default_cmd_ops[i].file_type(tmp->fd)) >= 0) {
3476 tmp->cmd_ops = default_cmd_ops[i];
3477 return tmp;
3479 i++;
3483 * If we got here, return NULL, as we could not figure out the type
3484 * of command file.
3486 * What about errors?
3489 free(tmp);
3490 return NULL;
3494 * Extract commands from the command file, and execute them.
3495 * We pass a table of command callbacks for that
3499 * Main code from here on ...
3503 * key print function here ...
3506 int print_key(const char *path, char *name, char *class_name, int root,
3507 int terminal, int vals)
3510 if (full_print || terminal) fprintf(stdout, "[%s%s]\n", path, name);
3512 return 1;
3516 * Sec Desc print functions
3519 void print_type(unsigned char type)
3521 switch (type) {
3522 case 0x00:
3523 fprintf(stdout, " ALLOW");
3524 break;
3525 case 0x01:
3526 fprintf(stdout, " DENY");
3527 break;
3528 case 0x02:
3529 fprintf(stdout, " AUDIT");
3530 break;
3531 case 0x03:
3532 fprintf(stdout, " ALARM");
3533 break;
3534 case 0x04:
3535 fprintf(stdout, "ALLOW CPD");
3536 break;
3537 case 0x05:
3538 fprintf(stdout, "OBJ ALLOW");
3539 break;
3540 case 0x06:
3541 fprintf(stdout, " OBJ DENY");
3542 default:
3543 fprintf(stdout, " UNKNOWN");
3544 break;
3548 void print_flags(unsigned char flags)
3550 char flg_output[21];
3551 int some = 0;
3553 flg_output[0] = 0;
3554 if (!flags) {
3555 fprintf(stdout, " ");
3556 return;
3558 if (flags & 0x01) {
3559 if (some) strcat(flg_output, ",");
3560 some = 1;
3561 strcat(flg_output, "OI");
3563 if (flags & 0x02) {
3564 if (some) strcat(flg_output, ",");
3565 some = 1;
3566 strcat(flg_output, "CI");
3568 if (flags & 0x04) {
3569 if (some) strcat(flg_output, ",");
3570 some = 1;
3571 strcat(flg_output, "NP");
3573 if (flags & 0x08) {
3574 if (some) strcat(flg_output, ",");
3575 some = 1;
3576 strcat(flg_output, "IO");
3578 if (flags & 0x10) {
3579 if (some) strcat(flg_output, ",");
3580 some = 1;
3581 strcat(flg_output, "IA");
3583 if (flags == 0xF) {
3584 if (some) strcat(flg_output, ",");
3585 some = 1;
3586 strcat(flg_output, "VI");
3588 fprintf(stdout, " %s", flg_output);
3591 void print_perms(int perms)
3593 fprintf(stdout, " %8X", perms);
3596 void print_sid(DOM_SID *sid)
3598 int i, comps = sid->auths;
3599 fprintf(stdout, "S-%u-%u", sid->ver, sid->auth[5]);
3601 for (i = 0; i < comps; i++) {
3603 fprintf(stdout, "-%u", sid->sub_auths[i]);
3606 fprintf(stdout, "\n");
3609 void print_acl(ACL *acl, char *prefix)
3611 int i;
3613 for (i = 0; i < acl->num_aces; i++) {
3614 fprintf(stdout, ";;%s", prefix);
3615 print_type(acl->aces[i]->type);
3616 print_flags(acl->aces[i]->flags);
3617 print_perms(acl->aces[i]->perms);
3618 fprintf(stdout, " ");
3619 print_sid(acl->aces[i]->trustee);
3623 int print_sec(SEC_DESC *sec_desc)
3625 if (!print_security) return 1;
3626 fprintf(stdout, ";; SECURITY\n");
3627 fprintf(stdout, ";; Owner: ");
3628 print_sid(sec_desc->owner);
3629 fprintf(stdout, ";; Group: ");
3630 print_sid(sec_desc->group);
3631 if (sec_desc->sacl) {
3632 fprintf(stdout, ";; SACL:\n");
3633 print_acl(sec_desc->sacl, " ");
3635 if (sec_desc->dacl) {
3636 fprintf(stdout, ";; DACL:\n");
3637 print_acl(sec_desc->dacl, " ");
3639 return 1;
3643 * Value print function here ...
3645 int print_val(const char *path, char *val_name, int val_type, int data_len,
3646 void *data_blk, int terminal, int first, int last)
3648 char data_asc[1024];
3650 bzero(data_asc, sizeof(data_asc));
3651 if (!terminal && first)
3652 fprintf(stdout, "%s\n", path);
3653 data_to_ascii((unsigned char *)data_blk, data_len, val_type, data_asc,
3654 sizeof(data_asc) - 1);
3655 fprintf(stdout, " %s = %s : %s\n", (val_name?val_name:"<No Name>"),
3656 val_to_str(val_type, reg_type_names), data_asc);
3657 return 1;
3660 void usage(void)
3662 fprintf(stderr, "Usage: editreg [-f] [-v] [-p] [-k] [-s] [-c <command-file>] <registryfile>\n");
3663 fprintf(stderr, "Version: 0.1\n\n");
3664 fprintf(stderr, "\n\t-v\t sets verbose mode");
3665 fprintf(stderr, "\n\t-f\t sets full print mode where non-terminals are printed");
3666 fprintf(stderr, "\n\t-p\t prints the registry");
3667 fprintf(stderr, "\n\t-s\t prints security descriptors");
3668 fprintf(stderr, "\n\t-c <command-file>\t specifies a command file");
3669 fprintf(stderr, "\n");
3672 int main(int argc, char *argv[])
3674 REGF *regf;
3675 extern char *optarg;
3676 extern int optind;
3677 int opt, print_keys = 0;
3678 int regf_opt = 1; /* Command name */
3679 int commands = 0;
3680 char *cmd_file_name = NULL;
3681 char *out_file_name = NULL;
3682 CMD_FILE *cmd_file = NULL;
3683 DOM_SID *lsid;
3685 if (argc < 2) {
3686 usage();
3687 exit(1);
3691 * Now, process the arguments
3694 while ((opt = getopt(argc, argv, "fspvko:O:c:")) != EOF) {
3695 switch (opt) {
3696 case 'c':
3697 commands = 1;
3698 cmd_file_name = optarg;
3699 regf_opt += 2;
3700 break;
3702 case 'f':
3703 full_print = 1;
3704 regf_opt++;
3705 break;
3707 case 'o':
3708 out_file_name = optarg;
3709 regf_opt += 2;
3710 break;
3712 case 'O':
3713 def_owner_sid_str = strdup(optarg);
3714 regf_opt += 2;
3715 if (!string_to_sid(&lsid, def_owner_sid_str)) {
3716 fprintf(stderr, "Default Owner SID: %s is incorrectly formatted\n",
3717 def_owner_sid_str);
3718 free(def_owner_sid_str);
3719 def_owner_sid_str = NULL;
3721 else
3722 nt_delete_sid(lsid);
3723 break;
3725 case 'p':
3726 print_keys++;
3727 regf_opt++;
3728 break;
3730 case 's':
3731 print_security++;
3732 full_print++;
3733 regf_opt++;
3734 break;
3736 case 'v':
3737 verbose++;
3738 regf_opt++;
3739 break;
3741 case 'k':
3742 regf_opt++;
3743 break;
3745 default:
3746 usage();
3747 exit(1);
3748 break;
3753 * We only want to complain about the lack of a default owner SID if
3754 * we need one. This approximates that need
3756 if (!def_owner_sid_str) {
3757 def_owner_sid_str = "S-1-5-21-1-2-3-4";
3758 if (out_file_name || verbose)
3759 fprintf(stderr, "Warning, default owner SID not set. Setting to %s\n",
3760 def_owner_sid_str);
3763 if ((regf = nt_create_regf()) == NULL) {
3764 fprintf(stderr, "Could not create registry object: %s\n", strerror(errno));
3765 exit(2);
3768 if (regf_opt < argc) { /* We have a registry file */
3769 if (!nt_set_regf_input_file(regf, argv[regf_opt])) {
3770 fprintf(stderr, "Could not set name of registry file: %s, %s\n",
3771 argv[regf_opt], strerror(errno));
3772 exit(3);
3775 /* Now, open it, and bring it into memory :-) */
3777 if (nt_load_registry(regf) < 0) {
3778 fprintf(stderr, "Could not load registry: %s\n", argv[1]);
3779 exit(4);
3783 if (out_file_name) {
3784 if (!nt_set_regf_output_file(regf, out_file_name)) {
3785 fprintf(stderr, "Could not set name of output registry file: %s, %s\n",
3786 out_file_name, strerror(errno));
3787 exit(3);
3792 if (commands) {
3793 CMD *cmd;
3795 cmd_file = cmd_file_create(cmd_file_name);
3797 while ((cmd = cmd_file->cmd_ops.get_cmd(cmd_file->fd)) != NULL) {
3800 * Now, apply the requests to the tree ...
3802 switch (cmd->cmd) {
3803 case CMD_ADD_KEY: {
3804 REG_KEY *tmp = NULL;
3806 tmp = nt_find_key_by_name(regf->root, cmd->key);
3808 /* If we found it, apply the other bits, else create such a key */
3810 if (!tmp)
3811 tmp = nt_add_reg_key(regf, cmd->key, True);
3813 if (tmp) {
3817 while (cmd->val_count) {
3818 VAL_SPEC_LIST *val = cmd->val_spec_list;
3819 VAL_KEY *reg_val = NULL;
3821 if (val->type == REG_TYPE_DELETE) {
3822 reg_val = nt_delete_reg_value(tmp, val -> name);
3823 if (reg_val) nt_delete_val_key(reg_val);
3825 else {
3826 reg_val = nt_add_reg_value(tmp, val->name, val->type,
3827 val->val);
3830 cmd->val_spec_list = val->next;
3831 free_val_spec_list(val);
3832 cmd->val_count--;
3835 break;
3838 case CMD_DEL_KEY:
3840 * Any value does not matter ...
3841 * Find the key if it exists, and delete it ...
3844 nt_delete_key_by_name(regf, cmd->key);
3845 break;
3848 free_cmd(cmd);
3852 * At this point, we should have a registry in memory and should be able
3853 * to iterate over it.
3856 if (print_keys) {
3857 nt_key_iterator(regf, regf->root, 0, "", print_key, print_sec, print_val);
3860 return 0;