Security: patchmemory/scidk

Security

docs/SECURITY.md

SciDK Security Guide

This guide covers the security architecture, best practices, compliance considerations, and incident response procedures for SciDK deployments.

⚠️ Status: implemented vs. recommended. This guide documents both controls that are implemented today and controls that are recommended / not yet implemented. Treat unmarked best-practice snippets (nginx, OS, compliance, monitoring) as deployment recommendations, not descriptions of current behavior. For the current security posture of the running app — including what is safe for single-user development vs. multi-user production — see SECURITY_HARDENING.md.

Implemented today: session-based login with bcrypt password hashing (scidk/core/auth.py), role-based access control with @require_role/@require_admin (scidk/web/decorators.py), per-user API tokens (Authorization: Bearer), the auth_users / auth_audit_log / auth_sessions tables, audit logging, manual session lock/unlock with auto-lock after inactivity, and Fernet-encrypted credentials in AlertManager/ConfigManager/API-endpoint registry and plugin settings (scidk/core/plugin_settings.py).

Recommended / not yet implemented:SESSION_COOKIE_SECURE / SESSION_COOKIE_HTTPONLY / SESSION_COOKIE_SAMESITE config, CSRF protection, password complexity enforcement, brute-force/lockout protection, and password reset or change (see inline notes below).

Only two roles exist: admin and userauth_users enforces CHECK (role IN ('admin', 'user')) (scidk/core/auth.py:60), and require_role(*allowed_roles) is a flat membership test (scidk/web/decorators.py:94), not a hierarchy. "Any authenticated user" is @require_role('admin', 'user'); naming a role that does not exist locks out everyone including admins.

Verified against the code on 2026-08-04 (Cycle 5, Task C). The plugin_settings.py encryption is genuine cryptography.fernet.Fernet, not a placeholder — confirmed by the Cycle 2 audit and re-checked here; do not reintroduce a note claiming otherwise.

Security Architecture Overview

SciDK implements defense-in-depth security with multiple layers of protection:

  1. Authentication & Authorization: Multi-user authentication with role-based access control (RBAC)
  2. Data Encryption: Encryption at rest and in transit
  3. Audit Logging: Comprehensive audit trails for all system activities
  4. Session Management: Secure session handling with timeout controls
  5. Input Validation: Protection against injection attacks
  6. Secure Configuration: Encrypted credential storage

Authentication and Authorization

User Authentication

SciDK supports session-based authentication with the following features:

Password Security:

  • Passwords hashed using bcrypt with salt
  • Minimum password complexity requirements ⚠️recommended / not yet implemented — nothing in scidk/ enforces a length or complexity rule
  • Protection against brute force attacks ⚠️recommended / not yet implemented — failed attempts are recorded in auth_audit_log but there is no rate limit and no account lockout
  • Secure password reset mechanisms ⚠️recommended / not yet implemented — there is no password reset or change path; an admin recreates the user

Session Management:

  • Session-based authentication, plus per-user API tokens via Authorization: Bearer
  • Session validity is 24 hours (AuthManager.create_session(duration_hours=24)), not a short inactivity timeout. The 30-minute figure below is a recommendation, not current behavior
  • Auto-lock after inactivity — implemented; a locked session answers 423 Locked until the password is re-entered (scidk/web/auth_middleware.py)
  • Session invalidation on logout
  • CSRF protection and secure-cookie flags (SESSION_COOKIE_SECURE/HTTPONLY/SAMESITE) ⚠️recommended / not yet implemented — no SESSION_COOKIE_* config or CSRF extension appears anywhere in scidk/

Example: Enabling Authentication⚠️illustrative only — the dict below is not a shape SciDK reads. Authentication is enabled through the Settings UI / auth_users table; session_timeout, password_min_length and require_complex_password are not consulted by any code path:

# ILLUSTRATIVE — not a supported config shape (see note above)auth_config= {
"enabled": True,
"session_timeout": 1800, # NOT read; sessions last duration_hours=24"password_min_length": 8, # NOT read; no length enforcement exists"require_complex_password": True# NOT read; no complexity enforcement exists
}

Role-Based Access Control (RBAC)

SciDK implements RBAC with the following roles:

Admin Role:

  • Full system access
  • User management capabilities
  • Settings configuration
  • Backup and restore operations
  • Security configuration

User Role:

  • Standard feature access
  • File browsing and searching
  • Graph visualization
  • Chat interface
  • Data exploration

Permissions Enforcement:

# Example permission check (internal)@require_role('admin')defdelete_user(user_id):
# Only admins can delete userspass

Creating Secure User Accounts

Best Practices:

  1. Use strong, unique passwords (minimum 12 characters)
  2. Enable multi-factor authentication (if available)
  3. Limit admin accounts to necessary personnel
  4. Regular password rotation (every 90 days)
  5. Disable or remove unused accounts

Example: Creating Admin User:

# Via Python script
python3 -c "from scidk.core.auth import create_usercreate_user('admin', 'SecurePassword123!', role='admin')"

Data Encryption

Encryption at Rest

SQLite Database:

  • File-level encryption using OS filesystem encryption
  • Sensitive data (passwords, API keys) encrypted using Fernet (symmetric encryption)
  • Encryption keys stored securely (not in version control)

Neo4j Database:

  • Enterprise Edition supports transparent data encryption
  • Community Edition: Use filesystem-level encryption

Example: Filesystem Encryption (Linux):

# LUKS encryption for data partition
sudo cryptsetup luksFormat /dev/sdb1
sudo cryptsetup luksOpen /dev/sdb1 encrypted_data
sudo mkfs.ext4 /dev/mapper/encrypted_data
sudo mount /dev/mapper/encrypted_data /var/lib/scidk

Backup Encryption:

# Encrypt backups with GPG
gpg --symmetric --cipher-algo AES256 backup.db

Encryption in Transit

HTTPS/TLS: All production deployments should use HTTPS:

# nginx configurationserver{listen443ssl http2;ssl_certificate /etc/ssl/certs/scidk.crt;ssl_certificate_key /etc/ssl/private/scidk.key; # Strong SSL configurationssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';ssl_prefer_server_ciphers on; # HSTSadd_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;}

Neo4j TLS: Configure Neo4j to use encrypted Bolt connections:

# neo4j.conf
dbms.connector.bolt.tls_level=REQUIRED
dbms.ssl.policy.bolt.enabled=true
dbms.ssl.policy.bolt.base_directory=certificates/bolt

API Communication:

  • All API endpoints should be accessed via HTTPS
  • Credentials never transmitted in plain text
  • Bearer tokens or session cookies for authentication

Audit Logging

Audit Trail Features

SciDK maintains comprehensive audit logs for:

  1. User Authentication Events:

    • Login attempts (success/failure)
    • Logout events
    • Session expiration
    • Password changes
  2. Data Access Events:

    • File access and downloads
    • Dataset queries
    • Graph queries
    • Export operations
  3. Administrative Actions:

    • User creation/modification/deletion
    • Settings changes
    • Backup operations
    • System configuration changes
  4. Security Events:

    • Failed authentication attempts
    • Permission denied errors
    • Suspicious activity patterns

Audit Log Format

{
"timestamp": "2024-01-15T10:30:00Z",
"event_type": "user.login",
"user": "admin",
"ip_address": "192.168.1.100",
"user_agent": "Mozilla/5.0...",
"status": "success",
"details": {
"session_id": "sess_abc123"
}
}

Accessing Audit Logs

Via systemd journals:

sudo journalctl -u scidk | grep AUDIT

Via SQLite database — the table is auth_audit_log in scidk_settings.db, and timestamp is a REAL epoch-seconds value, not a SQLite datetime string:

SELECTtimestamp, username, action, details, ip_address
FROM auth_audit_log
WHEREtimestamp> strftime('%s', 'now', '-7 days')
ORDER BYtimestampDESC;

Audit Log Retention

Recommended Retention Policies:

  • Security events: 1 year minimum
  • Authentication logs: 90 days minimum
  • Administrative actions: 1 year minimum
  • Data access: 30-90 days (or per compliance requirements)

Configure retention:

# systemd journal retention
sudo journalctl --vacuum-time=365d

Security Best Practices

Deployment Security

1. Network Security:

  • Deploy behind firewall
  • Use private networks for database connections
  • Limit exposed ports (only 443/80 for web, 7687 for internal Neo4j)
  • Implement IP allowlisting for admin access

Example firewall rules (ufw):

# Allow HTTPS
sudo ufw allow 443/tcp
# Allow Neo4j only from app server
sudo ufw allow from 10.0.1.10 to any port 7687
# Deny all other incoming
sudo ufw default deny incoming
sudo ufw enable

2. Operating System Security:

  • Keep OS and packages updated
  • Use dedicated service account (non-root)
  • Disable unnecessary services
  • Configure SELinux/AppArmor policies

3. Database Security:

  • Change default passwords immediately
  • Use strong authentication credentials
  • Regular security patches and updates
  • Database access restricted to application only

4. Application Security:

  • Run as non-privileged user
  • Use virtual environment isolation
  • Keep dependencies updated
  • Regular security scanning

Credential Management

Best Practices:

  1. Never commit credentials to version control
  2. Use environment variables or secret management systems
  3. Rotate credentials regularly (every 90 days)
  4. Use different credentials for dev/test/prod
  5. Encrypt credentials at rest

Example: Secret Management:

# Use environment variablesexport NEO4J_PASSWORD=$(vault read -field=password secret/neo4j)# Or use .env file (not in git)echo"NEO4J_AUTH=neo4j/$(openssl rand -base64 32)">> .env
chmod 600 .env

Credential Storage:

  • SciDK stores encrypted credentials in SQLite. Fernet (symmetric) encryption is used for SMTP/alert credentials, config-manager secrets, API-endpoint auth tokens, and plugin settings (scidk/core/plugin_settings.py).
  • Encryption key should be stored separately
  • Consider using external secret managers (HashiCorp Vault, AWS Secrets Manager)

Input Validation

SciDK implements input validation to prevent:

SQL Injection:

  • Parameterized queries for all database access
  • ORM-based database interactions
  • Input sanitization

Command Injection:

  • No shell command construction from user input
  • Subprocess calls use argument arrays (not shell=True)
  • Path validation for filesystem operations

Cross-Site Scripting (XSS):

  • HTML escaping in templates
  • Content Security Policy headers
  • Input sanitization

Path Traversal:

  • Path normalization
  • Validation against allowed directories
  • No direct user input in file paths

Session Security

Configuration⚠️Recommended / not yet implemented — the app does not currently set these cookie flags or enable CSRF protection; the snippet below is the recommended hardening to apply before multi-user production use:

# Flask session configuration (RECOMMENDED — not currently set in code)app.config.update(
SESSION_COOKIE_SECURE=True, # HTTPS onlySESSION_COOKIE_HTTPONLY=True, # No JavaScript accessSESSION_COOKIE_SAMESITE='Lax', # CSRF protectionPERMANENT_SESSION_LIFETIME=1800# 30 minutes
)

Session Management:

  • Automatic session expiration
  • Session invalidation on logout
  • Session regeneration after privilege escalation
  • Single sign-on support (if configured)

Secure Headers

Recommended HTTP Security Headers:

# nginx configurationadd_header X-Frame-Options "SAMEORIGIN" always;add_header X-Content-Type-Options "nosniff" always;add_header X-XSS-Protection "1; mode=block" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Compliance Considerations

HIPAA Compliance

For healthcare data:

Required Controls:

  1. Access Control: RBAC with unique user accounts
  2. Audit Controls: Comprehensive audit logging
  3. Integrity Controls: Data validation and checksums
  4. Transmission Security: TLS/HTTPS for all communications
  5. Authentication: Strong password policies
  6. Encryption: Data encryption at rest and in transit

BAA Requirements:

  • Ensure Business Associate Agreement with cloud providers
  • Document security policies and procedures
  • Regular security risk assessments
  • Incident response procedures

PHI Handling:

  • Minimize PHI exposure
  • De-identify data when possible
  • Secure disposal procedures
  • Access logging for all PHI

GDPR Compliance

For European data:

Right to Access:

  • Provide user data export functionality
  • API endpoints for data retrieval

Right to Erasure:

  • User deletion removes all associated data
  • Cascade delete for related records
  • Audit log of deletions (without retaining PII)

Right to Portability:

  • Export in machine-readable format (JSON, CSV)
  • Configuration backup/export functionality

Data Protection:

  • Encryption at rest and in transit
  • Access controls and audit logs
  • Privacy by design and default
  • Data minimization

Breach Notification:

  • 72-hour breach notification requirement
  • Incident response procedures
  • Contact data protection authorities

SOC 2 Compliance

For service organizations:

Trust Services Criteria:

  1. Security: Access controls, encryption, monitoring
  2. Availability: Uptime, redundancy, disaster recovery
  3. Processing Integrity: Data validation, error handling
  4. Confidentiality: Encryption, access controls
  5. Privacy: Data handling, consent management

Implementation:

  • Document security policies
  • Regular security assessments
  • Vendor management
  • Change management procedures
  • Incident response plan

Vulnerability Management

Security Updates

Update Process:

  1. Monitor security advisories for dependencies
  2. Test updates in staging environment
  3. Schedule maintenance window
  4. Apply updates and verify
  5. Document changes

Automated Scanning:

# Scan Python dependencies
pip install safety
safety check
# Scan for vulnerabilities
npm audit # If using Node.js tools

Penetration Testing

Recommended Schedule:

  • Annual penetration testing
  • After major releases
  • Before compliance audits

Testing Scope:

  • Web application security
  • API security
  • Authentication mechanisms
  • Database security
  • Network security

Responsible Disclosure

Security Issue Reporting:

  • Email: security@your-org.com
  • PGP key available for encrypted reports
  • Expected response time: 48 hours
  • Coordinated disclosure policy

Incident Response

Incident Response Plan

Phase 1: Detection

  • Monitor audit logs for suspicious activity
  • Alert system for security events
  • User reports of suspicious behavior

Phase 2: Containment

  • Isolate affected systems
  • Disable compromised accounts
  • Block malicious IP addresses
  • Preserve evidence

Phase 3: Eradication

  • Identify root cause
  • Remove malicious code/access
  • Patch vulnerabilities
  • Reset compromised credentials

Phase 4: Recovery

  • Restore from clean backups
  • Verify system integrity
  • Monitor for recurrence
  • Gradual service restoration

Phase 5: Lessons Learned

  • Document incident timeline
  • Identify improvements
  • Update procedures
  • Train personnel

Incident Response Procedures

Security Breach Response:

# 1. Isolate the system
sudo systemctl stop scidk
sudo ufw deny from suspicious_ip
# 2. Preserve evidence
sudo journalctl -u scidk > incident_logs.txt
cp ~/.scidk/db/files.db incident_db_$(date +%Y%m%d).backup
# 3. Reset credentials
./scripts/reset_all_passwords.sh
# 4. Restore from known good backup
cp ~/.scidk/db/files.db.verified ~/.scidk/db/files.db
# 5. Restart with monitoring
sudo systemctl start scidk
tail -f /var/log/syslog | grep scidk

Data Breach Response:

  1. Determine scope: What data was accessed?
  2. Notify affected parties (per regulations)
  3. Document the breach
  4. Report to authorities (if required)
  5. Implement additional controls

Incident Communication

Internal Communication:

  • Notify security team immediately
  • Escalate to management within 1 hour
  • Brief technical team on containment

External Communication:

  • Notify affected users (if PII compromised)
  • Regulatory notification (if required)
  • Public disclosure (if significant breach)

Communication Template:

Subject: Security Incident Notification
We are writing to inform you of a security incident that occurred on [date].
Incident Type: [Unauthorized access / Data breach / etc.]
Data Affected: [Description]
Actions Taken: [Containment, investigation, etc.]
User Actions Required: [Password reset, etc.]
We take security seriously and have implemented additional measures...

Security Monitoring

Real-Time Monitoring

Monitor for:

  • Failed login attempts (>5 in 5 minutes)
  • Unusual access patterns
  • Large data exports
  • Configuration changes
  • Database connection errors

Alert Configuration:

# Example alert rulealert_rules= {
"failed_logins": {
"condition": "count > 5 in 5 minutes",
"action": "email_admin",
"severity": "high"
}
}

Security Metrics

Track:

  • Authentication success/failure rate
  • Average session duration
  • API error rates
  • Disk space usage
  • Database connection pool status

Log Analysis

Regular Reviews:

  • Daily: Security event review
  • Weekly: Authentication pattern analysis
  • Monthly: Comprehensive security audit
  • Quarterly: Access control review
# Example log analysis# Failed logins
sudo journalctl -u scidk | grep "LOGIN_FAILED"| wc -l
# Unique IP addresses
sudo journalctl -u scidk | grep "LOGIN"| awk '{print $X}'| sort -u | wc -l

Security Checklist

Deployment Security Checklist

  • Change all default passwords
  • Enable HTTPS with valid certificates
  • Configure firewall rules
  • Enable authentication and RBAC
  • Set strong session timeout
  • Enable audit logging
  • Encrypt sensitive data at rest
  • Configure secure backup procedures
  • Set up security monitoring and alerts
  • Document incident response procedures
  • Perform security assessment
  • Train administrators on security procedures

Monthly Security Review

  • Review audit logs for anomalies
  • Check for security updates
  • Verify backup integrity
  • Review user accounts and permissions
  • Test disaster recovery procedures
  • Review alert configurations
  • Update documentation

Additional Resources

There aren't any published security advisories

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content

Security: patchmemory/scidk

