본문 바로가기

study

리눅스 + Python 도구 활용 (정적 분석)

1) 파일 유형 식별

 

사용법 : file <filename>

PE32 : 32비트 실행 파일

PE32+ : 64비트 실행 파일 

 

 

import magic
m = magic.open(magic.MAGIC_NONE)
m.load()
ftype = m.file(r'sample32.exe')
print(ftype)

 

파이썬으로 magic 모듈을 이용한 파일 유형 식별

 

2) 파일 해시 계산

 

 

사용법 : md5sum <filename> , sha256sum <filename> , sha1sum <filename> 

* 와일드카드로 전체 스캔 가능

 

 

 

import hashlib
content = open(r"sample32.exe","rb").read()
print(hashlib.md5(content).hexdigest())
print(hashlib.sha256(content).hexdigest())
print(hashlib.sha1(content).hexdigest())

 

파이썬으로 hashlib 모듈을 이용한 파일 해시 추출

 

3) 파일 문자열 추출

 

 

사용법 : strings <option> <filename>

최소 4문자 이상인 ASCII 문자열을 추출한다.

 

strings -a :  전체 파일에서 문자열 추출

strings -el : 유니코드 문자열 추출

 

 

 

사용법 : floss <filename>

난독화된 문자열을 자동으로 식별하고 추출하는 도구

 

 

 

4) 퍼지 해시 (파일 유사도 비교)

 

사용법 : ssdeep [-m file] [-k file] [-dpgvrsblcxa] [-t val] [-h|-V] [FILES]

 

퍼지 해싱 도구, 파일 유사도를 비교하는 데 사용됨 ,

동일한 악성코드군 또는 동일한 공격자 그룹에 속하는 샘플을 식별하는데 도움 됨

-p (상세 일치 모드) , -r (재귀 모드)

 

-m - FILES를 파일의 알려진 해시와 일치시킵니다.
-k - FILES의 서명을 파일의 서명과 일치시킵니다.
-d - 디렉터리 모드, 디렉터리의 모든 파일을 비교합니다.
-p - 일반 일치 모드. -d와 유사하지만 모든 일치 항목을 포함합니다.
-g - 일치 항목을 클러스터링 합니다.
-v - 자세한 모드. 처리 중인 파일 이름을 표시합니다.
-r - 재귀 모드
-s - 자동 모드. 모든 오류는 표시되지 않습니다.
-b - 파일의 이름만 사용하고 모든 경로 정보는 생략합니다.
-l - 파일 이름에 상대 경로를 사용합니다.
-c - CSV 형식으로 출력을 출력합니다.
-x - FILES를 서명 파일로 비교합니다.
-a - 점수에 관계없이 모든 일치 항목을 표시합니다.
-t - 지정된 임계값을 초과하는 일치 항목만 표시합니다.
-h - 이 도움말 메시지를 표시합니다.
-V - 버전 번호를 표시하고 종료합니다.

 

 

-r 옵션으로 샘플을 포함된 하위 디렉터리에서 ssdeep 실행 가능

 

 

응용하여 새 파일과 이전 분석한 샘플의 해시를 비교할 수 있음

 

 

import ssdeep
hash1 = ssdeep.hash_from_file('sample32.exe')
print (hash1)
hash2 = ssdeep.hash_from_file('MessageBox32.exe')
ssdeep.compare(hash1,hash2)

 

파이썬으로 ssdeep 모듈을 이용한 유사성 비교

 

import pefile
pe = pefile.PE("sample32.exe")
print (pe.get_imphash())

 

파이썬으로 pefile 모듈을 이용한 imphash 추출

imphash : (라이브러리/임포트 함수(API 명) 특유의 순서를 바탕으로 해시 값을 계산

 

 

import pefile
pe = pefile.PE("sample32.exe")
for section in pe.sections:
	print ("%s\t%s" % (section.Name, section.get_hash_md5()))

 

파이썬으로 pefile 모듈을 이용한 sectionhash 추출

 

 

5) 바이러스 토탈 조회

import requests
import sys

API_KEY = "<API_KEY>"

def check_virustotal(file_hash):
    url = f"https://www.virustotal.com/api/v3/files/{file_hash}"
    headers = {
        "accept": "application/json",
        "x-apikey": API_KEY
    }

    response = requests.get(url, headers=headers)

    # Sample not found
    if response.status_code == 404:
        print("[!] The sample does not exist on VirusTotal.")
        return

    data = response.json()

    try:
        stats = data["data"]["attributes"]["last_analysis_stats"]
        results = data["data"]["attributes"]["last_analysis_results"]

        print("\n===== Detection Summary =====")
        print(f"Malicious: {stats['malicious']}")
        print(f"Suspicious: {stats['suspicious']}")
        print(f"Undetected: {stats['undetected']}")
        print("=============================\n")

        print("===== Engine Detection Details =====")
        for engine, result in results.items():
            category = result.get("category", "unknown")
            if category != "undetected":
                print(f"{engine}: {category} ({result.get('result', 'N/A')})")
    except KeyError:
        print("[!] No analysis data is available.")


if __name__ == "__main__":
    if len(sys.argv) != 2:
        print(f"usage: python {sys.argv[0]} <file_hash>")
        sys.exit(1)

    file_hash = sys.argv[1]
    check_virustotal(file_hash)