메뉴
BL
MarkTechPost 41일 전

Magika와 OpenAI를 활용한 파일 탐지 및 보안 분석 파이프라인 구축

IMP
7/10
핵심 요약

이 튜토리얼에서는 구글의 딥러닝 기반 파일 타입 탐지 도구인 Magika와 OpenAI의 언어 모델을 결합하여 실용적인 파일 보안 분석 파이프라인을 구축하는 방법을 다룹니다. 파일 확장자가 아닌 원시 바이트(Raw bytes)를 기반으로 파일의 진짜 형식을 식별하고, GPT 모델을 통해 기술적인 분석 결과를 이해하기 쉬운 보안 인사이트와 요약으로 제공합니다. 이를 통해 대량의 파일 스캔, 변조된 파일 탐지, 업로드 리스크 스코어링 등 실무적인 보안 검역 시스템을 구축할 수 있습니다.

번역된 본문

인공지능(AI) 인프라 기술, AI 쇼츠, 애플리케이션, 에디터 추천, 머신러닝, 보안, 소프트웨어 엔지니어링, 스태프 튜토리얼

이 튜토리얼에서는 Magika의 딥러닝 기반 파일 타입 탐지 기능과 OpenAI의 언어 지능을 결합하여 실용적이고 통찰력 있는 분석 파이프라인을 구축하는 워크플로우를 만듭니다.

먼저 필요한 라이브러리를 설정하고 OpenAI API에 안전하게 연결한 뒤, 파일 이름이나 확장자에 의존하지 않고 원시 바이트(raw bytes)에서 직접 파일을 분류하도록 Magika를 초기화합니다.

튜토리얼을 진행하면서 일괄 스캔(batch scanning), 신뢰도 모드(confidence modes), 위장 파일(spoofed-file) 탐지, 포렌식 스타일 분석, 업로드 파이프라인 위험도 평가(risk scoring), 구조화된 JSON 보고서 생성 등을 살펴봅니다.

각 단계에서 GPT를 사용하여 기술적인 스캔 결과를 명확한 설명, 보안 통찰력, 경영진 수준의 요약으로 번역함으로써 저수준 바이트 탐지를 의미 있는 실제 해석과 연결할 수 있습니다.

코드 복사 완료 다른 브라우저를 사용하세요!

pip install magika openai -q 코드 실행

os, io, json, zipfile, textwrap, hashlib, tempfile, getpass 모듈을 가져오고, pathlib에서 Path를, collections에서 Counter를 가져옵니다. magika에서 Magika 모듈과 MagikaResult, PredictionMode 타입을 가져오며, openai에서 OpenAI를 가져옵니다.

"🔑 OpenAI API 키를 입력하세요 (입력값은 숨겨집니다):"를 출력합니다. getpass를 통해 OpenAI API 키를 입력받아 client 객체를 생성합니다.

client.models.list()를 시도해보고, 성공하면 "✅ OpenAI 연결 성공"을 출력합니다. 실패할 경우 예외를 처리하여 "❌ OpenAI 연결 실패"와 함께 시스템을 종료합니다.

Magika 객체를 생성하여 m에 할당하고, 모듈 버전, 모델 이름, 지원하는 출력 콘텐츠 타입의 개수 등을 출력하며 로드를 성공적으로 완료합니다.

ask_gpt라는 함수를 정의합니다. 이 함수는 시스템 프롬프트와 사용자 프롬프트를 받아 GPT-4o 모델을 사용해 응답을 생성하고, 그 결과의 텍스트를 반환합니다.

"=" * 60 "섹션 1 — 핵심 API 및 GPT 평이한 언어 설명" "=" * 60

Python, JavaScript, CSV, JSON, Shell, PDF magic, ZIP magic 등 다양한 형식의 샘플 바이트 데이터를 딕셔너리로 정의합니다.

라벨, MIME 타입, 점수(Score)를 출력하는 헤더를 표시합니다.

각 샘플 데이터를 순회하며 m.identify_bytes를 통해 원시 바이트를 식별하고, 그 결과 라벨을 magika_labels 리스트에 추가합니다. 식별된 라벨, MIME 타입, 점수를 출력합니다.

ask_gpt 함수를 사용하여 Magika가 식별한 파일 타입 목록을 바탕으로, 딥러닝 모델이 어떻게 원시 바이트만으로 파일 타입을 탐지하는지, 그리고 파일 확장자에 의존하는 것보다 왜 더 나은지를 간결한 머신러닝 엔지니어의 시점에서 설명을 요청하고 그 결과를 출력합니다.