Security

docs/SECURITY.md

SciDK Security Guide

This guide covers the security architecture, best practices, compliance considerations, and incident response procedures for SciDK deployments.

⚠️ Status: implemented vs. recommended. This guide documents both controls that are implemented today and controls that are recommended / not yet implemented. Treat unmarked best-practice snippets (nginx, OS, compliance, monitoring) as deployment recommendations, not descriptions of current behavior. For the current security posture of the running app — including what is safe for single-user development vs. multi-user production — see SECURITY_HARDENING.md.

Implemented today: session-based login with bcrypt password hashing (scidk/core/auth.py), role-based access control with @require_role/@require_admin (scidk/web/decorators.py), per-user API tokens (Authorization: Bearer), the auth_users / auth_audit_log / auth_sessions tables, audit logging, manual session lock/unlock with auto-lock after inactivity, and Fernet-encrypted credentials in AlertManager/ConfigManager/API-endpoint registry and plugin settings (scidk/core/plugin_settings.py).

Recommended / not yet implemented:SESSION_COOKIE_SECURE / SESSION_COOKIE_HTTPONLY / SESSION_COOKIE_SAMESITE config, CSRF protection, password complexity enforcement, brute-force/lockout protection, and password reset or change (see inline notes below).

Only two roles exist: admin and userauth_users enforces CHECK (role IN ('admin', 'user')) (scidk/core/auth.py:60), and require_role(*allowed_roles) is a flat membership test (scidk/web/decorators.py:94), not a hierarchy. "Any authenticated user" is @require_role('admin', 'user'); naming a role that does not exist locks out everyone including admins.

Verified against the code on 2026-08-04 (Cycle 5, Task C). The plugin_settings.py encryption is genuine cryptography.fernet.Fernet, not a placeholder — confirmed by the Cycle 2 audit and re-checked here; do not reintroduce a note claiming otherwise.

Security Architecture Overview

SciDK implements defense-in-depth security with multiple layers of protection:

  1. Authentication & Authorization: Multi-user authentication with role-based access control (RBAC)
  2. Data Encryption: Encryption at rest and in transit
  3. Audit Logging: Comprehensive audit trails for all system activities
  4. Session Management: Secure session handling with timeout controls
  5. Input Validation: Protection against injection attacks
  6. Secure Configuration: Encrypted credential storage

Authentication and Authorization

User Authentication

SciDK supports session-based authentication with the following features:

Password Security:

  • Passwords hashed using bcrypt with salt
  • Minimum password complexity requirements ⚠️recommended / not yet implemented — nothing in scidk/ enforces a length or complexity rule
  • Protection against brute force attacks ⚠️recommended / not yet implemented — failed attempts are recorded in auth_audit_log but there is no rate limit and no account lockout
  • Secure password reset mechanisms ⚠️recommended / not yet implemented — there is no password reset or change path; an admin recreates the user

Session Management:

  • Session-based authentication, plus per-user API tokens via Authorization: Bearer
  • Session validity is 24 hours (AuthManager.create_session(duration_hours=24)), not a short inactivity timeout. The 30-minute figure below is a recommendation, not current behavior
  • Auto-lock after inactivity — implemented; a locked session answers 423 Locked until the password is re-entered (scidk/web/auth_middleware.py)
  • Session invalidation on logout
  • CSRF protection and secure-cookie flags (SESSION_COOKIE_SECURE/HTTPONLY/SAMESITE) ⚠️recommended / not yet implemented — no SESSION_COOKIE_* config or CSRF extension appears anywhere in scidk/

Example: Enabling Authentication⚠️illustrative only — the dict below is not a shape SciDK reads. Authentication is enabled through the Settings UI / auth_users table; session_timeout, password_min_length and require_complex_password are not consulted by any code path:

# ILLUSTRATIVE — not a supported config shape (see note above)auth_config= {
"enabled": True,
"session_timeout": 1800, # NOT read; sessions last duration_hours=24"password_min_length": 8, # NOT read; no length enforcement exists"require_complex_password": True# NOT read; no complexity enforcement exists
}

Role-Based Access Control (RBAC)

SciDK implements RBAC with the following roles:

Admin Role:

  • Full system access
  • User management capabilities
  • Settings configuration
  • Backup and restore operations
  • Security configuration

User Role:

  • Standard feature access
  • File browsing and searching
  • Graph visualization
  • Chat interface
  • Data exploration

Permissions Enforcement:

# Example permission check (internal)@require_role('admin')defdelete_user(user_id):
# Only admins can delete userspass

Creating Secure User Accounts

Best Practices:

  1. Use strong, unique passwords (minimum 12 characters)
  2. Enable multi-factor authentication (if available)
  3. Limit admin accounts to necessary personnel
  4. Regular password rotation (every 90 days)
  5. Disable or remove unused accounts

Example: Creating Admin User:

# Via Python script
python3 -c "from scidk.core.auth import create_usercreate_user('admin', 'SecurePassword123!', role='admin')"

Data Encryption

Encryption at Rest

SQLite Database:

  • File-level encryption using OS filesystem encryption
  • Sensitive data (passwords, API keys) encrypted using Fernet (symmetric encryption)
  • Encryption keys stored securely (not in version control)

Neo4j Database:

  • Enterprise Edition supports transparent data encryption
  • Community Edition: Use filesystem-level encryption

Example: Filesystem Encryption (Linux):

# LUKS encryption for data partition
sudo cryptsetup luksFormat /dev/sdb1
sudo cryptsetup luksOpen /dev/sdb1 encrypted_data
sudo mkfs.ext4 /dev/mapper/encrypted_data
sudo mount /dev/mapper/encrypted_data /var/lib/scidk

Backup Encryption:

# Encrypt backups with GPG
gpg --symmetric --cipher-algo AES256 backup.db

Encryption in Transit

HTTPS/TLS: All production deployments should use HTTPS:

# nginx configurationserver{listen443ssl http2;ssl_certificate /etc/ssl/certs/scidk.crt;ssl_certificate_key /etc/ssl/private/scidk.key; # Strong SSL configurationssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';ssl_prefer_server_ciphers on; # HSTSadd_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;}

Neo4j TLS: Configure Neo4j to use encrypted Bolt connections:

# neo4j.conf
dbms.connector.bolt.tls_level=REQUIRED
dbms.ssl.policy.bolt.enabled=true
dbms.ssl.policy.bolt.base_directory=certificates/bolt

API Communication:

  • All API endpoints should be accessed via HTTPS
  • Credentials never transmitted in plain text
  • Bearer tokens or session cookies for authentication

Audit Logging

Audit Trail Features

SciDK maintains comprehensive audit logs for:

  1. User Authentication Events:

    • Login attempts (success/failure)
    • Logout events
    • Session expiration
    • Password changes
  2. Data Access Events:

    • File access and downloads
    • Dataset queries
    • Graph queries
    • Export operations
  3. Administrative Actions:

    • User creation/modification/deletion
    • Settings changes
    • Backup operations
    • System configuration changes
  4. Security Events:

    • Failed authentication attempts
    • Permission denied errors
    • Suspicious activity patterns

Audit Log Format

{
"timestamp": "2024-01-15T10:30:00Z",
"event_type": "user.login",
"user": "admin",
"ip_address": "192.168.1.100",
"user_agent": "Mozilla/5.0...",
"status": "success",
"details": {
"session_id": "sess_abc123"
}
}

Accessing Audit Logs

Via systemd journals:

sudo journalctl -u scidk | grep AUDIT

Via SQLite database — the table is auth_audit_log in scidk_settings.db, and timestamp is a REAL epoch-seconds value, not a SQLite datetime string:

SELECTtimestamp, username, action, details, ip_address
FROM auth_audit_log
WHEREtimestamp> strftime('%s', 'now', '-7 days')
ORDER BYtimestampDESC;

Audit Log Retention

Recommended Retention Policies:

  • Security events: 1 year minimum
  • Authentication logs: 90 days minimum
  • Administrative actions: 1 year minimum
  • Data access: 30-90 days (or per compliance requirements)

Configure retention:

# systemd journal retention
sudo journalctl --vacuum-time=365d

Security Best Practices

Deployment Security

1. Network Security:

  • Deploy behind firewall
  • Use private networks for database connections
  • Limit exposed ports (only 443/80 for web, 7687 for internal Neo4j)
  • Implement IP allowlisting for admin access

Example firewall rules (ufw):

# Allow HTTPS
sudo ufw allow 443/tcp
# Allow Neo4j only from app server
sudo ufw allow from 10.0.1.10 to any port 7687
# Deny all other incoming
sudo ufw default deny incoming
sudo ufw enable

2. Operating System Security:

  • Keep OS and packages updated
  • Use dedicated service account (non-root)
  • Disable unnecessary services
  • Configure SELinux/AppArmor policies

3. Database Security:

  • Change default passwords immediately
  • Use strong authentication credentials
  • Regular security patches and updates
  • Database access restricted to application only

4. Application Security:

  • Run as non-privileged user
  • Use virtual environment isolation
  • Keep dependencies updated
  • Regular security scanning

Credential Management

Best Practices:

  1. Never commit credentials to version control
  2. Use environment variables or secret management systems
  3. Rotate credentials regularly (every 90 days)
  4. Use different credentials for dev/test/prod
  5. Encrypt credentials at rest

Example: Secret Management:

# Use environment variablesexport NEO4J_PASSWORD=$(vault read -field=password secret/neo4j)# Or use .env file (not in git)echo"NEO4J_AUTH=neo4j/$(openssl rand -base64 32)">> .env
chmod 600 .env

Credential Storage:

  • SciDK stores encrypted credentials in SQLite. Fernet (symmetric) encryption is used for SMTP/alert credentials, config-manager secrets, API-endpoint auth tokens, and plugin settings (scidk/core/plugin_settings.py).
  • Encryption key should be stored separately
  • Consider using external secret managers (HashiCorp Vault, AWS Secrets Manager)

Input Validation

SciDK implements input validation to prevent:

SQL Injection:

  • Parameterized queries for all database access
  • ORM-based database interactions
  • Input sanitization

Command Injection:

  • No shell command construction from user input
  • Subprocess calls use argument arrays (not shell=True)
  • Path validation for filesystem operations

Cross-Site Scripting (XSS):

  • HTML escaping in templates
  • Content Security Policy headers
  • Input sanitization

Path Traversal:

  • Path normalization
  • Validation against allowed directories
  • No direct user input in file paths

Session Security

Configuration⚠️Recommended / not yet implemented — the app does not currently set these cookie flags or enable CSRF protection; the snippet below is the recommended hardening to apply before multi-user production use:

# Flask session configuration (RECOMMENDED — not currently set in code)app.config.update(
SESSION_COOKIE_SECURE=True, # HTTPS onlySESSION_COOKIE_HTTPONLY=True, # No JavaScript accessSESSION_COOKIE_SAMESITE='Lax', # CSRF protectionPERMANENT_SESSION_LIFETIME=1800# 30 minutes
)

Session Management:

  • Automatic session expiration
  • Session invalidation on logout
  • Session regeneration after privilege escalation
  • Single sign-on support (if configured)

Secure Headers

Recommended HTTP Security Headers:

# nginx configurationadd_header X-Frame-Options "SAMEORIGIN" always;add_header X-Content-Type-Options "nosniff" always;add_header X-XSS-Protection "1; mode=block" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Compliance Considerations

HIPAA Compliance

For healthcare data:

Required Controls:

  1. Access Control: RBAC with unique user accounts
  2. Audit Controls: Comprehensive audit logging
  3. Integrity Controls: Data validation and checksums
  4. Transmission Security: TLS/HTTPS for all communications
  5. Authentication: Strong password policies
  6. Encryption: Data encryption at rest and in transit

BAA Requirements:

  • Ensure Business Associate Agreement with cloud providers
  • Document security policies and procedures
  • Regular security risk assessments
  • Incident response procedures

PHI Handling:

  • Minimize PHI exposure
  • De-identify data when possible
  • Secure disposal procedures
  • Access logging for all PHI

GDPR Compliance

For European data:

Right to Access:

  • Provide user data export functionality
  • API endpoints for data retrieval

Right to Erasure:

  • User deletion removes all associated data
  • Cascade delete for related records
  • Audit log of deletions (without retaining PII)

Right to Portability:

  • Export in machine-readable format (JSON, CSV)
  • Configuration backup/export functionality

Data Protection:

  • Encryption at rest and in transit
  • Access controls and audit logs
  • Privacy by design and default
  • Data minimization

Breach Notification:

  • 72-hour breach notification requirement
  • Incident response procedures
  • Contact data protection authorities

SOC 2 Compliance

For service organizations:

Trust Services Criteria:

  1. Security: Access controls, encryption, monitoring
  2. Availability: Uptime, redundancy, disaster recovery
  3. Processing Integrity: Data validation, error handling
  4. Confidentiality: Encryption, access controls
  5. Privacy: Data handling, consent management

Implementation:

  • Document security policies
  • Regular security assessments
  • Vendor management
  • Change management procedures
  • Incident response plan

Vulnerability Management

Security Updates

Update Process:

  1. Monitor security advisories for dependencies
  2. Test updates in staging environment
  3. Schedule maintenance window
  4. Apply updates and verify
  5. Document changes

Automated Scanning:

# Scan Python dependencies
pip install safety
safety check
# Scan for vulnerabilities
npm audit # If using Node.js tools

Penetration Testing

Recommended Schedule:

  • Annual penetration testing
  • After major releases
  • Before compliance audits

Testing Scope:

  • Web application security
  • API security
  • Authentication mechanisms
  • Database security
  • Network security

Responsible Disclosure

Security Issue Reporting:

  • Email: security@your-org.com
  • PGP key available for encrypted reports
  • Expected response time: 48 hours
  • Coordinated disclosure policy

Incident Response

Incident Response Plan

Phase 1: Detection

  • Monitor audit logs for suspicious activity
  • Alert system for security events
  • User reports of suspicious behavior

Phase 2: Containment

  • Isolate affected systems
  • Disable compromised accounts
  • Block malicious IP addresses
  • Preserve evidence

Phase 3: Eradication

  • Identify root cause
  • Remove malicious code/access
  • Patch vulnerabilities
  • Reset compromised credentials

Phase 4: Recovery

  • Restore from clean backups
  • Verify system integrity
  • Monitor for recurrence
  • Gradual service restoration

Phase 5: Lessons Learned

  • Document incident timeline
  • Identify improvements
  • Update procedures
  • Train personnel

Incident Response Procedures

Security Breach Response:

# 1. Isolate the system
sudo systemctl stop scidk
sudo ufw deny from suspicious_ip
# 2. Preserve evidence
sudo journalctl -u scidk > incident_logs.txt
cp ~/.scidk/db/files.db incident_db_$(date +%Y%m%d).backup
# 3. Reset credentials
./scripts/reset_all_passwords.sh
# 4. Restore from known good backup
cp ~/.scidk/db/files.db.verified ~/.scidk/db/files.db
# 5. Restart with monitoring
sudo systemctl start scidk
tail -f /var/log/syslog | grep scidk

Data Breach Response:

  1. Determine scope: What data was accessed?
  2. Notify affected parties (per regulations)
  3. Document the breach
  4. Report to authorities (if required)
  5. Implement additional controls

Incident Communication

Internal Communication:

  • Notify security team immediately
  • Escalate to management within 1 hour
  • Brief technical team on containment

External Communication:

  • Notify affected users (if PII compromised)
  • Regulatory notification (if required)
  • Public disclosure (if significant breach)

Communication Template:

Subject: Security Incident Notification
We are writing to inform you of a security incident that occurred on [date].
Incident Type: [Unauthorized access / Data breach / etc.]
Data Affected: [Description]
Actions Taken: [Containment, investigation, etc.]
User Actions Required: [Password reset, etc.]
We take security seriously and have implemented additional measures...

Security Monitoring

Real-Time Monitoring

Monitor for:

  • Failed login attempts (>5 in 5 minutes)
  • Unusual access patterns
  • Large data exports
  • Configuration changes
  • Database connection errors

Alert Configuration:

# Example alert rulealert_rules= {
"failed_logins": {
"condition": "count > 5 in 5 minutes",
"action": "email_admin",
"severity": "high"
}
}

Security Metrics

Track:

  • Authentication success/failure rate
  • Average session duration
  • API error rates
  • Disk space usage
  • Database connection pool status

Log Analysis

Regular Reviews:

  • Daily: Security event review
  • Weekly: Authentication pattern analysis
  • Monthly: Comprehensive security audit
  • Quarterly: Access control review
# Example log analysis# Failed logins
sudo journalctl -u scidk | grep "LOGIN_FAILED"| wc -l
# Unique IP addresses
sudo journalctl -u scidk | grep "LOGIN"| awk '{print $X}'| sort -u | wc -l

Security Checklist

Deployment Security Checklist

  • Change all default passwords
  • Enable HTTPS with valid certificates
  • Configure firewall rules
  • Enable authentication and RBAC
  • Set strong session timeout
  • Enable audit logging
  • Encrypt sensitive data at rest
  • Configure secure backup procedures
  • Set up security monitoring and alerts
  • Document incident response procedures
  • Perform security assessment
  • Train administrators on security procedures

Monthly Security Review

  • Review audit logs for anomalies
  • Check for security updates
  • Verify backup integrity
  • Review user accounts and permissions
  • Test disaster recovery procedures
  • Review alert configurations
  • Update documentation

Additional Resources

There aren't any published security advisories

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Security: patchmemory/scidk

Security

