pyarmor icon indicating copy to clipboard operation
pyarmor copied to clipboard

[BUG] Dynamic import of obfuscated file fails

Open emileindik opened this issue 3 years ago • 1 comments

Dynamically importing an obfuscated file using importlib fails to find global method on obfuscated file.

# obfuscated_file.py
def run_task():
    print('foo')
# index.py
spec = importlib.util.spec_from_file_location('module_name, '/my/obfuscated_file.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
module.run_task()

Returns

AttributeError: module 'module_name' has no attribute 'run_task'

Both solutions from here worked for me.

I ended up using this solution because it was easier to implement.

Is this something that will be fixed?

emileindik avatar Sep 20 '22 21:09 emileindik

I'll check it first.

jondy avatar Sep 21 '22 07:09 jondy

The problem is that when spec.loader.exec_module(module) is called, the obfuscated script could not get the instance of the module passed by spec.loader.exec_module.

I have not find how to fix it directly, but there are 2 extra solutions

  1. Save module instance to sys.modules before exec_module
# index.py
import importlib.util
import sys
spec = importlib.util.spec_from_file_location(module_name, '/my/obfuscated_file.py')
module = importlib.util.module_from_spec(spec)

sys.modules[module_name] = module

spec.loader.exec_module(module)
module.run_task()
  1. Update module after exec_module
# index.py
import importlib.util
import sys
spec = importlib.util.spec_from_file_location(module_name, '/my/obfuscated_file.py')
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)

module = sys.modules[module_name]

module.run_task()

jondy avatar Sep 28 '22 10:09 jondy