]> wimlib.net Git - wimlib/blob - src/security.c
16e7b912a03caa284400fe6b5dad110cb7e235bb
[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 struct wim_security_data *
153 new_wim_security_data()
154 {
155         return CALLOC(1, sizeof(struct wim_security_data));
156 }
157
158 /*
159  * Reads the security data from the metadata resource.
160  *
161  * @metadata_resource:  An array that contains the uncompressed metadata
162  *                              resource for the WIM file.
163  * @metadata_resource_len:      The length of @metadata_resource.  It must be at
164  *                              least 8 bytes.
165  * @sd_p:       A pointer to a pointer to a wim_security_data structure that
166  *              will be filled in with a pointer to a new wim_security_data
167  *              structure on success.
168  *
169  * Note: There is no `offset' argument because the security data is located at
170  * the beginning of the metadata resource.
171  */
172 int
173 read_security_data(const u8 metadata_resource[], u64 metadata_resource_len,
174                    struct wim_security_data **sd_p)
175 {
176         struct wim_security_data *sd;
177         const u8 *p;
178         int ret;
179         u64 total_len;
180
181         wimlib_assert(metadata_resource_len >= 8);
182
183         /*
184          * Sorry this function is excessively complicated--- I'm just being
185          * extremely careful about integer overflows.
186          */
187
188         sd = MALLOC(sizeof(struct wim_security_data));
189         if (!sd) {
190                 ERROR("Out of memory");
191                 return WIMLIB_ERR_NOMEM;
192         }
193         sd->sizes       = NULL;
194         sd->descriptors = NULL;
195
196         p = metadata_resource;
197         p = get_u32(p, &sd->total_length);
198         p = get_u32(p, (u32*)&sd->num_entries);
199
200         /* The security_id field of each dentry is a signed 32-bit integer, so
201          * the possible indices into the security descriptors table are 0
202          * through 0x7fffffff.  Which means 0x80000000 security descriptors
203          * maximum.  Not like you should ever have anywhere close to that many
204          * security descriptors! */
205         if (sd->num_entries > 0x80000000) {
206                 ERROR("Security data has too many entries!");
207                 goto out_invalid_sd;
208         }
209
210         /* Verify the listed total length of the security data is big enough to
211          * include the sizes array, verify that the file data is big enough to
212          * include it as well, then allocate the array of sizes.
213          *
214          * Note: The total length of the security data must fit in a 32-bit
215          * integer, even though each security descriptor size is a 64-bit
216          * integer.  This is stupid, and we need to be careful not to actually
217          * let the security descriptor sizes be over 0xffffffff.  */
218         if ((u64)sd->total_length > metadata_resource_len) {
219                 ERROR("Security data total length (%u) is bigger than the "
220                       "metadata resource length (%"PRIu64")",
221                       sd->total_length, metadata_resource_len);
222                 goto out_invalid_sd;
223         }
224
225         DEBUG("Reading security data: %u entries, length = %u",
226               sd->num_entries, sd->total_length);
227
228         if (sd->num_entries == 0) {
229                 /* No security descriptors.  We allow the total_length field to
230                  * be either 8 (which is correct, since there are always 2
231                  * 32-bit integers) or 0. */
232                 if (sd->total_length != 0 && sd->total_length != 8) {
233                         ERROR("Invalid security data length (%u): expected 0 or 8",
234                               sd->total_length);
235                         goto out_invalid_sd;
236                 }
237                 sd->total_length = 8;
238                 goto out_return_sd;
239         }
240
241         u64 sizes_size = (u64)sd->num_entries * sizeof(u64);
242         u64 size_no_descriptors = 8 + sizes_size;
243         if (size_no_descriptors > (u64)sd->total_length) {
244                 ERROR("Security data total length of %u is too short because "
245                       "there seem to be at least %"PRIu64" bytes of security data",
246                       sd->total_length, 8 + sizes_size);
247                 goto out_invalid_sd;
248         }
249
250         sd->sizes = MALLOC(sizes_size);
251         if (!sd->sizes) {
252                 ret = WIMLIB_ERR_NOMEM;
253                 goto out_free_sd;
254         }
255
256         /* Copy the sizes array in from the file data. */
257         p = get_bytes(p, sizes_size, sd->sizes);
258         array_le64_to_cpu(sd->sizes, sd->num_entries);
259
260         /* Allocate the array of pointers to descriptors, and read them in. */
261         sd->descriptors = CALLOC(sd->num_entries, sizeof(u8*));
262         if (!sd->descriptors) {
263                 ERROR("Out of memory while allocating security "
264                       "descriptors");
265                 ret = WIMLIB_ERR_NOMEM;
266                 goto out_free_sd;
267         }
268         total_len = size_no_descriptors;
269
270         for (u32 i = 0; i < sd->num_entries; i++) {
271                 /* Watch out for huge security descriptor sizes that could
272                  * overflow the total length and wrap it around. */
273                 if (total_len + sd->sizes[i] < total_len) {
274                         ERROR("Caught overflow in security descriptor lengths "
275                               "(current total length = %"PRIu64", security "
276                               "descriptor size = %"PRIu64")",
277                               total_len, sd->sizes[i]);
278                         goto out_invalid_sd;
279                 }
280                 total_len += sd->sizes[i];
281                 /* This check ensures that the descriptor size fits in a 32 bit
282                  * integer.  Because if it didn't, the total length would come
283                  * out bigger than sd->total_length, which is a 32 bit integer.
284                  * */
285                 if (total_len > (u64)sd->total_length) {
286                         ERROR("Security data total length of %u is too short "
287                               "because there seem to be at least %"PRIu64" "
288                               "bytes of security data",
289                               sd->total_length, total_len);
290                         goto out_invalid_sd;
291                 }
292                 sd->descriptors[i] = MALLOC(sd->sizes[i]);
293                 if (!sd->descriptors[i]) {
294                         ERROR("Out of memory while allocating security "
295                               "descriptors");
296                         ret = WIMLIB_ERR_NOMEM;
297                         goto out_free_sd;
298                 }
299                 p = get_bytes(p, sd->sizes[i], sd->descriptors[i]);
300                 empty_sacl_fixup(sd->descriptors[i], &sd->sizes[i]);
301         }
302         wimlib_assert(total_len <= 0xffffffff);
303         if (((total_len + 7) & ~7) != ((sd->total_length + 7) & ~7)) {
304                 ERROR("Expected security data total length = %u, but "
305                       "calculated %u", sd->total_length, (unsigned)total_len);
306                 goto out_invalid_sd;
307         }
308         sd->total_length = total_len;
309 out_return_sd:
310         *sd_p = sd;
311         return 0;
312 out_invalid_sd:
313         ret = WIMLIB_ERR_INVALID_SECURITY_DATA;
314 out_free_sd:
315         free_security_data(sd);
316         return ret;
317 }
318
319 /*
320  * Writes security data to an in-memory buffer.
321  */
322 u8 *
323 write_security_data(const struct wim_security_data *sd, u8 *p)
324 {
325         DEBUG("Writing security data (total_length = %"PRIu32", num_entries "
326               "= %"PRIu32")", sd->total_length, sd->num_entries);
327
328         u32 aligned_length = (sd->total_length + 7) & ~7;
329
330         u8 *orig_p = p;
331         p = put_u32(p, aligned_length);
332         p = put_u32(p, sd->num_entries);
333
334         for (u32 i = 0; i < sd->num_entries; i++)
335                 p = put_u64(p, sd->sizes[i]);
336
337         for (u32 i = 0; i < sd->num_entries; i++)
338                 p = put_bytes(p, sd->sizes[i], sd->descriptors[i]);
339
340         wimlib_assert(p - orig_p == sd->total_length);
341         p = put_zeroes(p, aligned_length - sd->total_length);
342
343         DEBUG("Successfully wrote security data.");
344         return p;
345 }
346
347 static void
348 print_acl(const void *p, const tchar *type)
349 {
350         const ACL *acl = p;
351         u8 revision = acl->revision;
352         u16 acl_size = le16_to_cpu(acl->acl_size);
353         u16 ace_count = le16_to_cpu(acl->ace_count);
354         tprintf(T("    [%"TS" ACL]\n"), type);
355         tprintf(T("    Revision = %u\n"), revision);
356         tprintf(T("    ACL Size = %u\n"), acl_size);
357         tprintf(T("    ACE Count = %u\n"), ace_count);
358
359         p += sizeof(ACL);
360         for (u16 i = 0; i < ace_count; i++) {
361                 const ACEHeader *hdr = p;
362                 tprintf(T("        [ACE]\n"));
363                 tprintf(T("        ACE type  = %d\n"), hdr->type);
364                 tprintf(T("        ACE flags = 0x%x\n"), hdr->flags);
365                 tprintf(T("        ACE size  = %u\n"), hdr->size);
366                 const AccessAllowedACE *aaa = (const AccessAllowedACE*)hdr;
367                 tprintf(T("        ACE mask = %x\n"), le32_to_cpu(aaa->mask));
368                 tprintf(T("        SID start = %u\n"), le32_to_cpu(aaa->sid_start));
369                 p += hdr->size;
370         }
371         tputchar(T('\n'));
372 }
373
374 static void
375 print_sid(const void *p, const tchar *type)
376 {
377         const SID *sid = p;
378         tprintf(T("    [%"TS" SID]\n"), type);
379         tprintf(T("    Revision = %u\n"), sid->revision);
380         tprintf(T("    Subauthority count = %u\n"), sid->sub_authority_count);
381         tprintf(T("    Identifier authority = "));
382         print_byte_field(sid->identifier_authority,
383                          sizeof(sid->identifier_authority), stdout);
384         tputchar(T('\n'));
385         for (u8 i = 0; i < sid->sub_authority_count; i++) {
386                 tprintf(T("    Subauthority %u = %u\n"),
387                         i, le32_to_cpu(sid->sub_authority[i]));
388         }
389         tputchar(T('\n'));
390 }
391
392 static void
393 print_security_descriptor(const void *p, u64 size)
394 {
395         const SecurityDescriptor *sd = p;
396
397         u8 revision      = sd->revision;
398         u16 control      = le16_to_cpu(sd->security_descriptor_control);
399         u32 owner_offset = le32_to_cpu(sd->owner_offset);
400         u32 group_offset = le32_to_cpu(sd->group_offset);
401         u32 sacl_offset  = le32_to_cpu(sd->sacl_offset);
402         u32 dacl_offset  = le32_to_cpu(sd->dacl_offset);
403         tprintf(T("Revision = %u\n"), revision);
404         tprintf(T("Security Descriptor Control = %#x\n"), control);
405         tprintf(T("Owner offset = %u\n"), owner_offset);
406         tprintf(T("Group offset = %u\n"), group_offset);
407         tprintf(T("System ACL offset = %u\n"), sacl_offset);
408         tprintf(T("Discretionary ACL offset = %u\n"), dacl_offset);
409
410         if (sd->owner_offset != 0)
411                 print_sid(p + owner_offset, T("Owner"));
412         if (sd->group_offset != 0)
413                 print_sid(p + group_offset, T("Group"));
414         if (sd->sacl_offset != 0)
415                 print_acl(p + sacl_offset, T("System"));
416         if (sd->dacl_offset != 0)
417                 print_acl(p + dacl_offset, T("Discretionary"));
418 }
419
420 /*
421  * Prints the security data for a WIM file.
422  */
423 void
424 print_security_data(const struct wim_security_data *sd)
425 {
426         wimlib_assert(sd != NULL);
427
428         tputs(T("[SECURITY DATA]"));
429         tprintf(T("Length            = %"PRIu32" bytes\n"), sd->total_length);
430         tprintf(T("Number of Entries = %"PRIu32"\n"), sd->num_entries);
431
432         for (u32 i = 0; i < sd->num_entries; i++) {
433                 tprintf(T("[SecurityDescriptor %"PRIu32", length = %"PRIu64"]\n"),
434                         i, sd->sizes[i]);
435                 print_security_descriptor(sd->descriptors[i], sd->sizes[i]);
436                 tputchar(T('\n'));
437         }
438         tputchar(T('\n'));
439 }
440
441 void
442 free_security_data(struct wim_security_data *sd)
443 {
444         if (sd) {
445                 u8 **descriptors = sd->descriptors;
446                 u32 num_entries  = sd->num_entries;
447                 if (descriptors)
448                         while (num_entries--)
449                                 FREE(*descriptors++);
450                 FREE(sd->sizes);
451                 FREE(sd->descriptors);
452                 FREE(sd);
453         }
454 }
455
456 struct sd_node {
457         int security_id;
458         u8 hash[SHA1_HASH_SIZE];
459         struct rb_node rb_node;
460 };
461
462 static void
463 free_sd_tree(struct rb_node *node)
464 {
465         if (node) {
466                 free_sd_tree(node->rb_left);
467                 free_sd_tree(node->rb_right);
468                 FREE(container_of(node, struct sd_node, rb_node));
469         }
470 }
471
472 /* Frees a security descriptor index set. */
473 void
474 destroy_sd_set(struct sd_set *sd_set, bool rollback)
475 {
476         if (rollback) {
477                 struct wim_security_data *sd = sd_set->sd;
478                 int32_t i;
479                 for (i = sd_set->orig_num_entries; i < sd->num_entries; i++)
480                         FREE(sd->descriptors[i]);
481                 sd->num_entries = sd_set->orig_num_entries;
482         }
483         free_sd_tree(sd_set->rb_root.rb_node);
484 }
485
486 /* Inserts a a new node into the security descriptor index tree. */
487 static bool
488 insert_sd_node(struct sd_set *set, struct sd_node *new)
489 {
490         struct rb_root *root = &set->rb_root;
491         struct rb_node **p = &(root->rb_node);
492         struct rb_node *rb_parent = NULL;
493
494         while (*p) {
495                 struct sd_node *this = container_of(*p, struct sd_node, rb_node);
496                 int cmp = hashes_cmp(new->hash, this->hash);
497
498                 rb_parent = *p;
499                 if (cmp < 0)
500                         p = &((*p)->rb_left);
501                 else if (cmp > 0)
502                         p = &((*p)->rb_right);
503                 else
504                         return false; /* Duplicate security descriptor */
505         }
506         rb_link_node(&new->rb_node, rb_parent, p);
507         rb_insert_color(&new->rb_node, root);
508         return true;
509 }
510
511 /* Returns the index of the security descriptor having a SHA1 message digest of
512  * @hash.  If not found, return -1. */
513 int
514 lookup_sd(struct sd_set *set, const u8 hash[SHA1_HASH_SIZE])
515 {
516         struct rb_node *node = set->rb_root.rb_node;
517
518         while (node) {
519                 struct sd_node *sd_node = container_of(node, struct sd_node, rb_node);
520                 int cmp = hashes_cmp(hash, sd_node->hash);
521                 if (cmp < 0)
522                         node = node->rb_left;
523                 else if (cmp > 0)
524                         node = node->rb_right;
525                 else
526                         return sd_node->security_id;
527         }
528         return -1;
529 }
530
531 /*
532  * Adds a security descriptor to the indexed security descriptor set as well as
533  * the corresponding `struct wim_security_data', and returns the new security
534  * ID; or, if there is an existing security descriptor that is the same, return
535  * the security ID for it.  If a new security descriptor cannot be allocated,
536  * return -1.
537  */
538 int
539 sd_set_add_sd(struct sd_set *sd_set, const char descriptor[], size_t size)
540 {
541         u8 hash[SHA1_HASH_SIZE];
542         int security_id;
543         struct sd_node *new;
544         u8 **descriptors;
545         u64 *sizes;
546         u8 *descr_copy;
547         struct wim_security_data *sd;
548         bool bret;
549
550         sha1_buffer((const u8*)descriptor, size, hash);
551
552         security_id = lookup_sd(sd_set, hash);
553         if (security_id >= 0) /* Identical descriptor already exists */
554                 return security_id;
555
556         /* Need to add a new security descriptor */
557         new = MALLOC(sizeof(*new));
558         if (!new)
559                 goto out;
560         descr_copy = MALLOC(size);
561         if (!descr_copy)
562                 goto out_free_node;
563
564         sd = sd_set->sd;
565
566         memcpy(descr_copy, descriptor, size);
567         new->security_id = sd->num_entries;
568         copy_hash(new->hash, hash);
569
570         /* There typically are only a few dozen security descriptors in a
571          * directory tree, so expanding the array of security descriptors by
572          * only 1 extra space each time should not be a problem. */
573         descriptors = REALLOC(sd->descriptors,
574                               (sd->num_entries + 1) * sizeof(sd->descriptors[0]));
575         if (!descriptors)
576                 goto out_free_descr;
577         sd->descriptors = descriptors;
578         sizes = REALLOC(sd->sizes,
579                         (sd->num_entries + 1) * sizeof(sd->sizes[0]));
580         if (!sizes)
581                 goto out_free_descr;
582         sd->sizes = sizes;
583         sd->descriptors[sd->num_entries] = descr_copy;
584         sd->sizes[sd->num_entries] = size;
585         sd->num_entries++;
586         DEBUG("There are now %d security descriptors", sd->num_entries);
587         sd->total_length += size + sizeof(sd->sizes[0]);
588         bret = insert_sd_node(sd_set, new);
589         wimlib_assert(bret);
590         return new->security_id;
591 out_free_descr:
592         FREE(descr_copy);
593 out_free_node:
594         FREE(new);
595 out:
596         return -1;
597 }
598
599 /* Initialize a `struct sd_set' mapping from SHA1 message digests of security
600  * descriptors to indices into the security descriptors table of the WIM image
601  * (security IDs).  */
602 int
603 init_sd_set(struct sd_set *sd_set, struct wim_security_data *sd)
604 {
605         int ret;
606
607         sd_set->sd = sd;
608         sd_set->rb_root.rb_node = NULL;
609
610         /* Remember the original number of security descriptors so that newly
611          * added ones can be rolled back if needed. */
612         sd_set->orig_num_entries = sd->num_entries;
613         for (int32_t i = 0; i < sd->num_entries; i++) {
614                 struct sd_node *new;
615
616                 new = MALLOC(sizeof(struct sd_node));
617                 if (!new) {
618                         ret = WIMLIB_ERR_NOMEM;
619                         goto out_destroy_sd_set;
620                 }
621                 sha1_buffer(sd->descriptors[i], sd->sizes[i], new->hash);
622                 new->security_id = i;
623                 if (!insert_sd_node(sd_set, new))
624                         FREE(new); /* Ignore duplicate security descriptor */
625         }
626         ret = 0;
627         goto out;
628 out_destroy_sd_set:
629         destroy_sd_set(sd_set, false);
630 out:
631         return ret;
632 }