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