Make the configuration of iptables persistent (Debian)

12/11/2026 Categories: Sécurité, Système Tags: , , , Comments off

Objective

To make the configuration of iptables persistent on a Debian-based system

Background

The iptables and ip6tables commands can be used to instruct Linux to perform functions such as firewalling and network address translation, however the configuration that they create is non-persistent so is lost whenever the machine is rebooted. For most practical applications this is not the desired behaviour, so some means is needed to reinstate the configuration at boot time.

For security, the iptables configuration should be applied at an early stage of the bootstrap process: preferably before any network interfaces are brought up, and certainly before any network services are started or routing is enabled. If this is not done then there will be a window of vulnerability during which the machine is remotely accessible but not firewalled.

Scenario

Suppose you have a machine that you wish to protect using a firewall. You have written iptables and ip6tables rulesets, and wish to install them so that they will remain active if the machine is rebooted.

Lire la suite…

What are useful systemd commands?

11/11/2026 Categories: Système Tags: , , Comments off

Systemd is a modern init system and system and service manager for Linux. It is designed to be compatible with the traditional System V and LSB (Linux Standard Base) init scripts while providing advanced features for managing system services and resources. It has become the default init system for many popular Linux distributions, such as Fedora, Ubuntu, Debian, openSUSE, and Arch Linux.

In this tutorial, I will go over some of the most useful systemd commands. I will explain what each systemd command does, as well as some example usage.

1. systemdctl

systemctl is a command-line tool that allows you to interact with the systemd system and service manager on systemd-enabled Linux. It provides a wide range of functionalities to control and manage services, units, and system states.

  • systemctl status [service]: Check the status of a service or unit.
  • systemctl start [service]: Start a service or unit.
  • systemctl stop [service]: Stop a service or unit.
  • systemctl restart [service]: Restart a service or unit.
  • systemctl reload [service]: Reload a service’s configuration without restarting it (if supported).
  • systemctl enable [service]: Enable a service to start at boot.
  • systemctl disable [service]: Disable a service from starting at boot.
  • systemctl list-units: List all units (services, mounts, devices, etc.) managed by systemd.
  • systemctl list-unit-files: List all unit files and their enabled/disabled state.
  • systemctl daemon-reload: Reload the systemd configuration, required after modifying service files.

2. journalctl

journalctl is the command for querying and displaying logs from the systemd journal on Linux systems. The systemd journal is a centralized, structured logging system that collects and stores log messages from various system components, including the kernel, services, and applications. journalctl provides numerous options for filtering and viewing log entries, making it a powerful tool for troubleshooting and monitoring system events.

  • journalctl: Show the full journal log.
  • journalctl -u [service]: Show logs for a specific service or unit.
  • journalctl -f: Continuously show new log entries in real-time (follow mode).
  • journalctl --since "YYYY-MM-DD HH:MM:SS": Show log entries since a specific date and time.
  • journalctl --until "YYYY-MM-DD HH:MM:SS": Show log entries until a specific date and time.
  • journalctl -p [priority]: Show log entries with a specific priority (e.g., emerg, alert, crit, err, warning, notice, info, debug).
  • journalctl -k: Show kernel log messages.
  • journalctl --disk-usage: Show the total disk usage of the journal.

3. hostnamectl

hostnamectl is a command-line utility for managing the hostname and related settings. It allows you to view and modify the system hostname, as well as configure the static, transient, and pretty hostnames. Additionally, it provides information about the current operating system, kernel, and system architecture.

  • hostnamectl: Show the current hostname and related information.
  • hostnamectl set-hostname [hostname]: Set the system hostname.
  • hostnamectl set-chassis [type]: Set the system chassis type (e.g., desktop, laptop, server, vm).
  • hostnamectl set-deployment [environment]: Set the system deployment environment (e.g., development, staging, production).

4. timedatectl

timedatectl is a command used to manage date, time, and time zone settings. It provides an interface for viewing and modifying the system clock, adjusting the time zone, and configuring the Network Time Protocol (NTP) for time synchronization.

  • timedatectl: Show the current time, date, and time zone information.
  • timedatectl set-time [time]: Set the system time.
  • timedatectl set-timezone [timezone]: Set the system time zone.
  • timedatectl set-ntp [true/false]: Enable or disable network time synchronization (NTP).

5. localectl