docs/SECURITY.md

SciDK Security Guide

This guide covers the security architecture, best practices, compliance considerations, and incident response procedures for SciDK deployments.

⚠️ Status: implemented vs. recommended. This guide documents both controls that are implemented today and controls that are recommended / not yet implemented. Treat unmarked best-practice snippets (nginx, OS, compliance, monitoring) as deployment recommendations, not descriptions of current behavior. For the current security posture of the running app — including what is safe for single-user development vs. multi-user production — see SECURITY_HARDENING.md.

Implemented today: session-based login with bcrypt password hashing (scidk/core/auth.py), role-based access control with @require_role/@require_admin (scidk/web/decorators.py), per-user API tokens (Authorization: Bearer), the auth_users / auth_audit_log / auth_sessions tables, audit logging, manual session lock/unlock with auto-lock after inactivity, and Fernet-encrypted credentials in AlertManager/ConfigManager/API-endpoint registry and plugin settings (scidk/core/plugin_settings.py).

Recommended / not yet implemented:SESSION_COOKIE_SECURE / SESSION_COOKIE_HTTPONLY / SESSION_COOKIE_SAMESITE config, CSRF protection, password complexity enforcement, brute-force/lockout protection, and password reset or change (see inline notes below).

Only two roles exist: admin and userauth_users enforces CHECK (role IN ('admin', 'user')) (scidk/core/auth.py:60), and require_role(*allowed_roles) is a flat membership test (scidk/web/decorators.py:94), not a hierarchy. "Any authenticated user" is @require_role('admin', 'user'); naming a role that does not exist locks out everyone including admins.

Verified against the code on 2026-08-04 (Cycle 5, Task C). The plugin_settings.py encryption is genuine cryptography.fernet.Fernet, not a placeholder — confirmed by the Cycle 2 audit and re-checked here; do not reintroduce a note claiming otherwise.

Security Architecture Overview

SciDK implements defense-in-depth security with multiple layers of protection:

  1. Authentication & Authorization: Multi-user authentication with role-based access control (RBAC)
  2. Data Encryption: Encryption at rest and in transit
  3. Audit Logging: Comprehensive audit trails for all system activities
  4. Session Management: Secure session handling with timeout controls
  5. Input Validation: Protection against injection attacks
  6. Secure Configuration: Encrypted credential storage

Authentication and Authorization

User Authentication

SciDK supports session-based authentication with the following features:

Password Security:

  • Passwords hashed using bcrypt with salt
  • Minimum password complexity requirements ⚠️recommended / not yet implemented — nothing in scidk/ enforces a length or complexity rule
  • Protection against brute force attacks ⚠️recommended / not yet implemented — failed attempts are recorded in auth_audit_log but there is no rate limit and no account lockout
  • Secure password reset mechanisms ⚠️recommended / not yet implemented — there is no password reset or change path; an admin recreates the user

Session Management:

  • Session-based authentication, plus per-user API tokens via Authorization: Bearer
  • Session validity is 24 hours (AuthManager.create_session(duration_hours=24)), not a short inactivity timeout. The 30-minute figure below is a recommendation, not current behavior
  • Auto-lock after inactivity — implemented; a locked session answers 423 Locked until the password is re-entered (scidk/web/auth_middleware.py)
  • Session invalidation on logout
  • CSRF protection and secure-cookie flags (SESSION_COOKIE_SECURE/HTTPONLY/SAMESITE) ⚠️recommended / not yet implemented — no SESSION_COOKIE_* config or CSRF extension appears anywhere in scidk/

Example: Enabling Authentication⚠️illustrative only — the dict below is not a shape SciDK reads. Authentication is enabled through the Settings UI / auth_users table; session_timeout, password_min_length and require_complex_password are not consulted by any code path:

# ILLUSTRATIVE — not a supported config shape (see note above)auth_config= {
"enabled": True,
"session_timeout": 1800, # NOT read; sessions last duration_hours=24"password_min_length": 8, # NOT read; no length enforcement exists"require_complex_password": True# NOT read; no complexity enforcement exists
}

Role-Based Access Control (RBAC)

SciDK implements RBAC with the following roles:

Admin Role:

  • Full system access
  • User management capabilities
  • Settings configuration
  • Backup and restore operations
  • Security configuration

User Role:

  • Standard feature access
  • File browsing and searching
  • Graph visualization
  • Chat interface
  • Data exploration

Permissions Enforcement:

# Example permission check (internal)@require_role('admin')defdelete_user(user_id):
# Only admins can delete userspass

Creating Secure User Accounts

Best Practices:

  1. Use strong, unique passwords (minimum 12 characters)
  2. Enable multi-factor authentication (if available)
  3. Limit admin accounts to necessary personnel
  4. Regular password rotation (every 90 days)
  5. Disable or remove unused accounts

Example: Creating Admin User:

# Via Python script
python3 -c "from scidk.core.auth import create_usercreate_user('admin', 'SecurePassword123!', role='admin')"

Data Encryption

Encryption at Rest

SQLite Database:

  • File-level encryption using OS filesystem encryption
  • Sensitive data (passwords, API keys) encrypted using Fernet (symmetric encryption)
  • Encryption keys stored securely (not in version control)

Neo4j Database:

  • Enterprise Edition supports transparent data encryption
  • Community Edition: Use filesystem-level encryption

Example: Filesystem Encryption (Linux):

# LUKS encryption for data partition
sudo cryptsetup luksFormat /dev/sdb1
sudo cryptsetup luksOpen /dev/sdb1 encrypted_data
sudo mkfs.ext4 /dev/mapper/encrypted_data
sudo mount /dev/mapper/encrypted_data /var/lib/scidk

Backup Encryption:

# Encrypt backups with GPG
gpg --symmetric --cipher-algo AES256 backup.db

Encryption in Transit

HTTPS/TLS: All production deployments should use HTTPS:

# nginx configurationserver{listen443ssl http2;ssl_certificate /etc/ssl/certs/scidk.crt;ssl_certificate_key /etc/ssl/private/scidk.key; # Strong SSL configurationssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';ssl_prefer_server_ciphers on; # HSTSadd_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;}

Neo4j TLS: Configure Neo4j to use encrypted Bolt connections:

# neo4j.conf
dbms.connector.bolt.tls_level=REQUIRED
dbms.ssl.policy.bolt.enabled=true
dbms.ssl.policy.bolt.base_directory=certificates/bolt

API Communication:

  • All API endpoints should be accessed via HTTPS
  • Credentials never transmitted in plain text
  • Bearer tokens or session cookies for authentication

Audit Logging

Audit Trail Features

SciDK maintains comprehensive audit logs for:

  1. User Authentication Events:

    • Login attempts (success/failure)
    • Logout events
    • Session expiration
    • Password changes
  2. Data Access Events:

    • File access and downloads
    • Dataset queries
    • Graph queries
    • Export operations
  3. Administrative Actions:

    • User creation/modification/deletion
    • Settings changes
    • Backup operations
    • System configuration changes
  4. Security Events:

    • Failed authentication attempts
    • Permission denied errors
    • Suspicious activity patterns

Audit Log Format

{
"timestamp": "2024-01-15T10:30:00Z",
"event_type": "user.login",
"user": "admin",
"ip_address": "192.168.1.100",
"user_agent": "Mozilla/5.0...",
"status": "success",
"details": {
"session_id": "sess_abc123"
}
}

Accessing Audit Logs

Via systemd journals:

sudo journalctl -u scidk | grep AUDIT

Via SQLite database — the table is auth_audit_log in scidk_settings.db, and timestamp is a REAL epoch-seconds value, not a SQLite datetime string:

SELECTtimestamp, username, action, details, ip_address
FROM auth_audit_log
WHEREtimestamp> strftime('%s', 'now', '-7 days')
ORDER BYtimestampDESC;

Audit Log Retention

Recommended Retention Policies:

  • Security events: 1 year minimum
  • Authentication logs: 90 days minimum
  • Administrative actions: 1 year minimum
  • Data access: 30-90 days (or per compliance requirements)

Configure retention:

# systemd journal retention
sudo journalctl --vacuum-time=365d

Security Best Practices

Deployment Security

1. Network Security:

  • Deploy behind firewall
  • Use private networks for database connections
  • Limit exposed ports (only 443/80 for web, 7687 for internal Neo4j)
  • Implement IP allowlisting for admin access

Example firewall rules (ufw):

# Allow HTTPS
sudo ufw allow 443/tcp
# Allow Neo4j only from app server
sudo ufw allow from 10.0.1.10 to any port 7687
# Deny all other incoming
sudo ufw default deny incoming
sudo ufw enable

2. Operating System Security:

  • Keep OS and packages updated
  • Use dedicated service account (non-root)
  • Disable unnecessary services
  • Configure SELinux/AppArmor policies

3. Database Security:

  • Change default passwords immediately
  • Use strong authentication credentials
  • Regular security patches and updates
  • Database access restricted to application only

4. Application Security:

  • Run as non-privileged user
  • Use virtual environment isolation
  • Keep dependencies updated
  • Regular security scanning

Credential Management

Best Practices:

  1. Never commit credentials to version control
  2. Use environment variables or secret management systems
  3. Rotate credentials regularly (every 90 days)
  4. Use different credentials for dev/test/prod
  5. Encrypt credentials at rest

Example: Secret Management:

# Use environment variablesexport NEO4J_PASSWORD=$(vault read -field=password secret/neo4j)# Or use .env file (not in git)echo"NEO4J_AUTH=neo4j/$(openssl rand -base64 32)">> .env
chmod 600 .env

Credential Storage:

  • SciDK stores encrypted credentials in SQLite. Fernet (symmetric) encryption is used for SMTP/alert credentials, config-manager secrets, API-endpoint auth tokens, and plugin settings (scidk/core/plugin_settings.py).
  • Encryption key should be stored separately
  • Consider using external secret managers (HashiCorp Vault, AWS Secrets Manager)

Input Validation

SciDK implements input validation to prevent:

SQL Injection:

  • Parameterized queries for all database access
  • ORM-based database interactions
  • Input sanitization

Command Injection:

  • No shell command construction from user input
  • Subprocess calls use argument arrays (not shell=True)
  • Path validation for filesystem operations

Cross-Site Scripting (XSS):

  • HTML escaping in templates
  • Content Security Policy headers
  • Input sanitization

Path Traversal:

  • Path normalization
  • Validation against allowed directories
  • No direct user input in file paths

Session Security

Configuration⚠️Recommended / not yet implemented — the app does not currently set these cookie flags or enable CSRF protection; the snippet below is the recommended hardening to apply before multi-user production use:

# Flask session configuration (RECOMMENDED — not currently set in code)app.config.update(
SESSION_COOKIE_SECURE=True, # HTTPS onlySESSION_COOKIE_HTTPONLY=True, # No JavaScript accessSESSION_COOKIE_SAMESITE='Lax', # CSRF protectionPERMANENT_SESSION_LIFETIME=1800# 30 minutes
)

Session Management:

  • Automatic session expiration
  • Session invalidation on logout
  • Session regeneration after privilege escalation
  • Single sign-on support (if configured)

Secure Headers

Recommended HTTP Security Headers:

# nginx configurationadd_header X-Frame-Options "SAMEORIGIN" always;add_header X-Content-Type-Options "nosniff" always;add_header X-XSS-Protection "1; mode=block" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Compliance Considerations

HIPAA Compliance

For healthcare data:

Required Controls:

  1. Access Control: RBAC with unique user accounts
  2. Audit Controls: Comprehensive audit logging
  3. Integrity Controls: Data validation and checksums
  4. Transmission Security: TLS/HTTPS for all communications
  5. Authentication: Strong password policies
  6. Encryption: Data encryption at rest and in transit

BAA Requirements:

  • Ensure Business Associate Agreement with cloud providers
  • Document security policies and procedures
  • Regular security risk assessments
  • Incident response procedures

PHI Handling:

  • Minimize PHI exposure
  • De-identify data when possible
  • Secure disposal procedures
  • Access logging for all PHI

GDPR Compliance

For European data:

Right to Access:

  • Provide user data export functionality
  • API endpoints for data retrieval

Right to Erasure:

  • User deletion removes all associated data
  • Cascade delete for related records
  • Audit log of deletions (without retaining PII)

Right to Portability:

  • Export in machine-readable format (JSON, CSV)
  • Configuration backup/export functionality

Data Protection:

  • Encryption at rest and in transit
  • Access controls and audit logs
  • Privacy by design and default
  • Data minimization

Breach Notification:

  • 72-hour breach notification requirement
  • Incident response procedures
  • Contact data protection authorities

SOC 2 Compliance

For service organizations:

Trust Services Criteria:

  1. Security: Access controls, encryption, monitoring
  2. Availability: Uptime, redundancy, disaster recovery
  3. Processing Integrity: Data validation, error handling
  4. Confidentiality: Encryption, access controls
  5. Privacy: Data handling, consent management

Implementation:

  • Document security policies
  • Regular security assessments
  • Vendor management
  • Change management procedures
  • Incident response plan

Vulnerability Management

Security Updates

Update Process:

  1. Monitor security advisories for dependencies
  2. Test updates in staging environment
  3. Schedule maintenance window
  4. Apply updates and verify
  5. Document changes

Automated Scanning:

# Scan Python dependencies
pip install safety
safety check
# Scan for vulnerabilities
npm audit # If using Node.js tools

Penetration Testing

Recommended Schedule:

  • Annual penetration testing
  • After major releases
  • Before compliance audits

Testing Scope:

  • Web application security
  • API security
  • Authentication mechanisms
  • Database security
  • Network security

Responsible Disclosure

Security Issue Reporting:

  • Email: security@your-org.com
  • PGP key available for encrypted reports
  • Expected response time: 48 hours
  • Coordinated disclosure policy

Incident Response

Incident Response Plan

Phase 1: Detection

  • Monitor audit logs for suspicious activity
  • Alert system for security events
  • User reports of suspicious behavior

Phase 2: Containment

  • Isolate affected systems
  • Disable compromised accounts
  • Block malicious IP addresses
  • Preserve evidence

Phase 3: Eradication

  • Identify root cause
  • Remove malicious code/access
  • Patch vulnerabilities
  • Reset compromised credentials

Phase 4: Recovery

  • Restore from clean backups
  • Verify system integrity
  • Monitor for recurrence
  • Gradual service restoration

Phase 5: Lessons Learned

  • Document incident timeline
  • Identify improvements
  • Update procedures
  • Train personnel

Incident Response Procedures

Security Breach Response:

# 1. Isolate the system
sudo systemctl stop scidk
sudo ufw deny from suspicious_ip
# 2. Preserve evidence
sudo journalctl -u scidk > incident_logs.txt
cp ~/.scidk/db/files.db incident_db_$(date +%Y%m%d).backup
# 3. Reset credentials
./scripts/reset_all_passwords.sh
# 4. Restore from known good backup
cp ~/.scidk/db/files.db.verified ~/.scidk/db/files.db
# 5. Restart with monitoring
sudo systemctl start scidk
tail -f /var/log/syslog | grep scidk

Data Breach Response:

  1. Determine scope: What data was accessed?
  2. Notify affected parties (per regulations)
  3. Document the breach
  4. Report to authorities (if required)
  5. Implement additional controls

Incident Communication

Internal Communication:

  • Notify security team immediately
  • Escalate to management within 1 hour
  • Brief technical team on containment

External Communication:

  • Notify affected users (if PII compromised)
  • Regulatory notification (if required)
  • Public disclosure (if significant breach)

Communication Template:

Subject: Security Incident Notification
We are writing to inform you of a security incident that occurred on [date].
Incident Type: [Unauthorized access / Data breach / etc.]
Data Affected: [Description]
Actions Taken: [Containment, investigation, etc.]
User Actions Required: [Password reset, etc.]
We take security seriously and have implemented additional measures...

Security Monitoring

Real-Time Monitoring

Monitor for:

  • Failed login attempts (>5 in 5 minutes)
  • Unusual access patterns
  • Large data exports
  • Configuration changes
  • Database connection errors

Alert Configuration:

# Example alert rulealert_rules= {
"failed_logins": {
"condition": "count > 5 in 5 minutes",
"action": "email_admin",
"severity": "high"
}
}

Security Metrics

Track:

  • Authentication success/failure rate
  • Average session duration
  • API error rates
  • Disk space usage
  • Database connection pool status

Log Analysis

Regular Reviews:

  • Daily: Security event review
  • Weekly: Authentication pattern analysis
  • Monthly: Comprehensive security audit
  • Quarterly: Access control review
# Example log analysis# Failed logins
sudo journalctl -u scidk | grep "LOGIN_FAILED"| wc -l
# Unique IP addresses
sudo journalctl -u scidk | grep "LOGIN"| awk '{print $X}'| sort -u | wc -l

Security Checklist

Deployment Security Checklist

  • Change all default passwords
  • Enable HTTPS with valid certificates
  • Configure firewall rules
  • Enable authentication and RBAC
  • Set strong session timeout
  • Enable audit logging
  • Encrypt sensitive data at rest
  • Configure secure backup procedures
  • Set up security monitoring and alerts
  • Document incident response procedures
  • Perform security assessment
  • Train administrators on security procedures

Monthly Security Review

  • Review audit logs for anomalies
  • Check for security updates
  • Verify backup integrity
  • Review user accounts and permissions
  • Test disaster recovery procedures
  • Review alert configurations
  • Update documentation

Additional Resources

There aren't any published security advisories

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Security: patchmemory/scidk

Security

docs/SECURITY.md

