DEV Community

Daniel Ioni
Daniel Ioni

Posted on

πŸ” MyZubster Security Audit Guide

πŸ” MyZubster Security Audit Guide

Complete guide to securing your MyZubster deployment – from best practices to penetration testing
πŸ“Œ What is This Guide?

This guide covers everything you need to secure your MyZubster deployment:

βœ… Security best practices – Foundation for a secure deployment

βœ… Common vulnerabilities – What to look for and how to fix

βœ… Penetration testing – How to test your own system

βœ… Secure coding – Writing secure code for MyZubster

βœ… Compliance – GDPR, privacy, and data protection

βœ… Incident response – What to do if you're compromised
Enter fullscreen mode Exit fullscreen mode

🧩 Security Architecture Overview
text

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚ MyZubster Security Architecture β”‚
β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
β”‚ β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Network Security Layer β”‚ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚
β”‚ β”‚ β”‚ SSL/ β”‚ β”‚ DDoS β”‚ β”‚ WAF β”‚ β”‚ VPN/ β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ TLS β”‚ β”‚ Protectionβ”‚ β”‚ β”‚ β”‚ Tor β”‚ β”‚ β”‚
β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ β”‚
β”‚ β–Ό β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Application Security Layer β”‚ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚
β”‚ β”‚ β”‚ JWT β”‚ β”‚ PGP β”‚ β”‚ Rate β”‚ β”‚ Input β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ Auth β”‚ β”‚ Encrypt β”‚ β”‚ Limit β”‚ β”‚ Validateβ”‚ β”‚ β”‚
β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚ β”‚
β”‚ β–Ό β”‚
β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚
β”‚ β”‚ Data Security Layer β”‚ β”‚
β”‚ β”‚ β”‚ β”‚
β”‚ β”‚ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”‚ β”‚
β”‚ β”‚ β”‚ Encrypt β”‚ β”‚ Backup β”‚ β”‚ Access β”‚ β”‚ Audit β”‚ β”‚ β”‚
β”‚ β”‚ β”‚ at Rest β”‚ β”‚ & DR β”‚ β”‚ Control β”‚ β”‚ Logs β”‚ β”‚ β”‚
β”‚ β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ β”‚
β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚
β”‚ β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

πŸ”§ Step 1: Security Best Practices
1.1 Environment Variables Security

File: .env (Production)
env

πŸ” PRODUCTION ENVIRONMENT VARIABLES

NEVER commit this file to GitHub!

Database

POSTGRES_PASSWORD=STRONG_PASSWORD_HERE
MONGO_PASSWORD=STRONG_PASSWORD_HERE

JWT Secrets

GATEWAY_JWT_SECRET=at_least_64_characters_random
MARKETPLACE_JWT_SECRET=at_least_64_characters_random

API Tokens

MYZUBSTER_API_TOKEN=generate_random_64_char_token

Webhook Secrets

WEBHOOK_SECRET=generate_random_64_char_secret

PGP

PGP_KEY_PASSPHRASE=strong_passphrase_here

Rate Limiting

RATE_LIMIT_WINDOW=900000
RATE_LIMIT_MAX=100

Session

SESSION_SECRET=at_least_64_characters_random

1.2 Secure Database Configuration

File: marketplace/config/database.js
javascript

const { Sequelize } = require('sequelize');

// Secure database configuration
const sequelize = new Sequelize({
dialect: 'postgres',
host: process.env.DB_HOST || 'localhost',
port: process.env.DB_PORT || 5432,
database: process.env.DB_NAME,
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
logging: process.env.NODE_ENV === 'production' ? false : console.log,
pool: {
max: 10,
min: 0,
acquire: 30000,
idle: 10000,
},
dialectOptions: {
ssl: process.env.NODE_ENV === 'production' ? {
require: true,
rejectUnauthorized: true,
ca: process.env.DB_CA_CERT,
} : false,
},
// Prevent SQL injection
quoteIdentifiers: false,
// Enable prepared statements
native: true,
});

// Connection pooling security
sequelize.connectionManager.pool.on('acquire', (connection) => {
console.log(πŸ”’ Connection acquired (${connection.connectionId}));
});

sequelize.connectionManager.pool.on('release', () => {
console.log('πŸ”“ Connection released');
});

module.exports = sequelize;

1.3 Secure Server Configuration