"=" * 60 "섹션 2 — 일괄 식별 및 GPT 요약" "=" * 60

임시 디렉토리를 생성하고, Python, CSS, JSON, Shell, HTML, YAML, SQL, Markdown 등 다양한 확장자를 가진 파일 스펙들을 정의합니다. 경로를 저장할 빈 리스트(paths)를 초기화합니다.

원문 보기
원문 보기 (영어)
Artificial Intelligence AI Infrastructure Technology AI Shorts Applications Editors Pick Machine Learning Security Software Engineering Staff Tutorials In this tutorial, we build a workflow that combines Magika’s deep-learning-based file type detection with OpenAI’s language intelligence to create a practical and insightful analysis pipeline. We begin by setting up the required libraries, securely connecting to the OpenAI API, and initializing Magika to classify files directly from raw bytes rather than relying on filenames or extensions. As we move through the tutorial, we explore batch scanning, confidence modes, spoofed-file detection, forensic-style analysis, upload-pipeline risk scoring, and structured JSON reporting. At each stage, we use GPT to translate technical scan outputs into clear explanations, security insights, and executive-level summaries, allowing us to connect low-level byte detection with meaningful real-world interpretation. Copy Code Copied Use a different Browser !pip install magika openai -q import os, io, json, zipfile, textwrap, hashlib, tempfile, getpass from pathlib import Path from collections import Counter from magika import Magika from magika.types import MagikaResult, PredictionMode from openai import OpenAI print("🔑 Enter your OpenAI API key (input is hidden):") api_key = getpass.getpass("OpenAI API Key: ") client = OpenAI(api_key=api_key) try: client.models.list() print("✅ OpenAI connected successfully\n") except Exception as e: raise SystemExit(f"❌ OpenAI connection failed: {e}") m = Magika() print("✅ Magika loaded successfully\n") print(f" module version : {m.get_module_version()}") print(f" model name : {m.get_model_name()}") print(f" output types : {len(m.get_output_content_types())} supported labels\n") def ask_gpt(system: str, user: str, model: str = "gpt-4o", max_tokens: int = 600) -> str: resp = client.chat.completions.create( model=model, max_tokens=max_tokens, messages=[ {"role": "system", "content": system}, {"role": "user", "content": user}, ], ) return resp.choices[0].message.content.strip() print("=" * 60) print("SECTION 1 — Core API + GPT Plain-Language Explanation") print("=" * 60) samples = { "Python": b'import os\ndef greet(name):\n print(f"Hello, {name}")\n', "JavaScript": b'const fetch = require("node-fetch");\nasync function getData() { return await fetch("/api"); }', "CSV": b'name,age,city\nAlice,30,NYC\nBob,25,LA\n', "JSON": b'{"name": "Alice", "scores": [10, 20, 30], "active": true}', "Shell": b'#!/bin/bash\necho "Hello"\nfor i in $(seq 1 5); do echo $i; done', "PDF magic": b'%PDF-1.4\n1 0 obj\n<< /Type /Catalog >>\nendobj\n', "ZIP magic": bytes([0x50, 0x4B, 0x03, 0x04]) + bytes(26), } print(f"\n{'Label':<12} {'MIME Type':<30} {'Score':>6}") print("-" * 52) magika_labels = [] for name, raw in samples.items(): res = m.identify_bytes(raw) magika_labels.append(res.output.label) print(f"{res.output.label:<12} {res.output.mime_type:<30} {res.score:>5.1%}") explanation = ask_gpt( system="You are a concise ML engineer. Explain in 4–5 sentences.", user=( f"Magika is Google's AI file-type detector. It just identified these types from raw bytes: " f"{magika_labels}. Explain how a deep-learning model detects file types from " "just bytes, and why this beats relying on file extensions." ), max_tokens=250, ) print(f"\n💬 GPT on how Magika works:\n{textwrap.fill(explanation, 72)}\n") print("=" * 60) print("SECTION 2 — Batch Identification + GPT Summary") print("=" * 60) tmp_dir = Path(tempfile.mkdtemp()) file_specs = { "code.py": b"import sys\nprint(sys.version)\n", "style.css": b"body { font-family: Arial; margin: 0; }\n", "data.json": b'[{"id": 1, "val": "foo"}, {"id": 2, "val": "bar"}]', "script.sh": b"#!/bin/sh\necho Hello World\n", "doc.html": b"<html><body><p>Hello</p></body></html>", "config.yaml": b"server:\n host: localhost\n port: 8080\n", "query.sql": b"CREATE TABLE t (id INT PRIMARY KEY, name TEXT);\n", "notes.md": b"# Heading\n\n- item one\n- item two\n", } paths = [] for fname, content in file_specs.items(): p = tmp_dir / fname p.write_bytes(content) paths.append(p) results = m.identify_paths(paths) batch_summary = [ {"file": p.name, "label": r.output.label, "group": r.output.group, "score": f"{r.score:.1%}"} for p, r in zip(paths, results) ] print(f"\n{'File':<18} {'Label':<14} {'Group':<12} {'Score':>6}") print("-" * 54) for row in batch_summary: print(f"{row['file']:<18} {row['label']:<14} {row['group']:<12} {row['score']:>6}") gpt_summary = ask_gpt( system="You are a DevSecOps expert. Be concise and practical.", user=( f"A file upload scanner detected these file types in a batch: " f"{json.dumps(batch_summary)}. " "In 3–4 sentences, summarise what kind of project this looks like " "and flag any file types that might warrant extra scrutiny." ), max_tokens=220, ) print(f"\n💬 GPT project analysis:\n{textwrap.fill(gpt_summary, 72)}\n") We install the required libraries, connect Magika and OpenAI, and set up the core helper function that lets us send prompts for analysis. We begin by testing Magika on various raw byte samples to see how it identifies file types without relying on file extensions. We also create a batch of sample files and use GPT to summarize what kind of project or codebase the detected file collection appears to represent. Copy Code Copied Use a different Browser print("=" * 60) print("SECTION 3 — Prediction Modes + GPT Mode-Selection Guidance") print("=" * 60) ambiguous = b"Hello, world. This is a short text." mode_results = {} for mode in [PredictionMode.HIGH_CONFIDENCE, PredictionMode.MEDIUM_CONFIDENCE, PredictionMode.BEST_GUESS]: m_mode = Magika(prediction_mode=mode) res = m_mode.identify_bytes(ambiguous) mode_results[mode.name] = { "label": res.output.label, "score": f"{res.score:.1%}", } print(f" {mode.name:<22} label={res.output.label:<20} score={res.score:.1%}") guidance = ask_gpt( system="You are a security engineer. Be concise (3 bullet points).", user=( f"Magika's three confidence modes returned: {json.dumps(mode_results)} " "for the same ambiguous text snippet. Give one practical use-case where each mode " "(HIGH_CONFIDENCE, MEDIUM_CONFIDENCE, BEST_GUESS) is the right choice." ), max_tokens=220, ) print(f"\n💬 GPT on when to use each mode:\n{guidance}\n") print("=" * 60) print("SECTION 4 — MagikaResult Anatomy + GPT Field Explanation") print("=" * 60) code_snippet = b""" #!/usr/bin/env python3 from typing import List def fibonacci(n: int) -> List[int]: a, b = 0, 1 result = [] for _ in range(n): result.append(a) a, b = b, a + b return result """ res = m.identify_bytes(code_snippet) result_dict = { "output.label": res.output.label, "output.description": res.output.description, "output.mime_type": res.output.mime_type, "output.group": res.output.group, "output.extensions": res.output.extensions, "output.is_text": res.output.is_text, "dl.label": res.dl.label, "dl.description": res.dl.description, "dl.mime_type": res.dl.mime_type, "score": round(res.score, 4), } for k, v in result_dict.items(): print(f" {k:<28} = {v}") field_explanation = ask_gpt( system="You are a concise ML engineer.", user=( f"Magika returned this result object for a Python file: {json.dumps(result_dict)}. " "In 4 sentences, explain the difference between the `dl.*` fields and `output.*` fields, " "and why dl.label and output.label might differ even though there is only one score." ), max_tokens=220, ) print(f"\n💬 GPT explains dl vs output:\n{textwrap.fill(field_explanation, 72)}\n") print("=" * 60) print("SECTION 5 — Spoofed Files + GPT Threat Assessment") print("=" * 60) spoofed_files = { "invoice.pdf": b'#!/usr/bin/env python3\nprint("I am Python, not a PDF!")\n', "photo.jpg": b'<html><body>This is HTML masquerading as JPEG</body></html>', "data.csv": bytes([0x50, 0x4B, 0x03, 0x04]) + bytes(26), "readme.txt": b'%PDF-1.4\n1 0 obj\n<</Type /Catalog>>\nendobj\n', "legit.py": b'import sys\nprint(sys.argv)\n', } ext_to_expected = {"pdf": "pdf", "jpg": "jpeg", "csv": "zip", "txt": "pdf", "py": "