]> wimlib.net Git - wimlib/blob - src/security.c
Refactor some of the dentry, inode, and lookup table code
[wimlib] / src / security.c
1 /*
2  * security.c
3  *
4  * Read and write the per-WIM-image table of security descriptors.
5  */
6
7 /*
8  * Copyright (C) 2012, 2013 Eric Biggers
9  *
10  * This file is part of wimlib, a library for working with WIM files.
11  *
12  * wimlib is free software; you can redistribute it and/or modify it under the
13  * terms of the GNU General Public License as published by the Free
14  * Software Foundation; either version 3 of the License, or (at your option)
15  * any later version.
16  *
17  * wimlib is distributed in the hope that it will be useful, but WITHOUT ANY
18  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19  * A PARTICULAR PURPOSE. See the GNU General Public License for more
20  * details.
21  *
22  * You should have received a copy of the GNU General Public License
23  * along with wimlib; if not, see http://www.gnu.org/licenses/.
24  */
25
26 #ifdef HAVE_CONFIG_H
27 #  include "config.h"
28 #endif
29
30 #include "wimlib/assert.h"
31 #include "wimlib/endianness.h"
32 #include "wimlib/error.h"
33 #include "wimlib/security.h"
34 #include "wimlib/security_descriptor.h"
35 #include "wimlib/sha1.h"
36 #include "wimlib/util.h"
37
38 struct wim_security_data_disk {
39         le32 total_length;
40         le32 num_entries;
41         le64 sizes[];
42 } _packed_attribute;
43
44 struct wim_security_data *
45 new_wim_security_data(void)
46 {
47         return CALLOC(1, sizeof(struct wim_security_data));
48 }
49
50 /*
51  * Reads the security data from the metadata resource of a WIM image.
52  *
53  * @metadata_resource:  An array that contains the uncompressed metadata
54  *                              resource for the WIM image.
55  * @metadata_resource_len:      The length of @metadata_resource.  It must be at
56  *                              least 8 bytes.
57  * @sd_ret:     A pointer to a pointer to a wim_security_data structure that
58  *              will be filled in with a pointer to a new wim_security_data
59  *              structure containing the security data on success.
60  *
61  * Note: There is no `offset' argument because the security data is located at
62  * the beginning of the metadata resource.
63  *
64  * Return values:
65  *      WIMLIB_ERR_SUCCESS (0)
66  *      WIMLIB_ERR_INVALID_METADATA_RESOURCE
67  *      WIMLIB_ERR_NOMEM
68  */
69 int
70 read_wim_security_data(const u8 metadata_resource[], size_t metadata_resource_len,
71                        struct wim_security_data **sd_ret)
72 {
73         struct wim_security_data *sd;
74         int ret;
75         u64 total_len;
76         u64 sizes_size;
77         u64 size_no_descriptors;
78         const struct wim_security_data_disk *sd_disk;
79         const u8 *p;
80
81         wimlib_assert(metadata_resource_len >= 8);
82
83         sd = new_wim_security_data();
84         if (!sd)
85                 goto out_of_memory;
86
87         sd_disk = (const struct wim_security_data_disk*)metadata_resource;
88         sd->total_length = le32_to_cpu(sd_disk->total_length);
89         sd->num_entries = le32_to_cpu(sd_disk->num_entries);
90
91         DEBUG("Reading security data: num_entries=%u, total_length=%u",
92               sd->num_entries, sd->total_length);
93
94         /* Length field of 0 is a special case that really means length
95          * of 8. */
96         if (sd->total_length == 0)
97                 sd->total_length = 8;
98
99         /* The security_id field of each dentry is a signed 32-bit integer, so
100          * the possible indices into the security descriptors table are 0
101          * through 0x7fffffff.  Which means 0x80000000 security descriptors
102          * maximum.  Not like you should ever have anywhere close to that many
103          * security descriptors! */
104         if (sd->num_entries > 0x80000000)
105                 goto out_invalid_sd;
106
107         /* Verify the listed total length of the security data is big enough to
108          * include the sizes array, verify that the file data is big enough to
109          * include it as well, then allocate the array of sizes.
110          *
111          * Note: The total length of the security data must fit in a 32-bit
112          * integer, even though each security descriptor size is a 64-bit
113          * integer.  This is stupid, and we need to be careful not to actually
114          * let the security descriptor sizes be over 0xffffffff.  */
115         if (sd->total_length > metadata_resource_len)
116                 goto out_invalid_sd;
117
118         sizes_size = (u64)sd->num_entries * sizeof(u64);
119         size_no_descriptors = 8 + sizes_size;
120         if (size_no_descriptors > sd->total_length)
121                 goto out_invalid_sd;
122
123         total_len = size_no_descriptors;
124
125         /* Return immediately if no security descriptors. */
126         if (sd->num_entries == 0)
127                 goto out_align_total_length;
128
129         /* Allocate a new buffer for the sizes array */
130         sd->sizes = MALLOC(sizes_size);
131         if (!sd->sizes)
132                 goto out_of_memory;
133
134         /* Copy the sizes array into the new buffer */
135         for (u32 i = 0; i < sd->num_entries; i++) {
136                 sd->sizes[i] = le64_to_cpu(sd_disk->sizes[i]);
137                 if (sd->sizes[i] > 0xffffffff)
138                         goto out_invalid_sd;
139         }
140
141         p = (const u8*)sd_disk + size_no_descriptors;
142
143         /* Allocate the array of pointers to the security descriptors, then read
144          * them into separate buffers. */
145         sd->descriptors = CALLOC(sd->num_entries, sizeof(sd->descriptors[0]));
146         if (!sd->descriptors)
147                 goto out_of_memory;
148
149         for (u32 i = 0; i < sd->num_entries; i++) {
150                 if (sd->sizes[i] == 0)
151                         continue;
152                 total_len += sd->sizes[i];
153                 if (total_len > (u64)sd->total_length)
154                         goto out_invalid_sd;
155                 sd->descriptors[i] = memdup(p, sd->sizes[i]);
156                 if (!sd->descriptors[i])
157                         goto out_of_memory;
158                 p += sd->sizes[i];
159         }
160 out_align_total_length:
161         total_len = (total_len + 7) & ~7;
162         sd->total_length = (sd->total_length + 7) & ~7;
163         if (total_len != sd->total_length) {
164                 WARNING("Expected WIM security data total length of "
165                         "%u bytes, but calculated %u bytes",
166                         sd->total_length, (unsigned)total_len);
167         }
168         *sd_ret = sd;
169         ret = 0;
170         goto out;
171 out_invalid_sd:
172         ERROR("WIM security data is invalid!");
173         ret = WIMLIB_ERR_INVALID_METADATA_RESOURCE;
174         goto out_free_sd;
175 out_of_memory:
176         ERROR("Out of memory while reading WIM security data!");
177         ret = WIMLIB_ERR_NOMEM;
178 out_free_sd:
179         free_wim_security_data(sd);
180 out:
181         return ret;
182 }
183
184 /*
185  * Writes the security data for a WIM image to an in-memory buffer.
186  */
187 u8 *
188 write_wim_security_data(const struct wim_security_data * restrict sd,
189                         u8 * restrict p)
190 {
191         DEBUG("Writing security data (total_length = %"PRIu32", num_entries "
192               "= %"PRIu32")", sd->total_length, sd->num_entries);
193
194         u8 *orig_p = p;
195         struct wim_security_data_disk *sd_disk = (struct wim_security_data_disk*)p;
196         u32 num_entries = sd->num_entries;
197
198         sd_disk->total_length = cpu_to_le32(sd->total_length);
199         sd_disk->num_entries = cpu_to_le32(num_entries);
200
201         for (u32 i = 0; i < num_entries; i++)
202                 sd_disk->sizes[i] = cpu_to_le64(sd->sizes[i]);
203
204         p = (u8*)&sd_disk->sizes[num_entries];
205
206         for (u32 i = 0; i < num_entries; i++)
207                 p = mempcpy(p, sd->descriptors[i], sd->sizes[i]);
208
209         while ((uintptr_t)p & 7)
210                 *p++ = 0;
211
212         wimlib_assert(p - orig_p == sd->total_length);
213
214         DEBUG("Successfully wrote security data.");
215         return p;
216 }
217
218 static void
219 print_acl(const wimlib_ACL *acl, const tchar *type, size_t max_size)
220 {
221         const u8 *p;
222
223         if (max_size < sizeof(wimlib_ACL))
224                 return;
225
226         u8 revision = acl->revision;
227         u16 acl_size = le16_to_cpu(acl->acl_size);
228         u16 ace_count = le16_to_cpu(acl->ace_count);
229
230         tprintf(T("    [%"TS" ACL]\n"), type);
231         tprintf(T("    Revision = %u\n"), revision);
232         tprintf(T("    ACL Size = %u\n"), acl_size);
233         tprintf(T("    ACE Count = %u\n"), ace_count);
234
235         p = (const u8*)acl + sizeof(wimlib_ACL);
236         for (u16 i = 0; i < ace_count; i++) {
237                 if (max_size < p + sizeof(wimlib_ACCESS_ALLOWED_ACE) - (const u8*)acl)
238                         break;
239                 const wimlib_ACCESS_ALLOWED_ACE *aaa = (const wimlib_ACCESS_ALLOWED_ACE*)p;
240                 tprintf(T("        [ACE]\n"));
241                 tprintf(T("        ACE type  = %d\n"), aaa->hdr.type);
242                 tprintf(T("        ACE flags = 0x%x\n"), aaa->hdr.flags);
243                 tprintf(T("        ACE size  = %u\n"), le16_to_cpu(aaa->hdr.size));
244                 tprintf(T("        ACE mask = %x\n"), le32_to_cpu(aaa->mask));
245                 tprintf(T("        SID start = %u\n"), le32_to_cpu(aaa->sid_start));
246                 p += le16_to_cpu(aaa->hdr.size);
247         }
248         tputchar(T('\n'));
249 }
250
251 static void
252 print_sid(const wimlib_SID *sid, const tchar *type, size_t max_size)
253 {
254         if (max_size < sizeof(wimlib_SID))
255                 return;
256
257         tprintf(T("    [%"TS" SID]\n"), type);
258         tprintf(T("    Revision = %u\n"), sid->revision);
259         tprintf(T("    Subauthority count = %u\n"), sid->sub_authority_count);
260         tprintf(T("    Identifier authority = "));
261         print_byte_field(sid->identifier_authority,
262                          sizeof(sid->identifier_authority), stdout);
263         tputchar(T('\n'));
264         if (max_size < sizeof(wimlib_SID) + (size_t)sid->sub_authority_count * sizeof(u32))
265                 return;
266         for (u8 i = 0; i < sid->sub_authority_count; i++) {
267                 tprintf(T("    Subauthority %u = %u\n"),
268                         i, le32_to_cpu(sid->sub_authority[i]));
269         }
270         tputchar(T('\n'));
271 }
272
273 static void
274 print_security_descriptor(const wimlib_SECURITY_DESCRIPTOR_RELATIVE *descr,
275                           size_t size)
276 {
277         u8 revision      = descr->revision;
278         u16 control      = le16_to_cpu(descr->control);
279         u32 owner_offset = le32_to_cpu(descr->owner_offset);
280         u32 group_offset = le32_to_cpu(descr->group_offset);
281         u32 dacl_offset  = le32_to_cpu(descr->dacl_offset);
282         u32 sacl_offset  = le32_to_cpu(descr->sacl_offset);
283
284         tprintf(T("Revision = %u\n"), revision);
285         tprintf(T("Security Descriptor Control = %#x\n"), control);
286         tprintf(T("Owner offset = %u\n"), owner_offset);
287         tprintf(T("Group offset = %u\n"), group_offset);
288         tprintf(T("Discretionary ACL offset = %u\n"), dacl_offset);
289         tprintf(T("System ACL offset = %u\n"), sacl_offset);
290
291         if (owner_offset != 0 && owner_offset <= size)
292                 print_sid((const wimlib_SID*)((const u8*)descr + owner_offset),
293                           T("Owner"), size - owner_offset);
294
295         if (group_offset != 0 && group_offset <= size)
296                 print_sid((const wimlib_SID*)((const u8*)descr + group_offset),
297                           T("Group"), size - group_offset);
298
299         if (dacl_offset != 0 && dacl_offset <= size)
300                 print_acl((const wimlib_ACL*)((const u8*)descr + dacl_offset),
301                           T("Discretionary"), size - dacl_offset);
302
303         if (sacl_offset != 0 && sacl_offset <= size)
304                 print_acl((const wimlib_ACL*)((const u8*)descr + sacl_offset),
305                           T("System"), size - sacl_offset);
306 }
307
308 /*
309  * Prints the security data for a WIM file.
310  */
311 void
312 print_wim_security_data(const struct wim_security_data *sd)
313 {
314         tputs(T("[SECURITY DATA]"));
315         tprintf(T("Length            = %"PRIu32" bytes\n"), sd->total_length);
316         tprintf(T("Number of Entries = %"PRIu32"\n"), sd->num_entries);
317
318         for (u32 i = 0; i < sd->num_entries; i++) {
319                 tprintf(T("[SECURITY_DESCRIPTOR_RELATIVE %"PRIu32", length = %"PRIu64"]\n"),
320                         i, sd->sizes[i]);
321                 print_security_descriptor((const wimlib_SECURITY_DESCRIPTOR_RELATIVE*)sd->descriptors[i],
322                                           sd->sizes[i]);
323                 tputchar(T('\n'));
324         }
325         tputchar(T('\n'));
326 }
327
328 void
329 free_wim_security_data(struct wim_security_data *sd)
330 {
331         if (sd) {
332                 u8 **descriptors = sd->descriptors;
333                 u32 num_entries  = sd->num_entries;
334                 if (descriptors)
335                         while (num_entries--)
336                                 FREE(*descriptors++);
337                 FREE(sd->sizes);
338                 FREE(sd->descriptors);
339                 FREE(sd);
340         }
341 }
342
343 struct sd_node {
344         int security_id;
345         u8 hash[SHA1_HASH_SIZE];
346         struct rb_node rb_node;
347 };
348
349 static void
350 free_sd_tree(struct rb_node *node)
351 {
352         if (node) {
353                 free_sd_tree(node->rb_left);
354                 free_sd_tree(node->rb_right);
355                 FREE(container_of(node, struct sd_node, rb_node));
356         }
357 }
358
359 /* Frees a security descriptor index set. */
360 void
361 destroy_sd_set(struct wim_sd_set *sd_set, bool rollback)
362 {
363         if (rollback) {
364                 struct wim_security_data *sd = sd_set->sd;
365                 u8 **descriptors = sd->descriptors + sd_set->orig_num_entries;
366                 u32 num_entries  = sd->num_entries - sd_set->orig_num_entries;
367                 while (num_entries--)
368                         FREE(*descriptors++);
369                 sd->num_entries = sd_set->orig_num_entries;
370         }
371         free_sd_tree(sd_set->rb_root.rb_node);
372 }
373
374 /* Inserts a a new node into the security descriptor index tree. */
375 static bool
376 insert_sd_node(struct wim_sd_set *set, struct sd_node *new)
377 {
378         struct rb_root *root = &set->rb_root;
379         struct rb_node **p = &(root->rb_node);
380         struct rb_node *rb_parent = NULL;
381
382         while (*p) {
383                 struct sd_node *this = container_of(*p, struct sd_node, rb_node);
384                 int cmp = hashes_cmp(new->hash, this->hash);
385
386                 rb_parent = *p;
387                 if (cmp < 0)
388                         p = &((*p)->rb_left);
389                 else if (cmp > 0)
390                         p = &((*p)->rb_right);
391                 else
392                         return false; /* Duplicate security descriptor */
393         }
394         rb_link_node(&new->rb_node, rb_parent, p);
395         rb_insert_color(&new->rb_node, root);
396         return true;
397 }
398
399 /* Returns the index of the security descriptor having a SHA1 message digest of
400  * @hash.  If not found, return -1. */
401 int
402 lookup_sd(struct wim_sd_set *set, const u8 hash[SHA1_HASH_SIZE])
403 {
404         struct rb_node *node = set->rb_root.rb_node;
405
406         while (node) {
407                 struct sd_node *sd_node = container_of(node, struct sd_node, rb_node);
408                 int cmp = hashes_cmp(hash, sd_node->hash);
409                 if (cmp < 0)
410                         node = node->rb_left;
411                 else if (cmp > 0)
412                         node = node->rb_right;
413                 else
414                         return sd_node->security_id;
415         }
416         return -1;
417 }
418
419 /*
420  * Adds a security descriptor to the indexed security descriptor set as well as
421  * the corresponding `struct wim_security_data', and returns the new security
422  * ID; or, if there is an existing security descriptor that is the same, return
423  * the security ID for it.  If a new security descriptor cannot be allocated,
424  * return -1.
425  */
426 int
427 sd_set_add_sd(struct wim_sd_set *sd_set, const char *descriptor, size_t size)
428 {
429         u8 hash[SHA1_HASH_SIZE];
430         int security_id;
431         struct sd_node *new;
432         u8 **descriptors;
433         u64 *sizes;
434         u8 *descr_copy;
435         struct wim_security_data *sd;
436         bool bret;
437
438         sha1_buffer(descriptor, size, hash);
439
440         security_id = lookup_sd(sd_set, hash);
441         if (security_id >= 0) /* Identical descriptor already exists */
442                 goto out;
443
444         /* Need to add a new security descriptor */
445         security_id = -1;
446
447         new = MALLOC(sizeof(*new));
448         if (!new)
449                 goto out;
450
451         descr_copy = memdup(descriptor, size);
452         if (!descr_copy)
453                 goto out_free_node;
454
455         sd = sd_set->sd;
456         new->security_id = sd->num_entries;
457         copy_hash(new->hash, hash);
458
459         /* There typically are only a few dozen security descriptors in a
460          * directory tree, so expanding the array of security descriptors by
461          * only 1 extra space each time should not be a problem. */
462         descriptors = REALLOC(sd->descriptors,
463                               (sd->num_entries + 1) * sizeof(sd->descriptors[0]));
464         if (!descriptors)
465                 goto out_free_descr;
466         sd->descriptors = descriptors;
467         sizes = REALLOC(sd->sizes,
468                         (sd->num_entries + 1) * sizeof(sd->sizes[0]));
469         if (!sizes)
470                 goto out_free_descr;
471         sd->sizes = sizes;
472         sd->descriptors[sd->num_entries] = descr_copy;
473         sd->sizes[sd->num_entries] = size;
474         sd->num_entries++;
475         DEBUG("There are now %u security descriptors", sd->num_entries);
476         bret = insert_sd_node(sd_set, new);
477         wimlib_assert(bret);
478         security_id = new->security_id;
479         goto out;
480 out_free_descr:
481         FREE(descr_copy);
482 out_free_node:
483         FREE(new);
484 out:
485         return security_id;
486 }
487
488 /* Initialize a `struct sd_set' mapping from SHA1 message digests of security
489  * descriptors to indices into the security descriptors table of the WIM image
490  * (security IDs).  */
491 int
492 init_sd_set(struct wim_sd_set *sd_set, struct wim_security_data *sd)
493 {
494         int ret;
495
496         sd_set->sd = sd;
497         sd_set->rb_root.rb_node = NULL;
498
499         /* Remember the original number of security descriptors so that newly
500          * added ones can be rolled back if needed. */
501         sd_set->orig_num_entries = sd->num_entries;
502         for (u32 i = 0; i < sd->num_entries; i++) {
503                 struct sd_node *new;
504
505                 new = MALLOC(sizeof(struct sd_node));
506                 if (!new) {
507                         ret = WIMLIB_ERR_NOMEM;
508                         goto out_destroy_sd_set;
509                 }
510                 sha1_buffer(sd->descriptors[i], sd->sizes[i], new->hash);
511                 new->security_id = i;
512                 if (!insert_sd_node(sd_set, new))
513                         FREE(new); /* Ignore duplicate security descriptor */
514         }
515         ret = 0;
516         goto out;
517 out_destroy_sd_set:
518         destroy_sd_set(sd_set, false);
519 out:
520         return ret;
521 }