Spaces:
Sleeping
Sleeping
Add yara rules
Browse files
app.py
CHANGED
|
@@ -9,9 +9,12 @@ import shutil
|
|
| 9 |
import cv2
|
| 10 |
import logging
|
| 11 |
import uuid
|
|
|
|
|
|
|
| 12 |
from huggingface_hub import snapshot_download
|
| 13 |
-
from typing import Optional
|
| 14 |
import aiofiles
|
|
|
|
| 15 |
|
| 16 |
# Configure logging
|
| 17 |
logging.basicConfig(level=logging.INFO)
|
|
@@ -25,25 +28,103 @@ MAL_CLASSES = ['Adialer.C', 'Agent.FYI', 'Allaple.A', 'Allaple.L', 'Alueron.gen!
|
|
| 25 |
|
| 26 |
UPLOAD_DIR = "uploads"
|
| 27 |
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
|
|
|
|
|
|
| 28 |
|
| 29 |
# Environment configuration
|
| 30 |
MODEL_REPO = os.getenv("MODEL_REPO", "GranularFireplace/malware")
|
| 31 |
MODEL_FILE = os.getenv("MODEL_FILE", "model_v2_with_weight.keras")
|
| 32 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
@asynccontextmanager
|
| 34 |
async def lifespan(app: FastAPI):
|
| 35 |
-
"""Manage
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
try:
|
|
|
|
| 37 |
logger.info("Downloading model from Hugging Face Hub...")
|
| 38 |
download_dir = snapshot_download(MODEL_REPO)
|
| 39 |
app.state.model = tf.keras.models.load_model(os.path.join(download_dir, MODEL_FILE))
|
| 40 |
logger.info("Model loaded successfully")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 41 |
except Exception as e:
|
| 42 |
-
logger.error(f"
|
| 43 |
raise
|
|
|
|
| 44 |
yield
|
| 45 |
-
|
|
|
|
| 46 |
app.state.model = None
|
|
|
|
| 47 |
|
| 48 |
app = FastAPI(lifespan=lifespan)
|
| 49 |
|
|
|
|
| 9 |
import cv2
|
| 10 |
import logging
|
| 11 |
import uuid
|
| 12 |
+
import yara
|
| 13 |
+
import asyncio
|
| 14 |
from huggingface_hub import snapshot_download
|
| 15 |
+
from typing import Optional, List, Dict
|
| 16 |
import aiofiles
|
| 17 |
+
from fastapi.concurrency import run_in_threadpool
|
| 18 |
|
| 19 |
# Configure logging
|
| 20 |
logging.basicConfig(level=logging.INFO)
|
|
|
|
| 28 |
|
| 29 |
UPLOAD_DIR = "uploads"
|
| 30 |
os.makedirs(UPLOAD_DIR, exist_ok=True)
|
| 31 |
+
YARA_REPO_URL = "https://github.com/roadwy/DefenderYara.git"
|
| 32 |
+
YARA_REPO_DIR = "defenderyara"
|
| 33 |
|
| 34 |
# Environment configuration
|
| 35 |
MODEL_REPO = os.getenv("MODEL_REPO", "GranularFireplace/malware")
|
| 36 |
MODEL_FILE = os.getenv("MODEL_FILE", "model_v2_with_weight.keras")
|
| 37 |
|
| 38 |
+
async def clone_yara_repo():
|
| 39 |
+
"""Clone YARA rules repository asynchronously"""
|
| 40 |
+
try:
|
| 41 |
+
repo_path = Path(YARA_REPO_DIR)
|
| 42 |
+
|
| 43 |
+
# Remove existing repository if it exists
|
| 44 |
+
if repo_path.exists():
|
| 45 |
+
logger.info("Removing existing YARA rules repository")
|
| 46 |
+
shutil.rmtree(repo_path)
|
| 47 |
+
|
| 48 |
+
logger.info(f"Cloning YARA rules from {YARA_REPO_URL}")
|
| 49 |
+
proc = await asyncio.create_subprocess_exec(
|
| 50 |
+
'git', 'clone', YARA_REPO_URL, str(repo_path),
|
| 51 |
+
stdout=asyncio.subprocess.PIPE,
|
| 52 |
+
stderr=asyncio.subprocess.PIPE
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
stdout, stderr = await proc.communicate()
|
| 56 |
+
|
| 57 |
+
if proc.returncode != 0:
|
| 58 |
+
logger.error(f"Failed to clone YARA repo: {stderr.decode()}")
|
| 59 |
+
return None
|
| 60 |
+
|
| 61 |
+
logger.info("YARA rules repository cloned successfully")
|
| 62 |
+
return repo_path
|
| 63 |
+
|
| 64 |
+
except Exception as e:
|
| 65 |
+
logger.error(f"Error cloning YARA repository: {str(e)}")
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
def compile_yara_rules(repo_path: Path) -> Optional[yara.Rules]:
|
| 69 |
+
"""Compile YARA rules from repository"""
|
| 70 |
+
try:
|
| 71 |
+
yara_files = list(repo_path.glob("**/*.yar"))
|
| 72 |
+
if not yara_files:
|
| 73 |
+
logger.warning("No YARA files found in repository")
|
| 74 |
+
return None
|
| 75 |
+
|
| 76 |
+
logger.info(f"Found {len(yara_files)} YARA files, compiling rules")
|
| 77 |
+
rules = {}
|
| 78 |
+
|
| 79 |
+
for yara_file in yara_files:
|
| 80 |
+
try:
|
| 81 |
+
rules[str(yara_file)] = str(yara_file)
|
| 82 |
+
except Exception as e:
|
| 83 |
+
logger.warning(f"Error processing {yara_file}: {str(e)}")
|
| 84 |
+
|
| 85 |
+
return yara.compile(filepaths=rules)
|
| 86 |
+
|
| 87 |
+
except yara.SyntaxError as e:
|
| 88 |
+
logger.error(f"YARA syntax error: {str(e)}")
|
| 89 |
+
except Exception as e:
|
| 90 |
+
logger.error(f"Error compiling YARA rules: {str(e)}")
|
| 91 |
+
|
| 92 |
+
return None
|
| 93 |
+
|
| 94 |
@asynccontextmanager
|
| 95 |
async def lifespan(app: FastAPI):
|
| 96 |
+
"""Manage application lifecycle"""
|
| 97 |
+
# Initialize app state
|
| 98 |
+
app.state.model = None
|
| 99 |
+
app.state.yara_rules = None
|
| 100 |
+
|
| 101 |
try:
|
| 102 |
+
# Load ML model
|
| 103 |
logger.info("Downloading model from Hugging Face Hub...")
|
| 104 |
download_dir = snapshot_download(MODEL_REPO)
|
| 105 |
app.state.model = tf.keras.models.load_model(os.path.join(download_dir, MODEL_FILE))
|
| 106 |
logger.info("Model loaded successfully")
|
| 107 |
+
|
| 108 |
+
# Clone and compile YARA rules
|
| 109 |
+
yara_repo_path = await clone_yara_repo()
|
| 110 |
+
if yara_repo_path:
|
| 111 |
+
app.state.yara_rules = compile_yara_rules(yara_repo_path)
|
| 112 |
+
if app.state.yara_rules:
|
| 113 |
+
logger.info("YARA rules compiled successfully")
|
| 114 |
+
else:
|
| 115 |
+
logger.warning("No valid YARA rules compiled")
|
| 116 |
+
else:
|
| 117 |
+
logger.warning("YARA rules unavailable")
|
| 118 |
+
|
| 119 |
except Exception as e:
|
| 120 |
+
logger.error(f"Initialization error: {str(e)}")
|
| 121 |
raise
|
| 122 |
+
|
| 123 |
yield
|
| 124 |
+
|
| 125 |
+
# Cleanup
|
| 126 |
app.state.model = None
|
| 127 |
+
app.state.yara_rules = None
|
| 128 |
|
| 129 |
app = FastAPI(lifespan=lifespan)
|
| 130 |
|