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