HeshamXOR commited on
Commit
3cc985e
·
verified ·
1 Parent(s): 56336c8

feat: Add CSV injection detection & MP4 heuristic analysis

Browse files

- CSV analyzer service (XGBoost ML + rule engine)
- MP4 heuristic analyzer (structural validation)
- Generic upload router (/api/upload/analyze-generic)
- Updated main.py with new service init
- CSV injection model (csv_injection_model.joblib)
- Updated Dockerfile to include CSV model

Files changed (2) hide show
  1. PARTNER_API.md +37 -0
  2. backend/app/routers/partner.py +86 -0
PARTNER_API.md CHANGED
@@ -101,3 +101,40 @@ Response:
101
  "details": {}
102
  }
103
  ```
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  "details": {}
102
  }
103
  ```
104
+
105
+ ## Analyze a Generic File (CSV, MP4)
106
+
107
+ Supported generic files include `.csv`, `.tsv`, `.mp4`, `.m4v`, `.mov`.
108
+ Maximum file size is 50 MB.
109
+
110
+ ```bash
111
+ curl -X POST https://malwareguard-one.vercel.app/api/partner/analyze-generic \
112
+ -H "X-API-Key: shared-secret-key" \
113
+ -F "file=@data.csv"
114
+ ```
115
+
116
+ Response:
117
+
118
+ ```json
119
+ {
120
+ "analysis_type": "file",
121
+ "target": "data.csv",
122
+ "verdict": "Malicious",
123
+ "is_malicious": true,
124
+ "malicious_score": 0.99,
125
+ "confidence_level": "High",
126
+ "threshold_used": 0.5,
127
+ "source": "malwareguard-csv-xgboost",
128
+ "sha256": "file_sha256_hash",
129
+ "file_size": 1234,
130
+ "details": {
131
+ "threats": [
132
+ {
133
+ "type": "Formula Injection",
134
+ "severity": "Critical",
135
+ "description": "Found DDE injection payload"
136
+ }
137
+ ]
138
+ }
139
+ }
140
+ ```
backend/app/routers/partner.py CHANGED
@@ -17,9 +17,20 @@ from ..rate_limit import limiter
17
  from ..services.ember_features import LIEF_AVAILABLE, extract_features_and_lief
18
  from ..services.ml_service import get_ml_service
19
  from ..services.url_service import get_url_service
 
 
20
 
21
  logger = logging.getLogger(__name__)
22
 
 
 
 
 
 
 
 
 
 
23
  router = APIRouter(prefix="/api/partner", tags=["partner-api"])
24
 
25
 
@@ -79,6 +90,7 @@ async def partner_health(x_api_key: str | None = Header(default=None, alias="X-A
79
  "endpoints": {
80
  "url": "/api/partner/analyze-url",
81
  "file": "/api/partner/analyze-file",
 
82
  },
83
  }
84
 
@@ -171,3 +183,77 @@ async def analyze_partner_file(
171
  feature_count=len(features_list),
172
  inference_time_ms=prediction.inference_time_ms,
173
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  from ..services.ember_features import LIEF_AVAILABLE, extract_features_and_lief
18
  from ..services.ml_service import get_ml_service
19
  from ..services.url_service import get_url_service
20
+ from ..services.csv_analyzer import get_csv_analyzer
21
+ from ..services.mp4_analyzer import get_mp4_analyzer
22
 
23
  logger = logging.getLogger(__name__)
24
 
25
+ CSV_EXTENSIONS = {".csv", ".tsv"}
26
+ VIDEO_EXTENSIONS = {".mp4", ".m4v", ".m4a", ".mov", ".3gp"}
27
+ SUPPORTED_GENERIC_EXTENSIONS = CSV_EXTENSIONS | VIDEO_EXTENSIONS
28
+
29
+ def _get_extension(filename: str) -> str:
30
+ if "." in filename:
31
+ return "." + filename.rsplit(".", 1)[-1].lower()
32
+ return ""
33
+
34
  router = APIRouter(prefix="/api/partner", tags=["partner-api"])
35
 
36
 
 
90
  "endpoints": {
91
  "url": "/api/partner/analyze-url",
92
  "file": "/api/partner/analyze-file",
93
+ "generic": "/api/partner/analyze-generic",
94
  },
95
  }
96
 
 
183
  feature_count=len(features_list),
184
  inference_time_ms=prediction.inference_time_ms,
185
  )
186
+
187
+
188
+ @router.post("/analyze-generic", response_model=PartnerAnalysisResponse)
189
+ @limiter.limit(settings.rate_limit_partner)
190
+ async def analyze_partner_generic(
191
+ request: Request,
192
+ file: UploadFile = File(..., description="CSV or MP4 file to analyze"),
193
+ x_api_key: str | None = Header(default=None, alias="X-API-Key"),
194
+ ):
195
+ """Analyze a non-PE generic file (CSV, MP4) and return a compact verdict for partners."""
196
+ _verify_partner_key(x_api_key)
197
+
198
+ filename = file.filename or "unknown"
199
+ ext = _get_extension(filename)
200
+
201
+ if ext not in SUPPORTED_GENERIC_EXTENSIONS:
202
+ raise HTTPException(
203
+ status_code=400,
204
+ detail=f"Unsupported file type '{ext}'. Supported: {', '.join(sorted(SUPPORTED_GENERIC_EXTENSIONS))}",
205
+ )
206
+
207
+ try:
208
+ content = await file.read()
209
+ except Exception as exc:
210
+ raise HTTPException(status_code=400, detail=f"Failed to read file: {exc}") from exc
211
+
212
+ if not content:
213
+ raise HTTPException(status_code=400, detail="Empty file uploaded")
214
+ if len(content) > 50 * 1024 * 1024:
215
+ raise HTTPException(status_code=400, detail="File too large. Maximum size is 50MB.")
216
+
217
+ sha256 = hashlib.sha256(content).hexdigest()
218
+
219
+ try:
220
+ if ext in CSV_EXTENSIONS:
221
+ analyzer = get_csv_analyzer()
222
+ result = analyzer.analyze(content, filename).to_dict()
223
+ source = "malwareguard-csv-xgboost"
224
+ else:
225
+ analyzer = get_mp4_analyzer()
226
+ result = analyzer.analyze(content, filename).to_dict()
227
+ source = "malwareguard-mp4-heuristic"
228
+ except Exception as exc:
229
+ logger.error("Partner generic analysis failed for %s: %s", filename, exc)
230
+ raise HTTPException(status_code=500, detail=f"Analysis failed: {exc}") from exc
231
+
232
+ verdict_str = result.get("verdict", "Unknown")
233
+ is_malicious = verdict_str == "Malicious"
234
+
235
+ verdict = PredictionLabel.MALICIOUS if is_malicious else PredictionLabel.BENIGN
236
+
237
+ prob = result.get("probability")
238
+ risk_score = result.get("risk_score")
239
+ malicious_score = float(prob) if prob is not None else (float(risk_score) / 100.0 if risk_score is not None else 0.0)
240
+
241
+ details = {}
242
+ if "threats_found" in result:
243
+ details["threats"] = result["threats_found"]
244
+ if "structure_info" in result:
245
+ details["structure"] = result["structure_info"]
246
+
247
+ return PartnerAnalysisResponse(
248
+ analysis_type="file",
249
+ target=filename,
250
+ verdict=verdict,
251
+ is_malicious=is_malicious,
252
+ malicious_score=malicious_score,
253
+ confidence_level=result.get("confidence", "Low"),
254
+ threshold_used=0.5,
255
+ source=source,
256
+ sha256=sha256,
257
+ file_size=len(content),
258
+ details=details
259
+ )