File: gateway/server.js (Security Updates)
javascript

const express = require('express');
const helmet = require('helmet');
const cors = require('cors');
const rateLimit = require('express-rate-limit');
const sanitize = require('express-sanitizer');
const xss = require('xss-clean');
const hpp = require('hpp');
const compression = require('compression');

const app = express();

// ============================================
// SECURITY MIDDLEWARE
// ============================================

// Helmet - sets various HTTP headers
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", "'unsafe-inline'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:", "https:"],
},
},
hsts: {
maxAge: 31536000,
includeSubDomains: true,
preload: true,
},
frameguard: {
action: 'deny',
},
}));

// CORS - restrict origins
app.use(cors({
origin: process.env.ALLOWED_ORIGINS ?
process.env.ALLOWED_ORIGINS.split(',') :
['http://localhost:4000', 'http://localhost:3000'],
credentials: true,
optionsSuccessStatus: 200,
}));

// Rate limiting
const limiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 100,
message: {
error: 'Too many requests from this IP, please try again later.',
},
standardHeaders: true,
legacyHeaders: false,
keyGenerator: (req) => req.ip,
});

app.use('/api', limiter);

// Stricter rate limit for auth endpoints
const authLimiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 5,
message: {
error: 'Too many authentication attempts, please try again later.',
},
keyGenerator: (req) => req.ip,
});

app.use('/api/auth', authLimiter);

// Data sanitization
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));
app.use(sanitize());

// XSS protection
app.use(xss());

// Prevent HTTP parameter pollution
app.use(hpp());

// Compression
app.use(compression());

// Trust proxy (behind reverse proxy)
app.set('trust proxy', 1);

// Remove X-Powered-By header
app.disable('x-powered-by');

// Request logging (security audit)
app.use((req, res, next) => {
const start = Date.now();
res.on('finish', () => {
const duration = Date.now() - start;
console.log(πŸ” ${req.method} ${req.originalUrl} ${res.statusCode} ${duration}ms - ${req.ip});
});
next();
});

module.exports = app;

πŸ›‘οΈ Step 2: Common Vulnerabilities & Fixes
2.1 SQL Injection Prevention

❌ Vulnerable Code:
javascript

// DO NOT DO THIS
const user = await sequelize.query(
SELECT * FROM Users WHERE email = '${req.body.email}'
);

βœ… Secure Code:
javascript

// Use Sequelize ORM
const user = await User.findOne({
where: { email: req.body.email },
});

// Or use parameterized queries
const user = await sequelize.query(
'SELECT * FROM Users WHERE email = ?',
{
replacements: [req.body.email],
type: Sequelize.QueryTypes.SELECT,
}
);

2.2 XSS Prevention

❌ Vulnerable Code:
javascript

// DO NOT DO THIS
app.get('/user/:id', (req, res) => {
res.send(<h1>User: ${req.params.id}</h1>);
});

βœ… Secure Code:
javascript

// Use sanitization
const sanitize = require('sanitize-html');

app.get('/user/:id', (req, res) => {
const safeHtml = sanitize(req.params.id, {
allowedTags: [],
allowedAttributes: {},
});
res.send(<h1>User: ${safeHtml}</h1>);
});

// Or use JSON responses
app.get('/user/:id', (req, res) => {
res.json({ user: req.params.id });
});

2.3 CSRF Protection

File: middleware/csrf.js
javascript

const csrf = require('csurf');

// CSRF protection
const csrfProtection = csrf({
cookie: {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
sameSite: 'strict',
},
});

// Generate CSRF token
app.get('/api/csrf-token', csrfProtection, (req, res) => {
res.json({ csrfToken: req.csrfToken() });
});

// Apply to all state-changing routes
app.post('/api/orders', csrfProtection, (req, res) => {
// Route logic
});

2.4 Insecure Direct Object Reference (IDOR)

❌ Vulnerable Code:
javascript

// DO NOT DO THIS
router.get('/orders/:id', auth, async (req, res) => {
const order = await Order.findByPk(req.params.id);
res.json(order);
});

βœ… Secure Code:
javascript

// Check user authorization
router.get('/orders/:id', auth, async (req, res) => {
const order = await Order.findByPk(req.params.id);
if (!order) {
return res.status(404).json({ error: 'Order not found' });
}

// Check ownership
if (order.buyerId !== req.user.id && order.sellerId !== req.user.id) {
return res.status(403).json({ error: 'Access denied' });
}

res.json(order);
});

