Last active
October 28, 2016 18:04
-
-
Save damieng/8c69c6e09774e17d6b657e0f770a6a0d to your computer and use it in GitHub Desktop.
Identify 64-bit and 32-bit PE binaries in a path
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const fs = require('fs') | |
const path = require('path') | |
const process = require('process') | |
var rootPath | |
if (process.argv.length > 2) { | |
rootPath = process.argv[2] | |
} else { | |
rootPath = '.' | |
} | |
scanDir(rootPath) | |
function scanDir (p) { | |
if (p.endsWith('.git')) return | |
const files = fs.readdirSync(p) | |
for (var i = 0; i < files.length; i++) { | |
const filePath = path.join(p, files[i]) | |
const stat = fs.lstatSync(filePath) | |
if (stat) { | |
if (stat.isDirectory()) scanDir(filePath) | |
if (stat.isFile()) checkFile(filePath) | |
} | |
} | |
} | |
function checkFile (fileName) { | |
const fd = fs.openSync(fileName, "r") | |
const buffer = new Buffer(4096) | |
const bytesRead = fs.readSync(fd, buffer, 0, buffer.length, null) | |
fs.closeSync(fd) | |
checkBuffer (fileName, bytesRead, buffer) | |
} | |
function checkBuffer (fileName, bytesRead, buffer) { | |
if (bytesRead < 2 || buffer[0] != 0x4D || buffer[1] != 0x5A) return | |
if (bytesRead > 0x3C + 4) { | |
const peOffset = buffer.readUInt32LE(0x3C) | |
if (peOffset > bytesRead || buffer[peOffset] != 0x50 || buffer[peOffset + 1] != 0x45) return | |
const a1 = buffer[peOffset + 4] | |
const a2 = buffer[peOffset + 5] | |
if (a1 == 0x4C && a2 == 0x01) { | |
console.log(fileName + ' 32-bit') | |
return | |
} | |
if (a1 == 0x64 && a2 == 0x86) { | |
console.log(fileName + ' 64-bit') | |
return | |
} | |
console.log(fileName + ' unknown arch ' + buffer.slice(peOffset + 4, peOffset + 5).toString('hex')) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment