[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7B6667G6H4BK23ZXGJME5K3":3,"skill-same:01M7B6667G6H4BK23ZXGJME5K3":81},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":15,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":45,"commitSha":46,"skillDirectory":47,"forksCount":13,"repositoryHtmlUrl":48,"repositoryHomepageUrl":6,"ownerHtmlUrl":49,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":50,"install":51,"resources":64},"01M7B6667G6H4BK23ZXGJME5K3","detecting-port-scanning-with-fail2ban",null,"Configures Fail2ban with custom filters and actions to detect port scanning activity, SSH brute force attempts, and network reconnaissance, automatically banning offending IP addresses and alerting security teams to suspicious network probing.","vikasvardhanv\u002Fjerry_skills","vikasvardhanv","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99010657?v=4","01M7B2B0VN78W7529RQX5BR6DZ","01M7B2B0WDNTXJHRK3QNPNWRP6",0,"Apache-2.0","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fdetecting-port-scanning-with-fail2ban\u002FLICENSE","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fdetecting-port-scanning-with-fail2ban\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: detecting-port-scanning-with-fail2ban\ndescription: 'Configures Fail2ban with custom filters and actions to detect port scanning\n  activity, SSH brute force attempts, and network reconnaissance, automatically banning\n  offending IP addresses and alerting security teams to suspicious network probing.\n\n  '\ndomain: cybersecurity\nsubdomain: network-security\ntags:\n- network-security\n- fail2ban\n- port-scanning\n- intrusion-prevention\n- automated-defense\nversion: '1.0'\nauthor: mahipal\nlicense: Apache-2.0\nnist_csf:\n- PR.IR-01\n- DE.CM-01\n- ID.AM-03\n- PR.DS-02\nmitre_attack:\n- T1046\n- T1040\n- T1557\n- T1071\n- T1595\n---\n# Detecting Port Scanning with Fail2ban\n\n## When to Use\n\n- Automatically blocking IP addresses that perform port scans against internet-facing servers\n- Defending SSH, HTTP, FTP, and other services against brute force attacks with automated IP banning\n- Creating custom detection filters for organization-specific attack patterns in log files\n- Reducing noise from automated scanning bots before traffic reaches IDS\u002FIPS for deeper analysis\n- Implementing defense-in-depth by adding host-based automated response to network monitoring\n\n**Do not use** as the sole network security control, for protecting against distributed attacks from many source IPs, or as a replacement for proper firewall rules and network segmentation.\n\n## Prerequisites\n\n- Fail2ban 0.11+ installed (`fail2ban-client --version`)\n- Root\u002Fsudo access for iptables\u002Fnftables manipulation\n- Services logging connection attempts to parseable log files (syslog, auth.log, access.log)\n- iptables or nftables installed and operational as the host firewall\n- Optional: SMTP server for email notifications on ban events\n\n## Workflow\n\n### Step 1: Install and Configure Fail2ban\n\n```bash\n# Install Fail2ban\nsudo apt install -y fail2ban\n\n# Create local configuration (never edit jail.conf directly)\nsudo cp \u002Fetc\u002Ffail2ban\u002Fjail.conf \u002Fetc\u002Ffail2ban\u002Fjail.local\n\n# Configure global defaults\nsudo tee \u002Fetc\u002Ffail2ban\u002Fjail.local \u003C\u003C 'EOF'\n[DEFAULT]\n# Ban duration (1 hour default, escalates for repeat offenders)\nbantime = 3600\n# Detection window\nfindtime = 600\n# Max failures before ban\nmaxretry = 5\n# Ban action using iptables\nbanaction = iptables-multiport\nbanaction_allports = iptables-allports\n# Email notifications\ndestemail = security@example.com\nsender = fail2ban@example.com\nmta = sendmail\naction = %(action_mwl)s\n\n# Ignore internal networks\nignoreip = 127.0.0.1\u002F8 ::1 10.10.0.0\u002F16\n\n# Use systemd journal backend where available\nbackend = systemd\n\n[sshd]\nenabled = true\nport = ssh\nfilter = sshd\nlogpath = \u002Fvar\u002Flog\u002Fauth.log\nmaxretry = 3\nbantime = 7200\nfindtime = 300\n\n[sshd-ddos]\nenabled = true\nport = ssh\nfilter = sshd-ddos\nlogpath = \u002Fvar\u002Flog\u002Fauth.log\nmaxretry = 6\nbantime = 3600\nEOF\n```\n\n### Step 2: Create Custom Port Scan Detection Filter\n\n```bash\n# Create iptables logging rule for dropped connections\nsudo iptables -N PORTSCAN\nsudo iptables -A PORTSCAN -j LOG --log-prefix \"PORTSCAN_DETECTED: \" --log-level 4\nsudo iptables -A PORTSCAN -j DROP\n\n# Log SYN packets to closed ports (indicates scanning)\nsudo iptables -A INPUT -p tcp --tcp-flags SYN,ACK,FIN,RST SYN -m state --state NEW \\\n  -m recent --name portscan --set\nsudo iptables -A INPUT -p tcp --tcp-flags SYN,ACK,FIN,RST SYN -m state --state NEW \\\n  -m recent --name portscan --rcheck --seconds 10 --hitcount 20 -j PORTSCAN\n\n# Create Fail2ban filter for port scanning\nsudo tee \u002Fetc\u002Ffail2ban\u002Ffilter.d\u002Fportscan.conf \u003C\u003C 'EOF'\n[Definition]\n# Match iptables port scan log entries\nfailregex = PORTSCAN_DETECTED: .* SRC=\u003CHOST> DST=\\S+ .* DPT=\\d+\nignoreregex =\ndatepattern = {^LN-BEG}\nEOF\n\n# Create Fail2ban filter for Nmap detection via kernel logs\nsudo tee \u002Fetc\u002Ffail2ban\u002Ffilter.d\u002Fnmap-scan.conf \u003C\u003C 'EOF'\n[Definition]\n# Detect rapid connection attempts to multiple ports from same source\nfailregex = kernel: \\[.*\\] PORTSCAN_DETECTED: .* SRC=\u003CHOST>\n            iptables: .* PORTSCAN .* SRC=\u003CHOST>\nignoreregex =\ndatepattern = {^LN-BEG}\nEOF\n\n# Create filter for HTTP scanning\u002Fprobing\nsudo tee \u002Fetc\u002Ffail2ban\u002Ffilter.d\u002Fhttp-scan.conf \u003C\u003C 'EOF'\n[Definition]\n# Detect scanners probing for common vulnerabilities\nfailregex = ^\u003CHOST> .* \"(GET|POST|HEAD) \u002F(wp-login|wp-admin|phpmyadmin|admin|.env|xmlrpc|wp-content\u002Fuploads).*\" (403|404|444)\n            ^\u003CHOST> .* \"(GET|POST) \u002F.*\\.(php|asp|aspx|jsp|cgi)\\?.*\" (403|404)\n            ^\u003CHOST> .* \"() .*\" 400\n            ^\u003CHOST> .* \"(GET|POST) \u002F.*\" 400\nignoreregex =\ndatepattern = {^LN-BEG}\nEOF\n```\n\n### Step 3: Configure Jail for Port Scanning\n\n```bash\n# Add port scan jails to jail.local\nsudo tee -a \u002Fetc\u002Ffail2ban\u002Fjail.local \u003C\u003C 'EOF'\n\n[portscan]\nenabled = true\nfilter = portscan\nlogpath = \u002Fvar\u002Flog\u002Fkern.log\nmaxretry = 10\nfindtime = 60\nbantime = 86400\nbanaction = iptables-allports\naction = %(action_mwl)s\n\n[nmap-scan]\nenabled = true\nfilter = nmap-scan\nlogpath = \u002Fvar\u002Flog\u002Fkern.log\nmaxretry = 5\nfindtime = 30\nbantime = 86400\nbanaction = iptables-allports\naction = %(action_mwl)s\n\n[http-scan]\nenabled = true\nfilter = http-scan\nlogpath = \u002Fvar\u002Flog\u002Fnginx\u002Faccess.log\nmaxretry = 10\nfindtime = 300\nbantime = 3600\nbanaction = iptables-multiport\nport = http,https\n\n[recidive]\nenabled = true\nfilter = recidive\nlogpath = \u002Fvar\u002Flog\u002Ffail2ban.log\nbantime = 604800\nfindtime = 86400\nmaxretry = 3\nbanaction = iptables-allports\naction = %(action_mwl)s\nEOF\n```\n\n### Step 4: Configure Advanced Ban Actions\n\n```bash\n# Create custom action that blocks and sends webhook notification\nsudo tee \u002Fetc\u002Ffail2ban\u002Faction.d\u002Fiptables-webhook.conf \u003C\u003C 'EOF'\n[Definition]\nactionstart = \u003Ciptables> -N f2b-\u003Cname>\n              \u003Ciptables> -A f2b-\u003Cname> -j RETURN\n              \u003Ciptables> -I \u003Cchain> -p \u003Cprotocol> -j f2b-\u003Cname>\n\nactionstop = \u003Ciptables> -D \u003Cchain> -p \u003Cprotocol> -j f2b-\u003Cname>\n             \u003Ciptables> -F f2b-\u003Cname>\n             \u003Ciptables> -X f2b-\u003Cname>\n\nactioncheck = \u003Ciptables> -n -L \u003Cchain> | grep -q 'f2b-\u003Cname>[ \\t]'\n\nactionban = \u003Ciptables> -I f2b-\u003Cname> 1 -s \u003Cip> -j \u003Cblocktype>\n            curl -s -X POST \"\u003Cwebhook_url>\" \\\n              -H \"Content-Type: application\u002Fjson\" \\\n              -d '{\"text\":\"[Fail2ban] Banned \u003Cip> from \u003Cname> jail (failures: \u003Cfailures>)\"}'\n\nactionunban = \u003Ciptables> -D f2b-\u003Cname> -s \u003Cip> -j \u003Cblocktype>\n\n[Init]\nchain = INPUT\nblocktype = DROP\nwebhook_url = https:\u002F\u002Fhooks.slack.com\u002Fservices\u002FXXXX\u002FYYYY\u002FZZZZ\nEOF\n\n# Create escalating ban action for repeat offenders\nsudo tee \u002Fetc\u002Ffail2ban\u002Faction.d\u002Fescalating-ban.conf \u003C\u003C 'EOF'\n[Definition]\nactionban = \u003Ciptables> -I f2b-\u003Cname> 1 -s \u003Cip> -j DROP\n            echo \"$(date) BAN \u003Cip> jail=\u003Cname> failures=\u003Cfailures> bantime=\u003Cbantime>\" >> \u002Fvar\u002Flog\u002Ffail2ban-bans.log\n\nactionunban = \u003Ciptables> -D f2b-\u003Cname> -s \u003Cip> -j DROP\n              echo \"$(date) UNBAN \u003Cip> jail=\u003Cname>\" >> \u002Fvar\u002Flog\u002Ffail2ban-bans.log\nEOF\n```\n\n### Step 5: Test and Validate Detection\n\n```bash\n# Restart Fail2ban\nsudo systemctl restart fail2ban\n\n# Verify jails are active\nsudo fail2ban-client status\nsudo fail2ban-client status sshd\nsudo fail2ban-client status portscan\n\n# Test the port scan filter with a regex check\nsudo fail2ban-regex \u002Fvar\u002Flog\u002Fkern.log \u002Fetc\u002Ffail2ban\u002Ffilter.d\u002Fportscan.conf\n\n# Test the HTTP scan filter\nsudo fail2ban-regex \u002Fvar\u002Flog\u002Fnginx\u002Faccess.log \u002Fetc\u002Ffail2ban\u002Ffilter.d\u002Fhttp-scan.conf\n\n# Simulate a port scan from a test machine (authorized)\n# From the test machine:\nnmap -sS -p 1-1000 \u003Ctarget_ip>\n\n# Verify the scanner gets banned\nsudo fail2ban-client status portscan\n# Should show the test IP in the banned list\n\n# Check iptables for the ban rule\nsudo iptables -L f2b-portscan -n\n\n# Unban the test IP\nsudo fail2ban-client set portscan unbanip \u003Ctest_ip>\n```\n\n### Step 6: Monitor and Maintain\n\n```bash\n# View real-time ban activity\nsudo tail -f \u002Fvar\u002Flog\u002Ffail2ban.log | grep -E \"Ban|Unban\"\n\n# Generate daily summary report\nsudo tee \u002Fusr\u002Flocal\u002Fbin\u002Ffail2ban-report.sh \u003C\u003C 'SCRIPT'\n#!\u002Fbin\u002Fbash\necho \"=== Fail2ban Daily Report $(date) ===\"\necho \"\"\necho \"Active Jails:\"\nsudo fail2ban-client status | grep \"Jail list\"\necho \"\"\necho \"Currently Banned IPs:\"\nfor jail in $(sudo fail2ban-client status | grep \"Jail list\" | sed 's\u002F.*:\u002F\u002F;s\u002F,\u002F\u002Fg'); do\n    count=$(sudo fail2ban-client status \"$jail\" | grep \"Currently banned\" | awk '{print $NF}')\n    if [ \"$count\" -gt 0 ]; then\n        echo \"  $jail: $count banned\"\n        sudo fail2ban-client status \"$jail\" | grep \"Banned IP\"\n    fi\ndone\necho \"\"\necho \"Last 24 hours - Ban count by jail:\"\ngrep \"Ban \" \u002Fvar\u002Flog\u002Ffail2ban.log | grep \"$(date +%Y-%m-%d)\" | awk '{print $NF}' | sort | uniq -c | sort -rn\nSCRIPT\nchmod +x \u002Fusr\u002Flocal\u002Fbin\u002Ffail2ban-report.sh\n\n# Schedule daily report\necho \"0 8 * * * root \u002Fusr\u002Flocal\u002Fbin\u002Ffail2ban-report.sh | mail -s 'Fail2ban Report' security@example.com\" | sudo tee \u002Fetc\u002Fcron.d\u002Ffail2ban-report\n\n# Persist iptables rules across reboots\nsudo apt install iptables-persistent\nsudo netfilter-persistent save\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **Jail** | Fail2ban configuration unit that combines a filter (what to detect), an action (what to do), and parameters (thresholds, timing) for a specific service |\n| **Filter** | Regular expression patterns that Fail2ban applies to log files to identify failed authentication attempts, scanning, or other malicious activity |\n| **Recidive Jail** | Meta-jail that monitors Fail2ban's own log for repeat offenders, applying escalating ban durations to IPs banned multiple times |\n| **Find Time** | Time window in seconds during which Fail2ban counts matching log entries; maxretry failures within findtime triggers a ban |\n| **Ban Action** | Command or script executed when an IP is banned, typically adding firewall rules but extensible to webhooks, SIEM alerts, or blocklist updates |\n| **Ignore IP** | Whitelist of IP addresses or CIDR ranges that are never banned, preventing lockout of trusted networks and monitoring systems |\n\n## Tools & Systems\n\n- **Fail2ban 0.11+**: Log-parsing intrusion prevention framework that bans IP addresses based on pattern matching across any log file\n- **iptables\u002Fnftables**: Linux kernel firewall used by Fail2ban ban actions to block offending IP addresses at the network layer\n- **fail2ban-regex**: Testing utility for validating filter regular expressions against actual log files before deploying to production\n- **fail2ban-client**: Command-line management tool for querying jail status, manually banning\u002Funbanning IPs, and reloading configuration\n- **rsyslog\u002Fsyslog-ng**: System logging daemons that generate the log files Fail2ban monitors for attack detection\n\n## Common Scenarios\n\n### Scenario: Defending a Public-Facing Web Server Against Automated Scanning\n\n**Context**: A company runs a public web server that receives thousands of automated scan attempts daily from bots probing for vulnerable paths (\u002Fwp-admin, \u002Fphpmyadmin, \u002F.env). The security team wants to automatically block scanners while allowing legitimate traffic. The server runs Nginx on Ubuntu 22.04.\n\n**Approach**:\n1. Install Fail2ban and configure it to monitor Nginx access logs for scanning patterns (404\u002F403 responses to known vulnerability paths)\n2. Create a custom `http-scan` filter matching common scanner signatures and vulnerability probing URIs\n3. Set maxretry to 10 within a 5-minute findtime, with a 1-hour bantime for first offense\n4. Enable the recidive jail to escalate ban duration to 7 days for repeat offenders\n5. Configure webhook notifications to Slack for real-time visibility of banning activity\n6. Add iptables logging rules for SYN packets to closed ports to detect port scanning\n7. Create a daily report script showing banned IPs, attack patterns, and geographic distribution\n\n**Pitfalls**:\n- Setting maxretry too low (e.g., 1-2), causing legitimate users who mistype URLs to get banned\n- Not whitelisting monitoring systems (Nagios, UptimeRobot) that may trigger filters with their health checks\n- Forgetting to persist iptables rules, losing all bans after a reboot\n- Not testing filters with fail2ban-regex before deploying, resulting in no matches or excessive false positives\n\n## Output Format\n\n```\n## Fail2ban Port Scan Defense Report\n\n**Server**: web-prod-01 (203.0.113.50)\n**Reporting Period**: 2024-03-15 00:00 to 2024-03-16 00:00 UTC\n\n### Active Jails\n\n| Jail | Filter | Max Retry | Ban Time | Currently Banned |\n|------|--------|-----------|----------|------------------|\n| sshd | sshd | 3 | 2 hours | 12 IPs |\n| portscan | portscan | 10 | 24 hours | 47 IPs |\n| http-scan | http-scan | 10 | 1 hour | 89 IPs |\n| recidive | recidive | 3 | 7 days | 8 IPs |\n\n### 24-Hour Summary\n- Total ban events: 347\n- Unique IPs banned: 156\n- Top attacking country: CN (67 IPs), RU (34 IPs), US (21 IPs)\n- Most targeted service: HTTP scanning (214 bans)\n- Recidive escalations: 8 IPs banned for 7 days\n\n### Top 5 Banned IPs\n| IP Address | Jail | Ban Count | First Seen | Last Seen |\n|------------|------|-----------|------------|-----------|\n| 45.33.32.156 | portscan | 12 | 00:15 | 23:47 |\n| 198.51.100.23 | http-scan | 8 | 02:30 | 18:22 |\n| 203.0.113.100 | sshd | 6 | 05:12 | 21:33 |\n```\n","# Detecting Port Scanning with Fail2ban\n\n## When to Use\n\n- Automatically blocking IP addresses that perform port scans against internet-facing servers\n- Defending SSH, HTTP, FTP, and other services against brute force attacks with automated IP banning\n- Creating custom detection filters for organization-specific attack patterns in log files\n- Reducing noise from automated scanning bots before traffic reaches IDS\u002FIPS for deeper analysis\n- Implementing defense-in-depth by adding host-based automated response to network monitoring\n\n**Do not use** as the sole network security control, for protecting against distributed attacks from many source IPs, or as a replacement for proper firewall rules and network segmentation.\n\n## Prerequisites\n\n- Fail2ban 0.11+ installed (`fail2ban-client --version`)\n- Root\u002Fsudo access for iptables\u002Fnftables manipulation\n- Services logging connection attempts to parseable log files (syslog, auth.log, access.log)\n- iptables or nftables installed and operational as the host firewall\n- Optional: SMTP server for email notifications on ban events\n\n## Workflow\n\n### Step 1: Install and Configure Fail2ban\n\n```bash\n# Install Fail2ban\nsudo apt install -y fail2ban\n\n# Create local configuration (never edit jail.conf directly)\nsudo cp \u002Fetc\u002Ffail2ban\u002Fjail.conf \u002Fetc\u002Ffail2ban\u002Fjail.local\n\n# Configure global defaults\nsudo tee \u002Fetc\u002Ffail2ban\u002Fjail.local \u003C\u003C 'EOF'\n[DEFAULT]\n# Ban duration (1 hour default, escalates for repeat offenders)\nbantime = 3600\n# Detection window\nfindtime = 600\n# Max failures before ban\nmaxretry = 5\n# Ban action using iptables\nbanaction = iptables-multiport\nbanaction_allports = iptables-allports\n# Email notifications\ndestemail = security@example.com\nsender = fail2ban@example.com\nmta = sendmail\naction = %(action_mwl)s\n\n# Ignore internal networks\nignoreip = 127.0.0.1\u002F8 ::1 10.10.0.0\u002F16\n\n# Use systemd journal backend where available\nbackend = systemd\n\n[sshd]\nenabled = true\nport = ssh\nfilter = sshd\nlogpath = \u002Fvar\u002Flog\u002Fauth.log\nmaxretry = 3\nbantime = 7200\nfindtime = 300\n\n[sshd-ddos]\nenabled = true\nport = ssh\nfilter = sshd-ddos\nlogpath = \u002Fvar\u002Flog\u002Fauth.log\nmaxretry = 6\nbantime = 3600\nEOF\n```\n\n### Step 2: Create Custom Port Scan Detection Filter\n\n```bash\n# Create iptables logging rule for dropped connections\nsudo iptables -N PORTSCAN\nsudo iptables -A PORTSCAN -j LOG --log-prefix \"PORTSCAN_DETECTED: \" --log-level 4\nsudo iptables -A PORTSCAN -j DROP\n\n# Log SYN packets to closed ports (indicates scanning)\nsudo iptables -A INPUT -p tcp --tcp-flags SYN,ACK,FIN,RST SYN -m state --state NEW \\\n  -m recent --name portscan --set\nsudo iptables -A INPUT -p tcp --tcp-flags SYN,ACK,FIN,RST SYN -m state --state NEW \\\n  -m recent --name portscan --rcheck --seconds 10 --hitcount 20 -j PORTSCAN\n\n# Create Fail2ban filter for port scanning\nsudo tee \u002Fetc\u002Ffail2ban\u002Ffilter.d\u002Fportscan.conf \u003C\u003C 'EOF'\n[Definition]\n# Match iptables port scan log entries\nfailregex = PORTSCAN_DETECTED: .* SRC=\u003CHOST> DST=\\S+ .* DPT=\\d+\nignoreregex =\ndatepattern = {^LN-BEG}\nEOF\n\n# Create Fail2ban filter for Nmap detection via kernel logs\nsudo tee \u002Fetc\u002Ffail2ban\u002Ffilter.d\u002Fnmap-scan.conf \u003C\u003C 'EOF'\n[Definition]\n# Detect rapid connection attempts to multiple ports from same source\nfailregex = kernel: \\[.*\\] PORTSCAN_DETECTED: .* SRC=\u003CHOST>\n            iptables: .* PORTSCAN .* SRC=\u003CHOST>\nignoreregex =\ndatepattern = {^LN-BEG}\nEOF\n\n# Create filter for HTTP scanning\u002Fprobing\nsudo tee \u002Fetc\u002Ffail2ban\u002Ffilter.d\u002Fhttp-scan.conf \u003C\u003C 'EOF'\n[Definition]\n# Detect scanners probing for common vulnerabilities\nfailregex = ^\u003CHOST> .* \"(GET|POST|HEAD) \u002F(wp-login|wp-admin|phpmyadmin|admin|.env|xmlrpc|wp-content\u002Fuploads).*\" (403|404|444)\n            ^\u003CHOST> .* \"(GET|POST) \u002F.*\\.(php|asp|aspx|jsp|cgi)\\?.*\" (403|404)\n            ^\u003CHOST> .* \"() .*\" 400\n            ^\u003CHOST> .* \"(GET|POST) \u002F.*\" 400\nignoreregex =\ndatepattern = {^LN-BEG}\nEOF\n```\n\n### Step 3: Configure Jail for Port Scanning\n\n```bash\n# Add port scan jails to jail.local\nsudo tee -a \u002Fetc\u002Ffail2ban\u002Fjail.local \u003C\u003C 'EOF'\n\n[portscan]\nenabled = true\nfilter = portscan\nlogpath = \u002Fvar\u002Flog\u002Fkern.log\nmaxretry = 10\nfindtime = 60\nbantime = 86400\nbanaction = iptables-allports\naction = %(action_mwl)s\n\n[nmap-scan]\nenabled = true\nfilter = nmap-scan\nlogpath = \u002Fvar\u002Flog\u002Fkern.log\nmaxretry = 5\nfindtime = 30\nbantime = 86400\nbanaction = iptables-allports\naction = %(action_mwl)s\n\n[http-scan]\nenabled = true\nfilter = http-scan\nlogpath = \u002Fvar\u002Flog\u002Fnginx\u002Faccess.log\nmaxretry = 10\nfindtime = 300\nbantime = 3600\nbanaction = iptables-multiport\nport = http,https\n\n[recidive]\nenabled = true\nfilter = recidive\nlogpath = \u002Fvar\u002Flog\u002Ffail2ban.log\nbantime = 604800\nfindtime = 86400\nmaxretry = 3\nbanaction = iptables-allports\naction = %(action_mwl)s\nEOF\n```\n\n### Step 4: Configure Advanced Ban Actions\n\n```bash\n# Create custom action that blocks and sends webhook notification\nsudo tee \u002Fetc\u002Ffail2ban\u002Faction.d\u002Fiptables-webhook.conf \u003C\u003C 'EOF'\n[Definition]\nactionstart = \u003Ciptables> -N f2b-\u003Cname>\n              \u003Ciptables> -A f2b-\u003Cname> -j RETURN\n              \u003Ciptables> -I \u003Cchain> -p \u003Cprotocol> -j f2b-\u003Cname>\n\nactionstop = \u003Ciptables> -D \u003Cchain> -p \u003Cprotocol> -j f2b-\u003Cname>\n             \u003Ciptables> -F f2b-\u003Cname>\n             \u003Ciptables> -X f2b-\u003Cname>\n\nactioncheck = \u003Ciptables> -n -L \u003Cchain> | grep -q 'f2b-\u003Cname>[ \\t]'\n\nactionban = \u003Ciptables> -I f2b-\u003Cname> 1 -s \u003Cip> -j \u003Cblocktype>\n            curl -s -X POST \"\u003Cwebhook_url>\" \\\n              -H \"Content-Type: application\u002Fjson\" \\\n              -d '{\"text\":\"[Fail2ban] Banned \u003Cip> from \u003Cname> jail (failures: \u003Cfailures>)\"}'\n\nactionunban = \u003Ciptables> -D f2b-\u003Cname> -s \u003Cip> -j \u003Cblocktype>\n\n[Init]\nchain = INPUT\nblocktype = DROP\nwebhook_url = https:\u002F\u002Fhooks.slack.com\u002Fservices\u002FXXXX\u002FYYYY\u002FZZZZ\nEOF\n\n# Create escalating ban action for repeat offenders\nsudo tee \u002Fetc\u002Ffail2ban\u002Faction.d\u002Fescalating-ban.conf \u003C\u003C 'EOF'\n[Definition]\nactionban = \u003Ciptables> -I f2b-\u003Cname> 1 -s \u003Cip> -j DROP\n            echo \"$(date) BAN \u003Cip> jail=\u003Cname> failures=\u003Cfailures> bantime=\u003Cbantime>\" >> \u002Fvar\u002Flog\u002Ffail2ban-bans.log\n\nactionunban = \u003Ciptables> -D f2b-\u003Cname> -s \u003Cip> -j DROP\n              echo \"$(date) UNBAN \u003Cip> jail=\u003Cname>\" >> \u002Fvar\u002Flog\u002Ffail2ban-bans.log\nEOF\n```\n\n### Step 5: Test and Validate Detection\n\n```bash\n# Restart Fail2ban\nsudo systemctl restart fail2ban\n\n# Verify jails are active\nsudo fail2ban-client status\nsudo fail2ban-client status sshd\nsudo fail2ban-client status portscan\n\n# Test the port scan filter with a regex check\nsudo fail2ban-regex \u002Fvar\u002Flog\u002Fkern.log \u002Fetc\u002Ffail2ban\u002Ffilter.d\u002Fportscan.conf\n\n# Test the HTTP scan filter\nsudo fail2ban-regex \u002Fvar\u002Flog\u002Fnginx\u002Faccess.log \u002Fetc\u002Ffail2ban\u002Ffilter.d\u002Fhttp-scan.conf\n\n# Simulate a port scan from a test machine (authorized)\n# From the test machine:\nnmap -sS -p 1-1000 \u003Ctarget_ip>\n\n# Verify the scanner gets banned\nsudo fail2ban-client status portscan\n# Should show the test IP in the banned list\n\n# Check iptables for the ban rule\nsudo iptables -L f2b-portscan -n\n\n# Unban the test IP\nsudo fail2ban-client set portscan unbanip \u003Ctest_ip>\n```\n\n### Step 6: Monitor and Maintain\n\n```bash\n# View real-time ban activity\nsudo tail -f \u002Fvar\u002Flog\u002Ffail2ban.log | grep -E \"Ban|Unban\"\n\n# Generate daily summary report\nsudo tee \u002Fusr\u002Flocal\u002Fbin\u002Ffail2ban-report.sh \u003C\u003C 'SCRIPT'\n#!\u002Fbin\u002Fbash\necho \"=== Fail2ban Daily Report $(date) ===\"\necho \"\"\necho \"Active Jails:\"\nsudo fail2ban-client status | grep \"Jail list\"\necho \"\"\necho \"Currently Banned IPs:\"\nfor jail in $(sudo fail2ban-client status | grep \"Jail list\" | sed 's\u002F.*:\u002F\u002F;s\u002F,\u002F\u002Fg'); do\n    count=$(sudo fail2ban-client status \"$jail\" | grep \"Currently banned\" | awk '{print $NF}')\n    if [ \"$count\" -gt 0 ]; then\n        echo \"  $jail: $count banned\"\n        sudo fail2ban-client status \"$jail\" | grep \"Banned IP\"\n    fi\ndone\necho \"\"\necho \"Last 24 hours - Ban count by jail:\"\ngrep \"Ban \" \u002Fvar\u002Flog\u002Ffail2ban.log | grep \"$(date +%Y-%m-%d)\" | awk '{print $NF}' | sort | uniq -c | sort -rn\nSCRIPT\nchmod +x \u002Fusr\u002Flocal\u002Fbin\u002Ffail2ban-report.sh\n\n# Schedule daily report\necho \"0 8 * * * root \u002Fusr\u002Flocal\u002Fbin\u002Ffail2ban-report.sh | mail -s 'Fail2ban Report' security@example.com\" | sudo tee \u002Fetc\u002Fcron.d\u002Ffail2ban-report\n\n# Persist iptables rules across reboots\nsudo apt install iptables-persistent\nsudo netfilter-persistent save\n```\n\n## Key Concepts\n\n| Term | Definition |\n|------|------------|\n| **Jail** | Fail2ban configuration unit that combines a filter (what to detect), an action (what to do), and parameters (thresholds, timing) for a specific service |\n| **Filter** | Regular expression patterns that Fail2ban applies to log files to identify failed authentication attempts, scanning, or other malicious activity |\n| **Recidive Jail** | Meta-jail that monitors Fail2ban's own log for repeat offenders, applying escalating ban durations to IPs banned multiple times |\n| **Find Time** | Time window in seconds during which Fail2ban counts matching log entries; maxretry failures within findtime triggers a ban |\n| **Ban Action** | Command or script executed when an IP is banned, typically adding firewall rules but extensible to webhooks, SIEM alerts, or blocklist updates |\n| **Ignore IP** | Whitelist of IP addresses or CIDR ranges that are never banned, preventing lockout of trusted networks and monitoring systems |\n\n## Tools & Systems\n\n- **Fail2ban 0.11+**: Log-parsing intrusion prevention framework that bans IP addresses based on pattern matching across any log file\n- **iptables\u002Fnftables**: Linux kernel firewall used by Fail2ban ban actions to block offending IP addresses at the network layer\n- **fail2ban-regex**: Testing utility for validating filter regular expressions against actual log files before deploying to production\n- **fail2ban-client**: Command-line management tool for querying jail status, manually banning\u002Funbanning IPs, and reloading configuration\n- **rsyslog\u002Fsyslog-ng**: System logging daemons that generate the log files Fail2ban monitors for attack detection\n\n## Common Scenarios\n\n### Scenario: Defending a Public-Facing Web Server Against Automated Scanning\n\n**Context**: A company runs a public web server that receives thousands of automated scan attempts daily from bots probing for vulnerable paths (\u002Fwp-admin, \u002Fphpmyadmin, \u002F.env). The security team wants to automatically block scanners while allowing legitimate traffic. The server runs Nginx on Ubuntu 22.04.\n\n**Approach**:\n1. Install Fail2ban and configure it to monitor Nginx access logs for scanning patterns (404\u002F403 responses to known vulnerability paths)\n2. Create a custom `http-scan` filter matching common scanner signatures and vulnerability probing URIs\n3. Set maxretry to 10 within a 5-minute findtime, with a 1-hour bantime for first offense\n4. Enable the recidive jail to escalate ban duration to 7 days for repeat offenders\n5. Configure webhook notifications to Slack for real-time visibility of banning activity\n6. Add iptables logging rules for SYN packets to closed ports to detect port scanning\n7. Create a daily report script showing banned IPs, attack patterns, and geographic distribution\n\n**Pitfalls**:\n- Setting maxretry too low (e.g., 1-2), causing legitimate users who mistype URLs to get banned\n- Not whitelisting monitoring systems (Nagios, UptimeRobot) that may trigger filters with their health checks\n- Forgetting to persist iptables rules, losing all bans after a reboot\n- Not testing filters with fail2ban-regex before deploying, resulting in no matches or excessive false positives\n\n## Output Format\n\n```\n## Fail2ban Port Scan Defense Report\n\n**Server**: web-prod-01 (203.0.113.50)\n**Reporting Period**: 2024-03-15 00:00 to 2024-03-16 00:00 UTC\n\n### Active Jails\n\n| Jail | Filter | Max Retry | Ban Time | Currently Banned |\n|------|--------|-----------|----------|------------------|\n| sshd | sshd | 3 | 2 hours | 12 IPs |\n| portscan | portscan | 10 | 24 hours | 47 IPs |\n| http-scan | http-scan | 10 | 1 hour | 89 IPs |\n| recidive | recidive | 3 | 7 days | 8 IPs |\n\n### 24-Hour Summary\n- Total ban events: 347\n- Unique IPs banned: 156\n- Top attacking country: CN (67 IPs), RU (34 IPs), US (21 IPs)\n- Most targeted service: HTTP scanning (214 bans)\n- Recidive escalations: 8 IPs banned for 7 days\n\n### Top 5 Banned IPs\n| IP Address | Jail | Ban Count | First Seen | Last Seen |\n|------------|------|-----------|------------|-----------|\n| 45.33.32.156 | portscan | 12 | 00:15 | 23:47 |\n| 198.51.100.23 | http-scan | 8 | 02:30 | 18:22 |\n| 203.0.113.100 | sshd | 6 | 05:12 | 21:33 |\n```\n",{"name":5,"tags":24,"author":30,"domain":31,"license":14,"version":32,"nist_csf":33,"subdomain":25,"description":38,"mitre_attack":39},[25,26,27,28,29],"network-security","fail2ban","port-scanning","intrusion-prevention","automated-defense","mahipal","cybersecurity","1.0",[34,35,36,37],"PR.IR-01","DE.CM-01","ID.AM-03","PR.DS-02","Configures Fail2ban with custom filters and actions to detect port scanning activity, SSH brute force attempts, and network reconnaissance, automatically banning offending IP addresses and alerting security teams to suspicious network probing.\n",[40,41,42,43,44],"T1046","T1040","T1557","T1071","T1595","main","1eb986d0b0ecc180291597e08eb5a58288843536","skills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fdetecting-port-scanning-with-fail2ban","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv","2026-08-25 13:16:33",{"source":8,"skillName":5,"commands":52,"prompt":62,"zipAvailable":63},[53,56,59],{"tool":54,"command":55},"npx","npx skills add vikasvardhanv\u002Fjerry_skills --skill detecting-port-scanning-with-fail2ban",{"tool":57,"command":58},"bunx","bunx skills add vikasvardhanv\u002Fjerry_skills --skill detecting-port-scanning-with-fail2ban",{"tool":60,"command":61},"pnpm","pnpm dlx skills add vikasvardhanv\u002Fjerry_skills --skill detecting-port-scanning-with-fail2ban","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fdetecting-port-scanning-with-fail2ban\u002FSKILL.md",true,[65,69,75],{"path":66,"resourceType":66,"resourceTypeDesc":67,"sizeBytes":68,"sourceHtmlUrl":15},"LICENSE","许可证",11255,{"path":70,"resourceType":71,"resourceTypeDesc":72,"sizeBytes":73,"sourceHtmlUrl":74},"references\u002Fapi-reference.md","REFERENCE","参考文档",2044,"https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fdetecting-port-scanning-with-fail2ban\u002Freferences\u002Fapi-reference.md",{"path":76,"resourceType":77,"resourceTypeDesc":78,"sizeBytes":79,"sourceHtmlUrl":80},"scripts\u002Fagent.py","SCRIPT","脚本",8442,"https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fcurated_premium_skills\u002FAnthropic-Cybersecurity-Skills\u002Fskills\u002Fdetecting-port-scanning-with-fail2ban\u002Fscripts\u002Fagent.py",[82,90,97,104,111,118],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M7BESR1CJ3H5SP9XM8KYJZ9W","syllabus","Generates a curated supplementary reading list from any course syllabus using Consensus academic search. Grill-me intake (syllabus input format + course audience + year range) plus a grouping forcing-options checkpoint before any search runs — so the reading list matches the course's level and recency need. Parses the syllabus to extract topics and learning outcomes, searches Consensus for recent peer-reviewed papers per topic, and produces a professionally formatted .docx with clickable Consensus links, plain-language summaries calibrated to audience level, and Bloom-higher-order discussion questions tied to course learning goals. Use when the user uploads a syllabus, course outline, or curriculum document and wants supplementary readings (e.g., 'create a reading list from this syllabus', 'find recent papers for my course') — even casual mentions with a syllabus attached should trigger this skill.","MIT","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fsyllabus\u002Fskills\u002Fsyllabus\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M7BES1YA6R97W7QPMFFM1PED","pulse","Multi-source recency research skill that takes the pulse of any topic across Reddit, Hacker News, the open web, and optionally X\u002FTwitter within a configurable recent window (default 30 days). Forcing intake clarifies topic specificity, angle (trend\u002Fsentiment\u002Fproblems\u002Fopportunities\u002Fcomparison), time window, and platform scope before searching. Returns a synthesized briefing with citations, engagement metrics, and cross-platform pattern analysis. Use when the user requests multi-source recency intelligence on a topic (e.g., 'pulse on [topic]', 'what's happening with [topic]', 'what are people saying about [topic]', 'current conversation about [topic]', 'take the pulse of [topic]', 'trending: [topic]', 'find me info on [topic]'), and for competitor research, trend discovery, tool comparisons, and audience sentiment analysis.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fpulse\u002Fskills\u002Fpulse\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M7BERNHYGY035AR00VRT03KE","patent","Patent prior-art and landscape intelligence skill — not generic patent help. Commits to one of five sub-use-cases via forcing intake (novelty search \u002F freedom-to-operate \u002F competitive landscape \u002F acquisition diligence \u002F litigation prior-art) before any search runs. Searches Google Patents, Espacenet, USPTO, and optionally Lens.org for citation-graph signals. Output is an editable Word document (.docx) with verdict, ranked closest art (claim-text extracted), CPC-class-aware landscape, family-resolved hits, geographic coverage, FTO flags where applicable, strategy recommendations, and full audit log. Use when the user asks for patent searching or analysis (e.g., 'prior art search for [invention]', 'freedom to operate analysis for [product]'). Produces search signal, not legal advice — always recommends consulting a patent attorney before filing or licensing decisions. Trademark, copyright, and trade-secret questions are out of scope.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fpatent\u002Fskills\u002Fpatent\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":19},"01M7BERCK1EAKTWW7R436WAR0J","notebooklm","Browser automation skill for controlling Google's NotebookLM. Use when the user wants anything done in NotebookLM (e.g., 'open NotebookLM', 'check my [name] notebook', 'ask my notebook about X', 'add [source] to NotebookLM', 'generate a Video Overview from my notebook', 'use NotebookLM Studio'). Handles reading and querying notebooks, adding sources (URLs, text, files, YouTube links, synthesized content), generating Studio outputs (Audio\u002FVideo Overviews, Mind Maps, Reports incl. Briefing Doc\u002FStudy Guide\u002FFAQ, Flashcards, Quiz, slide decks, infographics — discover the exact set from the live Studio panel; the UI evolves fast), and creating new notebooks. Requires browser automation environment — fails gracefully when unavailable.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fnotebooklm\u002Fskills\u002Fnotebooklm\u002FSKILL.md",[],[],{"skillNo":112,"name":113,"nameZh":6,"description":114,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":115,"categories":116,"keywords":117,"publishedAt":19},"01M7BEQZAZAQRTXFJRY7RHV3TY","litreview","Academic literature orientation skill that searches papers via free keyless APIs (PubMed E-utilities + OpenAlex) by default — with the Consensus MCP as an optional enhancement lane when connected — builds a strategic search plan using PICO (default) or SPIDER \u002F Decomposition \u002F hybrid as fallbacks, and synthesizes findings into a formatted Word (.docx) research guide. Grill-me intake (research question specificity + framework hint + tentative depth) before the recon search; a second forcing checkpoint after Phase 2 confirms framework + sub-areas + depth before searches consume budget. Configurable depth (5\u002F10\u002F20 queries) controls coverage vs. speed. Output is a 'launching pad' — an orientation guide that lets a researcher dive in confidently, not a finished review. Use when the user starts literature-oriented research (e.g., 'litreview on [topic]', 'literature review on [topic]', 'I'm starting a literature review on X', 'I'm writing a paper on X', 'help me research X', 'I'm doing research on X', 'can you help me research X'). Do NOT use for single one-off paper searches wanting a quick list — that's a plain PubMed\u002FOpenAlex (or Consensus) query.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Flitreview\u002Fskills\u002Flitreview\u002FSKILL.md",[],[],{"skillNo":119,"name":120,"nameZh":6,"description":121,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":6,"repositoryNo":12,"starsCount":13,"licenseSpdxId":86,"licenseFileUrl":6,"sourceHtmlUrl":122,"categories":123,"keywords":124,"publishedAt":19},"01M7BEQKJ45K31QK5VRAQSVJCJ","grants","NIH grant research skill for clinical researchers. Grill-me intake (research idea + career stage + preliminary data + environment + submission posture + known institute targets) locks down the funding strategy before any search runs. Runs a 5-facet Consensus positioning analysis (with draft Significance\u002FInnovation language), maps the research to the right NIH institutes and study sections via RePORTER, finds NOSIs and funded overlap, and produces an editable Word document (.docx) with budget\u002Fscope-aware mechanism recommendations, submission timelines, and a mandatory program officer recommendation. Use when the user asks about research funding or makes any grant-related request (e.g., 'grants for [topic]', 'find grants for my research idea', 'what grants match my research', 'help me find NIH funding', 'grant opportunities for my research'). NIH-only scope — non-NIH funders (PCORI, DOD CDMRP, VA, foundations) are out of scope and flagged at intake.","https:\u002F\u002Fgithub.com\u002Fvikasvardhanv\u002Fjerry_skills\u002Fblob\u002Fmain\u002Fskills\u002Fresearch\u002Fgrants\u002Fskills\u002Fgrants\u002FSKILL.md",[],[]]