2.5 JWT Security

File: middleware/auth.js (Secure Version)
javascript

const jwt = require('jsonwebtoken');
const { User } = require('../models');

// JWT configuration
const JWT_SECRET = process.env.JWT_SECRET;
const JWT_EXPIRY = '7d';
const JWT_REFRESH_EXPIRY = '30d';

// Generate JWT with secure options
const generateToken = (user) => {
return jwt.sign(
{
id: user.id,
email: user.email,
role: user.role,
iat: Math.floor(Date.now() / 1000),
},
JWT_SECRET,
{
expiresIn: JWT_EXPIRY,
algorithm: 'HS512',
}
);
};

// Refresh token
const generateRefreshToken = (user) => {
return jwt.sign(
{ id: user.id },
JWT_SECRET + user.password.slice(0, 10),
{ expiresIn: JWT_REFRESH_EXPIRY }
);
};

// Verify JWT with blacklist check
const auth = async (req, res, next) => {
try {
const token = req.header('Authorization')?.replace('Bearer ', '');

if (!token) {
  throw new Error();
}

// Check if token is blacklisted (logout)
const blacklisted = await TokenBlacklist.findOne({ where: { token } });
if (blacklisted) {
  throw new Error('Token invalidated');
}

const decoded = jwt.verify(token, JWT_SECRET, { algorithms: ['HS512'] });
const user = await User.findByPk(decoded.id);

if (!user || !user.isActive) {
  throw new Error();
}

req.user = user;
req.token = token;
next();
Enter fullscreen mode Exit fullscreen mode

} catch (error) {
res.status(401).json({ error: 'Authentication required' });
}
};

module.exports = {
auth,
generateToken,
generateRefreshToken,
};

πŸ” Step 3: Penetration Testing
3.1 Automated Scanning with OWASP ZAP

Script: scripts/zap-scan.sh
bash

!/bin/bash

OWASP ZAP Security Scan

Usage: ./zap-scan.sh

set -e

TARGET_URL=${1:-"http://localhost:4000"}
API_KEY=${2:-"your-zap-api-key"}

echo "πŸ” Starting OWASP ZAP scan..."

Start ZAP in headless mode

docker run -d -p 8080:8080 --name zap \
owasp/zap2docker-stable \
zap.sh -daemon -host 0.0.0.0 -port 8080 -config api.key=$API_KEY

sleep 10

Run active scan

curl "http://localhost:8080/JSON/ascan/action/scan/?url=$TARGET_URL&recurse=true&apikey=$API_KEY"

Wait for scan to complete

sleep 300

Generate report

curl "http://localhost:8080/OTHER/core/other/htmlreport/?apikey=$API_KEY" > zap-report.html

Stop ZAP

docker stop zap
docker rm zap

echo "βœ… ZAP scan complete. Report: zap-report.html"

3.2 Directory Scan with Gobuster
bash

Install Gobuster

go install github.com/OJ/gobuster/v3@latest

Scan for hidden directories

gobuster dir \
-u http://localhost:4000 \
-w /usr/share/wordlists/dirb/common.txt \
-t 50 \
-x .js,.css,.html,.txt \
-o directory-scan.txt

Scan for files

gobuster dir \
-u http://localhost:4000 \
-w /usr/share/wordlists/dirb/common.txt \
-x .php,.env,.git,.sql,.json \
-o file-scan.txt

3.3 SQL Injection Testing with SQLMap
bash

Install SQLMap

git clone https://github.com/sqlmapproject/sqlmap.git
cd sqlmap

Test for SQL injection

python sqlmap.py \
-u "http://localhost:4000/api/skills?category=development" \
--batch \
--level=3 \
--risk=2 \
--output-dir=./sqlmap-results

Test POST endpoints

python sqlmap.py \
-u "http://localhost:4000/api/auth/login" \
--data '{"email":"test@test.com","password":"test123"}' \
--headers "Content-Type: application/json" \
--batch \
--level=3

3.4 SSL/TLS Security Check
bash

Install testssl.sh

git clone https://github.com/drwetter/testssl.sh.git
cd testssl.sh

Run SSL/TLS security scan

./testssl.sh https://myzubster.com