SciDK Security Guide

This guide covers the security architecture, best practices, compliance considerations, and incident response procedures for SciDK deployments.

⚠️ Status: implemented vs. recommended. This guide documents both controls that are implemented today and controls that are recommended / not yet implemented. Treat unmarked best-practice snippets (nginx, OS, compliance, monitoring) as deployment recommendations, not descriptions of current behavior. For the current security posture of the running app — including what is safe for single-user development vs. multi-user production — see SECURITY_HARDENING.md.

Implemented today: session-based login with bcrypt password hashing (scidk/core/auth.py), role-based access control with @require_role/@require_admin (scidk/web/decorators.py), per-user API tokens (Authorization: Bearer), the auth_users / auth_audit_log / auth_sessions tables, audit logging, manual session lock/unlock with auto-lock after inactivity, and Fernet-encrypted credentials in AlertManager/ConfigManager/API-endpoint registry and plugin settings (scidk/core/plugin_settings.py).

Recommended / not yet implemented:SESSION_COOKIE_SECURE / SESSION_COOKIE_HTTPONLY / SESSION_COOKIE_SAMESITE config, CSRF protection, password complexity enforcement, brute-force/lockout protection, and password reset or change (see inline notes below).

Only two roles exist: admin and userauth_users enforces CHECK (role IN ('admin', 'user')) (scidk/core/auth.py:60), and require_role(*allowed_roles) is a flat membership test (scidk/web/decorators.py:94), not a hierarchy. "Any authenticated user" is @require_role('admin', 'user'); naming a role that does not exist locks out everyone including admins.

Verified against the code on 2026-08-04 (Cycle 5, Task C). The plugin_settings.py encryption is genuine cryptography.fernet.Fernet, not a placeholder — confirmed by the Cycle 2 audit and re-checked here; do not reintroduce a note claiming otherwise.

Security Architecture Overview

SciDK implements defense-in-depth security with multiple layers of protection:

  1. Authentication & Authorization: Multi-user authentication with role-based access control (RBAC)
  2. Data Encryption: Encryption at rest and in transit
  3. Audit Logging: Comprehensive audit trails for all system activities
  4. Session Management: Secure session handling with timeout controls
  5. Input Validation: Protection against injection attacks
  6. Secure Configuration: Encrypted credential storage

Authentication and Authorization

User Authentication

SciDK supports session-based authentication with the following features:

Password Security:

  • Passwords hashed using bcrypt with salt
  • Minimum password complexity requirements ⚠️recommended / not yet implemented — nothing in scidk/ enforces a length or complexity rule
  • Protection against brute force attacks ⚠️recommended / not yet implemented — failed attempts are recorded in auth_audit_log but there is no rate limit and no account lockout
  • Secure password reset mechanisms ⚠️recommended / not yet implemented — there is no password reset or change path; an admin recreates the user

Session Management:

  • Session-based authentication, plus per-user API tokens via Authorization: Bearer
  • Session validity is 24 hours (AuthManager.create_session(duration_hours=24)), not a short inactivity timeout. The 30-minute figure below is a recommendation, not current behavior
  • Auto-lock after inactivity — implemented; a locked session answers 423 Locked until the password is re-entered (scidk/web/auth_middleware.py)
  • Session invalidation on logout
  • CSRF protection and secure-cookie flags (SESSION_COOKIE_SECURE/HTTPONLY/SAMESITE) ⚠️recommended / not yet implemented — no SESSION_COOKIE_* config or CSRF extension appears anywhere in scidk/

Example: Enabling Authentication⚠️illustrative only — the dict below is not a shape SciDK reads. Authentication is enabled through the Settings UI / auth_users table; session_timeout, password_min_length and require_complex_password are not consulted by any code path:

# ILLUSTRATIVE — not a supported config shape (see note above)auth_config= {
"enabled": True,
"session_timeout": 1800, # NOT read; sessions last duration_hours=24"password_min_length": 8, # NOT read; no length enforcement exists"require_complex_password": True# NOT read; no complexity enforcement exists
}

Role-Based Access Control (RBAC)

SciDK implements RBAC with the following roles:

Admin Role:

  • Full system access
  • User management capabilities
  • Settings configuration
  • Backup and restore operations
  • Security configuration

User Role:

  • Standard feature access
  • File browsing and searching
  • Graph visualization
  • Chat interface
  • Data exploration

Permissions Enforcement:

# Example permission check (internal)@require_role('admin')defdelete_user(user_id):
# Only admins can delete userspass

Creating Secure User Accounts

Best Practices:

  1. Use strong, unique passwords (minimum 12 characters)
  2. Enable multi-factor authentication (if available)
  3. Limit admin accounts to necessary personnel
  4. Regular password rotation (every 90 days)
  5. Disable or remove unused accounts

Example: Creating Admin User:

# Via Python script
python3 -c "from scidk.core.auth import create_usercreate_user('admin', 'SecurePassword123!', role='admin')"

Data Encryption

Encryption at Rest

SQLite Database:

  • File-level encryption using OS filesystem encryption
  • Sensitive data (passwords, API keys) encrypted using Fernet (symmetric encryption)
  • Encryption keys stored securely (not in version control)

Neo4j Database:

  • Enterprise Edition supports transparent data encryption
  • Community Edition: Use filesystem-level encryption

Example: Filesystem Encryption (Linux):

# LUKS encryption for data partition
sudo cryptsetup luksFormat /dev/sdb1
sudo cryptsetup luksOpen /dev/sdb1 encrypted_data
sudo mkfs.ext4 /dev/mapper/encrypted_data
sudo mount /dev/mapper/encrypted_data /var/lib/scidk

Backup Encryption:

# Encrypt backups with GPG
gpg --symmetric --cipher-algo AES256 backup.db

Encryption in Transit

HTTPS/TLS: All production deployments should use HTTPS:

# nginx configurationserver{listen443ssl http2;ssl_certificate /etc/ssl/certs/scidk.crt;ssl_certificate_key /etc/ssl/private/scidk.key; # Strong SSL configurationssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';ssl_prefer_server_ciphers on; # HSTSadd_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;}

Neo4j TLS: Configure Neo4j to use encrypted Bolt connections:

# neo4j.conf
dbms.connector.bolt.tls_level=REQUIRED
dbms.ssl.policy.bolt.enabled=true
dbms.ssl.policy.bolt.base_directory=certificates/bolt

API Communication:

  • All API endpoints should be accessed via HTTPS
  • Credentials never transmitted in plain text
  • Bearer tokens or session cookies for authentication

Audit Logging

Audit Trail Features

SciDK maintains comprehensive audit logs for:

  1. User Authentication Events:

    • Login attempts (success/failure)
    • Logout events
    • Session expiration
    • Password changes
  2. Data Access Events:

    • File access and downloads
    • Dataset queries
    • Graph queries
    • Export operations
  3. Administrative Actions:

    • User creation/modification/deletion
    • Settings changes
    • Backup operations
    • System configuration changes
  4. Security Events:

    • Failed authentication attempts
    • Permission denied errors
    • Suspicious activity patterns

Audit Log Format

{
"timestamp": "2024-01-15T10:30:00Z",
"event_type": "user.login",
"user": "admin",
"ip_address": "192.168.1.100",
"user_agent": "Mozilla/5.0...",
"status": "success",
"details": {
"session_id": "sess_abc123"
}
}

Accessing Audit Logs

Via systemd journals:

sudo journalctl -u scidk | grep AUDIT

Via SQLite database — the table is auth_audit_log in scidk_settings.db, and timestamp is a REAL epoch-seconds value, not a SQLite datetime string:

SELECTtimestamp, username, action, details, ip_address
FROM auth_audit_log
WHEREtimestamp> strftime('%s', 'now', '-7 days')
ORDER BYtimestampDESC;

Audit Log Retention

Recommended Retention Policies:

  • Security events: 1 year minimum
  • Authentication logs: 90 days minimum
  • Administrative actions: 1 year minimum
  • Data access: 30-90 days (or per compliance requirements)

Configure retention:

# systemd journal retention
sudo journalctl --vacuum-time=365d

Security Best Practices

Deployment Security

1. Network Security:

  • Deploy behind firewall
  • Use private networks for database connections
  • Limit exposed ports (only 443/80 for web, 7687 for internal Neo4j)
  • Implement IP allowlisting for admin access

Example firewall rules (ufw):

# Allow HTTPS
sudo ufw allow 443/tcp
# Allow Neo4j only from app server
sudo ufw allow from 10.0.1.10 to any port 7687
# Deny all other incoming
sudo ufw default deny incoming
sudo ufw enable

2. Operating System Security:

  • Keep OS and packages updated
  • Use dedicated service account (non-root)
  • Disable unnecessary services
  • Configure SELinux/AppArmor policies

3. Database Security:

  • Change default passwords immediately
  • Use strong authentication credentials
  • Regular security patches and updates
  • Database access restricted to application only

4. Application Security:

  • Run as non-privileged user
  • Use virtual environment isolation
  • Keep dependencies updated
  • Regular security scanning

Credential Management

Best Practices:

  1. Never commit credentials to version control
  2. Use environment variables or secret management systems
  3. Rotate credentials regularly (every 90 days)
  4. Use different credentials for dev/test/prod
  5. Encrypt credentials at rest

Example: Secret Management:

# Use environment variablesexport NEO4J_PASSWORD=$(vault read -field=password secret/neo4j)# Or use .env file (not in git)echo"NEO4J_AUTH=neo4j/$(openssl rand -base64 32)">> .env
chmod 600 .env

Credential Storage:

  • SciDK stores encrypted credentials in SQLite. Fernet (symmetric) encryption is used for SMTP/alert credentials, config-manager secrets, API-endpoint auth tokens, and plugin settings (scidk/core/plugin_settings.py).
  • Encryption key should be stored separately
  • Consider using external secret managers (HashiCorp Vault, AWS Secrets Manager)

Input Validation

SciDK implements input validation to prevent:

SQL Injection:

  • Parameterized queries for all database access
  • ORM-based database interactions
  • Input sanitization

Command Injection:

  • No shell command construction from user input
  • Subprocess calls use argument arrays (not shell=True)
  • Path validation for filesystem operations

Cross-Site Scripting (XSS):

  • HTML escaping in templates
  • Content Security Policy headers
  • Input sanitization

Path Traversal:

  • Path normalization
  • Validation against allowed directories
  • No direct user input in file paths

Session Security

Configuration⚠️Recommended / not yet implemented — the app does not currently set these cookie flags or enable CSRF protection; the snippet below is the recommended hardening to apply before multi-user production use:

# Flask session configuration (RECOMMENDED — not currently set in code)app.config.update(
SESSION_COOKIE_SECURE=True, # HTTPS onlySESSION_COOKIE_HTTPONLY=True, # No JavaScript accessSESSION_COOKIE_SAMESITE='Lax', # CSRF protectionPERMANENT_SESSION_LIFETIME=1800# 30 minutes
)

Session Management:

  • Automatic session expiration
  • Session invalidation on logout
  • Session regeneration after privilege escalation
  • Single sign-on support (if configured)

Secure Headers

Recommended HTTP Security Headers:

# nginx configurationadd_header X-Frame-Options "SAMEORIGIN" always;add_header X-Content-Type-Options "nosniff" always;add_header X-XSS-Protection "1; mode=block" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Compliance Considerations

HIPAA Compliance

For healthcare data:

Required Controls:

  1. Access Control: RBAC with unique user accounts
  2. Audit Controls: Comprehensive audit logging
  3. Integrity Controls: Data validation and checksums
  4. Transmission Security: TLS/HTTPS for all communications
  5. Authentication: Strong password policies
  6. Encryption: Data encryption at rest and in transit

BAA Requirements:

  • Ensure Business Associate Agreement with cloud providers
  • Document security policies and procedures
  • Regular security risk assessments
  • Incident response procedures

PHI Handling:

  • Minimize PHI exposure
  • De-identify data when possible
  • Secure disposal procedures
  • Access logging for all PHI

GDPR Compliance

For European data:

Right to Access:

  • Provide user data export functionality
  • API endpoints for data retrieval

Right to Erasure:

  • User deletion removes all associated data
  • Cascade delete for related records
  • Audit log of deletions (without retaining PII)

Right to Portability:

  • Export in machine-readable format (JSON, CSV)
  • Configuration backup/export functionality

Data Protection:

  • Encryption at rest and in transit
  • Access controls and audit logs
  • Privacy by design and default
  • Data minimization

Breach Notification:

  • 72-hour breach notification requirement
  • Incident response procedures
  • Contact data protection authorities

SOC 2 Compliance

For service organizations:

Trust Services Criteria:

  1. Security: Access controls, encryption, monitoring
  2. Availability: Uptime, redundancy, disaster recovery
  3. Processing Integrity: Data validation, error handling
  4. Confidentiality: Encryption, access controls
  5. Privacy: Data handling, consent management

Implementation:

  • Document security policies
  • Regular security assessments
  • Vendor management
  • Change management procedures
  • Incident response plan

Vulnerability Management

Security Updates

Update Process:

  1. Monitor security advisories for dependencies
  2. Test updates in staging environment
  3. Schedule maintenance window
  4. Apply updates and verify
  5. Document changes

Automated Scanning:

# Scan Python dependencies
pip install safety
safety check
# Scan for vulnerabilities
npm audit # If using Node.js tools

Penetration Testing

Recommended Schedule:

  • Annual penetration testing
  • After major releases
  • Before compliance audits

Testing Scope:

  • Web application security
  • API security
  • Authentication mechanisms
  • Database security
  • Network security

Responsible Disclosure

Security Issue Reporting:

  • Email: security@your-org.com
  • PGP key available for encrypted reports
  • Expected response time: 48 hours
  • Coordinated disclosure policy

Incident Response

Incident Response Plan

Phase 1: Detection

  • Monitor audit logs for suspicious activity
  • Alert system for security events
  • User reports of suspicious behavior

Phase 2: Containment

  • Isolate affected systems
  • Disable compromised accounts
  • Block malicious IP addresses
  • Preserve evidence

Phase 3: Eradication

  • Identify root cause
  • Remove malicious code/access
  • Patch vulnerabilities
  • Reset compromised credentials

Phase 4: Recovery

  • Restore from clean backups
  • Verify system integrity
  • Monitor for recurrence
  • Gradual service restoration

Phase 5: Lessons Learned

  • Document incident timeline
  • Identify improvements
  • Update procedures
  • Train personnel

Incident Response Procedures

Security Breach Response:

# 1. Isolate the system
sudo systemctl stop scidk
sudo ufw deny from suspicious_ip
# 2. Preserve evidence
sudo journalctl -u scidk > incident_logs.txt
cp ~/.scidk/db/files.db incident_db_$(date +%Y%m%d).backup
# 3. Reset credentials
./scripts/reset_all_passwords.sh
# 4. Restore from known good backup
cp ~/.scidk/db/files.db.verified ~/.scidk/db/files.db
# 5. Restart with monitoring
sudo systemctl start scidk
tail -f /var/log/syslog | grep scidk

Data Breach Response:

  1. Determine scope: What data was accessed?
  2. Notify affected parties (per regulations)
  3. Document the breach
  4. Report to authorities (if required)
  5. Implement additional controls

Incident Communication

Internal Communication:

  • Notify security team immediately
  • Escalate to management within 1 hour
  • Brief technical team on containment

External Communication:

  • Notify affected users (if PII compromised)
  • Regulatory notification (if required)
  • Public disclosure (if significant breach)

Communication Template:

Subject: Security Incident Notification
We are writing to inform you of a security incident that occurred on [date].
Incident Type: [Unauthorized access / Data breach / etc.]
Data Affected: [Description]
Actions Taken: [Containment, investigation, etc.]
User Actions Required: [Password reset, etc.]
We take security seriously and have implemented additional measures...

Security Monitoring

Real-Time Monitoring

Monitor for:

  • Failed login attempts (>5 in 5 minutes)
  • Unusual access patterns
  • Large data exports
  • Configuration changes
  • Database connection errors

Alert Configuration:

# Example alert rulealert_rules= {
"failed_logins": {
"condition": "count > 5 in 5 minutes",
"action": "email_admin",
"severity": "high"
}
}

Security Metrics

Track:

  • Authentication success/failure rate
  • Average session duration
  • API error rates
  • Disk space usage
  • Database connection pool status

Log Analysis

Regular Reviews:

  • Daily: Security event review
  • Weekly: Authentication pattern analysis
  • Monthly: Comprehensive security audit
  • Quarterly: Access control review
# Example log analysis# Failed logins
sudo journalctl -u scidk | grep "LOGIN_FAILED"| wc -l
# Unique IP addresses
sudo journalctl -u scidk | grep "LOGIN"| awk '{print $X}'| sort -u | wc -l

Security Checklist

Deployment Security Checklist

  • Change all default passwords
  • Enable HTTPS with valid certificates
  • Configure firewall rules
  • Enable authentication and RBAC
  • Set strong session timeout
  • Enable audit logging
  • Encrypt sensitive data at rest
  • Configure secure backup procedures
  • Set up security monitoring and alerts
  • Document incident response procedures
  • Perform security assessment
  • Train administrators on security procedures

Monthly Security Review

  • Review audit logs for anomalies
  • Check for security updates
  • Verify backup integrity
  • Review user accounts and permissions
  • Test disaster recovery procedures
  • Review alert configurations
  • Update documentation

Additional Resources

There aren't any published security advisories

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content

Security: patchmemory/scidk

Security

docs/SECURITY.md

SciDK Security Guide