localectl is a command for managing system locale and keyboard layout settings. It allows you to view and modify the system’s language, character encoding, and keyboard layout settings. This utility makes it easy to configure the appropriate locale and keyboard settings for your system, ensuring proper language support and input functionality.

  • localectl: Show the current locale and keyboard settings.
  • localectl set-locale [locale]: Set the system locale.
  • localectl list-locales: List available locales.
  • localectl set-keymap [keymap]: Set the system console keymap.
  • localectl list-keymaps: List available console keymaps.
  • localectl set-x11-keymap [layout] [model] [variant] [options]: Set the X11 (graphical) keymap. Specify layout, model, variant, and options as needed.

6. loginctl

loginctl is a command for managing user sessions and seats. It provides an interface to interact with and control various aspects of user sessions, such as listing active sessions, showing user and session status, terminating sessions, and locking or unlocking sessions.

  • loginctl: List user sessions.
  • loginctl user-status [user]: Show the status of a specific user.
  • loginctl show-session [session_id]: Show detailed information about a specific session.
  • loginctl show-user [user]: Show detailed information about a specific user.
  • loginctl terminate-user [user]: Terminate all sessions for a specific user.
  • loginctl terminate-session [session_id]: Terminate a specific session.
  • loginctl lock-session [session_id]: Lock a specific session.
  • loginctl unlock-session [session_id]: Unlock a specific session.

7. systemd-analyze

systemd-analyze is a command for analyzing and diagnosing system boot performance and service dependencies within the systemd system and service manager. It provides various options to inspect the boot process, identify slow-starting services, and visualize the critical chain of units during the boot sequence. By using systemd-analyze, you can gain insights into your system’s boot performance and identify potential bottlenecks or issues that need to be addressed.

  • systemd-analyze: Show the time taken to boot the system.
  • systemd-analyze blame: Show a list of services sorted by the time taken to initialize them.
  • systemd-analyze critical-chain: Show a tree of the time-critical chain of units during boot.
  • systemd-analyze plot > boot.svg: Generate a graphical representation of the boot process, saved as an SVG file.

8. systemd-cgls

systemd-cgls is a command for displaying the hierarchy of control groups (cgroups) and their associated processes on Linux. Control groups are a kernel feature that allows you to organize, manage, and limit resource usage for groups of processes. systemd-cgls provides an easy way to visualize the cgroup hierarchy in a tree-like structure, making it convenient to examine how resources are allocated and managed across different services and system components.

  • systemd-cgls: Show a tree view of all control groups and their processes.

9. systemd-cgtop

systemd-cgtop is a command that shows the top control groups (cgroups) by their resource usage. It provides a real-time, dynamic view of resource consumption, such as CPU, memory, and I/O, for each cgroup. This utility is similar in concept to the top command, but focuses specifically on the resource usage of cgroups.

  • systemd-cgtop: Display a real-time, top-like view of control groups and their resource usage (CPU, memory, and I/O).

10. systemd-delta

systemd-delta is a command that analyzes and displays the differences between the vendor-supplied, user-supplied, and runtime systemd unit files. It helps you identify the differences and changes made to unit files, which can be useful for troubleshooting or understanding customizations in your system’s configuration.

  • systemd-delta: Show the differences between vendor-supplied, user-supplied, and runtime unit files.
  • systemd-delta --type=masked: Show only masked units.
  • systemd-delta --type=extended: Show only units with extended configuration.

11. systemd-path

systemd-path is a command that displays the paths and directories used by the systemd system. It provides information about various system directories, such as configuration, state, cache, logs, and runtime data directories, among others. By using systemd-path, you can easily identify and locate the directories used by systemd and the associated services, which can be helpful when working with configuration files, logs, or other system data. It can also help ensure that you are working with the correct paths when troubleshooting or customizing your systemd configuration.

  • systemd-path: Show the paths of various system directories (e.g., state, cache, logs, etc.).
  • systemd-path [name]: Show the path of a specific directory by name (e.g., systemd-path logs).

12. systemd-nspawn

