abdull4h commited on
Commit
cc20bc5
·
verified ·
1 Parent(s): 6c8bbc8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +149 -51
app.py CHANGED
@@ -367,65 +367,158 @@ def load_model():
367
 
368
  @spaces.GPU
369
  def detect_threats(logs, sensitivity):
370
- """Task 1: Threat Detection"""
 
 
371
  if not logs.strip():
372
  return "Please provide log data.", "⚠️ No input"
373
 
374
  start_time = time.time()
375
 
376
- # Enhanced pattern-based detection that matches the screenshot
377
- threats = []
378
-
379
- # Check for failed login attempts
380
- if re.search(r'failed.*login|authentication.*failed', logs, re.IGNORECASE):
381
- threats.append("🚨 Brute Force Attack")
382
-
383
- # Check for PowerShell execution
384
- if re.search(r'powershell.*-enc|cmd\.exe', logs, re.IGNORECASE):
385
- threats.append("🚨 Malicious Script Execution")
386
-
387
- # Check for suspicious network activity
388
- if re.search(r'suspicious.*ip|unusual.*connection', logs, re.IGNORECASE):
389
- threats.append("🚨 Suspicious Network Activity")
390
-
391
- # Generate result matching the original screenshot format
392
- if threats:
393
- result = f"""ASSESSMENT:
394
- • Risk Score: 70/100
395
- • Severity: CRITICAL
396
- Confidence: 85%
397
- • Model: Pattern-based
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
398
 
399
  RECOMMENDATIONS:
400
- • Immediate containment required
401
- • Escalate to L2 analyst
402
  • Preserve all evidence
403
  • Update threat intelligence"""
404
- status = "🚨 THREATS DETECTED"
405
- else:
406
- result = """✅ NO THREATS DETECTED
 
 
 
 
 
407
 
408
- ANALYSIS: Clean logs
409
- CONFIDENCE: 75%
410
- STATUS: Normal operation
411
- RECOMMENDATION: Continue monitoring"""
412
- status = "✅ CLEAN"
413
-
414
- time_taken = round(time.time() - start_time, 1)
415
- return result, f"{status} ({time_taken}s)"
416
 
417
  @spaces.GPU
418
  def analyze_threat(threat, level):
419
- """Task 2: Analyst Assistant"""
 
 
420
  if not threat.strip():
421
  return "Please describe the threat.", "⚠️ No input"
422
 
423
  start_time = time.time()
424
 
425
- # Analysis templates that match the original screenshot format
426
- templates = {
427
- "L1": f"""🚨 L1 TRIAGE
428
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  THREAT: {threat[:60]}...
430
 
431
  IMMEDIATE ACTIONS:
@@ -437,8 +530,8 @@ IMMEDIATE ACTIONS:
437
  DECISION: Escalate to L2
438
  PRIORITY: High""",
439
 
440
- "L2": f"""🔍 L2 INVESTIGATION
441
-
442
  INCIDENT: {threat[:60]}...
443
 
444
  INVESTIGATION PLAN:
@@ -450,8 +543,8 @@ INVESTIGATION PLAN:
450
 
451
  NEXT STEPS: Deploy monitoring""",
452
 
453
- "L3": f"""🎯 L3 STRATEGIC ANALYSIS
454
-
455
  THREAT ASSESSMENT: {threat[:60]}...
456
 
457
  STRATEGIC RESPONSE:
@@ -462,13 +555,18 @@ STRATEGIC RESPONSE:
462
  • Security improvements
463
 
464
  RECOMMENDATION: Full IR activation"""
465
- }
466
-
467
- result = templates.get(level, templates["L2"])
468
- time_taken = round(time.time() - start_time, 1)
469
- return result, f"✅ {level} Complete ({time_taken}s)"
 
 
 
 
 
470
 