This guide covers the security architecture, best practices, compliance considerations, and incident response procedures for SciDK deployments.

⚠️ Status: implemented vs. recommended. This guide documents both controls that are implemented today and controls that are recommended / not yet implemented. Treat unmarked best-practice snippets (nginx, OS, compliance, monitoring) as deployment recommendations, not descriptions of current behavior. For the current security posture of the running app — including what is safe for single-user development vs. multi-user production — see SECURITY_HARDENING.md.

Implemented today: session-based login with bcrypt password hashing (scidk/core/auth.py), role-based access control with @require_role/@require_admin (scidk/web/decorators.py), per-user API tokens (Authorization: Bearer), the auth_users / auth_audit_log / auth_sessions tables, audit logging, manual session lock/unlock with auto-lock after inactivity, and Fernet-encrypted credentials in AlertManager/ConfigManager/API-endpoint registry and plugin settings (scidk/core/plugin_settings.py).

Recommended / not yet implemented:SESSION_COOKIE_SECURE / SESSION_COOKIE_HTTPONLY / SESSION_COOKIE_SAMESITE config, CSRF protection, password complexity enforcement, brute-force/lockout protection, and password reset or change (see inline notes below).

Only two roles exist: admin and userauth_users enforces CHECK (role IN ('admin', 'user')) (scidk/core/auth.py:60), and require_role(*allowed_roles) is a flat membership test (scidk/web/decorators.py:94), not a hierarchy. "Any authenticated user" is @require_role('admin', 'user'); naming a role that does not exist locks out everyone including admins.

Verified against the code on 2026-08-04 (Cycle 5, Task C). The plugin_settings.py encryption is genuine cryptography.fernet.Fernet, not a placeholder — confirmed by the Cycle 2 audit and re-checked here; do not reintroduce a note claiming otherwise.

Security Architecture Overview

SciDK implements defense-in-depth security with multiple layers of protection:

  1. Authentication & Authorization: Multi-user authentication with role-based access control (RBAC)
  2. Data Encryption: Encryption at rest and in transit
  3. Audit Logging: Comprehensive audit trails for all system activities
  4. Session Management: Secure session handling with timeout controls
  5. Input Validation: Protection against injection attacks
  6. Secure Configuration: Encrypted credential storage

Authentication and Authorization

User Authentication

SciDK supports session-based authentication with the following features:

Password Security:

  • Passwords hashed using bcrypt with salt
  • Minimum password complexity requirements ⚠️recommended / not yet implemented — nothing in scidk/ enforces a length or complexity rule
  • Protection against brute force attacks ⚠️recommended / not yet implemented — failed attempts are recorded in auth_audit_log but there is no rate limit and no account lockout
  • Secure password reset mechanisms ⚠️recommended / not yet implemented — there is no password reset or change path; an admin recreates the user

Session Management:

  • Session-based authentication, plus per-user API tokens via Authorization: Bearer
  • Session validity is 24 hours (AuthManager.create_session(duration_hours=24)), not a short inactivity timeout. The 30-minute figure below is a recommendation, not current behavior
  • Auto-lock after inactivity — implemented; a locked session answers 423 Locked until the password is re-entered (scidk/web/auth_middleware.py)
  • Session invalidation on logout
  • CSRF protection and secure-cookie flags (SESSION_COOKIE_SECURE/HTTPONLY/SAMESITE) ⚠️recommended / not yet implemented — no SESSION_COOKIE_* config or CSRF extension appears anywhere in scidk/

Example: Enabling Authentication⚠️illustrative only — the dict below is not a shape SciDK reads. Authentication is enabled through the Settings UI / auth_users table; session_timeout, password_min_length and require_complex_password are not consulted by any code path:

# ILLUSTRATIVE — not a supported config shape (see note above)auth_config= {
"enabled": True,
"session_timeout": 1800, # NOT read; sessions last duration_hours=24"password_min_length": 8, # NOT read; no length enforcement exists"require_complex_password": True# NOT read; no complexity enforcement exists
}

Role-Based Access Control (RBAC)

SciDK implements RBAC with the following roles:

Admin Role:

  • Full system access
  • User management capabilities
  • Settings configuration
  • Backup and restore operations
  • Security configuration

User Role:

  • Standard feature access
  • File browsing and searching
  • Graph visualization
  • Chat interface
  • Data exploration

Permissions Enforcement:

# Example permission check (internal)@require_role('admin')defdelete_user(user_id):
# Only admins can delete userspass

Creating Secure User Accounts

Best Practices:

  1. Use strong, unique passwords (minimum 12 characters)
  2. Enable multi-factor authentication (if available)
  3. Limit admin accounts to necessary personnel
  4. Regular password rotation (every 90 days)
  5. Disable or remove unused accounts

Example: Creating Admin User:

# Via Python script
python3 -c "from scidk.core.auth import create_usercreate_user('admin', 'SecurePassword123!', role='admin')"

Data Encryption

Encryption at Rest

SQLite Database:

  • File-level encryption using OS filesystem encryption
  • Sensitive data (passwords, API keys) encrypted using Fernet (symmetric encryption)
  • Encryption keys stored securely (not in version control)

Neo4j Database:

  • Enterprise Edition supports transparent data encryption
  • Community Edition: Use filesystem-level encryption

Example: Filesystem Encryption (Linux):

# LUKS encryption for data partition
sudo cryptsetup luksFormat /dev/sdb1
sudo cryptsetup luksOpen /dev/sdb1 encrypted_data
sudo mkfs.ext4 /dev/mapper/encrypted_data
sudo mount /dev/mapper/encrypted_data /var/lib/scidk

Backup Encryption:

# Encrypt backups with GPG
gpg --symmetric --cipher-algo AES256 backup.db

Encryption in Transit

HTTPS/TLS: All production deployments should use HTTPS:

# nginx configurationserver{listen443ssl http2;ssl_certificate /etc/ssl/certs/scidk.crt;ssl_certificate_key /etc/ssl/private/scidk.key; # Strong SSL configurationssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';ssl_prefer_server_ciphers on; # HSTSadd_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;}

Neo4j TLS: Configure Neo4j to use encrypted Bolt connections:

# neo4j.conf
dbms.connector.bolt.tls_level=REQUIRED
dbms.ssl.policy.bolt.enabled=true
dbms.ssl.policy.bolt.base_directory=certificates/bolt

API Communication:

  • All API endpoints should be accessed via HTTPS
  • Credentials never transmitted in plain text
  • Bearer tokens or session cookies for authentication

Audit Logging

Audit Trail Features

SciDK maintains comprehensive audit logs for:

  1. User Authentication Events:

    • Login attempts (success/failure)
    • Logout events
    • Session expiration
    • Password changes
  2. Data Access Events:

    • File access and downloads
    • Dataset queries
    • Graph queries
    • Export operations
  3. Administrative Actions:

    • User creation/modification/deletion
    • Settings changes
    • Backup operations
    • System configuration changes
  4. Security Events:

    • Failed authentication attempts
    • Permission denied errors
    • Suspicious activity patterns

Audit Log Format

{
"timestamp": "2024-01-15T10:30:00Z",
"event_type": "user.login",
"user": "admin",
"ip_address": "192.168.1.100",
"user_agent": "Mozilla/5.0...",
"status": "success",
"details": {
"session_id": "sess_abc123"
}
}

Accessing Audit Logs

Via systemd journals:

sudo journalctl -u scidk | grep AUDIT

Via SQLite database — the table is auth_audit_log in scidk_settings.db, and timestamp is a REAL epoch-seconds value, not a SQLite datetime string:

SELECTtimestamp, username, action, details, ip_address
FROM auth_audit_log
WHEREtimestamp> strftime('%s', 'now', '-7 days')
ORDER BYtimestampDESC;

Audit Log Retention

Recommended Retention Policies:

  • Security events: 1 year minimum
  • Authentication logs: 90 days minimum
  • Administrative actions: 1 year minimum
  • Data access: 30-90 days (or per compliance requirements)

Configure retention:

# systemd journal retention
sudo journalctl --vacuum-time=365d

Security Best Practices

Deployment Security

1. Network Security:

  • Deploy behind firewall
  • Use private networks for database connections
  • Limit exposed ports (only 443/80 for web, 7687 for internal Neo4j)
  • Implement IP allowlisting for admin access

Example firewall rules (ufw):

# Allow HTTPS
sudo ufw allow 443/tcp
# Allow Neo4j only from app server
sudo ufw allow from 10.0.1.10 to any port 7687
# Deny all other incoming
sudo ufw default deny incoming
sudo ufw enable

2. Operating System Security:

  • Keep OS and packages updated
  • Use dedicated service account (non-root)
  • Disable unnecessary services
  • Configure SELinux/AppArmor policies

3. Database Security:

  • Change default passwords immediately
  • Use strong authentication credentials
  • Regular security patches and updates
  • Database access restricted to application only

4. Application Security:

  • Run as non-privileged user
  • Use virtual environment isolation
  • Keep dependencies updated
  • Regular security scanning

Credential Management

Best Practices:

  1. Never commit credentials to version control
  2. Use environment variables or secret management systems
  3. Rotate credentials regularly (every 90 days)
  4. Use different credentials for dev/test/prod
  5. Encrypt credentials at rest

Example: Secret Management:

# Use environment variablesexport NEO4J_PASSWORD=$(vault read -field=password secret/neo4j)# Or use .env file (not in git)echo"NEO4J_AUTH=neo4j/$(openssl rand -base64 32)">> .env
chmod 600 .env

Credential Storage:

  • SciDK stores encrypted credentials in SQLite. Fernet (symmetric) encryption is used for SMTP/alert credentials, config-manager secrets, API-endpoint auth tokens, and plugin settings (scidk/core/plugin_settings.py).
  • Encryption key should be stored separately
  • Consider using external secret managers (HashiCorp Vault, AWS Secrets Manager)

Input Validation

SciDK implements input validation to prevent:

SQL Injection:

  • Parameterized queries for all database access
  • ORM-based database interactions
  • Input sanitization

Command Injection:

  • No shell command construction from user input
  • Subprocess calls use argument arrays (not shell=True)
  • Path validation for filesystem operations

Cross-Site Scripting (XSS):

  • HTML escaping in templates
  • Content Security Policy headers
  • Input sanitization

Path Traversal:

  • Path normalization
  • Validation against allowed directories
  • No direct user input in file paths

Session Security

Configuration⚠️Recommended / not yet implemented — the app does not currently set these cookie flags or enable CSRF protection; the snippet below is the recommended hardening to apply before multi-user production use:

# Flask session configuration (RECOMMENDED — not currently set in code)app.config.update(
SESSION_COOKIE_SECURE=True, # HTTPS onlySESSION_COOKIE_HTTPONLY=True, # No JavaScript accessSESSION_COOKIE_SAMESITE='Lax', # CSRF protectionPERMANENT_SESSION_LIFETIME=1800# 30 minutes
)

Session Management:

  • Automatic session expiration
  • Session invalidation on logout
  • Session regeneration after privilege escalation
  • Single sign-on support (if configured)

Secure Headers

Recommended HTTP Security Headers:

# nginx configurationadd_header X-Frame-Options "SAMEORIGIN" always;add_header X-Content-Type-Options "nosniff" always;add_header X-XSS-Protection "1; mode=block" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Compliance Considerations

HIPAA Compliance

For healthcare data:

Required Controls:

  1. Access Control: RBAC with unique user accounts
  2. Audit Controls: Comprehensive audit logging
  3. Integrity Controls: Data validation and checksums
  4. Transmission Security: TLS/HTTPS for all communications
  5. Authentication: Strong password policies
  6. Encryption: Data encryption at rest and in transit

BAA Requirements:

  • Ensure Business Associate Agreement with cloud providers
  • Document security policies and procedures
  • Regular security risk assessments
  • Incident response procedures

PHI Handling:

  • Minimize PHI exposure
  • De-identify data when possible
  • Secure disposal procedures
  • Access logging for all PHI

GDPR Compliance

For European data:

Right to Access:

  • Provide user data export functionality
  • API endpoints for data retrieval

Right to Erasure:

  • User deletion removes all associated data
  • Cascade delete for related records
  • Audit log of deletions (without retaining PII)

Right to Portability:

  • Export in machine-readable format (JSON, CSV)
  • Configuration backup/export functionality

Data Protection:

  • Encryption at rest and in transit
  • Access controls and audit logs
  • Privacy by design and default
  • Data minimization

Breach Notification:

  • 72-hour breach notification requirement
  • Incident response procedures
  • Contact data protection authorities

SOC 2 Compliance

For service organizations:

Trust Services Criteria:

  1. Security: Access controls, encryption, monitoring
  2. Availability: Uptime, redundancy, disaster recovery
  3. Processing Integrity: Data validation, error handling
  4. Confidentiality: Encryption, access controls
  5. Privacy: Data handling, consent management

Implementation:

  • Document security policies
  • Regular security assessments
  • Vendor management
  • Change management procedures
  • Incident response plan

Vulnerability Management

Security Updates

Update Process:

  1. Monitor security advisories for dependencies
  2. Test updates in staging environment
  3. Schedule maintenance window
  4. Apply updates and verify
  5. Document changes

Automated Scanning:

# Scan Python dependencies
pip install safety
safety check
# Scan for vulnerabilities
npm audit # If using Node.js tools

Penetration Testing

Recommended Schedule:

  • Annual penetration testing
  • After major releases
  • Before compliance audits

Testing Scope:

  • Web application security
  • API security
  • Authentication mechanisms
  • Database security
  • Network security

Responsible Disclosure

Security Issue Reporting:

  • Email: security@your-org.com
  • PGP key available for encrypted reports
  • Expected response time: 48 hours
  • Coordinated disclosure policy

Incident Response

Incident Response Plan

Phase 1: Detection

  • Monitor audit logs for suspicious activity
  • Alert system for security events
  • User reports of suspicious behavior

Phase 2: Containment

  • Isolate affected systems
  • Disable compromised accounts
  • Block malicious IP addresses
  • Preserve evidence

Phase 3: Eradication

  • Identify root cause
  • Remove malicious code/access
  • Patch vulnerabilities
  • Reset compromised credentials

Phase 4: Recovery

  • Restore from clean backups
  • Verify system integrity
  • Monitor for recurrence
  • Gradual service restoration

Phase 5: Lessons Learned

  • Document incident timeline
  • Identify improvements
  • Update procedures
  • Train personnel

Incident Response Procedures

Security Breach Response:

# 1. Isolate the system
sudo systemctl stop scidk
sudo ufw deny from suspicious_ip
# 2. Preserve evidence
sudo journalctl -u scidk > incident_logs.txt
cp ~/.scidk/db/files.db incident_db_$(date +%Y%m%d).backup
# 3. Reset credentials
./scripts/reset_all_passwords.sh
# 4. Restore from known good backup
cp ~/.scidk/db/files.db.verified ~/.scidk/db/files.db
# 5. Restart with monitoring
sudo systemctl start scidk
tail -f /var/log/syslog | grep scidk

Data Breach Response:

  1. Determine scope: What data was accessed?
  2. Notify affected parties (per regulations)
  3. Document the breach
  4. Report to authorities (if required)
  5. Implement additional controls

Incident Communication

Internal Communication:

  • Notify security team immediately
  • Escalate to management within 1 hour
  • Brief technical team on containment

External Communication:

  • Notify affected users (if PII compromised)
  • Regulatory notification (if required)
  • Public disclosure (if significant breach)

Communication Template:

Subject: Security Incident Notification
We are writing to inform you of a security incident that occurred on [date].
Incident Type: [Unauthorized access / Data breach / etc.]
Data Affected: [Description]
Actions Taken: [Containment, investigation, etc.]
User Actions Required: [Password reset, etc.]
We take security seriously and have implemented additional measures...

Security Monitoring

Real-Time Monitoring

Monitor for:

  • Failed login attempts (>5 in 5 minutes)
  • Unusual access patterns
  • Large data exports
  • Configuration changes
  • Database connection errors

Alert Configuration:

# Example alert rulealert_rules= {
"failed_logins": {
"condition": "count > 5 in 5 minutes",
"action": "email_admin",
"severity": "high"
}
}

Security Metrics

Track:

  • Authentication success/failure rate
  • Average session duration
  • API error rates
  • Disk space usage
  • Database connection pool status

Log Analysis

Regular Reviews:

  • Daily: Security event review
  • Weekly: Authentication pattern analysis
  • Monthly: Comprehensive security audit
  • Quarterly: Access control review
# Example log analysis# Failed logins
sudo journalctl -u scidk | grep "LOGIN_FAILED"| wc -l
# Unique IP addresses
sudo journalctl -u scidk | grep "LOGIN"| awk '{print $X}'| sort -u | wc -l

Security Checklist

Deployment Security Checklist

  • Change all default passwords
  • Enable HTTPS with valid certificates
  • Configure firewall rules
  • Enable authentication and RBAC
  • Set strong session timeout
  • Enable audit logging
  • Encrypt sensitive data at rest
  • Configure secure backup procedures
  • Set up security monitoring and alerts
  • Document incident response procedures
  • Perform security assessment
  • Train administrators on security procedures

Monthly Security Review

  • Review audit logs for anomalies
  • Check for security updates
  • Verify backup integrity
  • Review user accounts and permissions
  • Test disaster recovery procedures
  • Review alert configurations
  • Update documentation

Additional Resources

There aren't any published security advisories

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Security: patchmemory/scidk

Security

docs/SECURITY.md

SciDK Security Guide

