user1778354
user1778354

Reputation: 333

BASH: Convert hex representation inside a string to binary equivalent

I want to check inside a binary file if it matches a binary pattern.

For that, I'm using clamAV signature database

Exploit.HTML.ObjectType:3:*:3c6f626a65637420747970653d222f2f2f2f2f2f2f2f2f2f2f2f

I code this to retrieve the hex signature string

signature=$(echo "$line" |awk -F':' '{ print $4 }')

Moreover I would like to change hex string to binary

tmp=$(echo -n $signature | sed 's/\([0-9A-F]\{2\}\)/\\\\\\x\1/gI' | xargs print)

Finally I would like to check if my file ( *$raw_file_path* ) matches my binary pattern (now in $tmp)

test_var=$(cat $raw_file_path | grep -U -P "$tmp")

I don't why it doesn't work.

If you have any idea.

Thanks.

Upvotes: 0

Views: 1515

Answers (1)

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

How about this?

line=Exploit.HTML.ObjectType:3:*:3c6f626a65637420747970653d222f2f2f2f2f2f2f2f2f2f2f2f
printf $(sed 's/.*://;s/\(..\)/\\x\1/g' <<< "$line")

Which yields:

<object type="////////////

You can put the bin output in a variable thus:

printf -v variable $(sed 's/.*://;s/\(..\)/\\x\1/g' <<< "$line")

Now, please avoid a useless use of cat!

grep -U "$variable" "$raw_file_path"

is enough. If you want to test the result of grep (and ask grep to be quiet):

if grep -qU "$variable" "$raw_file_path"; then
    echo "Pattern found"
else
    echo "Pattern not found"
fi

Upvotes: 3

Related Questions