Sécurisation des postes de Travail



Chap 05 Linux Native Security Tools


Sommaire

  • Basic Commands and Configurations
  • Permissions
  • Access List
  • SSH
  • Firewall
  • SELINUX
  • Secure and Troubleshoot Boot
  • Open LDAP


Basic Commands and Configurations


Managing Users

Adding New User process

New User Adding process : exemple of Juan


1. A new line for juan is created in /etc/passwd: juan:x:1001:1001::/home/juan:/bin/bash
2. A new line for juan is created in /etc/shadow: juan:!!:14798:0:99999:7:::
3. A new line for a group named juan is created in /etc/group: juan:x:1001:
4. A new line for a group named juan is created in /etc/gshadow: juan:!::
5. A directory for user juan is created in the /home/directory
6. The files within the /etc/skel/ directory (which contain default user settings) are copied into the new /home/juan/ directory

Commands

adduser     |     openssl

Create a new user

[root@lab ~]# useradd user_name
or
[root@lab ~]# adduser user_name



[root@lab ~]# userdel user_name       Remove an user
[root@lab ~]# userdel -r user_name       Remove user_name from the system, along with his/her home directory and mail spool
[root@redhat ~]# id Display information about the current logged - in user
[root@redhat ~]# who Display connected users including used TTYs
[root@redhat ~]# w Know actives users
[root@redhat ~]# users Dispay Connected users



User Settings

UID (User Identifier) : New user created on RHEL 8 has a UID above 1000. UID 0 to 999 are reserved for System Users

Generate Encrypted Password

openssl command use DES Encryption

[root@redhat ~]# openssl passwd -crypt Standard Unix password algorithm (default)
[root@redhat ~]# openssl passwd -6 SHA512-based password algorithm

Application

pass=user

[root@redhat ~]# openssl passwd -crypt 
Password:
Verifying - Password:
uyOvQmy1a9v/.


[root@redhat ~]# adduser user6 -p uyOvQmy1a9v/.
[root@redhat ~]# cat /etc/shadow

[root@lab ~]# adduser user3 -c "Eninam BAGNABANA" -e 2023-07-01 -p uyOvQmy1a9v/. -s /bin/bash
[root@lab ~]# adduser user4 --comment "Eninam BAGNABANA" --expiredate 2024-07-01 --password uyOvQmy1a9v/. --shell /bin/sh




Files

/etc/default/useradd : adduser command default settings File


Users Files and Directories


/etc/passwd Users main configuration File [+]

/etc/shadow Users Passwords Main Configuration File in Shadow Mode . Stores by default Passwords Hashes

/etc/login.defs new user defaults settings

/etc/skel/ Directory which stores list of files and directories to copy in new user home directory

/home/user/.bash_history Bash commands log

/home/user/.bashrc User specific environment and startup programs (Aliases and functions) relative on bash Start
Countains user bash profile like alias (default commands options or middle name of commands)

Le fichier …/.bashrc contenu dans le répertoire personnel de chaque user contient des settings qui sont charges à chaque fois que l’user se connecte.
Si on veut définir donc des paramètres pour un user on le note dans ce fichier

/home/user/.bash_profile User specific environment and startup programs relative on login

/etc/default/useradd : adduser command default settings File


Managing Passwords

Commands

[root@lab ~]# passwd Change current user password
[root@lab ~]# passwd username Change an user password
[root@lab ~]# passwd –l username      lock an user password (he can’t login)
[root@lab ~]# passwd –u username unlock an user password
[root@lab ~]# passwd –S username password infos



Saving Passwords
we have two password saving modes
  • Standard
  • Shadow (default)
Dans le mode standard les comptes utilisateurs et les mots de passe sont stockés dans un seul fichier /etc/passwd.
Dans le mode shadow les comptes utilisateurs sont stockés dans le fichier /etc/passwd et les mots de passe dans le fichier /etc/shadow

In environments with multiple users, it is very important to use shadow passwords provided by the shadow-utils package to enhance the security of system authentication files.

For this reason, the installation program enables shadow passwords by default

[root@lab ~]# pwconv conversion of passwords to shadow passwords
[root@lab ~]# pwunconv conversion of shadow passwords to standard passwords.(/etc/shadow doesn’t exist)

Files

/etc/passwd Main users accounts Configuration file
/etc/shadow Main users accounts passwords Configuration file

Other Commands

[root@lab ~]# chage -l user Display a user Password Expiration infos
[root@lab ~]# usermod --expiredate=2018-12-25 user1 Set an expiration date to an user account

The su Command

Commands

[root@lab ~]# su use root privilege
[root@lab ~]# su user use an user privilege
[root@lab ~]# su – user change user
[user1@lab ~]# su –c command use a command like root (You must know root password)
[user1@lab ~]# su –c command user
use a command like another user (You must know user password)

su command users

Add users to the special administrative group called wheel
[root@lab ~]# usermod -G wheel username

NB: After you add the desired users to the wheel group, it is advisable to only allow these specific users to use the su command.
To do this, you will need to edit the PAM configuration file for su: /etc/pam.d/su

Open this file in a text editor and remove the comment (#) from the following line:
#auth required pam _wheel.so use_uid
This change means that only members of the administrative group wheel can switch to another user using the su command.

NB: The root user is part of the wheel group by default.

Files

/etc/pam.d/su su command principal Configuration File [+]


VI Improved (vim)

vi stands for Visual Interface.
VI Improved (vim)

VI IMproved

The version of vi that is shipped with Red Hat Enterprise Linux 7 is called vim. vim stands for VI IMproved, as vim comes with many features not found in the original vi, while still remaining (mostly) backward-compatible. Among the new features are popular options, such as

  • syntax highlighting,
  • completion modes,
  • and spell-checking.

Syntax

[root@lab ~]# vi file

[root@lab ~]# vim options file

■ Open and edit a file.
■ Creates file if it doesn’t exist

Execution modes

Vim functions in three different modes:
  • command mode
  • insert mode
  • last line mode.

Editing Steps

When you first start working with a file, you are in command mode. Here, you can issue commands that allow you to move around your file without actually inserting text into the file.

When you’re ready to insert text into the file, you can use i or a to move into insert mode, enabling you to insert text at the cursor location. To move out of insert mode back into command mode, just press the Esc key.

The last mode you can enter is last line mode, which you enter by typing a colon (:). In this mode, you can issue additional commands to save, quit, and do even more.

esc [key] to quit mode

Commands mode

i insert (insert mode). insert text at the current cursor position
a append (edit at end of line). append text after the current position of the cursor
v (visual) selection
d to cut the selection.
y to copy the selection
yy young (copy a line)
dd delete (cut a line)
p (paste)
P if you want to paste it above the current line
x to delete a single character.
dw to delete the rest of the word. from the current position of the cursor to the end of the word
D to delete from the current cursor position up to the end of the line
o open a new line under the current position of the cursor
O open a new line above the current position of the cursor.
r modify character. put the cursor on the letter and press r. Next type a new letter as a replacement for the letter .
e Moves to the end of a word
b Moves to the beginning of a word
$ Moves to the end of a line
H Moves to the first line onscreen
L Moves to the last line onscreen
a Appends after the cursor
o Opens a new line below and inserts
O Opens a new line above and inserts
R Enters insert mode but replaces characters instead of inserting
dd Deletes the current line
x Deletes text under the cursor
yy Yanks (copies) the current line
p Pastes the yanked line
u Undoes the last action

Last line mode

:set nonumber don’t show lines numbers
:set number show lines numbers
:number go to a line
:q to quit page
:q! to quit page without saving
:w to save page If you want to save it under a new filename, just enter the new name after the w command.
:wq to save and quit page
:/string search a string in file contains
:%s/oldtext/newtext/g replaces oldtext with newtext in the current file


Permissions


Permissions

Les permissions sur les fichiers sont codés sur 3 bits

- Le bit du poids le plus faible 20 pour le execute (x)
- le bit du milieu 21 pour le write (w)
- Le bit du poids fort 22 pour le read (r)

Les permissions sur un fichier sont affichées par le output de la commande ls -l

r = 1 x 22 = 4
w = 1 x 21 = 2
w = 1 x 20 = 1

Configuration

Files privilegeUsers
Read rUser Owner u
Write wGroup Owner g
Execute xOther o

First Method

Cette méthode consiste à ajouter ou à supprimer des permissions

[root@lab ~]# chmod user+privilege file ajouter un privilege
[root@lab ~]# chmod user-privilege file retirer un privilege

NB: les privileges peuvent etre associés comme suit rw, rx,wx, rwx

Exemple
[root@lab ~]# chmod u+wx,g-w,o-wx /home/content.txt

Second Method



[root@lab ~]# chmod ugo file
u represents user total
g represents group total
o represents other total
exple chmod 777 file
[+]

UMASK

The setting which determines what permissions are applied to a newly created file or directory
is called a umask and is configured in the /etc/.bashrc file

Displaying umask

[root@lab ~]# umask Display umask value
by default
umask=002 for users
umask=022 for root

[root@lab ~]# umask
0002

A breakdown of the output:
• The first 0 indicates that the umask is given as an octal number.
• The second 0 indicates which permissions to subtract from the default user owner's permissions.
• The third 0 indicates which permissions to subtract from the default group owner's permissions.
• The last number 2 indicates which permissions to subtract from the default other's permissions.

Default Permissions Determination

We can determine directories and files default permissions using umask value

Method 1
777 - umask = abc directories default access rights
abc - klm = xyz files default access rights

k =1 si a est impair et k= 0 si a est pair
l =1 si b est impair et l= 0 si b est pair
m =1 si c est impair et l= 0 si c est pair

NB:Plus precisement on retire les permissions x sur les permissions des repertoires pour trouver les permissions des fichiers

Example
777 – 002 = 775 – 111 = 664
775= directories default access rights
664= files default access rights

Modify umask

[user1@lab ~]# umask value change temporary umask value Insert command in .bashrc file for permanent Modification

Ownership

chown Command [+]

[root@lab ~]# chown -option user:group fichier
[root@lab ~]# chown -option user:group répertoire/

[root@lab ~]# chown lisa myfile Sets user lisa as the owner of myfile
[root@lab ~]# chown lisa.sales myfile Sets user lisa as user owner and group sales as group owner of myfile
[root@lab ~]# chown lisa:sales myfile Sets user lisa as user owner and group sales as group owner of myfile
[root@lab ~]# chown .sales myfile Sets group sales as group owner of myfile without changing the user owner
[root@lab ~]# chown :sales myfile Sets group sales as group owner of myfile without changing the user owner


Access List


POSIX Access list

ACLs configure file system to go beyond basics files permissions ugo/rwx by exple autorise your file acces to another user
Mount a file system with ACL configuration
#mount –o remount –o acl /dev/sda3 /home
Or
Add in /etc/fstab
/dev/sda3 on /home type ext4(rw,acl)

Commands

[root@lab ~]# getfacl file show configured ACL on a file

Application
[root@lab ~]# mkdir /RH134/DIR1/File1
[root@lab ~]# getfacl /RH134/DIR1/File1

setfacl Command
[root@lab ~]# setfacl Options ugo:user:permissions file

[root@lab ~]#setfacl –m u:user:rwx file add rights for an user
[root@lab ~]#setfacl –m g:group:rwx file add rights for a group
[root@lab ~]#setfacl –m o:rwx file add rights for others. It’s equivalent to chmod o+rwx file

Options
-R apply recursively
-m modify
-b delete all acl
-x delete a specific acl

Examples

[root@redhat SCRIPTS]# setfacl -m u:user1:x /root/SCRIPTS/table2
[root@redhat SCRIPTS]# setfacl -b /root/SCRIPTS/table2
[root@redhat SCRIPTS]# getfacl table2

Mask settings show the maximum permissions possible for all named users, the group-owner and named groups.


Application

Autoriser user1 a editer le fichier/root/LAB-DIR/file1. NB il faudrait qu il ait les permissions sur /root/ et /root/LAB-DIR/

[root@redhat ~]# setfacl -m u:user1:rwx /root/
[root@redhat ~]# setfacl -m u:user1:rwx /root/LAB-DIR/
[root@redhat ~]# setfacl -m u:user1:rw /root/LAB-DIR/file1

Autoriser les membres du groupe INGENIEURS a editer le fichier/root/LAB-DIR/file1. NB il faudrait qu ils aient les permissions sur /root/ et /root/LAB-DIR/

[root@redhat ~]# setfacl -m g:INGENIEURS:rwx /root/
[root@redhat ~]# setfacl -m g:INGENIEURS:rwx /root/LAB-DIR/
[root@redhat ~]# setfacl -m g:INGENIEURS:rw /root/LAB-DIR/file1

Delete all ACl on file2

[root@redhat ~]# setfacl -b LAB-DIR/file2
[root@redhat ~]# getfacl LAB-DIR/file2

Delete specific ACL

[root@redhat ~]# setfacl -x g:INGENIEURS /root/LAB-DIR/file3
[root@redhat ~]# getfacl LAB-DIR/file3


[root@redhat SCRIPTS]# ls -la
total 20
drwxr-xr-x. 2 root root   55 Mar 26 11:33 .
dr-xr-x---. 7 root root 4096 Mar 21 22:29 ..
-rwxrwxrwx. 1 root root  182 Mar 21 22:55 table
-rwxrwxrwx+ 1 root root  163 Mar 26 11:33 table2
-rw-r--r--. 1 root root    0 Mar 21 23:59 test
-rwxrwxrwx. 1 root root  102 Mar 22 00:16 testor



The "+" symbol indicates that there is an configured ACL


SSH


Secure Shell (SSH)


Accessing remote prompt

Secure Shell (SSH)

Authentication Methods

  1. Password Authentication
  2. SSH Key-based Authentication without passphrase
  3. SSH Key-based Authentication with passphrase


Configuring SSH Key-based Authentication

Les utilisateurs peuvent authentifier les connexions SSH sans mot de passe en utilisant l'authentification par clé publique. Ssh permet aux utilisateurs de s'authentifier à l'aide d'un schéma de clé public-privé. Cela signifie que deux clés sont générées, une clé privée et une clé publique. Le fichier de clé privée est utilisé comme authentification, informations d'identification, et comme un mot de passe, doit être gardé secret et sécurisé. La clé publique est copiée dans les systèmes sur lesquels l'utilisateur veut se connecter, et est utilisé pour vérifier la clé privée. La clé publique n'a pas besoin d'être secrète. Un serveur SSH disposant de la clé publique peut lancer un défi qui ne peut être géré que par un système contenant votre clé privée. Par conséquent, vous pouvez vous authentifier en utilisant la présence de votre clé. Cela vous permet d'accéder aux systèmes d'une manière qui ne nécessite pas de taper un mot de passe à chaque fois, mais qui reste sécurisée.




  1. Ensure for Key Based Authentication configuration on server

    /etc/ssh/sshd_config PubkeyAuthentication yes


  2. Keys generation

    Keys generation is done using the ssh-keygen command. This generates
    • the private key ~/.ssh/id_rsa
    • the public key ~/.ssh/id_rsa.pub
    You can generate keys with or without passphrase. Generate keys without passphrase is useful for automation actions (Just enter when prompt asks you for passphrase)

    Once the SSH keys have been generated, they are stored by default in the .ssh/ directory of your home directory. Permissions should be 600 on the private key and 644 on the public key.




  3. Check your keys

    Comparer les empreintes des clés
    Pour confirmer qu'une clé publique est valide et correspond à une clé privée, comparez leurs empreintes :

    - Empreinte de la clé privée
    # ssh-keygen -lf ~/.ssh/id_rsa

    - Empreinte de la clé publique
    # ssh-keygen -lf ~/.ssh/id_rsa.pub

    Si les empreintes sont identiques, la clé privée correspond bien à la clé publique.


  4. Copy key to SSH Server system user

    Before key-based authentication can be used, the public key needs to be copied to the Destination system. This can be done with ssh-copy-id.

    # ssh-copy-id remote-user@remote-host
    When the key is copied to another system using ssh-copy-id, it copies the ~/.ssh/id_rsa.pub file by default.

    On Server authorized connections keys are stored in ~/.ssh/authorized_keys file


  5. Initiate your ssh connection

    # ssh remote-user@remote-host -i pub_key_file

Customizing SSH Service Configuration

The OpenSSH server configuration file

While Open SSH server configuration usually does not require modification, additional security measures are available.
Various aspects of the Open SSH server can be modified in the configuration file /etc/ssh/sshd_config.

Prohibit the root user from logging in using SSH

From a security stand point. It is advisable to prohibit the root user from directly logging in to the system with ssh.
The user name root exists on every Linux system by default, so a potential attacker only has to guess the password, instead of a valid username and password combination.
The root user has unrestricted privileges.

PermitRootLogin no

Prohibit password authentication using SSH

Only allowing key-based logins to the remote command line has various advantages:

  • SSH keys are longer than an average password, which adds security.
  • Less effort to initiate remote shell access after the initial setup.
To prevent password authentication, the PasswordAuthentication option has to be set to no and the ssh service needs to be restarted
PasswordAuthentication no



Firewall


Red hat firewall

If a server is connected to the Internet, it needs to be protected against unauthorized access. SELinux is one part of this protection, and a firewall is the second part. The Linux kernel implements firewalling via the netfilter framework. To configure which packets are allowed and which are not, firewalld is the default solution in RHEL 7.

Firewalld was developed as a complete new solution for managing Linux firewalls. It uses the firewalld service to manage the netfilter firewall configuration. The firewalld service is incompatible with the iptables service. Do not ever use firewalld and iptables on the same system; they are mutually exclusive.

The RHCSA objective does not define which tool you should use to create firewall rules. It just mentions that you should be able to create firewall rules by using iptables, firewall-config, or firewall-cmd. So, you do not have to be able to work with each of these tools; you just have to be able to configure a firewall with the tool that works best for you.

Understanding Firewalld Zones

Firewalld is making firewall management easier by working with zones. A zone is a collection of rules that are applied to incoming packets matching a specific source address or network interface. Firewalld applies to incoming packets only by default, and no filtering is happening on outgoing packets.

The use of zones is particularly important on servers that have multiple interfaces. On such servers, zones allow administrators to easily assign a specific set of rules. On servers that have just one network interface, you might very well do with just one zone, which is the default zone. Every packet that comes into a system is analyzed for its source address, and based on that source address, firewalld analyzes to see whether the packet belongs to a specific zone. If that is not the case, the zone for the incoming network interface is used. If no specific zone is available, the packet is handled by the settings in the default zone.


Rules editing

Firewall GUI tool

#system-config-firewall

Firewalld Default Zones

Default Zones List :    Block     |     Dmz     |     Drop     |     External     |     Home     |     Internal     |     Public     |     trusted     |     work

Zone name Default Settings

Block Incoming network connections are rejected with an “icmp-host-prohibited” message. Only network connections that were initiated on this system are allowed.

Dmz For use on computers in the demilitarized zone. Only selected incoming connections are accepted, and limited access to the internal network is allowed.

Drop Any incoming packets are dropped and there is no reply.

External For use on external networks with masquerading (Network Address Translation [NAT]) enabled, used especially on routers. Only selected incoming connections are accepted.

Home For use with home networks. Most computers on the same network are trusted, and only selected incoming connections are accepted.

Internal For use in internal networks. Most computers on the same network are trusted, and only selected incoming connections are accepted.

Public For use in public areas. Other computers in the same network are not trusted, and limited connections are accepted. This is the default zone for all newly created network interfaces.

trusted All network connections are accepted.

work For use in work areas. Most computers on the same network are trusted, and only selected incoming connections are accepted.


Firewalld Zones

/usr/lib/firewalld/zones/
/etc/firewalld/zones/

Listing Zones

To see which zones are available on your system:

[root@lab ~]# firewall-cmd --get-zones
displays all zones that are available on the system, but it does not show any details for particular zones.

[root@lab ~]# firewall-cmd --list-all-zones To see detailed information for all zones

[root@lab ~]# firewall-cmd --zone=zone-name --list-all To see detailed information for a specific zone

The Default Zone

The Default Zone is the zone affected to unconfigured interfaces. By default, the default zone is "public". It's possible to change the default zone.

[root@lab ~]# firewall-cmd --get-default-zone Display the current default zone

[root@lab ~]# firewall-cmd --set-default-zone zone-name Set up the default zone

Assigning a Network Interface to a Zone

To assign the zone to a specific interface:
1. List the active zones and the interfaces assigned to them:
[root@lab ~]# firewall-cmd --get-active-zones

2. Assign the interface to a different zone:
[root@lab ~]# firewall-cmd --zone=zone-name --change-interface=interface-name

Assigning a Default Zone to a Network Connection

To set a default zone for an Internet connection, use either the NetworkManager GUI or edit the /etc/sysconfig/network-scripts/ifcfg-connection-name file and add a line that assigns a zone to this connection:

ZONE=zone-name

Creating a New Zone

To create a new zone:

[root@lab ~]# firewall-cmd --new-zone=zone-name --permanent
[root@lab ~]# systemctl restart firewalld.service
[root@lab ~]# firewall-cmd --get-zones


Firewalld Services

The second key element while working with firewalld is the service. Note that a service in firewalld is not the same as a service in systemd. In firewalld, some default services are defined, which allows administrators to easily allow or deny access to specific ports on a server.

Behind each service is a configuration file that explains which UDP or TCP ports are involved, and if so required, which kernel modules must be loaded. To get a list of all services available on your computer, you can use the command firewall-cmd --get-services .



✔ List of All Available Services

[root@redhat ~]# firewall-cmd --get-services

✔ Allow Traffic for a service

[root@redhat ~]# firewall-cmd --add-service service_name --permanent
[root@redhat ~]# firewall-cmd --add-service ftp --permanent
[root@redhat ~]# firewall-cmd --add-service ftp --zone=public --permanent
[root@redhat ~]# firewall-cmd --add-service=ssh --zone=public
[root@redhat ~]# firewall-cmd --reload

Services Files

Service files are stored in the directory /usr/lib/firewalld/services or /etc/firewalld/services.

Contents of the ftp Service File


Firewalld Services
Change runtime settings and then make them permanent as follows:
~]# firewall-cmd
~]# firewall-cmd --runtime-to-permanent