This guide covers the security architecture, best practices, compliance considerations, and incident response procedures for SciDK deployments.

⚠️ Status: implemented vs. recommended. This guide documents both controls that are implemented today and controls that are recommended / not yet implemented. Treat unmarked best-practice snippets (nginx, OS, compliance, monitoring) as deployment recommendations, not descriptions of current behavior. For the current security posture of the running app — including what is safe for single-user development vs. multi-user production — see SECURITY_HARDENING.md.

Implemented today: session-based login with bcrypt password hashing (scidk/core/auth.py), role-based access control with @require_role/@require_admin (scidk/web/decorators.py), per-user API tokens (Authorization: Bearer), the auth_users / auth_audit_log / auth_sessions tables, audit logging, manual session lock/unlock with auto-lock after inactivity, and Fernet-encrypted credentials in AlertManager/ConfigManager/API-endpoint registry and plugin settings (scidk/core/plugin_settings.py).

Recommended / not yet implemented:SESSION_COOKIE_SECURE / SESSION_COOKIE_HTTPONLY / SESSION_COOKIE_SAMESITE config, CSRF protection, password complexity enforcement, brute-force/lockout protection, and password reset or change (see inline notes below).

Only two roles exist: admin and userauth_users enforces CHECK (role IN ('admin', 'user')) (scidk/core/auth.py:60), and require_role(*allowed_roles) is a flat membership test (scidk/web/decorators.py:94), not a hierarchy. "Any authenticated user" is @require_role('admin', 'user'); naming a role that does not exist locks out everyone including admins.

Verified against the code on 2026-08-04 (Cycle 5, Task C). The plugin_settings.py encryption is genuine cryptography.fernet.Fernet, not a placeholder — confirmed by the Cycle 2 audit and re-checked here; do not reintroduce a note claiming otherwise.

Security Architecture Overview

SciDK implements defense-in-depth security with multiple layers of protection:

  1. Authentication & Authorization: Multi-user authentication with role-based access control (RBAC)
  2. Data Encryption: Encryption at rest and in transit
  3. Audit Logging: Comprehensive audit trails for all system activities
  4. Session Management: Secure session handling with timeout controls
  5. Input Validation: Protection against injection attacks
  6. Secure Configuration: Encrypted credential storage

Authentication and Authorization

User Authentication

SciDK supports session-based authentication with the following features:

Password Security:

  • Passwords hashed using bcrypt with salt
  • Minimum password complexity requirements ⚠️recommended / not yet implemented — nothing in scidk/ enforces a length or complexity rule
  • Protection against brute force attacks ⚠️recommended / not yet implemented — failed attempts are recorded in auth_audit_log but there is no rate limit and no account lockout
  • Secure password reset mechanisms ⚠️recommended / not yet implemented — there is no password reset or change path; an admin recreates the user

Session Management:

  • Session-based authentication, plus per-user API tokens via Authorization: Bearer
  • Session validity is 24 hours (AuthManager.create_session(duration_hours=24)), not a short inactivity timeout. The 30-minute figure below is a recommendation, not current behavior
  • Auto-lock after inactivity — implemented; a locked session answers 423 Locked until the password is re-entered (scidk/web/auth_middleware.py)
  • Session invalidation on logout
  • CSRF protection and secure-cookie flags (SESSION_COOKIE_SECURE/HTTPONLY/SAMESITE) ⚠️recommended / not yet implemented — no SESSION_COOKIE_* config or CSRF extension appears anywhere in scidk/

Example: Enabling Authentication⚠️illustrative only — the dict below is not a shape SciDK reads. Authentication is enabled through the Settings UI / auth_users table; session_timeout, password_min_length and require_complex_password are not consulted by any code path:

# ILLUSTRATIVE — not a supported config shape (see note above)auth_config= {
"enabled": True,
"session_timeout": 1800, # NOT read; sessions last duration_hours=24"password_min_length": 8, # NOT read; no length enforcement exists"require_complex_password": True# NOT read; no complexity enforcement exists
}

Role-Based Access Control (RBAC)

SciDK implements RBAC with the following roles:

Admin Role:

  • Full system access
  • User management capabilities
  • Settings configuration
  • Backup and restore operations
  • Security configuration

User Role:

  • Standard feature access
  • File browsing and searching
  • Graph visualization
  • Chat interface
  • Data exploration

Permissions Enforcement:

# Example permission check (internal)@require_role('admin')defdelete_user(user_id):
# Only admins can delete userspass

Creating Secure User Accounts

Best Practices:

  1. Use strong, unique passwords (minimum 12 characters)
  2. Enable multi-factor authentication (if available)
  3. Limit admin accounts to necessary personnel
  4. Regular password rotation (every 90 days)
  5. Disable or remove unused accounts

Example: Creating Admin User:

# Via Python script
python3 -c "from scidk.core.auth import create_usercreate_user('admin', 'SecurePassword123!', role='admin')"

Data Encryption

Encryption at Rest

SQLite Database:

  • File-level encryption using OS filesystem encryption
  • Sensitive data (passwords, API keys) encrypted using Fernet (symmetric encryption)
  • Encryption keys stored securely (not in version control)

Neo4j Database:

  • Enterprise Edition supports transparent data encryption
  • Community Edition: Use filesystem-level encryption

Example: Filesystem Encryption (Linux):

# LUKS encryption for data partition
sudo cryptsetup luksFormat /dev/sdb1
sudo cryptsetup luksOpen /dev/sdb1 encrypted_data
sudo mkfs.ext4 /dev/mapper/encrypted_data
sudo mount /dev/mapper/encrypted_data /var/lib/scidk

Backup Encryption:

# Encrypt backups with GPG
gpg --symmetric --cipher-algo AES256 backup.db

Encryption in Transit

HTTPS/TLS: All production deployments should use HTTPS:

# nginx configurationserver{listen443ssl http2;ssl_certificate /etc/ssl/certs/scidk.crt;ssl_certificate_key /etc/ssl/private/scidk.key; # Strong SSL configurationssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';ssl_prefer_server_ciphers on; # HSTSadd_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;}

Neo4j TLS: Configure Neo4j to use encrypted Bolt connections:

# neo4j.conf
dbms.connector.bolt.tls_level=REQUIRED
dbms.ssl.policy.bolt.enabled=true
dbms.ssl.policy.bolt.base_directory=certificates/bolt

API Communication:

  • All API endpoints should be accessed via HTTPS
  • Credentials never transmitted in plain text
  • Bearer tokens or session cookies for authentication

Audit Logging

Audit Trail Features

SciDK maintains comprehensive audit logs for:

  1. User Authentication Events:

    • Login attempts (success/failure)
    • Logout events
    • Session expiration
    • Password changes
  2. Data Access Events:

    • File access and downloads
    • Dataset queries
    • Graph queries
    • Export operations
  3. Administrative Actions:

    • User creation/modification/deletion
    • Settings changes
    • Backup operations
    • System configuration changes
  4. Security Events:

    • Failed authentication attempts
    • Permission denied errors
    • Suspicious activity patterns

Audit Log Format

{
"timestamp": "2024-01-15T10:30:00Z",
"event_type": "user.login",
"user": "admin",
"ip_address": "192.168.1.100",
"user_agent": "Mozilla/5.0...",
"status": "success",
"details": {
"session_id": "sess_abc123"
}
}

Accessing Audit Logs

Via systemd journals:

sudo journalctl -u scidk | grep AUDIT

Via SQLite database — the table is auth_audit_log in scidk_settings.db, and timestamp is a REAL epoch-seconds value, not a SQLite datetime string:

SELECTtimestamp, username, action, details, ip_address
FROM auth_audit_log
WHEREtimestamp> strftime('%s', 'now', '-7 days')
ORDER BYtimestampDESC;

Audit Log Retention

Recommended Retention Policies:

  • Security events: 1 year minimum
  • Authentication logs: 90 days minimum
  • Administrative actions: 1 year minimum
  • Data access: 30-90 days (or per compliance requirements)

Configure retention:

# systemd journal retention
sudo journalctl --vacuum-time=365d

Security Best Practices

Deployment Security

1. Network Security:

  • Deploy behind firewall
  • Use private networks for database connections
  • Limit exposed ports (only 443/80 for web, 7687 for internal Neo4j)
  • Implement IP allowlisting for admin access

Example firewall rules (ufw):

# Allow HTTPS
sudo ufw allow 443/tcp
# Allow Neo4j only from app server
sudo ufw allow from 10.0.1.10 to any port 7687
# Deny all other incoming
sudo ufw default deny incoming
sudo ufw enable

2. Operating System Security:

  • Keep OS and packages updated
  • Use dedicated service account (non-root)
  • Disable unnecessary services
  • Configure SELinux/AppArmor policies

3. Database Security:

  • Change default passwords immediately
  • Use strong authentication credentials
  • Regular security patches and updates
  • Database access restricted to application only

4. Application Security:

  • Run as non-privileged user
  • Use virtual environment isolation
  • Keep dependencies updated
  • Regular security scanning

Credential Management

Best Practices:

  1. Never commit credentials to version control
  2. Use environment variables or secret management systems
  3. Rotate credentials regularly (every 90 days)
  4. Use different credentials for dev/test/prod
  5. Encrypt credentials at rest

Example: Secret Management:

# Use environment variablesexport NEO4J_PASSWORD=$(vault read -field=password secret/neo4j)# Or use .env file (not in git)echo"NEO4J_AUTH=neo4j/$(openssl rand -base64 32)">> .env
chmod 600 .env

Credential Storage:

  • SciDK stores encrypted credentials in SQLite. Fernet (symmetric) encryption is used for SMTP/alert credentials, config-manager secrets, API-endpoint auth tokens, and plugin settings (scidk/core/plugin_settings.py).
  • Encryption key should be stored separately
  • Consider using external secret managers (HashiCorp Vault, AWS Secrets Manager)

Input Validation

SciDK implements input validation to prevent:

SQL Injection:

  • Parameterized queries for all database access
  • ORM-based database interactions
  • Input sanitization

Command Injection:

  • No shell command construction from user input
  • Subprocess calls use argument arrays (not shell=True)
  • Path validation for filesystem operations

Cross-Site Scripting (XSS):

  • HTML escaping in templates
  • Content Security Policy headers
  • Input sanitization

Path Traversal:

  • Path normalization
  • Validation against allowed directories
  • No direct user input in file paths

Session Security

Configuration⚠️Recommended / not yet implemented — the app does not currently set these cookie flags or enable CSRF protection; the snippet below is the recommended hardening to apply before multi-user production use:

# Flask session configuration (RECOMMENDED — not currently set in code)app.config.update(
SESSION_COOKIE_SECURE=True, # HTTPS onlySESSION_COOKIE_HTTPONLY=True, # No JavaScript accessSESSION_COOKIE_SAMESITE='Lax', # CSRF protectionPERMANENT_SESSION_LIFETIME=1800# 30 minutes
)

Session Management:

  • Automatic session expiration
  • Session invalidation on logout
  • Session regeneration after privilege escalation
  • Single sign-on support (if configured)

Secure Headers

Recommended HTTP Security Headers:

# nginx configurationadd_header X-Frame-Options "SAMEORIGIN" always;add_header X-Content-Type-Options "nosniff" always;add_header X-XSS-Protection "1; mode=block" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Compliance Considerations

HIPAA Compliance

For healthcare data:

Required Controls:

  1. Access Control: RBAC with unique user accounts
  2. Audit Controls: Comprehensive audit logging
  3. Integrity Controls: Data validation and checksums
  4. Transmission Security: TLS/HTTPS for all communications
  5. Authentication: Strong password policies
  6. Encryption: Data encryption at rest and in transit

BAA Requirements:

  • Ensure Business Associate Agreement with cloud providers
  • Document security policies and procedures
  • Regular security risk assessments
  • Incident response procedures

PHI Handling:

  • Minimize PHI exposure
  • De-identify data when possible
  • Secure disposal procedures
  • Access logging for all PHI

GDPR Compliance

For European data:

Right to Access:

  • Provide user data export functionality
  • API endpoints for data retrieval

Right to Erasure:

  • User deletion removes all associated data
  • Cascade delete for related records
  • Audit log of deletions (without retaining PII)

Right to Portability:

  • Export in machine-readable format (JSON, CSV)
  • Configuration backup/export functionality

Data Protection:

  • Encryption at rest and in transit
  • Access controls and audit logs
  • Privacy by design and default
  • Data minimization

Breach Notification:

  • 72-hour breach notification requirement
  • Incident response procedures
  • Contact data protection authorities

SOC 2 Compliance

For service organizations:

Trust Services Criteria:

  1. Security: Access controls, encryption, monitoring
  2. Availability: Uptime, redundancy, disaster recovery
  3. Processing Integrity: Data validation, error handling
  4. Confidentiality: Encryption, access controls
  5. Privacy: Data handling, consent management

Implementation:

  • Document security policies
  • Regular security assessments
  • Vendor management
  • Change management procedures
  • Incident response plan

Vulnerability Management

Security Updates

Update Process:

  1. Monitor security advisories for dependencies
  2. Test updates in staging environment
  3. Schedule maintenance window
  4. Apply updates and verify
  5. Document changes

Automated Scanning:

# Scan Python dependencies
pip install safety
safety check
# Scan for vulnerabilities
npm audit # If using Node.js tools

Penetration Testing

Recommended Schedule:

  • Annual penetration testing
  • After major releases
  • Before compliance audits

Testing Scope:

  • Web application security
  • API security
  • Authentication mechanisms
  • Database security
  • Network security

Responsible Disclosure

Security Issue Reporting:

  • Email: security@your-org.com
  • PGP key available for encrypted reports
  • Expected response time: 48 hours
  • Coordinated disclosure policy

Incident Response

Incident Response Plan

Phase 1: Detection

  • Monitor audit logs for suspicious activity
  • Alert system for security events
  • User reports of suspicious behavior

Phase 2: Containment

  • Isolate affected systems
  • Disable compromised accounts
  • Block malicious IP addresses
  • Preserve evidence

Phase 3: Eradication

  • Identify root cause
  • Remove malicious code/access
  • Patch vulnerabilities
  • Reset compromised credentials

Phase 4: Recovery

  • Restore from clean backups
  • Verify system integrity
  • Monitor for recurrence
  • Gradual service restoration

Phase 5: Lessons Learned

  • Document incident timeline
  • Identify improvements
  • Update procedures
  • Train personnel

Incident Response Procedures

Security Breach Response:

# 1. Isolate the system
sudo systemctl stop scidk
sudo ufw deny from suspicious_ip
# 2. Preserve evidence
sudo journalctl -u scidk > incident_logs.txt
cp ~/.scidk/db/files.db incident_db_$(date +%Y%m%d).backup
# 3. Reset credentials
./scripts/reset_all_passwords.sh
# 4. Restore from known good backup
cp ~/.scidk/db/files.db.verified ~/.scidk/db/files.db
# 5. Restart with monitoring
sudo systemctl start scidk
tail -f /var/log/syslog | grep scidk

Data Breach Response:

  1. Determine scope: What data was accessed?
  2. Notify affected parties (per regulations)
  3. Document the breach
  4. Report to authorities (if required)
  5. Implement additional controls

Incident Communication

Internal Communication:

  • Notify security team immediately
  • Escalate to management within 1 hour
  • Brief technical team on containment

External Communication:

  • Notify affected users (if PII compromised)
  • Regulatory notification (if required)
  • Public disclosure (if significant breach)

Communication Template:

Subject: Security Incident Notification
We are writing to inform you of a security incident that occurred on [date].
Incident Type: [Unauthorized access / Data breach / etc.]
Data Affected: [Description]
Actions Taken: [Containment, investigation, etc.]
User Actions Required: [Password reset, etc.]
We take security seriously and have implemented additional measures...

Security Monitoring

Real-Time Monitoring

Monitor for:

  • Failed login attempts (>5 in 5 minutes)
  • Unusual access patterns
  • Large data exports
  • Configuration changes
  • Database connection errors

Alert Configuration:

# Example alert rulealert_rules= {
"failed_logins": {
"condition": "count > 5 in 5 minutes",
"action": "email_admin",
"severity": "high"
}
}

Security Metrics

Track:

  • Authentication success/failure rate
  • Average session duration
  • API error rates
  • Disk space usage
  • Database connection pool status

Log Analysis

Regular Reviews:

  • Daily: Security event review
  • Weekly: Authentication pattern analysis
  • Monthly: Comprehensive security audit
  • Quarterly: Access control review
# Example log analysis# Failed logins
sudo journalctl -u scidk | grep "LOGIN_FAILED"| wc -l
# Unique IP addresses
sudo journalctl -u scidk | grep "LOGIN"| awk '{print $X}'| sort -u | wc -l

Security Checklist

Deployment Security Checklist

  • Change all default passwords
  • Enable HTTPS with valid certificates
  • Configure firewall rules
  • Enable authentication and RBAC
  • Set strong session timeout
  • Enable audit logging
  • Encrypt sensitive data at rest
  • Configure secure backup procedures
  • Set up security monitoring and alerts
  • Document incident response procedures
  • Perform security assessment
  • Train administrators on security procedures

Monthly Security Review

  • Review audit logs for anomalies
  • Check for security updates
  • Verify backup integrity
  • Review user accounts and permissions
  • Test disaster recovery procedures
  • Review alert configurations
  • Update documentation

Additional Resources

There aren't any published security advisories

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content

Security: patchmemory/scidk

Security

docs/SECURITY.md

SciDK Security Guide

