qiling icon indicating copy to clipboard operation
qiling copied to clipboard

[loader/elf.py] Qiling'env parameter can not contain byte strings

Open comewel opened this issue 5 years ago • 2 comments

Describe the bug In qiling/loader/elf.py if Qiling's env parameter contains byte strings the following error is raised:

Traceback (most recent call last):
  File ".../Downloads/test.py", line 4, in <module>
    ql = Qiling(
  File ".../lib/python3.9/site-packages/qiling/core.py", line 211, in __init__
    self.loader.run()
  File ".../lib/python3.9/site-packages/qiling/loader/elf.py", line 124, in run
    self.load_with_ld(stack_address + stack_size, argv=self.argv, env=self.env)
  File ".../ib/python3.9/site-packages/qiling/loader/elf.py", line 330, in load_with_ld
    env_addr, new_stack = self.copy_str(new_stack, [key + '=' + value for key, value in env.items()])
  File ".../lib/python3.9/site-packages/qiling/loader/elf.py", line 330, in <listcomp>
    env_addr, new_stack = self.copy_str(new_stack, [key + '=' + value for key, value in env.items()])
TypeError: can't concat str to bytes

I link here the line that causes the error for ease.

Sample Code

from qiling import *

env_dict = {b"test": b"test"}
ql = Qiling(
    ["qiling/examples/rootfs/x86_linux/bin/x86_hello"],
    "qiling/examples/rootfs/x86_linux",
    env=env_dict,
)

ql.run()

Expected behavior The loader should manage the case in which the Qiling's env variable contains byte strings. I think it could be easily achieved by making the concatenation with the = dependent on the type of the env entry.

Additional context A quick (and dirty) fix would be substituting the if block here :

...
# Set env
if len(env) != 0:
    env_addr, new_stack = self.copy_str(new_stack, [key + '=' + value for key, value in env.items()])
    elf_table += b''.join([self.ql.pack(_) for _ in env_addr])
...

with something like this:

...
# Set env
# The check with all is performed to guarantee that each key and value have the same type
if len(env) != 0 and all([type(key) == type(value) for key, value in env.items()]):
    list_of_env = []
    for key, value in env.items():
        if isinstance(key, bytes):
            list_of_env.append(key + b'=' + value)
        else:
            list_of_env.append(key + '=' + value)

    env_addr, new_stack = self.copy_str(new_stack, list_of_env)
    elf_table += b''.join([self.ql.pack(_) for _ in env_addr])
...

Thanks for your awesome work 😄

comewel avatar Jan 05 '21 18:01 comewel

Hi,

Thanks for the comments and PR appreciated!

xwings avatar Jan 06 '21 12:01 xwings

this issue should be fixed, can we close this? :)

TheZ3ro avatar Dec 27 '21 14:12 TheZ3ro

Closed.

xwings avatar Oct 06 '22 03:10 xwings