It is possible, especially on remote systems, that an incorrect setting results in a user locking themselves out of a machine. To prevent such situations, use the --timeout option. After a specified amount of time, any change reverts to its previous state. Using this options excludes the --permanent option.

For example, to add the SSH service for 15 minutes:
~]# firewall-cmd --add-service=ssh --timeout 15m

[root@localhost user1]# firewall-cmd --list-all
public (active)
target: default
icmp-block-inversion: no
interfaces: ens33
sources:
services: ssh dhcpv6-client
[root@lab ~]# firewall-cmd --list-all --zone=home
[root@lab ~]# firewall-cmd –help
[root@lab ~]# firewall-cmd --list-services
[root@lab ~]# firewall-cmd --list-services --zone=public

Disabling All Traffic in Case of Emergency using CLI

In an emergency situation, such as a system attack, it is possible to disable all network traffic and cut off the attacker.

[root@lab ~]# firewall-cmd --panic-on To immediately disable networking traffic, switch panic mode on

[root@lab ~]# firewall-cmd --panic-off Switching off panic mode reverts the firewall to its permanent settings.

[root@lab ~]# firewall-cmd --query-panic To see whether panic mode is switched on or off

Allow Traffic on ports:

✔ List all allowed ports

[root@lab ~]# firewall-cmd --list-ports

