Please fix the Python unpack error... I beg you.

Asked 2 years ago, Updated 2 years ago, 13 views

#-*- coding: utf-8-*-
from winreg import *
from os.path import basename
import re, struct

net = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\AppCompatCache"
reg = ConnectRegistry(None,HKEY_LOCAL_MACHINE)
key = OpenKey(reg, net)

a,b,c = EnumValue(key,0)
bin_size = len(b)
print(bin_size)
binary = b

n = 0
header_size = binary[0]
while n < bin_size:
    bin = binary[n+header_size:]
    signature = bin[0:4].decode()
    unknown = bin[4:8].hex()
    entry_size = struct.unpack('i',bin[8:12])[0]
    path_len = struct.unpack('h',bin[12:14])[0]
    path_str = bin[14:path_len+14].decode('UTF-16')
    time = bin[path_len+14:path_len+14+8]
    data_size = struct.unpack('i',bin[path_len+22:path_len+26])[0]
    #data = bin[path_len+14+12:path_len+14+12+data_size]

    print("\nSignatue : " + signature)
    print("\nEntrySize : ",entry_size)
    print("\nPath Length : ",path_len)
    print("\nPath : " + path_str)
    print("\nTime : " ,time)
    print("\nDataSize : " ,data_size)

    n += path_len+12+14+data_size

When I run the code, I get an error at the end of the result, but I have no idea why I get an error.

python

2022-09-20 19:49

1 Answers

Learn how to use debugger

The reason for the error is bin = binary[n+header_size:] No results after slicing.

It means that I will cut it unconditionally after the data size, but I missed that there may be no more value (only the header) if I proceed until the end.

The simple solution is to put the verification logic as shown below.

while n < bin_size:
    bin = binary[n+header_size:]
    If not bin:break # If there is no bin value, stop
    signature = bin[0:4].decode()


2022-09-20 19:49

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.