Check for specific vulnerabilities

./testssl.sh -U -S -P https://myzubster.com

πŸ§ͺ Step 4: Security Headers
4.1 Security Headers Configuration

File: middleware/securityHeaders.js
javascript

const securityHeaders = (req, res, next) => {
// HSTS - Force HTTPS
res.setHeader(
'Strict-Transport-Security',
'max-age=31536000; includeSubDomains; preload'
);

// X-Frame-Options - Prevent clickjacking
res.setHeader('X-Frame-Options', 'DENY');

// X-Content-Type-Options - Prevent MIME sniffing
res.setHeader('X-Content-Type-Options', 'nosniff');

// X-XSS-Protection - XSS protection
res.setHeader('X-XSS-Protection', '1; mode=block');

// Referrer-Policy
res.setHeader('Referrer-Policy', 'strict-origin-when-cross-origin');

// Permissions-Policy
res.setHeader(
'Permissions-Policy',
'geolocation=(), microphone=(), camera=()'
);

// Content-Security-Policy
res.setHeader(
'Content-Security-Policy',
"default-src 'self'; " +
"script-src 'self' 'unsafe-inline'; " +
"style-src 'self' 'unsafe-inline'; " +
"img-src 'self' data: https:; " +
"connect-src 'self' https:; " +
"font-src 'self'; " +
"frame-ancestors 'none';"
);

// Feature-Policy (older browsers)
res.setHeader(
'Feature-Policy',
"geolocation 'none'; microphone 'none'; camera 'none'"
);

next();
};

module.exports = securityHeaders;

4.2 Check Security Headers
bash

Check headers with curl

curl -I https://myzubster.com

Use securityheaders.com

curl https://securityheaders.com/ -F "q=myzubster.com" -s

Or use the API

curl "https://api.securityheaders.com/?q=myzubster.com"

πŸ“Š Step 5: Vulnerability Scanning
5.1 Dependency Vulnerability Scanning

File: scripts/audit-deps.sh
bash

!/bin/bash

Dependency Vulnerability Audit

Usage: ./audit-deps.sh

set -e

echo "πŸ” Scanning dependencies for vulnerabilities..."

Scan Gateway

echo "πŸ“¦ Checking Gateway dependencies..."
cd gateway
npm audit --audit-level=high
npm outdated

Scan Marketplace

echo "πŸ“¦ Checking Marketplace dependencies..."
cd ../marketplace
npm audit --audit-level=high
npm outdated

Scan App

echo "πŸ“¦ Checking App dependencies..."
cd ../app
npm audit --audit-level=high
npm outdated

Generate report

npx audit-ci \
--moderate \
--report-type=summary \
--output-file=audit-report.txt

echo "βœ… Audit complete!"

5.2 Automated Vulnerability Scanning with Nmap
bash

Install Nmap

sudo apt-get install nmap

Basic port scan

nmap -sV -p- -T4 localhost

Vulnerability scan with NSE scripts

nmap -sV --script vuln -p 80,443 localhost

Full vulnerability scan

nmap -sV --script vuln --script-args vulns.showall -p 80,443,3000,4000 localhost

πŸ“ Step 6: Incident Response Plan
6.1 Incident Response Procedure

File: docs/incident-response.md
markdown

Incident Response Plan

1. Detection

Type Detection Method Response
Unauthorized Access Suspicious login attempts, monitoring logs Block IP, reset credentials
Data Breach Unusual database activity, missing data Quarantine, backup restore
DDoS Attack High traffic, service degradation Enable WAF, scale resources
Ransomware Encrypted files, ransom note Isolate system, restore backup

2. Containment

  1. Immediate Actions:

    • Disable compromised accounts
    • Revoke exposed credentials
    • Block malicious IPs
    • Take affected services offline
  2. Short-term Actions:

    • Restore from clean backups
    • Apply security patches
    • Enable additional monitoring

3. Eradication

  1. Root Cause Analysis:

    • Identify how the breach occurred
    • Review logs and access patterns
    • Check for malware or backdoors
  2. System Hardening:

    • Update all passwords
    • Patch vulnerabilities
    • Review security configurations

4. Recovery

  1. Restore Services:

    • Bring services online gradually
    • Monitor for unusual activity
    • Verify data integrity
  2. Communication:

    • Notify affected users
    • Document the incident
    • Update security policies

