🚀 DevOps & SRE Certification Program 📅 Starting: 1st of Every Month 🤝 +91 8409492687 🔍 Contact@DevOpsSchool.com

Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

SSH Tutorials Complete Master Guide

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.

UFW (Uncomplicated Firewall) Commands --

1. Check UFW Status and Rules

sudo ufw status verbose # View current firewall status and rules sudo ufw status # Check if UFW is enabled

2. Allow SSH on Port 22

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)

3. Limit SSH Connections

sudo ufw limit 22/tcp # Limit SSH to default rate (e.g., 6 attempts per 30 seconds)

4. Deny SSH Access

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

5. Delete UFW Rules for SSH

sudo ufw delete allow 22/tcp # Delete the SSH allow rule sudo ufw delete limit 22/tcp # Delete the SSH limit rule

iptables Commands --

1. Check iptables Rules

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

2. Allow SSH on Port 22

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

3. Limit SSH Connections to Prevent Brute Force

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

This limits SSH to 10 attempts per IP per 5 minutes

4. Deny SSH Access

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

5. Delete iptables Rules for SSH

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

6. Save iptables Rules to Make Them Persistent

sudo netfilter-persistent save # Save iptables rules for persistence on reboot sudo apt-get install iptables-persistent # Install iptables-persistent if not installed

view raw README.md hosted with ❤ by GitHub

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.

Open SSH configuration file

sudo nano /etc/ssh/sshd_config

Recommended Options to Harden SSH Configuration

1. Limit the Number of Concurrent Sessions (per connection)

MaxSessions 2

Controls the maximum number of sessions per network connection. Lowering this reduces exposure to excessive simultaneous sessions.

2. Limit Unauthenticated Connection Attempts

MaxStartups 10:30:60

Limits unauthenticated connections:

- Allows up to 10 unauthenticated connections freely.

- Starts dropping connections at a rate of 30%.

- Refuses connections entirely after 60 attempts.

3. Use a Non-Standard Port for SSH

Port 2222

Changing the default SSH port (22) can reduce the likelihood of random attacks.

Note: Remember to allow this port in the firewall (e.g., sudo ufw allow 2222/tcp).

4. Disable Root Login

PermitRootLogin no

Disabling root login reduces the risk of brute-force attacks on the root account.

Instead, use a regular user with sudo privileges.

5. Allow Only Specific Users

AllowUsers your_username

Limits SSH access to specific users. Replace "your_username" with the actual username(s).

This reduces the attack surface by preventing login attempts for other accounts.

6. Disable Password Authentication (Use SSH Keys Only)

PasswordAuthentication no

Enforcing SSH key-based authentication eliminates the risk of password brute-forcing.

7. Set Client Timeout to Automatically Disconnect Idle Sessions

ClientAliveInterval 300 ClientAliveCountMax 2

Closes inactive sessions after a set period, reducing resource strain from idle connections.

- 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).

8. Enable Rate-Limiting with UFW or iptables (Separate from sshd_config)

If using UFW:

sudo ufw limit 22/tcp

Limits repeated connection attempts for SSH (default 6 attempts per 30 seconds).

If using iptables (alternative):

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

This limits connections to 3 per minute from any single IP.

Save Changes and Restart SSH Service

sudo systemctl restart sshd

view raw README.md hosted with ❤ by GitHub

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:

AWS Security Group Configuration Options for DDoS Prevention

1. Restrict SSH Access to Specific IP Addresses

Instead of allowing SSH (port 22) from anywhere (0.0.0.0/0), specify only trusted IP addresses or IP ranges.

This limits access to only authorized users, preventing random connection attempts.

Inbound Rule:

  • Type: SSH
  • Protocol: TCP
  • Port Range: 22
  • Source: <Your IP address or IP range (e.g., 203.0.113.0/24)>

2. Use Non-Standard Ports for Remote Access

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:

Note: Configure the instance's SSH daemon to listen on this new port instead of 22.

3. Limit Web Traffic to HTTP(S) and Only Required IP Ranges (If Needed)

If your web application does not need to be accessible to the public, restrict access to only trusted IPs.

This limits potential DDoS entry points.

Inbound Rule:

  • Type: HTTP or HTTPS
  • Protocol: TCP
  • Port Range: 80 or 443
  • Source:

For publicly accessible websites, use a Web Application Firewall (WAF) to filter traffic.

4. Deny All Unnecessary Ports and Services

Remove or block all open ports that aren’t strictly necessary for your application.

This minimizes exposure and attack surfaces.

Example: Only allow HTTP, HTTPS, and SSH from specific sources, and deny all other ports by default.

5. Rate-Limit Connections with a Network ACL (NACL) at the VPC Level (Optional)

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.

6. Use AWS WAF (Web Application Firewall) for Public Web Applications (Recommended)

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:

- IP Rate Limit: Set custom rate-based rules to limit requests from the same IP.

- Geo-Blocking: Restrict access to specific geographic regions if your app is region-specific.

- SQL Injection and XSS Protection: Use managed rules to protect against web vulnerabilities.

7. Enable AWS Shield Advanced for Enhanced DDoS Protection (Recommended for Enterprise)

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.

It provides detailed attack diagnostics and additional protections for large-scale attacks.

8. Monitor with CloudWatch Alarms and AWS Config

Set up CloudWatch alarms to monitor unusual spikes in metrics like "NetworkIn" or "NetworkPacketsIn" to detect potential DDoS attacks early.

Example:

- Create alarms on metrics for unexpected increases in incoming traffic.

- Use AWS Config to enforce compliance by ensuring Security Groups only have the allowed ports open.

9. Log and Analyze Traffic with VPC Flow Logs

Enable VPC Flow Logs to capture information about the IP traffic going to and from network interfaces in your VPC.

VPC Flow Logs help identify suspicious activity patterns, like sudden spikes from certain IP addresses or unusual traffic to uncommon ports.

Steps:

- Go to VPC Console > Flow Logs > Create Flow Log.

- Enable logs and store them in CloudWatch Logs or an S3 bucket for analysis.

Summary

- Restrict access to known IPs for SSH and critical services.

- Use custom ports and limit exposure by removing unnecessary open ports.

- Use AWS WAF, Shield Advanced, CloudWatch, and VPC Flow Logs for comprehensive monitoring and protection.

view raw README.md hosted with ❤ by GitHub

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.
Subscribe
Notify of
guest


0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.

0
Would love your thoughts, please comment.x
()
x