This guide covers the security architecture, best practices, compliance considerations, and incident response procedures for SciDK deployments.

⚠️ Status: implemented vs. recommended. This guide documents both controls that are implemented today and controls that are recommended / not yet implemented. Treat unmarked best-practice snippets (nginx, OS, compliance, monitoring) as deployment recommendations, not descriptions of current behavior. For the current security posture of the running app — including what is safe for single-user development vs. multi-user production — see SECURITY_HARDENING.md.

Implemented today: session-based login with bcrypt password hashing (scidk/core/auth.py), role-based access control with @require_role/@require_admin (scidk/web/decorators.py), per-user API tokens (Authorization: Bearer), the auth_users / auth_audit_log / auth_sessions tables, audit logging, manual session lock/unlock with auto-lock after inactivity, and Fernet-encrypted credentials in AlertManager/ConfigManager/API-endpoint registry and plugin settings (scidk/core/plugin_settings.py).

Recommended / not yet implemented:SESSION_COOKIE_SECURE / SESSION_COOKIE_HTTPONLY / SESSION_COOKIE_SAMESITE config, CSRF protection, password complexity enforcement, brute-force/lockout protection, and password reset or change (see inline notes below).

Only two roles exist: admin and userauth_users enforces CHECK (role IN ('admin', 'user')) (scidk/core/auth.py:60), and require_role(*allowed_roles) is a flat membership test (scidk/web/decorators.py:94), not a hierarchy. "Any authenticated user" is @require_role('admin', 'user'); naming a role that does not exist locks out everyone including admins.

Verified against the code on 2026-08-04 (Cycle 5, Task C). The plugin_settings.py encryption is genuine cryptography.fernet.Fernet, not a placeholder — confirmed by the Cycle 2 audit and re-checked here; do not reintroduce a note claiming otherwise.

Security Architecture Overview

SciDK implements defense-in-depth security with multiple layers of protection:

  1. Authentication & Authorization: Multi-user authentication with role-based access control (RBAC)
  2. Data Encryption: Encryption at rest and in transit
  3. Audit Logging: Comprehensive audit trails for all system activities
  4. Session Management: Secure session handling with timeout controls
  5. Input Validation: Protection against injection attacks
  6. Secure Configuration: Encrypted credential storage

Authentication and Authorization

User Authentication

SciDK supports session-based authentication with the following features:

Password Security:

  • Passwords hashed using bcrypt with salt
  • Minimum password complexity requirements ⚠️recommended / not yet implemented — nothing in scidk/ enforces a length or complexity rule
  • Protection against brute force attacks ⚠️recommended / not yet implemented — failed attempts are recorded in auth_audit_log but there is no rate limit and no account lockout
  • Secure password reset mechanisms ⚠️recommended / not yet implemented — there is no password reset or change path; an admin recreates the user

Session Management:

  • Session-based authentication, plus per-user API tokens via Authorization: Bearer
  • Session validity is 24 hours (AuthManager.create_session(duration_hours=24)), not a short inactivity timeout. The 30-minute figure below is a recommendation, not current behavior
  • Auto-lock after inactivity — implemented; a locked session answers 423 Locked until the password is re-entered (scidk/web/auth_middleware.py)
  • Session invalidation on logout
  • CSRF protection and secure-cookie flags (SESSION_COOKIE_SECURE/HTTPONLY/SAMESITE) ⚠️recommended / not yet implemented — no SESSION_COOKIE_* config or CSRF extension appears anywhere in scidk/

Example: Enabling Authentication⚠️illustrative only — the dict below is not a shape SciDK reads. Authentication is enabled through the Settings UI / auth_users table; session_timeout, password_min_length and require_complex_password are not consulted by any code path:

# ILLUSTRATIVE — not a supported config shape (see note above)auth_config= {
"enabled": True,
"session_timeout": 1800, # NOT read; sessions last duration_hours=24"password_min_length": 8, # NOT read; no length enforcement exists"require_complex_password": True# NOT read; no complexity enforcement exists
}

Role-Based Access Control (RBAC)

SciDK implements RBAC with the following roles:

Admin Role:

  • Full system access
  • User management capabilities
  • Settings configuration
  • Backup and restore operations
  • Security configuration

User Role:

  • Standard feature access
  • File browsing and searching
  • Graph visualization
  • Chat interface
  • Data exploration

Permissions Enforcement:

# Example permission check (internal)@require_role('admin')defdelete_user(user_id):
# Only admins can delete userspass

Creating Secure User Accounts

Best Practices:

  1. Use strong, unique passwords (minimum 12 characters)
  2. Enable multi-factor authentication (if available)
  3. Limit admin accounts to necessary personnel
  4. Regular password rotation (every 90 days)
  5. Disable or remove unused accounts

Example: Creating Admin User:

# Via Python script
python3 -c "from scidk.core.auth import create_usercreate_user('admin', 'SecurePassword123!', role='admin')"

Data Encryption

Encryption at Rest

SQLite Database:

  • File-level encryption using OS filesystem encryption
  • Sensitive data (passwords, API keys) encrypted using Fernet (symmetric encryption)
  • Encryption keys stored securely (not in version control)

Neo4j Database:

  • Enterprise Edition supports transparent data encryption
  • Community Edition: Use filesystem-level encryption

Example: Filesystem Encryption (Linux):

# LUKS encryption for data partition
sudo cryptsetup luksFormat /dev/sdb1
sudo cryptsetup luksOpen /dev/sdb1 encrypted_data
sudo mkfs.ext4 /dev/mapper/encrypted_data
sudo mount /dev/mapper/encrypted_data /var/lib/scidk

Backup Encryption:

# Encrypt backups with GPG
gpg --symmetric --cipher-algo AES256 backup.db

Encryption in Transit

HTTPS/TLS: All production deployments should use HTTPS:

# nginx configurationserver{listen443ssl http2;ssl_certificate /etc/ssl/certs/scidk.crt;ssl_certificate_key /etc/ssl/private/scidk.key; # Strong SSL configurationssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';ssl_prefer_server_ciphers on; # HSTSadd_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;}

Neo4j TLS: Configure Neo4j to use encrypted Bolt connections:

# neo4j.conf
dbms.connector.bolt.tls_level=REQUIRED
dbms.ssl.policy.bolt.enabled=true
dbms.ssl.policy.bolt.base_directory=certificates/bolt

API Communication:

  • All API endpoints should be accessed via HTTPS
  • Credentials never transmitted in plain text
  • Bearer tokens or session cookies for authentication

Audit Logging

Audit Trail Features

SciDK maintains comprehensive audit logs for:

  1. User Authentication Events:

    • Login attempts (success/failure)
    • Logout events
    • Session expiration
    • Password changes
  2. Data Access Events:

    • File access and downloads
    • Dataset queries
    • Graph queries
    • Export operations
  3. Administrative Actions:

    • User creation/modification/deletion
    • Settings changes
    • Backup operations
    • System configuration changes
  4. Security Events:

    • Failed authentication attempts
    • Permission denied errors
    • Suspicious activity patterns

Audit Log Format

{
"timestamp": "2024-01-15T10:30:00Z",
"event_type": "user.login",
"user": "admin",
"ip_address": "192.168.1.100",
"user_agent": "Mozilla/5.0...",
"status": "success",
"details": {
"session_id": "sess_abc123"
}
}

Accessing Audit Logs

Via systemd journals:

sudo journalctl -u scidk | grep AUDIT

Via SQLite database — the table is auth_audit_log in scidk_settings.db, and timestamp is a REAL epoch-seconds value, not a SQLite datetime string:

SELECTtimestamp, username, action, details, ip_address
FROM auth_audit_log
WHEREtimestamp> strftime('%s', 'now', '-7 days')
ORDER BYtimestampDESC;

Audit Log Retention

Recommended Retention Policies:

  • Security events: 1 year minimum
  • Authentication logs: 90 days minimum
  • Administrative actions: 1 year minimum
  • Data access: 30-90 days (or per compliance requirements)

Configure retention:

# systemd journal retention
sudo journalctl --vacuum-time=365d

Security Best Practices

Deployment Security

1. Network Security:

  • Deploy behind firewall
  • Use private networks for database connections
  • Limit exposed ports (only 443/80 for web, 7687 for internal Neo4j)
  • Implement IP allowlisting for admin access

Example firewall rules (ufw):

# Allow HTTPS
sudo ufw allow 443/tcp
# Allow Neo4j only from app server
sudo ufw allow from 10.0.1.10 to any port 7687
# Deny all other incoming
sudo ufw default deny incoming
sudo ufw enable

2. Operating System Security:

  • Keep OS and packages updated
  • Use dedicated service account (non-root)
  • Disable unnecessary services
  • Configure SELinux/AppArmor policies

3. Database Security:

  • Change default passwords immediately
  • Use strong authentication credentials
  • Regular security patches and updates
  • Database access restricted to application only

4. Application Security:

  • Run as non-privileged user
  • Use virtual environment isolation
  • Keep dependencies updated
  • Regular security scanning

Credential Management

Best Practices:

  1. Never commit credentials to version control
  2. Use environment variables or secret management systems
  3. Rotate credentials regularly (every 90 days)
  4. Use different credentials for dev/test/prod
  5. Encrypt credentials at rest

Example: Secret Management:

# Use environment variablesexport NEO4J_PASSWORD=$(vault read -field=password secret/neo4j)# Or use .env file (not in git)echo"NEO4J_AUTH=neo4j/$(openssl rand -base64 32)">> .env
chmod 600 .env

Credential Storage:

  • SciDK stores encrypted credentials in SQLite. Fernet (symmetric) encryption is used for SMTP/alert credentials, config-manager secrets, API-endpoint auth tokens, and plugin settings (scidk/core/plugin_settings.py).
  • Encryption key should be stored separately
  • Consider using external secret managers (HashiCorp Vault, AWS Secrets Manager)

Input Validation

SciDK implements input validation to prevent:

SQL Injection:

  • Parameterized queries for all database access
  • ORM-based database interactions
  • Input sanitization

Command Injection:

  • No shell command construction from user input
  • Subprocess calls use argument arrays (not shell=True)
  • Path validation for filesystem operations

Cross-Site Scripting (XSS):

  • HTML escaping in templates
  • Content Security Policy headers
  • Input sanitization

Path Traversal:

  • Path normalization
  • Validation against allowed directories
  • No direct user input in file paths

Session Security

Configuration⚠️Recommended / not yet implemented — the app does not currently set these cookie flags or enable CSRF protection; the snippet below is the recommended hardening to apply before multi-user production use:

# Flask session configuration (RECOMMENDED — not currently set in code)app.config.update(
SESSION_COOKIE_SECURE=True, # HTTPS onlySESSION_COOKIE_HTTPONLY=True, # No JavaScript accessSESSION_COOKIE_SAMESITE='Lax', # CSRF protectionPERMANENT_SESSION_LIFETIME=1800# 30 minutes
)

Session Management:

  • Automatic session expiration
  • Session invalidation on logout
  • Session regeneration after privilege escalation
  • Single sign-on support (if configured)

Secure Headers

Recommended HTTP Security Headers:

# nginx configurationadd_header X-Frame-Options "SAMEORIGIN" always;add_header X-Content-Type-Options "nosniff" always;add_header X-XSS-Protection "1; mode=block" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Compliance Considerations

HIPAA Compliance

For healthcare data:

Required Controls:

  1. Access Control: RBAC with unique user accounts
  2. Audit Controls: Comprehensive audit logging
  3. Integrity Controls: Data validation and checksums
  4. Transmission Security: TLS/HTTPS for all communications
  5. Authentication: Strong password policies
  6. Encryption: Data encryption at rest and in transit

BAA Requirements:

  • Ensure Business Associate Agreement with cloud providers
  • Document security policies and procedures
  • Regular security risk assessments
  • Incident response procedures

PHI Handling:

  • Minimize PHI exposure
  • De-identify data when possible
  • Secure disposal procedures
  • Access logging for all PHI

GDPR Compliance

For European data:

Right to Access:

  • Provide user data export functionality
  • API endpoints for data retrieval

Right to Erasure:

  • User deletion removes all associated data
  • Cascade delete for related records
  • Audit log of deletions (without retaining PII)

Right to Portability:

  • Export in machine-readable format (JSON, CSV)
  • Configuration backup/export functionality

Data Protection:

  • Encryption at rest and in transit
  • Access controls and audit logs
  • Privacy by design and default
  • Data minimization

Breach Notification:

  • 72-hour breach notification requirement
  • Incident response procedures
  • Contact data protection authorities

SOC 2 Compliance

For service organizations:

Trust Services Criteria:

  1. Security: Access controls, encryption, monitoring
  2. Availability: Uptime, redundancy, disaster recovery
  3. Processing Integrity: Data validation, error handling
  4. Confidentiality: Encryption, access controls
  5. Privacy: Data handling, consent management

Implementation:

  • Document security policies
  • Regular security assessments
  • Vendor management
  • Change management procedures
  • Incident response plan

Vulnerability Management

Security Updates

Update Process:

  1. Monitor security advisories for dependencies
  2. Test updates in staging environment
  3. Schedule maintenance window
  4. Apply updates and verify
  5. Document changes

Automated Scanning:

# Scan Python dependencies
pip install safety
safety check
# Scan for vulnerabilities
npm audit # If using Node.js tools

Penetration Testing

Recommended Schedule:

  • Annual penetration testing
  • After major releases
  • Before compliance audits

Testing Scope:

  • Web application security
  • API security
  • Authentication mechanisms
  • Database security
  • Network security

Responsible Disclosure

Security Issue Reporting:

  • Email: security@your-org.com
  • PGP key available for encrypted reports
  • Expected response time: 48 hours
  • Coordinated disclosure policy

Incident Response

Incident Response Plan

Phase 1: Detection

  • Monitor audit logs for suspicious activity
  • Alert system for security events
  • User reports of suspicious behavior

Phase 2: Containment

  • Isolate affected systems
  • Disable compromised accounts
  • Block malicious IP addresses
  • Preserve evidence

Phase 3: Eradication

  • Identify root cause
  • Remove malicious code/access
  • Patch vulnerabilities
  • Reset compromised credentials

Phase 4: Recovery

  • Restore from clean backups
  • Verify system integrity
  • Monitor for recurrence
  • Gradual service restoration

Phase 5: Lessons Learned

  • Document incident timeline
  • Identify improvements
  • Update procedures
  • Train personnel

Incident Response Procedures

Security Breach Response:

# 1. Isolate the system
sudo systemctl stop scidk
sudo ufw deny from suspicious_ip
# 2. Preserve evidence
sudo journalctl -u scidk > incident_logs.txt
cp ~/.scidk/db/files.db incident_db_$(date +%Y%m%d).backup
# 3. Reset credentials
./scripts/reset_all_passwords.sh
# 4. Restore from known good backup
cp ~/.scidk/db/files.db.verified ~/.scidk/db/files.db
# 5. Restart with monitoring
sudo systemctl start scidk
tail -f /var/log/syslog | grep scidk

Data Breach Response:

  1. Determine scope: What data was accessed?
  2. Notify affected parties (per regulations)
  3. Document the breach
  4. Report to authorities (if required)
  5. Implement additional controls

Incident Communication

Internal Communication:

  • Notify security team immediately
  • Escalate to management within 1 hour
  • Brief technical team on containment

External Communication:

  • Notify affected users (if PII compromised)
  • Regulatory notification (if required)
  • Public disclosure (if significant breach)

Communication Template:

Subject: Security Incident Notification
We are writing to inform you of a security incident that occurred on [date].
Incident Type: [Unauthorized access / Data breach / etc.]
Data Affected: [Description]
Actions Taken: [Containment, investigation, etc.]
User Actions Required: [Password reset, etc.]
We take security seriously and have implemented additional measures...

Security Monitoring

Real-Time Monitoring

Monitor for:

  • Failed login attempts (>5 in 5 minutes)
  • Unusual access patterns
  • Large data exports
  • Configuration changes
  • Database connection errors

Alert Configuration:

# Example alert rulealert_rules= {
"failed_logins": {
"condition": "count > 5 in 5 minutes",
"action": "email_admin",
"severity": "high"
}
}

Security Metrics

Track:

  • Authentication success/failure rate
  • Average session duration
  • API error rates
  • Disk space usage
  • Database connection pool status

Log Analysis

Regular Reviews:

  • Daily: Security event review
  • Weekly: Authentication pattern analysis
  • Monthly: Comprehensive security audit
  • Quarterly: Access control review
# Example log analysis# Failed logins
sudo journalctl -u scidk | grep "LOGIN_FAILED"| wc -l
# Unique IP addresses
sudo journalctl -u scidk | grep "LOGIN"| awk '{print $X}'| sort -u | wc -l

Security Checklist

Deployment Security Checklist

  • Change all default passwords
  • Enable HTTPS with valid certificates
  • Configure firewall rules
  • Enable authentication and RBAC
  • Set strong session timeout
  • Enable audit logging
  • Encrypt sensitive data at rest
  • Configure secure backup procedures
  • Set up security monitoring and alerts
  • Document incident response procedures
  • Perform security assessment
  • Train administrators on security procedures

Monthly Security Review

  • Review audit logs for anomalies
  • Check for security updates
  • Verify backup integrity
  • Review user accounts and permissions
  • Test disaster recovery procedures
  • Review alert configurations
  • Update documentation

Additional Resources

There aren't any published security advisories

, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content

Security: patchmemory/scidk

Security

docs/SECURITY.md

SciDK Security Guide

This guide covers the security architecture, best practices, compliance considerations, and incident response procedures for SciDK deployments.

