This commit is contained in:
Toby
2026-01-27 17:35:45 -05:00
commit 2639af6531
176 changed files with 27104 additions and 0 deletions
+126
View File
@@ -0,0 +1,126 @@
---
name: cis-benchmarks
description: Audit and remediate CIS benchmark violations. Use automated tools to assess compliance and implement hardening recommendations. Use when meeting compliance requirements or implementing security baselines.
license: MIT
metadata:
author: devops-skills
version: "1.0"
---
# CIS Benchmarks
Implement and audit CIS security benchmarks.
## When to Use This Skill
Use this skill when:
- Assessing security compliance
- Implementing security baselines
- Meeting regulatory requirements
- Hardening systems to standards
## Assessment Tools
### OpenSCAP
```bash
# Install
apt install openscap-scanner scap-security-guide
# Run CIS benchmark scan
oscap xccdf eval \
--profile xccdf_org.ssgproject.content_profile_cis \
--results results.xml \
--report report.html \
/usr/share/xml/scap/ssg/content/ssg-ubuntu2204-ds.xml
```
### Lynis
```bash
# Install
apt install lynis
# Run audit
lynis audit system
# Generate report
lynis audit system --report-file /tmp/lynis-report.dat
```
### InSpec
```ruby
# cis-profile/controls/ssh.rb
control 'cis-ssh-1' do
impact 1.0
title 'Ensure SSH root login is disabled'
describe sshd_config do
its('PermitRootLogin') { should eq 'no' }
end
end
control 'cis-ssh-2' do
impact 0.7
title 'Ensure SSH password authentication is disabled'
describe sshd_config do
its('PasswordAuthentication') { should eq 'no' }
end
end
```
```bash
# Run InSpec
inspec exec cis-profile -t ssh://user@target
```
### Kubernetes CIS
```bash
# kube-bench
docker run --rm -v /etc:/etc:ro -v /var:/var:ro \
aquasec/kube-bench:latest run --targets node
# Check specific sections
kube-bench run --targets master --check 1.1,1.2
```
## Remediation Workflow
```yaml
workflow:
1_scan:
- Run automated assessment
- Generate baseline report
2_analyze:
- Review findings
- Identify false positives
- Prioritize by risk
3_remediate:
- Apply fixes
- Document exceptions
- Verify changes
4_validate:
- Re-run assessment
- Confirm remediation
- Generate compliance report
```
## Best Practices
- Baseline before hardening
- Document exceptions
- Automate assessments
- Track compliance over time
- Regular re-assessment
- Version control configurations
## Related Skills
- [linux-hardening](../linux-hardening/) - Linux security
- [vulnerability-scanning](../../scanning/vulnerability-scanning/) - Security scanning
@@ -0,0 +1,102 @@
---
name: container-hardening
description: Secure Docker images and container runtime configurations. Implement non-root users, read-only filesystems, and security contexts. Use when building secure container images or hardening container deployments.
license: MIT
metadata:
author: devops-skills
version: "1.0"
---
# Container Hardening
Secure container images and runtime configurations.
## When to Use This Skill
Use this skill when:
- Building secure container images
- Hardening container deployments
- Meeting container security requirements
- Implementing defense in depth
## Dockerfile Security
```dockerfile
# Use minimal base image
FROM alpine:3.18
# Don't run as root
RUN addgroup -g 1001 -S appgroup && \
adduser -u 1001 -S appuser -G appgroup
# Copy with specific ownership
COPY --chown=appuser:appgroup . /app
# Remove unnecessary packages
RUN apk del --purge build-dependencies && \
rm -rf /var/cache/apk/*
# Use non-root user
USER appuser
# Read-only filesystem support
WORKDIR /app
```
## Runtime Security
```bash
# Run with security options
docker run -d \
--read-only \
--tmpfs /tmp \
--security-opt=no-new-privileges:true \
--cap-drop=ALL \
--cap-add=NET_BIND_SERVICE \
--user 1001:1001 \
myapp:latest
```
## Kubernetes Security Context
```yaml
apiVersion: v1
kind: Pod
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1001
fsGroup: 1001
containers:
- name: app
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
```
## Image Scanning
```bash
# Scan with Trivy
trivy image --severity HIGH,CRITICAL myapp:latest
# Use distroless images
FROM gcr.io/distroless/static-debian11
```
## Best Practices
- Use minimal base images
- Run as non-root user
- Enable read-only filesystem
- Drop all capabilities
- Scan images regularly
- Sign and verify images
- Use secrets management
## Related Skills
- [container-scanning](../../scanning/container-scanning/) - Vulnerability scanning
- [kubernetes-hardening](../kubernetes-hardening/) - K8s security
@@ -0,0 +1,105 @@
# Container Security Best Practices
## Dockerfile Hardening
```dockerfile
# Use minimal base image
FROM gcr.io/distroless/base-debian12
# Or Alpine
FROM alpine:3.19
# Non-root user
RUN addgroup -g 1000 appgroup && \
adduser -u 1000 -G appgroup -D appuser
USER appuser
# Read-only filesystem
# (Set at runtime with --read-only)
# No new privileges
# (Set at runtime with --security-opt=no-new-privileges)
```
## Security Scanning
```bash
# Trivy scan
trivy image --severity HIGH,CRITICAL myimage:latest
# Grype scan
grype myimage:latest --fail-on high
# Docker Scout
docker scout cves myimage:latest
```
## Runtime Security
```yaml
# Kubernetes securityContext
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
readOnlyRootFilesystem: true
allowPrivilegeEscalation: false
capabilities:
drop:
- ALL
seccompProfile:
type: RuntimeDefault
```
## Docker Run Hardening
```bash
docker run \
--read-only \
--tmpfs /tmp \
--security-opt=no-new-privileges:true \
--cap-drop=ALL \
--user 1000:1000 \
--memory=512m \
--cpus=0.5 \
myimage
```
## Image Signing
```bash
# Cosign
cosign sign --key cosign.key myimage:latest
cosign verify --key cosign.pub myimage:latest
# Docker Content Trust
export DOCKER_CONTENT_TRUST=1
docker push myimage:latest
```
## Network Policies
```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
```
## Checklist
- [ ] Use minimal base images
- [ ] Run as non-root
- [ ] Drop all capabilities
- [ ] Read-only filesystem
- [ ] No privilege escalation
- [ ] Scan for vulnerabilities
- [ ] Sign images
- [ ] Implement network policies
- [ ] Use secrets management
- [ ] Enable audit logging
@@ -0,0 +1,129 @@
---
name: kubernetes-hardening
description: Implement Kubernetes security contexts, Pod Security Standards, and network policies. Secure cluster components and workloads. Use when hardening Kubernetes deployments or meeting security compliance.
license: MIT
metadata:
author: devops-skills
version: "1.0"
---
# Kubernetes Hardening
Secure Kubernetes clusters and workloads.
## When to Use This Skill
Use this skill when:
- Hardening Kubernetes clusters
- Implementing Pod Security Standards
- Configuring network policies
- Meeting security compliance
## Pod Security Standards
```yaml
# Namespace with restricted policy
apiVersion: v1
kind: Namespace
metadata:
name: production
labels:
pod-security.kubernetes.io/enforce: restricted
pod-security.kubernetes.io/audit: restricted
pod-security.kubernetes.io/warn: restricted
```
## Security Context
```yaml
apiVersion: v1
kind: Pod
metadata:
name: secure-pod
spec:
securityContext:
runAsNonRoot: true
runAsUser: 1000
runAsGroup: 1000
fsGroup: 1000
seccompProfile:
type: RuntimeDefault
containers:
- name: app
image: myapp:latest
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
```
## Network Policies
```yaml
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
spec:
podSelector: {}
policyTypes:
- Ingress
- Egress
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-web
spec:
podSelector:
matchLabels:
app: web
ingress:
- from:
- podSelector:
matchLabels:
app: frontend
ports:
- port: 8080
```
## RBAC
```yaml
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: app-reader
rules:
- apiGroups: [""]
resources: ["pods", "services"]
verbs: ["get", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: app-reader-binding
subjects:
- kind: ServiceAccount
name: myapp
roleRef:
kind: Role
name: app-reader
apiGroup: rbac.authorization.k8s.io
```
## Best Practices
- Enable Pod Security Standards
- Implement network policies
- Use RBAC with least privilege
- Enable audit logging
- Secure etcd with encryption
- Use service mesh for mTLS
- Regular security scanning
## Related Skills
- [kubernetes-ops](../../../devops/orchestration/kubernetes-ops/) - K8s operations
- [container-hardening](../container-hardening/) - Container security
+130
View File
@@ -0,0 +1,130 @@
---
name: linux-hardening
description: Apply CIS benchmarks and secure Linux servers. Configure SSH, manage users, implement firewall rules, and enable security features. Use when hardening Linux systems for production or meeting security compliance requirements.
license: MIT
metadata:
author: devops-skills
version: "1.0"
---
# Linux Hardening
Secure Linux servers following CIS benchmarks and security best practices.
## When to Use This Skill
Use this skill when:
- Hardening production servers
- Meeting compliance requirements
- Implementing security baselines
- Configuring secure SSH access
## SSH Hardening
```bash
# /etc/ssh/sshd_config
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
AllowUsers deploy admin
Protocol 2
```
## User Security
```bash
# Password policy
sudo apt install libpam-pwquality
# /etc/security/pwquality.conf
minlen = 14
dcredit = -1
ucredit = -1
ocredit = -1
lcredit = -1
# Lock inactive accounts
useradd -D -f 30
# Audit sudo usage
echo "Defaults logfile=/var/log/sudo.log" >> /etc/sudoers
```
## Firewall Configuration
```bash
# UFW setup
ufw default deny incoming
ufw default allow outgoing
ufw allow ssh
ufw allow 443/tcp
ufw enable
# Or iptables
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -j ACCEPT
```
## Kernel Hardening
```bash
# /etc/sysctl.d/99-security.conf
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
kernel.randomize_va_space = 2
fs.suid_dumpable = 0
# Apply
sysctl -p
```
## File Permissions
```bash
# Critical files
chmod 600 /etc/shadow
chmod 644 /etc/passwd
chmod 700 /root
chmod 600 /etc/ssh/sshd_config
# Find world-writable files
find / -type f -perm -0002 -ls
# Find SUID files
find / -perm -4000 -type f -ls
```
## Audit Configuration
```bash
# Install auditd
apt install auditd
# /etc/audit/rules.d/audit.rules
-w /etc/passwd -p wa -k identity
-w /etc/shadow -p wa -k identity
-w /etc/sudoers -p wa -k actions
-a always,exit -F arch=b64 -S execve -k exec
```
## Best Practices
- Disable unused services
- Keep system updated
- Use fail2ban for intrusion prevention
- Enable SELinux/AppArmor
- Regular security audits
- Monitor log files
- Implement least privilege
## Related Skills
- [cis-benchmarks](../cis-benchmarks/) - Compliance scanning
- [firewall-config](../../network/firewall-config/) - Firewall rules
@@ -0,0 +1,111 @@
# SSH Server Hardening Configuration
# Place in /etc/ssh/sshd_config.d/hardening.conf
# Restart SSH: systemctl restart sshd
#------------------------------------------------------------------------------
# AUTHENTICATION
#------------------------------------------------------------------------------
# Disable root login
PermitRootLogin no
# Disable password authentication
PasswordAuthentication no
# Enable public key authentication
PubkeyAuthentication yes
# Disable empty passwords
PermitEmptyPasswords no
# Disable keyboard-interactive authentication
KbdInteractiveAuthentication no
# Disable challenge-response authentication
ChallengeResponseAuthentication no
# Maximum authentication attempts
MaxAuthTries 3
# Maximum sessions per connection
MaxSessions 2
# Maximum simultaneous unauthenticated connections
MaxStartups 10:30:60
# Login grace time
LoginGraceTime 60
#------------------------------------------------------------------------------
# SESSION
#------------------------------------------------------------------------------
# Client alive settings (timeout)
ClientAliveInterval 300
ClientAliveCountMax 2
# Disable TCP forwarding
AllowTcpForwarding no
# Disable agent forwarding
AllowAgentForwarding no
# Disable stream local forwarding
AllowStreamLocalForwarding no
# Disable X11 forwarding
X11Forwarding no
# Disable user environment processing
PermitUserEnvironment no
# Disable tunnel device forwarding
PermitTunnel no
# Disable gateway ports
GatewayPorts no
#------------------------------------------------------------------------------
# CRYPTOGRAPHY
#------------------------------------------------------------------------------
# Protocol version (SSH-2 only)
Protocol 2
# Strong ciphers only
Ciphers aes256-gcm@openssh.com,chacha20-poly1305@openssh.com,aes256-ctr
# Strong MACs only
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512,hmac-sha2-256
# Strong key exchange algorithms
KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512
# Strong host key algorithms
HostKeyAlgorithms ssh-ed25519,rsa-sha2-512,rsa-sha2-256
#------------------------------------------------------------------------------
# LOGGING
#------------------------------------------------------------------------------
# Log level
LogLevel VERBOSE
# Enable sftp logging
Subsystem sftp /usr/lib/openssh/sftp-server -l INFO
#------------------------------------------------------------------------------
# ACCESS CONTROL
#------------------------------------------------------------------------------
# Use PAM
UsePAM yes
# Show banner
Banner /etc/issue.net
# Restrict to specific users (uncomment and customize)
# AllowUsers admin deploy
# Restrict to specific groups (uncomment and customize)
# AllowGroups sshusers admins
@@ -0,0 +1,104 @@
# Linux Kernel Security Hardening
# Place in /etc/sysctl.d/99-security.conf
# Apply with: sysctl -p /etc/sysctl.d/99-security.conf
#------------------------------------------------------------------------------
# NETWORK SECURITY
#------------------------------------------------------------------------------
# Disable IP forwarding (unless router)
net.ipv4.ip_forward = 0
net.ipv6.conf.all.forwarding = 0
# Disable packet redirect sending
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
# Disable ICMP redirect acceptance
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0
# Disable source routing
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
net.ipv6.conf.all.accept_source_route = 0
net.ipv6.conf.default.accept_source_route = 0
# Log suspicious packets
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
# Ignore ICMP broadcast requests
net.ipv4.icmp_echo_ignore_broadcasts = 1
# Ignore bogus ICMP error responses
net.ipv4.icmp_ignore_bogus_error_responses = 1
# Enable reverse path filtering (spoofing protection)
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
# Enable TCP SYN cookies (SYN flood protection)
net.ipv4.tcp_syncookies = 1
# Disable IPv6 router advertisements
net.ipv6.conf.all.accept_ra = 0
net.ipv6.conf.default.accept_ra = 0
# Disable IPv6 if not needed
# net.ipv6.conf.all.disable_ipv6 = 1
# net.ipv6.conf.default.disable_ipv6 = 1
#------------------------------------------------------------------------------
# KERNEL SECURITY
#------------------------------------------------------------------------------
# Enable ASLR
kernel.randomize_va_space = 2
# Restrict access to kernel pointers
kernel.kptr_restrict = 2
# Restrict dmesg access
kernel.dmesg_restrict = 1
# Restrict ptrace scope
kernel.yama.ptrace_scope = 1
# Disable magic SysRq key
kernel.sysrq = 0
# Restrict unprivileged user namespaces
# kernel.unprivileged_userns_clone = 0
# Restrict loading TTY line disciplines
dev.tty.ldisc_autoload = 0
# Restrict userfaultfd to privileged users
vm.unprivileged_userfaultfd = 0
# Restrict BPF
kernel.unprivileged_bpf_disabled = 1
net.core.bpf_jit_harden = 2
# Restrict perf events
kernel.perf_event_paranoid = 3
#------------------------------------------------------------------------------
# FILE SYSTEM SECURITY
#------------------------------------------------------------------------------
# Restrict core dumps
fs.suid_dumpable = 0
# Restrict hardlinks and symlinks
fs.protected_hardlinks = 1
fs.protected_symlinks = 1
# Protect FIFOs and regular files
fs.protected_fifos = 2
fs.protected_regular = 2
@@ -0,0 +1,139 @@
# CIS Linux Hardening Checklist
## 1. Initial Setup
### 1.1 Filesystem Configuration
- [ ] Disable unused filesystems (cramfs, freevxfs, jffs2, hfs, hfsplus, squashfs, udf)
- [ ] Ensure `/tmp` is configured with nodev, nosuid, noexec
- [ ] Ensure `/var`, `/var/tmp`, `/var/log`, `/var/log/audit` are separate partitions
- [ ] Ensure `/home` is separate partition with nodev
### 1.2 Configure Software Updates
- [ ] Ensure package manager repositories are configured
- [ ] Ensure GPG keys are configured
- [ ] Ensure automatic updates are enabled
### 1.3 Filesystem Integrity
- [ ] Ensure AIDE is installed
- [ ] Ensure filesystem integrity is regularly checked
## 2. Services
### 2.1 Special Purpose Services
- [ ] Ensure time synchronization is configured (chrony/ntp)
- [ ] Ensure X Window System is not installed
- [ ] Ensure rsync service is not installed or masked
- [ ] Ensure Avahi Server is not installed
- [ ] Ensure CUPS is not installed
- [ ] Ensure DHCP Server is not installed
- [ ] Ensure LDAP server is not installed
- [ ] Ensure NFS is not installed
- [ ] Ensure DNS Server is not installed
- [ ] Ensure FTP Server is not installed
- [ ] Ensure HTTP Server is not installed
- [ ] Ensure IMAP and POP3 server is not installed
- [ ] Ensure Samba is not installed
- [ ] Ensure SNMP Server is not installed
### 2.2 Service Clients
- [ ] Ensure NIS Client is not installed
- [ ] Ensure rsh client is not installed
- [ ] Ensure talk client is not installed
- [ ] Ensure telnet client is not installed
- [ ] Ensure LDAP client is not installed
- [ ] Ensure RPC is not installed
## 3. Network Configuration
### 3.1 Network Parameters (Host Only)
- [ ] Ensure IP forwarding is disabled
- [ ] Ensure packet redirect sending is disabled
### 3.2 Network Parameters (Host and Router)
- [ ] Ensure source routed packets are not accepted
- [ ] Ensure ICMP redirects are not accepted
- [ ] Ensure secure ICMP redirects are not accepted
- [ ] Ensure suspicious packets are logged
- [ ] Ensure broadcast ICMP requests are ignored
- [ ] Ensure bogus ICMP responses are ignored
- [ ] Ensure Reverse Path Filtering is enabled
- [ ] Ensure TCP SYN Cookies is enabled
### 3.3 Firewall Configuration
- [ ] Ensure firewall is installed (iptables, nftables, or firewalld)
- [ ] Ensure default deny firewall policy
- [ ] Ensure loopback traffic is configured
- [ ] Ensure outbound connections are configured
## 4. Access, Authentication and Authorization
### 4.1 Configure Shadow Suite
- [ ] Ensure password expiration is 365 days or less
- [ ] Ensure minimum days between password changes is 7 or more
- [ ] Ensure password expiration warning days is 7 or more
- [ ] Ensure inactive password lock is 30 days or less
- [ ] Ensure all users last password change date is in the past
### 4.2 Configure SSH Server
- [ ] Ensure SSH Protocol is set to 2
- [ ] Ensure SSH LogLevel is appropriate
- [ ] Ensure SSH X11 forwarding is disabled
- [ ] Ensure SSH MaxAuthTries is set to 4 or less
- [ ] Ensure SSH IgnoreRhosts is enabled
- [ ] Ensure SSH HostbasedAuthentication is disabled
- [ ] Ensure SSH root login is disabled
- [ ] Ensure SSH PermitEmptyPasswords is disabled
- [ ] Ensure SSH PermitUserEnvironment is disabled
- [ ] Ensure SSH Idle Timeout Interval is configured
- [ ] Ensure SSH LoginGraceTime is set to one minute or less
- [ ] Ensure SSH warning banner is configured
- [ ] Ensure SSH PAM is enabled
- [ ] Ensure SSH AllowTcpForwarding is disabled
### 4.3 Configure PAM
- [ ] Ensure password creation requirements are configured
- [ ] Ensure lockout for failed password attempts is configured
- [ ] Ensure password reuse is limited
- [ ] Ensure password hashing algorithm is SHA-512
## 5. Logging and Auditing
### 5.1 Configure Logging
- [ ] Ensure rsyslog is installed
- [ ] Ensure rsyslog Service is enabled
- [ ] Ensure logging is configured
- [ ] Ensure rsyslog default file permissions configured
- [ ] Ensure remote rsyslog messages only accepted on designated log hosts
### 5.2 Configure auditd
- [ ] Ensure auditing is enabled
- [ ] Ensure audit log storage size is configured
- [ ] Ensure audit logs are not automatically deleted
- [ ] Ensure changes to system administration scope are collected
- [ ] Ensure login and logout events are collected
- [ ] Ensure session initiation information is collected
- [ ] Ensure file deletion events by users are collected
- [ ] Ensure kernel module loading and unloading is collected
## 6. System Maintenance
### 6.1 File Permissions
- [ ] Ensure permissions on /etc/passwd are configured (644)
- [ ] Ensure permissions on /etc/shadow are configured (600)
- [ ] Ensure permissions on /etc/group are configured (644)
- [ ] Ensure permissions on /etc/gshadow are configured (600)
- [ ] Ensure no world writable files exist
- [ ] Ensure no unowned files or directories exist
- [ ] Ensure no ungrouped files or directories exist
### 6.2 User and Group Settings
- [ ] Ensure accounts in /etc/passwd use shadowed passwords
- [ ] Ensure no legacy "+" entries exist in /etc/passwd
- [ ] Ensure root is the only UID 0 account
- [ ] Ensure root PATH integrity
- [ ] Ensure all users' home directories exist
- [ ] Ensure users' home directories permissions are 750 or more restrictive
- [ ] Ensure users own their home directories
- [ ] Ensure no users have .forward files
- [ ] Ensure no users have .netrc files
- [ ] Ensure no users have .rhosts files
@@ -0,0 +1,138 @@
#!/bin/bash
# Linux Security Audit Script
# Usage: ./audit-system.sh [--verbose]
set -euo pipefail
VERBOSE="${1:-}"
PASS=0
WARN=0
FAIL=0
check() {
local status="$1"
local message="$2"
case "$status" in
PASS) echo -e "\e[32m[PASS]\e[0m $message"; ((PASS++)) ;;
WARN) echo -e "\e[33m[WARN]\e[0m $message"; ((WARN++)) ;;
FAIL) echo -e "\e[31m[FAIL]\e[0m $message"; ((FAIL++)) ;;
esac
}
echo "========================================="
echo "Linux Security Audit"
echo "========================================="
echo ""
# 1. System Updates
echo "1. System Updates"
echo "-----------------"
UPDATES=$(apt-get -s upgrade 2>/dev/null | grep -c "^Inst" || echo 0)
if [ "$UPDATES" -eq 0 ]; then
check "PASS" "System is up to date"
else
check "FAIL" "$UPDATES packages need updating"
fi
# 2. SSH Configuration
echo ""
echo "2. SSH Configuration"
echo "--------------------"
if grep -q "^PermitRootLogin no" /etc/ssh/sshd_config* 2>/dev/null; then
check "PASS" "Root login disabled"
else
check "FAIL" "Root login may be enabled"
fi
if grep -q "^PasswordAuthentication no" /etc/ssh/sshd_config* 2>/dev/null; then
check "PASS" "Password authentication disabled"
else
check "WARN" "Password authentication may be enabled"
fi
# 3. User Accounts
echo ""
echo "3. User Accounts"
echo "----------------"
EMPTY_PASS=$(awk -F: '($2 == "") {print $1}' /etc/shadow 2>/dev/null | wc -l)
if [ "$EMPTY_PASS" -eq 0 ]; then
check "PASS" "No accounts with empty passwords"
else
check "FAIL" "$EMPTY_PASS accounts with empty passwords"
fi
ROOT_ACCOUNTS=$(awk -F: '($3 == 0) {print $1}' /etc/passwd | wc -l)
if [ "$ROOT_ACCOUNTS" -eq 1 ]; then
check "PASS" "Only root has UID 0"
else
check "FAIL" "$ROOT_ACCOUNTS accounts have UID 0"
fi
# 4. File Permissions
echo ""
echo "4. File Permissions"
echo "-------------------"
SHADOW_PERMS=$(stat -c %a /etc/shadow 2>/dev/null)
if [ "$SHADOW_PERMS" = "600" ] || [ "$SHADOW_PERMS" = "640" ]; then
check "PASS" "/etc/shadow permissions: $SHADOW_PERMS"
else
check "FAIL" "/etc/shadow permissions: $SHADOW_PERMS (should be 600)"
fi
WORLD_WRITABLE=$(find /etc -type f -perm -002 2>/dev/null | wc -l)
if [ "$WORLD_WRITABLE" -eq 0 ]; then
check "PASS" "No world-writable files in /etc"
else
check "FAIL" "$WORLD_WRITABLE world-writable files in /etc"
fi
# 5. Network Security
echo ""
echo "5. Network Security"
echo "-------------------"
if sysctl -n net.ipv4.tcp_syncookies 2>/dev/null | grep -q "1"; then
check "PASS" "TCP SYN cookies enabled"
else
check "WARN" "TCP SYN cookies not enabled"
fi
if sysctl -n net.ipv4.conf.all.rp_filter 2>/dev/null | grep -q "1"; then
check "PASS" "Reverse path filtering enabled"
else
check "WARN" "Reverse path filtering not enabled"
fi
# 6. Firewall
echo ""
echo "6. Firewall Status"
echo "------------------"
if command -v ufw &>/dev/null && ufw status | grep -q "active"; then
check "PASS" "UFW firewall is active"
elif command -v firewalld &>/dev/null && systemctl is-active firewalld &>/dev/null; then
check "PASS" "firewalld is active"
elif iptables -L -n 2>/dev/null | grep -q "DROP\|REJECT"; then
check "PASS" "iptables has rules configured"
else
check "FAIL" "No firewall appears to be active"
fi
# 7. Services
echo ""
echo "7. Running Services"
echo "-------------------"
LISTENING=$(ss -tlnp 2>/dev/null | grep -c LISTEN || echo 0)
check "WARN" "$LISTENING services listening on ports"
# Summary
echo ""
echo "========================================="
echo "Audit Summary"
echo "========================================="
echo -e "Passed: \e[32m$PASS\e[0m"
echo -e "Warnings: \e[33m$WARN\e[0m"
echo -e "Failed: \e[31m$FAIL\e[0m"
echo ""
if [ "$FAIL" -gt 0 ]; then
exit 1
fi
@@ -0,0 +1,131 @@
#!/bin/bash
# Linux System Hardening Script
# Usage: ./harden-system.sh [--apply]
# Run without --apply to see what changes would be made
set -euo pipefail
APPLY="${1:-}"
if [ "$APPLY" != "--apply" ]; then
echo "DRY RUN MODE - No changes will be made"
echo "Run with --apply to make changes"
echo ""
fi
apply_change() {
if [ "$APPLY" == "--apply" ]; then
eval "$1"
echo " [APPLIED] $2"
else
echo " [WOULD APPLY] $2"
fi
}
echo "========================================="
echo "Linux System Hardening"
echo "========================================="
echo ""
# 1. Update system
echo "1. System Updates"
echo "-----------------"
apply_change "apt-get update && apt-get upgrade -y" "Update all packages"
# 2. Disable unused filesystems
echo ""
echo "2. Disable Unused Filesystems"
echo "------------------------------"
FILESYSTEMS="cramfs freevxfs jffs2 hfs hfsplus squashfs udf"
for fs in $FILESYSTEMS; do
apply_change "echo 'install $fs /bin/true' >> /etc/modprobe.d/disable-filesystems.conf" "Disable $fs"
done
# 3. Kernel parameters
echo ""
echo "3. Kernel Hardening (sysctl)"
echo "----------------------------"
SYSCTL_CONF="/etc/sysctl.d/99-hardening.conf"
cat << 'EOF' > /tmp/sysctl-hardening.conf
# Network security
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 0
net.ipv4.conf.default.secure_redirects = 0
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.tcp_syncookies = 1
# IPv6 (disable if not needed)
net.ipv6.conf.all.disable_ipv6 = 1
net.ipv6.conf.default.disable_ipv6 = 1
# Kernel hardening
kernel.randomize_va_space = 2
kernel.kptr_restrict = 2
kernel.dmesg_restrict = 1
kernel.yama.ptrace_scope = 1
EOF
apply_change "cp /tmp/sysctl-hardening.conf $SYSCTL_CONF && sysctl -p $SYSCTL_CONF" "Apply kernel hardening parameters"
# 4. SSH hardening
echo ""
echo "4. SSH Hardening"
echo "----------------"
SSH_CONF="/etc/ssh/sshd_config.d/hardening.conf"
cat << 'EOF' > /tmp/ssh-hardening.conf
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
MaxAuthTries 3
ClientAliveInterval 300
ClientAliveCountMax 2
X11Forwarding no
AllowAgentForwarding no
PermitEmptyPasswords no
EOF
apply_change "cp /tmp/ssh-hardening.conf $SSH_CONF" "Apply SSH hardening"
# 5. File permissions
echo ""
echo "5. File Permissions"
echo "-------------------"
apply_change "chmod 600 /etc/shadow" "Secure /etc/shadow"
apply_change "chmod 644 /etc/passwd" "Secure /etc/passwd"
apply_change "chmod 600 /etc/gshadow" "Secure /etc/gshadow"
apply_change "chmod 644 /etc/group" "Secure /etc/group"
# 6. Remove unnecessary packages
echo ""
echo "6. Remove Unnecessary Services"
echo "------------------------------"
REMOVE_PKGS="telnet rsh-client rsh-redone-client"
for pkg in $REMOVE_PKGS; do
apply_change "apt-get remove -y $pkg 2>/dev/null || true" "Remove $pkg"
done
# 7. Configure firewall
echo ""
echo "7. Enable Firewall"
echo "------------------"
apply_change "ufw default deny incoming && ufw default allow outgoing && ufw allow ssh && ufw --force enable" "Configure UFW firewall"
# 8. Enable automatic updates
echo ""
echo "8. Automatic Security Updates"
echo "-----------------------------"
apply_change "apt-get install -y unattended-upgrades && dpkg-reconfigure -plow unattended-upgrades" "Enable unattended upgrades"
echo ""
echo "========================================="
echo "Hardening script complete"
if [ "$APPLY" != "--apply" ]; then
echo "Run with --apply to make changes"
fi
echo "========================================="
@@ -0,0 +1,98 @@
---
name: windows-hardening
description: Harden Windows servers per security baselines and CIS benchmarks. Configure Group Policy, Windows Defender, and security features. Use when securing Windows Server environments.
license: MIT
metadata:
author: devops-skills
version: "1.0"
---
# Windows Hardening
Secure Windows servers following Microsoft security baselines and CIS benchmarks.
## When to Use This Skill
Use this skill when:
- Hardening Windows servers
- Implementing security baselines
- Meeting compliance requirements
- Configuring Windows security features
## Security Baseline
```powershell
# Download Microsoft Security Baseline
# Apply via Group Policy or LGPO tool
# Install Security Compliance Toolkit
Install-Module -Name SecurityPolicyDsc
```
## Account Policies
```powershell
# Password policy via Group Policy
# Computer Configuration > Policies > Windows Settings > Security Settings
# PowerShell alternative
net accounts /minpwlen:14 /maxpwage:90 /minpwage:1 /uniquepw:24
# Disable Administrator account
Rename-LocalUser -Name "Administrator" -NewName "LocalAdmin"
Disable-LocalUser -Name "Guest"
```
## Windows Firewall
```powershell
# Enable firewall
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled True
# Default deny
Set-NetFirewallProfile -DefaultInboundAction Block -DefaultOutboundAction Allow
# Allow specific rules
New-NetFirewallRule -DisplayName "Allow RDP" -Direction Inbound -Protocol TCP -LocalPort 3389 -Action Allow
```
## Audit Configuration
```powershell
# Enable advanced audit policy
auditpol /set /subcategory:"Logon" /success:enable /failure:enable
auditpol /set /subcategory:"Account Lockout" /success:enable /failure:enable
auditpol /set /subcategory:"Security Group Management" /success:enable
# Enable PowerShell logging
Set-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging" -Name "EnableScriptBlockLogging" -Value 1
```
## Windows Defender
```powershell
# Enable real-time protection
Set-MpPreference -DisableRealtimeMonitoring $false
# Enable cloud protection
Set-MpPreference -MAPSReporting Advanced
# Configure scans
Set-MpPreference -ScanScheduleDay Everyday
Set-MpPreference -ScanScheduleTime 02:00:00
```
## Best Practices
- Apply security baselines
- Enable Windows Defender ATP
- Configure AppLocker
- Disable SMBv1
- Enable Credential Guard
- Regular Windows updates
- Implement LAPS for local admin passwords
## Related Skills
- [cis-benchmarks](../cis-benchmarks/) - Compliance scanning
- [windows-server](../../../infrastructure/servers/windows-server/) - Server administration