Last active
April 2, 2021 19:34
-
-
Save countingpine/78d198b2f3d7271427d3fa49c787b135 to your computer and use it in GitHub Desktop.
Convert MBR (or any 512-byte binary input) into a script that outputs the data but with editable partition fields
This file contains hidden or 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
#!/bin/bash | |
# wget https://gist.githubusercontent.com/countingpine/78d198b2f3d7271427d3fa49c787b135/raw/mbr2script.sh | |
set -e | |
set -u | |
echo '#!/bin/bash' | |
echo 'set -e' | |
echo 'set -u' | |
# Hexdump 512 bytes from stdin | |
a=( $(xxd -c1 -l 512 "${1--}" | awk '{print "0x" $2}') ) | |
# Raw dump first 446 bytes | |
data="'" | |
for i in {0..445}; do | |
data+=$(printf '\\x%x' "${a[$i]}") | |
done | |
data+="'" | |
echo "printf '%b' $data" | |
# Function to construct partitions in hexdump | |
function part() { | |
set -u | |
local status=$(($1)) | |
local chs1=$(($2)) | |
local type=$(($3)) | |
local chs2=$(($4)) | |
local lba1=$(($5)) | |
local lba2=$(($6)) | |
printf '%b' $( | |
printf '\\x%x' \ | |
$status \ | |
$(($chs1 & 255)) $(($chs1 >> 8 & 255)) $(($chs1 >> 16 & 255)) \ | |
$type \ | |
$(($chs2 & 255)) $(($chs2 >> 8 & 255)) $(($chs2 >> 16 & 255)) \ | |
$(($lba1 & 255)) $(($lba1 >> 8 & 255)) $(($lba1 >> 16 & 255)) $(($lba1 >> 24 & 255)) \ | |
$(($lba2 & 255)) $(($lba2 >> 8 & 255)) $(($lba2 >> 16 & 255)) $(($lba2 >> 24 & 255)) | |
); | |
} | |
# Copy above function into script | |
awk '/^function part/ {fn=1}; fn; /^[}]$/ {fn=0}' "$0" | |
# Dump partition fields | |
echo "# status chs1 type chs2 start length" | |
for i in {0..3}; do | |
for j in {0..15}; do | |
off=$((446+$i*16+$j)) | |
b[$j]=${a[$off]} | |
done | |
status=${b[0]} | |
chs1=$((${b[1]} | ${b[2]} << 8 | ${b[3]} << 16)) | |
type=${b[4]} | |
chs2=$((${b[5]} | ${b[6]} << 8 | ${b[7]} << 16)) | |
lba1=$((${b[ 8]} | ${b[ 9]} << 8 | ${b[10]} << 16 | ${b[11]} << 24)) | |
lba2=$((${b[12]} | ${b[13]} << 8 | ${b[14]} << 16 | ${b[15]} << 24)) | |
printf "part 0x%02x 0x%06x 0x%02x 0x%06x %d %d\n" $status $chs1 $type $chs2 $lba1 $lba2 | |
done | |
# Dump last two bytes (should be 55 AA) | |
data='$'"'" | |
for i in {510..511}; do | |
data+=$(printf '\\x%x' "${a[$i]}") | |
done | |
data+="'" | |
echo "echo -n $data" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment