Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -367,337 +367,106 @@ def load_model():
|
|
367 |
|
368 |
@spaces.GPU
|
369 |
def detect_threats(logs, sensitivity):
|
370 |
-
"""Task 1:
|
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 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
|
383 |
-
|
384 |
-
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
|
391 |
-
|
392 |
-
|
393 |
-
|
394 |
-
|
395 |
-
|
396 |
-
|
397 |
-
|
398 |
-
threats.append("⚠️ Authentication Failures")
|
399 |
-
risk_score += 15
|
400 |
-
|
401 |
-
# Malicious script execution
|
402 |
-
powershell_matches = re.findall(r'powershell.*-enc\s+([A-Za-z0-9+/=]+)', logs, re.IGNORECASE)
|
403 |
-
if powershell_matches:
|
404 |
-
threats.append("🚨 CRITICAL: Encoded PowerShell Execution")
|
405 |
-
detailed_findings.append("Suspicious PowerShell activity:")
|
406 |
-
detailed_findings.append(" - Encoded command execution detected")
|
407 |
-
detailed_findings.append(" - Potential command injection or malware")
|
408 |
-
detailed_findings.append(" - Hidden execution (-WindowStyle Hidden)")
|
409 |
-
risk_score += 40
|
410 |
-
|
411 |
-
# Network connections analysis
|
412 |
-
network_matches = re.findall(r'connection to\s+([\d\.]+):(\d+)', logs, re.IGNORECASE)
|
413 |
-
if network_matches:
|
414 |
-
for ip, port in network_matches:
|
415 |
-
if re.search(r'suspicious.*connection', logs, re.IGNORECASE):
|
416 |
-
threats.append("🚨 HIGH: Suspicious Network Activity")
|
417 |
-
detailed_findings.append(f"Suspicious outbound connection:")
|
418 |
-
detailed_findings.append(f" - Destination: {ip}:{port}")
|
419 |
-
detailed_findings.append(f" - Potential C2 communication")
|
420 |
-
risk_score += 30
|
421 |
-
|
422 |
-
# File system anomalies
|
423 |
-
if re.search(r'unusual.*file.*access.*pattern', logs, re.IGNORECASE):
|
424 |
-
threats.append("⚠️ MEDIUM: File System Anomaly")
|
425 |
-
detailed_findings.append("Unusual file access patterns detected")
|
426 |
-
detailed_findings.append(" - Potential data exfiltration or reconnaissance")
|
427 |
-
risk_score += 20
|
428 |
-
|
429 |
-
# Multiple connections from same source
|
430 |
-
if re.search(r'multiple.*connections.*same.*source', logs, re.IGNORECASE):
|
431 |
-
threats.append("⚠️ MEDIUM: Persistent Connection Attempts")
|
432 |
-
detailed_findings.append("Multiple connections from same source IP")
|
433 |
-
detailed_findings.append(" - Potential persistence mechanism")
|
434 |
-
risk_score += 15
|
435 |
-
|
436 |
-
# AI Analysis if model available
|
437 |
-
ai_analysis = ""
|
438 |
-
if pipe is not None:
|
439 |
-
try:
|
440 |
-
prompt = f"""Security Log Analysis - Detect threats and provide detailed assessment:
|
441 |
-
|
442 |
-
{logs}
|
443 |
-
|
444 |
-
Sensitivity: {sensitivity}
|
445 |
-
|
446 |
-
Identify all security threats, attack patterns, and provide risk assessment:"""
|
447 |
-
|
448 |
-
response = pipe(
|
449 |
-
prompt,
|
450 |
-
max_new_tokens=250,
|
451 |
-
do_sample=True,
|
452 |
-
temperature=0.3,
|
453 |
-
pad_token_id=50256,
|
454 |
-
truncation=True
|
455 |
-
)
|
456 |
-
|
457 |
-
ai_analysis = response[0]['generated_text'].split("Identify all security threats")[-1].strip()
|
458 |
-
except:
|
459 |
-
ai_analysis = "AI analysis temporarily unavailable"
|
460 |
-
|
461 |
-
# Severity calculation with sensitivity adjustment
|
462 |
-
sensitivity_multiplier = {"High": 1.3, "Medium": 1.0, "Low": 0.7}
|
463 |
-
adjusted_score = min(100, risk_score * sensitivity_multiplier.get(sensitivity, 1.0))
|
464 |
-
|
465 |
-
if threats:
|
466 |
-
if adjusted_score >= 70:
|
467 |
-
severity = "CRITICAL"
|
468 |
-
elif adjusted_score >= 50:
|
469 |
-
severity = "HIGH"
|
470 |
-
elif adjusted_score >= 30:
|
471 |
-
severity = "MEDIUM"
|
472 |
-
else:
|
473 |
-
severity = "LOW"
|
474 |
-
|
475 |
-
confidence = min(95, 75 + len(threats) * 5)
|
476 |
-
|
477 |
-
result = f"""🚨 THREAT DETECTION RESULTS
|
478 |
-
|
479 |
-
ASSESSMENT:
|
480 |
-
• Risk Score: {int(adjusted_score)}/100
|
481 |
-
• Severity: {severity}
|
482 |
-
• Confidence: {confidence}%
|
483 |
-
• Model: {"GPT-OSS-20B" if pipe else "Pattern-based"}
|
484 |
-
|
485 |
-
DETECTED THREATS:
|
486 |
-
{chr(10).join(f"• {threat}" for threat in threats)}
|
487 |
-
|
488 |
-
DETAILED FINDINGS:
|
489 |
-
{chr(10).join(detailed_findings)}
|
490 |
-
|
491 |
-
{f"AI ANALYSIS:{chr(10)}{ai_analysis}{chr(10)}" if ai_analysis and ai_analysis != "AI analysis temporarily unavailable" else ""}
|
492 |
-
|
493 |
-
RECOMMENDATIONS:
|
494 |
-
• {"🔴 Immediate containment required" if adjusted_score >= 60 else "🟡 Enhanced monitoring recommended"}
|
495 |
-
• {"🚨 Escalate to L2 analyst immediately" if adjusted_score >= 50 else "📋 Document and continue monitoring"}
|
496 |
-
• 🛡️ Preserve all evidence and logs
|
497 |
-
• 🔍 Begin threat hunting activities
|
498 |
-
• 📊 Update threat intelligence feeds"""
|
499 |
-
|
500 |
-
status = f"🚨 {len(threats)} THREATS - {severity}"
|
501 |
-
else:
|
502 |
-
result = f"""✅ NO IMMEDIATE THREATS DETECTED
|
503 |
-
|
504 |
-
ASSESSMENT:
|
505 |
-
• Risk Score: {int(adjusted_score)}/100
|
506 |
• Confidence: 85%
|
507 |
-
•
|
508 |
-
• Model: {"GPT-OSS-20B" if pipe else "Pattern-based"}
|
509 |
-
|
510 |
-
SUMMARY:
|
511 |
-
No critical threat patterns identified in the provided logs.
|
512 |
-
All activities appear within normal operational parameters.
|
513 |
-
|
514 |
-
{f"AI ANALYSIS:{chr(10)}{ai_analysis}{chr(10)}" if ai_analysis and ai_analysis != "AI analysis temporarily unavailable" else ""}
|
515 |
|
516 |
RECOMMENDATIONS:
|
517 |
-
•
|
518 |
-
•
|
519 |
-
•
|
520 |
-
•
|
521 |
-
|
522 |
-
|
523 |
-
|
524 |
-
time_taken = round(time.time() - start_time, 2)
|
525 |
-
return result, f"{status} ({time_taken}s)"
|
526 |
|
527 |
-
|
528 |
-
|
529 |
-
|
|
|
|
|
|
|
|
|
|
|
530 |
|
531 |
@spaces.GPU
|
532 |
def analyze_threat(threat, level):
|
533 |
-
"""Task 2:
|
534 |
-
global pipe
|
535 |
-
|
536 |
if not threat.strip():
|
537 |
return "Please describe the threat.", "⚠️ No input"
|
538 |
|
539 |
start_time = time.time()
|
540 |
|
541 |
-
|
542 |
-
|
543 |
-
|
544 |
-
'ips': re.findall(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', threat),
|
545 |
-
'domains': re.findall(r'\b[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b', threat),
|
546 |
-
'files': re.findall(r'\b\w+\.(exe|dll|bat|ps1|sh|zip|rar)\b', threat, re.IGNORECASE),
|
547 |
-
'processes': re.findall(r'\b(powershell|cmd|bash|python|java)\.exe\b', threat, re.IGNORECASE)
|
548 |
-
}
|
549 |
-
|
550 |
-
# AI Analysis if model available
|
551 |
-
ai_analysis = ""
|
552 |
-
if pipe is not None:
|
553 |
-
try:
|
554 |
-
prompt = f"""As a Level {level} SOC analyst, analyze this security incident:
|
555 |
-
|
556 |
-
{threat}
|
557 |
-
|
558 |
-
Analyst Level: {level}
|
559 |
-
- L1: Initial triage and escalation decisions
|
560 |
-
- L2: Detailed investigation and response coordination
|
561 |
-
- L3: Strategic response and executive-level analysis
|
562 |
-
|
563 |
-
Provide comprehensive analysis including threat assessment, IOCs, recommended actions, and next steps:"""
|
564 |
-
|
565 |
-
response = pipe(
|
566 |
-
prompt,
|
567 |
-
max_new_tokens=350,
|
568 |
-
do_sample=True,
|
569 |
-
temperature=0.4,
|
570 |
-
pad_token_id=50256,
|
571 |
-
truncation=True
|
572 |
-
)
|
573 |
-
|
574 |
-
ai_analysis = response[0]['generated_text'].split("Provide comprehensive analysis")[-1].strip()
|
575 |
-
except:
|
576 |
-
ai_analysis = "AI analysis temporarily unavailable - using structured analysis"
|
577 |
|
578 |
-
|
579 |
-
|
580 |
-
|
581 |
-
|
582 |
-
|
583 |
-
|
584 |
-
|
585 |
-
|
586 |
-
|
587 |
-
|
588 |
-
|
589 |
-
|
590 |
-
• Files: {', '.join(indicators['files']) if indicators['files'] else 'None detected'}
|
591 |
-
|
592 |
-
IMMEDIATE TRIAGE ACTIONS:
|
593 |
-
1. ✅ Validate threat indicators and scope
|
594 |
-
2. 🔍 Assess immediate impact to business operations
|
595 |
-
3. 🚨 Determine if systems need isolation
|
596 |
-
4. 📋 Document all available evidence
|
597 |
-
5. ⚡ Assess criticality and escalation needs
|
598 |
-
6. 📞 Notify Level 2 analyst if high severity
|
599 |
-
|
600 |
-
SEVERITY ASSESSMENT:
|
601 |
-
• Initial Risk: {"HIGH" if any(indicators.values()) else "MEDIUM"}
|
602 |
-
• Escalation Required: {"YES - Immediate" if len([v for v in indicators.values() if v]) > 2 else "YES - Standard"}
|
603 |
-
• Business Impact: Under Assessment
|
604 |
-
|
605 |
-
DECISION: ESCALATE TO L2
|
606 |
-
PRIORITY: HIGH
|
607 |
-
TIMELINE: Immediate (0-15 minutes)"""
|
608 |
-
|
609 |
-
elif level == "L2":
|
610 |
-
result = f"""🔍 LEVEL 2 INVESTIGATION
|
611 |
-
|
612 |
-
INCIDENT CLASSIFICATION:
|
613 |
-
{threat[:200]}{'...' if len(threat) > 200 else ''}
|
614 |
-
|
615 |
-
{f"AI DETAILED ANALYSIS:{chr(10)}{ai_analysis}{chr(10)}" if ai_analysis and "unavailable" not in ai_analysis else ""}
|
616 |
-
|
617 |
-
INDICATORS OF COMPROMISE (IOCs):
|
618 |
-
• IP Addresses: {', '.join(indicators['ips']) if indicators['ips'] else 'None identified'}
|
619 |
-
• Domains: {', '.join(indicators['domains']) if indicators['domains'] else 'None identified'}
|
620 |
-
• Files/Hashes: {', '.join(indicators['files']) if indicators['files'] else 'None identified'}
|
621 |
-
• Processes: {', '.join(indicators['processes']) if indicators['processes'] else 'None identified'}
|
622 |
-
|
623 |
-
DETAILED INVESTIGATION PLAN:
|
624 |
-
1. 📊 Comprehensive log analysis across all systems
|
625 |
-
2. ⏰ Timeline reconstruction of attack sequence
|
626 |
-
3. 🎯 Scope assessment - identify affected systems
|
627 |
-
4. 🔍 IOC identification and threat hunting
|
628 |
-
5. 🛡️ Implement immediate containment measures
|
629 |
-
6. 🤝 Coordinate with IT for system isolation
|
630 |
-
7. 🔎 Begin proactive threat hunting activities
|
631 |
-
8. 📈 Update threat intelligence feeds and signatures
|
632 |
-
|
633 |
-
CONTAINMENT MEASURES:
|
634 |
-
• Network segmentation of affected systems
|
635 |
-
• Account disabling if compromise suspected
|
636 |
-
• Memory/disk imaging for forensic analysis
|
637 |
-
• Traffic monitoring and filtering
|
638 |
-
|
639 |
-
NEXT STEPS:
|
640 |
-
• Deploy advanced monitoring on critical assets
|
641 |
-
• Coordinate with threat intelligence team
|
642 |
-
• Prepare incident report for management
|
643 |
-
• Consider L3 escalation for strategic response
|
644 |
-
|
645 |
-
INVESTIGATION STATUS: ACTIVE
|
646 |
-
ESTIMATED COMPLETION: 1-4 hours"""
|
647 |
-
|
648 |
-
else: # L3
|
649 |
-
result = f"""🎯 LEVEL 3 STRATEGIC ANALYSIS
|
650 |
-
|
651 |
-
EXECUTIVE THREAT ASSESSMENT:
|
652 |
-
{threat[:250]}{'...' if len(threat) > 250 else ''}
|
653 |
-
|
654 |
-
{f"STRATEGIC AI ANALYSIS:{chr(10)}{ai_analysis}{chr(10)}" if ai_analysis and "unavailable" not in ai_analysis else ""}
|
655 |
-
|
656 |
-
STRATEGIC INDICATORS:
|
657 |
-
• Network IOCs: {len(indicators['ips'])} IP addresses identified
|
658 |
-
• Process IOCs: {len(indicators['processes'])} suspicious processes
|
659 |
-
• File IOCs: {len(indicators['files'])} potential malicious files
|
660 |
-
• Domain IOCs: {len(indicators['domains'])} suspicious domains
|
661 |
-
|
662 |
-
STRATEGIC RESPONSE FRAMEWORK:
|
663 |
-
1. 🏢 Executive notification and stakeholder briefing
|
664 |
-
2. 💼 Business impact assessment and risk quantification
|
665 |
-
3. 🔬 Advanced forensic analysis coordination
|
666 |
-
4. 🌐 External agency coordination (if required)
|
667 |
-
5. 📋 Recovery and remediation planning
|
668 |
-
6. 📚 Security policy and procedure updates
|
669 |
-
7. 🔄 Post-incident review and lessons learned
|
670 |
-
8. 🛡️ Strategic security improvements implementation
|
671 |
-
|
672 |
-
BUSINESS IMPACT ANALYSIS:
|
673 |
-
• Operational Disruption: Under Assessment
|
674 |
-
• Data Integrity: Evaluation in Progress
|
675 |
-
• Regulatory Implications: Under Review
|
676 |
-
• Reputation Risk: Monitoring Required
|
677 |
-
|
678 |
-
RECOVERY PLANNING:
|
679 |
-
• System restoration priorities identified
|
680 |
-
• Communication strategy established
|
681 |
-
• Legal and compliance review initiated
|
682 |
-
• Customer/partner notification prepared
|
683 |
-
|
684 |
-
STRATEGIC RECOMMENDATIONS:
|
685 |
-
• Full incident response activation recommended
|
686 |
-
• Consider engaging external forensic experts
|
687 |
-
• Implement enhanced monitoring capabilities
|
688 |
-
• Review and update incident response procedures
|
689 |
-
|
690 |
-
EXECUTIVE DECISION: FULL IR ACTIVATION
|
691 |
-
PRIORITY: CRITICAL
|
692 |
-
OVERSIGHT: C-Level Involvement Required
|
693 |
-
TIMELINE: 4-24 hours for full resolution"""
|
694 |
|
695 |
-
|
696 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
697 |
|
698 |
-
|
699 |
-
|
700 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
701 |
|
702 |
# Sample data - matches the scenario in the screenshot
|
703 |
SAMPLE_LOGS = """2025-08-11 14:30:15 [AUTH] Failed login: 'admin' from 192.168.1.100
|
|
|
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:
|
432 |
+
• Assess severity
|
433 |
+
• Isolate systems
|
434 |
+
• Document evidence
|
435 |
+
• Escalate if high severity
|
436 |
+
|
437 |
+
DECISION: Escalate to L2
|
438 |
+
PRIORITY: High""",
|
439 |
+
|
440 |
+
"L2": f"""🔍 L2 INVESTIGATION
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
441 |
|
442 |
+
INCIDENT: {threat[:60]}...
|
443 |
+
|
444 |
+
INVESTIGATION PLAN:
|
445 |
+
1. Evidence collection
|
446 |
+
2. Timeline analysis
|
447 |
+
3. Scope assessment
|
448 |
+
4. IOC identification
|
449 |
+
5. Containment measures
|
450 |
+
|
451 |
+
NEXT STEPS: Deploy monitoring""",
|
452 |
+
|
453 |
+
"L3": f"""🎯 L3 STRATEGIC ANALYSIS
|
454 |
|
455 |
+
THREAT ASSESSMENT: {threat[:60]}...
|
456 |
+
|
457 |
+
STRATEGIC RESPONSE:
|
458 |
+
• Executive notification
|
459 |
+
• Business impact review
|
460 |
+
• Advanced forensics
|
461 |
+
• Recovery planning
|
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
|