✔ Add a port to the allowed ports to open it for incoming traffic:Allow traffic on a port

[root@lab ~]# firewall-cmd --add-port=port_number/port_type
[root@lab ~]# firewall-cmd --add-port=80/tcp
[root@lab ~]# firewall-cmd --add-port=53/udp

[root@lab ~]# firewall-cmd --runtime-to-permanent Make the new settings persistent

The port types are either tcp, udp, . The type must match the type of network communication.


SELINUX


Introduction

Since the earliest days of Linux, file permissions have been the standard method of securing Linux systems. In some cases, file permissions are just not enough for getting a secured server. Let’s take a look at an example:

One morning I found out that my server was hacked. An intruder had broken through a bad script on my web server and had obtained shell access as the httpd user. Using this file access, he managed to create thousands of little PHP scripts that were involved in a massive DDoS attack.

From a security perspective, it is interesting that nothing really was wrong with the security settings on this server. All permissions were set in a decent way, and the httpd user, like any other user on a Linux server, does have permissions to create files in /var/tmp, as in /tmp. So, what would have been a good solution to prevent this kind of problem?

You could, of course, argue that the administrator of the web server should have been doing a better job and should have been watching what the scripts on the server were doing. But that is not how Linux servers are normally used. The Linux server administrator does not know all the applications running on his server, and the application administrator does not understand enough about Linux to ensure that something like this can never happen.