systemd-nspawn is a command that provides lightweight container functionality. It allows you to create, start, and manage isolated environments, called containers, by using the existing Linux kernel and systemd features such as cgroups, namespaces, and capabilities. systemd-nspawn is not as feature-rich as Docker or LXC, but it offers a simple and straightforward approach to running containers for various purposes, such as testing, development, or sandboxing applications. It can start containers from directories or disk images, and it supports network isolation and resource management.

  • systemd-nspawn -D [directory]: Start a container with the specified directory as its root filesystem.
  • systemd-nspawn --image [image]: Start a container with the specified disk image as its root filesystem.
  • systemd-nspawn -bD [directory]: Start a container with the specified directory as its root filesystem and boot it using the contained init system.
  • systemd-nspawn --private-network: Start a container with its own private network namespace.

13. systemd-machine-id-setup

systemd-machine-id-setup is a command for initializing the /etc/machine-id file on Linux. The /etc/machine-id file contains a unique, 128-bit identifier for the system, which is used by various components of the operating system and applications to track the system and its state. The machine ID is intended to be unique for each system and remain unchanged throughout the system’s lifetime, even if hardware components are replaced or the system is reinstalled. The machine ID is not meant to be a secret and can be used by applications for various purposes, such as tracking system usage or maintaining system-specific configurations. In general, you don’t need to manually run systemd-machine-id-setup, as it is automatically executed during the system installation or first boot. However, in some cases, you may need to run it to generate or regenerate the machine ID, such as when creating custom system images or cloning virtual machines.

  • systemd-machine-id-setup: Generate a new machine ID and store it in /etc/machine-id.

14. systemd-escape

systemd-escape is a command that helps you convert arbitrary strings into a format suitable for use as systemd unit names, file paths, or other identifiers. It is particularly useful when working with strings that contain special characters, whitespace, or other elements that are not allowed or can cause conflicts in systemd unit names.

  • systemd-escape [string]: Escape the specified string for use in a systemd unit name.
  • systemd-escape --unescape [string]: Unescape a previously escaped string.

15. systemd-cat

systemd-cat is a command that allows you to send the output of any command or program directly to the systemd journal. This can be useful for capturing the output of short-lived processes or scripts in the systemd journal, making it easier to analyze, filter, and search for log entries related to those processes. By using systemd-cat, you can pipe the output of a command or script directly to the journal, or you can run a command with systemd-cat as a wrapper. This tool also supports adding custom metadata, such as log priority or identifier, to the captured log entries, which can help with organizing and filtering logs in the journal. systemd-cat provides a simple and convenient way to integrate custom logging and output from various sources into the centralized systemd journal, enabling better log management and analysis.

  • systemd-cat [command]: Run the specified command and forward its output to the systemd journal.

16. systemd-notify

systemd-notify is a command that enables services to send status updates, progress reports, or other notifications to the systemd system. It is particularly useful for implementing service readiness protocols, signaling service state changes, or reporting service-specific status information. Services can use systemd-notify to send messages to systemd over a communication channel called the notification socket. This utility supports various message types, such as READY, STATUS, ERRNO, MAINPID, and WATCHDOG. For example, a service can use the READY message to inform systemd that it has successfully started and is ready to process requests. By using systemd-notify, services can communicate with systemd more effectively, ensuring proper service management, monitoring, and coordination. This utility is particularly useful for long-running services or those with complex initialization procedures that need to signal their state to systemd.

  • systemd-notify --ready: Send a notification to systemd indicating that the service is ready.

17. systemd-tmpfiles

systemd-tmpfiles is a command-line tool and associated configuration system for managing temporary files and directories on systemd-enabled Linux. It provides a standardized and flexible way to create, clean, and remove temporary files and directories during system boot, shutdown, or on a periodic basis. systemd-tmpfiles uses configuration files located in /usr/lib/tmpfiles.d/, /etc/tmpfiles.d/, and /run/tmpfiles.d/ directories to define the rules and actions for managing temporary files. These configuration files contain directives specifying the file paths, access permissions, ownership, and other attributes, as well as the cleanup policies, such as aging and size limits. systemd-tmpfiles is usually run automatically by systemd at various stages of the system’s lifecycle, but it can also be invoked manually to apply the specified actions, such as creating or cleaning temporary files and directories. By using systemd-tmpfiles, you can ensure proper management and cleanup of temporary files and directories, helping maintain a clean and organized system, reducing the risk of data leaks, and conserving disk space.

  • systemd-tmpfiles --create: Create volatile files and directories as defined in the configuration files.
  • systemd-tmpfiles --clean: Clean up old, expired files and directories as defined in the configuration files.

18. systemd-run

