]> wimlib.net Git - wimlib/blob - src/security.c
Initial rewrite of resource 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 #include "wimlib_internal.h"
27 #include "buffer_io.h"
28 #include "security.h"
29
30 /* At the start of each type of access control entry.  */
31 typedef struct {
32         /* enum ace_type, specifies what type of ACE this is.  */
33         u8 type;
34
35         /* bitwise OR of the inherit ACE flags #defined above */
36         u8 flags;
37
38         /* Size of the access control entry. */
39         u8 size;
40 } ACEHeader;
41
42 /* Grants rights to a user or group */
43 typedef struct {
44         ACEHeader hdr;
45         u32 mask;
46         u32 sid_start;
47 } AccessAllowedACE;
48
49 /* Denies rights to a user or group */
50 typedef struct {
51         ACEHeader hdr;
52         u32 mask;
53         u32 sid_start;
54 } AccessDeniedACE;
55
56 typedef struct {
57         ACEHeader hdr;
58         u32 mask;
59         u32 sid_start;
60 } SystemAuditACE;
61
62
63 /* Header of an access control list. */
64 typedef struct {
65         /* ACL_REVISION or ACL_REVISION_DS */
66         u8 revision;
67
68         /* padding */
69         u8 sbz1;
70
71         /* Total size of the ACL, including all access control entries */
72         u16 acl_size;
73
74         /* Number of access control entry structures that follow the ACL
75          * structure. */
76         u16 ace_count;
77
78         /* padding */
79         u16 sbz2;
80 } ACL;
81
82 /* A structure used to identify users or groups. */
83 typedef struct {
84
85         /* example: 0x1 */
86         u8  revision;
87         u8  sub_authority_count;
88
89         /* Identifies the authority that issued the SID.  Can be, but does not
90          * have to be, one of enum sid_authority_value */
91         u8  identifier_authority[6];
92
93         u32 sub_authority[0];
94 } SID;
95
96
97 typedef struct {
98         /* Example: 0x1 */
99         u8 revision;
100         /* Example: 0x0 */
101         u8 sbz1;
102         /* Example: 0x4149 */
103         u16 security_descriptor_control;
104
105         /* Offset of a SID structure in the security descriptor. */
106         /* Example: 0x14 */
107         u32 owner_offset;
108
109         /* Offset of a SID structure in the security descriptor. */
110         /* Example: 0x24 */
111         u32 group_offset;
112
113         /* Offset of an ACL structure in the security descriptor. */
114         /* System ACL. */
115         /* Example: 0x00 */
116         u32 sacl_offset;
117
118         /* Offset of an ACL structure in the security descriptor. */
119         /* Discretionary ACL. */
120         /* Example: 0x34 */
121         u32 dacl_offset;
122 } SecurityDescriptor;
123
124 /*
125  * This is a hack to work around a problem in libntfs-3g.  libntfs-3g validates
126  * security descriptors with a function named ntfs_valid_descr().
127  * ntfs_valid_descr() considers a security descriptor that ends in a SACL
128  * (Sysetm Access Control List) with no ACE's (Access Control Entries) to be
129  * invalid.  However, a security descriptor like this exists in the Windows 7
130  * install.wim.  Here, security descriptors matching this pattern are modified
131  * to have no SACL.  This should make no difference since the SACL had no
132  * entries anyway; however this ensures that that the security descriptors pass
133  * the validation in libntfs-3g.
134  */
135 static void
136 empty_sacl_fixup(u8 *descr, u64 *size_p)
137 {
138         /* No-op if no NTFS-3g support, or if NTFS-3g is version 2013 or later
139          * */
140 #if defined(WITH_NTFS_3G) && !defined(HAVE_NTFS_MNT_RDONLY)
141         if (*size_p >= sizeof(SecurityDescriptor)) {
142                 SecurityDescriptor *sd = (SecurityDescriptor*)descr;
143                 u32 sacl_offset = le32_to_cpu(sd->sacl_offset);
144                 if (sacl_offset == *size_p - sizeof(ACL)) {
145                         sd->sacl_offset = cpu_to_le32(0);
146                         *size_p -= sizeof(ACL);
147                 }
148         }
149 #endif
150 }
151
152 /*
153  * Reads the security data from the metadata resource.
154  *
155  * @metadata_resource:  An array that contains the uncompressed metadata
156  *                              resource for the WIM file.
157  * @metadata_resource_len:      The length of @metadata_resource.  It must be at
158  *                              least 8 bytes.
159  * @sd_p:       A pointer to a pointer to a wim_security_data structure that
160  *              will be filled in with a pointer to a new wim_security_data
161  *              structure on success.
162  *
163  * Note: There is no `offset' argument because the security data is located at
164  * the beginning of the metadata resource.
165  */
166 int
167 read_security_data(const u8 metadata_resource[], u64 metadata_resource_len,
168                    struct wim_security_data **sd_p)
169 {
170         struct wim_security_data *sd;
171         const u8 *p;
172         int ret;
173         u64 total_len;
174
175         wimlib_assert(metadata_resource_len >= 8);
176
177         /*
178          * Sorry this function is excessively complicated--- I'm just being
179          * extremely careful about integer overflows.
180          */
181
182         sd = MALLOC(sizeof(struct wim_security_data));
183         if (!sd) {
184                 ERROR("Out of memory");
185                 return WIMLIB_ERR_NOMEM;
186         }
187         sd->sizes       = NULL;
188         sd->descriptors = NULL;
189         sd->refcnt      = 1;
190
191         p = metadata_resource;
192         p = get_u32(p, &sd->total_length);
193         p = get_u32(p, (u32*)&sd->num_entries);
194
195         /* The security_id field of each dentry is a signed 32-bit integer, so
196          * the possible indices into the security descriptors table are 0
197          * through 0x7fffffff.  Which means 0x80000000 security descriptors
198          * maximum.  Not like you should ever have anywhere close to that many
199          * security descriptors! */
200         if (sd->num_entries > 0x80000000) {
201                 ERROR("Security data has too many entries!");
202                 goto out_invalid_sd;
203         }
204
205         /* Verify the listed total length of the security data is big enough to
206          * include the sizes array, verify that the file data is big enough to
207          * include it as well, then allocate the array of sizes.
208          *
209          * Note: The total length of the security data must fit in a 32-bit
210          * integer, even though each security descriptor size is a 64-bit
211          * integer.  This is stupid, and we need to be careful not to actually
212          * let the security descriptor sizes be over 0xffffffff.  */
213         if ((u64)sd->total_length > metadata_resource_len) {
214                 ERROR("Security data total length (%u) is bigger than the "
215                       "metadata resource length (%"PRIu64")",
216                       sd->total_length, metadata_resource_len);
217                 goto out_invalid_sd;
218         }
219
220         DEBUG("Reading security data: %u entries, length = %u",
221               sd->num_entries, sd->total_length);
222
223         if (sd->num_entries == 0) {
224                 /* No security descriptors.  We allow the total_length field to
225                  * be either 8 (which is correct, since there are always 2
226                  * 32-bit integers) or 0. */
227                 if (sd->total_length != 0 && sd->total_length != 8) {
228                         ERROR("Invalid security data length (%u): expected 0 or 8",
229                               sd->total_length);
230                         goto out_invalid_sd;
231                 }
232                 sd->total_length = 8;
233                 goto out_return_sd;
234         }
235
236         u64 sizes_size = (u64)sd->num_entries * sizeof(u64);
237         u64 size_no_descriptors = 8 + sizes_size;
238         if (size_no_descriptors > (u64)sd->total_length) {
239                 ERROR("Security data total length of %u is too short because "
240                       "there seem to be at least %"PRIu64" bytes of security data",
241                       sd->total_length, 8 + sizes_size);
242                 goto out_invalid_sd;
243         }
244
245         sd->sizes = MALLOC(sizes_size);
246         if (!sd->sizes) {
247                 ret = WIMLIB_ERR_NOMEM;
248                 goto out_free_sd;
249         }
250
251         /* Copy the sizes array in from the file data. */
252         p = get_bytes(p, sizes_size, sd->sizes);
253         array_le64_to_cpu(sd->sizes, sd->num_entries);
254
255         /* Allocate the array of pointers to descriptors, and read them in. */
256         sd->descriptors = CALLOC(sd->num_entries, sizeof(u8*));
257         if (!sd->descriptors) {
258                 ERROR("Out of memory while allocating security "
259                       "descriptors");
260                 ret = WIMLIB_ERR_NOMEM;
261                 goto out_free_sd;
262         }
263         total_len = size_no_descriptors;
264
265         for (u32 i = 0; i < sd->num_entries; i++) {
266                 /* Watch out for huge security descriptor sizes that could
267                  * overflow the total length and wrap it around. */
268                 if (total_len + sd->sizes[i] < total_len) {
269                         ERROR("Caught overflow in security descriptor lengths "
270                               "(current total length = %"PRIu64", security "
271                               "descriptor size = %"PRIu64")",
272                               total_len, sd->sizes[i]);
273                         goto out_invalid_sd;
274                 }
275                 total_len += sd->sizes[i];
276                 /* This check ensures that the descriptor size fits in a 32 bit
277                  * integer.  Because if it didn't, the total length would come
278                  * out bigger than sd->total_length, which is a 32 bit integer.
279                  * */
280                 if (total_len > (u64)sd->total_length) {
281                         ERROR("Security data total length of %u is too short "
282                               "because there seem to be at least %"PRIu64" "
283                               "bytes of security data",
284                               sd->total_length, total_len);
285                         goto out_invalid_sd;
286                 }
287                 sd->descriptors[i] = MALLOC(sd->sizes[i]);
288                 if (!sd->descriptors[i]) {
289                         ERROR("Out of memory while allocating security "
290                               "descriptors");
291                         ret = WIMLIB_ERR_NOMEM;
292                         goto out_free_sd;
293                 }
294                 p = get_bytes(p, sd->sizes[i], sd->descriptors[i]);
295                 empty_sacl_fixup(sd->descriptors[i], &sd->sizes[i]);
296         }
297         wimlib_assert(total_len <= 0xffffffff);
298         if (((total_len + 7) & ~7) != ((sd->total_length + 7) & ~7)) {
299                 ERROR("Expected security data total length = %u, but "
300                       "calculated %u", sd->total_length, (unsigned)total_len);
301                 goto out_invalid_sd;
302         }
303         sd->total_length = total_len;
304 out_return_sd:
305         *sd_p = sd;
306         return 0;
307 out_invalid_sd:
308         ret = WIMLIB_ERR_INVALID_SECURITY_DATA;
309 out_free_sd:
310         free_security_data(sd);
311         return ret;
312 }
313
314 /*
315  * Writes security data to an in-memory buffer.
316  */
317 u8 *
318 write_security_data(const struct wim_security_data *sd, u8 *p)
319 {
320         DEBUG("Writing security data (total_length = %"PRIu32", num_entries "
321               "= %"PRIu32")", sd->total_length, sd->num_entries);
322
323         u32 aligned_length = (sd->total_length + 7) & ~7;
324
325         u8 *orig_p = p;
326         p = put_u32(p, aligned_length);
327         p = put_u32(p, sd->num_entries);
328
329         for (u32 i = 0; i < sd->num_entries; i++)
330                 p = put_u64(p, sd->sizes[i]);
331
332         for (u32 i = 0; i < sd->num_entries; i++)
333                 p = put_bytes(p, sd->sizes[i], sd->descriptors[i]);
334
335         wimlib_assert(p - orig_p == sd->total_length);
336         p = put_zeroes(p, aligned_length - sd->total_length);
337
338         DEBUG("Successfully wrote security data.");
339         return p;
340 }
341
342 static void
343 print_acl(const void *p, const tchar *type)
344 {
345         const ACL *acl = p;
346         u8 revision = acl->revision;
347         u16 acl_size = le16_to_cpu(acl->acl_size);
348         u16 ace_count = le16_to_cpu(acl->ace_count);
349         tprintf(T("    [%"TS" ACL]\n"), type);
350         tprintf(T("    Revision = %u\n"), revision);
351         tprintf(T("    ACL Size = %u\n"), acl_size);
352         tprintf(T("    ACE Count = %u\n"), ace_count);
353
354         p += sizeof(ACL);
355         for (u16 i = 0; i < ace_count; i++) {
356                 const ACEHeader *hdr = p;
357                 tprintf(T("        [ACE]\n"));
358                 tprintf(T("        ACE type  = %d\n"), hdr->type);
359                 tprintf(T("        ACE flags = 0x%x\n"), hdr->flags);
360                 tprintf(T("        ACE size  = %u\n"), hdr->size);
361                 const AccessAllowedACE *aaa = (const AccessAllowedACE*)hdr;
362                 tprintf(T("        ACE mask = %x\n"), le32_to_cpu(aaa->mask));
363                 tprintf(T("        SID start = %u\n"), le32_to_cpu(aaa->sid_start));
364                 p += hdr->size;
365         }
366         tputchar(T('\n'));
367 }
368
369 static void
370 print_sid(const void *p, const tchar *type)
371 {
372         const SID *sid = p;
373         tprintf(T("    [%"TS" SID]\n"), type);
374         tprintf(T("    Revision = %u\n"), sid->revision);
375         tprintf(T("    Subauthority count = %u\n"), sid->sub_authority_count);
376         tprintf(T("    Identifier authority = "));
377         print_byte_field(sid->identifier_authority,
378                          sizeof(sid->identifier_authority), stdout);
379         tputchar(T('\n'));
380         for (u8 i = 0; i < sid->sub_authority_count; i++) {
381                 tprintf(T("    Subauthority %u = %u\n"),
382                         i, le32_to_cpu(sid->sub_authority[i]));
383         }
384         tputchar(T('\n'));
385 }
386
387 static void
388 print_security_descriptor(const void *p, u64 size)
389 {
390         const SecurityDescriptor *sd = p;
391
392         u8 revision      = sd->revision;
393         u16 control      = le16_to_cpu(sd->security_descriptor_control);
394         u32 owner_offset = le32_to_cpu(sd->owner_offset);
395         u32 group_offset = le32_to_cpu(sd->group_offset);
396         u32 sacl_offset  = le32_to_cpu(sd->sacl_offset);
397         u32 dacl_offset  = le32_to_cpu(sd->dacl_offset);
398         tprintf(T("Revision = %u\n"), revision);
399         tprintf(T("Security Descriptor Control = %#x\n"), control);
400         tprintf(T("Owner offset = %u\n"), owner_offset);
401         tprintf(T("Group offset = %u\n"), group_offset);
402         tprintf(T("System ACL offset = %u\n"), sacl_offset);
403         tprintf(T("Discretionary ACL offset = %u\n"), dacl_offset);
404
405         if (sd->owner_offset != 0)
406                 print_sid(p + owner_offset, T("Owner"));
407         if (sd->group_offset != 0)
408                 print_sid(p + group_offset, T("Group"));
409         if (sd->sacl_offset != 0)
410                 print_acl(p + sacl_offset, T("System"));
411         if (sd->dacl_offset != 0)
412                 print_acl(p + dacl_offset, T("Discretionary"));
413 }
414
415 /*
416  * Prints the security data for a WIM file.
417  */
418 void
419 print_security_data(const struct wim_security_data *sd)
420 {
421         wimlib_assert(sd != NULL);
422
423         tputs(T("[SECURITY DATA]"));
424         tprintf(T("Length            = %"PRIu32" bytes\n"), sd->total_length);
425         tprintf(T("Number of Entries = %"PRIu32"\n"), sd->num_entries);
426
427         for (u32 i = 0; i < sd->num_entries; i++) {
428                 tprintf(T("[SecurityDescriptor %"PRIu32", length = %"PRIu64"]\n"),
429                         i, sd->sizes[i]);
430                 print_security_descriptor(sd->descriptors[i], sd->sizes[i]);
431                 tputchar(T('\n'));
432         }
433         tputchar(T('\n'));
434 }
435
436 void
437 free_security_data(struct wim_security_data *sd)
438 {
439         if (sd) {
440                 wimlib_assert(sd->refcnt != 0);
441                 if (--sd->refcnt == 0) {
442                         u8 **descriptors = sd->descriptors;
443                         u32 num_entries  = sd->num_entries;
444                         if (descriptors)
445                                 while (num_entries--)
446                                         FREE(*descriptors++);
447                         FREE(sd->sizes);
448                         FREE(sd->descriptors);
449                         FREE(sd);
450                 }
451         }
452 }
453
454 struct sd_node {
455         int security_id;
456         u8 hash[SHA1_HASH_SIZE];
457         struct rb_node rb_node;
458 };
459
460 static void
461 free_sd_tree(struct rb_node *node)
462 {
463         if (node) {
464                 free_sd_tree(node->rb_left);
465                 free_sd_tree(node->rb_right);
466                 FREE(container_of(node, struct sd_node, rb_node));
467         }
468 }
469
470 /* Frees a security descriptor index set. */
471 void
472 destroy_sd_set(struct sd_set *sd_set)
473 {
474         free_sd_tree(sd_set->rb_root.rb_node);
475 }
476
477 /* Inserts a a new node into the security descriptor index tree. */
478 static void
479 insert_sd_node(struct sd_set *set, struct sd_node *new)
480 {
481         struct rb_root *root = &set->rb_root;
482         struct rb_node **p = &(root->rb_node);
483         struct rb_node *rb_parent = NULL;
484
485         while (*p) {
486                 struct sd_node *this = container_of(*p, struct sd_node, rb_node);
487                 int cmp = hashes_cmp(new->hash, this->hash);
488
489                 rb_parent = *p;
490                 if (cmp < 0)
491                         p = &((*p)->rb_left);
492                 else if (cmp > 0)
493                         p = &((*p)->rb_right);
494                 else
495                         wimlib_assert(0); /* Duplicate SHA1 message digest */
496         }
497         rb_link_node(&new->rb_node, rb_parent, p);
498         rb_insert_color(&new->rb_node, root);
499 }
500
501 /* Returns the index of the security descriptor having a SHA1 message digest of
502  * @hash.  If not found, return -1. */
503 int
504 lookup_sd(struct sd_set *set, const u8 hash[SHA1_HASH_SIZE])
505 {
506         struct rb_node *node = set->rb_root.rb_node;
507
508         while (node) {
509                 struct sd_node *sd_node = container_of(node, struct sd_node, rb_node);
510                 int cmp = hashes_cmp(hash, sd_node->hash);
511                 if (cmp < 0)
512                         node = node->rb_left;
513                 else if (cmp > 0)
514                         node = node->rb_right;
515                 else
516                         return sd_node->security_id;
517         }
518         return -1;
519 }
520
521 /*
522  * Adds a security descriptor to the indexed security descriptor set as well as
523  * the corresponding `struct wim_security_data', and returns the new security
524  * ID; or, if there is an existing security descriptor that is the same, return
525  * the security ID for it.  If a new security descriptor cannot be allocated,
526  * return -1.
527  */
528 int
529 sd_set_add_sd(struct sd_set *sd_set, const char descriptor[], size_t size)
530 {
531         u8 hash[SHA1_HASH_SIZE];
532         int security_id;
533         struct sd_node *new;
534         u8 **descriptors;
535         u64 *sizes;
536         u8 *descr_copy;
537         struct wim_security_data *sd;
538
539         sha1_buffer((const u8*)descriptor, size, hash);
540
541         security_id = lookup_sd(sd_set, hash);
542         if (security_id >= 0) /* Identical descriptor already exists */
543                 return security_id;
544
545         /* Need to add a new security descriptor */
546         new = MALLOC(sizeof(*new));
547         if (!new)
548                 goto out;
549         descr_copy = MALLOC(size);
550         if (!descr_copy)
551                 goto out_free_node;
552
553         sd = sd_set->sd;
554
555         memcpy(descr_copy, descriptor, size);
556         new->security_id = sd->num_entries;
557         copy_hash(new->hash, hash);
558
559         /* There typically are only a few dozen security descriptors in a
560          * directory tree, so expanding the array of security descriptors by
561          * only 1 extra space each time should not be a problem. */
562         descriptors = REALLOC(sd->descriptors,
563                               (sd->num_entries + 1) * sizeof(sd->descriptors[0]));
564         if (!descriptors)
565                 goto out_free_descr;
566         sd->descriptors = descriptors;
567         sizes = REALLOC(sd->sizes,
568                         (sd->num_entries + 1) * sizeof(sd->sizes[0]));
569         if (!sizes)
570                 goto out_free_descr;
571         sd->sizes = sizes;
572         sd->descriptors[sd->num_entries] = descr_copy;
573         sd->sizes[sd->num_entries] = size;
574         sd->num_entries++;
575         DEBUG("There are now %d security descriptors", sd->num_entries);
576         sd->total_length += size + sizeof(sd->sizes[0]);
577         insert_sd_node(sd_set, new);
578         return new->security_id;
579 out_free_descr:
580         FREE(descr_copy);
581 out_free_node:
582         FREE(new);
583 out:
584         return -1;
585 }