Snyk Code Security คืออะไร
Snyk เป็น developer security platform ที่ช่วยค้นหาและแก้ไข vulnerabilities ใน code, dependencies, containers และ infrastructure as code ทำงานแบบ shift-left security ตรวจสอบตั้งแต่ขั้นตอน development ไม่ต้องรอจนถึง production
Snyk มี 4 products หลักได้แก่ Snyk Code สแกน source code หา vulnerabilities (SAST), Snyk Open Source สแกน dependencies หา known vulnerabilities, Snyk Container สแกน container images, Snyk IaC สแกน Terraform, Kubernetes, CloudFormation configs
Business Continuity Planning (BCP) สำหรับ security หมายถึงการวางแผนรับมือเมื่อเกิด security incidents เช่น data breach, ransomware, supply chain attack การใช้ Snyk เป็นส่วนหนึ่งของ BCP ช่วยลดความเสี่ยง ค้นพบ vulnerabilities เร็ว แก้ไขก่อนถูกโจมตี และ recover ได้เร็วเมื่อเกิดเหตุ
ติดตั้งและตั้งค่า Snyk
Setup Snyk สำหรับ project
# === Snyk Installation and Setup ===
# 1. Install Snyk CLI
npm install -g snyk
# or
brew install snyk
# or
curl --compressed https://static.snyk.io/cli/latest/snyk-linux -o snyk
chmod +x snyk && mv snyk /usr/local/bin/
# 2. Authenticate
snyk auth
# Opens browser for authentication
# Or use token:
snyk auth YOUR_API_TOKEN
# 3. Test Project for Vulnerabilities
# Open Source dependencies:
snyk test
# Source code (SAST):
snyk code test
# Container image:
snyk container test nginx:latest
# Infrastructure as Code:
snyk iac test ./terraform/
# 4. Monitor Project (continuous monitoring)
snyk monitor
# 5. Configuration (.snyk file)
cat > .snyk << 'EOF'
version: v1.5.0
ignore:
SNYK-JS-LODASH-567746:
- '*':
reason: 'Low risk, will upgrade in next sprint'
expires: 2024-06-01T00:00:00.000Z
patch: {}
EOF
# 6. Snyk Config for Organization
cat > .snyk.d/default.yaml << 'EOF'
org: my-company
severity-threshold: high
fail-on: all
project-name: my-app
EOF
# 7. IDE Integration
# VS Code: Install "Snyk Security" extension
# IntelliJ: Install "Snyk" plugin
# Both provide real-time vulnerability scanning in IDE
# 8. Docker Integration
# Scan during build:
# docker build -t myapp:latest .
# snyk container test myapp:latest --file=Dockerfile
echo "Snyk installed and configured"
Scan และแก้ไข Vulnerabilities
วิเคราะห์และแก้ไข security issues
#!/usr/bin/env python3
# security_scanner.py — Vulnerability Management
import json
import logging
from datetime import datetime, timedelta
from typing import Dict, List
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("security")
class VulnerabilityManager:
def __init__(self):
self.vulnerabilities = []
def scan_results(self):
"""Simulated Snyk scan results"""
return {
"project": "my-web-app",
"scan_date": datetime.utcnow().isoformat(),
"summary": {
"critical": 2,
"high": 5,
"medium": 12,
"low": 23,
"total": 42,
},
"vulnerabilities": [
{
"id": "SNYK-JS-EXPRESS-6474509",
"title": "Improper Input Validation in Express",
"severity": "critical",
"cvss": 9.8,
"package": "express",
"version": "4.17.1",
"fix_version": "4.19.2",
"exploitable": True,
"fix": "npm install express@4.19.2",
},
{
"id": "SNYK-PYTHON-REQUESTS-6928867",
"title": "SSRF in requests library",
"severity": "high",
"cvss": 7.5,
"package": "requests",
"version": "2.28.0",
"fix_version": "2.32.0",
"exploitable": True,
"fix": "pip install requests==2.32.0",
},
{
"id": "SNYK-JS-JSONWEBTOKEN-3180022",
"title": "JWT Algorithm Confusion in jsonwebtoken",
"severity": "critical",
"cvss": 9.1,
"package": "jsonwebtoken",
"version": "8.5.1",
"fix_version": "9.0.0",
"exploitable": True,
"fix": "npm install jsonwebtoken@9.0.0",
},
],
"code_issues": [
{
"id": "python/HardcodedCredential",
"severity": "high",
"file": "src/config.py",
"line": 15,
"message": "Hardcoded password detected",
"fix": "Use environment variables or secret manager",
},
{
"id": "python/SqlInjection",
"severity": "critical",
"file": "src/api/users.py",
"line": 42,
"message": "SQL injection through user input",
"fix": "Use parameterized queries",
},
],
}
def prioritize_fixes(self, results):
"""Prioritize vulnerabilities for fixing"""
all_vulns = results["vulnerabilities"] + results["code_issues"]
priorities = {
"immediate": [],
"this_sprint": [],
"next_sprint": [],
"backlog": [],
}
for v in all_vulns:
severity = v.get("severity", "low")
exploitable = v.get("exploitable", False)
if severity == "critical" and exploitable:
priorities["immediate"].append(v.get("id"))
elif severity == "critical" or (severity == "high" and exploitable):
priorities["this_sprint"].append(v.get("id"))
elif severity == "high":
priorities["next_sprint"].append(v.get("id"))
else:
priorities["backlog"].append(v.get("id"))
return priorities
manager = VulnerabilityManager()
results = manager.scan_results()
print("Summary:", json.dumps(results["summary"], indent=2))
priorities = manager.prioritize_fixes(results)
print("\nPriorities:", json.dumps(priorities, indent=2))
Business Continuity Planning
วางแผน Business Continuity สำหรับ security
# === Business Continuity Plan for Security ===
# 1. Incident Response Plan
# ===================================
# Phase 1: Detection (0-15 minutes)
# - Snyk alerts on new critical vulnerability
# - SIEM detects exploitation attempt
# - Automated triage and notification
#
# Phase 2: Containment (15-60 minutes)
# - Isolate affected systems
# - Block attack vectors (WAF rules, network policies)
# - Preserve evidence for forensics
#
# Phase 3: Eradication (1-24 hours)
# - Patch vulnerabilities
# - Remove compromised components
# - Deploy fixed versions
#
# Phase 4: Recovery (24-72 hours)
# - Restore from clean backups
# - Verify system integrity
# - Gradual service restoration
#
# Phase 5: Lessons Learned (1 week)
# - Post-incident review
# - Update security policies
# - Improve detection capabilities
# 2. Backup Strategy
cat > backup-policy.yaml << 'EOF'
backup_policy:
database:
frequency: every_6_hours
retention: 30_days
type: incremental
encryption: AES-256
offsite: true
test_restore: monthly
application_code:
method: git
remote: multiple_providers
signed_commits: true
configuration:
method: gitops
encrypted_secrets: true
versioned: true
container_images:
registry: private
scanning: on_push
retention: 90_days
signed: true
disaster_recovery:
rto: 4_hours
rpo: 1_hour
failover_site: secondary_region
automated_failover: true
test_frequency: quarterly
EOF
# 3. Security Monitoring Stack
cat > monitoring/security-stack.yaml << 'EOF'
monitoring:
siem:
tool: Wazuh
log_sources:
- application_logs
- system_logs
- network_logs
- authentication_logs
alerts:
- brute_force_detection
- privilege_escalation
- data_exfiltration
- anomalous_behavior
vulnerability_scanning:
tool: Snyk
frequency: every_commit
ci_integration: true
blocking: critical_and_high
monitoring: continuous
runtime_protection:
tool: Falco
rules:
- unexpected_process_execution
- file_integrity_monitoring
- network_anomaly_detection
- container_escape_detection
compliance:
frameworks:
- SOC2
- ISO27001
- PCI-DSS
audit_frequency: quarterly
automated_checks: daily
EOF
echo "Business continuity plan defined"
CI/CD Security Integration
รวม Snyk เข้ากับ CI/CD pipeline
#!/usr/bin/env python3
# cicd_security.py — CI/CD Security Pipeline
import json
import logging
from typing import Dict, List
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("cicd")
class SecurityPipeline:
def __init__(self):
self.gates = []
def github_actions_workflow(self):
"""Security-integrated CI/CD workflow"""
return {
"name": "Security Pipeline",
"on": {"push": {"branches": ["main"]}, "pull_request": {}},
"jobs": {
"snyk-code": {
"name": "Snyk Code (SAST)",
"runs-on": "ubuntu-latest",
"steps": [
{"uses": "actions/checkout@v4"},
{"uses": "snyk/actions/setup@master"},
{"run": "snyk code test --severity-threshold=high"},
],
},
"snyk-deps": {
"name": "Snyk Open Source",
"runs-on": "ubuntu-latest",
"steps": [
{"uses": "actions/checkout@v4"},
{"uses": "snyk/actions/node@master", "with": {"args": "--severity-threshold=high"}},
],
},
"snyk-container": {
"name": "Snyk Container",
"runs-on": "ubuntu-latest",
"needs": ["build"],
"steps": [
{"uses": "snyk/actions/docker@master", "with": {"image": "myapp:}"}},
],
},
"snyk-iac": {
"name": "Snyk IaC",
"runs-on": "ubuntu-latest",
"steps": [
{"uses": "actions/checkout@v4"},
{"run": "snyk iac test ./terraform/ --severity-threshold=high"},
],
},
},
}
def security_gates(self):
"""Define security gates for deployment"""
return {
"gates": [
{
"name": "Code Scan",
"tool": "Snyk Code",
"blocking": True,
"threshold": "no critical or high",
"stage": "pre-merge",
},
{
"name": "Dependency Scan",
"tool": "Snyk Open Source",
"blocking": True,
"threshold": "no critical, max 3 high",
"stage": "pre-merge",
},
{
"name": "Container Scan",
"tool": "Snyk Container",
"blocking": True,
"threshold": "no critical",
"stage": "pre-deploy",
},
{
"name": "IaC Scan",
"tool": "Snyk IaC",
"blocking": True,
"threshold": "no high misconfigurations",
"stage": "pre-deploy",
},
{
"name": "DAST Scan",
"tool": "OWASP ZAP",
"blocking": False,
"threshold": "report only",
"stage": "post-deploy-staging",
},
],
"bypass_policy": {
"requires": "Security team approval",
"max_bypass_duration": "72 hours",
"audit_logged": True,
},
}
pipeline = SecurityPipeline()
workflow = pipeline.github_actions_workflow()
print("Jobs:", json.dumps(list(workflow["jobs"].keys()), indent=2))
gates = pipeline.security_gates()
print("\nGates:", json.dumps(gates["gates"][:3], indent=2))
Monitoring และ Compliance
Monitor security posture
#!/usr/bin/env python3
# compliance_monitor.py — Security Compliance Monitoring
import json
import logging
from datetime import datetime
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("compliance")
class ComplianceMonitor:
def __init__(self):
self.checks = []
def security_posture(self):
return {
"timestamp": datetime.utcnow().isoformat(),
"overall_score": 85,
"categories": {
"vulnerability_management": {
"score": 90,
"critical_vulns": 0,
"high_vulns": 2,
"mean_time_to_remediate_days": 3,
"scan_coverage_pct": 98,
},
"access_control": {
"score": 88,
"mfa_adoption_pct": 95,
"privileged_accounts": 5,
"last_access_review": "2024-01-15",
},
"data_protection": {
"score": 82,
"encryption_at_rest": True,
"encryption_in_transit": True,
"backup_tested": True,
"data_classification": "completed",
},
"incident_response": {
"score": 78,
"plan_last_updated": "2024-01-01",
"last_drill": "2024-02-15",
"mean_time_to_detect_hours": 2,
"mean_time_to_respond_hours": 4,
},
},
"compliance_frameworks": {
"SOC2": {"status": "compliant", "last_audit": "2024-01-01", "next_audit": "2024-07-01"},
"ISO27001": {"status": "in_progress", "completion_pct": 75},
"PCI-DSS": {"status": "not_applicable"},
},
}
def remediation_sla(self):
return {
"critical": {"sla_hours": 24, "current_avg_hours": 8, "compliance": True},
"high": {"sla_hours": 72, "current_avg_hours": 48, "compliance": True},
"medium": {"sla_hours": 336, "current_avg_hours": 120, "compliance": True},
"low": {"sla_hours": 720, "current_avg_hours": 240, "compliance": True},
}
monitor = ComplianceMonitor()
posture = monitor.security_posture()
print("Score:", posture["overall_score"])
print("Vulns:", json.dumps(posture["categories"]["vulnerability_management"], indent=2))
sla = monitor.remediation_sla()
print("\nSLA:", json.dumps(sla, indent=2))
FAQ คำถามที่พบบ่อย
Q: Snyk กับ SonarQube ต่างกันอย่างไร?
A: Snyk เน้น security-focused ครอบคลุม code, dependencies, containers, IaC มี vulnerability database ที่ update เร็ว fix suggestions อัตโนมัติ developer-friendly SonarQube เน้น code quality ทั้ง bugs, code smells, security hotspots, test coverage เหมาะสำหรับ enforce code standards ทั้งสองใช้ร่วมกันได้ SonarQube สำหรับ code quality, Snyk สำหรับ security vulnerabilities โดยเฉพาะ
Q: Business Continuity Plan ต้องมีอะไรบ้าง?
A: ส่วนสำคัญได้แก่ Risk Assessment ระบุ threats และ vulnerabilities ที่อาจกระทบธุรกิจ, Incident Response Plan ขั้นตอนรับมือเมื่อเกิดเหตุ (detection, containment, eradication, recovery), Backup & Recovery Strategy วิธี backup ข้อมูล ความถี่ และ restore procedures, Communication Plan ใครต้องแจ้งบ้าง ช่องทางไหน เมื่อไหร่, Testing & Drills ทดสอบ plan อย่างน้อยทุก 6 เดือน, Recovery Time Objective (RTO) ระยะเวลาที่ยอมรับได้ก่อน restore, Recovery Point Objective (RPO) ปริมาณข้อมูลที่ยอมสูญเสียได้
Q: Shift-left security ทำอย่างไร?
A: Shift-left หมายถึงเลื่อน security testing มาทำตั้งแต่เริ่ม development ไม่ใช่รอตอน deploy ทำได้โดย IDE Integration ใช้ Snyk plugin ใน VS Code/IntelliJ สแกน real-time, Pre-commit hooks สแกน secrets ก่อน commit (gitleaks, detect-secrets), Pull Request checks สแกน code และ dependencies ทุก PR, Container scanning สแกน image ก่อน push to registry, IaC scanning สแกน Terraform/Kubernetes configs, Security training สอนทีม dev เกี่ยวกับ OWASP Top 10 ผลลัพธ์ ค้นพบ bugs เร็วขึ้น แก้ถูกกว่า ปลอดภัยกว่า
Q: Supply chain attack ป้องกันอย่างไร?
A: Supply chain attack โจมตีผ่าน dependencies ที่ใช้ใน project ป้องกันได้โดย Lock files ใช้ package-lock.json, Pipfile.lock ล็อก versions, Dependency scanning ใช้ Snyk/Dependabot สแกนทุก dependency, Vendoring copy dependencies เข้า project ไม่ดึงจาก registry ตรงๆ, Private registry ใช้ Artifactory/Nexus เป็น proxy กรอง packages, Signature verification ตรวจสอบ signatures ของ packages, Minimal dependencies ใช้ dependencies เท่าที่จำเป็น ลด attack surface, SBOM (Software Bill of Materials) รู้ว่าใช้อะไรบ้าง track ได้ง่ายเมื่อมี vulnerability ใหม่
