Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods to hex edit binary files via Powershell

Am trying to perform binary hex edit from the command line using only powershell. Have had partial success performing a hex replace with this snip. Problem springs up when 123456 occurs multiple times and the replacement was only supposed to occur at a specific location.

NOTE: The snip requires the Convert-ByteArrayToHexString and Convert-HexStringToByteArray functions found here.

http://www.sans.org/windows-security/2010/02/11/powershell-byte-array-hex-convert

$readin = [System.IO.File]::ReadAllBytes("C:\OldFile.exe");
$hx = Convert-ByteArrayToHexString $readin -width 40 -delimiter "";
$hx = $hx -replace "123456","FFFFFF";
$hx = "0x" + $hx;
$writeout = Convert-HexStringToByteArray $hx;
set-content -value $writeout -encoding byte -path "C:\NewFile.exe";

How can we specify an offset position into powershell to replace this sketchy -replace command.

like image 278
Knuckle-Dragger Avatar asked Jan 05 '14 15:01

Knuckle-Dragger


1 Answers

You already have a byte array, so you could simply modify the bytes at any given offset.

$bytes  = [System.IO.File]::ReadAllBytes("C:\OldFile.exe")
$offset = 23

$bytes[$offset]   = 0xFF
$bytes[$offset+1] = 0xFF
$bytes[$offset+2] = 0xFF

[System.IO.File]::WriteAllBytes("C:\NewFile.exe", $bytes)
like image 103
Ansgar Wiechers Avatar answered Nov 16 '22 00:11

Ansgar Wiechers