Server Security Best Practices 2025: Panduan Lengkap Mengamankan Server dan Infrastructure#
Keamanan server merupakan aspek krusial dalam era digital yang dipenuhi cyber threats yang semakin sophisticated. Dengan meningkatnya serangan ransomware, data breaches, dan advanced persistent threats (APT), implementasi server security best practices menjadi prioritas utama untuk melindungi aset digital dan business continuity.
Landscape Cyber Threats 2025#
Current Threat Landscape:#
- Ransomware attacks: Meningkat 41% dari tahun sebelumnya
- Supply chain attacks: Target pada third-party vendors
- AI-powered attacks: Automated dan sophisticated attacks
- Cloud misconfigurations: 95% cloud breaches karena human error
- Zero-day exploits: Serangan pada vulnerability yang belum dipatch
Common Attack Vectors:#
- Phishing dan social engineering: 82% data breaches melibatkan human element
- Unpatched vulnerabilities: 60% breaches melalui known vulnerabilities
- Weak credentials: Password-based attacks masih dominan
- Insider threats: 34% incidents melibatkan internal actors
- Misconfigured services: Default configurations yang tidak aman
Server Hardening Fundamentals#
1. Operating System Hardening#
Linux Server Hardening:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| # Update system packages
apt update && apt upgrade -y
# Remove unnecessary packages
apt autoremove -y
apt autoclean
# Disable unnecessary services
systemctl disable telnet
systemctl disable ftp
systemctl disable rsh
systemctl disable rlogin
# Configure automatic security updates
apt install unattended-upgrades
dpkg-reconfigure -plow unattended-upgrades
|
Kernel Security Parameters:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| # /etc/sysctl.conf security settings
# IP Spoofing protection
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.rp_filter = 1
# Ignore ICMP redirects
net.ipv4.conf.all.accept_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
# Ignore send redirects
net.ipv4.conf.all.send_redirects = 0
# Disable source packet routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
# Log Martians
net.ipv4.conf.all.log_martians = 1
# Ignore ping requests
net.ipv4.icmp_echo_ignore_all = 1
# Apply settings
sysctl -p
|
File System Security:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| # Secure mount options in /etc/fstab
/dev/sda1 /tmp ext4 defaults,nodev,nosuid,noexec 0 2
/dev/sda2 /var/tmp ext4 defaults,nodev,nosuid,noexec 0 2
/dev/sda3 /home ext4 defaults,nodev 0 2
# Set proper permissions
chmod 700 /root
chmod 755 /etc/passwd
chmod 644 /etc/group
chmod 600 /etc/shadow
chmod 600 /etc/gshadow
# Secure shared memory
echo "tmpfs /run/shm tmpfs defaults,noexec,nosuid 0 0" >> /etc/fstab
|
2. Windows Server Hardening#
Windows Security Configuration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| # Disable unnecessary services
Set-Service -Name "Telnet" -StartupType Disabled
Set-Service -Name "RemoteRegistry" -StartupType Disabled
Set-Service -Name "Messenger" -StartupType Disabled
# Configure Windows Firewall
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True
New-NetFirewallRule -DisplayName "Block Telnet" -Direction Inbound -Protocol TCP -LocalPort 23 -Action Block
# Enable Windows Defender
Set-MpPreference -DisableRealtimeMonitoring $false
Set-MpPreference -DisableBehaviorMonitoring $false
Set-MpPreference -DisableBlockAtFirstSeen $false
# Configure audit policies
auditpol /set /category:"Logon/Logoff" /success:enable /failure:enable
auditpol /set /category:"Account Management" /success:enable /failure:enable
|
Registry Security Settings:
1
2
3
4
5
6
7
8
| # Disable anonymous SID enumeration
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" -Name "RestrictAnonymousSAM" -Value 1
# Disable anonymous share enumeration
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" -Name "RestrictAnonymous" -Value 1
# Enable SMB signing
Set-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Services\lanmanserver\parameters" -Name "RequireSecuritySignature" -Value 1
|
Access Control dan Authentication#
1. Strong Authentication#
SSH Key-Based Authentication:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| # Generate SSH key pair
ssh-keygen -t ed25519 -b 4096 -f ~/.ssh/server_key
# Configure SSH server
# /etc/ssh/sshd_config
Protocol 2
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AuthorizedKeysFile .ssh/authorized_keys
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
AllowUsers admin developer
DenyUsers root guest
# Restart SSH service
systemctl restart sshd
|
Multi-Factor Authentication:
1
2
3
4
5
6
7
8
9
10
11
12
13
| # Install Google Authenticator PAM module
apt install libpam-google-authenticator
# Configure PAM
echo "auth required pam_google_authenticator.so" >> /etc/pam.d/sshd
# Configure SSH for 2FA
# /etc/ssh/sshd_config
ChallengeResponseAuthentication yes
AuthenticationMethods publickey,keyboard-interactive
# Setup 2FA for user
google-authenticator
|
2. Privilege Management#
Sudo Configuration:
1
2
3
4
5
6
7
8
9
10
11
| # /etc/sudoers.d/security
# Allow admin group with password
%admin ALL=(ALL:ALL) ALL
# Allow specific commands without password
developer ALL=(root) NOPASSWD: /bin/systemctl restart nginx
developer ALL=(root) NOPASSWD: /bin/systemctl reload apache2
# Log all sudo commands
Defaults logfile="/var/log/sudo.log"
Defaults log_input, log_output
|
Role-Based Access Control:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| # Create security groups
groupadd sysadmin
groupadd webadmin
groupadd dbadmin
# Assign users to groups
usermod -a -G sysadmin alice
usermod -a -G webadmin bob
usermod -a -G dbadmin charlie
# Set directory permissions
chown root:sysadmin /etc/security
chmod 750 /etc/security
chown root:webadmin /var/www
chmod 750 /var/www
chown mysql:dbadmin /var/lib/mysql
chmod 750 /var/lib/mysql
|
3. Account Security#
Password Policies:
1
2
3
4
5
6
7
8
9
10
11
| # /etc/login.defs
PASS_MAX_DAYS 90
PASS_MIN_DAYS 1
PASS_WARN_AGE 7
PASS_MIN_LEN 12
# Install password quality checking
apt install libpam-pwquality
# /etc/pam.d/common-password
password requisite pam_pwquality.so retry=3 minlen=12 difok=3 ucredit=-1 lcredit=-1 dcredit=-1 ocredit=-1
|
Account Lockout:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| # Install fail2ban
apt install fail2ban
# /etc/fail2ban/jail.local
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 3
backend = systemd
[sshd]
enabled = true
port = ssh
logpath = /var/log/auth.log
maxretry = 3
bantime = 3600
[apache-auth]
enabled = true
port = http,https
logpath = /var/log/apache2/error.log
maxretry = 3
|
Network Security#
1. Firewall Configuration#
iptables Rules:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
| #!/bin/bash
# Basic iptables firewall script
# Flush existing rules
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
# Set default policies
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT ACCEPT
# Allow loopback
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# Allow established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# Allow SSH (change port as needed)
iptables -A INPUT -p tcp --dport 22 -m state --state NEW -j ACCEPT
# Allow HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT
# Allow DNS
iptables -A INPUT -p udp --dport 53 -j ACCEPT
iptables -A INPUT -p tcp --dport 53 -j ACCEPT
# Rate limiting for SSH
iptables -A INPUT -p tcp --dport 22 -m recent --set --name SSH
iptables -A INPUT -p tcp --dport 22 -m recent --update --seconds 60 --hitcount 4 --name SSH -j DROP
# Log dropped packets
iptables -A INPUT -j LOG --log-prefix "iptables-dropped: "
# Save rules
iptables-save > /etc/iptables/rules.v4
|
UFW (Uncomplicated Firewall):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| # Enable UFW
ufw enable
# Default policies
ufw default deny incoming
ufw default allow outgoing
# Allow specific services
ufw allow ssh
ufw allow http
ufw allow https
# Allow from specific IP
ufw allow from 192.168.1.100 to any port 22
# Rate limiting
ufw limit ssh
# Show status
ufw status verbose
|
2. Network Segmentation#
VLAN Configuration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| # Create VLANs
ip link add link eth0 name eth0.10 type vlan id 10 # DMZ
ip link add link eth0 name eth0.20 type vlan id 20 # Internal
ip link add link eth0 name eth0.30 type vlan id 30 # Management
# Configure IP addresses
ip addr add 192.168.10.1/24 dev eth0.10 # DMZ
ip addr add 192.168.20.1/24 dev eth0.20 # Internal
ip addr add 192.168.30.1/24 dev eth0.30 # Management
# Bring interfaces up
ip link set dev eth0.10 up
ip link set dev eth0.20 up
ip link set dev eth0.30 up
|
Network Access Control:
1
2
3
4
5
6
7
8
9
10
11
12
13
| # Configure iptables for network segmentation
# Allow DMZ to Internet
iptables -A FORWARD -s 192.168.10.0/24 -o eth0 -j ACCEPT
# Block DMZ to Internal
iptables -A FORWARD -s 192.168.10.0/24 -d 192.168.20.0/24 -j DROP
# Allow Internal to DMZ (specific ports only)
iptables -A FORWARD -s 192.168.20.0/24 -d 192.168.10.0/24 -p tcp --dport 80 -j ACCEPT
iptables -A FORWARD -s 192.168.20.0/24 -d 192.168.10.0/24 -p tcp --dport 443 -j ACCEPT
# Management network access
iptables -A FORWARD -s 192.168.30.0/24 -j ACCEPT
|
3. Intrusion Detection#
Suricata IDS/IPS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
| # Install Suricata
apt install suricata
# Configure Suricata
# /etc/suricata/suricata.yaml
vars:
address-groups:
HOME_NET: "[192.168.0.0/16,10.0.0.0/8,172.16.0.0/12]"
EXTERNAL_NET: "!$HOME_NET"
HTTP_SERVERS: "$HOME_NET"
SMTP_SERVERS: "$HOME_NET"
SQL_SERVERS: "$HOME_NET"
DNS_SERVERS: "$HOME_NET"
# Enable rules
rule-files:
- suricata.rules
- emerging-threats.rules
- emerging-malware.rules
# Start Suricata
systemctl enable suricata
systemctl start suricata
|
OSSEC HIDS:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
| # Install OSSEC
wget https://github.com/ossec/ossec-hids/archive/3.7.0.tar.gz
tar -xzf 3.7.0.tar.gz
cd ossec-hids-3.7.0
./install.sh
# Configure OSSEC
# /var/ossec/etc/ossec.conf
<ossec_config>
<global>
<email_notification>yes</email_notification>
<email_to>[email protected]</email_to>
<smtp_server>localhost</smtp_server>
<email_from>[email protected]</email_from>
</global>
<rules>
<include>rules_config.xml</include>
<include>pam_rules.xml</include>
<include>sshd_rules.xml</include>
<include>telnetd_rules.xml</include>
<include>syslog_rules.xml</include>
<include>arpwatch_rules.xml</include>
<include>symantec-av_rules.xml</include>
<include>symantec-ws_rules.xml</include>
<include>pix_rules.xml</include>
<include>named_rules.xml</include>
<include>smbd_rules.xml</include>
<include>vsftpd_rules.xml</include>
<include>pure-ftpd_rules.xml</include>
<include>proftpd_rules.xml</include>
<include>ms_ftpd_rules.xml</include>
<include>ftpd_rules.xml</include>
<include>hordeimp_rules.xml</include>
<include>roundcube_rules.xml</include>
<include>wordpress_rules.xml</include>
<include>cimserver_rules.xml</include>
<include>vpopmail_rules.xml</include>
<include>vmpop3d_rules.xml</include>
<include>courier_rules.xml</include>
<include>web_rules.xml</include>
<include>web_appsec_rules.xml</include>
<include>apache_rules.xml</include>
<include>nginx_rules.xml</include>
<include>php_rules.xml</include>
<include>mysql_rules.xml</include>
<include>postgresql_rules.xml</include>
<include>ids_rules.xml</include>
<include>squid_rules.xml</include>
<include>firewall_rules.xml</include>
<include>cisco-ios_rules.xml</include>
<include>netscreenfw_rules.xml</include>
<include>sonicwall_rules.xml</include>
<include>postfix_rules.xml</include>
<include>sendmail_rules.xml</include>
<include>imapd_rules.xml</include>
<include>mailscanner_rules.xml</include>
<include>dovecot_rules.xml</include>
<include>ms-exchange_rules.xml</include>
<include>racoon_rules.xml</include>
<include>vpn_concentrator_rules.xml</include>
<include>spamd_rules.xml</include>
<include>msauth_rules.xml</include>
<include>mcafee_av_rules.xml</include>
<include>trend-osce_rules.xml</include>
<include>ms-se_rules.xml</include>
<include>zeus_rules.xml</include>
<include>solaris_bsm_rules.xml</include>
<include>vmware_rules.xml</include>
<include>ms_dhcp_rules.xml</include>
<include>asterisk_rules.xml</include>
<include>ossec_rules.xml</include>
<include>attack_rules.xml</include>
<include>local_rules.xml</include>
</rules>
<syscheck>
<frequency>79200</frequency>
<directories check_all="yes">/etc,/usr/bin,/usr/sbin</directories>
<directories check_all="yes">/bin,/sbin,/boot</directories>
<ignore>/etc/mtab</ignore>
<ignore>/etc/hosts.deny</ignore>
<ignore>/etc/mail/statistics</ignore>
<ignore>/etc/random-seed</ignore>
<ignore>/etc/random.seed</ignore>
<ignore>/etc/adjtime</ignore>
<ignore>/etc/httpd/logs</ignore>
<ignore>/etc/utmpx</ignore>
<ignore>/etc/wtmpx</ignore>
<ignore>/etc/cups/certs</ignore>
<ignore>/etc/dumpdates</ignore>
<ignore>/etc/svc/volatile</ignore>
</syscheck>
<rootcheck>
<rootkit_files>/var/ossec/etc/shared/rootkit_files.txt</rootkit_files>
<rootkit_trojans>/var/ossec/etc/shared/rootkit_trojans.txt</rootkit_trojans>
<system_audit>/var/ossec/etc/shared/system_audit_rcl.txt</system_audit>
<system_audit>/var/ossec/etc/shared/system_audit_ssh.txt</system_audit>
<system_audit>/var/ossec/etc/shared/cis_debian_linux_rcl.txt</system_audit>
<system_audit>/var/ossec/etc/shared/cis_rhel_linux_rcl.txt</system_audit>
<system_audit>/var/ossec/etc/shared/cis_rhel5_linux_rcl.txt</system_audit>
</rootcheck>
<localfile>
<log_format>syslog</log_format>
<location>/var/log/messages</location>
</localfile>
<localfile>
<log_format>syslog</log_format>
<location>/var/log/authlog</location>
</localfile>
<localfile>
<log_format>syslog</log_format>
<location>/var/log/secure</location>
</localfile>
<localfile>
<log_format>syslog</log_format>
<location>/var/log/xferlog</location>
</localfile>
<localfile>
<log_format>syslog</log_format>
<location>/var/log/maillog</location>
</localfile>
<localfile>
<log_format>apache</log_format>
<location>/var/log/httpd/error_log</location>
</localfile>
<localfile>
<log_format>apache</log_format>
<location>/var/log/httpd/access_log</location>
</localfile>
<localfile>
<log_format>apache</log_format>
<location>/var/log/apache2/error.log</location>
</localfile>
<localfile>
<log_format>apache</log_format>
<location>/var/log/apache2/access.log</location>
</localfile>
</ossec_config>
|
Application Security#
1. Web Server Security#
Apache Security Configuration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
| # /etc/apache2/conf-available/security.conf
# Hide server information
ServerTokens Prod
ServerSignature Off
# Security headers
Header always set X-Content-Type-Options nosniff
Header always set X-Frame-Options DENY
Header always set X-XSS-Protection "1; mode=block"
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
Header always set Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'"
# Disable unnecessary modules
# a2dismod autoindex
# a2dismod status
# a2dismod info
# Limit request size
LimitRequestBody 10485760 # 10MB
# Timeout settings
Timeout 60
KeepAliveTimeout 15
# Hide .htaccess files
<FilesMatch "^\.ht">
Require all denied
</FilesMatch>
# Disable server-status and server-info
<Location "/server-status">
Require all denied
</Location>
<Location "/server-info">
Require all denied
</Location>
|
Nginx Security Configuration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
| # /etc/nginx/nginx.conf
# Hide server information
server_tokens off;
# Security headers
add_header X-Frame-Options DENY;
add_header X-Content-Type-Options nosniff;
add_header X-XSS-Protection "1; mode=block";
add_header Strict-Transport-Security "max-age=63072000; includeSubDomains; preload";
add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'";
# Rate limiting
limit_req_zone $binary_remote_addr zone=login:10m rate=1r/s;
limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
# Client body size
client_max_body_size 10M;
# Timeouts
client_body_timeout 12;
client_header_timeout 12;
keepalive_timeout 15;
send_timeout 10;
# Hide sensitive files
location ~ /\. {
deny all;
access_log off;
log_not_found off;
}
location ~ ~$ {
deny all;
access_log off;
log_not_found off;
}
# Rate limiting for login
location /login {
limit_req zone=login burst=5 nodelay;
# ... other directives
}
|
2. Database Security#
MySQL Security:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
| -- Remove anonymous users
DELETE FROM mysql.user WHERE User='';
-- Remove remote root access
DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1');
-- Remove test database
DROP DATABASE IF EXISTS test;
DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%';
-- Create application user with limited privileges
CREATE USER 'appuser'@'localhost' IDENTIFIED BY 'strong_password';
GRANT SELECT, INSERT, UPDATE, DELETE ON myapp.* TO 'appuser'@'localhost';
-- Configure SSL
-- /etc/mysql/mysql.conf.d/mysqld.cnf
[mysqld]
ssl-ca=/etc/mysql/ssl/ca-cert.pem
ssl-cert=/etc/mysql/ssl/server-cert.pem
ssl-key=/etc/mysql/ssl/server-key.pem
require_secure_transport=ON
-- Enable binary logging for point-in-time recovery
log-bin=mysql-bin
binlog-format=ROW
expire_logs_days=7
-- Security settings
local-infile=0
skip-show-database
safe-user-create=1
|
PostgreSQL Security:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| -- postgresql.conf security settings
ssl = on
ssl_cert_file = 'server.crt'
ssl_key_file = 'server.key'
ssl_ca_file = 'ca.crt'
ssl_crl_file = 'server.crl'
-- Authentication settings
password_encryption = scram-sha-256
log_connections = on
log_disconnections = on
log_statement = 'all'
-- pg_hba.conf - require SSL
hostssl all all 0.0.0.0/0 scram-sha-256
-- Create application user
CREATE USER appuser WITH PASSWORD 'strong_password';
GRANT CONNECT ON DATABASE myapp TO appuser;
GRANT USAGE ON SCHEMA public TO appuser;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO appuser;
|
3. Application-Level Security#
PHP Security Configuration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| ; php.ini security settings
expose_php = Off
display_errors = Off
log_errors = On
error_log = /var/log/php_errors.log
; Disable dangerous functions
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,curl_exec,curl_multi_exec,parse_ini_file,show_source
; File upload security
file_uploads = On
upload_max_filesize = 2M
max_file_uploads = 20
upload_tmp_dir = /tmp
; Session security
session.cookie_httponly = 1
session.cookie_secure = 1
session.use_strict_mode = 1
session.cookie_samesite = "Strict"
; SQL injection protection
magic_quotes_gpc = Off
register_globals = Off
|
Input Validation Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
| <?php
// Input validation and sanitization
function validateInput($input, $type) {
switch($type) {
case 'email':
return filter_var($input, FILTER_VALIDATE_EMAIL);
case 'int':
return filter_var($input, FILTER_VALIDATE_INT);
case 'string':
return htmlspecialchars(trim($input), ENT_QUOTES, 'UTF-8');
case 'url':
return filter_var($input, FILTER_VALIDATE_URL);
default:
return false;
}
}
// Prepared statements for database queries
function getUserById($pdo, $userId) {
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$userId]);
return $stmt->fetch();
}
// CSRF protection
function generateCSRFToken() {
if (empty($_SESSION['csrf_token'])) {
$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}
return $_SESSION['csrf_token'];
}
function validateCSRFToken($token) {
return hash_equals($_SESSION['csrf_token'], $token);
}
?>
|
Encryption dan Data Protection#
1. Data Encryption at Rest#
File System Encryption:
1
2
3
4
5
6
7
8
9
10
11
12
| # LUKS encryption setup
cryptsetup luksFormat /dev/sdb
cryptsetup luksOpen /dev/sdb encrypted_disk
mkfs.ext4 /dev/mapper/encrypted_disk
# Mount encrypted filesystem
mkdir /encrypted
mount /dev/mapper/encrypted_disk /encrypted
# Auto-mount with key file
echo "encrypted_disk /dev/sdb /etc/luks-keys/disk.key luks" >> /etc/crypttab
echo "/dev/mapper/encrypted_disk /encrypted ext4 defaults 0 2" >> /etc/fstab
|
Database Encryption:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| -- MySQL Transparent Data Encryption
-- my.cnf
[mysqld]
early-plugin-load=keyring_file.so
keyring_file_data=/var/lib/mysql-keyring/keyring
-- Create encrypted table
CREATE TABLE sensitive_data (
id INT PRIMARY KEY,
data TEXT
) ENCRYPTION='Y';
-- PostgreSQL encryption
-- Enable pgcrypto extension
CREATE EXTENSION pgcrypto;
-- Encrypt sensitive data
INSERT INTO users (username, password)
VALUES ('john', crypt('password', gen_salt('bf')));
|
2. Data Encryption in Transit#
SSL/TLS Configuration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| # Generate SSL certificate
openssl req -x509 -nodes -days 365 -newkey rsa:4096 \
-keyout /etc/ssl/private/server.key \
-out /etc/ssl/certs/server.crt
# Strong SSL configuration for Apache
# /etc/apache2/sites-available/ssl.conf
<VirtualHost *:443>
SSLEngine on
SSLCertificateFile /etc/ssl/certs/server.crt
SSLCertificateKeyFile /etc/ssl/private/server.key
# Strong SSL protocols and ciphers
SSLProtocol all -SSLv2 -SSLv3 -TLSv1 -TLSv1.1
SSLCipherSuite ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305
SSLHonorCipherOrder on
# HSTS
Header always set Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
</VirtualHost>
|
VPN Configuration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
| # OpenVPN server configuration
# /etc/openvpn/server.conf
port 1194
proto udp
dev tun
ca ca.crt
cert server.crt
key server.key
dh dh2048.pem
server 10.8.0.0 255.255.255.0
ifconfig-pool-persist ipp.txt
# Security settings
cipher AES-256-CBC
auth SHA256
tls-auth ta.key 0
tls-version-min 1.2
# Client configuration
push "redirect-gateway def1 bypass-dhcp"
push "dhcp-option DNS 8.8.8.8"
push "dhcp-option DNS 8.8.4.4"
keepalive 10 120
comp-lzo
user nobody
group nogroup
persist-key
persist-tun
status openvpn-status.log
log-append /var/log/openvpn.log
verb 3
|
Security Monitoring dan Logging#
1. Centralized Logging#
Rsyslog Configuration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| # /etc/rsyslog.conf
# Enable remote logging
*.* @@log-server:514
# Local logging rules
auth,authpriv.* /var/log/auth.log
*.*;auth,authpriv.none -/var/log/syslog
daemon.* -/var/log/daemon.log
kern.* -/var/log/kern.log
mail.* -/var/log/mail.log
user.* -/var/log/user.log
# Security events
local0.* /var/log/security.log
|
ELK Stack Setup:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
| # docker-compose.yml for ELK stack
version: '3.7'
services:
elasticsearch:
image: docker.elastic.co/elasticsearch/elasticsearch:7.15.0
environment:
- discovery.type=single-node
- "ES_JAVA_OPTS=-Xms512m -Xmx512m"
ports:
- "9200:9200"
volumes:
- elasticsearch_data:/usr/share/elasticsearch/data
logstash:
image: docker.elastic.co/logstash/logstash:7.15.0
ports:
- "5044:5044"
volumes:
- ./logstash.conf:/usr/share/logstash/pipeline/logstash.conf
depends_on:
- elasticsearch
kibana:
image: docker.elastic.co/kibana/kibana:7.15.0
ports:
- "5601:5601"
environment:
- ELASTICSEARCH_HOSTS=http://elasticsearch:9200
depends_on:
- elasticsearch
volumes:
elasticsearch_data:
|
Logstash Configuration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
| # logstash.conf
input {
beats {
port => 5044
}
syslog {
port => 514
}
}
filter {
if [type] == "syslog" {
grok {
match => { "message" => "%{SYSLOGTIMESTAMP:timestamp} %{IPORHOST:host} %{DATA:program}(?:\[%{POSINT:pid}\])?: %{GREEDYDATA:message}" }
}
date {
match => [ "timestamp", "MMM d HH:mm:ss", "MMM dd HH:mm:ss" ]
}
}
if [program] == "sshd" {
if "Failed password" in [message] {
mutate {
add_tag => [ "ssh_failed_login" ]
}
}
}
}
output {
elasticsearch {
hosts => ["elasticsearch:9200"]
index => "logs-%{+YYYY.MM.dd}"
}
}
|
Wazuh SIEM Setup:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
| # Install Wazuh manager
curl -s https://packages.wazuh.com/key/GPG-KEY-WAZUH | apt-key add -
echo "deb https://packages.wazuh.com/4.x/apt/ stable main" | tee /etc/apt/sources.list.d/wazuh.list
apt update
apt install wazuh-manager
# Configure Wazuh
# /var/ossec/etc/ossec.conf
<ossec_config>
<global>
<jsonout_output>yes</jsonout_output>
<alerts_log>yes</alerts_log>
<logall>no</logall>
<logall_json>no</logall_json>
<email_notification>yes</email_notification>
<smtp_server>localhost</smtp_server>
<email_from>[email protected]</email_from>
<email_to>[email protected]</email_to>
</global>
<rules>
<include>rules_config.xml</include>
<include>pam_rules.xml</include>
<include>sshd_rules.xml</include>
<include>apache_rules.xml</include>
<include>nginx_rules.xml</include>
<include>web_rules.xml</include>
<include>local_rules.xml</include>
</rules>
<syscheck>
<disabled>no</disabled>
<frequency>43200</frequency>
<scan_on_start>yes</scan_on_start>
<directories check_all="yes">/etc,/usr/bin,/usr/sbin</directories>
<directories check_all="yes">/bin,/sbin</directories>
</syscheck>
<rootcheck>
<disabled>no</disabled>
<check_files>yes</check_files>
<check_trojans>yes</check_trojans>
<check_dev>yes</check_dev>
<check_sys>yes</check_sys>
<check_pids>yes</check_pids>
<check_ports>yes</check_ports>
<check_if>yes</check_if>
</rootcheck>
<wodle name="cis-cat">
<disabled>yes</disabled>
<timeout>1800</timeout>
<interval>1d</interval>
<scan-on-start>yes</scan-on-start>
</wodle>
<wodle name="osquery">
<disabled>yes</disabled>
<run_daemon>yes</run_daemon>
<log_path>/var/log/osquery/osqueryd.results.log</log_path>
<config_path>/etc/osquery/osquery.conf</config_path>
<add_labels>yes</add_labels>
</wodle>
<wodle name="syscollector">
<disabled>no</disabled>
<interval>1h</interval>
<scan_on_start>yes</scan_on_start>
<hardware>yes</hardware>
<os>yes</os>
<network>yes</network>
<packages>yes</packages>
<ports all="no">yes</ports>
<processes>yes</processes>
</wodle>
<wodle name="vulnerability-detector">
<disabled>no</disabled>
<interval>5m</interval>
<run_on_start>yes</run_on_start>
<feed name="ubuntu-18">
<disabled>no</disabled>
<update_interval>1h</update_interval>
</feed>
<feed name="redhat">
<disabled>no</disabled>
<update_interval>1h</update_interval>
</feed>
</wodle>
</ossec_config>
|
3. Real-time Alerting#
Custom Alert Scripts:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
| #!/bin/bash
# security_alert.sh
ALERT_TYPE="$1"
ALERT_MESSAGE="$2"
ALERT_SEVERITY="$3"
# Slack notification
send_slack_alert() {
local webhook_url="https://hooks.slack.com/services/YOUR/WEBHOOK/URL"
local payload="{\"text\":\"🚨 Security Alert: $ALERT_TYPE\n$ALERT_MESSAGE\nSeverity: $ALERT_SEVERITY\"}"
curl -X POST -H 'Content-type: application/json' \
--data "$payload" "$webhook_url"
}
# Email notification
send_email_alert() {
echo "Security Alert: $ALERT_TYPE
Message: $ALERT_MESSAGE
Severity: $ALERT_SEVERITY
Time: $(date)
Server: $(hostname)" | mail -s "Security Alert: $ALERT_TYPE" [email protected]
}
# PagerDuty integration
send_pagerduty_alert() {
local integration_key="YOUR_INTEGRATION_KEY"
local payload="{
\"routing_key\": \"$integration_key\",
\"event_action\": \"trigger\",
\"payload\": {
\"summary\": \"Security Alert: $ALERT_TYPE\",
\"source\": \"$(hostname)\",
\"severity\": \"$ALERT_SEVERITY\",
\"custom_details\": {
\"message\": \"$ALERT_MESSAGE\"
}
}
}"
curl -X POST -H 'Content-Type: application/json' \
-d "$payload" \
https://events.pagerduty.com/v2/enqueue
}
# Send alerts based on severity
case "$ALERT_SEVERITY" in
"critical")
send_slack_alert
send_email_alert
send_pagerduty_alert
;;
"high")
send_slack_alert
send_email_alert
;;
"medium")
send_slack_alert
;;
*)
echo "Alert logged: $ALERT_TYPE - $ALERT_MESSAGE"
;;
esac
|
Vulnerability Management#
1. Vulnerability Scanning#
OpenVAS Setup:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| # Install OpenVAS
apt update
apt install openvas
# Setup OpenVAS
gvm-setup
# Start services
systemctl start ospd-openvas
systemctl start gvmd
systemctl start gsad
# Create admin user
gvmd --create-user=admin --password=admin_password
# Update feeds
greenbone-feed-sync --type GVMD_DATA
greenbone-feed-sync --type SCAP
greenbone-feed-sync --type CERT
|
Nessus Configuration:
1
2
3
4
5
6
7
8
9
| # Download and install Nessus
wget https://www.tenable.com/downloads/api/v1/public/pages/nessus/downloads/nessus-latest-ubuntu1404_amd64.deb
dpkg -i nessus-latest-ubuntu1404_amd64.deb
# Start Nessus
systemctl start nessusd
systemctl enable nessusd
# Access web interface at https://localhost:8834
|
Automated Vulnerability Scanning:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
| #!/bin/bash
# vulnerability_scan.sh
SCAN_TARGET="$1"
REPORT_DIR="/var/reports/vulnerability"
DATE=$(date +%Y%m%d_%H%M%S)
# Create report directory
mkdir -p "$REPORT_DIR"
# Nmap vulnerability scan
nmap --script vuln "$SCAN_TARGET" > "$REPORT_DIR/nmap_vuln_$DATE.txt"
# Nikto web vulnerability scan
if [[ "$SCAN_TARGET" =~ ^https?:// ]]; then
nikto -h "$SCAN_TARGET" -output "$REPORT_DIR/nikto_$DATE.txt"
fi
# Custom vulnerability checks
check_ssl_vulnerabilities() {
local target="$1"
sslscan "$target" > "$REPORT_DIR/sslscan_$DATE.txt"
testssl.sh "$target" > "$REPORT_DIR/testssl_$DATE.txt"
}
# Generate summary report
generate_summary() {
echo "Vulnerability Scan Summary - $(date)" > "$REPORT_DIR/summary_$DATE.txt"
echo "Target: $SCAN_TARGET" >> "$REPORT_DIR/summary_$DATE.txt"
echo "----------------------------------------" >> "$REPORT_DIR/summary_$DATE.txt"
# Count vulnerabilities
local high_vulns=$(grep -c "HIGH" "$REPORT_DIR"/*_$DATE.txt 2>/dev/null || echo 0)
local medium_vulns=$(grep -c "MEDIUM" "$REPORT_DIR"/*_$DATE.txt 2>/dev/null || echo 0)
local low_vulns=$(grep -c "LOW" "$REPORT_DIR"/*_$DATE.txt 2>/dev/null || echo 0)
echo "High Risk Vulnerabilities: $high_vulns" >> "$REPORT_DIR/summary_$DATE.txt"
echo "Medium Risk Vulnerabilities: $medium_vulns" >> "$REPORT_DIR/summary_$DATE.txt"
echo "Low Risk Vulnerabilities: $low_vulns" >> "$REPORT_DIR/summary_$DATE.txt"
# Send alert if high-risk vulnerabilities found
if [ "$high_vulns" -gt 0 ]; then
/scripts/security_alert.sh "High Risk Vulnerabilities Found" \
"$high_vulns high-risk vulnerabilities detected on $SCAN_TARGET" "high"
fi
}
# Run scans
if [[ "$SCAN_TARGET" =~ ^https?:// ]]; then
check_ssl_vulnerabilities "$SCAN_TARGET"
fi
generate_summary
echo "Vulnerability scan completed. Reports saved to $REPORT_DIR"
|
2. Patch Management#
Automated Patch Management:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
| #!/bin/bash
# patch_management.sh
LOG_FILE="/var/log/patch_management.log"
REBOOT_REQUIRED_FILE="/var/run/reboot-required"
log_message() {
echo "$(date): $1" >> "$LOG_FILE"
}
# Check for available updates
check_updates() {
log_message "Checking for available updates..."
apt update
local updates=$(apt list --upgradable 2>/dev/null | grep -c upgradable)
log_message "Found $updates available updates"
return $updates
}
# Install security updates
install_security_updates() {
log_message "Installing security updates..."
# Install unattended-upgrades if not present
if ! dpkg -l | grep -q unattended-upgrades; then
apt install -y unattended-upgrades
fi
# Configure automatic security updates
cat > /etc/apt/apt.conf.d/50unattended-upgrades << EOF
Unattended-Upgrade::Allowed-Origins {
"\${distro_id}:\${distro_codename}-security";
"\${distro_id} ESMApps:\${distro_codename}-apps-security";
"\${distro_id} ESM:\${distro_codename}-infra-security";
};
Unattended-Upgrade::AutoFixInterruptedDpkg "true";
Unattended-Upgrade::MinimalSteps "true";
Unattended-Upgrade::Remove-Unused-Dependencies "true";
Unattended-Upgrade::Automatic-Reboot "false";
Unattended-Upgrade::Automatic-Reboot-Time "02:00";
EOF
# Run unattended upgrades
unattended-upgrade -d
log_message "Security updates installation completed"
}
# Check if reboot is required
check_reboot_required() {
if [ -f "$REBOOT_REQUIRED_FILE" ]; then
log_message "Reboot required after updates"
# Send notification
/scripts/security_alert.sh "Reboot Required" \
"Server $(hostname) requires reboot after security updates" "medium"
return 0
fi
return 1
}
# Main execution
main() {
log_message "Starting patch management process"
if check_updates; then
install_security_updates
if check_reboot_required; then
log_message "Scheduling reboot for maintenance window"
# Schedule reboot during maintenance window
echo "shutdown -r +60" | at 02:00
fi
else
log_message "No updates available"
fi
log_message "Patch management process completed"
}
main "$@"
|
3. Configuration Management#
Ansible Security Playbook:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
| # security_hardening.yml
---
- name: Server Security Hardening
hosts: all
become: yes
vars:
security_packages:
- fail2ban
- ufw
- aide
- rkhunter
- chkrootkit
tasks:
- name: Update package cache
apt:
update_cache: yes
cache_valid_time: 3600
- name: Install security packages
apt:
name: "{{ security_packages }}"
state: present
- name: Configure SSH security
lineinfile:
path: /etc/ssh/sshd_config
regexp: "{{ item.regexp }}"
line: "{{ item.line }}"
backup: yes
with_items:
- { regexp: '^PermitRootLogin', line: 'PermitRootLogin no' }
- { regexp: '^PasswordAuthentication', line: 'PasswordAuthentication no' }
- { regexp: '^MaxAuthTries', line: 'MaxAuthTries 3' }
- { regexp: '^ClientAliveInterval', line: 'ClientAliveInterval 300' }
- { regexp: '^ClientAliveCountMax', line: 'ClientAliveCountMax 2' }
notify: restart ssh
- name: Configure UFW firewall
ufw:
rule: "{{ item.rule }}"
port: "{{ item.port }}"
proto: "{{ item.proto | default('tcp') }}"
with_items:
- { rule: 'allow', port: '22' }
- { rule: 'allow', port: '80' }
- { rule: 'allow', port: '443' }
- name: Enable UFW
ufw:
state: enabled
policy: deny
direction: incoming
- name: Configure fail2ban
template:
src: jail.local.j2
dest: /etc/fail2ban/jail.local
backup: yes
notify: restart fail2ban
- name: Set up AIDE
command: aideinit
args:
creates: /var/lib/aide/aide.db
- name: Schedule AIDE checks
cron:
name: "AIDE integrity check"
minute: "0"
hour: "2"
job: "/usr/bin/aide --check"
- name: Configure kernel security parameters
sysctl:
name: "{{ item.name }}"
value: "{{ item.value }}"
state: present
reload: yes
with_items:
- { name: 'net.ipv4.conf.default.rp_filter', value: '1' }
- { name: 'net.ipv4.conf.all.rp_filter', value: '1' }
- { name: 'net.ipv4.conf.all.accept_redirects', value: '0' }
- { name: 'net.ipv6.conf.all.accept_redirects', value: '0' }
- { name: 'net.ipv4.conf.all.send_redirects', value: '0' }
- { name: 'net.ipv4.conf.all.accept_source_route', value: '0' }
- { name: 'net.ipv6.conf.all.accept_source_route', value: '0' }
- { name: 'net.ipv4.conf.all.log_martians', value: '1' }
handlers:
- name: restart ssh
service:
name: ssh
state: restarted
- name: restart fail2ban
service:
name: fail2ban
state: restarted
|
Incident Response#
1. Incident Response Plan#
Incident Classification:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
| Severity 1 (Critical):
- Active data breach
- Ransomware infection
- Complete system compromise
- Response Time: Immediate (< 15 minutes)
Severity 2 (High):
- Suspected data breach
- Malware detection
- Unauthorized access
- Response Time: < 1 hour
Severity 3 (Medium):
- Security policy violations
- Failed login attempts
- Suspicious activities
- Response Time: < 4 hours
Severity 4 (Low):
- Security awareness issues
- Minor policy violations
- Response Time: < 24 hours
|
Incident Response Procedures:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
| #!/bin/bash
# incident_response.sh
INCIDENT_ID="INC-$(date +%Y%m%d-%H%M%S)"
INCIDENT_DIR="/var/incidents/$INCIDENT_ID"
LOG_FILE="$INCIDENT_DIR/incident.log"
# Create incident directory
mkdir -p "$INCIDENT_DIR"
log_incident() {
echo "$(date): $1" | tee -a "$LOG_FILE"
}
# Phase 1: Preparation
prepare_response() {
log_incident "Incident Response Started - ID: $INCIDENT_ID"
log_incident "Incident Type: $1"
log_incident "Severity: $2"
# Notify incident response team
/scripts/security_alert.sh "Security Incident" \
"Incident $INCIDENT_ID detected: $1" "$2"
}
# Phase 2: Identification
identify_incident() {
log_incident "Starting incident identification phase"
# Collect system information
hostname > "$INCIDENT_DIR/hostname.txt"
date > "$INCIDENT_DIR/timestamp.txt"
uptime > "$INCIDENT_DIR/uptime.txt"
ps aux > "$INCIDENT_DIR/processes.txt"
netstat -tulpn > "$INCIDENT_DIR/network_connections.txt"
ss -tulpn > "$INCIDENT_DIR/socket_stats.txt"
# Collect user information
who > "$INCIDENT_DIR/logged_users.txt"
last -n 50 > "$INCIDENT_DIR/login_history.txt"
# Collect file system information
find /tmp -type f -mtime -1 > "$INCIDENT_DIR/recent_tmp_files.txt"
find /var/log -name "*.log" -mtime -1 -exec ls -la {} \; > "$INCIDENT_DIR/recent_logs.txt"
log_incident "Incident identification phase completed"
}
# Phase 3: Containment
contain_incident() {
log_incident "Starting incident containment phase"
case "$1" in
"malware")
# Isolate infected system
iptables -A INPUT -j DROP
iptables -A OUTPUT -j DROP
log_incident "System isolated from network"
;;
"unauthorized_access")
# Disable compromised accounts
passwd -l suspicious_user
log_incident "Suspicious user account locked"
;;
"data_breach")
# Preserve evidence
dd if=/dev/sda of="$INCIDENT_DIR/disk_image.dd" bs=4M
log_incident "Disk image created for forensic analysis"
;;
esac
log_incident "Incident containment phase completed"
}
# Phase 4: Eradication
eradicate_threat() {
log_incident "Starting threat eradication phase"
# Remove malware
rkhunter --check --report-warnings-only > "$INCIDENT_DIR/rkhunter_scan.txt"
chkrootkit > "$INCIDENT_DIR/chkrootkit_scan.txt"
# Update system
apt update && apt upgrade -y
# Reset compromised passwords
# This should be done manually for security
log_incident "Threat eradication phase completed"
}
# Phase 5: Recovery
recover_systems() {
log_incident "Starting system recovery phase"
# Restore from clean backups if necessary
# Verify system integrity
aide --check > "$INCIDENT_DIR/aide_check.txt"
# Gradually restore network access
iptables -F
iptables -P INPUT ACCEPT
iptables -P OUTPUT ACCEPT
log_incident "System recovery phase completed"
}
# Phase 6: Lessons Learned
document_lessons() {
log_incident "Starting lessons learned documentation"
cat > "$INCIDENT_DIR/incident_report.txt" << EOF
Incident Response Report
========================
Incident ID: $INCIDENT_ID
Date: $(date)
Type: $INCIDENT_TYPE
Severity: $INCIDENT_SEVERITY
Timeline:
- Detection: $DETECTION_TIME
- Response: $RESPONSE_TIME
- Containment: $CONTAINMENT_TIME
- Eradication: $ERADICATION_TIME
- Recovery: $RECOVERY_TIME
Root Cause:
$ROOT_CAUSE
Actions Taken:
$ACTIONS_TAKEN
Lessons Learned:
$LESSONS_LEARNED
Recommendations:
$RECOMMENDATIONS
EOF
log_incident "Incident documentation completed"
}
# Main incident response workflow
main() {
INCIDENT_TYPE="$1"
INCIDENT_SEVERITY="$2"
prepare_response "$INCIDENT_TYPE" "$INCIDENT_SEVERITY"
identify_incident
contain_incident "$INCIDENT_TYPE"
eradicate_threat
recover_systems
document_lessons
log_incident "Incident response completed"
}
# Execute if called directly
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
main "$@"
fi
|
2. Digital Forensics#
Evidence Collection:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
| #!/bin/bash
# forensic_collection.sh
CASE_ID="$1"
EVIDENCE_DIR="/var/forensics/$CASE_ID"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
# Create evidence directory
mkdir -p "$EVIDENCE_DIR"
# Calculate hashes for integrity
calculate_hash() {
local file="$1"
md5sum "$file" > "$file.md5"
sha256sum "$file" > "$file.sha256"
}
# Memory dump
collect_memory() {
echo "Collecting memory dump..."
if command -v lime &> /dev/null; then
insmod lime.ko "path=$EVIDENCE_DIR/memory_$TIMESTAMP.lime format=lime"
elif command -v avml &> /dev/null; then
avml "$EVIDENCE_DIR/memory_$TIMESTAMP.lime"
else
echo "No memory acquisition tool available"
fi
if [ -f "$EVIDENCE_DIR/memory_$TIMESTAMP.lime" ]; then
calculate_hash "$EVIDENCE_DIR/memory_$TIMESTAMP.lime"
fi
}
# Disk imaging
collect_disk_image() {
local device="$1"
echo "Creating disk image of $device..."
dd if="$device" of="$EVIDENCE_DIR/disk_$TIMESTAMP.dd" bs=4M conv=noerror,sync
calculate_hash "$EVIDENCE_DIR/disk_$TIMESTAMP.dd"
}
# Network connections
collect_network_info() {
echo "Collecting network information..."
netstat -tulpn > "$EVIDENCE_DIR/netstat_$TIMESTAMP.txt"
ss -tulpn > "$EVIDENCE_DIR/ss_$TIMESTAMP.txt"
arp -a > "$EVIDENCE_DIR/arp_$TIMESTAMP.txt"
route -n > "$EVIDENCE_DIR/route_$TIMESTAMP.txt"
# Capture network traffic
if command -v tcpdump &> /dev/null; then
timeout 300 tcpdump -i any -w "$EVIDENCE_DIR/network_$TIMESTAMP.pcap" &
fi
}
# Process information
collect_process_info() {
echo "Collecting process information..."
ps auxf > "$EVIDENCE_DIR/processes_$TIMESTAMP.txt"
lsof > "$EVIDENCE_DIR/open_files_$TIMESTAMP.txt"
# Process memory dumps
for pid in $(ps -eo pid --no-headers); do
if [ -r "/proc/$pid/maps" ]; then
cp "/proc/$pid/maps" "$EVIDENCE_DIR/proc_${pid}_maps.txt" 2>/dev/null
cp "/proc/$pid/environ" "$EVIDENCE_DIR/proc_${pid}_environ.txt" 2>/dev/null
fi
done
}
# Log files
collect_logs() {
echo "Collecting log files..."
tar -czf "$EVIDENCE_DIR/logs_$TIMESTAMP.tar.gz" /var/log/
calculate_hash "$EVIDENCE_DIR/logs_$TIMESTAMP.tar.gz"
}
# System information
collect_system_info() {
echo "Collecting system information..."
uname -a > "$EVIDENCE_DIR/system_info_$TIMESTAMP.txt"
cat /proc/version >> "$EVIDENCE_DIR/system_info_$TIMESTAMP.txt"
cat /etc/os-release >> "$EVIDENCE_DIR/system_info_$TIMESTAMP.txt"
# Hardware information
lshw > "$EVIDENCE_DIR/hardware_$TIMESTAMP.txt"
lscpu > "$EVIDENCE_DIR/cpu_$TIMESTAMP.txt"
lsblk > "$EVIDENCE_DIR/block_devices_$TIMESTAMP.txt"
# User information
cat /etc/passwd > "$EVIDENCE_DIR/passwd_$TIMESTAMP.txt"
cat /etc/group > "$EVIDENCE_DIR/group_$TIMESTAMP.txt"
last -n 100 > "$EVIDENCE_DIR/login_history_$TIMESTAMP.txt"
}
# Timeline creation
create_timeline() {
echo "Creating filesystem timeline..."
find / -type f -printf "%T@ %Tc %p\n" 2>/dev/null | sort -n > "$EVIDENCE_DIR/timeline_$TIMESTAMP.txt"
}
# Main collection process
main() {
if [ -z "$CASE_ID" ]; then
echo "Usage: $0 <case_id>"
exit 1
fi
echo "Starting forensic collection for case: $CASE_ID"
echo "Evidence will be stored in: $EVIDENCE_DIR"
collect_system_info
collect_process_info
collect_network_info
collect_logs
create_timeline
# Optional: collect memory and disk images
read -p "Collect memory dump? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
collect_memory
fi
read -p "Create disk image? Enter device (e.g., /dev/sda) or 'n' to skip: " device
if [[ "$device" != "n" && -b "$device" ]]; then
collect_disk_image "$device"
fi
# Create case summary
cat > "$EVIDENCE_DIR/case_summary.txt" << EOF
Forensic Collection Summary
===========================
Case ID: $CASE_ID
Collection Date: $(date)
Collector: $(whoami)
System: $(hostname)
Evidence Collected:
- System information
- Process information
- Network information
- Log files
- Filesystem timeline
$([ -f "$EVIDENCE_DIR/memory_$TIMESTAMP.lime" ] && echo "- Memory dump")
$([ -f "$EVIDENCE_DIR/disk_$TIMESTAMP.dd" ] && echo "- Disk image")
Chain of Custody:
- Collected by: $(whoami)
- Collection time: $(date)
- Storage location: $EVIDENCE_DIR
EOF
echo "Forensic collection completed"
echo "Case summary: $EVIDENCE_DIR/case_summary.txt"
}
main "$@"
|
Compliance dan Audit#
1. Security Compliance Frameworks#
CIS Controls Implementation:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
| #!/bin/bash
# cis_compliance_check.sh
REPORT_DIR="/var/reports/compliance"
DATE=$(date +%Y%m%d_%H%M%S)
REPORT_FILE="$REPORT_DIR/cis_compliance_$DATE.txt"
mkdir -p "$REPORT_DIR"
# CIS Control 1: Inventory and Control of Hardware Assets
check_hardware_inventory() {
echo "=== CIS Control 1: Hardware Asset Inventory ===" >> "$REPORT_FILE"
# List hardware components
lshw -short >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
# Check for unauthorized devices
lsusb >> "$REPORT_FILE"
lspci >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
}
# CIS Control 2: Inventory and Control of Software Assets
check_software_inventory() {
echo "=== CIS Control 2: Software Asset Inventory ===" >> "$REPORT_FILE"
# List installed packages
dpkg -l >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
# Check for unauthorized software
find /opt -type f -executable >> "$REPORT_FILE"
find /usr/local/bin -type f >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
}
# CIS Control 3: Continuous Vulnerability Management
check_vulnerability_management() {
echo "=== CIS Control 3: Vulnerability Management ===" >> "$REPORT_FILE"
# Check for available updates
apt list --upgradable >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
# Check last update time
stat /var/lib/apt/lists/ | grep Modify >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
}
# CIS Control 4: Controlled Use of Administrative Privileges
check_admin_privileges() {
echo "=== CIS Control 4: Administrative Privileges ===" >> "$REPORT_FILE"
# List users with sudo access
grep -E '^sudo|^admin|^wheel' /etc/group >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
# Check for users with UID 0
awk -F: '$3 == 0 {print $1}' /etc/passwd >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
# Check sudo configuration
cat /etc/sudoers >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
}
# CIS Control 5: Secure Configuration for Hardware and Software
check_secure_configuration() {
echo "=== CIS Control 5: Secure Configuration ===" >> "$REPORT_FILE"
# Check SSH configuration
echo "SSH Configuration:" >> "$REPORT_FILE"
grep -E '^PermitRootLogin|^PasswordAuthentication|^MaxAuthTries' /etc/ssh/sshd_config >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
# Check firewall status
echo "Firewall Status:" >> "$REPORT_FILE"
ufw status >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
# Check for unnecessary services
echo "Running Services:" >> "$REPORT_FILE"
systemctl list-units --type=service --state=running >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
}
# CIS Control 6: Maintenance, Monitoring, and Analysis of Audit Logs
check_audit_logs() {
echo "=== CIS Control 6: Audit Logs ===" >> "$REPORT_FILE"
# Check if auditd is running
systemctl status auditd >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
# Check log rotation
cat /etc/logrotate.conf | grep -A 5 -B 5 "rotate\|size" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
# Check recent security events
grep -i "authentication failure\|failed password\|invalid user" /var/log/auth.log | tail -20 >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
}
# Generate compliance score
calculate_compliance_score() {
local total_checks=6
local passed_checks=0
# Simple scoring based on key indicators
if systemctl is-active ufw >/dev/null 2>&1; then
((passed_checks++))
fi
if grep -q "PermitRootLogin no" /etc/ssh/sshd_config; then
((passed_checks++))
fi
if systemctl is-active fail2ban >/dev/null 2>&1; then
((passed_checks++))
fi
if [ -f /var/lib/aide/aide.db ]; then
((passed_checks++))
fi
if systemctl is-active auditd >/dev/null 2>&1; then
((passed_checks++))
fi
if [ "$(find /var/lib/apt/lists/ -mtime -7 | wc -l)" -gt 0 ]; then
((passed_checks++))
fi
local score=$((passed_checks * 100 / total_checks))
echo "=== Compliance Score ===" >> "$REPORT_FILE"
echo "Score: $score% ($passed_checks/$total_checks checks passed)" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
}
# Main compliance check
main() {
echo "Starting CIS compliance check..."
echo "CIS Compliance Report - $(date)" > "$REPORT_FILE"
echo "System: $(hostname)" >> "$REPORT_FILE"
echo "========================================" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
check_hardware_inventory
check_software_inventory
check_vulnerability_management
check_admin_privileges
check_secure_configuration
check_audit_logs
calculate_compliance_score
echo "Compliance check completed. Report saved to: $REPORT_FILE"
}
main "$@"
|
2. Audit Trail Management#
Comprehensive Audit Configuration:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
| # /etc/audit/rules.d/audit.rules
# Delete all existing rules
-D
# Buffer size
-b 8192
# Failure mode (0=silent, 1=printk, 2=panic)
-f 1
# Monitor file access
-w /etc/passwd -p wa -k identity
-w /etc/group -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/sudoers -p wa -k identity
# Monitor authentication events
-w /var/log/auth.log -p wa -k authentication
-w /var/log/secure -p wa -k authentication
# Monitor system configuration changes
-w /etc/ssh/sshd_config -p wa -k ssh_config
-w /etc/apache2/ -p wa -k apache_config
-w /etc/nginx/ -p wa -k nginx_config
# Monitor privilege escalation
-a always,exit -F arch=b64 -S execve -F euid=0 -F auid>=1000 -F auid!=4294967295 -k privilege_escalation
-a always,exit -F arch=b32 -S execve -F euid=0 -F auid>=1000 -F auid!=4294967295 -k privilege_escalation
# Monitor network configuration
-w /etc/hosts -p wa -k network_config
-w /etc/resolv.conf -p wa -k network_config
# Monitor kernel module loading
-w /sbin/insmod -p x -k modules
-w /sbin/rmmod -p x -k modules
-w /sbin/modprobe -p x -k modules
# Monitor file deletion
-a always,exit -F arch=b64 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295 -k delete
-a always,exit -F arch=b32 -S unlink -S unlinkat -S rename -S renameat -F auid>=1000 -F auid!=4294967295 -k delete
# Make rules immutable
-e 2
|
Audit Log Analysis:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
| #!/bin/bash
# audit_analysis.sh
AUDIT_LOG="/var/log/audit/audit.log"
REPORT_DIR="/var/reports/audit"
DATE=$(date +%Y%m%d_%H%M%S)
REPORT_FILE="$REPORT_DIR/audit_analysis_$DATE.txt"
mkdir -p "$REPORT_DIR"
# Analyze authentication events
analyze_authentication() {
echo "=== Authentication Analysis ===" >> "$REPORT_FILE"
# Failed login attempts
echo "Failed Login Attempts:" >> "$REPORT_FILE"
ausearch -m USER_LOGIN -sv no --start today | aureport -au -i >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
# Successful logins
echo "Successful Logins:" >> "$REPORT_FILE"
ausearch -m USER_LOGIN -sv yes --start today | aureport -au -i >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
# Root access events
echo "Root Access Events:" >> "$REPORT_FILE"
ausearch -k privilege_escalation --start today | aureport -x -i >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
}
# Analyze file access
analyze_file_access() {
echo "=== File Access Analysis ===" >> "$REPORT_FILE"
# Configuration file changes
echo "Configuration File Changes:" >> "$REPORT_FILE"
ausearch -k identity,ssh_config,apache_config,nginx_config --start today | aureport -f -i >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
# File deletions
echo "File Deletions:" >> "$REPORT_FILE"
ausearch -k delete --start today | aureport -f -i >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
}
# Analyze system events
analyze_system_events() {
echo "=== System Events Analysis ===" >> "$REPORT_FILE"
# Kernel module events
echo "Kernel Module Events:" >> "$REPORT_FILE"
ausearch -k modules --start today | aureport -x -i >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
# Network configuration changes
echo "Network Configuration Changes:" >> "$REPORT_FILE"
ausearch -k network_config --start today | aureport -f -i >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
}
# Generate summary statistics
generate_summary() {
echo "=== Audit Summary ===" >> "$REPORT_FILE"
# Total events
local total_events=$(wc -l < "$AUDIT_LOG")
echo "Total audit events today: $total_events" >> "$REPORT_FILE"
# Failed authentication attempts
local failed_auth=$(ausearch -m USER_LOGIN -sv no --start today 2>/dev/null | wc -l)
echo "Failed authentication attempts: $failed_auth" >> "$REPORT_FILE"
# Privilege escalation events
local priv_esc=$(ausearch -k privilege_escalation --start today 2>/dev/null | wc -l)
echo "Privilege escalation events: $priv_esc" >> "$REPORT_FILE"
# File modification events
local file_mods=$(ausearch -k identity,ssh_config,apache_config,nginx_config --start today 2>/dev/null | wc -l)
echo "Configuration file modifications: $file_mods" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
}
# Main analysis
main() {
echo "Starting audit log analysis..."
echo "Audit Log Analysis Report - $(date)" > "$REPORT_FILE"
echo "System: $(hostname)" >> "$REPORT_FILE"
echo "========================================" >> "$REPORT_FILE"
echo "" >> "$REPORT_FILE"
analyze_authentication
analyze_file_access
analyze_system_events
generate_summary
echo "Audit analysis completed. Report saved to: $REPORT_FILE"
# Send alert if suspicious activity detected
local failed_auth=$(ausearch -m USER_LOGIN -sv no --start today 2>/dev/null | wc -l)
if [ "$failed_auth" -gt 10 ]; then
/scripts/security_alert.sh "Suspicious Authentication Activity" \
"$failed_auth failed login attempts detected today" "medium"
fi
}
main "$@"
|
Future Trends Security#
1. Zero Trust Architecture#
Zero Trust Implementation:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
| #!/bin/bash
# zero_trust_setup.sh
# Implement micro-segmentation
setup_microsegmentation() {
# Create network namespaces for isolation
ip netns add web_tier
ip netns add app_tier
ip netns add db_tier
# Configure inter-tier communication rules
iptables -A FORWARD -s 192.168.10.0/24 -d 192.168.20.0/24 -p tcp --dport 8080 -j ACCEPT
iptables -A FORWARD -s 192.168.20.0/24 -d 192.168.30.0/24 -p tcp --dport 3306 -j ACCEPT
iptables -A FORWARD -j DROP
}
# Implement continuous verification
setup_continuous_verification() {
# Install and configure certificate-based authentication
cat > /etc/pam.d/common-auth << EOF
auth required pam_pkcs11.so
auth required pam_unix.so
EOF
# Configure device certificates
mkdir -p /etc/ssl/devices
# Generate device certificates (implementation specific)
}
# Implement least privilege access
setup_least_privilege() {
# Create role-based access control
groupadd web_admins
groupadd db_admins
groupadd app_admins
# Configure sudo rules for specific roles
cat > /etc/sudoers.d/zero_trust << EOF
%web_admins ALL=(root) /bin/systemctl restart nginx, /bin/systemctl reload nginx
%db_admins ALL=(mysql) /usr/bin/mysql, /usr/bin/mysqldump
%app_admins ALL=(app) /bin/systemctl restart myapp
EOF
}
main() {
echo "Implementing Zero Trust Architecture..."
setup_microsegmentation
setup_continuous_verification
setup_least_privilege
echo "Zero Trust implementation completed"
}
main "$@"
|
2. AI-Powered Security#
Machine Learning Threat Detection:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
| #!/usr/bin/env python3
# ml_threat_detection.py
import pandas as pd
import numpy as np
from sklearn.ensemble import IsolationForest
from sklearn.preprocessing import StandardScaler
import joblib
import syslog
import re
from datetime import datetime
class ThreatDetector:
def __init__(self):
self.model = None
self.scaler = StandardScaler()
self.features = [
'login_attempts',
'failed_logins',
'unique_ips',
'data_transfer',
'process_count',
'network_connections'
]
def extract_features(self, log_data):
"""Extract features from log data"""
features = {}
# Count login attempts
features['login_attempts'] = len(re.findall(r'authentication', log_data))
features['failed_logins'] = len(re.findall(r'authentication failure', log_data))
# Count unique IPs
ips = re.findall(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b', log_data)
features['unique_ips'] = len(set(ips))
# Simulate other metrics (in real implementation, collect from system)
features['data_transfer'] = np.random.randint(1000, 10000)
features['process_count'] = np.random.randint(50, 200)
features['network_connections'] = np.random.randint(10, 100)
return features
def train_model(self, training_data):
"""Train the anomaly detection model"""
df = pd.DataFrame(training_data)
X = df[self.features]
# Scale features
X_scaled = self.scaler.fit_transform(X)
# Train Isolation Forest
self.model = IsolationForest(contamination=0.1, random_state=42)
self.model.fit(X_scaled)
# Save model
joblib.dump(self.model, '/var/models/threat_detection_model.pkl')
joblib.dump(self.scaler, '/var/models/threat_detection_scaler.pkl')
def load_model(self):
"""Load trained model"""
try:
self.model = joblib.load('/var/models/threat_detection_model.pkl')
self.scaler = joblib.load('/var/models/threat_detection_scaler.pkl')
return True
except FileNotFoundError:
return False
def detect_anomaly(self, log_data):
"""Detect anomalies in current data"""
if not self.model:
if not self.load_model():
syslog.syslog(syslog.LOG_ERR, "Threat detection model not available")
return False
# Extract features
features = self.extract_features(log_data)
feature_vector = np.array([[features[f] for f in self.features]])
# Scale features
feature_vector_scaled = self.scaler.transform(feature_vector)
# Predict anomaly
prediction = self.model.predict(feature_vector_scaled)
anomaly_score = self.model.decision_function(feature_vector_scaled)
# Log results
if prediction[0] == -1: # Anomaly detected
syslog.syslog(syslog.LOG_WARNING,
f"Anomaly detected - Score: {anomaly_score[0]:.3f}, Features: {features}")
return True
return False
def continuous_monitoring(self):
"""Continuous threat monitoring"""
import time
import subprocess
while True:
try:
# Collect recent log data
result = subprocess.run(['tail', '-n', '1000', '/var/log/auth.log'],
capture_output=True, text=True)
log_data = result.stdout
# Detect anomalies
if self.detect_anomaly(log_data):
# Send alert
subprocess.run(['/scripts/security_alert.sh',
'ML Threat Detection',
'Anomalous behavior detected by ML model',
'high'])
time.sleep(60) # Check every minute
except Exception as e:
syslog.syslog(syslog.LOG_ERR, f"Threat detection error: {str(e)}")
time.sleep(300) # Wait 5 minutes on error
if __name__ == "__main__":
detector = ThreatDetector()
# Generate sample training data (in real implementation, use historical data)
training_data = []
for _ in range(1000):
training_data.append({
'login_attempts': np.random.randint(1, 20),
'failed_logins': np.random.randint(0, 5),
'unique_ips': np.random.randint(1, 10),
'data_transfer': np.random.randint(1000, 5000),
'process_count': np.random.randint(50, 150),
'network_connections': np.random.randint(10, 50)
})
# Train model
detector.train_model(training_data)
# Start continuous monitoring
detector.continuous_monitoring()
|
3. Cloud Security Evolution#
Container Security:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
| #!/bin/bash
# container_security.sh
# Docker security configuration
configure_docker_security() {
# Create docker daemon configuration
cat > /etc/docker/daemon.json << EOF
{
"icc": false,
"userns-remap": "default",
"log-driver": "syslog",
"log-opts": {
"syslog-address": "tcp://log-server:514"
},
"live-restore": true,
"userland-proxy": false,
"no-new-privileges": true
}
EOF
# Restart docker service
systemctl restart docker
}
# Kubernetes security policies
configure_k8s_security() {
# Pod Security Policy
cat > pod-security-policy.yaml << EOF
apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
name: restricted
spec:
privileged: false
allowPrivilegeEscalation: false
requiredDropCapabilities:
- ALL
volumes:
- 'configMap'
- 'emptyDir'
- 'projected'
- 'secret'
- 'downwardAPI'
- 'persistentVolumeClaim'
runAsUser:
rule: 'MustRunAsNonRoot'
seLinux:
rule: 'RunAsAny'
fsGroup:
rule: 'RunAsAny'
EOF
kubectl apply -f pod-security-policy.yaml
}
# Container image scanning
scan_container_images() {
# Install Trivy scanner
wget -qO - https://aquasecurity.github.io/trivy-repo/deb/public.key | apt-key add -
echo "deb https://aquasecurity.github.io/trivy-repo/deb generic main" | tee -a /etc/apt/sources.list.d/trivy.list
apt update && apt install trivy
# Scan images
for image in $(docker images --format "{{.Repository}}:{{.Tag}}"); do
echo "Scanning $image..."
trivy image --severity HIGH,CRITICAL "$image"
done
}
main() {
echo "Configuring container security..."
configure_docker_security
configure_k8s_security
scan_container_images
echo "Container security configuration completed"
}
main "$@"
|
Kesimpulan#
Server security merupakan aspek fundamental yang memerlukan pendekatan holistik dan berkelanjutan. Implementasi security best practices harus disesuaikan dengan threat landscape yang terus berkembang dan kebutuhan spesifik organisasi.
Key Security Principles:
Defense in Depth:
- Multiple layers: Implement security pada setiap layer
- Redundancy: Backup security controls
- Fail-safe: Secure by default configurations
- Monitoring: Continuous security monitoring
Zero Trust Approach:
- Never trust, always verify: Verify setiap access request
- Least privilege: Minimal access yang diperlukan
- Micro-segmentation: Isolate network segments
- Continuous verification: Real-time access validation
Proactive Security:
- Threat hunting: Actively search untuk threats
- Vulnerability management: Regular vulnerability assessment
- Incident response: Prepared incident response plan
- Security awareness: Regular security training
Essential Security Controls:
Technical Controls:
- Access control: Strong authentication dan authorization
- Encryption: Data protection at rest dan in transit
- Monitoring: Comprehensive logging dan alerting
- Patch management: Regular security updates
- Backup: Secure dan tested backup procedures
Administrative Controls:
- Security policies: Clear security policies dan procedures
- Risk assessment: Regular risk assessment
- Compliance: Regulatory compliance management
- Training: Security awareness training
- Incident response: Documented response procedures
Physical Controls:
- Physical access: Controlled physical access
- Environmental: Proper environmental controls
- Asset management: Hardware asset tracking
- Disposal: Secure asset disposal
- Facility security: Comprehensive facility security
Future Considerations:
- AI/ML integration: Leverage AI untuk threat detection
- Cloud security: Cloud-native security approaches
- IoT security: Secure Internet of Things devices
- Quantum cryptography: Prepare untuk quantum computing
- Automation: Automate security operations
Untuk mendapatkan insights lebih mendalam tentang server security dan cybersecurity best practices, kunjungi Petir.id - platform terpercaya yang menyediakan panduan komprehensif, tutorial praktis, dan update terbaru tentang cybersecurity untuk melindungi infrastruktur IT dan data bisnis Anda dari ancaman cyber yang terus berkembang.
Artikel ini dipersembahkan oleh Petir.id - Your comprehensive guide to server security and cybersecurity best practices.