Improved authenticode.js executable header parsing.

Ylian Saint-Hilaire committed May 30, 2022 at 13:11 UTC 66b1ca95d9e488155e7a60d232351d69fbe4199e
1 file changed +237 -33
authenticode.js
+237 -33
@@ -125,30 +125,64 @@ function createAuthenticodeHandler(path) {
125 obj.filesize = obj.stats.size;
126 if (obj.filesize < 64) { obj.close(); return false; } // File too short.
127
128 - // Read the PE header size
128 + // Read the PE header pointer
129 var buf = readFileSlice(60, 4);
130 - obj.header.header_size = buf.readUInt32LE(0);
130 + obj.header.PeHeaderLocation = buf.readUInt32LE(0); // The DOS header is 64 bytes long, the last 4 bytes are a pointer to the PE header.
131 + obj.header.PeOptionalHeaderLocation = obj.header.PeHeaderLocation + 24; // The PE optional header is located just after the PE header which is 24 bytes long.
132
133 // Check file size and PE header
133 - if (obj.filesize < (160 + obj.header.header_size)) { obj.close(); return false; } // Invalid SizeOfHeaders.
134 - if (readFileSlice(obj.header.header_size, 4).toString('hex') != '50450000') { obj.close(); return false; } // Invalid PE File.
134 + if (obj.filesize < (160 + obj.header.PeHeaderLocation)) { obj.close(); return false; } // Invalid SizeOfHeaders.
135 + if (readFileSlice(obj.header.PeHeaderLocation, 4).toString('hex') != '50450000') { obj.close(); return false; } // Invalid PE header, must start with "PE" (HEX: 50 45 00 00).
136 +
137 + // Read the size of the optional header
138 + obj.header.PeOptionalHeaderSize = readFileSlice(obj.header.PeHeaderLocation + 20, 2).readUInt16LE(0);
139 +
140 + // The section headers are located after the optional PE header
141 + obj.header.SectionHeadersPtr = obj.header.PeOptionalHeaderLocation + obj.header.PeOptionalHeaderSize;
142
143 // Check header magic data
137 - var magic = readFileSlice(obj.header.header_size + 24, 2).readUInt16LE(0);
144 + var magic = readFileSlice(obj.header.PeOptionalHeaderLocation, 2).readUInt16LE(0);
145 switch (magic) {
139 - case 0x20b: obj.header.pe32plus = 1; break;
140 - case 0x10b: obj.header.pe32plus = 0; break;
146 + case 0x020B: obj.header.pe32plus = 1; break;
147 + case 0x010B: obj.header.pe32plus = 0; break;
148 default: { obj.close(); return false; } // Invalid Magic in PE
149 }
150
144 - // Read PE header information
145 - obj.header.pe_checksum = readFileSlice(obj.header.header_size + 88, 4).readUInt32LE(0);
146 - obj.header.numRVA = readFileSlice(obj.header.header_size + 116 + (obj.header.pe32plus * 16), 4).readUInt32LE(0);
147 - buf = readFileSlice(obj.header.header_size + 152 + (obj.header.pe32plus * 16), 8);
151 + // Read optional PE header information
152 + obj.header.pe_checksum = readFileSlice(obj.header.PeOptionalHeaderLocation + 64, 4).readUInt32LE(0);
153 + obj.header.numRVA = readFileSlice(obj.header.PeOptionalHeaderLocation + 92 + (obj.header.pe32plus * 16), 4).readUInt32LE(0);
154 + buf = readFileSlice(obj.header.PeOptionalHeaderLocation + 128 + (obj.header.pe32plus * 16), 8);
155 obj.header.sigpos = buf.readUInt32LE(0);
156 obj.header.siglen = buf.readUInt32LE(4);
157 obj.header.signed = ((obj.header.sigpos != 0) && (obj.header.siglen != 0));
158
159 + // Read the sections
160 + obj.header.sections = {};
161 + for (var i = 0; i < 16; i++) {
162 + var section = {};
163 + buf = readFileSlice(obj.header.SectionHeadersPtr + (i * 40), 40);
164 + if (buf[0] != 46) break; // Name of the section must start with a dot. If not, we are done reading sections.
165 + var sectionName = buf.slice(0, 8).toString().trim('\0');
166 + var j = sectionName.indexOf('\0');
167 + if (j >= 0) { sectionName = sectionName.substring(0, j); } // Trim any trailing zeroes
168 + section.virtualSize = buf.readUInt32LE(8);
169 + section.virtualAddr = buf.readUInt32LE(12);
170 + section.rawSize = buf.readUInt32LE(16);
171 + section.rawAddr = buf.readUInt32LE(20);
172 + section.relocAddr = buf.readUInt32LE(24);
173 + section.lineNumbers = buf.readUInt32LE(28);
174 + section.relocNumber = buf.readUInt16LE(32);
175 + section.lineNumbersNumber = buf.readUInt16LE(34);
176 + section.characteristics = buf.readUInt32LE(36);
177 + obj.header.sections[sectionName] = section;
178 + }
179 +
180 + // If there is a .rsrc section, read the resource information and locations
181 + if (obj.header.sections['.rsrc'] != null) {
182 + var ptr = obj.header.sections['.rsrc'].rawAddr;
183 + obj.resources = readResourceTable(ptr, 0); // Read all resources recursively
184 + }
185 +
186 if (obj.header.signed) {
187 // Read signature block
188
@@ -164,7 +198,7 @@ function createAuthenticodeHandler(path) {
198
199 // Decode the signature block
200 var pkcs7der = forge.asn1.fromDer(forge.util.createBuffer(pkcs7raw));
167 -
201 +
202 // To work around ForgeJS PKCS#7 limitation, this may break PKCS7 verify if ForjeJS adds support for it in the future
203 // Switch content type from "1.3.6.1.4.1.311.2.1.4" to "1.2.840.113549.1.7.1"
204 pkcs7der.value[1].value[0].value[2].value[0].value = forge.asn1.oidToDer(forge.pki.oids.data).data;
@@ -173,14 +207,12 @@ function createAuthenticodeHandler(path) {
207 var pkcs7 = p7.messageFromAsn1(pkcs7der);
208 var pkcs7content = pkcs7.rawCapture.content.value[0];
209
176 - /*
210 // Verify a PKCS#7 signature
211 // Verify is not currently supported in node-forge, but if implemented in the future, this code could work.
179 - var caStore = forge.pki.createCaStore();
180 - for (var i in obj.certificates) { caStore.addCertificate(obj.certificates[i]); }
212 + //var caStore = forge.pki.createCaStore();
213 + //for (var i in obj.certificates) { caStore.addCertificate(obj.certificates[i]); }
214 // Return is true if all signatures are valid and chain up to a provided CA
182 - if (!pkcs7.verify(caStore)) { throw ('Executable file has an invalid signature.'); }
183 - */
215 + //if (!pkcs7.verify(caStore)) { throw ('Executable file has an invalid signature.'); }
216
217 // Get the signing attributes
218 obj.signingAttribs = [];
@@ -219,12 +251,174 @@ function createAuthenticodeHandler(path) {
251 return true;
252 }
253
254 + // Read a resource table.
255 + // ptr: The pointer to the start of the resource section
256 + // offset: The offset start of the resource table to read
257 + function readResourceTable(ptr, offset) {
258 + var buf = readFileSlice(ptr + offset, 16);
259 + var r = {};
260 + r.characteristics = buf.readUInt32LE(0);
261 + r.timeDateStamp = buf.readUInt32LE(4);
262 + r.majorVersion = buf.readUInt16LE(8);
263 + r.minorVersion = buf.readUInt16LE(10);
264 + var numberOfNamedEntries = buf.readUInt16LE(12);
265 + var numberofIdEntries = buf.readUInt16LE(14);
266 + r.entries = [];
267 + var totalResources = numberOfNamedEntries + numberofIdEntries;
268 + for (var i = 0; i < totalResources; i++) {
269 + buf = readFileSlice(ptr + offset + 16 + (i * 8), 8);
270 + var resource = {};
271 + resource.name = buf.readUInt32LE(0);
272 + var offsetToData = buf.readUInt32LE(4);
273 + if ((resource.name & 0x80000000) != 0) { resource.name = readLenPrefixUnicodeString(ptr + (resource.name - 0x80000000)); }
274 + if ((offsetToData & 0x80000000) != 0) { resource.table = readResourceTable(ptr, offsetToData - 0x80000000); } else { resource.item = readResourceItem(ptr, offsetToData); }
275 + r.entries.push(resource);
276 + }
277 + return r;
278 + }
279 +
280 + // Read a resource item
281 + // ptr: The pointer to the start of the resource section
282 + // offset: The offset start of the resource item to read
283 + function readResourceItem(ptr, offset) {
284 + var buf = readFileSlice(ptr + offset, 16), r = {};
285 + r.offsetToData = buf.readUInt32LE(0);
286 + r.size = buf.readUInt32LE(4);
287 + r.codePage = buf.readUInt32LE(8);
288 + r.reserved = buf.readUInt32LE(12);
289 + return r;
290 + }
291 +
292 + // Read a unicode stting that starts with the string length as the first byte.
293 + function readLenPrefixUnicodeString(ptr) {
294 + var nameLen = readFileSlice(ptr, 1)[0];
295 + var buf = readFileSlice(ptr + 1, nameLen * 2), name = '';
296 + for (var i = 0; i < nameLen; i++) { name += String.fromCharCode(buf.readUInt16BE(i * 2)); }
297 + return name;
298 + }
299 +
300 + // Convert a unicode buffer to a string
301 + function unicodeToString(buf) {
302 + var r = '';
303 + for (var i = 0; i < (buf.length / 2) ; i++) { r += String.fromCharCode(buf.readUInt16LE(i * 2)); }
304 + return r;
305 + }
306 +
307 + // Decode the version information from the resource
308 + obj.getVersionInfo = function () {
309 + var r = {}, info = readVersionInfo(getVersionInfoData(), 0);
310 + if (info == null) return null;
311 + const strings = info.stringFile.stringTable.strings;
312 + for (var i in strings) { r[strings[i].key] = strings[i].value; }
313 + return r;
314 + }
315 +
316 + // Return the version info data block
317 + function getVersionInfoData() {
318 + if (obj.resources == null) return null;
319 + var ptr = obj.header.sections['.rsrc'].rawAddr;
320 + for (var i = 0; i < obj.resources.entries.length; i++) {
321 + if (obj.resources.entries[i].name == 16) {
322 + const verInfo = obj.resources.entries[i].table.entries[0].table.entries[0].item;
323 + const actualPtr = (verInfo.offsetToData - obj.header.sections['.rsrc'].virtualAddr) + ptr;
324 + return readFileSlice(actualPtr, verInfo.size);
325 + }
326 + }
327 + return null;
328 + }
329 +
330 + // VS_VERSIONINFO structure: https://docs.microsoft.com/en-us/windows/win32/menurc/vs-versioninfo
331 + function readVersionInfo(buf, ptr) {
332 + const r = {};
333 + if (buf.length < 2) return null;
334 + r.wLength = buf.readUInt16LE(ptr);
335 + if (buf.length < r.wLength) return null;
336 + r.wValueLength = buf.readUInt16LE(ptr + 2);
337 + r.wType = buf.readUInt16LE(ptr + 4);
338 + r.szKey = unicodeToString(buf.slice(ptr + 6, ptr + 36));
339 + if (r.szKey != 'VS_VERSION_INFO') return null;
340 + //console.log('getVersionInfo', r.wLength, r.wValueLength, r.wType, r.szKey.toString());
341 + if (r.wValueLength == 52) { r.fixedFileInfo = readFixedFileInfoStruct(buf, ptr + 40); }
342 + r.stringFile = readStringFileStruct(buf, ptr + 40 + r.wValueLength);
343 + return r;
344 + }
345 +
346 + // VS_FIXEDFILEINFO structure: https://docs.microsoft.com/en-us/windows/win32/api/verrsrc/ns-verrsrc-vs_fixedfileinfo
347 + function readFixedFileInfoStruct(buf, ptr) {
348 + if (buf.length - ptr < 50) return null;
349 + var r = {};
350 + r.dwSignature = buf.readUInt32LE(ptr);
351 + if (r.dwSignature != 0xFEEF04BD) return null;
352 + r.dwStrucVersion = buf.readUInt32LE(ptr + 4);
353 + r.dwFileVersionMS = buf.readUInt32LE(ptr + 8);
354 + r.dwFileVersionLS = buf.readUInt32LE(ptr + 12);
355 + r.dwProductVersionMS = buf.readUInt32LE(ptr + 16);
356 + r.dwProductVersionLS = buf.readUInt32LE(ptr + 20);
357 + r.dwFileFlagsMask = buf.readUInt32LE(ptr + 24);
358 + r.dwFileFlags = buf.readUInt32LE(ptr + 28);
359 + r.dwFileOS = buf.readUInt32LE(ptr + 32);
360 + r.dwFileType = buf.readUInt32LE(ptr + 36);
361 + r.dwFileSubtype = buf.readUInt32LE(ptr + 40);
362 + r.dwFileDateMS = buf.readUInt32LE(ptr + 44);
363 + r.dwFileDateLS = buf.readUInt32LE(ptr + 48);
364 + return r;
365 + }
366 +
367 + // StringFileInfo structure: https://docs.microsoft.com/en-us/windows/win32/menurc/stringfileinfo
368 + function readStringFileStruct(buf, ptr) {
369 + const r = {};
370 + r.wLength = buf.readUInt16LE(ptr);
371 + r.wValueLength = buf.readUInt16LE(ptr + 2);
372 + r.wType = buf.readUInt16LE(ptr + 4);
373 + r.szKey = unicodeToString(buf.slice(ptr + 6, ptr + 34));
374 + if (r.szKey != 'StringFileInfo') return null;
375 + //console.log('readStringFileStruct', r.wLength, r.wValueLength, r.wType, r.szKey.toString());
376 + r.stringTable = readStringTableStruct(buf, ptr + 36 + r.wValueLength);
377 + return r;
378 + }
379 +
380 + // StringTable structure: https://docs.microsoft.com/en-us/windows/win32/menurc/stringtable
381 + function readStringTableStruct(buf, ptr) {
382 + const r = {};
383 + r.wLength = buf.readUInt16LE(ptr);
384 + r.wValueLength = buf.readUInt16LE(ptr + 2);
385 + r.wType = buf.readUInt16LE(ptr + 4); // 1 = Text, 2 = Binary
386 + r.szKey = unicodeToString(buf.slice(ptr + 6, ptr + 6 + 16)); // An 8-digit hexadecimal number stored as a Unicode string.
387 + //console.log('readStringTableStruct', r.wLength, r.wValueLength, r.wType, r.szKey);
388 + r.strings = readStringStructs(buf, ptr + 24 + r.wValueLength, r.wLength - 22);
389 + return r;
390 + }
391 +
392 + // String structure: https://docs.microsoft.com/en-us/windows/win32/menurc/string-str
393 + function readStringStructs(buf, ptr, len) {
394 + var t = [], startPtr = ptr;
395 + while (ptr < (startPtr + len)) {
396 + const r = {};
397 + r.wLength = buf.readUInt16LE(ptr);
398 + if (r.wLength == 0) return t;
399 + r.wValueLength = buf.readUInt16LE(ptr + 2);
400 + r.wType = buf.readUInt16LE(ptr + 4); // 1 = Text, 2 = Binary
401 + var szKey = unicodeToString(buf.slice(ptr + 6, ptr + 6 + (r.wLength - 6))); // String value
402 + var splitStr = szKey.split('\0');
403 + r.key = splitStr[0];
404 + for (var i = 1; i < splitStr.length; i++) { if (splitStr[i] != '') { r.value = splitStr[i]; } }
405 + //console.log('readStringStruct', r.wLength, r.wValueLength, r.wType, r.key, r.value);
406 + t.push(r);
407 + ptr += r.wLength;
408 + ptr = padPointer(ptr);
409 + }
410 + return t;
411 + }
412 +
413 + // Return the next 4 byte aligned number
414 + function padPointer(ptr) { return ptr + (ptr % 4); }
415 +
416 // Hash the file using the selected hashing system
417 obj.getHash = function(algo) {
418 var hash = crypto.createHash(algo);
225 - runHash(hash, 0, obj.header.header_size + 88);
226 - runHash(hash, obj.header.header_size + 88 + 4, obj.header.header_size + 152 + (obj.header.pe32plus * 16));
227 - runHash(hash, obj.header.header_size + 152 + (obj.header.pe32plus * 16) + 8, obj.header.sigpos > 0 ? obj.header.sigpos : obj.filesize);
419 + runHash(hash, 0, obj.header.PeHeaderLocation + 88);
420 + runHash(hash, obj.header.PeHeaderLocation + 88 + 4, obj.header.PeHeaderLocation + 152 + (obj.header.pe32plus * 16));
421 + runHash(hash, obj.header.PeHeaderLocation + 152 + (obj.header.pe32plus * 16) + 8, obj.header.sigpos > 0 ? obj.header.sigpos : obj.filesize);
422 return hash.digest();
423 }
424
@@ -275,13 +469,13 @@ function createAuthenticodeHandler(path) {
469 var p7signature = Buffer.from(forge.pkcs7.messageToPem(p7).split('-----BEGIN PKCS7-----')[1].split('-----END PKCS7-----')[0], 'base64');
470 //console.log('Signature', Buffer.from(p7signature, 'binary').toString('base64'));
471
278 - // Open the outut file
472 + // Open the output file
473 var output = fs.openSync(args.out, 'w');
474 var tmp, written = 0;
475 var executableSize = obj.header.sigpos ? obj.header.sigpos : this.filesize;
476
477 // Compute pre-header length and copy that to the new file
284 - var preHeaderLen = (obj.header.header_size + 152 + (obj.header.pe32plus * 16));
478 + var preHeaderLen = (obj.header.PeHeaderLocation + 152 + (obj.header.pe32plus * 16));
479 var tmp = readFileSlice(written, preHeaderLen);
480 fs.writeSync(output, tmp);
481 written += tmp.length;
@@ -324,7 +518,7 @@ function createAuthenticodeHandler(path) {
518 var written = 0, totalWrite = obj.header.sigpos;
519
520 // Compute pre-header length and copy that to the new file
327 - var preHeaderLen = (obj.header.header_size + 152 + (obj.header.pe32plus * 16));
521 + var preHeaderLen = (obj.header.PeHeaderLocation + 152 + (obj.header.pe32plus * 16));
522 var tmp = readFileSlice(written, preHeaderLen);
523 fs.writeSync(output, tmp);
524 written += tmp.length;
@@ -357,6 +551,7 @@ function start() {
551 console.log(" node authenticode.js [command] [options]");
552 console.log("Commands:");
553 console.log(" info: Show information about an executable.");
554 + console.log(" --exe [file] Required executable to view information.");
555 console.log(" --json Show information in JSON format.");
556 console.log(" sign: Sign an executable.");
557 console.log(" --exe [file] Required executable to sign.");
@@ -403,19 +598,28 @@ function start() {
598 if (command == 'info') { // Get signature information about an executable
599 if (exe == null) { console.log("Missing --exe [filename]"); return; }
600 if (args.json) {
406 - var r = { header: exe.header, filesize: exe.filesize }
407 - if (exe.fileHashAlgo != null) { r.hashMethod = exe.fileHashAlgo; }
408 - if (exe.fileHashSigned != null) { r.hashSigned = exe.fileHashSigned.toString('hex'); }
409 - if (exe.fileHashActual != null) { r.hashActual = exe.fileHashActual.toString('hex'); }
410 - if (exe.signingAttribs && exe.signingAttribs.length > 0) { r.signAttributes = exe.signingAttribs; }
601 + var r = { }, versionInfo = exe.getVersionInfo();
602 + if (versionInfo != null) { r.versionInfo = versionInfo; }
603 + if (exe.fileHashAlgo != null) {
604 + r.signture = {};
605 + if (exe.fileHashAlgo != null) { r.signture.hashMethod = exe.fileHashAlgo; }
606 + if (exe.fileHashSigned != null) { r.signture.hashSigned = exe.fileHashSigned.toString('hex'); }
607 + if (exe.fileHashActual != null) { r.signture.hashActual = exe.fileHashActual.toString('hex'); }
608 + if (exe.signingAttribs && exe.signingAttribs.length > 0) { r.signture.attributes = exe.signingAttribs; }
609 + }
610 console.log(JSON.stringify(r, null, 2));
611 } else {
413 - console.log("Header", exe.header);
414 - if (exe.fileHashAlgo != null) { console.log("Hash Method:", exe.fileHashAlgo); }
415 - if (exe.fileHashSigned != null) { console.log("Signed Hash:", exe.fileHashSigned.toString('hex')); }
416 - if (exe.fileHashActual != null) { console.log("Actual Hash:", exe.fileHashActual.toString('hex')); }
612 + var versionInfo = exe.getVersionInfo();
613 + if (versionInfo != null) { console.log("Version Information:"); for (var i in versionInfo) { console.log(' ' + i + ': \"' + versionInfo[i] + '\"'); } }
614 + console.log("Signature Information:");
615 + if (exe.fileHashAlgo != null) {
616 + console.log(" Hash Method:", exe.fileHashAlgo);
617 + if (exe.fileHashSigned != null) { console.log(" Signed Hash:", exe.fileHashSigned.toString('hex')); }
618 + if (exe.fileHashActual != null) { console.log(" Actual Hash:", exe.fileHashActual.toString('hex')); }
619 + } else {
620 + console.log(" This file is not signed.");
621 + }
622 if (exe.signingAttribs && exe.signingAttribs.length > 0) { console.log("Signature Attributes:"); for (var i in exe.signingAttribs) { console.log(' ' + exe.signingAttribs[i]); } }
418 - console.log("File Length: " + exe.filesize);
623 }
624 }
625 if (command == 'sign') { // Sign an executable