systemd-run is a command that allows you to run a command or a script as a transient systemd service or scope unit on systemd-enabled Linux systems. Transient units are created dynamically at runtime and automatically removed when they are no longer needed or when the system is rebooted. This command provides a wide range of options for configuring the created units, including resource limits, dependencies, environment variables, and restart policies, among others.

  • systemd-run --unit=[name] [command]: Run the specified command as a transient service with the given name.
  • systemd-run --scope [command]: Run the specified command as a transient service in a new scope.

19. systemd-mount

systemd-mount is a command-line utility that allows you to mount and manage file systems using the systemd system. It provides a convenient way to mount file systems as transient .mount units, which are automatically managed by systemd. The command also supports various options for configuring the mounted file systems, such as mount options, time-outs, and dependencies on other systemd units.

  • systemd-mount [device] [path]: Mount the specified device at the given path, creating a mount unit under systemd.
  • systemd-mount --umount [path]: Unmount the specified path, stopping the associated systemd mount unit.

20. systemd-ask-password

systemd-ask-password allows you to query user passwords or passphrases in a secure and consistent manner on systemd-enabled Linux. This command is typically used by system services or scripts that require user authentication or secret input, such as mounting encrypted file systems or unlocking secure key stores. systemd-ask-password works by displaying a password prompt to the user, either on the console, in a graphical dialog, or over a remote connection, depending on the environment and available password agents. The entered password or passphrase is then securely passed to the requesting service or script.

  • systemd-ask-password: Prompt the user for a password or passphrase with the given message.

21. systemd-inhibit

systemd-inhibit allows you to execute a program or script while temporarily blocking specific system operations, such as shutdown, reboot, or sleep. It is particularly useful for ensuring that critical tasks or maintenance operations are not interrupted by a sudden system state change. systemd-inhibit works by creating an « inhibitor lock » that prevents the specified system operations from taking place while the program or script is running. You can specify the type of inhibitor lock and a descriptive reason for its use. Common types of locks include « shutdown », « sleep », « idle », and « suspend ».

  • systemd-inhibit --what=[operation] [command]: Run the specified command while inhibiting the specified operation (e.g., shutdown, sleep, idle).

22. systemd-dissect

systemd-dissect is a command-line tool that provides the functionality to inspect and analyze disk images and file system trees. It is particularly useful for examining disk images that contain operating system files, such as those used for containers, virtual machines, or system installation. By using systemd-dissect, you can easily inspect and analyze disk images and file system trees, which can be helpful when working with containers, virtual machines, or creating custom system images. It provides a convenient way to examine the contents and structure of disk images without having to mount them manually or use multiple tools for different tasks.

  • systemd-dissect [image]: Show a brief summary of the contents of the specified disk or OS image.
  • systemd-dissect --mount [image]: Mount the specified disk or OS image, showing a summary of its contents.

23. systemd-resolve

systemd-resolve is a command that is part of the systemd-resolved service, which provides network name resolution and caching on systemd-enabled Linux. The command allows you to query and manage the DNS resolver and cache provided by systemd-resolved.

  • systemd-resolve [hostname]: Resolve the specified hostname to an IP address using the system DNS resolver.
  • systemd-resolve --status: Show the current status of the system DNS resolver, including the configured DNS servers and search domains.

24. systemd-firstboot

systemd-firstboot is a command that allows you to initialize various basic system settings on systemd-enabled Linux. It is typically used during the first boot of a newly installed system or when creating custom system images for deployment. The utility can be used in both interactive and non-interactive modes. In interactive mode, systemd-firstboot prompts the user for the required information, while in non-interactive mode, the settings are provided via command-line options or configuration files.

  • systemd-firstboot --setup-machine-id: Set up the machine ID on the first boot.
  • systemd-firstboot --setup-root-password: Set the root password on the first boot.

These are some of the most useful systemd commands for managing various aspects of your Linux system. Remember that most of these commands require administrative privileges, so prepend sudo when necessary.

Source: xmodulo

Categories: Système Tags: , ,

GeoIP pour iptables

11/11/2026 Categories: Réseau, Sécurité Tags: , , Comments off

Source: how-to.ovh

Marre des pays exotiques qui essaient de s’introduire sur le serveur et pourrissent vos logs et font bosser fail2ban ?

Une solution pour bloquer les pays avec lesquels vous n’avez pas de relations. Pour Debian mais sûrement adaptable à d’autres distributions.

