강의로 돌아가기
-

Python 입문자입니다. SyntaxError: invalid syntax

Python에 대해서는 아직 기본도 모르는 학생입니다.
현재 강의와는 별개의 질문이지만, 현재 기초부터 공부하면서 해결하기에는 급한일이라 먼저 질문을 드립니다.
VLAB에서 2013년에 코딩한 PE Carver 프로그램의 코드인데, encode('hex')부분에서 오류가 나는데 해결방법이나 공부방향에대해서 조언 부탁드립니다.

  • Python 버전이 올라가면서 encode('hex')로 코딩된 부분을 .hexlify() 으로 바꾸어야만 제대로 프로그램이 동작하는것인지 궁금합니다.

import glob
import struct
import time
import binascii
import os

def Timestamp(epoch=None):
if epoch == None:
localTime = time.localtime()
else:
localTime = time.localtime(epoch)
return '%04d%02d%02d-%02d%02d%02d' % localTime[0:6]
def LogLine(line):
print('%s: %s' % (Timestamp(), line))

def File2Data(filename):
try:
f = open(filename, 'rb')
except:
return None
try:
return f.read()
except MemoryError:
return MemoryError
except:
return None
finally:
f.close()
def Data2File(data, filename):
try:
f = open(filename, 'wb')
except:
return False
try:
f.write(data)
except:
return False
finally:
f.close()
return True

def CheckPEStructure(baseAddress, data, rData, bSize, filename):
rSize = os.path.getsize(rData)
found = False
index = 0

while index != -1:
index = data.find('\x4D\x5A', index)

MZ찾기

if index != -1:
e_lfanew = index + 60
e_lfanew_value = int(binascii.hexlify(data[e_lfanew:e_lfanew+4]), 16)
e_lfanew_value_little = struct.pack(' e_lfanew_value_little = e_lfanew_value_little.encode('hex')
e_lfanew_value_little = int(e_lfanew_value_little, 16)
NT_Header = index + e_lfanew_value_little

NT Header 위치 확인

verifyOptional_Header = binascii.hexlify(data[NT_Header+24:NT_Header+26])
if '50450000' == binascii.hexlify(data[NT_Header:NT_Header+4]) and \
'0b01' == verifyOptional_Header or '0b02' == verifyOptional_Header:

PE 및 Optional_Header 확인

numberOfSections = binascii.hexlify(data[NT_Header+6:NT_Header+7])
if len(numberOfSections) > 0:
numberOfSections_little = int(numberOfSections, 16)
numberOfSections_little = struct.pack(' numberOfSections_little = numberOfSections_little.encode('hex')
numberOfSections_big = int(numberOfSections_little[0:2], 16)

Section 개수 확인

sizeOfOptional_Header = binascii.hexlify(data[NT_Header+20:NT_Header+22])
if len(sizeOfOptional_Header) > 0:
sizeOfOptional_Header_little = int(sizeOfOptional_Header, 16)
sizeOfOptional_Header_little = struct.pack(' sizeOfOptional_Header_little = sizeOfOptional_Header_little.encode('hex')
sizeOfOptional_Header_big = int(sizeOfOptional_Header_little[0:4], 16)

Optional Header 크기 확인

sizeOfPE_Header = binascii.hexlify(data[NT_Header+84:NT_Header+88])
if len(sizeOfPE_Header) > 0:
sizeOfPE_Header_little = int(sizeOfPE_Header, 16)
sizeOfPE_Header_little = struct.pack(' sizeOfPE_Header_little = sizeOfPE_Header_little.encode('hex')
sizeOfPE_Header_big = int(sizeOfPE_Header_little, 16)

PE Header 크기 확인

if len(sizeOfOptional_Header) > 0:
count = numberOfSections_big
defaultSize = 40

Section Default 크기는 0x28

totalSizeOfSection = 0
startOfSection_Header = NT_Header + 24 + sizeOfOptional_Header_big
startOfSection_HeaderOffset = startOfSection_Header

Section Header 시작 위치 찾기

sizeOfSection_header = 40 * numberOfSections_big
endOfSection_Header = startOfSection_Header + sizeOfSection_header
while count > 0:
sizeOfSection = startOfSection_Header + 16
sizeOfSection_little = int(binascii.hexlify(data[sizeOfSection:sizeOfSection+4]), 16)
sizeOfSection_little = struct.pack(' sizeOfSection_little = sizeOfSection_little.encode('hex')
sizeOfSection_big = int(sizeOfSection_little, 16)

print sizeOfSection is + str(sizeOfSection_big)

startOfSection_Header = startOfSection_Header + defaultSize
totalSizeOfSection = totalSizeOfSection + sizeOfSection_big
count = count - 1
totalLength = sizeOfPE_Header_big + totalSizeOfSection
filenameExists = os.path.exists(filename)

if filenameExists == False:
os.mkdir(filename)
running = 1
elif filenameExists == True and running == 1:
running = 1
else:
print Directory exists
return True
resultDir = str(os.path.abspath(filename)) + \\ + str(index)
print resultDir
f = open(resultDir, 'wb')
f.write(data[index:index+totalLength])

검증이 끝난 데이터를 파일로 생성

print MZ Offset + str(index)
print MZ Hex Value + binascii.hexlify(data[index:index+2])
print NT_Header Offset + str(NT_Header)
print NT_Header Hex Value + binascii.hexlify(data[NT_Header:NT_Header+4])
print Number Of Sections + str(numberOfSections_big)
print Size Of Optional_Header + str(sizeOfOptional_Header_big)
print Verify Optional_Header + verifyOptional_Header
print Size Of PE_Header + str(sizeOfPE_Header_big)
print Size Of Section + str(sizeOfSection_header)
print Start of Section + str(startOfSection_HeaderOffset)
print End of Section + str(endOfSection_Header)
print Total Size Of Section + str(totalSizeOfSection)
print Total Length + str(totalLength) + '\n\n'
index = index + int(bSize)
index = index + int(bSize)
return True

def ExtractPEFromFile(rawDataName, blockSize, folderName, filename):
LogLine('Start')
LogLine('Reading file %s' % rawDataName)
rawData = File2Data(rawDataName)

print rawData

if rawData == None:
LogLine('Error reading file')
if rawData == MemoryError:
LogLine('File is too large to fit in memory')
else:
LogLine('Searching for PE Format\n')
CheckPEStructure(0, rawData, rawDataName, blockSize, filename)
LogLine('Done')
return True

def Main():
Parser = optparse.OptionParser(usage='usage: python PE_Carver.py -i input_dummy -b block_size -o output_folder')
Parser.add_option('-i', '--input', dest='input', default=False, help='input dummy')
Parser.add_option('-b', '--bsize', dest='bsize', default=False, help='Block Size')
Parser.add_option('-o', '--output', dest='output', default=False, help='The Directory included Carved Files')
(options, args) = Parser.parse_args()
if options.input == False or options.bsize == False or options.output == False:
print('')
print(' python PE_Carver.py --help\n\n')
Parser.error(incorrect number of arguments\n\n)
return
else:
a = []
rData = options.input
bSize = options.bsize
folder = options.output

filenames = sum(map(glob.glob, filenames), [])

ExtractPEFromFile(rData, bSize, folder, options.output)
if name == 'main':
Main()

1 개의 답변
프로그래머스

이러한 질문은 프로그래머스 강의가 아니라 Q&A 전문 사이트인 해시코드를 이용해주세요.

답변 쓰기
이 입력폼은 마크다운 문법을 지원합니다. 마크다운 가이드 를 참고하세요.