471
- # Sample data - matches the scenario in the screenshot
472
  SAMPLE_LOGS = """2025-08-11 14:30:15 [AUTH] Failed login: 'admin' from 192.168.1.100
473
  2025-08-11 14:30:18 [AUTH] Failed login: 'administrator' from 192.168.1.100
474
  2025-08-11 14:30:45 [PROC] powershell.exe -WindowStyle Hidden -enc ZXhlYyBjYWxjLmV4ZQ==
 
367
 
368
  @spaces.GPU
369
  def detect_threats(logs, sensitivity):
370
+ """Task 1: AI-powered Threat Detection"""
371
+ global pipe
372
+
373
  if not logs.strip():
374
  return "Please provide log data.", "⚠️ No input"
375
 
376
  start_time = time.time()
377
 
378
+ try:
379
+ if pipe is not None:
380
+ # Use GPT-OSS-20B for AI-powered detection
381
+ prompt = f"""Analyze these security logs for threats:
382
+
383
+ {logs}
384
+
385
+ Detection sensitivity: {sensitivity}
386
+
387
+ Analysis:"""
388
+
389
+ response = pipe(
390
+ prompt,
391
+ max_new_tokens=200,
392
+ do_sample=True,
393
+ temperature=0.3,
394
+ pad_token_id=50256,
395
+ truncation=True
396
+ )
397
+
398
+ ai_analysis = response[0]['generated_text'].split("Analysis:")[-1].strip()
399
+
400
+ else:
401
+ # Fallback to pattern-based detection
402
+ ai_analysis = "AI model unavailable. Using pattern-based detection."
403
+
404
+ # Enhanced pattern-based detection as backup/supplement
405
+ threats = []
406
+ risk_score = 0
407
+
408
+ # Authentication threats
409
+ failed_logins = len(re.findall(r'failed.*login|authentication.*failed', logs, re.IGNORECASE))
410
+ if failed_logins > 3:
411
+ threats.append(f"🚨 Brute Force Attack ({failed_logins} failed attempts)")
412
+ risk_score += 30
413
+ elif failed_logins > 0:
414
+ threats.append(f"⚠️ Failed Authentication ({failed_logins} attempts)")
415
+ risk_score += 15
416
+
417
+ # Malicious execution
418
+ if re.search(r'powershell.*-enc|cmd\.exe|eval\(|exec\(', logs, re.IGNORECASE):
419
+ threats.append("🚨 Malicious Script Execution")
420
+ risk_score += 35
421
+
422
+ # Network anomalies
423
+ if re.search(r'suspicious.*ip|unusual.*connection', logs, re.IGNORECASE):
424
+ threats.append("🚨 Suspicious Network Activity")
425
+ risk_score += 25
426
+
427
+ # File anomalies
428
+ if re.search(r'unusual.*file|suspicious.*access', logs, re.IGNORECASE):
429
+ threats.append("⚠️ File System Anomaly")
430
+ risk_score += 20
431
+
432
+ # Generate final result
433
+ if threats or pipe is not None:
434
+ severity = "CRITICAL" if risk_score > 50 else "HIGH" if risk_score > 30 else "MEDIUM"
435
+ confidence = min(95, 70 + len(threats) * 5)
436
+
437
+ result = f"""🚨 THREAT ANALYSIS RESULTS
438
+
439
+ AI ANALYSIS:
440
+ {ai_analysis}
441
+
442
+ DETECTED PATTERNS:
443
+ {chr(10).join(f"• {threat}" for threat in threats) if threats else "• No obvious threat patterns detected"}
444
+
445
+ ASSESSMENT:
446
+ • Risk Score: {risk_score}/100
447
+ • Severity: {severity if threats else "LOW"}
448
+ • Confidence: {confidence}%
449
+ • Model: {"GPT-OSS-20B" if pipe else "Pattern-based"}
450
 
451
  RECOMMENDATIONS:
452
+ {"Immediate containment required" if risk_score > 40 else "Continue monitoring"}
453
+ {"Escalate to L2 analyst" if risk_score > 30 else "Standard response"}
454
  • Preserve all evidence
