Showing posts with label binascii. Show all posts
Showing posts with label binascii. Show all posts

Tuesday, March 10, 2020

Convert String to Shell Code Hex in Python

if you want
  //bin/sh
to become hex you can use in assembly for shell code

>>> for word in (re.findall(".{8}", binascii.hexlify("//bin/sh".encode()).decode())):
...  byte = re.findall(".{2}", word)
...  cmd = ""
...  for index in range(len(byte)-1,-1,-1):
...   cmd = cmd + byte[index]
...  print("push 0x%s" % cmd)
...

push 0x69622f2f
push 0x68732f6e


side notes
   binascii.hexlify converts string to binary
   re.findall(".{8}", finds the words
   re.findall(".{2}" , finds the bytes
   range(... ,... , -1) loops through the bytes in each word backwards (endianess)
   cmd = cmd + ...  rebuilds the hex in the correct order


Decode ShellCode String in Python

if you see this

push 0x68732f2f
push 0x6e69622f

it may be a string
you can use python 3 to decode and see

import binascii
>>> binascii.unhexlify("68732f2f").decode()[::-1]
'//sh'
>>> binascii.unhexlify("6e69622f").decode()[::-1]
'/bin'

yep! shellcode

//sh/bin



side note:
  binascii.hexlify was used to convert the hex to a binary

  decode() was used to convert the binary to a string

  [::-1] was used to reverse the string's characters