Another solution is to apply further security measures. For instance, this specific situation would have been prevented if the permission to run program files from the /tmp and /var/tmp directory would have been taken away by using the noexec mount option. But even if that would have worked for this specific situation, it is not a good overall security solution that prevents applications from doing things they are not supposed to be doing.

That is why SELinux was invented. SELinux provides mandatory access control to a Linux server, where every system call is denied unless it has been specifically allowed. This chapter explains how to use SELinux to make sure that serious security incidents will never happen on your server.

Security Enhanced Linux (SELinux)

Understanding SELinux Working and Modes

If SELinux is enabled and nothing else has been configured, all system calls are denied. To specify what exactly is allowed, a policy is used. In this policy, rules define which source domain is allowed to access which target domain.

The source domain is the object that is trying to access something. Typically, this is a process or a user.

The target domain is the object that is accessed. Typically, that is a file, directory, or a network port to define exactly what is allowed; context labels are used. Using these labels is the essence of SELinux because these labels are used to define access rules.

SELinux Core Elements

Policy

A collection of rules that define which source has access to which target.

Source domain

The object that is trying to access a target. Typically a user or a process.

Target domain

The thing that a source domain is trying to access. Typically a file or port.

Context

A security label that is used to categorize objects in SELinux.

Rule

A specific part of the policy that determines which source domain has which access permissions to which target domain.

