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 // Each command should be aligned
80 constexpr size_t expectedAlignment = alignof(void *);
81 if (Q_UNLIKELY(cmdsize % expectedAlignment != 0))
82 return std::nullopt;
83
84 // A load command must at least contain its own header
85 if (Q_UNLIKELY(cmdsize < sizeof(load_command)))
86 return std::nullopt;
87
88 // cmdsize can't be trusted until validated against fdlen
89 if (qAddOverflow(minsize, ulong(cmdsize), &minsize) || Q_UNLIKELY(minsize > fdlen))
90 return std::nullopt;
91
92 if (loadCommand->cmd == LC_ENCRYPTION_INFO || loadCommand->cmd == LC_ENCRYPTION_INFO_64) {
93 // The layout of encryption_info_command and encryption_info_command_64 is the same
94 // up until and including cryptid, so we can treat it as encryption_info_command.
95 // Make sure the command is big enough to hold the field we read.
96 if (Q_UNLIKELY(cmdsize < sizeof(encryption_info_command)))
97 return std::nullopt;
98 auto encryptionInfoCommand = reinterpret_cast<encryption_info_command*>(loadCommand);
99 return encryptionInfoCommand->cryptid != 0;
100 }
101
102 commandCursor += cmdsize;
103 }
104
105 return false;
106}
107
108QLibraryScanResult QMachOParser::parse(const char *m_s, ulong fdlen, QString *errorString)
109{
110 // The minimum size of a Mach-O binary we're interested in.
111 // It must have a full Mach header, at least one segment and at least one
112 // section. It's probably useless with just the "qtmetadata" section, but
113 // it's valid nonetheless.
114 // A fat binary must have this plus the fat header, of course.
115 static const size_t MinFileSize = sizeof(my_mach_header) + sizeof(my_segment_command) + sizeof(my_section);
116 static const size_t MinFatHeaderSize = sizeof(fat_header) + 2 * sizeof(fat_arch);
117
118 if (Q_UNLIKELY(fdlen < MinFileSize))
119 return notfound(QLibrary::tr("file too small"), errorString);
120
121 // find out if this is a fat Mach-O binary first
122 const my_mach_header *header = nullptr;
123 const fat_header *fat = reinterpret_cast<const fat_header *>(m_s);
124 if (fat->magic == qToBigEndian(FAT_MAGIC)) {
125 // find our architecture in the binary
126 const fat_arch *arch = reinterpret_cast<const fat_arch *>(fat + 1);
127 if (Q_UNLIKELY(fdlen < MinFatHeaderSize)) {
128 return notfound(QLibrary::tr("file too small"), errorString);
129 }
130
131 uint32_t count = qFromBigEndian(fat->nfat_arch);
132 if (Q_UNLIKELY(fdlen < sizeof(*fat) + sizeof(*arch) * quint64{count}))
133 return notfound(QString(), errorString);
134
135 for (uint32_t i = 0; i < count; ++i) {
136 if (arch[i].cputype == qToBigEndian(my_cputype)) {
137 // ### should we check the CPU subtype? Maybe on ARM?
138 uint32_t size = qFromBigEndian(arch[i].size);
139 uint32_t offset = qFromBigEndian(arch[i].offset);
140 uint32_t align = qFromBigEndian(arch[i].align);
141 if (Q_UNLIKELY(size > fdlen) || Q_UNLIKELY(offset > fdlen)
142 || Q_UNLIKELY(size > fdlen - offset) || Q_UNLIKELY(size < MinFileSize)
143 || Q_UNLIKELY(align >= 32) || Q_UNLIKELY(offset % (1u << align) != 0))
144 return notfound(QString(), errorString);
145
146 header = reinterpret_cast<const my_mach_header *>(m_s + offset);
147 fdlen = size;
148 break;
149 }
150 }
151 if (!header)
152 return notfound(QLibrary::tr("no suitable architecture in fat binary"), errorString);
153
154 // check the magic again
155 if (Q_UNLIKELY(header->magic != my_magic))
156 return notfound(QString(), errorString);
157 } else {
158 header = reinterpret_cast<const my_mach_header *>(m_s);
159 fat = 0;
160
161 // check magic
162 if (header->magic != my_magic)
163 return notfound(QLibrary::tr("invalid magic %1").arg(qFromBigEndian(header->magic),
164 8, 16, '0'_L1),
165 errorString);
166 }
167
168 // from this point on, everything is in host byte order
169
170 // (re-)check the CPU type
171 // ### should we check the CPU subtype? Maybe on ARM?
172 if (header->cputype != my_cputype) {
173 if (fat)
174 return notfound(QString(), errorString);
175 return notfound(QLibrary::tr("wrong architecture"), errorString);
176 }
177
178 // check the file type
179 if (Q_UNLIKELY(header->filetype != MH_BUNDLE && header->filetype != MH_DYLIB))
180 return notfound(QLibrary::tr("not a dynamic library"), errorString);
181
182 // find the __TEXT segment, "qtmetadata" section
183 const my_segment_command *seg = reinterpret_cast<const my_segment_command *>(header + 1);
184 ulong minsize = sizeof(*header);
185
186 for (uint i = 0; i < header->ncmds; ++i,
187 seg = reinterpret_cast<const my_segment_command *>(reinterpret_cast<const char *>(seg) + seg->cmdsize)) {
188 // We're sure that the file size includes at least one load command
189 // but we have to check anyway if we're past the first
190 if (Q_UNLIKELY(fdlen < minsize + sizeof(load_command)))
191 return notfound(QString(), errorString);
192
193 // cmdsize can't be trusted until validated
194 // so check it against fdlen anyway
195 // (these are unsigned operations, with overflow behavior specified in the standard)
196 minsize += seg->cmdsize;
197
198 // Each command should be aligned
199 constexpr size_t expectedAlignment = alignof(void *);
200 if (Q_UNLIKELY(seg->cmdsize % expectedAlignment != 0))
201 return notfound(QString(), errorString);
202
203 // The command should at least contain its header...
204 if (Q_UNLIKELY(seg->cmdsize < sizeof(load_command)))
205 return notfound(QString(), errorString);
206 // ... and also must not exceed the file length
207 if (Q_UNLIKELY(fdlen < minsize) || Q_UNLIKELY(fdlen < seg->cmdsize))
208 return notfound(QString(), errorString);
209
210 const uint32_t MyLoadCommand = sizeof(void *) > 4 ? LC_SEGMENT_64 : LC_SEGMENT;
211 if (seg->cmd != MyLoadCommand)
212 continue;
213
214 // Similarly, for segment command, check that it at least contains its
215 // header.
216 if (Q_UNLIKELY(seg->cmdsize < sizeof(my_segment_command)))
217 return notfound(QString(), errorString);
218
219 // is this the __TEXT segment?
220 if (strcmp(seg->segname, "__TEXT") == 0) {
221 const my_section *sect = reinterpret_cast<const my_section *>(seg + 1);
222 // Verify that seg->nsects sections actually fit into the command.
223 // We already checked that cmdsize is within the file size earlier.
224 if (Q_UNLIKELY(quint64{seg->cmdsize} < sizeof(my_segment_command) + quint64{seg->nsects} * sizeof(my_section)))
225 return notfound(QString(), errorString);
226 for (uint j = 0; j < seg->nsects; ++j) {
227 // is this the "qtmetadata" section?
228 if (strcmp(sect[j].sectname, "qtmetadata") != 0)
229 continue;
230
231 // found it!
232 if (Q_UNLIKELY(fdlen < sect[j].offset) || Q_UNLIKELY(fdlen < sect[j].size)
233 || Q_UNLIKELY(fdlen < sect[j].offset + sect[j].size))
234 return notfound(QString(), errorString);
235
236 if (sect[j].size < sizeof(QPluginMetaData::MagicHeader))
237 return notfound(QLibrary::tr(".qtmetadata section is too small"), errorString);
238
239 const std::optional<bool> binaryIsEncrypted = isEncrypted(header, fdlen);
240 if (Q_UNLIKELY(!binaryIsEncrypted))
241 return notfound(QLibrary::tr("corrupted encryption_info section"), errorString);
242 qsizetype pos = reinterpret_cast<const char *>(header) - m_s + sect[j].offset;
243
244 // We can not read the section data of encrypted libraries until they
245 // have been dlopened(), so skip validity check if that's the case.
246 if (IncludeValidityChecks && !*binaryIsEncrypted) {
247 QByteArrayView expectedMagic = QByteArrayView::fromArray(QPluginMetaData::MagicString);
248 QByteArrayView actualMagic = QByteArrayView(m_s + pos, expectedMagic.size());
249 if (expectedMagic != actualMagic)
250 return notfound(QLibrary::tr(".qtmetadata section has incorrect magic"), errorString);
251 }
252
253 pos += sizeof(QPluginMetaData::MagicString);
254 return { pos, qsizetype(sect[j].size - sizeof(QPluginMetaData::MagicString)), *binaryIsEncrypted };
255 }
256 }
257 }
258
259 // No .qtmetadata section was found
260 *errorString = QLibrary::tr("'%1' is not a Qt plugin").arg(*errorString);
261 return {};
262}
263
264QT_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)