5. Lessons Learned

  1. Post-Incident Review:

    • What went wrong?
    • What worked?
    • What needs improvement?
  2. Preventive Measures:

    • Implement new security controls
    • Update incident response plan
    • Conduct training

6.2 Automated Incident Response Script

File: scripts/incident-response.sh
bash

!/bin/bash

Incident Response Script

Usage: ./incident-response.sh

set -e

echo "🚨 Incident Response Activated!"

1. Block suspicious IPs

echo "πŸ”’ Blocking suspicious IPs..."
iptables -A INPUT -s $SUSPICIOUS_IP -j DROP
ufw deny from $SUSPICIOUS_IP

2. Disable compromised user

echo "πŸ‘€ Disabling compromised user..."
docker exec myzubster-postgres psql -U myzubster myzubster \
-c "UPDATE Users SET isActive = false WHERE email = '$COMPROMISED_EMAIL';"

3. Revoke all tokens

echo "πŸ”‘ Revoking all tokens..."
docker exec myzubster-postgres psql -U myzubster myzubster \
-c "DELETE FROM TokenBlacklist;"

4. Enable WAF

echo "πŸ›‘οΈ Enabling Web Application Firewall..."
docker exec myzubster-nginx waf-enable

5. Start additional logging

echo "πŸ“Š Starting detailed logging..."
docker exec myzubster-gateway pm2 logs --lines 100 > incident-logs.txt

6. Create backup before changes

echo "πŸ’Ύ Creating backup before changes..."
./scripts/backup.sh

7. Notify admins

echo "πŸ“§ Sending alerts to admins..."
echo "🚨 Incident Response Activated at $(date)" | mail -s "Security Incident" admin@myzubster.com

echo "βœ… Incident response actions completed!"

🧩 Step 7: Security Checklist
βœ… Production Security Checklist
markdown

MyZubster Production Security Checklist

Environment & Configuration

  • [ ] All secrets stored in environment variables (.env)
  • [ ] .env file excluded from Git (.gitignore)
  • [ ] Different secrets for development and production
  • [ ] Production secrets are at least 64 characters long
  • [ ] Secrets rotated regularly (every 90 days)
  • [ ] Environment variables validated on startup

Network Security

  • [ ] HTTPS enabled with valid SSL certificate
  • [ ] SSL/TLS version 1.2 or higher
  • [ ] HSTS header enabled (Strict-Transport-Security)
  • [ ] WAF/Cloudflare enabled for DDoS protection
  • [ ] Firewall configured (only necessary ports open)
  • [ ] Rate limiting enabled for API endpoints
  • [ ] CORS configured with specific origins (not '*')

Authentication & Authorization

  • [ ] JWT tokens use strong algorithms (HS512/RS256)
  • [ ] JWT expiry configured (7 days or less)
  • [ ] Refresh token rotation implemented
  • [ ] Token blacklist for logout
  • [ ] Rate limiting for login attempts
  • [ ] Role-based access control (RBAC) implemented
  • [ ] Session management secure (httpOnly, secure cookies)

Data Security

  • [ ] Database connection uses SSL/TLS
  • [ ] Strong database passwords (generated, not typed)
  • [ ] Database backups encrypted
  • [ ] Personal data encrypted at rest (PGP)
  • [ ] GDPR/Privacy compliance for data handling
  • [ ] Audit logs for access to sensitive data
  • [ ] Data retention policy implemented

Code Security

  • [ ] Dependencies scanned for vulnerabilities
  • [ ] Input validation on all user inputs
  • [ ] SQL injection prevention (parameterized queries)
  • [ ] XSS prevention (sanitization, CSP headers)
  • [ ] CSRF protection for state-changing requests
  • [ ] IDOR prevention (authorization checks)
  • [ ] Error handling (no stack traces in production)

Monitoring & Logging

  • [ ] Centralized logging (ELK/SumoLogic/Datadog)
  • [ ] Monitoring and alerts (Prometheus/Grafana)
  • [ ] Audit logs for admin actions
  • [ ] Login attempt logging
  • [ ] API usage logging
  • [ ] Health check endpoint (for monitoring)

Backup & Recovery

  • [ ] Automated daily backups
  • [ ] Backups stored in separate location
  • [ ] Backup encryption
  • [ ] Backup retention policy (30 days minimum)
  • [ ] Recovery plan documented and tested
  • [ ] Disaster recovery plan in place