Labels

Same as context label, defined to determine which source domain has access to which target domain.

On a Linux system, you can choose to enable or disable SELinux. When SELinux is enabled, kernel support for SELinux is loaded, and some applications that are SELinux aware change their behavior, because specific libraries are used on a system that has SELinux enabled. If SELinux is disabled, no SELinux activity will be happening at all. Changing between SELinux enabled and SELinux disabled mode requires a reboot of your system. This is because SELinux is a feature that is deeply interwoven with the Linux kernel.

If on a system SELinux is enabled, you can select to put SELinux in enforcing mode or in permissive mode. In enforcing mode, SELinux is fully operational and enforcing all SELinux rules in the policy. If SELinux is in permissive mode, all SELinuxrelated activity is logged, but no access is blocked. This makes SELinux permissive mode an excellent mode to do troubleshooting. Permissive mode is also a great way to do something and see the result from an SELinux perspective. That can help in building new and more efficient policies.

Principe

SELinux (Security Enhanced Linux) est un système de contrôle d’accès obligatoire (Mandatory Access Control) qui s’appuie sur l’interface Linux Security Modules fournie par le noyau Linux. Concrètement, le noyau interroge SELinux avant chaque appel système pour savoir si le processus est autorisé à effectuer l’opération concernée.

SELinux s’appuie sur un ensemble de règles (policy) pour autoriser ou interdire une opération. Ces règles sont assez délicates à créer, mais heureusement deux jeux de règles standards (targeted et strict) sont fournies pour éviter le plus gros du travail de configuration.

SELinux security Concept

Security Enhanced Linux (SELinux) is an additional layer of system security. A primary goal of SELinux is to protect user data from system services that have been compromised.

Configuration files and directories

/etc/selinux/ SELinux configuration directory
/selinux/ rules boolean values directory
/etc/sysconfig/selinux SELinux modes configuration file
/var/log/audit/ permissive mode rules violation logs directory
/var/log/audit/audit.log SELinux logfile

SELinux context

  • Identity : Identité de celui qui lance le processus
  • Rôle de l’identité
  • Domaine ou type
NB:
- Type attribué aux objets (files, program, )
- Domaine attribué aux sujets (processus)

SELinux Identities

guest_u no GUI no networking, no access to su and sudo commands
xguest_u GUI, networking only via firefox
user_u GUI and networking available
unconfined_u full system access

SELinux Running Modes

Enforcing active mode avec les règles en vigueur
Permissive active mode mais les règles ne sont pas en vigueur
Disabled desactive le mode

Commands

[root@lab ~]# getenforce show mode
[root@lab ~]# sestatus show mode with detailed infos. show SELinux status
[root@lab ~]# sestatus -v shows detailed information about the current status of SELinux on a server
[root@lab ~]# setenforce permissive puts SELinux in permissive mode
[root@lab ~]# setenforce enforcing puts SELinux in enforcing mode
[root@lab ~]# setenforce 0 puts SELinux in permissive mode
[root@lab ~]# setenforce 1 puts SELinux in enforcing mode.

semanage command

Installation

semanage command provided by policycoreutils-python Package

[root@sun yum.repos.d]# yum install *policycoreutils-python*

Commands

[root@lab ~]# semanage login -l liste les correspondances existantes entre identifiants d’utilisateurs et identités SELinux. Si un utilisateur n’a pas de correspondance explicite, il aura l’identité indiquée en face de __default__.

[root@lab ~]# semanage login -a -s user_u utilisateur va associer l’identité user_u à l’utilisateur.

[root@lab ~]# semanage login -a -s xguest_u utilisateur va associer l’identité xguest_u à l’utilisateur.

[root@lab ~]# semanage login -d utilisateur va retirer la correspondance affectée à l’utilisateur.