455
  • Update threat intelligence"""
456
+
457
+ status = f"🚨 Analysis Complete - {len(threats)} threats found" if threats else "✅ Analysis Complete"
458
+ else:
459
+ result = """✅ NO THREATS DETECTED
460
+
461
+ Clean log analysis with no suspicious patterns identified.
462
+ Continue standard monitoring procedures."""
463
+ status = "✅ CLEAN"
464
 
465
+ time_taken = round(time.time() - start_time, 1)
466
+ return result, f"{status} ({time_taken}s)"
467
+
468
+ except Exception as e:
469
+ logger.error(f"Detection error: {str(e)}")
470
+ return f"❌ Analysis failed: {str(e)}", "❌ ERROR"
 
 
471
 
472
  @spaces.GPU
473
  def analyze_threat(threat, level):
474
+ """Task 2: AI-powered Analyst Assistant"""
475
+ global pipe
476
+
477
  if not threat.strip():
478
  return "Please describe the threat.", "⚠️ No input"
479
 
480
  start_time = time.time()
481
 
482
+ try:
483
+ if pipe is not None:
484
+ # Use GPT-OSS-20B for AI analysis
485
+ prompt = f"""As a Level {level} SOC analyst, analyze this security threat:
486
+
487
+ {threat}
488
+
489
+ Provide detailed analysis including:
490
+ 1. Threat assessment
491
+ 2. Recommended actions
492
+ 3. Priority level
493
+ 4. Next steps
494
+
495
+ Analysis:"""
496
+
497
+ response = pipe(
498
+ prompt,
499
+ max_new_tokens=300,
500
+ do_sample=True,
501
+ temperature=0.4,
502
+ pad_token_id=50256,
503
+ truncation=True
504
+ )
505
+
506
+ ai_analysis = response[0]['generated_text'].split("Analysis:")[-1].strip()
507
+
508
+ result = f"""🤖 AI-POWERED {level} ANALYSIS
509
+
510
+ THREAT ASSESSMENT:
511
+ {ai_analysis}
512
+
513
+ MODEL: GPT-OSS-20B
514
+ ANALYST LEVEL: {level}
515
+ STATUS: AI Analysis Complete"""
516
+
517
+ else:
518
+ # Fallback analysis templates
519
+ templates = {
520
+ "L1": f"""🚨 L1 TRIAGE ANALYSIS
521
+
522
  THREAT: {threat[:60]}...
523
 
524
  IMMEDIATE ACTIONS:
 
530
  DECISION: Escalate to L2
531
  PRIORITY: High""",
532
 
533
+ "L2": f"""🔍 L2 INVESTIGATION
534
+
535
  INCIDENT: {threat[:60]}...
536
 
537
  INVESTIGATION PLAN:
 
543
 
544
  NEXT STEPS: Deploy monitoring""",
545
 
546
+ "L3": f"""🎯 L3 STRATEGIC ANALYSIS
547
+
548
  THREAT ASSESSMENT: {threat[:60]}...
549
 
550
  STRATEGIC RESPONSE:
 
555
  • Security improvements
556
 
557
  RECOMMENDATION: Full IR activation"""
558
+ }
559
+
560
+ result = templates.get(level, templates["L2"])
561
+
562
+ time_taken = round(time.time() - start_time, 1)
563
+ return result, f"✅ {level} Complete ({time_taken}s)"
564
+
565
+ except Exception as e:
566
+ logger.error(f"Analysis error: {str(e)}")
567
+ return f"❌ Analysis failed: {str(e)}", "❌ ERROR"
568
 
569
+ # Sample data
570
  SAMPLE_LOGS = """2025-08-11 14:30:15 [AUTH] Failed login: 'admin' from 192.168.1.100
571
  2025-08-11 14:30:18 [AUTH] Failed login: 'administrator' from 192.168.1.100
572
  2025-08-11 14:30:45 [PROC] powershell.exe -WindowStyle Hidden -enc ZXhlYyBjYWxjLmV4ZQ==