English version: README.md | Русская версия: README_ru.md
A robust, configurable MikroTik RouterOS script that automatically detects and blocks suspicious network connections based on asymmetric packet patterns. Perfect for mitigating port scans, TLS handshake timeouts, and other network anomalies.
⚠️ EXPERIMENTAL WARNING
This script is currently in experimental status. While it has been tested and works as intended, it should be deployed with caution:
- Test in a non-production environment first
- Monitor logs closely after initial deployment
- Review blocked IPs regularly to ensure no false positives
- Keep allowlist updated with your trusted IPs and services
- Be prepared to adjust thresholds based on your network's behavior
- Backup your configuration before implementing
Use at your own risk. The authors are not responsible for any network disruptions or unintended blocking.
- 🛡️ MikroTik Connection Anomaly Detection & Blocking Script
- 🎯 Smart Detection: Identifies connections with asymmetric packet counts (high outgoing, low/no incoming)
- ⚙️ Highly Configurable: All parameters adjustable via global variables
- 🚫 Auto-Blocking: Automatically adds suspicious IPs to firewall address-list
- ✅ Allowlist Support: Protect trusted IPs from being blocked
- 🔒 Local IP Protection: Prevents blocking your own router addresses
- 📊 Multi-Protocol: Supports TCP, UDP, and other protocols
- 🎚️ Granular Logging: Configurable log levels (debug, info, warning, error)
- ⚡ Performance Optimized: Rate limiting and efficient connection processing
- 🔄 Self-Healing: Automatic recovery from errors with detailed logging
- 📝 Detailed Comments: Track blocking reasons with source information
The script monitors active connections and identifies suspicious patterns:
- Connection Analysis: Scans firewall connections for asymmetric packet counts
- Pattern Detection: Flags connections with >3 outgoing packets but ≤2 incoming packets
- Validation: Checks against allowlists, local addresses, and monitored ports
- Auto-Block: Adds offending IPs to address-list with configurable timeout
- Cleanup: Optionally removes TCP connections to free resources
Common Use Cases:
- Detecting failed TLS handshakes (port 443 timeouts)
- Identifying port scanning attempts
- Blocking DoS/DDoS sources
- Mitigating connection flood attacks
- MikroTik RouterOS: Version 7.20 or higher
- Permissions: Admin or script policy access
- Resources: Minimal CPU/memory overhead (configurable)
- Open your MikroTik router interface
- Navigate to System → Scripts
- Click Add New (+)
- Set the following:
- Name:
connection-monitor - Policy:
read, write, policy, test - Source: Paste the script code
- Name:
- Click OK
# Connect to your router
ssh [email protected]
# Create the script (paste the entire script, then Ctrl+D)
/system script add name=connection-monitor policy=read,write,policy,test source={
# Paste script here
}
# Run the script
/system script run connection-monitorTo run the script automatically on router startup:
/system scheduler add \
name=connection-monitor-startup \
on-event="/system script run connection-monitor" \
start-time=startup \
interval=0
All configuration is done via global variables at the top of the script:
:global cfgEnabled true # Enable/disable script
:global cfgMonitoredPorts {443; 80; 8443} # Ports to monitor
:global cfgProtocols {"tcp"; "udp"} # Protocols to check
:global cfgMinOrigPackets 3 # Min outgoing packets to trigger
:global cfgMaxReplPackets 2 # Max incoming packets allowed
:global cfgBlockTimeout "1d" # How long to block IPs (1d, 12h, 30m)
:global cfgLoopDelay 2 # Seconds between checks
:global cfgMaxConnPerCycle 50 # Max connections per cycle
:global cfgAddressList "tls_block" # Name of blocking address-list
:global cfgAllowlistName "allowlist" # Name of allowlist
:global cfgLogLevel "warning" # Log level: debug/info/warning/error
:global cfgRemoveTCPConn true # Remove blocked TCP connections
:global cfgCheckLocalAddr true # Skip local router IPs
Example 1: Monitor HTTPS and SSH
:global cfgMonitoredPorts {443; 22; 8443}
:global cfgBlockTimeout "2d"
Example 2: Aggressive Blocking
:global cfgMinOrigPackets 2
:global cfgMaxReplPackets 1
:global cfgBlockTimeout "7d"
Example 3: Debug Mode
:global cfgLogLevel "debug"
:global cfgLoopDelay 5
/system script run connection-monitor
# Find the script process
/system script job print
# Kill the job (replace X with job number)
/system script job remove X
Prevent trusted IPs from being blocked:
/ip firewall address-list add list=allowlist address=8.8.8.8 comment="Google DNS"
/ip firewall address-list add list=allowlist address=1.1.1.1 comment="Cloudflare DNS"
/ip firewall address-list add list=allowlist address=192.168.1.100 comment="Trusted Server"
/ip firewall address-list print where list=tls_block
/ip firewall address-list remove [find where address=1.2.3.4 and list=tls_block]
/ip firewall address-list remove [find where list=tls_block]
The script only adds IPs to an address-list. You need firewall rules to actually block traffic:
Block in Forward Chain (for router traffic):
/ip firewall filter add \
chain=forward \
action=drop \
src-address-list=tls_block \
comment="Block detected anomalous connections" \
place-before=0
Block in Input Chain (for router itself):
/ip firewall filter add \
chain=input \
action=drop \
src-address-list=tls_block \
comment="Block attacks on router" \
place-before=0
Log Before Dropping (optional):
/ip firewall filter add \
chain=forward \
action=log \
src-address-list=tls_block \
log-prefix="BLOCKED-ANOMALY" \
place-before=0
/ip firewall filter add \
chain=forward \
action=drop \
src-address-list=tls_block \
place-before=1
/log print where message~"ConnectionMonitor"
/log print follow where message~"ConnectionMonitor"
warning: [ConnectionMonitor] Detected asymmetric tcp connection: 192.168.1.50:54321 -> 203.0.113.45:443 (orig>3, repl<=2)
info: [ConnectionMonitor] Added 203.0.113.45 to tls_block (timeout: 1d)
info: [ConnectionMonitor] Processed 5 suspicious connections
Check how many IPs are currently blocked:
:put [/ip firewall address-list print count-only where list=tls_block]
Check if script exists:
/system script print
Check for syntax errors:
/system script run connection-monitor
# Look for error messages
Verify scheduler (if using auto-start):
/system scheduler print
Check log level:
:global cfgLogLevel "debug"
# Then check logs for "Skipping" messages
Verify monitored ports:
# Make sure traffic is going to ports in cfgMonitoredPorts
/ip firewall connection print where dst-port=443
Check thresholds:
# Lower thresholds for more sensitive detection
:global cfgMinOrigPackets 2
:global cfgMaxReplPackets 1
Increase loop delay:
:global cfgLoopDelay 5
Reduce max connections:
:global cfgMaxConnPerCycle 20
Change log level:
:global cfgLogLevel "error"
Add to allowlist:
/ip firewall address-list add list=allowlist address=X.X.X.X
Adjust thresholds:
:global cfgMinOrigPackets 5
:global cfgMaxReplPackets 3
Increase block timeout:
:global cfgBlockTimeout "1h" # Shorter timeout for testing
| Connections | Loop Delay | CPU Impact |
|---|---|---|
| < 1000 | 2s | Minimal (~1-2%) |
| 1000-5000 | 3s | Low (~3-5%) |
| 5000-10000 | 5s | Moderate (~5-10%) |
| > 10000 | 10s | Consider optimization |
- Adjust Loop Delay: Increase
cfgLoopDelayfor busy routers - Limit Port Monitoring: Only monitor critical ports
- Reduce Max Connections: Set
cfgMaxConnPerCycleto 20-30 - Use Warning/Error Logs: Avoid debug logging in production
- Clean Old Blocks: Shorter
cfgBlockTimeoutreduces address-list size
- Base Script: ~10-20 KB
- Per Blocked IP: ~200 bytes
- 1000 Blocked IPs: ~200 KB additional
Contributions are welcome! Please feel free to submit a Pull Request.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Test on MikroTik RouterOS 7.20+
- Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Please include:
- RouterOS version
- Script configuration (sanitized)
- Log output
- Steps to reproduce
This project is licensed under the MIT License - see the LICENSE file for details.
- MikroTik for RouterOS scripting capabilities
- Community members who tested and provided feedback
- Original inspiration from TLS timeout detection scripts
- Issues: GitHub Issues
- MikroTik Forum: forum.mikrotik.com
⭐ If this script helps secure your network, please star this repository!
Made with ❤️ for the MikroTik community