Tag: Encryption

  • Synchronous vs Asynchronous Encryption in Simple Words

    Synchronous vs Asynchronous Encryption in Simple Words

    synchronous vs asynchronous encryption

    Encryption keeps our data safe. In simple terms, there are two big families: methods where both sides share the same secret, and methods where each side has different keys. People often call these synchronous and asynchronous encryption, but the more common names are symmetric and asymmetric encryption. This guide explains both in plain English, with short code examples and practical tips.

    Synchronous vs Asynchronous Encryption Explained

    When people say synchronous encryption in everyday security talk, they usually mean symmetric encryption: the sender and the receiver use the same secret key to lock and unlock data. Think of it like a safe with one combination that both of you know. This is the powerhouse used to protect most data in motion and at rest because it is fast and efficient.

    Asynchronous encryption is the common term for asymmetric encryption: there are two different keys, a public key and a private key. The public key is like a lock you can share with the world, and the private key is the only key that opens it. Anyone can lock a message for you using your public key, but only you can open it with your private key.

    Why does the naming cause confusion? In programming, synchronous vs asynchronous usually describes timing and waiting, not cryptography. But in security writing, some folks casually use synchronous to mean “same key on both sides” and asynchronous to mean “different keys on each side.” In this article, synchronous = symmetric (shared key) and asynchronous = asymmetric (public/private key).

    Real-world use mixes both. Your Wi‑Fi with WPA2 or WPA3 mainly uses symmetric encryption (like AES) to keep traffic fast and secure. When you visit an HTTPS site, your browser first uses asymmetric crypto to safely agree on a shared secret, and then switches to symmetric crypto for the actual data transfer. This combo is called hybrid encryption and is the standard on the internet.

    Speed is the big practical difference. Symmetric encryption is very fast and good for large files or streaming. Asymmetric encryption is slower and better for small things like exchanging keys, verifying identity, and digital signatures. That’s why protocols rarely encrypt entire videos with RSA; they use RSA or Elliptic Curve to set up a safe session, then use AES or ChaCha20 for the heavy lifting.

    A good mental model: asymmetric is for trust and handshake, symmetric is for performance. Use asymmetric to agree on secrets without meeting in person, and symmetric to actually protect the bulk of your data once you share a key.

    Public Key vs Shared Key: What These Terms Mean

    A shared key (symmetric key) is a single secret that both sender and receiver know. If you both keep it safe, you can encrypt and decrypt messages quickly. The tough part is how to share that key securely in the first place. If someone steals it, they can read and forge messages.

    A public key system (asymmetric) gives you a key pair. Your public key is safe to share; your private key must stay secret. If I encrypt with your public key, only your private key can decrypt. If I verify your digital signature, I use your public key to check that only your private key could have created it.

    Key exchange is the art of creating a shared key without anyone else learning it. Modern connections often use Diffie-Hellman or Elliptic Curve Diffie-Hellman so both sides derive the same secret over an insecure network. Certificates and certificate authorities help you trust that the public key you see actually belongs to the website or service you intended, blocking simple man-in-the-middle attacks.

    Digital signatures solve a different but related problem: authenticity and integrity. With signatures, you don’t hide the message; you prove who sent it and that it wasn’t changed. The sender signs with their private key; anyone can verify with their public key. That’s how software updates and package managers prove that files are legit.

    Algorithms you will hear a lot: AES and ChaCha20 for symmetric encryption; RSA and Elliptic Curve (like Curve25519, P-256) for asymmetric crypto; SHA-256 and SHA-3 for hashing; GCM and Poly1305 for authenticated encryption. Key sizes matter too: AES-256 is very strong; for RSA, 2048-bit is the common minimum today, with 3072 or 4096 used in higher-assurance systems; for elliptic curve, 256-bit curves like P-256 or X25519 give strong security with small keys.

    Common myths: asymmetric isn’t “better” than symmetric; it does different jobs. Another myth is that bigger keys always mean better security for everything—bigger RSA keys can be slower and increase message size, and not all algorithms scale the same way. Pick modern, vetted algorithms and follow best practices instead of chasing extreme sizes.

    Plain Examples and Simple Code Snippets for Beginners

    Let’s start with a simple symmetric example using AES-GCM in Python. AES-GCM is fast and provides authenticated encryption, meaning it both hides your data and detects tampering. This is great for most app use cases like tokens, small files, or API secrets.

    # Python 3.x
    # pip install cryptography
    from cryptography.hazmat.primitives.ciphers.aead import AESGCM
    import os
    
    key = AESGCM.generate_key(bit_length=256)  # 32 bytes
    aesgcm = AESGCM(key)
    nonce = os.urandom(12)  # 12-byte nonce for GCM
    plaintext = b"hello symmetric world"
    ciphertext = aesgcm.encrypt(nonce, plaintext, associated_data=None)
    
    # Decrypt
    decrypted = AESGCM(key).decrypt(nonce, ciphertext, associated_data=None)
    print(decrypted)  # b'hello symmetric world'

    Here’s the same idea in Node.js using AES-256-GCM. Note how we keep the key and IV (nonce) safe and store the auth tag alongside the ciphertext. You must never reuse the same nonce with the same key in GCM.

    // Node.js
    const crypto = require('crypto');
    
    const key = crypto.randomBytes(32);     // 256-bit key
    const iv = crypto.randomBytes(12);      // 96-bit IV for GCM
    const plaintext = Buffer.from('hello symmetric world');
    
    const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);
    const encrypted = Buffer.concat([cipher.update(plaintext), cipher.final()]);
    const tag = cipher.getAuthTag();
    
    // Decrypt
    const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
    decipher.setAuthTag(tag);
    const decrypted = Buffer.concat([decipher.update(encrypted), decipher.final()]);
    console.log(decrypted.toString()); // hello symmetric world

    Now an asymmetric example in Python with RSA-OAEP. We generate a key pair, encrypt with the public key, and decrypt with the private key. In real apps, you’d store keys safely and avoid re-generating them every time.

    # Python 3.x
    # pip install cryptography
    from cryptography.hazmat.primitives.asymmetric import rsa, padding
    from cryptography.hazmat.primitives import hashes
    
    private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)
    public_key = private_key.public_key()
    
    message = b"hello asymmetric world"
    ciphertext = public_key.encrypt(
        message,
        padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                     algorithm=hashes.SHA256(),
                     label=None)
    )
    
    plaintext = private_key.decrypt(
        ciphertext,
        padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()),
                     algorithm=hashes.SHA256(),
                     label=None)
    )
    print(plaintext)  # b'hello asymmetric world'

    And the same idea in Node.js with RSA-OAEP. Again, asymmetric crypto is slower and better used for small messages like keys or short secrets.

    // Node.js
    const { generateKeyPairSync, publicEncrypt, privateDecrypt } = require('crypto');
    
    const { publicKey, privateKey } = generateKeyPairSync('rsa', { modulusLength: 2048 });
    
    const msg = Buffer.from('hello asymmetric world');
    const enc = publicEncrypt({ key: publicKey, oaepHash: 'sha256' }, msg);
    const dec = privateDecrypt({ key: privateKey, oaepHash: 'sha256' }, enc);
    
    console.log(dec.toString()); // hello asymmetric world

    Practical tips: never roll your own crypto; use high-level, audited libraries. Prefer authenticated encryption modes like AES-GCM or ChaCha20-Poly1305. For new systems, consider elliptic curves (X25519/XChaCha20) for speed and strong security. Always use a secure random number generator for keys and nonces. Rotate keys and store them with a proper key management system.

    Choosing the Right Method: Speed, Size, Security

    Speed: symmetric encryption wins by a mile. AES and ChaCha20 can encrypt gigabytes per second on modern hardware, sometimes with CPU instruction support. Asymmetric methods like RSA and ECDH are thousands to millions of times slower per byte, which is why we only use them for small payloads such as keys or identity operations.

    Size: asymmetric ciphertexts and signatures are larger. For RSA-2048, the ciphertext size is roughly the key size (around 256 bytes) even for a tiny message. Symmetric ciphertexts add a small overhead (nonce + tag, often a few dozen bytes) no matter the message size. If you care about bandwidth or storage, symmetric is more compact for bulk data.

    Security properties: asymmetric gives you identity tools like digital signatures and safe key exchange over the public internet. Symmetric gives you efficient confidentiality and integrity once you already share a secret. For modern protocols, add forward secrecy using ephemeral Diffie-Hellman (X25519 or P-256): if a server’s long-term key is later stolen, past traffic stays safe.

    Typical pattern: hybrid encryption. Use asymmetric crypto to authenticate and agree on a fresh symmetric session key (the TLS handshake), then use symmetric crypto to protect the rest of the traffic. For files, encrypt the file with a random symmetric key, then encrypt that key with the recipient’s public key and attach it.

    A simple decision guide: if you need to encrypt large data fast (files, streams, databases), choose symmetric (AES-GCM or ChaCha20-Poly1305) and manage keys well. If you need to send a secret to someone you don’t share a key with, or you need verifiable identity, use asymmetric to exchange or wrap the symmetric key. For offline backups you control, symmetric with a strong passphrase-based key derivation (Argon2, scrypt) is a good fit.

    Quick Q&A:
    Q: Is asymmetric always more secure? A: No, it solves different problems; both are strong when used correctly.
    Q: Can I encrypt big files with RSA? A: Don’t. Use RSA/ECC to encrypt a random symmetric key, then use AES/ChaCha20 for the file.
    Q: What’s best for mobile? A: ChaCha20-Poly1305 is fast on devices without AES hardware; AES-GCM is great where hardware support exists.
    Q: What about passwords? A: Never encrypt passwords; hash them with a slow, salted KDF like Argon2, bcrypt, or scrypt.

    In short, synchronous (symmetric) encryption is your fast workhorse for protecting data, and asynchronous (asymmetric) encryption is your smart doorman for identity, key exchange, and signatures. Most real systems use both in a hybrid design: public key methods to agree on secrets, shared key methods to move data at high speed. Use modern, vetted algorithms, authenticated modes, secure randomness, and proper key management to stay safe without overcomplicating your stack.

    Related reading

  • Understanding VPN Tunneling and How It Protects You

    Understanding VPN Tunneling and How It Protects You

    VPN tunnel encrypting traffic between a device and a server

    In today’s digital world, online protection has become more important than ever. Every time you connect to the internet, your data travels across public networks that can easily expose your personal details. This is where VPN tunneling comes into play. Whether you are streaming, working remotely, or simply browsing, understanding VPN tunneling can help you stay private, secure, and anonymous online. Let’s break down what VPN tunneling is, how it works, and what types of tunnels offer the best protection.

    What Is VPN Tunneling and Why It Matters

    VPN tunneling is a method of creating a secure, encrypted connection between your device and the internet. Imagine your data traveling inside a secret passageway that hides it from prying eyes. This “tunnel” ensures that hackers, internet service providers (ISPs), and cybercriminals cannot access what you do online. Your information moves safely between your device and the VPN server before reaching the website or app you want to use.

    The reason VPN tunneling matters is that it creates a layer of security on otherwise risky public networks. When you use Wi-Fi at a coffee shop, airport, or hotel, you are sharing that network with many unknown users. VPN tunneling ensures that even if someone tries to intercept your connection, all they will see is unreadable, encrypted data.

    Users also value VPN tunneling for maintaining privacy. Without a VPN, your IP address — your unique online identifier — can be tracked, logged, and linked to your location. A VPN tunnel hides your IP, replacing it with one from the VPN provider’s server. This gives you online anonymity and access to region-restricted sites.

    Furthermore, VPN tunneling helps bypass censorship in certain regions. Some countries block popular websites or restrict specific online content. Through a secure tunnel, users can connect to servers in other countries and enjoy unrestricted internet access.

    In short, VPN tunneling is not just about hiding your identity; it is about protecting your freedom and data integrity. It helps you browse, stream, and work online without having to worry about who might be watching.

    How VPN Tunneling Keeps Your Data Safe Online

    The main benefit of VPN tunneling is encryption. Encryption scrambles your data into a coded format that only your VPN server can decode. Even if someone intercepts the traffic, it would appear as gibberish. This makes tunneling particularly useful for handling sensitive information like bank details or passwords.

    When you start a VPN connection, your device first authenticates with the VPN server. After verification, the tunnel is established, and an encryption key is generated. This key ensures that all data transmitted between your device and the server remains secure throughout your session.

    VPN tunneling also adds protection from data leaks. Without a tunnel, ISPs can track the websites you visit and even sell your browsing history to third parties. The VPN hides these details, making your online behavior invisible to trackers and advertisers.

    Additionally, VPN tunneling protects you from man-in-the-middle attacks — a common hacking method where attackers position themselves between you and your destination site. Since all communication is encrypted within the tunnel, the attacker cannot alter or steal data from your session.

    This technology also helps secure remote work connections, especially for businesses. Employees accessing company servers from outside networks rely on VPNs to ensure confidential data remains private. VPN tunneling becomes the digital version of a secure office connection, even from home.

    In essence, VPN tunneling gives you digital peace of mind. It ensures that your online sessions remain personal and untampered, protecting both your privacy and identity across every connection.

    Types of VPN Tunneling Protocols Explained Simply

    There are several types of VPN tunneling protocols, each designed for different levels of speed, security, and compatibility. One of the most well-known protocols is OpenVPN. It uses strong encryption and is available on almost all devices. Its balance between speed and safety makes it a top choice for regular users.

    Another popular option is IKEv2/IPSec. This protocol is known for maintaining a stable connection, even when switching between Wi-Fi and mobile data. It’s fast, secure, and especially convenient for mobile users.

    WireGuard is one of the newest VPN protocols that has gained attention for its simplicity and performance. It uses modern cryptography and runs on a lightweight codebase, making it extremely fast while maintaining high security. Many modern VPN services are now switching to WireGuard for better performance.

    L2TP/IPSec, though older, is still used by some VPNs for added compatibility. It wraps data twice for encryption, providing decent security but slightly slower speeds. It’s good for users focusing more on privacy than performance.

    There’s also PPTP, the oldest VPN protocol. While it’s fast, it’s now considered insecure for most use cases because of its outdated encryption. It’s mainly found in legacy systems or for low-risk applications.

    Understanding the different protocols helps users choose the right VPN tunnel for their needs. Whether you want blazing speed for streaming or airtight security for work, the protocol defines how efficiently your VPN tunnel performs.

    Choosing the Right VPN Tunnel for Better Security

    Selecting the best VPN tunnel depends on your online activities and devices. If you’re a casual user who primarily browses or streams, a protocol like WireGuard or OpenVPN offers both speed and reliability. These are the go-to choices for most users due to their performance and advanced encryption standards.

    For mobile users who frequently move between networks, IKEv2/IPSec is highly recommended. Its ability to reconnect quickly when switching networks keeps sessions stable and uninterrupted — ideal for travelers or business professionals on the go.

    If your goal is to ensure top-level encryption for corporate or government-level data, OpenVPN with strong cipher settings is the most trusted option. It provides deep customization for administrators to fine-tune the balance between speed and security.

    It’s essential to avoid outdated protocols like PPTP unless you specifically need compatibility with older systems. Modern online threats easily exploit older encryption methods, and relying on them can put your data at risk.

    In addition to protocol choice, users should evaluate the VPN provider’s policies. A reliable VPN should have a strict no-logs policy, strong server infrastructure, and updated security measures. These factors are just as important as the tunnel type itself.

    Ultimately, the right VPN tunnel is one that fits your lifestyle while keeping privacy intact. Test different VPN configurations, and choose the one that offers seamless performance without compromising your online safety.

    VPN tunneling is a cornerstone of modern online privacy. It shields your data, masks your identity, and provides the freedom to explore the web safely. Understanding how it works and choosing the right protocol can dramatically improve your online protection. By using secure VPN tunnels, you’re not just encrypting connections — you’re taking control of your digital life. Stay informed, choose wisely, and enjoy a safer, more private internet experience.

    Related reading

  • How to Back Up an Ubuntu Server: rsync, Borg, Restic, and Snapshots

    How to Back Up an Ubuntu Server: rsync, Borg, Restic, and Snapshots

    Ubuntu server backup process copying files and databases to storage

    Why a Proper Ubuntu Backup Strategy Matters

    Hardware failures, botched package upgrades, accidental rm commands, and ransomware can wipe out a production host in seconds. Whether you run Ubuntu 24.04 LTS or Ubuntu 26.04 LTS, a tested Ubuntu backup plan lets you restore configurations, files, and databases cleanly instead of rebuilding from memory.

    This guide covers the 3-2-1-1-0 rule, what to include and exclude, practical commands for rsync, tar, BorgBackup, and Restic, how Timeshift and Déjà Dup fit in, consistent database dumps, systemd timers, ransomware-proof offsite storage, and restore testing.

    Key Facts: Ubuntu Server Backup at a Glance

    • LTS versions covered: Ubuntu 24.04 LTS (Noble Numbat) and Ubuntu 26.04 LTS (Resolute Raccoon, released April 2026 and supported until April 2031).
    • Strategy: 3-2-1-1-0 rule (3 copies, 2 media types, 1 offsite, 1 immutable/offline, 0 unverified restores).
    • Primary tools: BorgBackup (1.2.8 in 24.04 / 1.4.4 in 26.04) or Restic (0.16.4 in 24.04 / 0.18.1 in 26.04) for encrypted deduplication; rsync and tar for mirrors and archives.
    • Desktop tools note: Déjà Dup is for desktop user files; Timeshift creates local OS rollback snapshots (skipping /home by default) and is not an offsite backup.
    • Databases: dump MySQL/MariaDB or PostgreSQL logically before copying files.
    • Automation: use systemd timers for journalctl logs and missed-run catch-up.

    Follow the 3-2-1 (and 3-2-1-1-0) Backup Rule

    CISA’s backup guidance recommends keeping at least 3 copies of data on 2 different storage media, with 1 copy offsite. To defend against ransomware and compromised admin keys, extend this to 3-2-1-1-0: add 1 immutable or offline copy that the live server cannot delete, and maintain 0 errors via automated checks and restore drills.

    Ubuntu backup architecture diagram showing the 3-2-1-1-0 rule across live Ubuntu 24.04 and 26.04 LTS server, local encrypted Borg or Restic repo, immutable offsite storage, and restore verification
    The 3-2-1-1-0 Ubuntu backup architecture balancing fast local recovery and immutable offsite protection.

    What to Back Up on an Ubuntu Server

    Skip virtual kernel filesystems and focus on configuration, application state, and recovery manifests:

    • Configs & certs: /etc/ (Nginx, Apache, SSH, UFW/nftables, systemd units in /etc/systemd/system/, and /etc/letsencrypt/).
    • App data & users: /var/www/, /srv/, container volumes, and /home/.
    • Database dumps: scheduled exports in /var/backups/db/.
    • Package list: run apt-mark showmanual > /var/backups/apt-manual.txt so you can reinstall software on a clean Ubuntu image.

    For full-filesystem mirrors, exclude /dev/*, /proc/*, /sys/*, /tmp/*, /run/*, /mnt/*, /media/*, /lost+found, and /var/cache/*.

    Choosing the Right Ubuntu Backup Tool

    Match the tool to your recovery goal: quick directory mirrors, portable archives, or encrypted deduplicated offsite repositories.

    Ubuntu backup tools comparison matrix for BorgBackup, Restic, rsync, tar, and Timeshift snapshots showing encryption, deduplication, offsite support, and best server use cases
    Comparison of core Ubuntu server backup tools across encryption, deduplication, and offsite support.

    1. Incremental Mirroring with rsync

    rsync mirrors files quickly while preserving permissions, ACLs, and extended attributes. Store exclusions in a file so scripts work identically under cron, systemd, and interactive shells:

    sudo rsync -aAXHv --delete --exclude-from=/etc/backup-exclude.txt / /mnt/backup/ubuntu-mirror/
    sudo rsync -aAXHz --delete /etc /var/www /var/backups/db backup@198.51.100.10:/srv/backups/web01/

    Remember that /etc/ copies directory contents whereas /etc copies the folder itself, and always dry-run (-n) before enabling --delete. For multi-day hardlink snapshots over rsync, see Ubuntu’s rsnapshot guide. Note that rsync encrypts only in transit over SSH, not at rest.

    2. Portable Archives with tar

    tar is ideal for quick snapshots of /etc before config changes. Keep archives outside web roots and encrypt with gpg --symmetric --cipher-algo AES256 before uploading offsite:

    sudo tar --acls --xattrs -czpf /var/backups/etc-$(date +%F).tar.gz /etc
    tar -tzvf /var/backups/etc-$(date +%F).tar.gz | head

    3. Encrypted SSH Backups with BorgBackup

    BorgBackup provides chunk-level deduplication, compression, and client-side encryption. Ubuntu 24.04 ships borgbackup 1.2.8 and Ubuntu 26.04 ships 1.4.4 (26.04 also includes borgbackup2 as a 2.0.0b20 beta, so use stable borgbackup 1.x in production):

    sudo apt update && sudo apt install -y borgbackup
    export BORG_PASSPHRASE="strong-generated-passphrase"
    
    borg init --encryption=repokey-blake2 ssh://borg@backup.example.com:22/srv/borg/web01
    borg key export ssh://borg@backup.example.com:22/srv/borg/web01 /root/borg-key.txt
    
    borg create --stats --compression zstd,6 \
      ssh://borg@backup.example.com:22/srv/borg/web01::"{hostname}-{now:%Y-%m-%d}" \
      /etc /var/www /home /var/backups/db
    
    borg prune --list --keep-daily=7 --keep-weekly=4 --keep-monthly=6 \
      ssh://borg@backup.example.com:22/srv/borg/web01
    borg compact ssh://borg@backup.example.com:22/srv/borg/web01

    4. Encrypted S3 & Cloud Backups with Restic

    Restic (0.16.4 in Ubuntu 24.04; 0.18.1 in Ubuntu 26.04) encrypts and deduplicates data natively to S3-compatible buckets, Backblaze B2, SFTP, or rclone:

    sudo apt update && sudo apt install -y restic
    export RESTIC_REPOSITORY="s3:s3.us-east-1.amazonaws.com/my-ubuntu-backups/web01"
    export RESTIC_PASSWORD_FILE="/root/.restic-pass"
    
    restic init
    restic backup /etc /var/www /home /var/backups/db
    restic forget --keep-daily 7 --keep-weekly 4 --keep-monthly 6 --prune

    5. Timeshift, Déjà Dup, and Cloud/LVM Snapshots

    Déjà Dup targets GNOME desktop folders, not headless servers. Timeshift takes local Rsync or Btrfs system snapshots (also usable via CLI), but excludes /home and /root by default and lacks encrypted offsite storage. Similarly, VPS, LVM, and ZFS snapshots help roll back botched updates quickly, but they live on the same host or cloud account and do not replace independent offsite backups.

    Backing Up MySQL, MariaDB, and PostgreSQL Safely

    Copying /var/lib/mysql or /var/lib/postgresql on a live server risks inconsistent tables. Export logical dumps into a root-only directory right before your file backup runs:

    sudo install -d -m 0700 /var/backups/db
    
    # MySQL (use mariadb-dump on MariaDB)
    mysqldump --single-transaction --routines --triggers --all-databases \
      | gzip > /var/backups/db/mysql-all-$(date +%F).sql.gz
    
    # PostgreSQL
    sudo -u postgres pg_dump -Fc mydb > /var/backups/db/mydb-$(date +%F).dump
    sudo -u postgres pg_dumpall | gzip > /var/backups/db/pg-all-$(date +%F).sql.gz

    Running WordPress on Ubuntu? Pair these database dumps with our WordPress backup guide.

    Automating Backups with systemd Timers (and Cron)

    systemd timers beat bare cron jobs on Ubuntu 24.04 and 26.04 because output goes straight to journalctl and Persistent=true catches missed runs after reboots. Put your backup script at /usr/local/sbin/run-ubuntu-backup.sh (chmod 700) and create a unit pair:

    # /etc/systemd/system/ubuntu-backup.service
    [Unit]
    Description=Daily Ubuntu Server Backup
    After=network-online.target
    Wants=network-online.target
    
    [Service]
    Type=oneshot
    EnvironmentFile=/etc/default/ubuntu-backup
    ExecStart=/usr/local/sbin/run-ubuntu-backup.sh
    
    # /etc/systemd/system/ubuntu-backup.timer
    [Unit]
    Description=Run Ubuntu Server Backup Daily
    
    [Timer]
    OnCalendar=*-*-* 02:30:00
    RandomizedDelaySec=15m
    Persistent=true
    
    [Install]
    WantedBy=timers.target
    sudo systemctl daemon-reload
    sudo systemctl enable --now ubuntu-backup.timer
    journalctl -u ubuntu-backup.service -n 40

    Prefer cron? Call the same script from sudo crontab -e (30 2 * * * /usr/local/sbin/run-ubuntu-backup.sh >/var/log/ubuntu-backup.log 2>&1) rather than putting inline date +%F commands inside crontab.

    Securing Backups Against Ransomware

    CISA’s #StopRansomware Guide warns that intruders actively delete reachable backups. Lock down your backup targets:

    • Make offsite storage append-only or immutable: Restrict Borg SSH keys with command="borg serve --append-only --restrict-to-path /srv/borg/web01",restrict, use Restic’s append-only REST server, or enable S3 Object Lock so a compromised host cannot erase past snapshots.
    • Keep recovery keys off the server: Store Borg key exports and passphrases in a password manager—not only on the host being backed up.
    • Lock down credential files: Keep /etc/default/ubuntu-backup owned by root:root with permissions 0600.
    • Harden the server itself: Follow our Ubuntu server security guide and ransomware prevention guide.

    Testing Your Restores

    Verify repository integrity weekly and test real restores into a temporary directory or staging VM quarterly:

    # Borg integrity check + test extract
    borg check ssh://borg@backup.example.com:22/srv/borg/web01
    mkdir -p /tmp/restore-test && cd /tmp/restore-test
    borg extract ssh://borg@backup.example.com:22/srv/borg/web01::"web01-2026-11-25" etc/nginx
    
    # Restic integrity check + test restore
    restic check --read-data-subset=5%
    restic restore latest --target /tmp/restore-test --include /etc/nginx
    
    # Test database restore
    gunzip < /tmp/restore-test/var/backups/db/mysql-all-2026-11-25.sql.gz | sudo mysql
    sudo -u postgres pg_restore -d mydb_test /tmp/restore-test/var/backups/db/mydb-2026-11-25.dump

    FAQ

    What is the best Ubuntu backup tool for a production server?

    BorgBackup (for SSH servers) and Restic (for S3/cloud object storage) are top choices because both provide client-side encryption, deduplication, and automated pruning.

    Should I use Timeshift or Déjà Dup on Ubuntu Server?

    Déjà Dup is a desktop app. Timeshift works on the CLI for local OS rollbacks, but it excludes /home and /root by default and does not replace encrypted offsite backups.

    Are VPS or cloud snapshots enough?

    No. Snapshots live inside the same cloud account and hypervisor; keep an independent encrypted offsite copy under separate credentials.

    Why use mysqldump or pg_dump instead of copying /var/lib/mysql?

    Copying active database files can capture half-written pages and corrupt tables. Logical dumps produce consistent, restorable snapshots.

    How often should I back up an Ubuntu server?

    Run encrypted incremental backups at least daily, take an extra snapshot before major upgrades, and dump busy databases hourly or ship WAL/binlogs.

    How do I protect Ubuntu backups from ransomware?

    Use append-only SSH keys or S3 Object Lock, keep passphrases off the server, and maintain one offline or air-gapped copy.

    References

    Related Articles

    Last Verified: November 25, 2026. Verified for Ubuntu 24.04 LTS and Ubuntu 26.04 LTS against Ubuntu Server documentation, BorgBackup, Restic, PostgreSQL, systemd, and CISA guidance.