List of Commands to Check, Add, Edit Firewall configuration of SSH in ubuntu
Here is a comprehensive set of commands for managing SSH firewall configurations on Ubuntu, using both UFW and iptables. You can use these commands to check, add, edit, and delete firewall rules for SSH.
sudo ufw status verbose # View current firewall status and rules sudo ufw status # Check if UFW is enabled
sudo ufw allow 22/tcp # Allow SSH (port 22) from any IP sudo ufw allow from x.x.x.x to any port 22 # Allow SSH from specific IP (replace x.x.x.x with IP)
sudo ufw limit 22/tcp # Limit SSH to default rate (e.g., 6 attempts per 30 seconds)
sudo ufw deny 22/tcp # Deny all incoming SSH requests sudo ufw deny from x.x.x.x to any port 22 # Deny SSH from a specific IP
sudo ufw delete allow 22/tcp # Delete the SSH allow rule sudo ufw delete limit 22/tcp # Delete the SSH limit rule
sudo iptables -L -v -n --line-numbers # List all iptables rules with line numbers sudo iptables -L -v -n | grep dpt:22 # Filter for SSH-specific rules
sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT # Allow SSH access from any IP sudo iptables -A INPUT -p tcp -s x.x.x.x --dport 22 -j ACCEPT # Allow SSH from specific IP
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 300 --hitcount 11 -j DROP
sudo iptables -A INPUT -p tcp --dport 22 -j DROP # Block SSH access from all IPs sudo iptables -A INPUT -p tcp -s x.x.x.x --dport 22 -j DROP # Block SSH from a specific IP
sudo iptables -L INPUT -v -n --line-numbers # List rules with line numbers for deletion sudo iptables -D INPUT [line_number] # Delete specific rule by line number
sudo netfilter-persistent save # Save iptables rules for persistence on reboot sudo apt-get install iptables-persistent # Install iptables-persistent if not installed
List of options to change in SSH configuration from Preventing from DDOS attack
To harden your SSH configuration on Ubuntu and help prevent DDoS attacks, you can adjust several settings in the SSH configuration file (/etc/ssh/sshd_config
). Below are options you can modify to improve security against DDoS and brute-force attacks.
sudo nano /etc/ssh/sshd_config
MaxSessions 2
Controls the maximum number of sessions per network connection. Lowering this reduces exposure to excessive simultaneous sessions.
MaxStartups 10:30:60
Port 2222
PermitRootLogin no
AllowUsers your_username
PasswordAuthentication no
ClientAliveInterval 300 ClientAliveCountMax 2
- ClientAliveInterval 300: Sends a null packet every 300 seconds (5 minutes) to keep the connection alive.
- ClientAliveCountMax 2: Disconnects the client after 2 missed responses (10 minutes of inactivity).
sudo ufw limit 22/tcp
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP
sudo systemctl restart sshd
List of options to Preventing from DDOS attack in AWS Security Group
To prevent DDoS attacks on AWS EC2 instances, you can configure your AWS Security Groups with specific rules to control access and reduce exposure. Here are some best-practice options for configuring security groups to enhance protection against DDoS attacks:
Instead of allowing SSH (port 22) from anywhere (0.0.0.0/0), specify only trusted IP addresses or IP ranges.
Inbound Rule:
- Type: SSH
- Protocol: TCP
- Port Range: 22
- Source: <Your IP address or IP range (e.g., 203.0.113.0/24)>
Consider using a custom port for SSH or other critical services. Update your instance configuration accordingly.
Inbound Rule:
- Type: Custom TCP
- Protocol: TCP
- Port Range: 2222 (example)
- Source:
If your web application does not need to be accessible to the public, restrict access to only trusted IPs.
Inbound Rule:
- Type: HTTP or HTTPS
- Protocol: TCP
- Port Range: 80 or 443
- Source:
Example: Only allow HTTP, HTTPS, and SSH from specific sources, and deny all other ports by default.
Security groups don’t natively support rate limiting, but Network ACLs can control traffic flow at the subnet level.
For example, allow limited connections on port 22 by setting "Allow" rules with specific conditions, and a "Deny" rule if hit count exceeds a threshold.
Rate limiting is best configured in combination with AWS WAF or third-party services for detailed control.
AWS WAF provides advanced filtering options to protect against common attacks, including SQL injection and XSS, and allows for IP-based rate limiting.
Enable AWS WAF on CloudFront distributions, ALB, or API Gateway, and configure WAF rules as follows:
AWS Shield Advanced provides dedicated DDoS protection, including always-on detection, automatic traffic monitoring, and attack mitigation.
Shield Advanced works automatically with services like CloudFront, Route 53, and Elastic Load Balancing.
Set up CloudWatch alarms to monitor unusual spikes in metrics like "NetworkIn" or "NetworkPacketsIn" to detect potential DDoS attacks early.
- Use AWS Config to enforce compliance by ensuring Security Groups only have the allowed ports open.
Enable VPC Flow Logs to capture information about the IP traffic going to and from network interfaces in your VPC.
List of Approach to protect SSH session from Preventing from DDOS attack
To protect SSH sessions from DDoS attacks, you can apply several best practices, configurations, and additional tools to safeguard your SSH access. Below is a comprehensive list of approaches for securing SSH against DDoS and brute-force attacks.
# Approaches to Protect SSH Sessions from DDoS Attacks
# 1. Restrict SSH Access to Specific IP Addresses or Ranges
# Limit SSH access to known IPs by configuring firewall rules to only allow connections from trusted IPs or ranges.
# On AWS: Use Security Groups to allow SSH only from specific IPs.
# On Ubuntu: Use UFW or iptables to permit only trusted IPs for SSH access.
# Example (AWS Security Group): Allow SSH from a specific IP
- Type: SSH
- Protocol: TCP
- Port Range: 22
- Source: <Trusted IP or IP Range>
# 2. Use a VPN for SSH Access
# Set up a VPN to restrict SSH access to users connected through the VPN.
# VPNs, like AWS Client VPN or OpenVPN, add an additional layer of security and restrict access to authorized users only.
# 3. Change the Default SSH Port (Obscurity)
# Use a non-standard port for SSH to reduce random DDoS attacks on port 22.
# Update SSH configuration in /etc/ssh/sshd_config:
Port 2222
# Note: Update firewall rules to allow the new SSH port.
# 4. Limit Concurrent and Unauthenticated Connections
# Configure sshd settings to limit the number of concurrent sessions and new connections.
# Edit /etc/ssh/sshd_config to include:
MaxSessions 2 # Limit the number of sessions per connection
MaxStartups 10:30:60 # Controls unauthenticated connections: 10 allowed, drop rate at 30%, and refuse at 60
# 5. Use SSH Key-Based Authentication and Disable Passwords
# Disable password authentication to prevent brute-force attacks and require SSH keys.
# In /etc/ssh/sshd_config:
PasswordAuthentication no # Enforces key-based authentication only
# Make sure all users have SSH keys set up before applying this setting.
# 6. Set Up Fail2ban to Ban IPs after Multiple Failed Login Attempts
# Fail2ban automatically bans IPs with repeated failed login attempts, preventing brute-force attacks.
# Install and configure Fail2ban:
sudo apt update
sudo apt install fail2ban
# Edit Fail2ban config in /etc/fail2ban/jail.local to enable SSH protection:
[sshd]
enabled = true
maxretry = 5
bantime = 600 # Ban IP for 10 minutes after 5 failed attempts
# 7. Enable UFW or iptables Rate Limiting for SSH Connections
# UFW:
sudo ufw limit 22/tcp # Limits SSH to 6 attempts per 30 seconds (default)
# iptables (for custom limits, e.g., 10 attempts in 5 minutes):
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set
sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 300 --hitcount 11 -j DROP
# 8. Implement Two-Factor Authentication (2FA) for SSH
# Use 2FA for additional security, requiring a second authentication factor.
# Install Google Authenticator or another 2FA tool:
sudo apt install libpam-google-authenticator
google-authenticator # Run the setup per user
# Configure SSH to require 2FA in /etc/pam.d/sshd and /etc/ssh/sshd_config.
# 9. Monitor SSH Activity with Logging and CloudWatch Alarms
# Enable SSH logs to monitor failed attempts, and set up alerts for suspicious activity.
# Check /var/log/auth.log on Ubuntu:
sudo tail -f /var/log/auth.log
# On AWS, enable CloudWatch Alarms to notify you of spikes in SSH traffic.
# 10. Enable AWS Shield Advanced for DDoS Protection (for Enterprise-Level Protection)
# AWS Shield Advanced offers dedicated DDoS protection for high-risk applications, including protections for EC2.
# It provides additional support and monitoring for DDoS attacks targeting your instance.
# 11. Enable VPC Flow Logs to Track Suspicious SSH Traffic
# VPC Flow Logs capture IP traffic going to and from your EC2 instance.
# Analyze these logs to detect unusual SSH connection patterns.
# Steps:
# - Go to VPC Console > Flow Logs > Create Flow Log.
# - Enable logs and store in CloudWatch or S3 for review.
# Summary
# - Use IP restrictions, VPNs, and non-standard ports to limit access.
# - Implement SSH session limits, Fail2ban, and rate-limiting to control connection frequency.
# - Use 2FA and key-based authentication for enhanced security.
# - Monitor and log SSH activity to stay proactive in detecting and handling potential threats.
I’m a DevOps/SRE/DevSecOps/Cloud Expert passionate about sharing knowledge and experiences. I am working at Cotocus. I blog tech insights at DevOps School, travel stories at Holiday Landmark, stock market tips at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at I reviewed , and SEO strategies at Wizbrand.
Please find my social handles as below;
Rajesh Kumar Personal Website
Rajesh Kumar at YOUTUBE
Rajesh Kumar at INSTAGRAM
Rajesh Kumar at X
Rajesh Kumar at FACEBOOK
Rajesh Kumar at LINKEDIN
Rajesh Kumar at PINTEREST
Rajesh Kumar at QUORA
Rajesh Kumar at WIZBRAND