Category: Cron EN

  • A Digital Noah’s Ark: How UrBackup and TrueNAS Protect Your Data

    A Digital Noah’s Ark: How UrBackup and TrueNAS Protect Your Data

    In today’s digital world, our lives—both personal and professional—are recorded as data. From family photos to crucial company databases, losing this information can be catastrophic. Despite this, many individuals and businesses still treat backups as an afterthought. Here is a complete guide to building a powerful, automated, and secure backup system using free tools: UrBackup, TrueNAS Scale, and Tailscale.

    Why You Need a Plan B: The Importance of Backups

    Imagine one morning your laptop’s hard drive refuses to work. Or the server that runs your business falls victim to a ransomware attack, and all your files are encrypted. These aren’t scenarios from science-fiction films but everyday reality. Hardware failure, human error, malicious software, or even theft—the threats are numerous.

    A backup is your insurance policy. It’s the only way to quickly and painlessly recover valuable data in the event of a disaster, minimising downtime and financial loss. Without it, rebuilding lost information is often impossible or astronomically expensive.

    The Golden Rule: The 3-2-1 Strategy

    In the world of data security, there is a simple but incredibly effective principle known as the 3-2-1 strategy. It states that you should have:

    • THREE copies of your data (the original and two backups).
    • On TWO different storage media (e.g., a disk in your computer and a disk in a NAS server).
    • ONE copy in a different location (off-site), in case of fire, flood, or theft at your main location.

    Having three copies of your data drastically reduces the risk of losing them all simultaneously. If one drive fails, you have a second. If the entire office is destroyed, you have a copy in the cloud or at home.

    A Common Misconception: Why RAID is NOT a Backup

    Many NAS server users mistakenly believe that a RAID configuration absolves them of the responsibility to make backups. This is a dangerous error.

    RAID (Redundant Array of Independent Disks) is a technology that provides redundancy and high availability, not data security. It protects against the physical failure of a hard drive. Depending on the configuration (e.g., RAID 1, RAID 5, RAID 6, or their RAID-Z equivalents in TrueNAS), the array can survive the failure of one or even two drives at the same time, allowing them to be replaced without data loss or system downtime.

    However, RAID will not protect you from:

    • Human error: Accidentally deleting a file is instantly replicated across all drives in the array.
    • Ransomware attack: Encrypted files are immediately synchronised across all drives.
    • Power failure or RAID controller failure: This can lead to the corruption of the entire array.
    • Theft or natural disaster: Losing the entire device means losing all the data.

    Remember: Redundancy protects against hardware failure; a backup protects against data loss.

    image 135

    Your Backup Hub: UrBackup on TrueNAS Scale

    Creating a robust backup system doesn’t have to involve expensive subscriptions. An ideal solution is to combine the TrueNAS Scale operating system with the UrBackup application.

    • TrueNAS Scale: A powerful, free operating system for building NAS servers. It is based on Linux and offers advanced features such as the ZFS file system and support for containerised applications.
    • UrBackup: An open-source, client-server software for creating backups. It is extremely efficient and flexible, allowing for the backup of both individual files and entire disk images.

    The TrueNAS Protective Shield: ZFS Snapshots

    One of the most powerful features of TrueNAS, resulting from its use of the ZFS file system, is snapshots. A snapshot is an instantly created, read-only image of the entire file system at a specific moment. It works like freezing your data in time.

    Why is this so important in the context of ransomware?

    When ransomware attacks and encrypts files on a network share, these changes affect the “live” version of the data. However, previously taken snapshots remain untouched and unchanged because they are inherently read-only. In the event of an attack, you can restore the entire dataset to its pre-infection state in seconds, completely nullifying the effects of the attack.

    You can configure TrueNAS to automatically create snapshots (e.g., every hour) and retain them for a specified period. This creates an additional, incredibly powerful layer of protection that perfectly complements the backups performed by UrBackup.

    Advantages and Disadvantages of the Solution

    Advantages:

    • Full control and privacy: Your data is stored on your own hardware.
    • No licence fees: The software is completely free.
    • Exceptional efficiency: Incremental backups save space and time.
    • Flexibility: Supports Windows, macOS, Linux, physical servers, and VPS.
    • Disk image backups: Ability to perform a “bare-metal restore” of an entire system.

    Disadvantages:

    • Requires your own hardware: You need to have a NAS server.
    • Initial configuration: Requires some technical knowledge.
    • Full responsibility: The user is responsible for the security and operation of the server.

    Step-by-Step: Installation and Configuration

    1. Installing UrBackup on TrueNAS Scale

    1. Log in to the TrueNAS web interface.
    2. Navigate to the Apps section.
    3. Search for the UrBackup application and click Install.
    4. In the most important configuration step, you must specify the path where backups will be stored (e.g., /mnt/YourPool/backups).
    5. After the installation is complete, start the application and go to its web interface.

    2. Basic Server Configuration

    In the UrBackup interface, go to Settings. The most important initial options are:

    • Path to backup storage: This should already be set during installation.
    • Backup intervals: Set how often incremental backups (e.g., every few hours) and full backups (e.g., every few weeks) should be performed.
    • Email settings: Configure email notifications to receive reports on the status of your backups.

    3. Installing the Client on Computers

    The process of adding a computer to the backup system consists of two stages: registering it on the server and installing the software on the client machine.

    a) Adding a new client on the server:

    1. In the UrBackup interface, go to the Status tab.
    2. Click the blue + Add new client button.
    3. Select the option Add new internet/active client. This is recommended as it works both on the local network and over the internet (e.g., via Tailscale).
    4. Enter a unique name for the new client (e.g., “Annas-Laptop” or “Web-Server”) and click Add client.

    b) Installing the software on the client machine:

    1. After adding the client on the server, while still on the Status tab, you will see buttons to Download client for Windows and Download client for Linux.
    2. Click the appropriate button and select the name of the client you just added from the drop-down list.
    3. Download the prepared installation file (.exe or .sh). It is already fully configured to connect to your server.
    4. Run the installer on the client computer and follow the instructions.

    After a few minutes, the new client should connect to the server and appear on the list with an “Online” status, ready for its first backup.

    Security Above All: Tailscale Enters the Scene

    How can you securely back up computers located outside your local network? The ideal solution is Tailscale. It creates a secure, private network (a mesh VPN) between all your devices, regardless of their location.

    Why use Tailscale with UrBackup?

    • Simplicity: Installation and configuration take minutes.
    • “Zero Trust” Security: Every connection is end-to-end encrypted.
    • Stable IP Addresses: Each device receives a static IP address from the 100.x.x.x range, which does not change even when the device moves to a different physical location.

    What to do if the IP address changes?

    If for some reason you need to change the IP address of the UrBackup server (e.g., after switching from another VPN to Tailscale), the procedure is simple:

    1. Update the address on the UrBackup server: In Settings -> Internet/Active Clients, enter the new, correct server address (e.g., urbackup://100.x.x.x).
    2. Download the updated installer: On the Status tab, click Download client, select the offline client from the list, and download a new installation script for it.
    3. Run the installer on the client: Running the new installer will automatically update the configuration on the client machine.

    Managing and Monitoring Backups

    The UrBackup interface provides all the necessary tools to supervise the system.

    • Status: The main dashboard showing a list of all clients, their online/offline status, and the status of their last backup.
    • Activities: A live view of currently running operations, such as file indexing or data transfer.
    • Backups: A list of all completed backups for each client, with the ability to browse and restore files.
    • Logs: A detailed record of all events, errors, and warnings—an invaluable tool for diagnosing problems.
    • Statistics: Charts and tables showing disk space usage by individual clients over time.

    Backing Up Databases: Do It Right!

    Never back up a database by simply copying its files from the disk while the service is running! This risks creating an inconsistent copy that will be useless. The correct method is to perform a “dump” using tools like mysqldump or mariadb-dump.

    Method 1: All Databases to a Single File

    A simple approach, ideal for small environments.

    Command: mysqldump –all-databases -u [user] -p[password] > /path/to/backup/all_databases.sql

    Method 2: Each Database to a Separate File (Recommended)

    A more flexible solution. The script below will automatically save each database to a separate, compressed file. It should be run periodically (e.g., via cron) just before the scheduled backup by UrBackup.

    #!/bin/bash
    
    # Configuration
    BACKUP_DIR="/var/backups/mysql"
    DB_USER="root"
    DB_PASS="YourSuperSecretPassword"
    
    # Check if user and password are provided
    if [ -z "$DB_USER" ] || [ -z "$DB_PASS" ]; then
        echo "Error: DB_USER or DB_PASS variables are not set in the script."
        exit 1
    fi
    
    # Create backup directory if it doesn't exist
    mkdir -p "$BACKUP_DIR"
    
    # Get a list of all databases, excluding system databases
    DATABASES=$(mysql -u "$DB_USER" -p"$DB_PASS" -e "SHOW DATABASES;" | tr -d " " | grep -vE "(Database|information_schema|performance_schema|mysql|sys)")
    
    # Loop through each database
    for db in $DATABASES; do
        echo "Dumping database: $db"
        # Perform the dump and compress on the fly
        mysqldump -u "$DB_USER" -p"$DB_PASS" --databases "$db" | gzip > "$BACKUP_DIR/$db-$(date +%Y-%m-%d).sql.gz"
        if [ $? -eq 0 ]; then
            echo "Dump of database $db completed successfully."
        else
            echo "Error during dump of database $db."
        fi
    done
    
    # Optional: Remove old backups (older than 7 days)
    find "$BACKUP_DIR" -type f -name "*.sql.gz" -mtime +7 -exec rm {} \;
    
    echo "Backup process for all databases has finished."
    

    Your Digital Fortress

    Having a solid, automated backup strategy is not a luxury but an absolute necessity. Combining the power of TrueNAS Scale with its ZFS snapshots, the flexibility of UrBackup, and the security of Tailscale allows you to build a multi-layered, enterprise-class defence system at zero software cost.

    It is an investment of time that provides priceless peace of mind. Remember, however, that no system is entirely maintenance-free. Regularly monitoring logs, checking email reports, and, most importantly, periodically performing test restores of your files are the final, crucial elements that turn a good backup system into an impregnable fortress protecting your most valuable asset—your data.

  • Your Server is Secure: A Guide to Permanently Blocking Attacks

    Your Server is Secure: A Guide to Permanently Blocking Attacks

    A Permanent IP Blacklist with Fail2ban, UFW, and Ipset

    Introduction: Beyond Temporary Protection

    In the digital world, where server attacks are a daily occurrence, merely reacting is not enough. Although tools like Fail2ban provide a basic line of defence, their temporary blocks leave a loophole—persistent attackers can return and try again after the ban expires. This article provides a detailed guide to building a fully automated, two-layer system that turns ephemeral bans into permanent, global blocks. The combination of Fail2ban, UFW, and the powerful Ipset tool creates a mechanism that permanently protects your server from known repeat offenders.

    Layer One: Reaction with Fail2ban

    At the start of every attack is Fail2ban. This daemon monitors log files (e.g., sshd.log, apache.log) for patterns indicating break-in attempts, such as multiple failed login attempts. When it detects such activity, it immediately blocks the attacker’s IP address by adding it to the firewall rules for a defined period (e.g., 10 minutes, 30 days). This is an effective but short-term response.

    Layer Two: Persistence with UFW and Ipset

    For a ban to become permanent, we need a more robust, centralised method of managing IP addresses. This is where UFW and Ipset come in.

    What is Ipset?

    Ipset is a Linux kernel extension that allows you to manage sets of IP addresses, networks, or ports. It is a much more efficient solution than adding thousands of individual rules to a firewall. Instead, the firewall can refer to an entire set with a single rule.

    Ipset Installation and Configuration

    The first step is to install Ipset on your system. We use standard package managers for this.

    sudo apt update
    sudo apt install ipset

    Next, we create two sets: blacklist for IPv4 addresses and blacklist_v6 for IPv6.

    sudo ipset create blacklist hash:ip hashsize 4096
    sudo ipset create blacklist_v6 hash:net family inet6 hashsize 4096

    The hashsize parameter determines the maximum number of entries, which is crucial for performance.

    Integrating Ipset with the UFW Firewall

    For UFW to start using our sets, we must add the appropriate commands to its rules. We edit the UFW configuration files, adding rules that block traffic originating from addresses contained in our Ipset sets. For IPv4, we edit /etc/ufw/before.rules:

    sudo nano /etc/ufw/before.rules

    Immediately after *filter and :ufw-before-input [0:0], add:

    # Rules for the permanent blacklist (ipset)
    # Block any incoming traffic from IP addresses in the ‘blacklist’ set (IPv4)
    -A ufw-before-input -m set –match-set blacklist src -j DROP

    For IPv6, we edit /etc/ufw/before6.rules:

    sudo nano /etc/ufw/before6.rules

    Immediately after *filter and :ufw6-before-input [0:0], add:

    # Rules for the permanent blacklist (ipset) IPv6
    # Block any incoming traffic from IP addresses in the ‘blacklist_v6’ set
    -A ufw6-before-input -m set –match-set blacklist_v6 src -j DROP

    After adding the rules, we reload UFW for them to take effect:

    sudo ufw reload

    Script for Automatic Blacklist Updates

    The core of the system is a script that acts as a bridge between Fail2ban and Ipset. Its job is to collect banned addresses, ensure they are unique, and synchronise them with the Ipset sets.

    Create the script file:

    sudo nano /usr/local/bin/update-blacklist.sh

    Below is the content of the script. It works in several steps:

    1. Creates a temporary, unique list of IP addresses from Fail2ban logs and the existing blacklist.
    2. Creates temporary Ipset sets.
    3. Reads addresses from the unique list and adds them to the appropriate temporary sets (distinguishing between IPv4 and IPv6).
    4. Atomically swaps the old Ipset sets with the new, temporary ones, minimising the risk of protection gaps.
    5. Destroys the old, temporary sets.
    6. Returns a summary of the number of blocked addresses.

    #!/bin/bash

    BLACKLIST_FILE=”/etc/fail2ban/blacklist.local”
    IPSET_NAME_V4=”blacklist”
    IPSET_NAME_V6=”blacklist_v6″

    touch “$BLACKLIST_FILE”

    # Create a unique list of banned IPs from the log and the existing blacklist file
    (grep ‘Ban’ /var/log/fail2ban.log | awk ‘{print $(NF)}’ && cat “$BLACKLIST_FILE”) | sort -u > “$BLACKLIST_FILE.tmp”
    mv “$BLACKLIST_FILE.tmp” “$BLACKLIST_FILE”

    # Create temporary ipsets
    sudo ipset create “${IPSET_NAME_V4}_tmp” hash:ip hashsize 4096 –exist
    sudo ipset create “${IPSET_NAME_V6}_tmp” hash:net family inet6 hashsize 4096 –exist

    # Add IPs to the temporary sets
    while IFS= read -r ip; do
        if [[ “$ip” == *”:”* ]]; then
            sudo ipset add “${IPSET_NAME_V6}_tmp” “$ip”
        else
            sudo ipset add “${IPSET_NAME_V4}_tmp” “$ip”
        fi
    done < “$BLACKLIST_FILE”

    # Atomically swap the temporary sets with the active ones
    sudo ipset swap “${IPSET_NAME_V4}_tmp” “$IPSET_NAME_V4”
    sudo ipset swap “${IPSET_NAME_V6}_tmp” “$IPSET_NAME_V6”

    # Destroy the temporary sets
    sudo ipset destroy “${IPSET_NAME_V4}_tmp”
    sudo ipset destroy “${IPSET_NAME_V6}_tmp”

    # Count the number of entries
    COUNT_V4=$(sudo ipset list “$IPSET_NAME_V4” | wc -l)
    COUNT_V6=$(sudo ipset list “$IPSET_NAME_V6” | wc -l)

    # Subtract header lines from count
    let COUNT_V4=$COUNT_V4-7
    let COUNT_V6=$COUNT_V6-7

    # Ensure count is not negative
    [ $COUNT_V4 -lt 0 ] && COUNT_V4=0
    [ $COUNT_V6 -lt 0 ] && COUNT_V6=0

    echo “Blacklist and ipset updated. Blocked IPv4: $COUNT_V4, Blocked IPv6: $COUNT_V6”
    exit 0

    After creating the script, give it execute permissions:

    sudo chmod +x /usr/local/bin/update-blacklist.sh

    Automation and Persistence After a Reboot

    To run the script without intervention, we use a cron schedule. Open the crontab editor for the root user and add a rule to run the script every hour:

    sudo crontab -e

    Add this line:

    0 * * * * /usr/local/bin/update-blacklist.sh

    Or to run it once a day at 6 a.m.:

    0 6 * * * /usr/local/bin/update-blacklist.sh

    The final, crucial step is to ensure the Ipset sets survive a reboot, as they are stored in RAM by default. We create a systemd service that will save their state before the server shuts down and load it again on startup.

    sudo nano /etc/systemd/system/ipset-persistent.service
    “`ini
    [Unit]
    Description=Saves and restores ipset sets on boot/shutdown
    Before=network-pre.target
    ConditionFileNotEmpty=/etc/ipset.rules

    [Service]
    Type=oneshot
    RemainAfterExit=yes
    ExecStart=/bin/bash -c “/sbin/ipset create blacklist hash:ip –exist; /sbin/ipset create blacklist_v6 hash:net family inet6 –exist; /sbin/ipset restore -f /etc/ipset.rules”
    ExecStop=/sbin/ipset save -f /etc/ipset.rules

    [Install]
    WantedBy=multi-user.target

    Finally, enable and start the service:

    sudo systemctl daemon-reload
    sudo systemctl enable –now ipset-persistent.service

    How Does It Work in Practice?

    The entire system is an automated chain of events that works in the background to protect your server from attacks. Here is the flow of information and actions:

    1. Attack Response (Fail2ban):
    • Someone tries to break into the server (e.g., by repeatedly entering the wrong password via SSH).
    • Fail2ban, monitoring system logs (/var/log/fail2ban.log), detects this pattern.
    • It immediately adds the attacker’s IP address to a temporary firewall rule, blocking their access for a specified time.
    1. Permanent Banning (Script and Cron):
    • Every hour (as set in cron), the system runs the update-blacklist.sh script.
    • The script reads the Fail2ban logs, finds all addresses that have been banned (lines containing “Ban”), and then compares them with the existing local blacklist (/etc/fail2ban/blacklist.local).
    • It creates a unique list of all banned addresses.
    • It then creates temporary ipset sets (blacklist_tmp and blacklist_v6_tmp) and adds all addresses from the unique list to them.
    • It performs an ipset swap operation, which atomically replaces the old, active sets with the new, updated ones.
    • UFW, thanks to the previously defined rules, immediately starts blocking the new addresses that have appeared in the updated ipset sets.
    1. Persistence After Reboot (systemd Service):
    • Ipset’s operation is volatile—the sets only exist in memory. The ipset-persistent.service solves this problem.
    • Before shutdown/reboot: systemd runs the ExecStop=/sbin/ipset save -f /etc/ipset.rules command. This saves the current state of all ipset sets to a file on the disk.
    • After power-on/reboot: systemd runs the ExecStart command, which restores the sets. It reads all blocked addresses from the /etc/ipset.rules file and automatically recreates the ipset sets in memory.

    Thanks to this, even if the server is rebooted, the IP blacklist remains intact, and protection is active from the first moments after the system starts.

    Summary and Verification

    The system you have built is a fully automated, multi-layered protection mechanism. Attackers are temporarily banned by Fail2ban, and their addresses are automatically added to a permanent blacklist, which is instantly blocked by UFW and Ipset. The systemd service ensures that the blacklist survives server reboots, protecting against repeat offenders permanently. To verify its operation, you can use the following commands:

    sudo ufw status verbose
    sudo ipset list blacklist
    sudo ipset list blacklist_v6
    sudo systemctl status ipset-persistent.service

    How to Create a Reliable IP Whitelist in UFW and Ipset

    Introduction: Why a Whitelist is Crucial

    When configuring advanced firewall rules, especially those that automatically block IP addresses (like in systems with Fail2ban), there is a risk of accidentally blocking yourself or key services. A whitelist is a mechanism that acts like a VIP pass for your firewall—IP addresses on this list will always have access, regardless of other, more restrictive blocking rules.

    This guide will show you, step-by-step, how to create a robust and persistent whitelist using UFW (Uncomplicated Firewall) and ipset. As an example, we will use the IP address 111.222.333.444, which we want to add as trusted.

    Step 1: Create a Dedicated Ipset Set for the Whitelist

    The first step is to create a separate “container” for our trusted IP addresses. Using ipset is much more efficient than adding many individual rules to iptables.

    Open a terminal and enter the following command:

    sudo ipset create whitelist hash:ip

    What did we do?

    • ipset create: The command to create a new set.
    • whitelist: The name of our set. It’s short and unambiguous.
    • hash:ip: The type of set. hash:ip is optimised for storing and very quickly looking up single IPv4 addresses.

    Step 2: Add a Trusted IP Address

    Now that we have the container ready, let’s add our example trusted IP address to it.

    sudo ipset add whitelist 111.222.333.444

    You can repeat this command for every address you want to add to the whitelist. To check the contents of the list, use the command:

    sudo ipset list whitelist

    Step 3: Modify the Firewall – Giving Priority to the Whitelist

    This is the most important step. We need to modify the UFW rules so that connections from addresses on the whitelist are accepted immediately, before the firewall starts processing any blocking rules (including those from the ipset blacklist or Fail2ban).

    Open the before.rules configuration file. This is the file where rules processed before the main UFW rules are located.

    sudo nano /etc/ufw/before.rules

    Go to the beginning of the file and find the *filter section. Just below the :ufw-before-input [0:0] line, add our new snippet. Placing it at the very top ensures it will be processed first.

    *filter
    :ufw-before-input [0:0]
    # Rule for the whitelist (ipset) ALWAYS HAS PRIORITY
    # Accept any traffic from IP addresses in the ‘whitelist’ set
    -A ufw-before-input -m set –match-set whitelist src -j ACCEPT

    • -A ufw-before-input: We add the rule to the ufw-before-input chain.
    • -m set –match-set whitelist src: Condition: if the source (src) IP address matches the whitelist set…
    • -j ACCEPT: Action: “immediately accept (ACCEPT) the packet and stop processing further rules for this packet.”

    Save the file and reload UFW:

    sudo ufw reload

    From this point on, any connection from the address 111.222.333.444 will be accepted immediately.

    Step 4: Ensuring Whitelist Persistence

    Ipset sets are stored in memory and disappear after a server reboot. To make our whitelist persistent, we need to ensure it is automatically loaded every time the system starts. We will use our previously created ipset-persistent.service for this.

    Update the systemd service to “teach” it about the existence of the new whitelist set.

    sudo nano /etc/systemd/system/ipset-persistent.service

    Find the ExecStart line and add the create command for whitelist. If you already have other sets, simply add whitelist to the line. An example of an updated line:

    ExecStart=/bin/bash -c “/sbin/ipset create whitelist hash:ip –exist; /sbin/ipset create blacklist hash:ip –exist; /sbin/ipset create blacklist_v6 hash:net family inet6 –exist; /sbin/ipset restore -f /etc/ipset.rules”

    Reload the systemd configuration:

    sudo systemctl daemon-reload

    Save the current state of all sets to the file. This command will overwrite the old /etc/ipset.rules file with a new version that includes information about your whitelist.

    sudo ipset save > /etc/ipset.rules

    Restart the service to ensure it is running with the new configuration:

    sudo systemctl restart ipset-persistent.service

    Summary

    Congratulations! You have created a solid and reliable whitelist mechanism. With it, you can securely manage your server, confident that trusted IP addresses like 111.222.333.444 will never be accidentally blocked. Remember to only add fully trusted addresses to this list, such as your home or office IP address.

    How to Effectively Block IP Addresses and Subnets on a Linux Server

    Blocking single IP addresses is easy, but what if attackers use multiple addresses from the same network? Manually banning each one is inefficient and time-consuming.

    In this article, you will learn how to use ipset and iptables to effectively block entire subnets, automating the process and saving valuable time.

    Why is Blocking Entire Subnets Better?

    Many attacks, especially brute-force types, are carried out from multiple IP addresses belonging to the same operator or from the same pool of addresses (subnet). Blocking just one of them is like patching a small hole in a large dam—the rest of the traffic can still get through.

    Instead, you can block an entire subnet, for example, 45.148.10.0/24. This notation means you are blocking 256 addresses at once, which is much more effective.

    Script for Automatic Subnet Blocking

    To automate the process, you can use the following bash script. This script is interactive—it asks you to provide the subnet to block, then adds it to an ipset list and saves it to a file, making the block persistent.

    Let’s analyse the script step-by-step:

    #!/bin/bash

    # The name of the ipset list to which subnets will be added
    BLACKLIST_NAME=”blacklist_nets”
    # The file where blocked subnets will be appended
    BLACKLIST_FILE=”/etc/fail2ban/blacklist_net.local”

    # 1. Create the blacklist file if it doesn’t exist
    touch “$BLACKLIST_FILE”

    # 2. Check if the ipset list already exists. If not, create it.
    # Using “hash:net” allows for storing subnets, which is key.
    if ! sudo ipset list $BLACKLIST_NAME >/dev/null 2>&1; then
        sudo ipset create $BLACKLIST_NAME hash:net maxelem 65536
    fi

    # 3. Loop to prompt the user for subnets to block.
    # The loop ends when the user types “exit”.
    while true; do
        read -p “Enter the subnet address to block (e.g., 192.168.1.0/24) or type ‘exit’: ” subnet
        if [ “$subnet” == “exit” ]; then
            break
        elif [[ “$subnet” =~ ^([0-9]{1,3}\.){3}[0-9]{1,3}\/[0-9]{1,2}$ ]]; then
            # Check if the subnet is not already in the file to avoid duplicates
            if ! grep -q “^$subnet$” “$BLACKLIST_FILE”; then
                echo “$subnet” | sudo tee -a “$BLACKLIST_FILE” > /dev/null
                # Add the subnet to the ipset list
                sudo ipset add $BLACKLIST_NAME $subnet
                echo “Subnet $subnet added.”
            else
                echo “Subnet $subnet is already on the list.”
            fi
        else
            # Check if the entered format is correct
            echo “Error: Invalid format. Please provide the address in ‘X.X.X.X/Y’ format.”
        fi
    done

    # 4. Add a rule in iptables that blocks all traffic from addresses on the ipset list.
    # This ensures the rule is added only once.
    if ! sudo iptables -C INPUT -m set –match-set $BLACKLIST_NAME src -j DROP >/dev/null 2>&1; then
        sudo iptables -I INPUT -m set –match-set $BLACKLIST_NAME src -j DROP
    fi

    # 5. Save the iptables rules to survive a reboot.
    # This part checks which tool the system uses.
    if command -v netfilter-persistent &> /dev/null; then
        sudo netfilter-persistent save
    elif command -v service &> /dev/null && service iptables status >/dev/null 2>&1; then
        sudo service iptables save
    fi

    echo “Script finished. The ‘$BLACKLIST_NAME’ list has been updated, and the iptables rules are active.”

    How to Use the Script

    1. Save the script: Save the code above into a file, e.g., block_nets.sh.
    2. Give permissions: Make sure the file has execute permissions: chmod +x block_nets.sh.
    3. Run the script: Execute the script with root privileges: sudo ./block_nets.sh.
    4. Provide subnets: The script will prompt you to enter subnet addresses. Simply type them in the X.X.X.X/Y format and press Enter. When you are finished, type exit.

    Ensuring Persistence After a Server Reboot

    Ipset sets are stored in RAM by default and disappear after a server restart. For the blocked addresses to remain active, you must use a systemd service that will load them at system startup.

    If you already have such a service (e.g., ipset-persistent.service), you must update it to include the new blacklist_nets list.

    1. Edit the service file: Open your service’s configuration file.
      sudo nano /etc/systemd/system/ipset-persistent.service
    2. Update the ExecStart line: Find the ExecStart line and add the create command for the blacklist_nets set. An example updated ExecStart line should look like this (including previous sets):
      ExecStart=/bin/bash -c “/sbin/ipset create whitelist hash:ip –exist; /sbin/ipset create blacklist hash:ip –exist; /sbin/ipset create blacklist_v6 hash:net family inet6 –exist; /sbin/ipset create blacklist_nets hash:net –exist; /sbin/ipset restore -f /etc/ipset.rules”
    3. Reload the systemd configuration:
      sudo systemctl daemon-reload
    4. Save the current state of all sets to the file: This command will overwrite the old /etc/ipset.rules file with a new version that contains information about all your lists, including blacklist_nets.
      sudo ipset save > /etc/ipset.rules
    5. Restart the service:
      sudo systemctl restart ipset-persistent.service

    With this method, you can simply and efficiently manage your server’s security, effectively blocking entire subnets that show suspicious activity, and be sure that these rules will remain active after every reboot.

  • How to Run a CRON Job Every Hour in Linux and CyberPanel

    How to Run a CRON Job Every Hour in Linux and CyberPanel

    There are certain tasks on a computer that we need to perform regularly – for example, performing backups. In Linux, the Cron command is used for such repetitive tasks; it is invaluable for executing scheduled jobs. In this article, we will show you how to configure crontab to run a cron job every hour.

    What is cron?

    Cron is a tool, an application used for scheduling tasks, and running applications and scripts at a specific time in Unix-like operating systems. It allows you to schedule tasks (cyclically running applications or shell scripts) that will automatically run at a specified time and date. These tasks are called cron jobs.

    In Linux and Unix systems, cron is commonly used for maintenance or administrative tasks, such as running backups (with the option to later send them to an FTP server, for example) or sending automated emails. Cron can also be used, for instance, to check for system updates and many other things.

    Cron uses a configuration file called crontab. A crontab is a plain text file that can be edited with any text editor. The system administrator can configure a global crontab file with root permissions, and additionally, each user can have their own settings, limited by their user permissions.

    A cron job is usually executed in the background, and if there is any output, it can be sent to the user via email or saved to a file. Cron is a powerful tool that allows you to automate virtually any task, but it can be difficult for novice users to operate if they are not familiar with the required command syntax.

    What can we use cron for?

    With cron, we can manage virtually any function of a computer or server and run cyclical tasks at a specific time and date. We can use it for example to:

    • Automate repetitive tasks. A cron job can be used to automate tasks at regular intervals, such as running backups or sending cyclical emails, for example, with reminders.
    • Run system tasks on a schedule. A cron job can check for available updates for the operating system or applications, or for example, it can regularly clean the computer of temporary files and unnecessary system logs.
    • Automatically perform system updates, update security, and install new software. This can help to better secure the system and ensure that we always have the latest versions of applications and libraries installed on our computer or server.
    • Improve performance. Thanks to cron, we can configure the execution of tasks that heavily load the computer to run during hours when the computer is least used, for example, at night.

    Overall, cron can significantly streamline the performance of cyclical tasks through their automation.

    Create a cron job in the Linux terminal

    The crontab command is used to create cron jobs. To create a new cron job:

    1. Open a terminal window.
    2. Type the command crontab -e to open the cron configuration file.
    3. Add a new entry to the crontab file, remembering to maintain the correct format, otherwise the task will not run:minute hour day-of-month month day-of-week command-to-executeAn asterisk instead of minutes, hours, or months means that this task will run every hour, minute, or every month. For example, if we want a command or script to run on the hour (i.e., at minute 0) every day of every month, we must type:0 * * * * command-to-execute
    4. Save the crontab file and close it.
    5. Use the command crontab -l to display the list of saved cron jobs to be executed.

    NOTE: The syntax for cron job commands may vary depending on the version of the Linux system. We are basing this on the Ubuntu system. To learn more about the cron application, type man cron in the terminal.

    How to create a cron job in CyberPanel

    If your web server is based on LiteSpeed, you should install the CyberPanel overlay. Creating cron jobs in CyberPanel is much simpler and more pleasant than in a crontab file.

    1. Log in to your CyberPanel Dashboard.
    2. On the left side, click on Websites, then List Websites, select your website and click Manage.
    3. Scroll down and click on Cron Jobs.
    4. To add a new cron job, press ADD CRON. To see a list of existing jobs, click FETCH CURRENT CRON JOBS.
    image 18
    image 20
    image 21
    image 22

    To have a given task run weekly, select Every week from the list. In the example below, cron will run a previously written backup script every week, on Wednesday at 4:16 AM. In the Day of week window, we enter numbers from 0 to 7. 0 or 7 means Sunday, 1 Monday, 2 Tuesday, etc.

    We can also enter the days of the week by name in English: mon, tue, wed, thu, fri, sat, or sun.

    Press Add Cron to save the created task.

    Isn’t configuring cron in CyberPanel more pleasant?