Example [root@lab ~]# semanage login -a -s xguest_u user2
va associer l’identité xguest_u à l’utilisateur user2.

Faire logout, se connecter avec user2
faire ping 127.0.0.1 ca va pas passer
ouvrir firefox et aller sur une page

Chaque module SELinux fournit un ensemble de règles d’étiquetage des fichiers mais il est également possible de rajouter des règles d’étiquetage spécifiques afin de les adapter à un cas particulier. Ainsi pour rendre toute l’arborescence /srv/www/ accessible au serveur web on pourrait exécuter

[root@lab ~]# semanage fcontext -a -t httpd_sys_content_t "/srv/www(/.*)?" puis
[root@lab ~]# restorecon -R /srv/www/.

La première commande enregistre la nouvelle règle d’étiquetage et la deuxième restaure les bonnes étiquettes en fonction des règles enregistrées. D’une manière similaire, les ports TCP/UDP sont étiquetés afin que seuls les démons correspondants puissent y écouter. Ainsi, si l’on veut que le serveur web puisse également écouter sur le port 8080, il faut exécuter la commande

[root@lab ~]# semanage port -m -t http_port_t -p tcp 8080

chcon Command

Commands

[root@lab ~]# chcon –R - -reference=directory1 directory2
attributes directory1 SELinux context to directory2 (R defines recursive)

Exercise: Manipulating SELinux Modes

1. Open a root console on your server and type getenforce . You’ll normally see that SELinux is in enforcing mode.

2. Type setenforce 0 and type getenforce again. SELinux now switches to permissive mode.

3. Open the file /etc/sysconfig/selinux with an editor and change the line SELINUX= so that it reads SELINUX=disabled . Reboot your server.

4. After rebooting, log in to a root shell again and type getenforce . You’ll see that SELinux is now in disabled mode.

5. Try using the command setenforce 1 . You’ll see the message “setenforce: SELinux is disabled.” You cannot switch between disabled and enforcing mode without rebooting your server.

6. Open the file /etc/sysconfig/selinux again and change the line SELINUX=disabled back to SELINUX=enforcing . Reboot your system again.

7. After rebooting, type sestatus -v and read current status information about SELinux.

Exercise 21.2 Setting a Context Label on a Nondefault Apache Document Root

1. Open a root shell and type yum install httpd elinks –y .

2. Still from the root shell, type mkdir /web .

3. Type vim /web/index.html and put the following contents in the file: welcome to my web server .

4. Type vim /etc/httpd/conf/httpd.conf to open the Apache configuration file and find the DocumentRoot parameter. Change it so that it reads DocumentRoot “/web” .

5. In the same httpd.conf configuration file, add the following section:
<Directory "/web">
AllowOverride None
Require all granted
</Directory>

6. Type systemctl restart httpd; systemctl enable httpd to start and enable the httpd service.

7. Type elinks http://localhost . You’ll see the default Red Hat web page and not the contents of the index.html file you have just created.

8. Type setenforce 0 to switch SELinux to permissive mode.

9. Repeat Step 7. You’ll now get access to your custom web page, which proves that SELinux was doing something to block access.

10. Type semanage fcontext -a -t httpd_sys_content_t "/web(/.*)?" to apply the new context label to /web.

11. Type restorecon -R -v /web . The -v (verbose) option ensures that you see what is happening and that you will see the new context being applied to /web.

12. Set SELinux back in enforcing mode, using setenforce 1 .

13. Type elinks http://localhost . You’ll now get access to your custom web page.


Secure and Troubleshoot Boot


Resetting the Root Password

A common scenario for a Linux administrator is that the root password has gone missing. If that happens, you need to reset it. The only way to do that is by booting into minimal mode, which allows you to log in without entering a password. To do so, follow these steps:

1. On system boot, press e when the GRUB 2 boot menu is shown.

2. Enter rd.break as boot argument to the line that loads the kernel and press Ctrl+X to boot with this option.

3. You’ll now be dropped at the end of the boot stage where initramfs is loaded, just before a mount of the root file system on the directory /.

4. Type mount -o remount,rw /sysroot to get read/write access to the system image.

5. At this point, make the contents of the /sysimage directory your new root directory by typing chroot /sysroot .

6. Now you can enter passwd and set the new password for the user root.

7. Because at this very early boot stage SELinux has not been activated yet, the context type on /etc/shadow will be messed up. If you reboot at this point, no one will be able to log in. So you must make sure that the context type is set correctly. To do this, at this point you should load the SELinux policy by using load_policy -i .

8. Now you can manually set the correct context type to /etc/shadow. To do this, type chcon -t shadow_t /etc/shadow .

9. Reboot. You can now log in with the changed password for user root. systemctl reboot


PROTECTING GRUB 2 WITH A PASSWORD

GRUB 2 offers two types of password protection:
  • Password is required for modifying menu entries but not for booting existing menu entries;
  • Password is required for modifying menu entries and for booting one, several, or all menu entries.

Configuring GRUB 2 to Require a Password only for Modifying Entries

To require password authentication for modifying GRUB 2 entries, follow these steps: Run the grub2-setpassword command as root:

[root@lab ~]# grub2-setpassword
Enter and confirm the password:
Enter password:
Confirm password:

Following this procedure creates a /boot/grub2/user.cfg file that contains the hash of the password. The user for this password, root, is defined in the /boot/grub2/grub.cfg file. With this change, modifying a boot entry during booting requires you to specify the root user name and your password.


Configuring GRUB 2 to Require a Password for Modifying and Booting Entries (RHEL 7)

Setting a password using the grub2-setpassword prevents menu entries from unauthorized modification but not from unauthorized booting. To also require password for booting an entry, follow these steps after setting the password with grub2-setpassword: Warning If you forget your GRUB 2 password, you will not be able to boot the entries you reconfigure in the following procedure.

Open the /boot/grub2/grub.cfg file.

Find the boot entry that you want to protect with password by searching for lines beginning with menuentry. Delete the --unrestricted parameter from the menu entry block, for example:
menuentry 'Red Hat Enterprise Linux Server (3.10.0-327.18.2.rt56.223.el7_2.x86_64) 7.2 (Maipo)' --class red --class gnu-linux --class gnu --class os --unrestricted $menuentry_id_option 'gnulinux-3.10.0-327.el7.x86_64-advanced-c109825c-de2f-4340-a0ef-4f47d19fe4bf' {
        load_video
        set gfxpayload=keep

Save and close the file.
Now even booting the entry requires entering the root user name and password.
Note

Manual changes to the /boot/grub2/grub.cfg persist when new kernel versions are installed, but are lost when re-generating grub.cfg using the grub2-mkconfig command. Therefore, to retain password protection, use the above procedure after every use of grub2-mkconfig.

Note

If you delete the --unrestricted parameter from every menu entry in the /boot/grub2/grub.cfg file, all newly installed kernels will have menu entry created without --unrestricted and hence automatically inherit the password protection. Passwords Set Before Updating to Red Hat Enterprise Linux 7.2

The grub2-setpassword tool was added in Red Hat Enterprise Linux 7.2 and is now the standard method of setting GRUB 2 passwords. This is in contrast to previous versions of Red Hat Enterprise Linux, where boot entries needed to be manually specified in the /etc/grub.d/40_custom file, and super users - in the /etc/grub.d/01_users file.

Additional GRUB 2 Users

Booting entries without the --unrestricted parameter requires the root password. However, GRUB 2 also enables creating additional non-root users that can boot such entries without providing a password. Modifying the entries still requires the root password. For information on creating such users, see the GRUB 2 Manual.


Open LDAP


Lightweight Directory Access Protocol (LDAP)

LDAP (Lightweight Directory Access Protocol ; http://www.openldap.org)

Les Annuaires sont des Bases de Données particulières spécialisées dans la recherche de l'information, pas dans le traitement

Évolutivité : on peut facilement ajouter des informations à un objet d'un annuaire (structure et contenu)

La dernière version LDAPv3 propose chiffrement (SSL, ...) et authentification (SASL) pour sécuriser l'accès aux informations

OpenLDAP est un annuaire dérivé de LDAP de l'Université du Michigan

Un annuaire permet de stocker des données typées,

- organisées selon des classes particulières
- présentées dans un arbre.

L'exemple le plus commun est l'annuaire de personnes Mais on peut stocker bien d'autres choses : - comptes Unix,
- données personnelles (carnet d'adresses, photos, etc.),
- données d'identification,
- certificats ...
... plus généralement tout ce qui peut être nommé et à qui on peut attacher des informations.


Un client ouvre une session LDAP sur le port TCP 389 du serveur.

Le client envoie des requêtes au serveur qui envoie des réponses en retour.

Une fois la connexion au serveur établie, les opérations classiques sont :

- Bind : indique la version du protocole utilisée, et authentifie l'utilisateur.
- Start TLS : utilisation Transport Layer Security pour sécuriser la connexion
o Search : recherche dans l'annuaire et rapatriement des données ;
o Compare : test si une entrée contient un attribut avec une valeur donnée
o Add : ajout d'une nouvelle entrée ;
o Delete : suppression d'une entrée ;
o Modify : modification d'une entrée ;
o Modify DN : déplacement ou renommage d'une entrée ;
o Abandon : annulation d'une requête précédente ;
o Extended : permet de définir d'autres opérations ;
- Unbind : clôture la connexion.

Packets
openldapservers2.3.6
openldap-clients
fournit les commandes : ldapadd, ldapdelete, ldapmodify, ldapsearch, ...

nss_ldap
fournit l'interfaçage entre LDAP et le Name Service Switch (fichier /etc/nsswitch)

pam_ldap
fournit l'interfaçage entre LDAP et le Linux-PAM - (Module d'authentification pour Linux)

Configuration Files

/etc/logrotate.d/ldap
/etc/openldap
/etc/openldap/DB_CONFIG.example
/etc/openldap/schema
/etc/openldap/schema/local.schema
/etc/openldap/slapd.access.conf
/etc/openldap/slapd.conf

Eninam BAGNABANA     |         |     bagnadavid@outlook.fr     |