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
qcoffpeparser.cpp
Go to the documentation of this file.
1// Copyright (C) 2021 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#include <qloggingcategory.h>
9#include <qnumeric.h>
10
11#include <optional>
12
13// Include minimal set of headers
14#define WIN32_LEAN_AND_MEAN
15#define NOGDI
16#include <qt_windows.h>
17
18QT_BEGIN_NAMESPACE
19
20using namespace Qt::StringLiterals;
21
22// Whether we include some extra validity checks
23// (checks to ensure we don't read out-of-bounds are always included)
24static constexpr bool IncludeValidityChecks = true;
25
26static constexpr inline auto metadataSectionName() noexcept { return ".qtmetadata"_L1; }
28 metadataSectionName().left(sizeof(IMAGE_SECTION_HEADER::Name));
29
30#ifdef QT_BUILD_INTERNAL
31# define QCOFFPEPARSER_DEBUG
32#endif
33#if defined(QCOFFPEPARSER_DEBUG)
34Q_STATIC_LOGGING_CATEGORY(lcCoffPeParser, "qt.core.plugin.coffpeparser")
35# define peDebug qCDebug(lcCoffPeParser) << reinterpret_cast<const char16_t *>(error.errMsg->constData()) << ':'
36#else
37# define peDebug if (false) {} else QNoDebug()
38#endif
39
40QT_WARNING_PUSH
41QT_WARNING_DISABLE_CLANG("-Wunused-const-variable")
42
43static const WORD ExpectedMachine =
44#if 0
45 // nothing, just so everything is #elf
46#elif defined(Q_PROCESSOR_ARM_32)
47 IMAGE_FILE_MACHINE_ARMNT
48#elif defined(Q_PROCESSOR_ARM_64)
49 IMAGE_FILE_MACHINE_ARM64
50#elif defined(Q_PROCESSOR_IA64)
51 IMAGE_FILE_MACHINE_IA64
52#elif defined(Q_PROCESSOR_RISCV_32)
53 0x5032 // IMAGE_FILE_MACHINE_RISCV32
54#elif defined(Q_PROCESSOR_RISCV_64)
55 0x5064 // IMAGE_FILE_MACHINE_RISCV64
56#elif defined(Q_PROCESSOR_X86_32)
57 IMAGE_FILE_MACHINE_I386
58#elif defined(Q_PROCESSOR_X86_64)
59 IMAGE_FILE_MACHINE_AMD64
60#else
61# error "Unknown Q_PROCESSOR_xxx macro, please update."
62 IMAGE_FILE_MACHINE_UNKNOWN
63#endif
64 ;
65
67 sizeof(void*) == sizeof(quint64) ? IMAGE_NT_OPTIONAL_HDR64_MAGIC :
68 IMAGE_NT_OPTIONAL_HDR32_MAGIC;
69
70namespace {
71struct ErrorMaker
72{
73 QString *errMsg;
74 constexpr ErrorMaker(QString *errMsg) : errMsg(errMsg) {}
75
76 Q_DECL_COLD_FUNCTION QLibraryScanResult operator()(QString &&text) const
77 {
78 *errMsg = QLibrary::tr("'%1' is not a valid Windows DLL (%2)").arg(*errMsg, std::move(text));
79 return {};
80 }
81
82 Q_DECL_COLD_FUNCTION QLibraryScanResult toosmall() const
83 {
84 *errMsg = QLibrary::tr("'%1' is too small").arg(*errMsg);
85 return {};
86 }
87
88 Q_DECL_COLD_FUNCTION QLibraryScanResult notplugin(QString &&explanation) const
89 {
90 *errMsg = QLibrary::tr("'%1' is not a Qt plugin (%2)").arg(*errMsg, explanation);
91 return {};
92 }
93
94 Q_DECL_COLD_FUNCTION QLibraryScanResult notfound() const
95 {
96 return notplugin(QLibrary::tr("metadata not found"));
97 }
98};
99
100struct HeaderDebug { const IMAGE_NT_HEADERS *h; };
101Q_DECL_UNUSED static QDebug &operator<<(QDebug &d, HeaderDebug h)
102{
103 switch (h.h->Signature & 0xffff) {
104 case IMAGE_OS2_SIGNATURE: return d << "NE executable";
105 case IMAGE_VXD_SIGNATURE: return d << "LE executable";
106 default: return d << "Unknown file type";
107 case IMAGE_NT_SIGNATURE: break;
108 }
109
110 // the FileHeader and the starting portion of OptionalHeader are the same
111 // for 32- and 64-bit
112 switch (h.h->OptionalHeader.Magic) {
113 case IMAGE_NT_OPTIONAL_HDR32_MAGIC: d << "COFF PE"; break;
114 case IMAGE_NT_OPTIONAL_HDR64_MAGIC: d << "COFF PE+"; break;
115 default: return d << "Unknown COFF PE type";
116 }
117
118 QDebugStateSaver saver(d);
119 d.nospace() << Qt::hex << Qt::showbase;
120
121 switch (h.h->FileHeader.Machine) {
122 case IMAGE_FILE_MACHINE_I386: d << "i386"; break;
123 case IMAGE_FILE_MACHINE_ARM: d << "ARM"; break;
124 case IMAGE_FILE_MACHINE_ARMNT: d << "ARM Thumb-2"; break;
125 case IMAGE_FILE_MACHINE_THUMB: d << "Thumb"; break;
126 case IMAGE_FILE_MACHINE_IA64: d << "IA-64"; break;
127 case IMAGE_FILE_MACHINE_MIPS16: d << "MIPS16"; break;
128 case IMAGE_FILE_MACHINE_MIPSFPU: d << "MIPS with FPU"; break;
129 case IMAGE_FILE_MACHINE_MIPSFPU16: d << "MIPS16 with FPU"; break;
130 case IMAGE_FILE_MACHINE_AMD64: d << "x86-64"; break;
131 case 0xaa64: d << "AArch64"; break;
132 default: d << h.h->FileHeader.Machine; break;
133 }
134
135 // this usually prints "executable DLL"
136 if (h.h->FileHeader.Characteristics & IMAGE_FILE_EXECUTABLE_IMAGE)
137 d << " executable";
138 if (h.h->FileHeader.Characteristics & IMAGE_FILE_DLL)
139 d << " DLL";
140 if (h.h->FileHeader.Characteristics & IMAGE_FILE_LARGE_ADDRESS_AWARE)
141 d << " large-address aware";
142
143 d << ", " << Qt::dec << h.h->FileHeader.NumberOfSections << " sections, ";
144 if (h.h->FileHeader.SizeOfOptionalHeader < sizeof(IMAGE_OPTIONAL_HEADER32))
145 return d;
146
147 auto optDebug = [&d](const auto *hdr) {
148 d << "(Windows " << hdr->MajorSubsystemVersion
149 << '.' << hdr->MinorSubsystemVersion;
150 switch (hdr->Subsystem) {
151 case IMAGE_SUBSYSTEM_NATIVE: d << " native)"; break;
152 case IMAGE_SUBSYSTEM_WINDOWS_GUI: d << " GUI)"; break;
153 case IMAGE_SUBSYSTEM_WINDOWS_CUI: d << " CUI)"; break;
154 default: d << " subsystem " << hdr->Subsystem << ')'; break;
155 }
156
157 d.space() << Qt::hex << hdr->SizeOfHeaders << "header bytes,"
158 << Qt::dec << hdr->NumberOfRvaAndSizes << "RVA entries";
159 };
160
161 if (h.h->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC)
162 optDebug(reinterpret_cast<const IMAGE_OPTIONAL_HEADER64 *>(&h.h->OptionalHeader));
163 else
164 optDebug(reinterpret_cast<const IMAGE_OPTIONAL_HEADER32 *>(&h.h->OptionalHeader));
165 return d;
166}
167
168struct SectionDebug { const IMAGE_SECTION_HEADER *s; };
169Q_DECL_UNUSED static QDebug &operator<<(QDebug &d, SectionDebug s)
170{
171 QDebugStateSaver saver(d);
172 d << Qt::hex << Qt::showbase;
173 d << "contains";
174 if (s.s->Characteristics & IMAGE_SCN_CNT_CODE)
175 d << "CODE";
176 if (s.s->Characteristics & IMAGE_SCN_CNT_INITIALIZED_DATA)
177 d << "DATA";
178 if (s.s->Characteristics & IMAGE_SCN_CNT_UNINITIALIZED_DATA)
179 d << "BSS";
180
181 d << "flags";
182 d.nospace();
183 if (s.s->Characteristics & IMAGE_SCN_MEM_READ)
184 d << 'R';
185 if (s.s->Characteristics & IMAGE_SCN_MEM_WRITE)
186 d << 'W';
187 if (s.s->Characteristics & IMAGE_SCN_MEM_EXECUTE)
188 d << 'X';
189 if (s.s->Characteristics & IMAGE_SCN_MEM_SHARED)
190 d << 'S';
191 if (s.s->Characteristics & IMAGE_SCN_MEM_DISCARDABLE)
192 d << 'D';
193
194 d.space() << "offset" << s.s->PointerToRawData << "size" << s.s->SizeOfRawData;
195 return d;
196}
197} // unnamed namespace
198
199QT_WARNING_POP
200
201const IMAGE_NT_HEADERS *checkNtHeaders(QByteArrayView data, const ErrorMaker &error)
202{
203 if (size_t(data.size()) < qMax(sizeof(IMAGE_DOS_HEADER), sizeof(IMAGE_NT_HEADERS))) {
204 peDebug << "file too small:" << size_t(data.size());
205 return error.toosmall(), nullptr;
206 }
207
208 // check if there's a DOS image header (almost everything does)
209 size_t off = 0;
210 auto dosHeader = reinterpret_cast<const IMAGE_DOS_HEADER *>(data.data());
211 if (dosHeader->e_magic == IMAGE_DOS_SIGNATURE) {
212 off = dosHeader->e_lfanew;
213 // peDebug << "DOS file header redirects to offset" << Qt::hex << Qt::showbase << off;
214 if (size_t end; qAddOverflow<sizeof(IMAGE_NT_HEADERS)>(off, &end)
215 || end > size_t(data.size())) {
216 peDebug << "file too small:" << size_t(data.size());
217 return error.toosmall(), nullptr;
218 }
219 }
220
221 // now check the NT headers
222 auto ntHeader = reinterpret_cast<const IMAGE_NT_HEADERS *>(data.data() + off);
223 peDebug << HeaderDebug{ntHeader};
224 if (ntHeader->Signature != IMAGE_NT_SIGNATURE) // "PE\0\0"
225 return error(QLibrary::tr("invalid signature")), nullptr;
226 if (ntHeader->FileHeader.Machine != ExpectedMachine)
227 return error(QLibrary::tr("file is for a different processor")), nullptr;
228 if (ntHeader->FileHeader.NumberOfSections == 0)
229 return error(QLibrary::tr("file has no sections")), nullptr;
230
231 WORD requiredCharacteristics =
232 IMAGE_FILE_EXECUTABLE_IMAGE | IMAGE_FILE_DLL;
233 if ((ntHeader->FileHeader.Characteristics & requiredCharacteristics) != requiredCharacteristics)
234 return error(QLibrary::tr("wrong characteristics")), nullptr;
235
236 // the optional header is not optional
237 if (ntHeader->OptionalHeader.Magic != ExpectedOptionalHeaderSignature)
238 return error(QLibrary::tr("file is for a different word size")), nullptr;
239 if (ntHeader->OptionalHeader.SizeOfCode == 0)
240 return error.notplugin(QLibrary::tr("file has no code")), nullptr;
241
242 return ntHeader;
243}
244
245static const IMAGE_SECTION_HEADER *
246findSectionTable(QByteArrayView data, const IMAGE_NT_HEADERS *ntHeader, const ErrorMaker &error)
247{
248 // macro IMAGE_FIRST_SECTION can't overflow due to limited range
249 // of type, but adding to the offset from the DOS header could
250 // overflow on 32-bit
251 static_assert(sizeof(ntHeader->FileHeader.SizeOfOptionalHeader) < sizeof(size_t));
252 static_assert(sizeof(ntHeader->FileHeader.NumberOfSections) < sizeof(size_t));
253
254 size_t off = offsetof(IMAGE_NT_HEADERS, OptionalHeader);
255 off += ntHeader->FileHeader.SizeOfOptionalHeader;
256 if (qAddOverflow<size_t>(off, reinterpret_cast<const char *>(ntHeader) - data.data(), &off))
257 return error.toosmall(), nullptr;
258
259 size_t end = ntHeader->FileHeader.NumberOfSections * sizeof(IMAGE_SECTION_HEADER);
260
261 // validate that the file is big enough for all sections we're
262 // supposed to have
263 if (qAddOverflow(end, off, &end) || end > size_t(data.size()))
264 return error.toosmall(), nullptr;
265
266 peDebug << "contains" << ntHeader->FileHeader.NumberOfSections << "sections at offset" << off;
267 return reinterpret_cast<const IMAGE_SECTION_HEADER *>(data.data() + off);
268}
269
271findStringTable(QByteArrayView data, const IMAGE_NT_HEADERS *ntHeader, const ErrorMaker &error)
272{
273 // first, find the symbol table
274 size_t off = ntHeader->FileHeader.PointerToSymbolTable;
275 if (off == 0)
276 return QByteArrayView();
277
278 // skip the symbol table to find the string table after it
279 constexpr size_t SymbolEntrySize = 18;
280 size_t size = ntHeader->FileHeader.NumberOfSymbols;
281 if (qMulOverflow<SymbolEntrySize>(size, &size)
282 || qAddOverflow(off, size, &off)
283 || qAddOverflow(off, sizeof(DWORD), &off)
284 || off > size_t(data.size()))
285 return error.toosmall(), std::nullopt;
286
287 off -= sizeof(DWORD);
288
289 // we've found the string table, ensure it's big enough
290 size = qFromUnaligned<DWORD>(data.data() + off);
291 if (size_t end; qAddOverflow(off, size, &end) || end > size_t(data.size()))
292 return error.toosmall(), std::nullopt;
293
294 // the conversion to signed is fine because we checked above it wasn't
295 // bigger than data.size()
296 return data.sliced(off, size);
297}
298
299static QLatin1StringView findSectionName(const IMAGE_SECTION_HEADER *section, QByteArrayView stringTable)
300{
301 auto ptr = reinterpret_cast<const char *>(section->Name);
302 qsizetype n = qstrnlen(ptr, sizeof(section->Name));
303 if (ptr[0] == '/' && !stringTable.isEmpty()) {
304 // long section name
305 // Microsoft's link.exe does not use these and will truncate the
306 // section name to fit section->Name. GNU binutils' ld does use long
307 // section names on executable image files by default (can be disabled
308 // using --disable-long-section-names). LLVM's lld does generate a
309 // string table in MinGW mode, but does not use it for our section.
310
311 static_assert(sizeof(section->Name) - 1 < std::numeric_limits<uint>::digits10);
312 bool ok;
313 qsizetype offset = QByteArrayView(ptr + 1, n - 1).toUInt(&ok);
314 if (!ok || offset >= stringTable.size())
315 return {};
316
317 ptr = stringTable.data() + offset;
318 n = qstrnlen(ptr, stringTable.size() - offset);
319 }
320
321 return {ptr, n};
322}
323
324QLibraryScanResult QCoffPeParser::parse(QByteArrayView data, QString *errMsg)
325{
326 ErrorMaker error(errMsg);
327 auto ntHeaders = checkNtHeaders(data, error);
328 if (!ntHeaders)
329 return {};
330
331 auto section = findSectionTable(data, ntHeaders, error);
332 if (!ntHeaders)
333 return {};
334
335 QByteArrayView stringTable;
336 if (auto optional = findStringTable(data, ntHeaders, error))
337 stringTable = *optional;
338 else
339 return {};
340
341 // scan the sections now
342 const auto sectionTableEnd = section + ntHeaders->FileHeader.NumberOfSections;
343 for ( ; section < sectionTableEnd; ++section) {
344 QLatin1StringView sectionName = findSectionName(section, stringTable);
345 peDebug << "section" << sectionName << SectionDebug{section};
346 if (IncludeValidityChecks && sectionName.isEmpty())
347 return error(QLibrary::tr("a section name is empty or extends past the end of the file"));
348
349 size_t offset = section->PointerToRawData;
350 if (size_t end; qAddOverflow<size_t>(offset, section->SizeOfRawData, &end)
351 || end > size_t(data.size()))
352 return error(QLibrary::tr("section contents extend past the end of the file"));
353
354 DWORD type = section->Characteristics
355 & (IMAGE_SCN_CNT_CODE | IMAGE_SCN_CNT_INITIALIZED_DATA
356 | IMAGE_SCN_CNT_UNINITIALIZED_DATA);
357 if (type != IMAGE_SCN_CNT_INITIALIZED_DATA)
358 continue;
359
360 // if we do have a string table, the name may be complete
361 if (sectionName != truncatedSectionName && sectionName != metadataSectionName())
362 continue;
363 peDebug << "found .qtmetadata section";
364
365 size_t size = qMin(section->SizeOfRawData, section->Misc.VirtualSize);
366 if (size < sizeof(QPluginMetaData::MagicHeader))
367 return error(QLibrary::tr(".qtmetadata section is too small"));
368 if (IncludeValidityChecks) {
369 QByteArrayView expectedMagic = QByteArrayView::fromArray(QPluginMetaData::MagicString);
370 QByteArrayView actualMagic = data.sliced(offset, expectedMagic.size());
371 if (expectedMagic != actualMagic)
372 return error(QLibrary::tr(".qtmetadata section has incorrect magic"));
373
374 if (section->Characteristics & IMAGE_SCN_MEM_WRITE)
375 return error(QLibrary::tr(".qtmetadata section is writable"));
376 if (section->Characteristics & IMAGE_SCN_MEM_EXECUTE)
377 return error(QLibrary::tr(".qtmetadata section is executable"));
378 }
379
380 return { qsizetype(offset + sizeof(QPluginMetaData::MagicString)),
381 qsizetype(size - sizeof(QPluginMetaData::MagicString)) };
382 }
383
384 return error.notfound();
385}
386
387QT_END_NAMESPACE
static QT_WARNING_PUSH const WORD ExpectedMachine
static QLatin1StringView findSectionName(const IMAGE_SECTION_HEADER *section, QByteArrayView stringTable)
static constexpr auto metadataSectionName() noexcept
#define peDebug
static constexpr bool IncludeValidityChecks
static std::optional< QByteArrayView > findStringTable(QByteArrayView data, const IMAGE_NT_HEADERS *ntHeader, const ErrorMaker &error)
static constexpr QLatin1StringView truncatedSectionName
static const WORD ExpectedOptionalHeaderSignature
static const IMAGE_SECTION_HEADER * findSectionTable(QByteArrayView data, const IMAGE_NT_HEADERS *ntHeader, const ErrorMaker &error)