# Install GeoIP pour iptables

apt-get install dkms xtables-addons-dkms xtables-addons-common xtables-addons-dkms geoip-database libgeoip1 libtext-csv-xs-perl unzip

# On vérifie que c’est ok

dkms status xtables-addons

# on crée le repertoire

mkdir /usr/share/xt_geoip

# on se déplace dedans

cd /usr/share/xt_geoip/

# on télécharge le fichier

wget http://man.sethuper.com/wp-content/uploads/2013/06/geoip-dl-build.tar.gz

# on le décompresse

tar xvf geoip-dl-build.tar.gz

# on l’exécute

./xt_geoip_dl

# si cela donne un message d’erreur, on fait ceci

/usr/bin/perl -MCPAN -e'install Text::CSV_XS'

# on exécute l’autre fichier

./xt_geoip_build -D . *.csv

# on efface les fichiers inutiles

rm -rf geoip-dl-build.tar.gz

# on teste iptables en bloquant la Chine et la Russie

iptables -A INPUT -m geoip --src-cc CN,RU -j DROP

# on vérifie

iptables -L -v

# ce qui donnera cette ligne indiquant que les pays seront bloqués

DROP all -- anywhere anywhere -m geoip --source-country CN,RU

pour interdire le port 22 à ces pays

iptables -A INPUT -p tcp --dport 22 -m geoip --src-cc CN,RU -j DROP

Block entire countries on Ubuntu server with Xtables and GeoIP

11/11/2026 Categories: Réseau, Sécurité Tags: , , , Comments off

Source: jeshurun.ca

Anyone who has administered even a moderately high traffic server will have noticed that certain unwelcome traffic such as port scans and probes tend to come from IP addresses belonging to a certain group of countries. If your application or service does not cater to users in these countries, it might be a safe bet to block these countries off entirely.

This is especially true for email servers. The average email server, based on anecdotal evidence of servers for around 20 domains, rejects about 30% of incoming email every day as spam. Some servers on some days reject up to as much as 97% of incoming email as spam. Most of these originate in a certain subset of countries. That is a lot of wasted CPU cycles being expended on scanning these undesired emails for spam and viruses. Although tools such as amavisd and spamassasin do a good job of keeping the vast majority of spam out of users’ inboxes, when the rare well crafted and targeted phishing email does get through, it wrecks havoc in the enterprise.

Lire la suite…

The role of shells in the Linux environment

10/11/2026 Categories: Système Tags: , , Comments off

Shell is used for various purposes under Linux. Linux user environment is made of the following components:

  • Kernel – The core of Linux operating system.
  • Shell – Provides an interface between the user and the kernel.
  • Terminal emulator – The xterm program is a terminal emulator for the X Window System. It allows user to enter commands and display back their results on screen. 
  • Linux Desktop and Windows Manager – Linux desktop is collection of various software apps. It includes the file manger, the windows manager, the Terminal emulator and much more. KDE and Gnome are two examples of the complete desktop environment in Linux.

Login

User can login locally into the console when in runlevel # 3 or graphically when in runlevel # 5 (the level numbers may differ depending on the distribution). In both cases you need to provide username and password. Bash uses the following initialization and start-up files:

  1. /etc/profile – The systemwide initialization file, executed for login shells.
  2. /etc/bash.bashrc – The systemwide per-interactive-shell startup file. This is a non-standard file which may not exist on your distribution. Even if it exists, it will not be sourced unless it is done explicitly in another start-up file.
  3. /etc/bash.logout – The systemwide login shell cleanup file, executed when a login shell exits.
  4. $HOME/.bash_profile – The personal initialization file, executed for login shells.
  5. $HOME/.bashrc – The individual per-interactive-shell startup file.
  6. $HOME/.bash_logout – The individual login shell cleanup file, executed when a login shell exits.
  7. $HOME/.inputrc – Individual readline initialization file.

Bash Startup Scripts

Script of commands executed at login to set up environment. For example, setup JAVA_HOME path.

Login Shell

Login shells are first shell started when you log in to the system. Login shells set environment which is exported to non-login shells. Login shell calls the following when a user logs in:

Non-Login Shell

Bash Logout Scripts

  • When a login shell exits, bash reads and executes commands from the file $HOME/.bash_logout, if it exists.

Source: Cybercitiz

Categories: Système Tags: , ,