Compliance

  • [ ] GDPR compliance checklist completed
  • [ ] Privacy policy posted
  • [ ] Terms of service posted
  • [ ] Cookie consent implemented
  • [ ] Data deletion process documented

Third-Party Security

  • [ ] API keys stored securely (not in code)
  • [ ] Third-party dependencies vetted
  • [ ] Service accounts have least privilege
  • [ ] External services monitored for breaches

Regular Audits

  • [ ] Security headers checked monthly
  • [ ] Dependency scan performed monthly
  • [ ] Penetration test conducted quarterly
  • [ ] Security review after each major release
  • [ ] Security training for all contributors

🚨 Step 8: Security Monitoring Alerts
8.1 Critical Alerts to Configure
Alert Threshold Response
Failed Login Attempts >5 per IP per 5min Block IP, alert admin
Suspicious API Requests >100 per IP per 5min Rate limit, investigate
Database Errors >10 per 5min Check database health
High Memory Usage >80% for 5min Scale up, investigate
SSL Certificate Expiry <30 days Renew certificate
Backup Failure Any failure Check backup logs
User Deletion Bulk deletion Verify authorization
8.2 Slack Alert Integration

File: services/alertService.js
javascript

const axios = require('axios');

const SLACK_WEBHOOK = process.env.SLACK_WEBHOOK;
const SLACK_CHANNEL = process.env.SLACK_CHANNEL || '#alerts';

const sendAlert = async (message, level = 'info') => {
const colors = {
info: '#0077CC',
warning: '#FFA500',
error: '#FF0000',
critical: '#8B0000',
};

const payload = {
channel: SLACK_CHANNEL,
attachments: [
{
color: colors[level] || colors.info,
title: 🚨 ${level.toUpperCase()} Alert,
text: message,
fields: [
{
title: 'Environment',
value: process.env.NODE_ENV || 'development',
short: true,
},
{
title: 'Time',
value: new Date().toISOString(),
short: true,
},
],
footer: 'MyZubster Security Monitor',
ts: Math.floor(Date.now() / 1000),
},
],
};

try {
await axios.post(SLACK_WEBHOOK, payload);
} catch (error) {
console.error('Failed to send alert:', error);
}
};

// Alert thresholds
const checkSecurity = async () => {
// Check failed login attempts
const failedLogins = await getFailedLoginCount();
if (failedLogins > 10) {
await sendAlert(
⚠️ High failed login attempts: ${failedLogins} in 5 minutes,
'warning'
);
}

// Check database connections
const dbConnections = await getDatabaseConnections();
if (dbConnections > 50) {
await sendAlert(
⚠️ High database connections: ${dbConnections},
'warning'
);
}

// Check for suspicious activity
const suspiciousIPs = await getSuspiciousIPs();
if (suspiciousIPs.length > 0) {
await sendAlert(
🚨 Suspicious IPs detected: ${suspiciousIPs.join(', ')},
'critical'
);
}
};

// Run security checks every 5 minutes
setInterval(checkSecurity, 5 * 60 * 1000);

module.exports = {
sendAlert,
checkSecurity,
};

πŸ“š Resources

OWASP Top 10: owasp.org

Security Headers: securityheaders.com

SSL Labs: ssllabs.com

Nmap: nmap.org

OWASP ZAP: zaproxy.org

SQLMap: sqlmap.org

Gobuster: github.com/OJ/gobuster
Enter fullscreen mode Exit fullscreen mode

🌐 Connect with Me

πŸ“– Blog & Articles: DEV.to - Daniel Ioni
🐦 X (Twitter): @myzubster
πŸ’Ό LinkedIn: Daniel Ioni
πŸ™ GitHub: DanielIoni-creator
🎡 TikTok: @h4x0r_23

⭐ Star the project on GitHub – it helps a lot!

Built with ❀️ for privacy, freedom, and decentralization.

Stay secure! πŸš€
βœ… Instructions for Publishing

Copy all the content above

Go to dev.to/new

Set the editor to Markdown mode

Paste the content

Title: MyZubster Security Audit Guide: Securing Your Deployment

Tags: security, cybersecurity, devsecops, opensource

Publish!
Enter fullscreen mode Exit fullscreen mode

Top comments (0)