Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qmachparser.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 Intel Corporation.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:critical reason:data-parser
4
6
7#include <qendian.h>
8
9#include <optional>
10
11#include <mach-o/loader.h>
12#include <mach-o/fat.h>
13
14QT_BEGIN_NAMESPACE
15
16using namespace Qt::StringLiterals;
17
18// Whether we include some extra validity checks
19// (checks to ensure we don't read out-of-bounds are always included)
20static constexpr bool IncludeValidityChecks = true;
21
22#if defined(Q_PROCESSOR_X86_64)
23# define MACHO64
24static const cpu_type_t my_cputype = CPU_TYPE_X86_64;
25#elif defined(Q_PROCESSOR_X86_32)
26static const cpu_type_t my_cputype = CPU_TYPE_X86;
27#elif defined(Q_PROCESSOR_POWER_64)
28# define MACHO64
29static const cpu_type_t my_cputype = CPU_TYPE_POWERPC64;
30#elif defined(Q_PROCESSOR_POWER_32)
31static const cpu_type_t my_cputype = CPU_TYPE_POWERPC;
32#elif defined(Q_PROCESSOR_ARM_64)
33# define MACHO64
34static const cpu_type_t my_cputype = CPU_TYPE_ARM64;
35#elif defined(Q_PROCESSOR_ARM)
36static const cpu_type_t my_cputype = CPU_TYPE_ARM;
37#else
38# error "Unknown CPU type"
39#endif
40
41#ifdef MACHO64
42# undef MACHO64
43typedef mach_header_64 my_mach_header;
44typedef segment_command_64 my_segment_command;
45typedef section_64 my_section;
46static const uint32_t my_magic = MH_MAGIC_64;
47#else
51static const uint32_t my_magic = MH_MAGIC;
52#endif
53
54Q_DECL_COLD_FUNCTION
55static QLibraryScanResult notfound(const QString &reason, QString *errorString)
56{
57 *errorString = QLibrary::tr("'%1' is not a valid Mach-O binary (%2)")
58 .arg(*errorString, reason.isEmpty() ? QLibrary::tr("file is corrupt") : reason);
59 return {};
60}
61
62// Returns whether the binary is encrypted, or nullopt if the load-command table
63// is malformed or extends past the end of the (mmapped) file.
64static std::optional<bool> isEncrypted(const my_mach_header *header, ulong fdlen)
65{
66 auto commandCursor = uintptr_t(header) + sizeof(my_mach_header);
67 // QMachOParser::parse() verifies that fdlen is large enough for at least
68 // my_mach_header + load_command.
69 ulong minsize = sizeof(my_mach_header);
70
71 for (uint32_t i = 0; i < header->ncmds; ++i) {
72 // We must be able to read the load command header (cmd + cmdsize).
73 if (Q_UNLIKELY(fdlen - sizeof(load_command) < minsize))
74 return std::nullopt;
75
76 load_command *loadCommand = reinterpret_cast<load_command *>(commandCursor);
77 const uint32_t cmdsize = loadCommand->cmdsize;
78
79 // A load command must at least contain its own header
80 if (Q_UNLIKELY(cmdsize < sizeof(load_command)))
81 return std::nullopt;
82
83 // cmdsize can't be trusted until validated against fdlen
84 if (qAddOverflow(minsize, ulong(cmdsize), &minsize) || Q_UNLIKELY(minsize > fdlen))
85 return std::nullopt;
86
87 if (loadCommand->cmd == LC_ENCRYPTION_INFO || loadCommand->cmd == LC_ENCRYPTION_INFO_64) {
88 // The layout of encryption_info_command and encryption_info_command_64 is the same
89 // up until and including cryptid, so we can treat it as encryption_info_command.
90 // Make sure the command is big enough to hold the field we read.
91 if (Q_UNLIKELY(cmdsize < sizeof(encryption_info_command)))
92 return std::nullopt;
93 auto encryptionInfoCommand = reinterpret_cast<encryption_info_command*>(loadCommand);
94 return encryptionInfoCommand->cryptid != 0;
95 }
96
97 commandCursor += cmdsize;
98 }
99
100 return false;
101}
102
103QLibraryScanResult QMachOParser::parse(const char *m_s, ulong fdlen, QString *errorString)
104{
105 // The minimum size of a Mach-O binary we're interested in.
106 // It must have a full Mach header, at least one segment and at least one
107 // section. It's probably useless with just the "qtmetadata" section, but
108 // it's valid nonetheless.
109 // A fat binary must have this plus the fat header, of course.
110 static const size_t MinFileSize = sizeof(my_mach_header) + sizeof(my_segment_command) + sizeof(my_section);
111 static const size_t MinFatHeaderSize = sizeof(fat_header) + 2 * sizeof(fat_arch);
112
113 if (Q_UNLIKELY(fdlen < MinFileSize))
114 return notfound(QLibrary::tr("file too small"), errorString);
115
116 // find out if this is a fat Mach-O binary first
117 const my_mach_header *header = nullptr;
118 const fat_header *fat = reinterpret_cast<const fat_header *>(m_s);
119 if (fat->magic == qToBigEndian(FAT_MAGIC)) {
120 // find our architecture in the binary
121 const fat_arch *arch = reinterpret_cast<const fat_arch *>(fat + 1);
122 if (Q_UNLIKELY(fdlen < MinFatHeaderSize)) {
123 return notfound(QLibrary::tr("file too small"), errorString);
124 }
125
126 int count = qFromBigEndian(fat->nfat_arch);
127 if (Q_UNLIKELY(fdlen < sizeof(*fat) + sizeof(*arch) * count))
128 return notfound(QString(), errorString);
129
130 for (int i = 0; i < count; ++i) {
131 if (arch[i].cputype == qToBigEndian(my_cputype)) {
132 // ### should we check the CPU subtype? Maybe on ARM?
133 uint32_t size = qFromBigEndian(arch[i].size);
134 uint32_t offset = qFromBigEndian(arch[i].offset);
135 if (Q_UNLIKELY(size > fdlen) || Q_UNLIKELY(offset > fdlen)
136 || Q_UNLIKELY(size + offset > fdlen) || Q_UNLIKELY(size < MinFileSize))
137 return notfound(QString(), errorString);
138
139 header = reinterpret_cast<const my_mach_header *>(m_s + offset);
140 fdlen = size;
141 break;
142 }
143 }
144 if (!header)
145 return notfound(QLibrary::tr("no suitable architecture in fat binary"), errorString);
146
147 // check the magic again
148 if (Q_UNLIKELY(header->magic != my_magic))
149 return notfound(QString(), errorString);
150 } else {
151 header = reinterpret_cast<const my_mach_header *>(m_s);
152 fat = 0;
153
154 // check magic
155 if (header->magic != my_magic)
156 return notfound(QLibrary::tr("invalid magic %1").arg(qFromBigEndian(header->magic),
157 8, 16, '0'_L1),
158 errorString);
159 }
160
161 // from this point on, everything is in host byte order
162
163 // (re-)check the CPU type
164 // ### should we check the CPU subtype? Maybe on ARM?
165 if (header->cputype != my_cputype) {
166 if (fat)
167 return notfound(QString(), errorString);
168 return notfound(QLibrary::tr("wrong architecture"), errorString);
169 }
170
171 // check the file type
172 if (Q_UNLIKELY(header->filetype != MH_BUNDLE && header->filetype != MH_DYLIB))
173 return notfound(QLibrary::tr("not a dynamic library"), errorString);
174
175 // find the __TEXT segment, "qtmetadata" section
176 const my_segment_command *seg = reinterpret_cast<const my_segment_command *>(header + 1);
177 ulong minsize = sizeof(*header);
178
179 for (uint i = 0; i < header->ncmds; ++i,
180 seg = reinterpret_cast<const my_segment_command *>(reinterpret_cast<const char *>(seg) + seg->cmdsize)) {
181 // We're sure that the file size includes at least one load command
182 // but we have to check anyway if we're past the first
183 if (Q_UNLIKELY(fdlen < minsize + sizeof(load_command)))
184 return notfound(QString(), errorString);
185
186 // cmdsize can't be trusted until validated
187 // so check it against fdlen anyway
188 // (these are unsigned operations, with overflow behavior specified in the standard)
189 minsize += seg->cmdsize;
190 if (Q_UNLIKELY(fdlen < minsize) || Q_UNLIKELY(fdlen < seg->cmdsize))
191 return notfound(QString(), errorString);
192
193 const uint32_t MyLoadCommand = sizeof(void *) > 4 ? LC_SEGMENT_64 : LC_SEGMENT;
194 if (seg->cmd != MyLoadCommand)
195 continue;
196
197 // is this the __TEXT segment?
198 if (strcmp(seg->segname, "__TEXT") == 0) {
199 const my_section *sect = reinterpret_cast<const my_section *>(seg + 1);
200 for (uint j = 0; j < seg->nsects; ++j) {
201 // is this the "qtmetadata" section?
202 if (strcmp(sect[j].sectname, "qtmetadata") != 0)
203 continue;
204
205 // found it!
206 if (Q_UNLIKELY(fdlen < sect[j].offset) || Q_UNLIKELY(fdlen < sect[j].size)
207 || Q_UNLIKELY(fdlen < sect[j].offset + sect[j].size))
208 return notfound(QString(), errorString);
209
210 if (sect[j].size < sizeof(QPluginMetaData::MagicHeader))
211 return notfound(QLibrary::tr(".qtmetadata section is too small"), errorString);
212
213 const std::optional<bool> binaryIsEncrypted = isEncrypted(header, fdlen);
214 if (Q_UNLIKELY(!binaryIsEncrypted))
215 return notfound(QLibrary::tr("corrupted encryption_info section"), errorString);
216 qsizetype pos = reinterpret_cast<const char *>(header) - m_s + sect[j].offset;
217
218 // We can not read the section data of encrypted libraries until they
219 // have been dlopened(), so skip validity check if that's the case.
220 if (IncludeValidityChecks && !*binaryIsEncrypted) {
221 QByteArrayView expectedMagic = QByteArrayView::fromArray(QPluginMetaData::MagicString);
222 QByteArrayView actualMagic = QByteArrayView(m_s + pos, expectedMagic.size());
223 if (expectedMagic != actualMagic)
224 return notfound(QLibrary::tr(".qtmetadata section has incorrect magic"), errorString);
225 }
226
227 pos += sizeof(QPluginMetaData::MagicString);
228 return { pos, qsizetype(sect[j].size - sizeof(QPluginMetaData::MagicString)), *binaryIsEncrypted };
229 }
230 }
231
232 // other type of segment
233 seg = reinterpret_cast<const my_segment_command *>(reinterpret_cast<const char *>(seg) + seg->cmdsize);
234 }
235
236 // No .qtmetadata section was found
237 *errorString = QLibrary::tr("'%1' is not a Qt plugin").arg(*errorString);
238 return {};
239}
240
241QT_END_NAMESPACE
mach_header my_mach_header
static const uint32_t my_magic
segment_command my_segment_command
static constexpr bool IncludeValidityChecks
section my_section
static std::optional< bool > isEncrypted(const my_mach_header *header, ulong fdlen)