⚠️ Status: implemented vs. recommended. This guide documents both controls that are implemented today and controls that are recommended / not yet implemented. Treat unmarked best-practice snippets (nginx, OS, compliance, monitoring) as deployment recommendations, not descriptions of current behavior. For the current security posture of the running app — including what is safe for single-user development vs. multi-user production — see SECURITY_HARDENING.md.

Implemented today: session-based login with bcrypt password hashing (scidk/core/auth.py), role-based access control with @require_role/@require_admin (scidk/web/decorators.py), per-user API tokens (Authorization: Bearer), the auth_users / auth_audit_log / auth_sessions tables, audit logging, manual session lock/unlock with auto-lock after inactivity, and Fernet-encrypted credentials in AlertManager/ConfigManager/API-endpoint registry and plugin settings (scidk/core/plugin_settings.py).

Recommended / not yet implemented:SESSION_COOKIE_SECURE / SESSION_COOKIE_HTTPONLY / SESSION_COOKIE_SAMESITE config, CSRF protection, password complexity enforcement, brute-force/lockout protection, and password reset or change (see inline notes below).

Only two roles exist: admin and userauth_users enforces CHECK (role IN ('admin', 'user')) (scidk/core/auth.py:60), and require_role(*allowed_roles) is a flat membership test (scidk/web/decorators.py:94), not a hierarchy. "Any authenticated user" is @require_role('admin', 'user'); naming a role that does not exist locks out everyone including admins.

Verified against the code on 2026-08-04 (Cycle 5, Task C). The plugin_settings.py encryption is genuine cryptography.fernet.Fernet, not a placeholder — confirmed by the Cycle 2 audit and re-checked here; do not reintroduce a note claiming otherwise.

Security Architecture Overview

SciDK implements defense-in-depth security with multiple layers of protection:

  1. Authentication & Authorization: Multi-user authentication with role-based access control (RBAC)
  2. Data Encryption: Encryption at rest and in transit
  3. Audit Logging: Comprehensive audit trails for all system activities
  4. Session Management: Secure session handling with timeout controls
  5. Input Validation: Protection against injection attacks
  6. Secure Configuration: Encrypted credential storage

Authentication and Authorization

User Authentication

SciDK supports session-based authentication with the following features:

Password Security:

  • Passwords hashed using bcrypt with salt
  • Minimum password complexity requirements ⚠️recommended / not yet implemented — nothing in scidk/ enforces a length or complexity rule
  • Protection against brute force attacks ⚠️recommended / not yet implemented — failed attempts are recorded in auth_audit_log but there is no rate limit and no account lockout
  • Secure password reset mechanisms ⚠️recommended / not yet implemented — there is no password reset or change path; an admin recreates the user

Session Management:

  • Session-based authentication, plus per-user API tokens via Authorization: Bearer
  • Session validity is 24 hours (AuthManager.create_session(duration_hours=24)), not a short inactivity timeout. The 30-minute figure below is a recommendation, not current behavior
  • Auto-lock after inactivity — implemented; a locked session answers 423 Locked until the password is re-entered (scidk/web/auth_middleware.py)
  • Session invalidation on logout
  • CSRF protection and secure-cookie flags (SESSION_COOKIE_SECURE/HTTPONLY/SAMESITE) ⚠️recommended / not yet implemented — no SESSION_COOKIE_* config or CSRF extension appears anywhere in scidk/

Example: Enabling Authentication⚠️illustrative only — the dict below is not a shape SciDK reads. Authentication is enabled through the Settings UI / auth_users table; session_timeout, password_min_length and require_complex_password are not consulted by any code path:

# ILLUSTRATIVE — not a supported config shape (see note above)auth_config= {
"enabled": True,
"session_timeout": 1800, # NOT read; sessions last duration_hours=24"password_min_length": 8, # NOT read; no length enforcement exists"require_complex_password": True# NOT read; no complexity enforcement exists
}

Role-Based Access Control (RBAC)

SciDK implements RBAC with the following roles:

Admin Role:

  • Full system access
  • User management capabilities
  • Settings configuration
  • Backup and restore operations
  • Security configuration

User Role:

  • Standard feature access
  • File browsing and searching
  • Graph visualization
  • Chat interface
  • Data exploration

Permissions Enforcement:

# Example permission check (internal)@require_role('admin')defdelete_user(user_id):
# Only admins can delete userspass

Creating Secure User Accounts

Best Practices:

  1. Use strong, unique passwords (minimum 12 characters)
  2. Enable multi-factor authentication (if available)
  3. Limit admin accounts to necessary personnel
  4. Regular password rotation (every 90 days)
  5. Disable or remove unused accounts

Example: Creating Admin User:

# Via Python script
python3 -c "from scidk.core.auth import create_usercreate_user('admin', 'SecurePassword123!', role='admin')"

Data Encryption

Encryption at Rest

SQLite Database:

  • File-level encryption using OS filesystem encryption
  • Sensitive data (passwords, API keys) encrypted using Fernet (symmetric encryption)
  • Encryption keys stored securely (not in version control)

Neo4j Database:

  • Enterprise Edition supports transparent data encryption
  • Community Edition: Use filesystem-level encryption

Example: Filesystem Encryption (Linux):

# LUKS encryption for data partition
sudo cryptsetup luksFormat /dev/sdb1
sudo cryptsetup luksOpen /dev/sdb1 encrypted_data
sudo mkfs.ext4 /dev/mapper/encrypted_data
sudo mount /dev/mapper/encrypted_data /var/lib/scidk

Backup Encryption:

# Encrypt backups with GPG
gpg --symmetric --cipher-algo AES256 backup.db

Encryption in Transit

HTTPS/TLS: All production deployments should use HTTPS:

# nginx configurationserver{listen443ssl http2;ssl_certificate /etc/ssl/certs/scidk.crt;ssl_certificate_key /etc/ssl/private/scidk.key; # Strong SSL configurationssl_protocols TLSv1.2 TLSv1.3;ssl_ciphers'ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256';ssl_prefer_server_ciphers on; # HSTSadd_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;}

Neo4j TLS: Configure Neo4j to use encrypted Bolt connections:

# neo4j.conf
dbms.connector.bolt.tls_level=REQUIRED
dbms.ssl.policy.bolt.enabled=true
dbms.ssl.policy.bolt.base_directory=certificates/bolt

API Communication:

  • All API endpoints should be accessed via HTTPS
  • Credentials never transmitted in plain text
  • Bearer tokens or session cookies for authentication

Audit Logging

Audit Trail Features

SciDK maintains comprehensive audit logs for:

  1. User Authentication Events:

    • Login attempts (success/failure)
    • Logout events
    • Session expiration
    • Password changes
  2. Data Access Events:

    • File access and downloads
    • Dataset queries
    • Graph queries
    • Export operations
  3. Administrative Actions:

    • User creation/modification/deletion
    • Settings changes
    • Backup operations
    • System configuration changes
  4. Security Events:

    • Failed authentication attempts
    • Permission denied errors
    • Suspicious activity patterns

Audit Log Format

{
"timestamp": "2024-01-15T10:30:00Z",
"event_type": "user.login",
"user": "admin",
"ip_address": "192.168.1.100",
"user_agent": "Mozilla/5.0...",
"status": "success",
"details": {
"session_id": "sess_abc123"
}
}

Accessing Audit Logs

Via systemd journals:

sudo journalctl -u scidk | grep AUDIT

Via SQLite database — the table is auth_audit_log in scidk_settings.db, and timestamp is a REAL epoch-seconds value, not a SQLite datetime string:

SELECTtimestamp, username, action, details, ip_address
FROM auth_audit_log
WHEREtimestamp> strftime('%s', 'now', '-7 days')
ORDER BYtimestampDESC;

Audit Log Retention

Recommended Retention Policies:

  • Security events: 1 year minimum
  • Authentication logs: 90 days minimum
  • Administrative actions: 1 year minimum
  • Data access: 30-90 days (or per compliance requirements)

Configure retention:

# systemd journal retention
sudo journalctl --vacuum-time=365d

Security Best Practices

Deployment Security

1. Network Security:

  • Deploy behind firewall
  • Use private networks for database connections
  • Limit exposed ports (only 443/80 for web, 7687 for internal Neo4j)
  • Implement IP allowlisting for admin access

Example firewall rules (ufw):

# Allow HTTPS
sudo ufw allow 443/tcp
# Allow Neo4j only from app server
sudo ufw allow from 10.0.1.10 to any port 7687
# Deny all other incoming
sudo ufw default deny incoming
sudo ufw enable

2. Operating System Security:

  • Keep OS and packages updated
  • Use dedicated service account (non-root)
  • Disable unnecessary services
  • Configure SELinux/AppArmor policies

3. Database Security:

  • Change default passwords immediately
  • Use strong authentication credentials
  • Regular security patches and updates
  • Database access restricted to application only

4. Application Security:

  • Run as non-privileged user
  • Use virtual environment isolation
  • Keep dependencies updated
  • Regular security scanning

Credential Management

Best Practices:

  1. Never commit credentials to version control
  2. Use environment variables or secret management systems
  3. Rotate credentials regularly (every 90 days)
  4. Use different credentials for dev/test/prod
  5. Encrypt credentials at rest

Example: Secret Management:

# Use environment variablesexport NEO4J_PASSWORD=$(vault read -field=password secret/neo4j)# Or use .env file (not in git)echo"NEO4J_AUTH=neo4j/$(openssl rand -base64 32)">> .env
chmod 600 .env

Credential Storage:

  • SciDK stores encrypted credentials in SQLite. Fernet (symmetric) encryption is used for SMTP/alert credentials, config-manager secrets, API-endpoint auth tokens, and plugin settings (scidk/core/plugin_settings.py).
  • Encryption key should be stored separately
  • Consider using external secret managers (HashiCorp Vault, AWS Secrets Manager)

Input Validation

SciDK implements input validation to prevent:

SQL Injection:

  • Parameterized queries for all database access
  • ORM-based database interactions
  • Input sanitization

Command Injection:

  • No shell command construction from user input
  • Subprocess calls use argument arrays (not shell=True)
  • Path validation for filesystem operations

Cross-Site Scripting (XSS):

  • HTML escaping in templates
  • Content Security Policy headers
  • Input sanitization

Path Traversal:

  • Path normalization
  • Validation against allowed directories
  • No direct user input in file paths

Session Security

Configuration⚠️Recommended / not yet implemented — the app does not currently set these cookie flags or enable CSRF protection; the snippet below is the recommended hardening to apply before multi-user production use:

# Flask session configuration (RECOMMENDED — not currently set in code)app.config.update(
SESSION_COOKIE_SECURE=True, # HTTPS onlySESSION_COOKIE_HTTPONLY=True, # No JavaScript accessSESSION_COOKIE_SAMESITE='Lax', # CSRF protectionPERMANENT_SESSION_LIFETIME=1800# 30 minutes
)

Session Management:

  • Automatic session expiration
  • Session invalidation on logout
  • Session regeneration after privilege escalation
  • Single sign-on support (if configured)

Secure Headers

Recommended HTTP Security Headers:

# nginx configurationadd_header X-Frame-Options "SAMEORIGIN" always;add_header X-Content-Type-Options "nosniff" always;add_header X-XSS-Protection "1; mode=block" always;add_header Referrer-Policy "strict-origin-when-cross-origin" always;add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline';" always;add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;

Compliance Considerations

HIPAA Compliance

For healthcare data:

Required Controls:

  1. Access Control: RBAC with unique user accounts
  2. Audit Controls: Comprehensive audit logging
  3. Integrity Controls: Data validation and checksums
  4. Transmission Security: TLS/HTTPS for all communications
  5. Authentication: Strong password policies
  6. Encryption: Data encryption at rest and in transit

BAA Requirements:

  • Ensure Business Associate Agreement with cloud providers
  • Document security policies and procedures
  • Regular security risk assessments
  • Incident response procedures

PHI Handling:

  • Minimize PHI exposure
  • De-identify data when possible
  • Secure disposal procedures
  • Access logging for all PHI

GDPR Compliance

For European data:

Right to Access:

  • Provide user data export functionality
  • API endpoints for data retrieval

Right to Erasure:

  • User deletion removes all associated data
  • Cascade delete for related records
  • Audit log of deletions (without retaining PII)

Right to Portability:

  • Export in machine-readable format (JSON, CSV)
  • Configuration backup/export functionality

Data Protection:

  • Encryption at rest and in transit
  • Access controls and audit logs
  • Privacy by design and default
  • Data minimization

Breach Notification:

  • 72-hour breach notification requirement
  • Incident response procedures
  • Contact data protection authorities

SOC 2 Compliance

For service organizations:

Trust Services Criteria:

  1. Security: Access controls, encryption, monitoring
  2. Availability: Uptime, redundancy, disaster recovery
  3. Processing Integrity: Data validation, error handling
  4. Confidentiality: Encryption, access controls
  5. Privacy: Data handling, consent management

Implementation:

  • Document security policies
  • Regular security assessments
  • Vendor management
  • Change management procedures
  • Incident response plan

Vulnerability Management

Security Updates

Update Process:

  1. Monitor security advisories for dependencies
  2. Test updates in staging environment
  3. Schedule maintenance window
  4. Apply updates and verify
  5. Document changes

Automated Scanning:

# Scan Python dependencies
pip install safety
safety check
# Scan for vulnerabilities
npm audit # If using Node.js tools

Penetration Testing

Recommended Schedule:

  • Annual penetration testing
  • After major releases
  • Before compliance audits

Testing Scope:

  • Web application security
  • API security
  • Authentication mechanisms
  • Database security
  • Network security

Responsible Disclosure

Security Issue Reporting:

  • Email: security@your-org.com
  • PGP key available for encrypted reports
  • Expected response time: 48 hours
  • Coordinated disclosure policy

Incident Response

Incident Response Plan

Phase 1: Detection

  • Monitor audit logs for suspicious activity
  • Alert system for security events
  • User reports of suspicious behavior

Phase 2: Containment

  • Isolate affected systems
  • Disable compromised accounts
  • Block malicious IP addresses
  • Preserve evidence

Phase 3: Eradication

  • Identify root cause
  • Remove malicious code/access
  • Patch vulnerabilities
  • Reset compromised credentials

Phase 4: Recovery

  • Restore from clean backups
  • Verify system integrity
  • Monitor for recurrence
  • Gradual service restoration

Phase 5: Lessons Learned

  • Document incident timeline
  • Identify improvements
  • Update procedures
  • Train personnel

Incident Response Procedures

Security Breach Response:

# 1. Isolate the system
sudo systemctl stop scidk
sudo ufw deny from suspicious_ip
# 2. Preserve evidence
sudo journalctl -u scidk > incident_logs.txt
cp ~/.scidk/db/files.db incident_db_$(date +%Y%m%d).backup
# 3. Reset credentials
./scripts/reset_all_passwords.sh
# 4. Restore from known good backup
cp ~/.scidk/db/files.db.verified ~/.scidk/db/files.db
# 5. Restart with monitoring
sudo systemctl start scidk
tail -f /var/log/syslog | grep scidk

Data Breach Response:

  1. Determine scope: What data was accessed?
  2. Notify affected parties (per regulations)
  3. Document the breach
  4. Report to authorities (if required)
  5. Implement additional controls

Incident Communication

Internal Communication:

  • Notify security team immediately
  • Escalate to management within 1 hour
  • Brief technical team on containment

External Communication:

  • Notify affected users (if PII compromised)
  • Regulatory notification (if required)
  • Public disclosure (if significant breach)

Communication Template:

Subject: Security Incident Notification
We are writing to inform you of a security incident that occurred on [date].
Incident Type: [Unauthorized access / Data breach / etc.]
Data Affected: [Description]
Actions Taken: [Containment, investigation, etc.]
User Actions Required: [Password reset, etc.]
We take security seriously and have implemented additional measures...

Security Monitoring

Real-Time Monitoring

Monitor for:

  • Failed login attempts (>5 in 5 minutes)
  • Unusual access patterns
  • Large data exports
  • Configuration changes
  • Database connection errors

Alert Configuration:

# Example alert rulealert_rules= {
"failed_logins": {
"condition": "count > 5 in 5 minutes",
"action": "email_admin",
"severity": "high"
}
}

Security Metrics

Track:

  • Authentication success/failure rate
  • Average session duration
  • API error rates
  • Disk space usage
  • Database connection pool status

Log Analysis

Regular Reviews:

  • Daily: Security event review
  • Weekly: Authentication pattern analysis
  • Monthly: Comprehensive security audit
  • Quarterly: Access control review
# Example log analysis# Failed logins
sudo journalctl -u scidk | grep "LOGIN_FAILED"| wc -l
# Unique IP addresses
sudo journalctl -u scidk | grep "LOGIN"| awk '{print $X}'| sort -u | wc -l

Security Checklist

Deployment Security Checklist

  • Change all default passwords
  • Enable HTTPS with valid certificates
  • Configure firewall rules
  • Enable authentication and RBAC
  • Set strong session timeout
  • Enable audit logging
  • Encrypt sensitive data at rest
  • Configure secure backup procedures
  • Set up security monitoring and alerts
  • Document incident response procedures
  • Perform security assessment
  • Train administrators on security procedures

Monthly Security Review

  • Review audit logs for anomalies
  • Check for security updates
  • Verify backup integrity
  • Review user accounts and permissions
  • Test disaster recovery procedures
  • Review alert configurations
  • Update documentation

Additional Resources

There aren't any published security advisories