]> wimlib.net Git - wimlib/blob - src/security.c
5b0e81b3363f1b0372f741e4a56aedc52d6c06f4
[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 _ACE_HEADER {
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         u16 size;
47 } _packed_attribute ACE_HEADER;
48
49 /* Grants rights to a user or group */
50 typedef struct _ACCESS_ALLOWED_ACE {
51         ACE_HEADER hdr;
52         u32 mask;
53         u32 sid_start;
54 } _packed_attribute ACCESS_ALLOWED_ACE;
55
56 /* Denies rights to a user or group */
57 typedef struct _ACCESS_DENIED_ACE {
58         ACE_HEADER hdr;
59         u32 mask;
60         u32 sid_start;
61 } _packed_attribute ACCESS_DENIED_ACE;
62
63 typedef struct _SYSTEM_AUDIT_ACE {
64         ACE_HEADER hdr;
65         u32 mask;
66         u32 sid_start;
67 } _packed_attribute SYSTEM_AUDIT_ACE;
68
69
70 /* Header of an access control list. */
71 typedef struct _ACL {
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 } _packed_attribute ACL;
88
89 /* A structure used to identify users or groups. */
90 typedef struct _SID {
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 } _packed_attribute SID;
102
103
104 typedef struct _SECURITY_DESCRIPTOR_RELATIVE  {
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 } _packed_attribute SECURITY_DESCRIPTOR_RELATIVE;
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(SECURITY_DESCRIPTOR_RELATIVE)) {
149                 SECURITY_DESCRIPTOR_RELATIVE *sd = (SECURITY_DESCRIPTOR_RELATIVE*)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 * restrict sd,
331                     u8 * restrict p)
332 {
333         DEBUG("Writing security data (total_length = %"PRIu32", num_entries "
334               "= %"PRIu32")", sd->total_length, sd->num_entries);
335
336         u32 aligned_length = (sd->total_length + 7) & ~7;
337
338         u8 *orig_p = p;
339         p = put_u32(p, aligned_length);
340         p = put_u32(p, sd->num_entries);
341
342         for (u32 i = 0; i < sd->num_entries; i++)
343                 p = put_u64(p, sd->sizes[i]);
344
345         for (u32 i = 0; i < sd->num_entries; i++)
346                 p = put_bytes(p, sd->sizes[i], sd->descriptors[i]);
347
348         wimlib_assert(p - orig_p == sd->total_length);
349         p = put_zeroes(p, aligned_length - sd->total_length);
350
351         DEBUG("Successfully wrote security data.");
352         return p;
353 }
354
355 static void
356 print_acl(const void *p, const tchar *type)
357 {
358         const ACL *acl = p;
359         u8 revision = acl->revision;
360         u16 acl_size = le16_to_cpu(acl->acl_size);
361         u16 ace_count = le16_to_cpu(acl->ace_count);
362         tprintf(T("    [%"TS" ACL]\n"), type);
363         tprintf(T("    Revision = %u\n"), revision);
364         tprintf(T("    ACL Size = %u\n"), acl_size);
365         tprintf(T("    ACE Count = %u\n"), ace_count);
366
367         p += sizeof(ACL);
368         for (u16 i = 0; i < ace_count; i++) {
369                 const ACE_HEADER *hdr = p;
370                 tprintf(T("        [ACE]\n"));
371                 tprintf(T("        ACE type  = %d\n"), hdr->type);
372                 tprintf(T("        ACE flags = 0x%x\n"), hdr->flags);
373                 tprintf(T("        ACE size  = %u\n"), hdr->size);
374                 const ACCESS_ALLOWED_ACE *aaa = (const ACCESS_ALLOWED_ACE*)p;
375                 tprintf(T("        ACE mask = %x\n"), le32_to_cpu(aaa->mask));
376                 tprintf(T("        SID start = %u\n"), le32_to_cpu(aaa->sid_start));
377                 p += hdr->size;
378         }
379         tputchar(T('\n'));
380 }
381
382 static void
383 print_sid(const void *p, const tchar *type)
384 {
385         const SID *sid = p;
386         tprintf(T("    [%"TS" SID]\n"), type);
387         tprintf(T("    Revision = %u\n"), sid->revision);
388         tprintf(T("    Subauthority count = %u\n"), sid->sub_authority_count);
389         tprintf(T("    Identifier authority = "));
390         print_byte_field(sid->identifier_authority,
391                          sizeof(sid->identifier_authority), stdout);
392         tputchar(T('\n'));
393         for (u8 i = 0; i < sid->sub_authority_count; i++) {
394                 tprintf(T("    Subauthority %u = %u\n"),
395                         i, le32_to_cpu(sid->sub_authority[i]));
396         }
397         tputchar(T('\n'));
398 }
399
400 static void
401 print_security_descriptor(const void *p, u64 size)
402 {
403         const SECURITY_DESCRIPTOR_RELATIVE *sd = p;
404
405         u8 revision      = sd->revision;
406         u16 control      = le16_to_cpu(sd->security_descriptor_control);
407         u32 owner_offset = le32_to_cpu(sd->owner_offset);
408         u32 group_offset = le32_to_cpu(sd->group_offset);
409         u32 sacl_offset  = le32_to_cpu(sd->sacl_offset);
410         u32 dacl_offset  = le32_to_cpu(sd->dacl_offset);
411         tprintf(T("Revision = %u\n"), revision);
412         tprintf(T("Security Descriptor Control = %#x\n"), control);
413         tprintf(T("Owner offset = %u\n"), owner_offset);
414         tprintf(T("Group offset = %u\n"), group_offset);
415         tprintf(T("System ACL offset = %u\n"), sacl_offset);
416         tprintf(T("Discretionary ACL offset = %u\n"), dacl_offset);
417
418         if (sd->owner_offset != 0)
419                 print_sid(p + owner_offset, T("Owner"));
420         if (sd->group_offset != 0)
421                 print_sid(p + group_offset, T("Group"));
422         if (sd->sacl_offset != 0)
423                 print_acl(p + sacl_offset, T("System"));
424         if (sd->dacl_offset != 0)
425                 print_acl(p + dacl_offset, T("Discretionary"));
426 }
427
428 /*
429  * Prints the security data for a WIM file.
430  */
431 void
432 print_security_data(const struct wim_security_data *sd)
433 {
434         tputs(T("[SECURITY DATA]"));
435         tprintf(T("Length            = %"PRIu32" bytes\n"), sd->total_length);
436         tprintf(T("Number of Entries = %"PRIu32"\n"), sd->num_entries);
437
438         for (u32 i = 0; i < sd->num_entries; i++) {
439                 tprintf(T("[SECURITY_DESCRIPTOR_RELATIVE %"PRIu32", length = %"PRIu64"]\n"),
440                         i, sd->sizes[i]);
441                 print_security_descriptor(sd->descriptors[i], sd->sizes[i]);
442                 tputchar(T('\n'));
443         }
444         tputchar(T('\n'));
445 }
446
447 void
448 free_security_data(struct wim_security_data *sd)
449 {
450         if (sd) {
451                 u8 **descriptors = sd->descriptors;
452                 u32 num_entries  = sd->num_entries;
453                 if (descriptors)
454                         while (num_entries--)
455                                 FREE(*descriptors++);
456                 FREE(sd->sizes);
457                 FREE(sd->descriptors);
458                 FREE(sd);
459         }
460 }
461
462 struct sd_node {
463         int security_id;
464         u8 hash[SHA1_HASH_SIZE];
465         struct rb_node rb_node;
466 };
467
468 static void
469 free_sd_tree(struct rb_node *node)
470 {
471         if (node) {
472                 free_sd_tree(node->rb_left);
473                 free_sd_tree(node->rb_right);
474                 FREE(container_of(node, struct sd_node, rb_node));
475         }
476 }
477
478 /* Frees a security descriptor index set. */
479 void
480 destroy_sd_set(struct wim_sd_set *sd_set, bool rollback)
481 {
482         if (rollback) {
483                 struct wim_security_data *sd = sd_set->sd;
484                 for (s32 i = sd_set->orig_num_entries; i < sd->num_entries; i++)
485                         FREE(sd->descriptors[i]);
486                 sd->num_entries = sd_set->orig_num_entries;
487         }
488         free_sd_tree(sd_set->rb_root.rb_node);
489 }
490
491 /* Inserts a a new node into the security descriptor index tree. */
492 static bool
493 insert_sd_node(struct wim_sd_set *set, struct sd_node *new)
494 {
495         struct rb_root *root = &set->rb_root;
496         struct rb_node **p = &(root->rb_node);
497         struct rb_node *rb_parent = NULL;
498
499         while (*p) {
500                 struct sd_node *this = container_of(*p, struct sd_node, rb_node);
501                 int cmp = hashes_cmp(new->hash, this->hash);
502
503                 rb_parent = *p;
504                 if (cmp < 0)
505                         p = &((*p)->rb_left);
506                 else if (cmp > 0)
507                         p = &((*p)->rb_right);
508                 else
509                         return false; /* Duplicate security descriptor */
510         }
511         rb_link_node(&new->rb_node, rb_parent, p);
512         rb_insert_color(&new->rb_node, root);
513         return true;
514 }
515
516 /* Returns the index of the security descriptor having a SHA1 message digest of
517  * @hash.  If not found, return -1. */
518 int
519 lookup_sd(struct wim_sd_set *set, const u8 hash[SHA1_HASH_SIZE])
520 {
521         struct rb_node *node = set->rb_root.rb_node;
522
523         while (node) {
524                 struct sd_node *sd_node = container_of(node, struct sd_node, rb_node);
525                 int cmp = hashes_cmp(hash, sd_node->hash);
526                 if (cmp < 0)
527                         node = node->rb_left;
528                 else if (cmp > 0)
529                         node = node->rb_right;
530                 else
531                         return sd_node->security_id;
532         }
533         return -1;
534 }
535
536 /*
537  * Adds a security descriptor to the indexed security descriptor set as well as
538  * the corresponding `struct wim_security_data', and returns the new security
539  * ID; or, if there is an existing security descriptor that is the same, return
540  * the security ID for it.  If a new security descriptor cannot be allocated,
541  * return -1.
542  */
543 int
544 sd_set_add_sd(struct wim_sd_set *sd_set, const char *descriptor, size_t size)
545 {
546         u8 hash[SHA1_HASH_SIZE];
547         int security_id;
548         struct sd_node *new;
549         u8 **descriptors;
550         u64 *sizes;
551         char *descr_copy;
552         struct wim_security_data *sd;
553         bool bret;
554
555         sha1_buffer(descriptor, size, hash);
556
557         security_id = lookup_sd(sd_set, hash);
558         if (security_id >= 0) /* Identical descriptor already exists */
559                 return security_id;
560
561         /* Need to add a new security descriptor */
562         new = MALLOC(sizeof(*new));
563         if (!new)
564                 goto out;
565         descr_copy = MALLOC(size);
566         if (!descr_copy)
567                 goto out_free_node;
568
569         sd = sd_set->sd;
570
571         memcpy(descr_copy, descriptor, size);
572         new->security_id = sd->num_entries;
573         copy_hash(new->hash, hash);
574
575         /* There typically are only a few dozen security descriptors in a
576          * directory tree, so expanding the array of security descriptors by
577          * only 1 extra space each time should not be a problem. */
578         descriptors = REALLOC(sd->descriptors,
579                               (sd->num_entries + 1) * sizeof(sd->descriptors[0]));
580         if (!descriptors)
581                 goto out_free_descr;
582         sd->descriptors = descriptors;
583         sizes = REALLOC(sd->sizes,
584                         (sd->num_entries + 1) * sizeof(sd->sizes[0]));
585         if (!sizes)
586                 goto out_free_descr;
587         sd->sizes = sizes;
588         sd->descriptors[sd->num_entries] = descr_copy;
589         sd->sizes[sd->num_entries] = size;
590         sd->num_entries++;
591         DEBUG("There are now %d security descriptors", sd->num_entries);
592         sd->total_length += size + sizeof(sd->sizes[0]);
593         bret = insert_sd_node(sd_set, new);
594         wimlib_assert(bret);
595         return new->security_id;
596 out_free_descr:
597         FREE(descr_copy);
598 out_free_node:
599         FREE(new);
600 out:
601         return -1;
602 }
603
604 /* Initialize a `struct sd_set' mapping from SHA1 message digests of security
605  * descriptors to indices into the security descriptors table of the WIM image
606  * (security IDs).  */
607 int
608 init_sd_set(struct wim_sd_set *sd_set, struct wim_security_data *sd)
609 {
610         int ret;
611
612         sd_set->sd = sd;
613         sd_set->rb_root.rb_node = NULL;
614
615         /* Remember the original number of security descriptors so that newly
616          * added ones can be rolled back if needed. */
617         sd_set->orig_num_entries = sd->num_entries;
618         for (s32 i = 0; i < sd->num_entries; i++) {
619                 struct sd_node *new;
620
621                 new = MALLOC(sizeof(struct sd_node));
622                 if (!new) {
623                         ret = WIMLIB_ERR_NOMEM;
624                         goto out_destroy_sd_set;
625                 }
626                 sha1_buffer(sd->descriptors[i], sd->sizes[i], new->hash);
627                 new->security_id = i;
628                 if (!insert_sd_node(sd_set, new))
629                         FREE(new); /* Ignore duplicate security descriptor */
630         }
631         ret = 0;
632         goto out;
633 out_destroy_sd_set:
634         destroy_sd_set(sd_set, false);
635 out:
636         return ret;
637 }