|
| 1 | +def protect_pytransform(): |
| 2 | + |
| 3 | + try: |
| 4 | + import pytransform{suffix} as pytransform |
| 5 | + except ImportError: |
| 6 | + from . import pytransform{suffix} as pytransform |
| 7 | + |
| 8 | + def assert_builtin(func): |
| 9 | + type = ''.__class__.__class__ |
| 10 | + builtin_function = type(''.join) |
| 11 | + if type(func) is not builtin_function: |
| 12 | + raise RuntimeError('%s() is not a builtin' % func.__name__) |
| 13 | + |
| 14 | + def check_obfuscated_script(): |
| 15 | + CO_SIZES = 30, 39 |
| 16 | + CO_NAMES = set(['pytransform{suffix}', 'pyarmor', |
| 17 | + '__name__', '__file__']) |
| 18 | + co = pytransform.sys._getframe(1).f_code |
| 19 | + if not ((set(co.co_names) <= CO_NAMES) |
| 20 | + and (len(co.co_code) in CO_SIZES)): |
| 21 | + raise RuntimeError('unexpected obfuscated script') |
| 22 | + |
| 23 | + def check_lib_pytransform(): |
| 24 | + platname = pytransform.sys.platform |
| 25 | + libname = 'pytransform{suffix}.dylib' if platname.startswith('darwin') else \ |
| 26 | + 'pytransform{suffix}.dll' if platname.startswith('win') else \ |
| 27 | + 'pytransform{suffix}.so' |
| 28 | + if getattr(pytransform.sys, 'frozen', False): |
| 29 | + filename = pytransform.os.path.join(pytransform.sys._MEIPASS, libname) |
| 30 | + else: |
| 31 | + filename = pytransform.os.path.join({rpath}, {spath}, libname) |
| 32 | + |
| 33 | + size = pytransform.os.path.getsize(filename) & 0xFFFFFFF0 |
| 34 | + n = size >> 2 |
| 35 | + with open(filename, 'rb') as f: |
| 36 | + buf = f.read(size) |
| 37 | + fmt = 'I' * n |
| 38 | + checksum = sum(pytransform.struct.unpack(fmt, buf)) & 0xFFFFFFFF |
| 39 | + if checksum not in {checksum}: |
| 40 | + raise RuntimeError('unexpected %s' % filename) |
| 41 | + |
| 42 | + try: |
| 43 | + assert_builtin(sum) |
| 44 | + assert_builtin(open) |
| 45 | + assert_builtin(len) |
| 46 | + |
| 47 | + check_obfuscated_script() |
| 48 | + check_lib_pytransform() |
| 49 | + except Exception as e: |
| 50 | + raise RuntimeError("Protection Fault: %s" % e) |
| 51 | + |
| 52 | + |
| 53 | +protect_pytransform() |
0 commit comments