Ceci est une ancienne révision du document !


Table des matières

Version : 2022.01

Dernière mise-à-jour : 2022/10/12 08:51

Topic 6: Networking Configuration

  • Topic 6: Networking Configuration
    • Configuration du Réseau sous Debian 6
      • Configuration de TCP/IP
        • /etc/network/interfaces
        • DHCP
        • IP Fixe
      • La Commande hostname
      • La Commande ifconfig
      • Activer/Désactiver une Interface Manuellement
      • /etc/networks
      • Résolution d'adresses IP
        • /etc/resolv.conf
        • /etc/nsswitch.conf
        • /etc/hosts
    • Configuration du Réseau sous Debian 11
      • 1.1 - Connections et Profils
      • 1.2 - Résolution des Noms
      • 1.3 - Ajouter une Deuxième Adresse IP à un Profil
      • 1.4 - La Commande hostname
      • 1.5 - La Commande ip
      • 1.6 - Activer/Désactiver une Interface Manuellement
      • 1.7 - Routage Statique
        • La commande ip
        • Activer/désactiver le routage sur le serveur
    • LAB #2 - Diagnostique du Réseau
      • 2.1 - ping
      • 2.2 - netstat -i
      • 2.3 - traceroute
    • LAB #3 - Connexions à Distance
      • 3.1 - Telnet
      • 3.2 - wget
      • 3.3 - ftp
      • 3.4 - SSH
        • Présentation
          • SSH-1
          • SSH-2
        • Authentification par mot de passe
        • Authentification par clef asymétrique
        • Configuration du Serveur
        • Configuration du Client
        • Tunnels SSH
      • 3.5 - SCP
        • Présentation
        • Utilisation
      • 3.6 - Mise en Place des Clefs Asymétriques
      • 3.7 - Services réseaux
        • inetd
        • TCP Wrapper
    • Configuration du Réseau sous RHEL/CentOS 6
      • Configuration de TCP/IP
        • DHCP
          • /etc/sysconfig/network
          • /etc/sysconfig/network-scripts/ifcfg-ethX (où X=0,1 …)
        • IP Fixe
          • /etc/sysconfig/network
          • /etc/sysconfig/network-scripts/ifcfg-ethX (où X=0,1 …)
        • La Commande hostname
        • La Commande ifconfig
        • Activer/Désactiver une Interface Manuellement
        • /etc/networks
        • Résolution d'adresses IP
          • /etc/resolv.conf
          • /etc/nsswitch.conf
          • /etc/hosts
        • Services réseaux
          • xinetd
          • TCP Wrapper
        • Routage Statique
          • La Commande route
          • Activer/désactiver le routage sur le serveur
    • Configuration du Réseau sous RHEL/CentOS 7
      • La Commande nmcli
      • Connections et Profils
      • Ajouter une Deuxième Adresse IP à un Profil
      • La Commande hostname
      • La Commande ip
      • Activer/Désactiver une Interface Manuellement
      • Routage Statique
        • La commande ip
        • Activer/désactiver le routage sur le serveur
      • LAB #4 - Utilisation de nmap et de netcat
        • 4.1 - nmap
          • Installation
          • Utilisation
          • Fichiers de Configuration
          • Scripts
        • 4.2 - netcat
          • Utilisation
      • LAB #5 - Utilisation de tcpdump
        • 5.1 - Utilisation
          • L'option -i
          • L'option -x
          • L'option -X
          • L'option -w
          • L'option -v
        • 5.2 - Filtrage à l'écoute
      • LAB #6 - Mise en place d'un VPN avec OpenVPN
        • Présentation
        • Configuration commune au client et au serveur
        • Configuration du client
        • Configuration du serveur
        • Tests
          • Du client vers le serveur
          • Du serveur vers le client
    • Annexe #1 - Comprendre les Réseaux
      • Présentation des Réseaux
      • Classification des Réseaux
        • Classification par Mode de Transmission
        • Classification par Topologie
          • La Topologie Physique
          • La Topologie en Ligne
          • La Topologie en Bus
          • La Topologie en Étoile
          • La Topologie en Anneau
          • La Topologie en Arbre
          • La Topologie Maillée
        • Classification par Étendue
        • Les Types de LAN
          • Réseau à Serveur Dédié
          • Réseau Poste-à-Poste
      • Le Modèle Client/Serveur
      • Modèles de Communication
        • Le modèle OSI
          • Les Couches
          • Les Protocoles
          • Les Interfaces
          • Protocol Data Units
          • Encapsulation et Désencapsulation
        • Spécification NDIS et le Modèle ODI
        • Le modèle TCP/IP
      • Les Raccordements
        • Les Modes de Transmission
        • Les Câbles
          • Le Câble Coaxial
          • Le Câble Paire Torsadée
          • Catégories de Blindage
          • La Prise RJ45
          • Channel Link et Basic Link
          • La Fibre Optique
        • Les Réseaux sans Fils
        • Le Courant Porteur en Ligne
      • Technologies
        • Ethernet
        • Token-Ring
      • Périphériques Réseaux Spéciaux
        • Les Concentrateurs
        • Les Répéteurs
        • Les Ponts
          • Le Pont de Base
          • Le Pont en Cascade
          • Le Pont en Dorsale
        • Les Commutateurs
        • Les Routeurs
        • Les Passerelles
    • Annexe #2 - Comprendre TCP Version 4
      • En-tête TCP
      • En-tête UDP
      • Fragmentation et Ré-encapsulation
      • Adressage
      • Masques de sous-réseaux
      • VLSM
      • Ports et sockets
      • /etc/services
      • Résolution d'adresses Ethernet
    • Annexe #3 - Comprendre le Chiffrement
      • Introduction à la cryptologie
        • Définitions
          • La Cryptographie
          • Le Chiffrement par Substitution
      • Algorithmes à clé secrète
        • Le Chiffrement Symétrique
      • Algorithmes à clef publique
        • Le Chiffrement Asymétrique
        • La Clef de Session
      • Fonctions de Hachage
      • Signature Numérique
      • LAB #1 - Utilisation de GnuPG
        • Présentation
        • Installation
        • Configuration
        • Signer un message
        • Chiffrer un message
      • PKI
        • Certificats X509

Configuration de TCP/IP sous Debian 6

La configuration TCP/IP se trouve dans le fichier /etc/network/interfaces :

DHCP

/etc/network/interfaces

root@debian6:~# cat /etc/network/interfaces
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).

# The loopback network interface
auto lo
iface lo inet loopback

# The primary network interface
allow-hotplug eth0
#NetworkManager#iface eth0 inet dhcp

Dans ce fichier chaque déclaration est de la forme suivante :

interface   nom    type    mode

On peut constater donc dans notre exemple ci-dessus :

  • une déclaration pour l'interface lo de loopback
  • une déclaration pour l'interface eth0 en dhcp

IP Fixe

Dans le cas où l'interface eth0 était configuré en IP statique, la déclaration concernant eth0 prendrait la forme suivante :

auto eth0
iface eth0 inet static
        address 10.0.2.15
        netmask 255.255.255.0
        broadcast 10.0.2.255
        network 10.0.2.0
        gateway 10.0.2.2

Dans ce fichier vous pouvez constater les directives suivantes :

Directive Description
address Indique l'adresse IPv4 de l'interface
netmask Indique le masque de sous-réseau IPv4
broadcast Indique l'adresse de diffusion IPv4
network Indique l'adresse réseau IPv4
gateway Indique l'adresse IPv4 de la passerelle par défaut

Notez que VirtualBox fournit une passerelle par défaut ( 10.0.2.2 ).

Après avoir modifier le fichier /etc/network/interfaces vous devez arrêter le service network-manager utilisé pour la connexion DHCP et activer le service networking :

root@debian6:~# service network-manager stop
Stopping network connection manager: NetworkManager.
root@debian6:~# update-rc.d -f network-manager remove
update-rc.d: using dependency based boot sequencing
root@debian6:~# chkconfig --level 2345 networking on
root@debian6:~# service networking start
Configuring network interfaces...done.

Si le service networking réfuse de démarrer en produisant une erreur, le problème vient certainement du fait que votre interface réseau a été configurée par udev en eth1. La solution la plus simple est d'éditer le fichier /etc/udev/rules.d/70-persistent-net.rules en supprimant toutes les lignes qui ne commencent pas par le caractère # et de re-démarrer votre machine virtuelle.

La Commande hostname

Le nom de la machine se trouve dans le fichier /etc/hostname :

root@debian6:~# cat /etc/hostname
debian6

Ce nom doit être un FQDN (Fully Qualified Domain Name). Modifiez donc ce fichier ainsi :

root@debian6:~# cat /etc/hostname
debian6.fenestros.loc

Afin d'informer le système immédiatement de la modification du FQDN, utilisez la commande hostname :

root@debian6:~# hostname
debian6
root@debian6:~# hostname debian6.fenestros.loc
root@debian6:~# hostname
debian6.fenestros.loc

Pour afficher le FQDN du système vous pouvez également utiliser la commande suivante :

root@debian6:~# uname -n
debian6.fenestros.loc

Options de la commande hostname

Les options de cette commande sont :

root@debian6:~# hostname --help
Usage: hostname [-v] [-b] {hostname|-F file}         set host name (from file)
       hostname [-v] [-d|-f|-s|-a|-i|-y|-A|-I]             display formatted name
       hostname [-v]                                 display host name

       {yp,nis,}domainname [-v] {nisdomain|-F file}  set NIS domain name (from file)
       {yp,nis,}domainname [-v]                      display NIS domain name

       dnsdomainname [-v]                            display dns domain name

       hostname -V|--version|-h|--help               print info and exit

Program name:
       {yp,nis,}domainname=hostname -y
       dnsdomainname=hostname -d

Program options:
    -s, --short            short host name
    -a, --alias            alias names
    -i, --ip-address       addresses for the host name
    -I, --all-ip-addresses all addresses for the host
    -f, --fqdn, --long     long host name (FQDN)
    -A, --all-fqdns        all long host names (FQDNs)
    -d, --domain           DNS domain name
    -y, --yp, --nis        NIS/YP domain name
    -b, --boot             set default hostname if none available
    -F, --file             read host name or NIS domain name from given file

Description:
   This command can get or set the host name or the NIS domain name. You can
   also get the DNS domain or the FQDN (fully qualified domain name).
   Unless you are using bind or NIS for host lookups you can change the
   FQDN (Fully Qualified Domain Name) and the DNS domain name (which is
   part of the FQDN) in the /etc/hosts file.

La Commande ifconfig

Pour afficher la configuration IP de la machine il faut saisir la commande suivante :

root@debian6:~# ifconfig
eth0      Link encap:Ethernet  HWaddr 08:00:27:2a:02:5c  
          inet adr:10.0.2.15  Bcast:10.0.2.255  Masque:255.255.255.0
          adr inet6: fe80::a00:27ff:fe2a:25c/64 Scope:Lien
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:990 errors:0 dropped:0 overruns:0 frame:0
          TX packets:580 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:1000 
          RX bytes:684107 (668.0 KiB)  TX bytes:97392 (95.1 KiB)

lo        Link encap:Boucle locale  
          inet adr:127.0.0.1  Masque:255.0.0.0
          adr inet6: ::1/128 Scope:Hôte
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:0 
          RX bytes:560 (560.0 B)  TX bytes:560 (560.0 B)

La commande ifconfig est également utilisée pour configurer une interface.

Créez maintenant une interface fictive ainsi :

root@debian6:~# ifconfig eth0:1 192.168.1.2 netmask 255.255.255.0 broadcast 192.168.1.255

Constatez maintenant le résultat :

root@debian:~# ifconfig
eth0      Link encap:Ethernet  HWaddr 08:00:27:2a:02:5c  
          inet adr:10.0.2.15  Bcast:10.0.2.255  Masque:255.255.255.0
          adr inet6: fe80::a00:27ff:fe2a:25c/64 Scope:Lien
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1013 errors:0 dropped:0 overruns:0 frame:0
          TX packets:611 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:1000 
          RX bytes:686171 (670.0 KiB)  TX bytes:100060 (97.7 KiB)

eth0:1    Link encap:Ethernet  HWaddr 08:00:27:2a:02:5c  
          inet adr:192.168.1.2  Bcast:192.168.1.255  Masque:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

lo        Link encap:Boucle locale  
          inet adr:127.0.0.1  Masque:255.0.0.0
          adr inet6: ::1/128 Scope:Hôte
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:0 
          RX bytes:560 (560.0 B)  TX bytes:560 (560.0 B)

Options de la commande ifconfig

Les options de cette commande sont :

root@debian:~# ifconfig --help
Usage:
  ifconfig [-a] [-v] [-s] <interface> [[<AF>] <address>]
  [add <adresse>[/<lg_prefixe>]]
  [del <adresse>[/<lg_prefixe>]]
  [[-]broadcast [<adresse>]]  [[-]pointopoint [<adresse>]]
  [netmask <address>]  [dstaddr <address>]  [tunnel <address>]
  [outfill <NN>] [keepalive <NN>]
  [hw <HW> <adresse>]  [metric <NN>]  [mtu <NN>]
  [[-]trailers]  [[-]arp]  [[-]allmulti]
  [multicast]  [[-]promisc]
  [mem_start <NN>]  [io_addr <NN>]  [irq <NN>]  [media <type>]
  [txqueuelen <NN>]
  [[-]dynamic]
  [up|down] ...

  <HW>=Type de matériel.
  Liste des types de matériels possibles:
    loop (Boucle locale) slip (IP ligne série) cslip (IP ligne série - VJ ) 
    slip6 (IP ligne série - 6 bits) cslip6 (IP ligne série - 6 bits VJ) adaptive (IP ligne série adaptative) 
    strip (Metricom Starmode IP) ash (Ash) ether (Ethernet) 
    tr (16/4 Mbps Token Ring) tr (16/4 Mbps Token Ring (New)) ax25 (AMPR AX.25) 
    netrom (AMPR NET/ROM) rose (AMPR ROSE) tunnel (IPIP Tunnel) 
    ppp (Protocole Point-à-Point) hdlc ((Cisco)-HDLC) lapb (LAPB) 
    arcnet (ARCnet) dlci (Frame Relay DLCI) frad (Périphériue d'accès Frame Relay) 
    sit (IPv6-dans-IPv4) fddi (Fiber Distributed Data Interface) hippi (HIPPI) 
    irda (IrLAP) ec (Econet) x25 (generic X.25) 
    eui64 (Generic EUI-64) 
  <AF>=famille d'Adresses. Défaut: inet
  Liste des familles d'adresses possibles:
    unix (Domaine UNIX) inet (DARPA Internet) inet6 (IPv6) 
    ax25 (AMPR AX.25) netrom (AMPR NET/ROM) rose (AMPR ROSE) 
    ipx (Novell IPX) ddp (Appletalk DDP) ec (Econet) 
    ash (Ash) x25 (CCITT X.25) 

Activer/Désactiver une Interface Manuellement

Deux commandes existent pour activer et désactiver manuellement une interface réseau :

root@debian6:~# ifdown eth0
root@debian6:~# ifconfig
lo        Link encap:Boucle locale  
          inet adr:127.0.0.1  Masque:255.0.0.0
          adr inet6: ::1/128 Scope:Hôte
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:0 
          RX bytes:560 (560.0 B)  TX bytes:560 (560.0 B)

root@debian6:~# ifup eth0
root@debian6:~# ifconfig
eth0      Link encap:Ethernet  HWaddr 08:00:27:2a:02:5c  
          inet adr:10.0.2.15  Bcast:10.0.2.255  Masque:255.255.255.0
          adr inet6: fe80::a00:27ff:fe2a:25c/64 Scope:Lien
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:2556 errors:0 dropped:0 overruns:0 frame:0
          TX packets:1632 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:1000 
          RX bytes:2893516 (2.7 MiB)  TX bytes:176291 (172.1 KiB)

eth0:1    Link encap:Ethernet  HWaddr 08:00:27:2a:02:5c  
          inet adr:192.168.1.2  Bcast:192.168.1.255  Masque:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

lo        Link encap:Boucle locale  
          inet adr:127.0.0.1  Masque:255.0.0.0
          adr inet6: ::1/128 Scope:Hôte
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:0 
          RX bytes:560 (560.0 B)  TX bytes:560 (560.0 B)

/etc/networks

Ce fichier contient la correspondance entre des noms de réseaux et l'adresse IP du réseau :

root@debian6:~# cat /etc/networks
default		0.0.0.0
loopback	127.0.0.0
link-local	169.254.0.0

Résolution d'adresses IP

La configuration DNS est stockée dans le fichier /etc/resolv.conf.

/etc/resolv.conf

La configuration DNS est stockée dans le fichier /etc/resolv.conf :

root@debian:~# cat /etc/resolv.conf
nameserver 8.8.8.8
nameserver 8.8.4.4

Notez que les DNS utilisés sont les serveurs DNS publics de Google.

/etc/nsswitch.conf

L'ordre de recherche des services de noms est stocké dans le fichier /etc/nsswitch.conf. Pour connaître l'ordre, saisissez la commande suivante :

root@debian6:~# grep '^hosts:' /etc/nsswitch.conf
hosts:          files mdns4_minimal [NOTFOUND=return] dns mdns4
/etc/hosts

Le mot files dans la sortie de la commande précédente fait référence au fichier /etc/hosts :

root@debian6:~# cat /etc/hosts
127.0.0.1	localhost
127.0.1.1	debian6.fenestros.loc	debian6

# The following lines are desirable for IPv6 capable hosts
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters

Pour tester le serveur DNS, deux commandes sont possibles :

root@debian6:~# nslookup www.linuxelearning.com
Server:		8.8.8.8
Address:	8.8.8.8#53

Non-authoritative answer:
www.linuxelearning.com	canonical name = linuxelearning.com.
Name:	linuxelearning.com
Address: 212.198.31.61

root@debian6:~# dig www.linuxelearning.com

; <<>> DiG 9.7.3 <<>> www.linuxelearning.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 45521
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 0

;; QUESTION SECTION:
;www.linuxelearning.com.		IN	A

;; ANSWER SECTION:
www.linuxelearning.com.	42847	IN	CNAME	linuxelearning.com.
linuxelearning.com.	60	IN	A	212.198.31.61

;; Query time: 51 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Wed May  9 15:47:18 2012
;; MSG SIZE  rcvd: 70

LAB #1 - Configuration du Réseau sous Debian 11

Debian 11 utilise Network Manager pour gérer le réseau. Network Manager est composé de deux éléments :

  • un service qui gère les connexions réseaux et rapporte leurs états,
  • des front-ends qui passent par un API de configuration du service.

Important : Notez qu'avec cette version de NetworkManager, IPv6 est activée par défaut.

Le service NetworkManager doit toujours être lancé :

root@debian11:~# systemctl status NetworkManager.service
● NetworkManager.service - Network Manager
     Loaded: loaded (/lib/systemd/system/NetworkManager.service; enabled; vendor pres>
     Active: active (running) since Sun 2022-05-01 18:00:05 CEST; 20h ago
       Docs: man:NetworkManager(8)
   Main PID: 499 (NetworkManager)
      Tasks: 3 (limit: 4632)
     Memory: 13.3M
        CPU: 1.811s
     CGroup: /system.slice/NetworkManager.service
             └─499 /usr/sbin/NetworkManager --no-daemon

May 01 18:00:05 debian11 NetworkManager[499]: <info>  [1651420805.4957] device (ens18>
May 01 18:00:05 debian11 NetworkManager[499]: <info>  [1651420805.5102] device (ens18>
May 01 18:00:05 debian11 NetworkManager[499]: <info>  [1651420805.5136] device (ens18>
May 01 18:00:05 debian11 NetworkManager[499]: <info>  [1651420805.5141] device (ens18>
May 01 18:00:05 debian11 NetworkManager[499]: <info>  [1651420805.5147] manager: Netw>
May 01 18:00:05 debian11 NetworkManager[499]: <info>  [1651420805.5157] manager: Netw>
May 01 18:00:05 debian11 NetworkManager[499]: <info>  [1651420805.5159] policy: set '>
May 01 18:00:05 debian11 NetworkManager[499]: <info>  [1651420805.6555] device (ens18>
May 01 18:00:05 debian11 NetworkManager[499]: <info>  [1651420805.6577] manager: Netw>
May 01 18:00:05 debian11 NetworkManager[499]: <info>  [1651420805.6604] manager: star>
lines 1-21/21 (END)
[q]

La commande nmcli (Network Manager Command Line Interface) est utilisée pour configurer NetworkManager.

Les options et les sous-commandes peuvent être consultées en utilisant les commandes suivantes :

root@debian11:~# nmcli help
Usage: nmcli [OPTIONS] OBJECT { COMMAND | help }

OPTIONS
  -a, --ask                                ask for missing parameters
  -c, --colors auto|yes|no                 whether to use colors in output
  -e, --escape yes|no                      escape columns separators in values
  -f, --fields <field,...>|all|common      specify fields to output
  -g, --get-values <field,...>|all|common  shortcut for -m tabular -t -f
  -h, --help                               print this help
  -m, --mode tabular|multiline             output mode
  -o, --overview                           overview mode
  -p, --pretty                             pretty output
  -s, --show-secrets                       allow displaying passwords
  -t, --terse                              terse output
  -v, --version                            show program version
  -w, --wait <seconds>                     set timeout waiting for finishing operations

OBJECT
  g[eneral]       NetworkManager's general status and operations
  n[etworking]    overall networking control
  r[adio]         NetworkManager radio switches
  c[onnection]    NetworkManager's connections
  d[evice]        devices managed by NetworkManager
  a[gent]         NetworkManager secret agent or polkit agent
  m[onitor]       monitor NetworkManager changes

1.1 - Connections et Profils

NetworkManager inclus la notion de connections ou profils permettant des configurations différentes en fonction de la localisation. Pour voir les connections actuelles, utilisez la commande nmcli c avec la sous-commande show :

root@debian11:~# nmcli c show
NAME                UUID                                  TYPE      DEVICE 
Wired connection 1  77c569e6-3176-4c10-8008-40d7634d2504  ethernet  ens18 

Créez donc un profil IP fixe rattaché au périphérique ens18 :

root@debian11:~# nmcli connection add con-name ip_fixe ifname ens18 type ethernet ip4 10.0.2.41/24 gw4 10.0.2.1
Connection 'ip_fixe' (c52994fc-0918-4108-81d2-d86dade62c7a) successfully added.

Constatez sa présence :

root@debian11:~# nmcli c show
NAME                UUID                                  TYPE      DEVICE 
Wired connection 1  77c569e6-3176-4c10-8008-40d7634d2504  ethernet  ens18  
ip_fixe             c52994fc-0918-4108-81d2-d86dade62c7a  ethernet  --  

Notez que la sortie n'indique pas que le profil ip_fixe soit associé au periphérique ens18 car le profil ip_fixe n'est pas activé :

root@debian11:~# nmcli d show
GENERAL.DEVICE:                         ens18
GENERAL.TYPE:                           ethernet
GENERAL.HWADDR:                         F6:35:D1:39:09:72
GENERAL.MTU:                            1500
GENERAL.STATE:                          100 (connected)
GENERAL.CONNECTION:                     Wired connection 1
GENERAL.CON-PATH:                       /org/freedesktop/NetworkManager/ActiveConnect>
WIRED-PROPERTIES.CARRIER:               on
IP4.ADDRESS[1]:                         10.0.2.40/24
IP4.GATEWAY:                            10.0.2.1
IP4.ROUTE[1]:                           dst = 10.0.2.0/24, nh = 0.0.0.0, mt = 100
IP4.ROUTE[2]:                           dst = 0.0.0.0/0, nh = 10.0.2.1, mt = 100
IP4.DNS[1]:                             8.8.8.8
IP4.DNS[2]:                             8.8.4.4
IP6.ADDRESS[1]:                         fe80::f435:d1ff:fe39:972/64
IP6.GATEWAY:                            --
IP6.ROUTE[1]:                           dst = fe80::/64, nh = ::, mt = 100
IP6.ROUTE[2]:                           dst = ff00::/8, nh = ::, mt = 256, table=255

GENERAL.DEVICE:                         lo
GENERAL.TYPE:                           loopback
GENERAL.HWADDR:                         00:00:00:00:00:00
GENERAL.MTU:                            65536
lines 1-23
[q]

Pour activer le profil ip_fixe, utilisez la commande suivante :

[root@centos8 ~]# nmcli connection up ip_fixe

Notez que votre terminal est bloqué à cause du changement de l'adresse IP.

A faire - Revenez à votre Gateway et re-connectez-vous à la VM en tant que trainee en utilisant l'adresse IP 10.0.2.41.

Le profil ip_fixe est maintenant activé tandis que le profil enp0s3 a été désactivé :

root@debian11:~# nmcli c show
NAME                UUID                                  TYPE      DEVICE 
ip_fixe             c52994fc-0918-4108-81d2-d86dade62c7a  ethernet  ens18  
Wired connection 1  77c569e6-3176-4c10-8008-40d7634d2504  ethernet  --   
   
root@debian11:~# nmcli d show
GENERAL.DEVICE:                         ens18
GENERAL.TYPE:                           ethernet
GENERAL.HWADDR:                         F6:35:D1:39:09:72
GENERAL.MTU:                            1500
GENERAL.STATE:                          100 (connected)
GENERAL.CONNECTION:                     ip_fixe
GENERAL.CON-PATH:                       /org/freedesktop/NetworkManager/ActiveC>
WIRED-PROPERTIES.CARRIER:               on
IP4.ADDRESS[1]:                         10.0.2.41/24
IP4.GATEWAY:                            10.0.2.1
IP4.ROUTE[1]:                           dst = 10.0.2.0/24, nh = 0.0.0.0, mt = 1>
IP4.ROUTE[2]:                           dst = 0.0.0.0/0, nh = 10.0.2.1, mt = 100
IP6.ADDRESS[1]:                         fe80::7958:e23f:31e:62cd/64
IP6.GATEWAY:                            --
IP6.ROUTE[1]:                           dst = fe80::/64, nh = ::, mt = 100
IP6.ROUTE[2]:                           dst = ff00::/8, nh = ::, mt = 256, tabl>

GENERAL.DEVICE:                         lo
GENERAL.TYPE:                           loopback
lines 1-19
[q]

Pour consulter les paramètres du profil Wired connection 1, utilisez la commande suivante :

root@debian11:~# nmcli -p connection show "Wired connection 1"
===============================================================================
                Connection profile details (Wired connection 1)
===============================================================================
connection.id:                          Wired connection 1
connection.uuid:                        77c569e6-3176-4c10-8008-40d7634d2504
connection.stable-id:                   --
connection.type:                        802-3-ethernet
connection.interface-name:              --
connection.autoconnect:                 yes
connection.autoconnect-priority:        0
connection.autoconnect-retries:         -1 (default)
connection.multi-connect:               0 (default)
connection.auth-retries:                -1
connection.timestamp:                   1651494383
connection.read-only:                   no
connection.permissions:                 --
connection.zone:                        --
connection.master:                      --
connection.slave-type:                  --
connection.autoconnect-slaves:          -1 (default)
connection.secondaries:                 --
connection.gateway-ping-timeout:        0
connection.metered:                     unknown
connection.lldp:                        default
connection.mdns:                        -1 (default)
connection.llmnr:                       -1 (default)
connection.wait-device-timeout:         -1
-------------------------------------------------------------------------------
802-3-ethernet.port:                    --
802-3-ethernet.speed:                   0
802-3-ethernet.duplex:                  --
802-3-ethernet.auto-negotiate:          no
802-3-ethernet.mac-address:             --
802-3-ethernet.cloned-mac-address:      --
802-3-ethernet.generate-mac-address-mask:--
802-3-ethernet.mac-address-blacklist:   --
802-3-ethernet.mtu:                     auto
802-3-ethernet.s390-subchannels:        --
802-3-ethernet.s390-nettype:            --
802-3-ethernet.s390-options:            --
802-3-ethernet.wake-on-lan:             default
802-3-ethernet.wake-on-lan-password:    --
-------------------------------------------------------------------------------
ipv4.method:                            manual
ipv4.dns:                               8.8.8.8,8.8.4.4
ipv4.dns-search:                        --
ipv4.dns-options:                       --
ipv4.dns-priority:                      0
ipv4.addresses:                         10.0.2.40/24
ipv4.gateway:                           10.0.2.1
ipv4.routes:                            --
ipv4.route-metric:                      -1
ipv4.route-table:                       0 (unspec)
ipv4.routing-rules:                     --
ipv4.ignore-auto-routes:                no
ipv4.ignore-auto-dns:                   no
lines 1-56
[q]

De même, pour consulter les paramètres du profil ip_fixe, utilisez la commande suivante :

root@debian11:~# nmcli -p connection show ip_fixe
===============================================================================
                     Connection profile details (ip_fixe)
===============================================================================
connection.id:                          ip_fixe
connection.uuid:                        c52994fc-0918-4108-81d2-d86dade62c7a
connection.stable-id:                   --
connection.type:                        802-3-ethernet
connection.interface-name:              ens18
connection.autoconnect:                 yes
connection.autoconnect-priority:        0
connection.autoconnect-retries:         -1 (default)
connection.multi-connect:               0 (default)
connection.auth-retries:                -1
connection.timestamp:                   1651496105
connection.read-only:                   no
connection.permissions:                 --
connection.zone:                        --
connection.master:                      --
connection.slave-type:                  --
connection.autoconnect-slaves:          -1 (default)
connection.secondaries:                 --
connection.gateway-ping-timeout:        0
connection.metered:                     unknown
connection.lldp:                        default
connection.mdns:                        -1 (default)
connection.llmnr:                       -1 (default)
connection.wait-device-timeout:         -1
-------------------------------------------------------------------------------
802-3-ethernet.port:                    --
802-3-ethernet.speed:                   0
802-3-ethernet.duplex:                  --
802-3-ethernet.auto-negotiate:          no
802-3-ethernet.mac-address:             --
802-3-ethernet.cloned-mac-address:      --
802-3-ethernet.generate-mac-address-mask:--
802-3-ethernet.mac-address-blacklist:   --
802-3-ethernet.mtu:                     auto
802-3-ethernet.s390-subchannels:        --
802-3-ethernet.s390-nettype:            --
802-3-ethernet.s390-options:            --
802-3-ethernet.wake-on-lan:             default
802-3-ethernet.wake-on-lan-password:    --
-------------------------------------------------------------------------------
ipv4.method:                            manual
ipv4.dns:                               --
ipv4.dns-search:                        --
ipv4.dns-options:                       --
ipv4.dns-priority:                      0
ipv4.addresses:                         10.0.2.41/24
ipv4.gateway:                           10.0.2.1
ipv4.routes:                            --
ipv4.route-metric:                      -1
ipv4.route-table:                       0 (unspec)
ipv4.routing-rules:                     --
ipv4.ignore-auto-routes:                no
ipv4.ignore-auto-dns:                   no
lines 1-56
[q]

Pour consulter la liste profils associés à un périphérique, utilisez la commande suivante :

root@debian11:~# nmcli -f CONNECTIONS device show ens18
CONNECTIONS.AVAILABLE-CONNECTION-PATHS: /org/freedesktop/NetworkManager/Settings/1,/o>
CONNECTIONS.AVAILABLE-CONNECTIONS[1]:   77c569e6-3176-4c10-8008-40d7634d2504 | Wired >
CONNECTIONS.AVAILABLE-CONNECTIONS[2]:   c52994fc-0918-4108-81d2-d86dade62c7a | ip_fixe
lines 1-3/3 (END)
[q]

Les fichiers de configuration pour le periphérique ens18 se trouvent dans le répertoire /etc/NetworkManager/system-connections/ :

root@debian11:~# ls -l /etc/NetworkManager/system-connections
total 8
-rw------- 1 root root 284 May  2 14:23  ip_fixe.nmconnection
-rw------- 1 root root 249 Apr 25 07:01 'Wired connection 1'

1.2 - Résolution des Noms

L'étude du fichier /etc/NetworkManager/system-connections/ip_fixe.nmconnection démontre l'abscence de directives concernant les DNS :

root@debian11:~# cat /etc/NetworkManager/system-connections/ip_fixe.nmconnection 
[connection]
id=ip_fixe
uuid=c52994fc-0918-4108-81d2-d86dade62c7a
type=ethernet
interface-name=ens18
permissions=

[ethernet]
mac-address-blacklist=

[ipv4]
address1=10.0.2.41/24,10.0.2.1
dns-search=
method=manual

[ipv6]
addr-gen-mode=stable-privacy
dns-search=
method=auto

[proxy]

La résolution des noms est donc inactive :

root@debian11:~# ping www.free.fr
ping: www.free.fr: Temporary failure in name resolution

Modifiez donc la configuration du profil ip_fixe :

root@debian11:~# nmcli connection mod ip_fixe ipv4.dns 8.8.8.8

L'étude du fichier /etc/NetworkManager/system-connections/ip_fixe.nmconnection démontre que la directive concernant le serveur DNS a été ajoutée :

root@debian11:~# cat /etc/NetworkManager/system-connections/ip_fixe.nmconnection
[connection]
id=ip_fixe
uuid=c52994fc-0918-4108-81d2-d86dade62c7a
type=ethernet
interface-name=ens18
permissions=
timestamp=1651499105

[ethernet]
mac-address-blacklist=

[ipv4]
address1=10.0.2.41/24,10.0.2.1
dns=8.8.8.8;
dns-search=
method=manual

[ipv6]
addr-gen-mode=stable-privacy
dns-search=
method=auto

[proxy]

Afin que la modification du serveur DNS soit prise en compte, re-démarrez le service NetworkManager :

root@debian11:~# systemctl restart NetworkManager.service

Vérifiez que le fichier /etc/resolv.conf ait été modifié par NetworkManager :

root@debian11:~# cat /etc/resolv.conf
# Generated by NetworkManager
nameserver 8.8.8.8

Dernièrement vérifiez la resolution des noms :

root@debian11:~# ping www.free.fr
PING www.free.fr (212.27.48.10) 56(84) bytes of data.
64 bytes from www.free.fr (212.27.48.10): icmp_seq=1 ttl=47 time=10.8 ms
64 bytes from www.free.fr (212.27.48.10): icmp_seq=2 ttl=47 time=11.1 ms
^C
--- www.free.fr ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1002ms
rtt min/avg/max/mdev = 10.804/10.931/11.058/0.127 ms

Important : Notez qu'il existe un front-end graphique en mode texte, nmtui, pour configurer NetworkManager.

1.3 - Ajouter une Deuxième Adresse IP à un Profil

Pour ajouter une deuxième adresse IP à un profil sous Debian 11, il convient d'utiliser la commande suivante :

root@debian11:~# nmcli connection mod ip_fixe +ipv4.addresses 192.168.1.2/24

Rechargez la configuration du profil :

root@debian11:~# nmcli con up ip_fixe
Connection successfully activated (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/2)

Saisissez ensuite la commande suivante :

root@debian11:~# nmcli connection show ip_fixe
connection.id:                          ip_fixe
connection.uuid:                        c52994fc-0918-4108-81d2-d86dade62c7a
connection.stable-id:                   --
connection.type:                        802-3-ethernet
connection.interface-name:              ens18
connection.autoconnect:                 yes
connection.autoconnect-priority:        0
connection.autoconnect-retries:         -1 (default)
connection.multi-connect:               0 (default)
connection.auth-retries:                -1
connection.timestamp:                   1651499367
connection.read-only:                   no
connection.permissions:                 --
connection.zone:                        --
connection.master:                      --
connection.slave-type:                  --
connection.autoconnect-slaves:          -1 (default)
connection.secondaries:                 --
connection.gateway-ping-timeout:        0
connection.metered:                     unknown
connection.lldp:                        default
connection.mdns:                        -1 (default)
connection.llmnr:                       -1 (default)
connection.wait-device-timeout:         -1
802-3-ethernet.port:                    --
802-3-ethernet.speed:                   0
802-3-ethernet.duplex:                  --
802-3-ethernet.auto-negotiate:          no
802-3-ethernet.mac-address:             --
802-3-ethernet.cloned-mac-address:      --
802-3-ethernet.generate-mac-address-mask:--
802-3-ethernet.mac-address-blacklist:   --
802-3-ethernet.mtu:                     auto
802-3-ethernet.s390-subchannels:        --
802-3-ethernet.s390-nettype:            --
802-3-ethernet.s390-options:            --
802-3-ethernet.wake-on-lan:             default
802-3-ethernet.wake-on-lan-password:    --
ipv4.method:                            manual
ipv4.dns:                               8.8.8.8
ipv4.dns-search:                        --
ipv4.dns-options:                       --
ipv4.dns-priority:                      0
ipv4.addresses:                         10.0.2.41/24, 192.168.1.2/24
ipv4.gateway:                           10.0.2.1
ipv4.routes:                            --
ipv4.route-metric:                      -1
ipv4.route-table:                       0 (unspec)
ipv4.routing-rules:                     --
ipv4.ignore-auto-routes:                no
ipv4.ignore-auto-dns:                   no
ipv4.dhcp-client-id:                    --
ipv4.dhcp-iaid:                         --
ipv4.dhcp-timeout:                      0 (default)
ipv4.dhcp-send-hostname:                yes
ipv4.dhcp-hostname:                     --
lines 1-56
[Space Bar]
IP4.ADDRESS[1]:                         10.0.2.41/24
IP4.ADDRESS[2]:                         192.168.1.2/24
IP4.GATEWAY:                            10.0.2.1
IP4.ROUTE[1]:                           dst = 10.0.2.0/24, nh = 0.0.0.0, mt = 100
IP4.ROUTE[2]:                           dst = 192.168.1.0/24, nh = 0.0.0.0, mt = 100
IP4.ROUTE[3]:                           dst = 0.0.0.0/0, nh = 10.0.2.1, mt = 100
IP4.DNS[1]:                             8.8.8.8
lines 57-112
[q]

Important : Notez l'ajout de l'adresse secondaire à la ligne ipv4.addresses: ainsi que l'ajout de la ligne IP4.ADDRESS[2]:.

Consultez maintenant le contenu du fichier /etc/NetworkManager/system-connections/ip_fixe.nmconnection :

root@debian11:~# cat /etc/NetworkManager/system-connections/ip_fixe.nmconnection
[connection]
id=ip_fixe
uuid=c52994fc-0918-4108-81d2-d86dade62c7a
type=ethernet
interface-name=ens18
permissions=
timestamp=1651499263

[ethernet]
mac-address-blacklist=

[ipv4]
address1=10.0.2.41/24,10.0.2.1
address2=192.168.1.2/24
dns=8.8.8.8;
dns-search=
method=manual

[ipv6]
addr-gen-mode=stable-privacy
dns-search=
method=auto

[proxy]

Important : Notez l'ajout de la ligne address2=192.168.1.2/24.

1.4 - La Commande hostname

La procédure de la modification du hostname est simplifiée et sa prise en compte est immédiate :

root@debian11:~# hostname
debian11

root@debian11:~# nmcli general hostname debian11.ittraining.loc

root@debian11:~# cat /etc/hostname
debian11.ittraining.loc

root@debian11:~# hostname
debian11.ittraining.loc

1.5 - La Commande ip

Sous Debian 11 la commande ip est préférée par rapport à la commande ifconfig :

root@debian11:~# ip address
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: ens18: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc fq_codel state UP group default qlen 1000
    link/ether f6:35:d1:39:09:72 brd ff:ff:ff:ff:ff:ff
    altname enp0s18
    inet 10.0.2.41/24 brd 10.0.2.255 scope global noprefixroute ens18
       valid_lft forever preferred_lft forever
    inet 192.168.1.2/24 brd 192.168.1.255 scope global noprefixroute ens18
       valid_lft forever preferred_lft forever
    inet6 fe80::7958:e23f:31e:62cd/64 scope link noprefixroute 
       valid_lft forever preferred_lft forever

En cas de besoin, pour extraire les adresses IP de cette sortie, utilisez les commandes suivantes :

root@debian11:~# ip addr show ens18 | grep "inet" | grep -v "inet6" | awk '{ print $2; }' | sed 's/\/.*$//'
10.0.2.41
192.168.1.2

Les options de cette commande sont :

root@debian11:~# ip --help
Usage: ip [ OPTIONS ] OBJECT { COMMAND | help }
       ip [ -force ] -batch filename
where  OBJECT := { link | address | addrlabel | route | rule | neigh | ntable |
                   tunnel | tuntap | maddress | mroute | mrule | monitor | xfrm |
                   netns | l2tp | fou | macsec | tcp_metrics | token | netconf | ila |
                   vrf | sr | nexthop | mptcp }
       OPTIONS := { -V[ersion] | -s[tatistics] | -d[etails] | -r[esolve] |
                    -h[uman-readable] | -iec | -j[son] | -p[retty] |
                    -f[amily] { inet | inet6 | mpls | bridge | link } |
                    -4 | -6 | -I | -D | -M | -B | -0 |
                    -l[oops] { maximum-addr-flush-attempts } | -br[ief] |
                    -o[neline] | -t[imestamp] | -ts[hort] | -b[atch] [filename] |
                    -rc[vbuf] [size] | -n[etns] name | -N[umeric] | -a[ll] |
                    -c[olor]}

1.6 - Activer/Désactiver une Interface Manuellement

Deux commandes existent pour désactiver et activer manuellement une interface réseau :

# nmcli device disconnect enp0s3
# nmcli device connect enp0s3

Important : Veuillez ne PAS exécuter ces deux commandes.

1.7 - Routage Statique

La commande ip

Sous Debian 11, pour supprimer la route vers le réseau 192.168.1.0 il convient d'utiliser la commande ip et non pas la commande route :

root@debian11:~# ip route
default via 10.0.2.1 dev ens18 proto static metric 100 
10.0.2.0/24 dev ens18 proto kernel scope link src 10.0.2.41 metric 100 
192.168.1.0/24 dev ens18 proto kernel scope link src 192.168.1.2 metric 100 

root@debian11:~# ip route del 192.168.1.0/24 via 0.0.0.0

root@debian11:~# ip route
default via 10.0.2.1 dev ens18 proto static metric 100 
10.0.2.0/24 dev ens18 proto kernel scope link src 10.0.2.41 metric 100

Pour ajouter la route vers le réseau 192.168.1.0 :

root@debian11:~# ip route add 192.168.1.0/24 via 10.0.2.1

root@debian11:~# ip route
default via 10.0.2.1 dev ens18 proto static metric 100 
10.0.2.0/24 dev ens18 proto kernel scope link src 10.0.2.41 metric 100 
192.168.1.0/24 via 10.0.2.1 dev ens18 

Important - La commande utilisée pour ajouter une passerelle par défaut prend la forme suivante ip route add default via adresse ip.

Activer le routage sur le serveur

Pour activer le routage sur le serveur, il convient d'activer la retransmission des paquets:

root@debian11:~# echo 1 > /proc/sys/net/ipv4/ip_forward
root@debian11:~# cat /proc/sys/net/ipv4/ip_forward
1

LAB #2 - Diagnostique du Réseau

2.1 - ping

Pour tester l'accessibilité d'une machine, vous devez utiliser la commande ping :

root@debian11:~# ping -c4 10.0.2.1
PING 10.0.2.1 (10.0.2.1) 56(84) bytes of data.
64 bytes from 10.0.2.1: icmp_seq=1 ttl=64 time=0.184 ms
64 bytes from 10.0.2.1: icmp_seq=2 ttl=64 time=0.167 ms
64 bytes from 10.0.2.1: icmp_seq=3 ttl=64 time=0.168 ms
^C
--- 10.0.2.1 ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2036ms
rtt min/avg/max/mdev = 0.167/0.173/0.184/0.007 ms

Les options de cette commande sont :

root@debian11:~# ping --help
ping: invalid option -- '-'

Usage
  ping [options] <destination>

Options:
  <destination>      dns name or ip address
  -a                 use audible ping
  -A                 use adaptive ping
  -B                 sticky source address
  -c <count>         stop after <count> replies
  -D                 print timestamps
  -d                 use SO_DEBUG socket option
  -f                 flood ping
  -h                 print help and exit
  -I <interface>     either interface name or address
  -i <interval>      seconds between sending each packet
  -L                 suppress loopback of multicast packets
  -l <preload>       send <preload> number of packages while waiting replies
  -m <mark>          tag the packets going out
  -M <pmtud opt>     define mtu discovery, can be one of <do|dont|want>
  -n                 no dns name resolution
  -O                 report outstanding replies
  -p <pattern>       contents of padding byte
  -q                 quiet output
  -Q <tclass>        use quality of service <tclass> bits
  -s <size>          use <size> as number of data bytes to be sent
  -S <size>          use <size> as SO_SNDBUF socket option value
  -t <ttl>           define time to live
  -U                 print user-to-user latency
  -v                 verbose output
  -V                 print version and exit
  -w <deadline>      reply wait <deadline> in seconds
  -W <timeout>       time to wait for response

IPv4 options:
  -4                 use IPv4
  -b                 allow pinging broadcast
  -R                 record route
  -T <timestamp>     define timestamp, can be one of <tsonly|tsandaddr|tsprespec>

IPv6 options:
  -6                 use IPv6
  -F <flowlabel>     define flow label, default is random
  -N <nodeinfo opt>  use icmp6 node info query, try <help> as argument

For more details see ping(8).

2.2 - netstat -i

Pour visualiser les statistiques réseaux, vous disposez de la commande netstat :

root@debian11:~# netstat -i
-bash: netstat: command not found

root@debian11:~# apt -y install net-tools

root@debian11:~# netstat -i
Kernel Interface table
Iface      MTU    RX-OK RX-ERR RX-DRP RX-OVR    TX-OK TX-ERR TX-DRP TX-OVR Flg
ens18     1500     7861      0      0 0          7299      0      0      0 BMRU
lo       65536       82      0      0 0            82      0      0      0 LRU

Les options de cette commande sont :

root@debian11:~# netstat --help
usage: netstat [-vWeenNcCF] [<Af>] -r         netstat {-V|--version|-h|--help}
       netstat [-vWnNcaeol] [<Socket> ...]
       netstat { [-vWeenNac] -i | [-cnNe] -M | -s [-6tuw] }

        -r, --route              display routing table
        -i, --interfaces         display interface table
        -g, --groups             display multicast group memberships
        -s, --statistics         display networking statistics (like SNMP)
        -M, --masquerade         display masqueraded connections

        -v, --verbose            be verbose
        -W, --wide               don't truncate IP addresses
        -n, --numeric            don't resolve names
        --numeric-hosts          don't resolve host names
        --numeric-ports          don't resolve port names
        --numeric-users          don't resolve user names
        -N, --symbolic           resolve hardware names
        -e, --extend             display other/more information
        -p, --programs           display PID/Program name for sockets
        -o, --timers             display timers
        -c, --continuous         continuous listing

        -l, --listening          display listening server sockets
        -a, --all                display all sockets (default: connected)
        -F, --fib                display Forwarding Information Base (default)
        -C, --cache              display routing cache instead of FIB
        -Z, --context            display SELinux security context for sockets

  <Socket>={-t|--tcp} {-u|--udp} {-U|--udplite} {-S|--sctp} {-w|--raw}
           {-x|--unix} --ax25 --ipx --netrom
  <AF>=Use '-6|-4' or '-A <af>' or '--<af>'; default: inet
  List of possible address families (which support routing):
    inet (DARPA Internet) inet6 (IPv6) ax25 (AMPR AX.25) 
    netrom (AMPR NET/ROM) ipx (Novell IPX) ddp (Appletalk DDP) 
    x25 (CCITT X.25) 

2.3 - traceroute

La commande ping est à la base de la commande traceroute. Cette commande sert à découvrir la route empruntée pour accéder à un site donné :

root@debian11:~# traceroute www.free.fr
traceroute to www.free.fr (212.27.48.10), 30 hops max, 60 byte packets
 1  10.0.2.1 (10.0.2.1)  0.476 ms  0.440 ms  0.419 ms
 2  51.68.180.253 (51.68.180.253)  2.730 ms  2.786 ms  2.927 ms
 3  10.161.41.253 (10.161.41.253)  0.315 ms 10.161.41.252 (10.161.41.252)  0.293 ms  0.274 ms
 4  10.17.242.66 (10.17.242.66)  0.467 ms 10.17.242.62 (10.17.242.62)  0.620 ms 10.17.242.66 (10.17.242.66)  0.795 ms
 5  10.73.40.38 (10.73.40.38)  0.189 ms  2.403 ms 10.73.40.42 (10.73.40.42)  2.339 ms
 6  10.73.249.68 (10.73.249.68)  4.894 ms * *
 7  fra-fr5-sbb1-nc5.de.eu (91.121.215.116)  1.909 ms  1.491 ms fra-fr5-sbb2-nc5.de.eu (94.23.122.246)  1.475 ms
 8  be101.sbg-g1-nc5.fr.eu (94.23.122.136)  4.182 ms be101.sbg-g2-nc5.fr.eu (91.121.215.196)  4.504 ms  4.918 ms
 9  be103.par-gsw-sbb1-nc5.fr.eu (91.121.215.219)  10.471 ms be103.par-th2-sbb1-nc5.fr.eu (94.23.122.139)  10.448 ms  10.198 ms
10  10.200.2.65 (10.200.2.65)  10.174 ms 10.200.2.71 (10.200.2.71)  10.211 ms 10.200.2.65 (10.200.2.65)  10.111 ms
11  * * *
12  194.149.166.61 (194.149.166.61)  10.289 ms *  10.111 ms
13  * * *
14  * * *
15  * * *
16  * * *
17  * * *
18  * * *
19  * * *
20  * * *
21  * * *
22  * * *
23  * * *
24  * * *
25  * * *
26  * * *
27  * * *
28  * * *
29  * * *
30  * * *

Les options de cette commande sont :

root@debian11:~# traceroute --help
Usage:
  traceroute [ -46dFITnreAUDV ] [ -f first_ttl ] [ -g gate,... ] [ -i device ] [ -m max_ttl ] [ -N squeries ] [ -p port ] [ -t tos ] [ -l flow_label ] [ -w MAX,HERE,NEAR ] [ -q nqueries ] [ -s src_addr ] [ -z sendwait ] [ --fwmark=num ] host [ packetlen ]
Options:
  -4                          Use IPv4
  -6                          Use IPv6
  -d  --debug                 Enable socket level debugging
  -F  --dont-fragment         Do not fragment packets
  -f first_ttl  --first=first_ttl
                              Start from the first_ttl hop (instead from 1)
  -g gate,...  --gateway=gate,...
                              Route packets through the specified gateway
                              (maximum 8 for IPv4 and 127 for IPv6)
  -I  --icmp                  Use ICMP ECHO for tracerouting
  -T  --tcp                   Use TCP SYN for tracerouting (default port is 80)
  -i device  --interface=device
                              Specify a network interface to operate with
  -m max_ttl  --max-hops=max_ttl
                              Set the max number of hops (max TTL to be
                              reached). Default is 30
  -N squeries  --sim-queries=squeries
                              Set the number of probes to be tried
                              simultaneously (default is 16)
  -n                          Do not resolve IP addresses to their domain names
  -p port  --port=port        Set the destination port to use. It is either
                              initial udp port value for "default" method
                              (incremented by each probe, default is 33434), or
                              initial seq for "icmp" (incremented as well,
                              default from 1), or some constant destination
                              port for other methods (with default of 80 for
                              "tcp", 53 for "udp", etc.)
  -t tos  --tos=tos           Set the TOS (IPv4 type of service) or TC (IPv6
                              traffic class) value for outgoing packets
  -l flow_label  --flowlabel=flow_label
                              Use specified flow_label for IPv6 packets
  -w MAX,HERE,NEAR  --wait=MAX,HERE,NEAR
                              Wait for a probe no more than HERE (default 3)
                              times longer than a response from the same hop,
                              or no more than NEAR (default 10) times than some
                              next hop, or MAX (default 5.0) seconds (float
                              point values allowed too)
  -q nqueries  --queries=nqueries
                              Set the number of probes per each hop. Default is
                              3
  -r                          Bypass the normal routing and send directly to a
                              host on an attached network
  -s src_addr  --source=src_addr
                              Use source src_addr for outgoing packets
  -z sendwait  --sendwait=sendwait
                              Minimal time interval between probes (default 0).
                              If the value is more than 10, then it specifies a
                              number in milliseconds, else it is a number of
                              seconds (float point values allowed too)
  -e  --extensions            Show ICMP extensions (if present), including MPLS
  -A  --as-path-lookups       Perform AS path lookups in routing registries and
                              print results directly after the corresponding
                              addresses
  -M name  --module=name      Use specified module (either builtin or external)
                              for traceroute operations. Most methods have
                              their shortcuts (`-I' means `-M icmp' etc.)
  -O OPTS,...  --options=OPTS,...
                              Use module-specific option OPTS for the
                              traceroute module. Several OPTS allowed,
                              separated by comma. If OPTS is "help", print info
                              about available options
  --sport=num                 Use source port num for outgoing packets. Implies
                              `-N 1'
  --fwmark=num                Set firewall mark for outgoing packets
  -U  --udp                   Use UDP to particular port for tracerouting
                              (instead of increasing the port per each probe),
                              default port is 53
  -UL                         Use UDPLITE for tracerouting (default dest port
                              is 53)
  -D  --dccp                  Use DCCP Request for tracerouting (default port
                              is 33434)
  -P prot  --protocol=prot    Use raw packet of protocol prot for tracerouting
  --mtu                       Discover MTU along the path being traced. Implies
                              `-F -N 1'
  --back                      Guess the number of hops in the backward path and
                              print if it differs
  -V  --version               Print version info and exit
  --help                      Read this help and exit

Arguments:
+     host          The host to traceroute to
      packetlen     The full packet length (default is the length of an IP
                    header plus 40). Can be ignored or increased to a minimal
                    allowed value

LAB #3 - Connexions à Distance

3.1 - Telnet

La commande telnet est utilisée pour établir une connexion à distance avec un serveur telnet :

  # telnet numero_ip

Important - Le service telnet revient à une redirection des canaux standards d'entrée et de sortie. Notez que la connexion n'est pas sécurisée. Pour fermer la connexion, il faut saisir la commande exit. La commande telnet n'offre pas de services de transfert de fichiers. Pour cela, il convient d'utiliser la command ftp.

Les options de cette commande sont :

root@debian11:~# which telnet
/usr/bin/telnet
root@debian11:~# telnet --help
telnet: invalid option -- '-'
Usage: telnet [-4] [-6] [-8] [-E] [-L] [-a] [-d] [-e char] [-l user]
        [-n tracefile] [ -b addr ] [-r] [host-name [port]]

3.2 - wget

La commande wget est utilisée pour récupérer un fichier via http, https ou ftp :

root@debian11:~# wget https://www.dropbox.com/s/wk79lkfr6f12u9j/wget_file.txt
--2022-05-03 10:07:50--  https://www.dropbox.com/s/wk79lkfr6f12u9j/wget_file.txt
Resolving www.dropbox.com (www.dropbox.com)... 162.125.67.18, 2620:100:6023:18::a27d:4312
Connecting to www.dropbox.com (www.dropbox.com)|162.125.67.18|:443... connected.
HTTP request sent, awaiting response... 301 Moved Permanently
Location: /s/raw/wk79lkfr6f12u9j/wget_file.txt [following]
--2022-05-03 10:07:51--  https://www.dropbox.com/s/raw/wk79lkfr6f12u9j/wget_file.txt
Reusing existing connection to www.dropbox.com:443.
HTTP request sent, awaiting response... 302 Found
Location: https://uc64dcd84ee4be2a0c2f111bd2ab.dl.dropboxusercontent.com/cd/0/inline/BkjB7WuIg8oRJsAnsjaq0YeQrof8LaM6svUdazV8cmiN5MWJqHVYZlMfbR33nIokof9ZHmK551ixoOU8CgteUybofFdo_vD62VcF-WNi4ACD8o6JsjdD7kiiuge-8mfbD1unwz4UtpyHIuVPQ9sUrh0QNNTVtsj3kcjDJAgEDg-uKQ/file# [following]
--2022-05-03 10:07:51--  https://uc64dcd84ee4be2a0c2f111bd2ab.dl.dropboxusercontent.com/cd/0/inline/BkjB7WuIg8oRJsAnsjaq0YeQrof8LaM6svUdazV8cmiN5MWJqHVYZlMfbR33nIokof9ZHmK551ixoOU8CgteUybofFdo_vD62VcF-WNi4ACD8o6JsjdD7kiiuge-8mfbD1unwz4UtpyHIuVPQ9sUrh0QNNTVtsj3kcjDJAgEDg-uKQ/file
Resolving uc64dcd84ee4be2a0c2f111bd2ab.dl.dropboxusercontent.com (uc64dcd84ee4be2a0c2f111bd2ab.dl.dropboxusercontent.com)... 162.125.67.15, 2620:100:6023:15::a27d:430f
Connecting to uc64dcd84ee4be2a0c2f111bd2ab.dl.dropboxusercontent.com (uc64dcd84ee4be2a0c2f111bd2ab.dl.dropboxusercontent.com)|162.125.67.15|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 46 [text/plain]
Saving to: ‘wget_file.txt’

wget_file.txt         100%[=======================>]      46  --.-KB/s    in 0s      

2022-05-03 10:07:51 (26.8 MB/s) - ‘wget_file.txt’ saved [46/46]

root@debian11:~# cat wget_file.txt 
This is a file retrieved by the wget command.

Les options de cette commande sont :

root@debian11:~# wget --help | more
GNU Wget 1.21, a non-interactive network retriever.
Usage: wget [OPTION]... [URL]...

Mandatory arguments to long options are mandatory for short options too.

Startup:
  -V,  --version                   display the version of Wget and exit
  -h,  --help                      print this help
  -b,  --background                go to background after startup
  -e,  --execute=COMMAND           execute a `.wgetrc'-style command

Logging and input file:
  -o,  --output-file=FILE          log messages to FILE
  -a,  --append-output=FILE        append messages to FILE
  -d,  --debug                     print lots of debugging information
  -q,  --quiet                     quiet (no output)
  -v,  --verbose                   be verbose (this is the default)
  -nv, --no-verbose                turn off verboseness, without being quiet
       --report-speed=TYPE         output bandwidth as TYPE.  TYPE can be bits
  -i,  --input-file=FILE           download URLs found in local or external FILE
  -F,  --force-html                treat input file as HTML
  -B,  --base=URL                  resolves HTML input-file links (-i -F)
                                     relative to URL
       --config=FILE               specify config file to use
       --no-config                 do not read any config file
       --rejected-log=FILE         log reasons for URL rejection to FILE

Download:
  -t,  --tries=NUMBER              set number of retries to NUMBER (0 unlimits)
       --retry-connrefused         retry even if connection is refused
       --retry-on-http-error=ERRORS    comma-separated list of HTTP errors to retry
  -O,  --output-document=FILE      write documents to FILE
  -nc, --no-clobber                skip downloads that would download to
                                     existing files (overwriting them)
       --no-netrc                  don't try to obtain credentials from .netrc
  -c,  --continue                  resume getting a partially-downloaded file
       --start-pos=OFFSET          start downloading from zero-based position OFFSET
       --progress=TYPE             select progress gauge type
       --show-progress             display the progress bar in any verbosity mode
  -N,  --timestamping              don't re-retrieve files unless newer than
                                     local
       --no-if-modified-since      don't use conditional if-modified-since get
                                     requests in timestamping mode
       --no-use-server-timestamps  don't set the local file's timestamp by
                                     the one on the server
  -S,  --server-response           print server response
       --spider                    don't download anything
  -T,  --timeout=SECONDS           set all timeout values to SECONDS
       --dns-timeout=SECS          set the DNS lookup timeout to SECS
       --connect-timeout=SECS      set the connect timeout to SECS
       --read-timeout=SECS         set the read timeout to SECS
  -w,  --wait=SECONDS              wait SECONDS between retrievals
                                     (applies if more then 1 URL is to be retrieved)
--More--
[q]

3.3 - ftp

Important - Si la commande ftp n'est pas installée sous Debian 11, installez-le à l'aide de la commande apt install ftp en tant que root.

La commande ftp est utilisée pour le transfert de fichiers. Une fois connecté, il convient d'utiliser la commande help pour afficher la liste des commandes disponibles :

ftp> help
Commands may be abbreviated.  Commands are:

!               dir             mdelete         qc              site
$               disconnect      mdir            sendport        size
account         exit            mget            put             status
append          form            mkdir           pwd             struct
ascii           get             mls             quit            system
bell            glob            mode            quote           sunique
binary          hash            modtime         recv            tenex
bye             help            mput            reget           tick
case            idle            newer           rstatus         trace
cd              image           nmap            rhelp           type
cdup            ipany           nlist           rename          user
chmod           ipv4            ntrans          reset           umask
close           ipv6            open            restart         verbose
cr              lcd             prompt          rmdir           ?
delete          ls              passive         runique
debug           macdef          proxy           send
ftp> 

Le caractère ! permet d'exécuter une commande sur la machine cliente

ftp> !pwd
/root

Pour transférer un fichier vers le serveur, il convient d'utiliser la commande put :

ftp> put nom_fichier_local nom_fichier_distant

Vous pouvez également transférer plusieurs fichiers à la fois grâce à la commande mput. Dans ce cas précis, il convient de saisir la commande suivante:

ftp> mput nom*.*

Pour transférer un fichier du serveur, il convient d'utiliser la commande get :

ftp> get nom_fichier

Vous pouvez également transférer plusieurs fichiers à la fois grâce à la commande mget ( voir la commande mput ci-dessus ).

Pour supprimer un fichier sur le serveur, il convient d'utiliser la commande del :

ftp> del nom_fichier

Pour fermer la session, il convient d'utiliser la commande quit :

ftp> quit
root@debian11:~# 

3.4 - SSH

Présentation

La commande ssh est le successeur et la remplaçante de la commande rlogin. Il permet d'établir des connexions sécurisées avec une machine distante. SSH comporte cinq acteurs :

  • Le serveur SSH
    • le démon sshd, qui s'occupe des authentifications et autorisations des clients,
  • Le client SSH
    • ssh ou scp, qui assure la connexion et le dialogue avec le serveur,
  • La session qui représente la connexion courante et qui commence juste après l'authentification réussie,
  • Les clefs
    • Couple de clef utilisateur asymétriques et persistantes qui assurent l'identité d'un utilisateur et qui sont stockés sur disque dur,
    • Clef hôte asymétrique et persistante garantissant l'identité du serveur er qui est conservé sur disque dur
    • Clef serveur asymétrique et temporaire utilisée par le protocole SSH1 qui sert au chiffrement de la clé de session,
    • Clef de session symétrique qui est générée aléatoirement et qui permet le chiiffrement de la communication entre le client et le serveur. Elle est détruite en fin de session. SSH-1 utilise une seule clef tandis que SSH-2 utilise une clef par direction de la communication,
  • La base de données des hôtes connus qui stocke les clés des connexions précédentes.

SSH fonctionne de la manière suivante pour la la mise en place d'un canal sécurisé:

  • Le client contacte le serveur sur son port 22,
  • Les client et le serveur échangent leur version de SSH. En cas de non-compatibilité de versions, l'un des deux met fin au processus,
  • Le serveur SSH s'identifie auprès du client en lui fournissant :
    • Sa clé hôte,
    • Sa clé serveur,
    • Une séquence aléatoire de huit octets à inclure dans les futures réponses du client,
    • Une liste de méthodes de chiffrage, compression et authentification,
  • Le client et le serveur produisent un identifiant identique, un haché MD5 long de 128 bits contenant la clé hôte, la clé serveur et la séquence aléatoire,
  • Le client génère sa clé de session symétrique et la chiffre deux fois de suite, une fois avec la clé hôte du serveur et la deuxième fois avec la clé serveur. Le client envoie cette clé au serveur accompagnée de la séquence aléatoire et un choix d'algorithmes supportés,
  • Le serveur déchiffre la clé de session,
  • Le client et le serveur mettent en place le canal sécurisé.
SSH-1

SSH-1 utilise une paire de clefs de type RSA1. Il assure l'intégrité des données par une Contrôle de Redondance Cyclique (CRC) et est un bloc dit monolithique.

Afin de s'identifier, le client essaie chacune des six méthodes suivantes :

  • Kerberos,
  • Rhosts,
  • RhostsRSA,
  • Par clef asymétrique,
  • TIS,
  • Par mot de passe.
SSH-2

SSH-2 utilise DSA ou RSA. Il assure l'intégrité des données par l'algorithme HMAC. SSH-2 est organisé en trois couches :

  • SSH-TRANS – Transport Layer Protocol,
  • SSH-AUTH – Authentification Protocol,
  • SSH-CONN – Connection Protocol.

SSH-2 diffère de SSH-1 essentiellement dans la phase authentification.

Trois méthodes d'authentification :

  • Par clef asymétrique,
    • Identique à SSH-1 sauf avec l'algorithme DSA,
  • RhostsRSA,
  • Par mot de passe.

Les options de cette commande sont :

root@debian11:~# ssh --help
unknown option -- -
usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]
           [-b bind_address] [-c cipher_spec] [-D [bind_address:]port]
           [-E log_file] [-e escape_char] [-F configfile] [-I pkcs11]
           [-i identity_file] [-J [user@]host[:port]] [-L address]
           [-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
           [-Q query_option] [-R address] [-S ctl_path] [-W host:port]
           [-w local_tun[:remote_tun]] destination [command]

Authentification par mot de passe

L'utilisateur fournit un mot de passe au client ssh. Le client ssh le transmet de façon sécurisée au serveur ssh puis le serveur vérifie le mot de passe et l'accepte ou non.

Avantage:

  • Aucune configuration de clef asymétrique n'est nécessaire.

Inconvénients:

  • L'utilisateur doit fournir à chaque connexion un identifiant et un mot de passe,
  • Moins sécurisé qu'un système par clef asymétrique.

Authentification par clef asymétrique

  • Le client envoie au serveur une requête d'authentification par clé asymétrique qui contient le module de la clé à utiliser,
  • Le serveur recherche une correspondance pour ce module dans le fichier des clés autorisés ~/.ssh/authorized_keys,
    • Dans le cas où une correspondance n'est pas trouvée, le serveur met fin à la communication,
    • Dans le cas contraire le serveur génère une chaîne aléatoire de 256 bits appelée un challenge et la chiffre avec la clé publique du client,
  • Le client reçoit le challenge et le décrypte avec la partie privée de sa clé. Il combine le challenge avec l'identifiant de session et chiffre le résultat. Ensuite il envoie le résultat chiffré au serveur.
  • Le serveur génère le même haché et le compare avec celui reçu du client. Si les deux hachés sont identiques, l'authentification est réussie.

Configuration du Serveur

La configuration du serveur s'effectue dans le fichier /etc/ssh/sshd_config :

root@debian11:~# cat /etc/ssh/sshd_config
#       $OpenBSD: sshd_config,v 1.103 2018/04/09 20:41:22 tj Exp $

# This is the sshd server system-wide configuration file.  See
# sshd_config(5) for more information.

# This sshd was compiled with PATH=/usr/bin:/bin:/usr/sbin:/sbin

# The strategy used for options in the default sshd_config shipped with
# OpenSSH is to specify options with their default value where
# possible, but leave them commented.  Uncommented options override the
# default value.

Include /etc/ssh/sshd_config.d/*.conf

#Port 22
#AddressFamily any
#ListenAddress 0.0.0.0
#ListenAddress ::

#HostKey /etc/ssh/ssh_host_rsa_key
#HostKey /etc/ssh/ssh_host_ecdsa_key
#HostKey /etc/ssh/ssh_host_ed25519_key

# Ciphers and keying
#RekeyLimit default none

# Logging
#SyslogFacility AUTH
#LogLevel INFO

# Authentication:

#LoginGraceTime 2m
PermitRootLogin yes 
#StrictModes yes
#MaxAuthTries 6
#MaxSessions 10

#PubkeyAuthentication yes

# Expect .ssh/authorized_keys2 to be disregarded by default in future.
#AuthorizedKeysFile     .ssh/authorized_keys .ssh/authorized_keys2

#AuthorizedPrincipalsFile none

#AuthorizedKeysCommand none
#AuthorizedKeysCommandUser nobody

# For this to work you will also need host keys in /etc/ssh/ssh_known_hosts
#HostbasedAuthentication no
# Change to yes if you don't trust ~/.ssh/known_hosts for
# HostbasedAuthentication
#IgnoreUserKnownHosts no
# Don't read the user's ~/.rhosts and ~/.shosts files
#IgnoreRhosts yes

# To disable tunneled clear text passwords, change to no here!
#PasswordAuthentication yes
#PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
ChallengeResponseAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes
#KerberosGetAFSToken no

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes
#GSSAPIStrictAcceptorCheck yes
#GSSAPIKeyExchange no

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
UsePAM yes

#AllowAgentForwarding yes
#AllowTcpForwarding yes
#GatewayPorts no
X11Forwarding yes
#X11DisplayOffset 10
#X11UseLocalhost yes
#PermitTTY yes
PrintMotd no
#PrintLastLog yes
#TCPKeepAlive yes
#PermitUserEnvironment no
#Compression delayed
#ClientAliveInterval 0
#ClientAliveCountMax 3
#UseDNS no
#PidFile /var/run/sshd.pid
#MaxStartups 10:30:100
#PermitTunnel no
#ChrootDirectory none
#VersionAddendum none

# no default banner path
#Banner none

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

# override default of no subsystems
Subsystem       sftp    /usr/lib/openssh/sftp-server

# Example of overriding settings on a per-user basis
#Match User anoncvs
#       X11Forwarding no
#       AllowTcpForwarding no
#       PermitTTY no
#       ForceCommand cvs server

Pour ôter les lignes de commentaires dans ce fichier, utilisez la commande suivante :

root@debian11:~# cd /tmp ; grep -E -v '^(#|$)'  /etc/ssh/sshd_config > sshd_config
root@debian11:/tmp# cat sshd_config
Include /etc/ssh/sshd_config.d/*.conf
PermitRootLogin yes 
ChallengeResponseAuthentication no
UsePAM yes
X11Forwarding yes
PrintMotd no
AcceptEnv LANG LC_*
Subsystem       sftp    /usr/lib/openssh/sftp-server

Pour sécuriser le serveur ssh, ajoutez ou modifiez les directives suivantes :

AllowGroups adm
Banner /etc/issue.net
HostbasedAuthentication no
IgnoreRhosts yes
LoginGraceTime 60
LogLevel INFO
PermitEmptyPasswords no
PermitRootLogin no
PrintLastLog yes
Protocol 2
StrictModes yes
X11Forwarding no

Votre fichier ressemblera à celui-ci :

root@debian11:/tmp# vi sshd_config
root@debian11:/tmp# cat sshd_config
AllowGroups adm
Banner /etc/issue.net
HostbasedAuthentication no
IgnoreRhosts yes
LoginGraceTime 60
LogLevel INFO
PermitEmptyPasswords no
PermitRootLogin no
PrintLastLog yes
Protocol 2
StrictModes yes
X11Forwarding no
Include /etc/ssh/sshd_config.d/*.conf
ChallengeResponseAuthentication no
UsePAM yes
PrintMotd no
AcceptEnv LANG LC_*
Subsystem       sftp    /usr/lib/openssh/sftp-server

Renommez le fichier /etc/ssh/sshd_config en /etc/ssh/sshd_config.old :

[root@centos11 tmp]# cp /etc/ssh/sshd_config /etc/ssh/sshd_config.old

Copiez le fichier /tmp/sshd_config vers /etc/ssh/ :

root@debian11:/tmp# cp /tmp/sshd_config /etc/ssh

Redémarrez le service sshd :

root@debian11:/tmp# systemctl restart sshd
root@debian11:/tmp# systemctl status sshd
● ssh.service - OpenBSD Secure Shell server
     Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
     Active: active (running) since Tue 2022-05-03 11:01:24 CEST; 7s ago
       Docs: man:sshd(8)
             man:sshd_config(5)
    Process: 4885 ExecStartPre=/usr/sbin/sshd -t (code=exited, status=0/SUCCESS)
   Main PID: 4888 (sshd)
      Tasks: 1 (limit: 4632)
     Memory: 1.1M
        CPU: 24ms
     CGroup: /system.slice/ssh.service
             └─4888 sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups

May 03 11:01:24 debian11.ittraining.loc sshd[4888]: Server listening on 0.0.0.0 port >
May 03 11:01:24 debian11.ittraining.loc systemd[1]: Stopping OpenBSD Secure Shell ser>
May 03 11:01:24 debian11.ittraining.loc sshd[4888]: Server listening on :: port 22.
May 03 11:01:24 debian11.ittraining.loc systemd[1]: ssh.service: Succeeded.
May 03 11:01:24 debian11.ittraining.loc systemd[1]: Stopped OpenBSD Secure Shell serv>
May 03 11:01:24 debian11.ittraining.loc systemd[1]: Starting OpenBSD Secure Shell ser>
May 03 11:01:24 debian11.ittraining.loc systemd[1]: Started OpenBSD Secure Shell serv>
lines 1-20/20 (END)
[q]

Mettez l'utilisateur trainee dans le groupe adm :

root@debian11:/tmp# groups trainee
trainee : trainee cdrom floppy audio dip src video plugdev netdev lpadmin scanner
root@debian11:/tmp# usermod -aG adm trainee
root@debian11:/tmp# groups trainee
trainee : trainee adm cdrom floppy audio dip src video plugdev netdev lpadmin scanner

Pour générer les clefs du serveur, saisissez la commande suivante en tant que root. Notez que la passphrase doit être vide.

root@debian11:/tmp# ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/root/.ssh/id_dsa): /etc/ssh/ssh_host_dsa_key
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /etc/ssh/ssh_host_dsa_key
Your public key has been saved in /etc/ssh/ssh_host_dsa_key.pub
The key fingerprint is:
SHA256:emwF3Bq/2H+JGk5dNXgKBLTtbuC04byZmFJDxkUxso4 root@debian11.ittraining.loc
The key's randomart image is:
+---[DSA 1024]----+
|       .o*o.     |
|       .oo=   .  |
|      ..=..o . o.|
|      o+ =. . o..|
|     Eo.S+o. ..  |
|       ==+=o .   |
|      o *==o.. . |
|     . ooo=o. o  |
|      .o +o...   |
+----[SHA256]-----+
root@debian11:/tmp# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): /etc/ssh/ssh_host_rsa_key
/etc/ssh/ssh_host_rsa_key already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /etc/ssh/ssh_host_rsa_key
Your public key has been saved in /etc/ssh/ssh_host_rsa_key.pub
The key fingerprint is:
SHA256:xrkpZ6lfF1hQIZEYJuH1L+Z2QGhQCf8Xwt9HPwTuT7Y root@debian11.ittraining.loc
The key's randomart image is:
+---[RSA 3072]----+
|      =+=+++oo   |
|     . *o+.o. .  |
|      . + = o. ..|
|       o + *.o...|
|        S * =..+o|
|       . * + .+.o|
|      . * + o  E |
|       = o o     |
|      ...        |
+----[SHA256]-----+
root@debian11:/tmp# ssh-keygen -t ecdsa
Generating public/private ecdsa key pair.
Enter file in which to save the key (/root/.ssh/id_ecdsa): /etc/ssh/ssh_host_ecdsa_key
/etc/ssh/ssh_host_ecdsa_key already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /etc/ssh/ssh_host_ecdsa_key
Your public key has been saved in /etc/ssh/ssh_host_ecdsa_key.pub
The key fingerprint is:
SHA256:38O9lqa1AHvviceNEbQ1AOUMspkYBpIpLlu/U05ymqo root@debian11.ittraining.loc
The key's randomart image is:
+---[ECDSA 256]---+
|   .o..o . ooo.  |
| . o. . o = + ...|
|. .    . +   + o.|
|...           o  |
|.o .    S .    . |
|.   o +  . = ..  |
|     X    o *.o= |
|    = .    . *B+.|
|E... .      o**  |
+----[SHA256]-----+
root@debian11:/tmp# ssh-keygen -t ed25519
Generating public/private ed25519 key pair.
Enter file in which to save the key (/root/.ssh/id_ed25519): /etc/ssh/ssh_host_ed25519_key
/etc/ssh/ssh_host_ed25519_key already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /etc/ssh/ssh_host_ed25519_key
Your public key has been saved in /etc/ssh/ssh_host_ed25519_key.pub
The key fingerprint is:
SHA256:f8arQ5MBRGNJoj4eARYapvxf/MLxFFMZcKf1eLkgeow root@debian11.ittraining.loc
The key's randomart image is:
+--[ED25519 256]--+
|..+.  .+*o.+oo   |
|++ . . oo.o.+ o .|
|o.  o    + o o + |
|  .. ..   B . o .|
|   .+  +SE =   . |
|   ..oo =.=.     |
|    .. o +..+    |
|        . .o .   |
|          .o.    |
+----[SHA256]-----+

Les clefs publiques générées possèdent l'extension .pub. Les clefs privées n'ont pas d'extension :

root@debian11:/tmp# ls /etc/ssh
moduli        sshd_config.d         ssh_host_ecdsa_key        ssh_host_rsa_key
ssh_config    sshd_config.old       ssh_host_ecdsa_key.pub    ssh_host_rsa_key.pub
ssh_config.d  ssh_host_dsa_key      ssh_host_ed25519_key
sshd_config   ssh_host_dsa_key.pub  ssh_host_ed25519_key.pub

Re-démarrez ensuite le service sshd :

root@debian11:/tmp# systemctl restart sshd.service
root@debian11:/tmp# systemctl status sshd.service
● ssh.service - OpenBSD Secure Shell server
     Loaded: loaded (/lib/systemd/system/ssh.service; enabled; vendor preset: enabled)
     Active: active (running) since Tue 2022-05-03 11:30:09 CEST; 8s ago
       Docs: man:sshd(8)
             man:sshd_config(5)
    Process: 4942 ExecStartPre=/usr/sbin/sshd -t (code=exited, status=0/SUCCESS)
   Main PID: 4943 (sshd)
      Tasks: 1 (limit: 4632)
     Memory: 1.1M
        CPU: 24ms
     CGroup: /system.slice/ssh.service
             └─4943 sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups

May 03 11:30:09 debian11.ittraining.loc systemd[1]: Starting OpenBSD Secure Shell ser>
May 03 11:30:09 debian11.ittraining.loc sshd[4943]: Server listening on 0.0.0.0 port >
May 03 11:30:09 debian11.ittraining.loc sshd[4943]: Server listening on :: port 22.
May 03 11:30:09 debian11.ittraining.loc systemd[1]: Started OpenBSD Secure Shell serv>
lines 1-17/17 (END)
[q]

Configuration du Client

Saisissez maintenant les commandes suivantes en tant que trainee :

Important - Lors de la génération des clefs, la passphrase doit être vide.

root@debian11:/tmp# exit
logout
trainee@debian11:~$ ssh-keygen -t dsa
Generating public/private dsa key pair.
Enter file in which to save the key (/home/trainee/.ssh/id_dsa): 
Created directory '/home/trainee/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/trainee/.ssh/id_dsa
Your public key has been saved in /home/trainee/.ssh/id_dsa.pub
The key fingerprint is:
SHA256:WijVQNwc9klBZxW4R8ZY5LwZK08/FaZCkWP0yKNj+20 trainee@debian11.ittraining.loc
The key's randomart image is:
+---[DSA 1024]----+
|     ooooo=++B=. |
|      .+oo.B*o+  |
|      . . +=.=+o |
|     . .  o o +=.|
|    . . S+ ..o= .|
|     . o. o .+ ..|
|      .  .    ...|
|          . .E  .|
|           ...   |
+----[SHA256]-----+
trainee@debian11:~$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/trainee/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/trainee/.ssh/id_rsa
Your public key has been saved in /home/trainee/.ssh/id_rsa.pub
The key fingerprint is:
SHA256:r8id4Px97b9t7GMybe7OTaQU5lgaRjsTK/EAyMFdgjo trainee@debian11.ittraining.loc
The key's randomart image is:
+---[RSA 3072]----+
|     o.=oo+ o    |
|      = .. = +   |
|     .    . O +  |
|    E      o X . |
|     .  S   o o .|
|         .   . o |
|      .   .  .o..|
|     + + +  .oo*=|
|      =.= .. .XXB|
+----[SHA256]-----+
trainee@debian11:~$ ssh-keygen -t ecdsa
Generating public/private ecdsa key pair.
Enter file in which to save the key (/home/trainee/.ssh/id_ecdsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/trainee/.ssh/id_ecdsa
Your public key has been saved in /home/trainee/.ssh/id_ecdsa.pub
The key fingerprint is:
SHA256:IL44+ZzExDxBFCt9nZtMgCQB/iuq9UtJC6uq/RhrPvg trainee@debian11.ittraining.loc
The key's randomart image is:
+---[ECDSA 256]---+
|..o+=o.          |
|.  +.. o .       |
| .. = o +        |
|  .= + + o       |
|  ..B   S        |
|   O.=           |
| oB.B            |
|o++@ .           |
|X+EoB.           |
+----[SHA256]-----+
trainee@debian11:~$ ssh-keygen -t ed25519
Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/trainee/.ssh/id_ed25519): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/trainee/.ssh/id_ed25519
Your public key has been saved in /home/trainee/.ssh/id_ed25519.pub
The key fingerprint is:
SHA256:yQ9mtIx1nK7D1vSZjkkbofXHZsTDp5P0rywiJIMX35M trainee@debian11.ittraining.loc
The key's randomart image is:
+--[ED25519 256]--+
|                 |
|         . .     |
|        o +      |
|      .* =   o   |
|     ..oS.=.  * .|
|    . ++oOE+ * * |
|     . +* =.= O .|
|       ..o.*.= ..|
|         .+...o..|
+----[SHA256]-----+

Les clés générées seront placées dans le répertoire ~/.ssh/ :

trainee@debian11:~$ ls .ssh
id_dsa      id_ecdsa      id_ed25519      id_rsa
id_dsa.pub  id_ecdsa.pub  id_ed25519.pub  id_rsa.pub

Tunnels SSH

Le protocole SSH peut être utilisé pour sécuriser les protocoles tels telnet, pop3 etc.. En effet, on peut créer un tunnel SSH dans lequel passe les communications du protocole non-sécurisé.

La commande pour créer un tunnel ssh prend la forme suivante :

ssh -N -f compte@hôte -Lport-local:localhost:port_distant

Dans votre cas, vous allez créer un tunnel dans votre propre VM entre le port 15023 et le port 23 :

trainee@debian11:~$ su -
Password: fenestros
root@debian11:~# ssh -N -f trainee@localhost -L15023:localhost:23
The authenticity of host 'localhost (::1)' can't be established.
ECDSA key fingerprint is SHA256:38O9lqa1AHvviceNEbQ1AOUMspkYBpIpLlu/U05ymqo.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'localhost' (ECDSA) to the list of known hosts.
Debian GNU/Linux 11
trainee@localhost's password: trainee

Installez maintenant le serveur telnet :

root@debian11:~# apt -y install telnetd

Vérifiez que le service inetd est démarré :

root@debian11:~# systemctl status inetd
● inetd.service - Internet superserver
     Loaded: loaded (/lib/systemd/system/inetd.service; enabled; vendor preset: enabl>
     Active: active (running) since Tue 2022-05-03 11:55:27 CEST; 44s ago
       Docs: man:inetd(8)
   Main PID: 5110 (inetd)
      Tasks: 1 (limit: 4632)
     Memory: 576.0K
        CPU: 7ms
     CGroup: /system.slice/inetd.service
             └─5110 /usr/sbin/inetd

May 03 11:55:27 debian11.ittraining.loc systemd[1]: Starting Internet superserver...
May 03 11:55:27 debian11.ittraining.loc systemd[1]: Started Internet superserver.

Connectez-vous ensuite via telnet sur le port 15023, vous constaterez que votre connexion n'aboutit pas :

root@debian11:~# telnet localhost 15023
Trying ::1...
Connected to localhost.
Escape character is '^]'.
Debian GNU/Linux 11
debian11.ittraining.loc login: trainee
Password: trainee
Linux debian11.ittraining.loc 5.17.0-1-amd64 #1 SMP PREEMPT Debian 5.17.3-1 (2022-04-18) x86_64

The programs included with the Debian GNU/Linux system are free software;
the exact distribution terms for each program are described in the
individual files in /usr/share/doc/*/copyright.

Debian GNU/Linux comes with ABSOLUTELY NO WARRANTY, to the extent
permitted by applicable law.
Last login: Tue May  3 08:57:59 CEST 2022 from 10.0.2.1 on pts/0

trainee@debian11:~$ whoami
trainee

trainee@debian11:~$ pwd
/home/trainee

trainee@debian11:~$ exit
logout
Connection closed by foreign host.

Important - Notez bien que votre communication telnet passe par le tunnel SSH.

3.5 - SCP

Présentation

La commande scp est le successeur et la remplaçante de la commande rcp de la famille des commandes remote. Il permet de faire des transferts sécurisés à partir d'une machine distante :

$ scp compte@numero_ip(nom_de_machine):/chemin_distant/fichier_distant /chemin_local/fichier_local

ou vers une machine distante :

$ scp /chemin_local/fichier_local compte@numero_ip(nom_de_machine):/chemin_distant/fichier_distant

Utilisation

Nous allons maintenant utiliser scp pour chercher un fichier sur le «serveur» :

Créez le fichier /home/trainee/scp_test :

[trainee@centos8 ~]$ touch scp-test
[trainee@centos8 ~]$ exit
logout
Connection closed by foreign host.
[root@centos8 ~]# 

Récupérez le fichier scp_test en utilisant scp :

[root@centos8 ~]# scp trainee@127.0.0.1:/home/trainee/scp-test .
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:Q7T/CP0SLiMbMAIgVzTuEHegYS/spPE5zzQchCHD5Vw.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '127.0.0.1' (ECDSA) to the list of known hosts.
\S
Kernel \r on an \m
trainee@127.0.0.1's password: trainee
scp-test                                                                                                           100%    0     0.0KB/s   00:00    

[root@centos8 ~]# ls -l
total 32
-rw-------. 1 root root 1358 Jun 16 06:40 anaconda-ks.cfg
drwxr-xr-x. 3 root root   21 Jun 16 06:39 home
-rw-r--r--. 1 root root 1749 Aug 24 11:20 I2TCH.asc
-rw-r--r--. 1 root root 1853 Jun 16 06:54 initial-setup-ks.cfg
-rw-r--r--. 1 root root   31 Aug 24 11:22 message.txt
-rw-r--r--. 1 root root  561 Aug 24 11:32 message.txt.asc
-rw-r--r--. 1 root root  367 Aug 24 11:30 message.txt.gpg
-rw-r--r--. 1 root root  329 Aug 24 11:23 message.txt.sig
-rw-r--r--. 1 root root    0 Aug 30 03:55 scp-test
-rw-r--r--. 1 root root   46 Aug 29 06:22 wget_file.txt

3.6 - Mise en Place des Clefs Asymétriques

Il convient maintenant de se connecter sur le «serveur» en utilisant ssh et vérifiez la présence du répertoire ~/.ssh :

[root@centos8 ~]# ssh -l trainee 127.0.0.1
\S
Kernel \r on an \m
trainee@127.0.0.1's password: trainee
Activate the web console with: systemctl enable --now cockpit.socket

[trainee@centos8 ~]$ ls -la | grep .ssh
drwx------.  2 trainee trainee      4096 Aug 30 02:26 .ssh

Important - Si le dossier distant .ssh n'existe pas dans le répertoire personnel de l'utilisateur connecté, il faut le créer avec des permissions de 700. Dans votre cas, puisque votre machine joue le rôle de serveur et du client, le dossier /home/trainee/.ssh existe déjà.

Ensuite, il convient de transférer le fichier local .ssh/id_ecdsa.pub du «client» vers le «serveur» en le renommant en authorized_keys :

[trainee@centos8 ~]$ exit
logout
Connection to 127.0.0.1 closed.

[root@centos8 ~]# exit
logout

[trainee@centos8 ~]$ scp .ssh/id_ecdsa.pub trainee@127.0.0.1:/home/trainee/.ssh/authorized_keys
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
ECDSA key fingerprint is SHA256:Q7T/CP0SLiMbMAIgVzTuEHegYS/spPE5zzQchCHD5Vw.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added '127.0.0.1' (ECDSA) to the list of known hosts.
\S
Kernel \r on an \m
trainee@127.0.0.1's password: trainee
id_ecdsa.pub                                                                                                       100%  192   497.6KB/s   00:00

Connectez-vous via telnet :

[trainee@centos8 ~]$ ssh -l trainee localhost
The authenticity of host 'localhost (::1)' can't be established.
ECDSA key fingerprint is SHA256:Q7T/CP0SLiMbMAIgVzTuEHegYS/spPE5zzQchCHD5Vw.
Are you sure you want to continue connecting (yes/no/[fingerprint])? yes
Warning: Permanently added 'localhost' (ECDSA) to the list of known hosts.
\S
Kernel \r on an \m
Activate the web console with: systemctl enable --now cockpit.socket

Last login: Mon Aug 30 03:57:14 2021 from 127.0.0.1
[trainee@centos8 ~]$

Important - Lors de la connexion au serveur, l'authentification utilise le couple de clefs asymétrique au format ecdsa et aucun mot de passe n'est requis.

Insérez maintenant les clefs publiques restantes dans le fichier .ssh/authorized_keys :

[trainee@centos8 ~]$ cd .ssh
[trainee@centos8 .ssh]$ ls
authorized_keys  id_dsa  id_dsa.pub  id_ecdsa  id_ecdsa.pub  id_ed25519  id_ed25519.pub  id_rsa  id_rsa.pub  known_hosts
[trainee@centos8 .ssh]$ cat authorized_keys 
ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBHDrzSXP+Ecxf/sQ18VwCRNm7rrSrrsaJmuIw/RgTH5puKF5E+Yy15cvAAKBXpJPxUmrOaOyhab84PevV7XSHcI= trainee@centos8.ittraining.loc

[trainee@centos8 .ssh]$ cat id_rsa.pub >> authorized_keys
[trainee@centos8 .ssh]$ cat id_dsa.pub >> authorized_keys
[trainee@centos8 .ssh]$ cat id_ed25519.pub >> authorized_keys

[trainee@centos8 .ssh]$ cat authorized_keys
ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBHDrzSXP+Ecxf/sQ18VwCRNm7rrSrrsaJmuIw/RgTH5puKF5E+Yy15cvAAKBXpJPxUmrOaOyhab84PevV7XSHcI= trainee@centos8.ittraining.loc
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQD3ZSMn/GIAHtaDFc6ZNnKJam9hzq8TxqMN5IopUr8QhwODyPadbB+FgH4r50qTux4ubwr1BlymgIdqRVWy32mE15M8tdtKc3j8DNMpUwPGEh+s/PT7GW+3E3shoyPvpLc1kKaKXKGl/JwfCK/8IYsubk2BmiiJYkzLECotPlaaxm4w1K0AtlnZQuLHt1HK3/rHChxo2o2w1t59/QwNcMLiKve1Z+zQ1POKo8VJ/DDrf90y2QWC28ejUs/ZjP6f6C4bn5Jjol4TbHls3ArMsbU6C1Ev5jqbzZ0kmognQ2CnRjeNM51YdFo6nRsLoPQKpeLRMBpT/87HK1bPUOBVCyhXxSkqkVhMlgg8tgcD/MRlBaUVFoZ1wQ0L26Fe+q7c2Oykj54pdXCAK2ZTpCXGfhd/FxrfqGw7cSeKlGX4QUzHMjMk2oHFC9h30BUk1gGN21KJPTh7/S1OZVrnCc3GUi5fXPvEpral0IU0sws+j03dj0sWm5ICQFKRkmZN11HCyT0= trainee@centos8.ittraining.loc
ssh-dss AAAAB3NzaC1kc3MAAACBALIdwEEqHrMWSUdzARm9ldsZK9ebbtZShtmwgdjphOk77fxymK0y6wV7QEmLL25LOcLb12uZ1F0LtRt/t2oqgrwqk3vUSpCPLr09AXpcD/nxL9kc+rUxHyl6u1mHtyfCVLCPSvavCMR8TaA8egVMk3EwGRfHTiuDOKi7Iwus7gXPAAAAFQDHEQPGVRI7gVYKzCT6nrjDsQQ6jwAAAIEAhhhH7fEjdldASXY0qTWkCvcs3cfK9/Ff315zByn47O02y9Vdo3QG5nOr1Oo8fc2xEkIBNmFr8Rr2g60cpvEev5hy4XZ1ghxnQ53iwKuiS72ZATwhD6bZBrsiH0k1Et25gRcj5KCvDe/jHhbxCxsCuHUH2qvWsQNVwztE7hD0sxkAAACAQ8Dkpy8zXj7jW8o1txxf2W6J4r2+1lPldymA45ywZokN4SCwvXlpPAuyBt0/HiU0R2PI9aqOAMosCLcy9WmnSwLQ2Z7QcD2i3XlAih2+1q9NJP22sPT3jSK9UZcdRjoZ/eNiz84sXZucNape32tFxjvcV4txobH/vD53q8g63fA= trainee@centos8.ittraining.loc
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOfFQULLU8IZyKiSU63D2Zz6yGLqyHcBHnCRdSR9JSmc trainee@centos8.ittraining.loc

3.7 - Services réseaux

Quand un client émet une demande de connexion vers une application réseau sur un serveur, il utilise un socket attaché à un port local supérieur à 1023, alloué d'une manière dynamique. La requête contient le port de destination sur le serveur. Certaines applications serveurs se gèrent toutes seules, ce qui est la cas par exemple d'apache2. Par contre d'autres sont gérées par le service xinetd.

inetd

Le programme inetd est configuré via le fichier /etc/inetd.conf :

root@debian11:~# cat /etc/inetd.conf
# /etc/inetd.conf:  see inetd(8) for further informations.
#
# Internet superserver configuration database
#
#
# Lines starting with "#:LABEL:" or "#<off>#" should not
# be changed unless you know what you are doing!
#
# If you want to disable an entry so it isn't touched during
# package updates just comment it out with a single '#' character.
#
# Packages should modify this file by using update-inetd(8)
#
# <service_name> <sock_type> <proto> <flags> <user> <server_path> <args>
#
#:INTERNAL: Internal services
#discard                stream  tcp     nowait  root    internal
#discard                dgram   udp     wait    root    internal
#daytime                stream  tcp     nowait  root    internal
#time           stream  tcp     nowait  root    internal

#:STANDARD: These are standard services.
telnet          stream  tcp     nowait  telnetd /usr/sbin/tcpd  /usr/sbin/in.telnetd

#:BSD: Shell, login, exec and talk are BSD protocols.

#:MAIL: Mail, news and uucp services.

#:INFO: Info services

#:BOOT: TFTP service is provided primarily for booting.  Most sites
#       run this only on machines acting as "boot servers."

#:RPC: RPC based services

#:HAM-RADIO: amateur-radio services

#:OTHER: Other services

Les lignes de configuration des serveurs ressemblent à :

telnet          stream  tcp     nowait  telnetd /usr/sbin/tcpd  /usr/sbin/in.telnetd

Le premier champs de la ligne identifie le nom du port qui identifie l'application. Inetd lit ensuite le fichier /etc/services pour déduire le numéro de port concerné et se met à l'écoute de celui-ci.

Le deuxième et le troisième champs définissent le type de protocole, à savoir:

  • stream tcp pour le tcp
  • dgram udp pour l'udp

Le quatrième champs prend un de deux valeurs:

  • nowait
    • indique qu'il y aura un serveur par client
  • wait
    • indique qu'il y aura un seul serveur pour l'ensemble des clients

Le cinquième champs indique l'identité sous laquelle sera exécuté le serveur.

Le sixième champs indique l'exécutable. Dans ce cas c'est /usr/sbin/tcpd.

Le septième champs indique les arguments de l'application serveur dont l'argument 0 est le nom de l'application.

TCP Wrapper

Lors de l'utilisation d'inetd, TCP Wrapper est utilisé pour contrôler l'accès à des services réseaux grâce à des ACL :

telnet          stream  tcp     nowait  telnetd /usr/sbin/tcpd  /usr/sbin/in.telnetd

Quand une requête arrive pour le serveur telnet, inetd active le wrapper tcpd au lieu d'activer /usr/sbin/in.telnetd directement.

tcpd met à jour un journal et vérifie si le client a le droit d'utiliser le service concerné. Les ACL se trouvent dans deux fichiers:

root@debian11:~# cat /etc/hosts.allow
# /etc/hosts.allow: list of hosts that are allowed to access the system.
#                   See the manual pages hosts_access(5) and hosts_options(5).
#
# Example:    ALL: LOCAL @some_netgroup
#             ALL: .foobar.edu EXCEPT terminalserver.foobar.edu
#
# If you're going to protect the portmapper use the name "rpcbind" for the
# daemon name. See rpcbind(8) and rpc.mountd(8) for further information.
#

root@debian11:~# cat /etc/hosts.deny
# /etc/hosts.deny: list of hosts that are _not_ allowed to access the system.
#                  See the manual pages hosts_access(5) and hosts_options(5).
#
# Example:    ALL: some.host.name, .some.domain
#             ALL EXCEPT in.fingerd: other.host.name, .other.domain
#
# If you're going to protect the portmapper use the name "rpcbind" for the
# daemon name. See rpcbind(8) and rpc.mountd(8) for further information.
#
# The PARANOID wildcard matches any host whose name does not match its
# address.
#
# You may wish to enable this to ensure any programs that don't
# validate looked up hostnames still leave understandable logs. In past
# versions of Debian this has been the default.
# ALL: PARANOID

Il faut noter que si ces fichiers n'existent pas ou sont vides, il n'y a pas de contrôle d'accès.

Le format d'une ligne dans un de ces deux fichiers est:

démon: liste_de_clients

Par exemple dans le cas de notre serveur telnetd, une ligne dans le fichier /etc/hosts.allow similaire à:

in.telnetd: 192.168.1.10, .fenestros.com

implique que la machine dont le numéro IP est le 192.168.1.10 ainsi que les machines du domaine fenestros.com sont autorisées à utiliser le service.

Le mot clef ALL peut être utilisé pour indiquer tout. Par exemple, ALL:ALL dans le fichier /etc/host.deny bloque effectivement toute tentative de connexion à un service inetd sauf pour les ACL inclus dans le fichier /etc/host.allow.

Configuration du Réseau sous RHEL/CentOS 6

Configuration de TCP/IP

La configuration TCP/IP se trouve dans le répertoire /etc/sysconfig. Les fichiers importants sont :

DHCP

/etc/sysconfig/network
[root@centos6 ~]# cat /etc/sysconfig/network
NETWORKING=yes
HOSTNAME=centos6

Dans ce fichier vous pouvez constater les directives suivantes :

Directive Description
NETWORKING Indique que la prise en charge du réseau est activée
HOSTNAME Indique le nom d'hôte de la machine

Ce fichier peut également contenir les directives suivantes :

Directive Description
GATEWAY Indique l'adresse IPv4 de la passerelle
GATEWAYDEV Indique l'interface réseau utilisée pour accéder à la passerelle
NISDOMAIN Indique le domaine NIS s'il en existe un
NETWORKING_IPV6 Active ou désactive le support IPv6
/etc/sysconfig/network-scripts/ifcfg-ethX (où X=0,1 ...)

ifcfg-eth0

[root@centos6 ~]# cat /etc/sysconfig/network-scripts/ifcfg-eth0
DEVICE="eth0"
NM_CONTROLLED="yes"
ONBOOT=yes
TYPE=Ethernet
BOOTPROTO=dhcp
DEFROUTE=yes
IPV4_FAILURE_FATAL=yes
IPV6INIT=no
NAME="System eth0"
UUID=5fb06bd0-0bb0-7ffb-45f1-d6edd65f3e03
HWADDR=08:00:27:48:7D:7F
PEERDNS=yes
PEERROUTES=yes

Dans ce fichier vous pouvez constater les directives suivantes :

Directive Description
DEVICE Indique le nom de l'interface
NM_CONTROLLED Indique que le service NetworkManager est utilisé pour gérer les interfaces réseau
ONBOOT Indique que l'interface est activée au démarrage de la machine
TYPE Indique que le type de réseau est ethernet. Les valeurs permises sont ethernet ou wireless
BOOTPROTO Indique comment monter l'interface. Les valeurs permises sont dhcp, static ou bootp
DEFROUTE Définit l'interface en tant que passerelle par défaut
IPV4_FAILURE_FATAL Stipule que si IPv4 et IPv6 sont activés et la connexion IPv4 est perdue, la connexion IPv6 est considérée d'être perdue
IPV6INIT Indique que le support IPv6 ne sera pas initialisé
NAME Indique un nom descriptif de l'interface
UUID Indique la valeur de l'UUID de l'interface
HWADDR Indique l'adresse MAC de l'interface
PEERDNS Indique que le fichier /etc/resolv.conf doit être modifié automatiquement pour contenir les adresses IP des DNS fournies par le serveur DHCP

Recherchez la définition de la directive PEERROUTES=yes.

IP Fixe

/etc/sysconfig/network
NETWORKING=yes
NETWORKING_IPV6=no
HOSTNAME=centos6.fenestros.loc
/etc/sysconfig/network-scripts/ifcfg-ethX (où X=0,1 ...)

ifcfg-eth0

DEVICE="eth0"
NM_CONTROLLED="no"
ONBOOT=yes
TYPE=Ethernet
BOOTPROTO=static
IPV6INIT=no
HWADDR="08:00:27:9B:55:B1"
NETMASK=255.255.255.0
IPADDR=10.0.2.15
GATEWAY=10.0.2.2
DNS1=8.8.8.8
DNS2=8.8.4.4
DOMAIN=fenestros.loc
USERCTL=yes

Dans ce fichier vous pouvez constater les nouvelles directives suivantes :

Directive Description
NETMASK Indique le masque de sous-réseau IPv4 associé à l'interface
IPADDR Indique l'adresse IPv4 de l'interface
GATEWAY Indique l'adresse IPv4 de la passerelle par défaut
DNS1 Indique le DNS primaire
DNS2 Indique le DNS secondaire
DOMAIN Indique le nom du domaine local
USERCTL Indique que les utilisateurs normaux peuvent activer/désactiver l'interface

Notez que VirtualBox fournit une passerelle par défaut ( 10.0.2.2 ).

Après avoir modifier les deux fichiers /etc/sysconfig/network et /etc/sysconfig/network-scripts/ifcfg-eth0 vous devez désactiver le service NetworkManager utilisé pour la connexion DHCP et activer le service network :

[root@centos6 ~]# service NetworkManager stop
Arrêt du démon NetworkManager :                            [  OK  ]
[root@centos6 ~]# chkconfig --del NetworkManager
[root@centos6 ~]# service network start
Activation de l'interface loopback :                       [  OK  ]
Activation de l'interface eth0 :                           [  OK  ]
[root@centos6 ~]#

La Commande hostname

Lors du passage à une configuration en IPv4 fixe vous avez modifié la directive HOSTNAME du fichier /etc/sysconfig/network de centos à centos.fenestros.loc. Afin d'informer le système immédiatement de la modification du FQDN (Fully Qualified Domain Name), utilisez la commande hostname :

[root@centos6 ~]# hostname
centos6
[root@centos6 ~]# hostname centos6.fenestros.loc
[root@centos6 ~]# hostname
centos6.fenestros.loc

Pour afficher le FQDN du système vous pouvez également utiliser la commande suivante :

[root@centos6 ~]# uname -n
centos6.fenestros.loc

Options de la commande hostname

Les options de cette commande sont :

[root@centos6 ~]# hostname --help
Syntaxe : hostname [-v] {hôte|-F fichier}      définit le nom d'hôte (depuis le fichier)
       domainname [-v] {domaine_nis|-F fichier}   définit le domaine NIS (depuis le fichier)
       hostname [-v] [-d|-f|-s|-a|-i|-y]  display formatted name
       hostname [-v]                         affiche le nom d'hôte

       hostname -V|--version|-h|--help       affiche des infos et termine

    dnsdomainname=hostname -d, {yp,nis,}domainname=hostname -y

    -s, --short           nom d'hôte court
    -a, --alias           noms d'alias
    -i, --ip-address      adresses de l'hôte
    -f, --fqdn, --long    nom d'hôte long (FQDN)
    -d, --domain          nom de domaine DNS
    -y, --yp, --nis       nom de domaine NIS/YP
    -F, --file            read hostname or NIS domainname from given file

   This command can read or set the hostname or the NIS domainname. You can
   also read the DNS domain or the FQDN (fully qualified domain name).
   Unless you are using bind or NIS for host lookups you can change the
   FQDN (Fully Qualified Domain Name) and the DNS domain name (which is
   part of the FQDN) in the /etc/hosts file.

La Commande ifconfig

Pour afficher la configuration IP de la machine il faut saisir la commande suivante :

[root@centos6 ~]# ifconfig
eth0      Link encap:Ethernet  HWaddr 08:00:27:48:7D:7F  
          inet adr:10.0.2.15  Bcast:10.0.2.255  Masque:255.255.255.0
          adr inet6: fe80::a00:27ff:fe48:7d7f/64 Scope:Lien
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:16765 errors:0 dropped:0 overruns:0 frame:0
          TX packets:15256 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:1000 
          RX bytes:12435171 (11.8 MiB)  TX bytes:4767389 (4.5 MiB)

lo        Link encap:Boucle locale  
          inet adr:127.0.0.1  Masque:255.0.0.0
          adr inet6: ::1/128 Scope:Hôte
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:0 
          RX bytes:480 (480.0 b)  TX bytes:480 (480.0 b)

La commande ifconfig est également utilisée pour configurer une interface.

Créez maintenant une interface fictive ainsi :

[root@centos6 ~]# ifconfig eth0:1 192.168.1.2 netmask 255.255.255.0 broadcast 192.168.1.255

Constatez maintenant le résultat :

[root@centos6 ~]# ifconfig
eth0      Link encap:Ethernet  HWaddr 08:00:27:48:7D:7F  
          inet adr:10.0.2.15  Bcast:10.0.2.255  Masque:255.255.255.0
          adr inet6: fe80::a00:27ff:fe48:7d7f/64 Scope:Lien
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:16904 errors:0 dropped:0 overruns:0 frame:0
          TX packets:15337 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:1000 
          RX bytes:12445250 (11.8 MiB)  TX bytes:4816855 (4.5 MiB)

eth0:1    Link encap:Ethernet  HWaddr 08:00:27:48:7D:7F  
          inet adr:192.168.1.2  Bcast:192.168.1.255  Masque:255.255.255.0
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1

lo        Link encap:Boucle locale  
          inet adr:127.0.0.1  Masque:255.0.0.0
          adr inet6: ::1/128 Scope:Hôte
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:0 
          RX bytes:480 (480.0 b)  TX bytes:480 (480.0 b)

Options de la commande ifconfig

Les options de cette commande sont :

[root@centos6 ~]# ifconfig --help
Usage:
  ifconfig [-a] [-v] [-s] <interface> [[<AF>] <address>]
  [add <adresse>[/<lg_prefixe>]]
  [del <adresse>[/<lg_prefixe>]]
  [[-]broadcast [<adresse>]]  [[-]pointopoint [<adresse>]]
  [netmask <address>]  [dstaddr <address>]  [tunnel <address>]
  [outfill <NN>] [keepalive <NN>]
  [hw <HW> <adresse>]  [metric <NN>]  [mtu <NN>]
  [[-]trailers]  [[-]arp]  [[-]allmulti]
  [multicast]  [[-]promisc]
  [mem_start <NN>]  [io_addr <NN>]  [irq <NN>]  [media <type>]
  [txqueuelen <NN>]
  [[-]dynamic]
  [up|down] ...

  <HW>=Type de matériel.
  Liste des types de matériels possibles:
    loop (Boucle locale) slip (IP ligne série) cslip (IP ligne série - VJ ) 
    slip6 (IP ligne série - 6 bits) cslip6 (IP ligne série - 6 bits VJ) adaptive (IP ligne série adaptative) 
    strip (Metricom Starmode IP) ash (Ash) ether (Ethernet) 
    tr (16/4 Mbps Token Ring) tr (16/4 Mbps Token Ring (New)) ax25 (AMPR AX.25) 
    netrom (AMPR NET/ROM) rose (AMPR ROSE) tunnel (IPIP Tunnel) 
    ppp (Protocole Point-à-Point) hdlc ((Cisco)-HDLC) lapb (LAPB) 
    arcnet (ARCnet) dlci (Frame Relay DLCI) frad (Périphériue d'accès Frame Relay) 
    sit (IPv6-dans-IPv4) fddi (Fiber Distributed Data Interface) hippi (HIPPI) 
    irda (IrLAP) ec (Econet) x25 (generic X.25) 
    infiniband (InfiniBand) 
  <AF>=famille d'Adresses. Défaut: inet
  Liste des familles d'adresses possibles:
    unix (Domaine UNIX) inet (DARPA Internet) inet6 (IPv6) 
    ax25 (AMPR AX.25) netrom (AMPR NET/ROM) rose (AMPR ROSE) 
    ipx (Novell IPX) ddp (Appletalk DDP) ec (Econet) 
    ash (Ash) x25 (CCITT X.25) 

Activer/Désactiver une Interface Manuellement

Deux commandes existent pour activer et désactiver manuellement une interface réseau :

[root@centos6 ~]# ifdown eth0
[root@centos6 ~]# ifconfig
lo        Link encap:Boucle locale  
          inet adr:127.0.0.1  Masque:255.0.0.0
          adr inet6: ::1/128 Scope:Hôte
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:384 errors:0 dropped:0 overruns:0 frame:0
          TX packets:384 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:0 
          RX bytes:32496 (31.7 KiB)  TX bytes:32496 (31.7 KiB)

[root@centos6 ~]# ifup eth0
État de connexion active&nbsp;: activation
État de chemin actif&nbsp;: /org/freedesktop/NetworkManager/ActiveConnection/0
état&nbsp;: activé
Connexion activée
[root@centos6 ~]# ifconfig
eth0      Link encap:Ethernet  HWaddr 08:00:27:9B:55:B1  
          inet adr:10.0.2.15  Bcast:10.0.2.255  Masque:255.255.255.0
          adr inet6: fe80::a00:27ff:fe9b:55b1/64 Scope:Lien
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:27 errors:0 dropped:0 overruns:0 frame:0
          TX packets:42 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:1000 
          RX bytes:4271 (4.1 KiB)  TX bytes:6145 (6.0 KiB)

lo        Link encap:Boucle locale  
          inet adr:127.0.0.1  Masque:255.0.0.0
          adr inet6: ::1/128 Scope:Hôte
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:392 errors:0 dropped:0 overruns:0 frame:0
          TX packets:392 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 lg file transmission:0 
          RX bytes:33600 (32.8 KiB)  TX bytes:33600 (32.8 KiB)

/etc/networks

Ce fichier contient la correspondance entre des noms de réseaux et l'adresse IP du réseau :

[root@centos6 ~]# cat /etc/networks 
default 0.0.0.0
loopback 127.0.0.0
link-local 169.254.0.0

Résolution d'adresses IP

La configuration DNS est stockée dans le fichier /etc/resolv.conf.

/etc/resolv.conf

La configuration DNS est stockée dans le fichier /etc/resolv.conf :

[root@centos6 ~]# cat /etc/resolv.conf
# Generated by NetworkManager


# No nameservers found; try putting DNS servers into your
# ifcfg files in /etc/sysconfig/network-scripts like so:
#
# DNS1=xxx.xxx.xxx.xxx
# DNS2=xxx.xxx.xxx.xxx
# DOMAIN=lab.foo.com bar.foo.com
nameserver 8.8.8.8
nameserver 8.8.4.4
search fenestros.loc 

Notez que les DNS utilisés sont les serveurs DNS publics de Google.

/etc/nsswitch.conf

L'ordre de recherche des services de noms est stocké dans le fichier /etc/nsswitch.conf. Pour connaître l'ordre, saisissez la commande suivante :

[root@centos6 ~]# grep '^hosts:' /etc/nsswitch.conf
hosts:      files dns
/etc/hosts

Le mot files dans la sortie de la commande précédente fait référence au fichier /etc/hosts :

[root@centos6 ~]# cat /etc/hosts
10.0.2.15	centos6	# Added by NetworkManager
127.0.0.1	localhost.localdomain	localhost
::1	centos6	localhost6.localdomain6	localhost6

Pour tester le serveur DNS, deux commandes sont possibles :

[root@centos6 ~]# nslookup www.i2tch.com
Server:		8.8.8.8
Address:	8.8.8.8#53

Non-authoritative answer:
www.i2tch.com	canonical name = i2tch.com.
Name:	i2tch.com
Address: 90.119.37.144

[root@centos6 ~]# dig www.i2tch.com

; <<>> DiG 9.10.3-P4-Ubuntu <<>> www.i2tch.com
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 25061
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 65494
;; QUESTION SECTION:
;www.i2tch.com.			IN	A

;; ANSWER SECTION:
www.i2tch.com.		6563	IN	CNAME	i2tch.com.
i2tch.com.		50	IN	A	90.119.37.144

;; Query time: 1 msec
;; SERVER: 8.8.8.8#53(8.8.8.8)
;; WHEN: Mon Jan 22 18:00:27 CET 2018
;; MSG SIZE  rcvd: 72

Configuration du Réseau sous RHEL/CentOS 7

RHEL/CentOS 7 utilise exclusivement Network Manager pour gérer le réseau. Network Manager est composé de deux éléments :

  • un service qui gère les connexions réseaux et rapporte leurs états,
  • des front-ends qui passent par un API de configuration du service.

Important : Notez qu'avec cette version de NetworkManager, IPv6 est activée par défaut.

Le service NetworkManager doit toujours être lancé :

[root@centos7 ~]# systemctl status NetworkManager.service
● NetworkManager.service - Network Manager
   Loaded: loaded (/usr/lib/systemd/system/NetworkManager.service; enabled; vendor preset: enabled)
   Active: active (running) since Sun 2016-08-07 09:18:20 CEST; 1 day 1h ago
 Main PID: 673 (NetworkManager)
   CGroup: /system.slice/NetworkManager.service
           ├─ 673 /usr/sbin/NetworkManager --no-daemon
           └─2673 /sbin/dhclient -d -q -sf /usr/libexec/nm-dhcp-helper -pf /var/run/dhclient-enp0s3.pid -lf /var/lib/NetworkManager/dhclient-45b701c1-0a21-4d76-a795-...

Aug 08 11:03:55 centos7.fenestros.loc NetworkManager[673]: <info>    nameserver '8.8.8.8'
Aug 08 11:03:55 centos7.fenestros.loc NetworkManager[673]: <info>  (enp0s3): DHCPv4 state changed unknown -> bound
Aug 08 11:03:55 centos7.fenestros.loc NetworkManager[673]: <info>  (enp0s3): device state change: ip-config -> ip-check (reason 'none') [70 80 0]
Aug 08 11:03:55 centos7.fenestros.loc NetworkManager[673]: <info>  (enp0s3): device state change: ip-check -> secondaries (reason 'none') [80 90 0]
Aug 08 11:03:55 centos7.fenestros.loc NetworkManager[673]: <info>  (enp0s3): device state change: secondaries -> activated (reason 'none') [90 100 0]
Aug 08 11:03:55 centos7.fenestros.loc NetworkManager[673]: <info>  NetworkManager state is now CONNECTED_LOCAL
Aug 08 11:03:55 centos7.fenestros.loc NetworkManager[673]: <info>  NetworkManager state is now CONNECTED_GLOBAL
Aug 08 11:03:55 centos7.fenestros.loc NetworkManager[673]: <info>  Policy set 'Wired connection 1' (enp0s3) as default for IPv4 routing and DNS.
Aug 08 11:03:55 centos7.fenestros.loc NetworkManager[673]: <info>  (enp0s3): Activation: successful, device activated.
Aug 08 11:03:55 centos7.fenestros.loc dhclient[2673]: bound to 10.0.2.15 -- renewal in 39589 seconds.

La Commande nmcli

La commande nmcli (Network Manager Command Line Interface) est utilisée pour configurer NetworkManager.

Les options et les sous-commandes peuvent être consultées en utilisant les commandes suivantes :

[root@centos7 ~]# nmcli help
Usage: nmcli [OPTIONS] OBJECT { COMMAND | help }

OPTIONS
  -t[erse]                                   terse output
  -p[retty]                                  pretty output
  -m[ode] tabular|multiline                  output mode
  -f[ields] <field1,field2,...>|all|common   specify fields to output
  -e[scape] yes|no                           escape columns separators in values
  -n[ocheck]                                 don't check nmcli and NetworkManager versions
  -a[sk]                                     ask for missing parameters
  -w[ait] <seconds>                          set timeout waiting for finishing operations
  -v[ersion]                                 show program version
  -h[elp]                                    print this help

OBJECT
  g[eneral]       NetworkManager's general status and operations
  n[etworking]    overall networking control
  r[adio]         NetworkManager radio switches
  c[onnection]    NetworkManager's connections
  d[evice]        devices managed by NetworkManager
  a[gent]         NetworkManager secret agent or polkit agent

[root@centos7 ~]# nmcli g help
Usage: nmcli general { COMMAND | help }

COMMAND := { status | hostname | permissions | logging }

  status

  hostname [<hostname>]

  permissions

  logging [level <log level>] [domains <log domains>]


[root@centos7 ~]# nmcli g status help
Usage: nmcli general status { help }

Show overall status of NetworkManager.
'status' is the default action, which means 'nmcli gen' calls 'nmcli gen status'

Connections et Profils

NetworkManager inclus la notion de connections ou profils permettant des configurations différentes en fonction de la localisation. Pour voir les connections actuelles, utilisez la commande nmcli c avec la sous-commande show :

[root@centos7 ~]# nmcli c show
NAME                UUID                                  TYPE            DEVICE 
Wired connection 1  45b701c1-0a21-4d76-a795-2f2bcba86955  802-3-ethernet  enp0s3 

Comme on peut constater ici, il n'existe pour le moment, qu'un seul profil.

Créez donc un profil IP fixe rattaché au périphérique enp0s3 :

[root@centos7 ~]# nmcli connection add con-name ip_fixe ifname enp0s3 type ethernet ip4 10.0.2.16/24 gw4 10.0.2.2
Connection 'ip_fixe' (fb3a11d9-4e03-4032-b26e-09d1195d2bcd) successfully added.

Constatez sa présence :

[root@centos7 ~]# nmcli c show
NAME                UUID                                  TYPE            DEVICE 
ip_fixe             fb3a11d9-4e03-4032-b26e-09d1195d2bcd  802-3-ethernet  --     
Wired connection 1  45b701c1-0a21-4d76-a795-2f2bcba86955  802-3-ethernet  enp0s3  

Notez que la sortie n'indique pas que le profil ip_fixe soit associé au periphérique enp0s3 car le profil ip_fixe n'est pas activé :

[root@centos7 ~]# nmcli d show
GENERAL.DEVICE:                         enp0s3
GENERAL.TYPE:                           ethernet
GENERAL.HWADDR:                         08:00:27:03:97:DD
GENERAL.MTU:                            1500
GENERAL.STATE:                          100 (connected)
GENERAL.CONNECTION:                     Wired connection 1
GENERAL.CON-PATH:                       /org/freedesktop/NetworkManager/ActiveConnection/2
WIRED-PROPERTIES.CARRIER:               on
IP4.ADDRESS[1]:                         10.0.2.15/24
IP4.GATEWAY:                            10.0.2.2
IP4.DNS[1]:                             8.8.8.8
IP6.ADDRESS[1]:                         fe80::a00:27ff:fe03:97dd/64
IP6.GATEWAY:                            

GENERAL.DEVICE:                         lo
GENERAL.TYPE:                           loopback
GENERAL.HWADDR:                         00:00:00:00:00:00
GENERAL.MTU:                            65536
GENERAL.STATE:                          10 (unmanaged)
GENERAL.CONNECTION:                     --
GENERAL.CON-PATH:                       --
IP4.ADDRESS[1]:                         127.0.0.1/8
IP4.GATEWAY:                            
IP6.ADDRESS[1]:                         ::1/128
IP6.GATEWAY:

Pour activer le profil ip_fixe, utilisez la commande suivante :

[root@centos7 ~]# nmcli connection up ip_fixe

Le profil ip_fixe est maintenant activé tandis que le profil enp0s3 a été désactivé :

[root@centos7 ~]# nmcli c show
NAME                UUID                                  TYPE            DEVICE 
ip_fixe             fb3a11d9-4e03-4032-b26e-09d1195d2bcd  802-3-ethernet  enp0s3 
Wired connection 1  45b701c1-0a21-4d76-a795-2f2bcba86955  802-3-ethernet  --     
[root@centos7 ~]# nmcli d show
GENERAL.DEVICE:                         enp0s3
GENERAL.TYPE:                           ethernet
GENERAL.HWADDR:                         08:00:27:03:97:DD
GENERAL.MTU:                            1500
GENERAL.STATE:                          100 (connected)
GENERAL.CONNECTION:                     ip_fixe
GENERAL.CON-PATH:                       /org/freedesktop/NetworkManager/ActiveConnection/3
WIRED-PROPERTIES.CARRIER:               on
IP4.ADDRESS[1]:                         10.0.2.16/24
IP4.GATEWAY:                            10.0.2.2
IP6.ADDRESS[1]:                         fe80::a00:27ff:fe03:97dd/64
IP6.GATEWAY:                            

GENERAL.DEVICE:                         lo
GENERAL.TYPE:                           loopback
GENERAL.HWADDR:                         00:00:00:00:00:00
GENERAL.MTU:                            65536
GENERAL.STATE:                          10 (unmanaged)
GENERAL.CONNECTION:                     --
GENERAL.CON-PATH:                       --
IP4.ADDRESS[1]:                         127.0.0.1/8
IP4.GATEWAY:                            
IP6.ADDRESS[1]:                         ::1/128
IP6.GATEWAY: 

Pour consulter les paramètres d'un profil, utilisez la commande suivante :

[root@centos7 ~]# nmcli -p connection show "Wired connection 1"
===============================================================================
                Connection profile details (Wired connection 1)
===============================================================================
connection.id:                          Wired connection 1
connection.uuid:                        45b701c1-0a21-4d76-a795-2f2bcba86955
connection.interface-name:              --
connection.type:                        802-3-ethernet
connection.autoconnect:                 yes
connection.autoconnect-priority:        0
connection.timestamp:                   1470647387
connection.read-only:                   no
connection.permissions:                 
connection.zone:                        --
connection.master:                      --
connection.slave-type:                  --
connection.autoconnect-slaves:          -1 (default)
connection.secondaries:                 
connection.gateway-ping-timeout:        0
connection.metered:                     unknown
-------------------------------------------------------------------------------
802-3-ethernet.port:                    --
802-3-ethernet.speed:                   0
802-3-ethernet.duplex:                  --
802-3-ethernet.auto-negotiate:          yes
802-3-ethernet.mac-address:             08:00:27:03:97:DD
802-3-ethernet.cloned-mac-address:      --
802-3-ethernet.mac-address-blacklist:   
802-3-ethernet.mtu:                     auto
802-3-ethernet.s390-subchannels:        
802-3-ethernet.s390-nettype:            --
802-3-ethernet.s390-options:            
802-3-ethernet.wake-on-lan:             1 (default)
802-3-ethernet.wake-on-lan-password:    --
-------------------------------------------------------------------------------
ipv4.method:                            auto
ipv4.dns:                               
ipv4.dns-search:                        
ipv4.addresses:                         
ipv4.gateway:                           --
ipv4.routes:                            
ipv4.route-metric:                      -1
ipv4.ignore-auto-routes:                no
ipv4.ignore-auto-dns:                   no
ipv4.dhcp-client-id:                    --
ipv4.dhcp-send-hostname:                yes
ipv4.dhcp-hostname:                     --
ipv4.never-default:                     no
ipv4.may-fail:                          yes
-------------------------------------------------------------------------------
ipv6.method:                            auto
ipv6.dns:                               
ipv6.dns-search:                        
ipv6.addresses:                         
ipv6.gateway:                           --
ipv6.routes:                            
ipv6.route-metric:                      -1
ipv6.ignore-auto-routes:                no
ipv6.ignore-auto-dns:                   no
ipv6.never-default:                     no
ipv6.may-fail:                          yes
ipv6.ip6-privacy:                       -1 (unknown)
ipv6.dhcp-send-hostname:                yes
ipv6.dhcp-hostname:                     --
-------------------------------------------------------------------------------
[root@centos7 ~]# nmcli -p connection show ip_fixe
===============================================================================
                     Connection profile details (ip_fixe)
===============================================================================
connection.id:                          ip_fixe
connection.uuid:                        fb3a11d9-4e03-4032-b26e-09d1195d2bcd
connection.interface-name:              enp0s3
connection.type:                        802-3-ethernet
connection.autoconnect:                 yes
connection.autoconnect-priority:        0
connection.timestamp:                   1470647577
connection.read-only:                   no
connection.permissions:                 
connection.zone:                        --
connection.master:                      --
connection.slave-type:                  --
connection.autoconnect-slaves:          -1 (default)
connection.secondaries:                 
connection.gateway-ping-timeout:        0
connection.metered:                     unknown
-------------------------------------------------------------------------------
802-3-ethernet.port:                    --
802-3-ethernet.speed:                   0
802-3-ethernet.duplex:                  --
802-3-ethernet.auto-negotiate:          yes
802-3-ethernet.mac-address:             --
802-3-ethernet.cloned-mac-address:      --
802-3-ethernet.mac-address-blacklist:   
802-3-ethernet.mtu:                     auto
802-3-ethernet.s390-subchannels:        
802-3-ethernet.s390-nettype:            --
802-3-ethernet.s390-options:            
802-3-ethernet.wake-on-lan:             1 (default)
802-3-ethernet.wake-on-lan-password:    --
-------------------------------------------------------------------------------
ipv4.method:                            manual
ipv4.dns:                               
ipv4.dns-search:                        
ipv4.addresses:                         10.0.2.16/24
ipv4.gateway:                           10.0.2.2
ipv4.routes:                            
ipv4.route-metric:                      -1
ipv4.ignore-auto-routes:                no
ipv4.ignore-auto-dns:                   no
ipv4.dhcp-client-id:                    --
ipv4.dhcp-send-hostname:                yes
ipv4.dhcp-hostname:                     --
ipv4.never-default:                     no
ipv4.may-fail:                          yes
-------------------------------------------------------------------------------
ipv6.method:                            auto
ipv6.dns:                               
ipv6.dns-search:                        
ipv6.addresses:                         
ipv6.gateway:                           --
ipv6.routes:                            
ipv6.route-metric:                      -1
ipv6.ignore-auto-routes:                no
ipv6.ignore-auto-dns:                   no
ipv6.never-default:                     no
ipv6.may-fail:                          yes
ipv6.ip6-privacy:                       -1 (unknown)
ipv6.dhcp-send-hostname:                yes
ipv6.dhcp-hostname:                     --
-------------------------------------------------------------------------------
===============================================================================
      Activate connection details (fb3a11d9-4e03-4032-b26e-09d1195d2bcd)
===============================================================================
GENERAL.NAME:                           ip_fixe
GENERAL.UUID:                           fb3a11d9-4e03-4032-b26e-09d1195d2bcd
GENERAL.DEVICES:                        enp0s3
GENERAL.STATE:                          activated
GENERAL.DEFAULT:                        yes
GENERAL.DEFAULT6:                       no
GENERAL.VPN:                            no
GENERAL.ZONE:                           --
GENERAL.DBUS-PATH:                      /org/freedesktop/NetworkManager/ActiveConnection/3
GENERAL.CON-PATH:                       /org/freedesktop/NetworkManager/Settings/1
GENERAL.SPEC-OBJECT:                    /
GENERAL.MASTER-PATH:                    --
-------------------------------------------------------------------------------
IP4.ADDRESS[1]:                         10.0.2.16/24
IP4.GATEWAY:                            10.0.2.2
-------------------------------------------------------------------------------
IP6.ADDRESS[1]:                         fe80::a00:27ff:fe03:97dd/64
IP6.GATEWAY:                            
-------------------------------------------------------------------------------

Pour consulter la liste profils associés à un périphérique, utilisez la commande suivante :

[root@centos7 ~]# nmcli -f CONNECTIONS device show enp0s3
CONNECTIONS.AVAILABLE-CONNECTION-PATHS: /org/freedesktop/NetworkManager/Settings/{0,1}
CONNECTIONS.AVAILABLE-CONNECTIONS[1]:   45b701c1-0a21-4d76-a795-2f2bcba86955 | Wired connection 1
CONNECTIONS.AVAILABLE-CONNECTIONS[2]:   fb3a11d9-4e03-4032-b26e-09d1195d2bcd | ip_fixe

Les fichiers de configuration pour le periphérique enp0s3 se trouvent dans le répertoire /etc/sysconfig/network-scripts/ :

[root@centos7 ~]# ls -l /etc/sysconfig/network-scripts/ | grep ifcfg
-rw-r--r--. 1 root root   296 Aug  8 11:08 ifcfg-ip_fixe
-rw-r--r--. 1 root root   254 Sep 16  2015 ifcfg-lo

L'étude du fichier /etc/sysconfig/network-scripts/ifcfg-ip_fixe démontre l'abscence de directives concernant les DNS :

[root@centos7 ~]# cat /etc/sysconfig/network-scripts/ifcfg-ip_fixe
TYPE=Ethernet
BOOTPROTO=none
IPADDR=10.0.2.16
PREFIX=24
GATEWAY=10.0.2.2
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes
IPV6_FAILURE_FATAL=no
NAME=ip_fixe
UUID=fb3a11d9-4e03-4032-b26e-09d1195d2bcd
DEVICE=enp0s3
ONBOOT=yes

La résolution des noms est donc inactive :

[root@centos7 ~]# ping www.free.fr
ping: unknown host www.free.fr

Modifiez donc la configuration du profil ip_fixe :

[root@centos7 ~]# nmcli connection mod ip_fixe ipv4.dns 8.8.8.8

L'étude du fichier /etc/sysconfig/network-scripts/ifcfg-ip_fixe démontre que la directive concernant le serveur DNS a été ajoutée :

[root@centos7 ~]# cat /etc/sysconfig/network-scripts/ifcfg-ip_fixe
TYPE=Ethernet
BOOTPROTO=none
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
NAME=ip_fixe
UUID=fb3a11d9-4e03-4032-b26e-09d1195d2bcd
DEVICE=enp0s3
ONBOOT=yes
IPADDR=10.0.2.16
PREFIX=24
GATEWAY=10.0.2.2
DNS1=8.8.8.8
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes

Afin que la modification du serveur DNS soit prise en compte, re-démarrez le service NetworkManager :

[root@centos7 ~]# systemctl restart NetworkManager.service
[root@centos7 ~]# systemctl status NetworkManager.service
● NetworkManager.service - Network Manager
   Loaded: loaded (/usr/lib/systemd/system/NetworkManager.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2016-08-08 11:16:53 CEST; 7s ago
 Main PID: 8394 (NetworkManager)
   CGroup: /system.slice/NetworkManager.service
           └─8394 /usr/sbin/NetworkManager --no-daemon

Aug 08 11:16:53 centos7.fenestros.loc NetworkManager[8394]: <info>  (enp0s3): device state change: prepare -> config (reason 'none') [40 50 0]
Aug 08 11:16:53 centos7.fenestros.loc NetworkManager[8394]: <info>  (enp0s3): device state change: config -> ip-config (reason 'none') [50 70 0]
Aug 08 11:16:53 centos7.fenestros.loc NetworkManager[8394]: <info>  (enp0s3): device state change: ip-config -> ip-check (reason 'none') [70 80 0]
Aug 08 11:16:53 centos7.fenestros.loc NetworkManager[8394]: <info>  (enp0s3): device state change: ip-check -> secondaries (reason 'none') [80 90 0]
Aug 08 11:16:53 centos7.fenestros.loc NetworkManager[8394]: <info>  (enp0s3): device state change: secondaries -> activated (reason 'none') [90 100 0]
Aug 08 11:16:53 centos7.fenestros.loc NetworkManager[8394]: <info>  NetworkManager state is now CONNECTED_LOCAL
Aug 08 11:16:53 centos7.fenestros.loc NetworkManager[8394]: <info>  NetworkManager state is now CONNECTED_GLOBAL
Aug 08 11:16:53 centos7.fenestros.loc NetworkManager[8394]: <info>  Policy set 'ip_fixe' (enp0s3) as default for IPv4 routing and DNS.
Aug 08 11:16:53 centos7.fenestros.loc NetworkManager[8394]: <info>  (enp0s3): Activation: successful, device activated.
Aug 08 11:16:53 centos7.fenestros.loc NetworkManager[8394]: <info>  wpa_supplicant running

Vérifiez que le fichier /etc/resolv.conf ait été modifié par NetworkManager :

[root@centos7 ~]# cat /etc/resolv.conf
# Generated by NetworkManager
search fenestros.loc
nameserver 8.8.8.8

Dernièrement vérifiez la resolution des noms :

[root@centos7 ~]# ping www.free.fr
PING www.free.fr (212.27.48.10) 56(84) bytes of data.
64 bytes from www.free.fr (212.27.48.10): icmp_seq=1 ttl=63 time=10.4 ms
64 bytes from www.free.fr (212.27.48.10): icmp_seq=2 ttl=63 time=9.44 ms
64 bytes from www.free.fr (212.27.48.10): icmp_seq=3 ttl=63 time=12.1 ms
^C
--- www.free.fr ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2002ms
rtt min/avg/max/mdev = 9.448/10.680/12.171/1.126 ms

Important : Notez qu'il existe un front-end graphique en mode texte, nmtui, pour configurer NetworkManager.

Ajouter une Deuxième Adresse IP à un Profil

Pour ajouter une deuxième adresse IP à un profil sous RHEL/CentOS 7, il convient d'utiliser la commande suivante :

[root@centos7 ~]# nmcli connection mod ip_fixe +ipv4.addresses 192.168.1.2/24

Redémarrez la machine virtuelle puis en tant que root saisissez la commande suivante :

[root@centos7 ~]# nmcli connection show ip_fixe
connection.id:                          ip_fixe
connection.uuid:                        fb3a11d9-4e03-4032-b26e-09d1195d2bcd
connection.interface-name:              enp0s3
connection.type:                        802-3-ethernet
connection.autoconnect:                 yes
connection.autoconnect-priority:        0
connection.timestamp:                   1470555543
connection.read-only:                   no
connection.permissions:                 
connection.zone:                        --
connection.master:                      --
connection.slave-type:                  --
connection.autoconnect-slaves:          -1 (default)
connection.secondaries:                 
connection.gateway-ping-timeout:        0
connection.metered:                     unknown
802-3-ethernet.port:                    --
802-3-ethernet.speed:                   0
802-3-ethernet.duplex:                  --
802-3-ethernet.auto-negotiate:          yes
802-3-ethernet.mac-address:             --
802-3-ethernet.cloned-mac-address:      --
802-3-ethernet.mac-address-blacklist:   
802-3-ethernet.mtu:                     auto
802-3-ethernet.s390-subchannels:        
802-3-ethernet.s390-nettype:            --
802-3-ethernet.s390-options:            
802-3-ethernet.wake-on-lan:             1 (default)
802-3-ethernet.wake-on-lan-password:    --
ipv4.method:                            manual
ipv4.dns:                               8.8.8.8
ipv4.dns-search:                        
ipv4.addresses:                         10.0.2.16/24, 192.168.1.2/24
ipv4.gateway:                           10.0.2.2
ipv4.routes:                            
ipv4.route-metric:                      -1
ipv4.ignore-auto-routes:                no
ipv4.ignore-auto-dns:                   no
ipv4.dhcp-client-id:                    --
ipv4.dhcp-send-hostname:                yes
ipv4.dhcp-hostname:                     --
ipv4.never-default:                     no
ipv4.may-fail:                          yes
ipv6.method:                            auto
ipv6.dns:                               
ipv6.dns-search:                        
ipv6.addresses:                         
ipv6.gateway:                           --
ipv6.routes:                            
ipv6.route-metric:                      -1
ipv6.ignore-auto-routes:                no
ipv6.ignore-auto-dns:                   no
ipv6.never-default:                     no
ipv6.may-fail:                          yes
ipv6.ip6-privacy:                       -1 (unknown)
ipv6.dhcp-send-hostname:                yes
ipv6.dhcp-hostname:                     --
GENERAL.NAME:                           ip_fixe
GENERAL.UUID:                           fb3a11d9-4e03-4032-b26e-09d1195d2bcd
GENERAL.DEVICES:                        enp0s3
GENERAL.STATE:                          activated
GENERAL.DEFAULT:                        yes
GENERAL.DEFAULT6:                       no
GENERAL.VPN:                            no
GENERAL.ZONE:                           --
GENERAL.DBUS-PATH:                      /org/freedesktop/NetworkManager/ActiveConnection/0
GENERAL.CON-PATH:                       /org/freedesktop/NetworkManager/Settings/0
GENERAL.SPEC-OBJECT:                    /
GENERAL.MASTER-PATH:                    --
IP4.ADDRESS[1]:                         10.0.2.16/24
IP4.ADDRESS[2]:                         192.168.1.2/24
IP4.GATEWAY:                            10.0.2.2
IP4.DNS[1]:                             8.8.8.8
IP6.ADDRESS[1]:                         fe80::a00:27ff:fe03:97dd/64
IP6.GATEWAY: 

Important : Notez l'ajout de la ligne IP4.ADDRESS[2]:.

Consultez maintenant le contenu du fichier /etc/sysconfig/network-scripts/ifcfg-ip_fixe :

[root@centos7 ~]# cat /etc/sysconfig/network-scripts/ifcfg-ip_fixe
TYPE=Ethernet
BOOTPROTO=none
DEFROUTE=yes
IPV4_FAILURE_FATAL=no
IPV6INIT=yes
IPV6_AUTOCONF=yes
IPV6_DEFROUTE=yes
IPV6_FAILURE_FATAL=no
NAME=ip_fixe
UUID=fb3a11d9-4e03-4032-b26e-09d1195d2bcd
DEVICE=enp0s3
ONBOOT=yes
DNS1=8.8.8.8
IPADDR=10.0.2.16
PREFIX=24
IPADDR1=192.168.1.2
PREFIX1=24
GATEWAY=10.0.2.2
IPV6_PEERDNS=yes
IPV6_PEERROUTES=yes

Important : Notez l'ajout de la ligne IPADDR1=192.168.1.2.

La Commande hostname

La procédure de la modification du hostname est simplifiée et sa prise en compte est immédiate :

[root@centos7 ~]# nmcli general hostname centos.fenestros.loc
[root@centos7 ~]# cat /etc/hostname
centos.fenestros.loc
[root@centos7 ~]# hostname
centos.fenestros.loc
[root@centos7 ~]# nmcli general hostname centos7.fenestros.loc
[root@centos7 ~]# cat /etc/hostname
centos7.fenestros.loc
[root@centos7 ~]# hostname
centos7.fenestros.loc

La Commande ip

Sous RHEL/CentOS 7 la commande ip est préférée par rapport à la commande ifconfig :

[root@centos7 ~]# ip address
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:03:97:dd brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.16/24 brd 10.0.2.255 scope global enp0s3
       valid_lft forever preferred_lft forever
    inet 192.168.1.2/24 brd 192.168.1.255 scope global enp0s3
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe03:97dd/64 scope link 
       valid_lft forever preferred_lft forever
[root@centos7 ~]# ip addr
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: enp0s3: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 08:00:27:03:97:dd brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.16/24 brd 10.0.2.255 scope global enp0s3
       valid_lft forever preferred_lft forever
    inet 192.168.1.2/24 brd 192.168.1.255 scope global enp0s3
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fe03:97dd/64 scope link 
       valid_lft forever preferred_lft forever

Options de la Commande ip

Les options de cette commande sont :

[root@centos7 ~]# ip --help
Usage: ip [ OPTIONS ] OBJECT { COMMAND | help }
       ip [ -force ] -batch filename
where  OBJECT := { link | addr | addrlabel | route | rule | neigh | ntable |
                   tunnel | tuntap | maddr | mroute | mrule | monitor | xfrm |
                   netns | l2tp | tcp_metrics | token }
       OPTIONS := { -V[ersion] | -s[tatistics] | -d[etails] | -r[esolve] |
                    -f[amily] { inet | inet6 | ipx | dnet | bridge | link } |
                    -4 | -6 | -I | -D | -B | -0 |
                    -l[oops] { maximum-addr-flush-attempts } |
                    -o[neline] | -t[imestamp] | -b[atch] [filename] |
                    -rc[vbuf] [size]}

Activer/Désactiver une Interface Manuellement

Deux commandes existent pour désactiver et activer manuellement une interface réseau :

[root@centos7 ~]# nmcli device disconnect enp0s3
[root@centos7 ~]# nmcli device connect enp0s3

Routage Statique

La commande ip

Sous RHEL/CentOS 7, pour supprimer la route vers le réseau 192.168.1.0 il convient d'utiliser la commande ip et non pas la commande route :

[root@centos7 ~]# ip route
default via 10.0.2.2 dev enp0s3  proto static  metric 100 
10.0.2.0/24 dev enp0s3  proto kernel  scope link  src 10.0.2.16  metric 100 
192.168.1.0/24 dev enp0s3  proto kernel  scope link  src 192.168.1.2  metric 100 

[root@centos7 ~]# ip route del 192.168.1.0/24 via 0.0.0.0

[root@centos7 ~]# ip route
default via 10.0.2.2 dev enp0s3  proto static  metric 100 
10.0.2.0/24 dev enp0s3  proto kernel  scope link  src 10.0.2.16  metric 100 

Pour ajouter la route vers le réseau 192.168.1.0 :

[root@centos7 ~]# ip route add 192.168.1.0/24 via 10.0.2.2

[root@centos7 ~]# ip route
default via 10.0.2.2 dev enp0s3  proto static  metric 100 
10.0.2.0/24 dev enp0s3  proto kernel  scope link  src 10.0.2.16  metric 100 
192.168.1.0/24 via 10.0.2.2 dev enp0s3

La commande utilisée pour ajouter une passerelle par défaut prend la forme suivante ip route add default via adresse ip.

Activer/désactiver le routage sur le serveur

Pour activer le routage sur le serveur, il convient d'activer la retransmission des paquets:

[root@centos7 ~]# echo 1 > /proc/sys/net/ipv4/ip_forward
[root@centos7 ~]# cat /proc/sys/net/ipv4/ip_forward
1

Pour désactiver le routage sur le serveur, il convient de désactiver la retransmission des paquets:

[root@centos7 ~]# echo 0 > /proc/sys/net/ipv4/ip_forward
[root@centos7 ~]# cat /proc/sys/net/ipv4/ip_forward
0

LAB #4 - Utilisation de nmap et de netcat

4.1 - nmap

Installation

Sous RHEL/CentOS 7, nmap n'est pas installé par défaut :

[root@centos7 ~]# which nmap
/usr/bin/which: no nmap in (/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin:/root/bin)

Installez donc nmap en utilisant yum :

[root@centos7 ~]# yum install nmap
Loaded plugins: fastestmirror, langpacks
Repodata is over 2 weeks old. Install yum-cron? Or run: yum makecache fast
adobe-linux-x86_64                                       | 2.9 kB     00:00     
base                                                     | 3.6 kB     00:00     
extras                                                   | 3.4 kB     00:00     
updates                                                  | 3.4 kB     00:00     
(1/3): adobe-linux-x86_64/primary_db                       | 2.7 kB   00:00     
(2/3): extras/7/x86_64/primary_db                          | 191 kB   00:00     
(3/3): updates/7/x86_64/primary_db                         | 7.8 MB   00:04     
Determining fastest mirrors
 * base: ftp.rezopole.net
 * extras: ftp.rezopole.net
 * updates: ftp.rezopole.net
Resolving Dependencies
--> Running transaction check
---> Package nmap.x86_64 2:6.40-7.el7 will be installed
--> Processing Dependency: nmap-ncat = 2:6.40-7.el7 for package: 2:nmap-6.40-7.el7.x86_64
--> Running transaction check
---> Package nmap-ncat.x86_64 2:6.40-7.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package            Arch            Version                 Repository     Size
================================================================================
Installing:
 nmap               x86_64          2:6.40-7.el7            base          4.0 M
Installing for dependencies:
 nmap-ncat          x86_64          2:6.40-7.el7            base          201 k

Transaction Summary
================================================================================
Install  1 Package (+1 Dependent package)

Total download size: 4.2 M
Installed size: 17 M
Is this ok [y/d/N]: y

Les options de cette commande sont :

[root@centos7 ~]# nmap --help
Nmap 6.40 ( http://nmap.org )
Usage: nmap [Scan Type(s)] [Options] {target specification}
TARGET SPECIFICATION:
  Can pass hostnames, IP addresses, networks, etc.
  Ex: scanme.nmap.org, microsoft.com/24, 192.168.0.1; 10.0.0-255.1-254
  -iL <inputfilename>: Input from list of hosts/networks
  -iR <num hosts>: Choose random targets
  --exclude <host1[,host2][,host3],...>: Exclude hosts/networks
  --excludefile <exclude_file>: Exclude list from file
HOST DISCOVERY:
  -sL: List Scan - simply list targets to scan
  -sn: Ping Scan - disable port scan
  -Pn: Treat all hosts as online -- skip host discovery
  -PS/PA/PU/PY[portlist]: TCP SYN/ACK, UDP or SCTP discovery to given ports
  -PE/PP/PM: ICMP echo, timestamp, and netmask request discovery probes
  -PO[protocol list]: IP Protocol Ping
  -n/-R: Never do DNS resolution/Always resolve [default: sometimes]
  --dns-servers <serv1[,serv2],...>: Specify custom DNS servers
  --system-dns: Use OS's DNS resolver
  --traceroute: Trace hop path to each host
SCAN TECHNIQUES:
  -sS/sT/sA/sW/sM: TCP SYN/Connect()/ACK/Window/Maimon scans
  -sU: UDP Scan
  -sN/sF/sX: TCP Null, FIN, and Xmas scans
  --scanflags <flags>: Customize TCP scan flags
  -sI <zombie host[:probeport]>: Idle scan
  -sY/sZ: SCTP INIT/COOKIE-ECHO scans
  -sO: IP protocol scan
  -b <FTP relay host>: FTP bounce scan
PORT SPECIFICATION AND SCAN ORDER:
  -p <port ranges>: Only scan specified ports
    Ex: -p22; -p1-65535; -p U:53,111,137,T:21-25,80,139,8080,S:9
  -F: Fast mode - Scan fewer ports than the default scan
  -r: Scan ports consecutively - don't randomize
  --top-ports <number>: Scan <number> most common ports
  --port-ratio <ratio>: Scan ports more common than <ratio>
SERVICE/VERSION DETECTION:
  -sV: Probe open ports to determine service/version info
  --version-intensity <level>: Set from 0 (light) to 9 (try all probes)
  --version-light: Limit to most likely probes (intensity 2)
  --version-all: Try every single probe (intensity 9)
  --version-trace: Show detailed version scan activity (for debugging)
SCRIPT SCAN:
  -sC: equivalent to --script=default
  --script=<Lua scripts>: <Lua scripts> is a comma separated list of 
           directories, script-files or script-categories
  --script-args=<n1=v1,[n2=v2,...]>: provide arguments to scripts
  --script-args-file=filename: provide NSE script args in a file
  --script-trace: Show all data sent and received
  --script-updatedb: Update the script database.
  --script-help=<Lua scripts>: Show help about scripts.
           <Lua scripts> is a comma separted list of script-files or
           script-categories.
OS DETECTION:
  -O: Enable OS detection
  --osscan-limit: Limit OS detection to promising targets
  --osscan-guess: Guess OS more aggressively
TIMING AND PERFORMANCE:
  Options which take <time> are in seconds, or append 'ms' (milliseconds),
  's' (seconds), 'm' (minutes), or 'h' (hours) to the value (e.g. 30m).
  -T<0-5>: Set timing template (higher is faster)
  --min-hostgroup/max-hostgroup <size>: Parallel host scan group sizes
  --min-parallelism/max-parallelism <numprobes>: Probe parallelization
  --min-rtt-timeout/max-rtt-timeout/initial-rtt-timeout <time>: Specifies
      probe round trip time.
  --max-retries <tries>: Caps number of port scan probe retransmissions.
  --host-timeout <time>: Give up on target after this long
  --scan-delay/--max-scan-delay <time>: Adjust delay between probes
  --min-rate <number>: Send packets no slower than <number> per second
  --max-rate <number>: Send packets no faster than <number> per second
FIREWALL/IDS EVASION AND SPOOFING:
  -f; --mtu <val>: fragment packets (optionally w/given MTU)
  -D <decoy1,decoy2[,ME],...>: Cloak a scan with decoys
  -S <IP_Address>: Spoof source address
  -e <iface>: Use specified interface
  -g/--source-port <portnum>: Use given port number
  --data-length <num>: Append random data to sent packets
  --ip-options <options>: Send packets with specified ip options
  --ttl <val>: Set IP time-to-live field
  --spoof-mac <mac address/prefix/vendor name>: Spoof your MAC address
  --badsum: Send packets with a bogus TCP/UDP/SCTP checksum
OUTPUT:
  -oN/-oX/-oS/-oG <file>: Output scan in normal, XML, s|<rIpt kIddi3,
     and Grepable format, respectively, to the given filename.
  -oA <basename>: Output in the three major formats at once
  -v: Increase verbosity level (use -vv or more for greater effect)
  -d: Increase debugging level (use -dd or more for greater effect)
  --reason: Display the reason a port is in a particular state
  --open: Only show open (or possibly open) ports
  --packet-trace: Show all packets sent and received
  --iflist: Print host interfaces and routes (for debugging)
  --log-errors: Log errors/warnings to the normal-format output file
  --append-output: Append to rather than clobber specified output files
  --resume <filename>: Resume an aborted scan
  --stylesheet <path/URL>: XSL stylesheet to transform XML output to HTML
  --webxml: Reference stylesheet from Nmap.Org for more portable XML
  --no-stylesheet: Prevent associating of XSL stylesheet w/XML output
MISC:
  -6: Enable IPv6 scanning
  -A: Enable OS detection, version detection, script scanning, and traceroute
  --datadir <dirname>: Specify custom Nmap data file location
  --send-eth/--send-ip: Send using raw ethernet frames or IP packets
  --privileged: Assume that the user is fully privileged
  --unprivileged: Assume the user lacks raw socket privileges
  -V: Print version number
  -h: Print this help summary page.
EXAMPLES:
  nmap -v -A scanme.nmap.org
  nmap -v -sn 192.168.0.0/16 10.0.0.0/8
  nmap -v -iR 10000 -Pn -p 80
SEE THE MAN PAGE (http://nmap.org/book/man.html) FOR MORE OPTIONS AND EXAMPLES

Utilisation

Pour connaître la liste des ports ouverts sur votre machine virtuelle, saisissez la commande suivante :

[root@centos7 ~]# nmap 127.0.0.1

Starting Nmap 6.40 ( http://nmap.org ) at 2017-08-05 14:17 CEST
Nmap scan report for localhost.localdomain (127.0.0.1)
Host is up (-2100s latency).
Not shown: 996 closed ports
PORT    STATE SERVICE
22/tcp  open  ssh
25/tcp  open  smtp
111/tcp open  rpcbind
631/tcp open  ipp

Nmap done: 1 IP address (1 host up) scanned in 0.06 seconds

Important - Pour connaître les ports ouverts sur une machine distante, la procédure est identique sauf que vous devez utiliser l'adresse IP de votre cible.

Fichiers de Configuration

nmap utilise un fichier spécifique pour identifier les ports. Ce fichier est /usr/share/nmap/nmap-services:

[root@centos7 ~]# more /usr/share/nmap/nmap-services
# THIS FILE IS GENERATED AUTOMATICALLY FROM A MASTER - DO NOT EDIT.
# EDIT /nmap-private-dev/nmap-services-all IN SVN INSTEAD.
# Well known service port numbers -*- mode: fundamental; -*-
# From the Nmap Security Scanner ( http://nmap.org )
#
# $Id: nmap-services 31220 2013-07-03 04:30:43Z david $
#
# Derived from IANA data and our own research
# 
# This collection of service data is (C) 1996-2011 by Insecure.Com
# LLC.  It is distributed under the Nmap Open Source license as
# provided in the COPYING file of the source distribution or at
# http://nmap.org/data/COPYING .  Note that this license
# requires you to license your own work under a compatable open source
# license.  If you wish to embed Nmap technology into proprietary
# software, we sell alternative licenses (contact sales@insecure.com).
# Dozens of software vendors already license Nmap technology such as
# host discovery, port scanning, OS detection, and version detection.
# For more details, see http://nmap.org/book/man-legal.html
#
# Fields in this file are: Service name, portnum/protocol, open-frequency, optional comments
#
tcpmux	1/tcp	0.001995	# TCP Port Service Multiplexer [rfc-1078]
tcpmux	1/udp	0.001236	# TCP Port Service Multiplexer
compressnet	2/tcp	0.000013	# Management Utility
compressnet	2/udp	0.001845	# Management Utility
compressnet	3/tcp	0.001242	# Compression Process
compressnet	3/udp	0.001532	# Compression Process
unknown	4/tcp	0.000477
rje	5/udp	0.000593	# Remote Job Entry
unknown	6/tcp	0.000502
echo	7/sctp	0.000000
echo	7/tcp	0.004855
echo	7/udp	0.024679
unknown	8/tcp	0.000013
--More--(0%)

Le répertoire /usr/share/nmap contient d'autres fichiers importants :

[root@centos7 ~]# ls -l /usr/share/nmap
total 6548
-rw-r--r--. 1 root root   10546 Nov 20  2015 nmap.dtd
-rw-r--r--. 1 root root  455371 Nov 20  2015 nmap-mac-prefixes
-rw-r--r--. 1 root root 3694559 Nov 20  2015 nmap-os-db
-rw-r--r--. 1 root root   11749 Nov 20  2015 nmap-payloads
-rw-r--r--. 1 root root    6631 Nov 20  2015 nmap-protocols
-rw-r--r--. 1 root root   49243 Nov 20  2015 nmap-rpc
-rw-r--r--. 1 root root 1727204 Nov 20  2015 nmap-service-probes
-rw-r--r--. 1 root root  622039 Nov 20  2015 nmap-services
-rw-r--r--. 1 root root   31935 Nov 20  2015 nmap.xsl
drwxr-xr-x. 3 root root    4096 Aug  5 14:16 nselib
-rw-r--r--. 1 root root   47190 Nov 20  2015 nse_main.lua
drwxr-xr-x. 2 root root   20480 Aug  5 14:16 scripts

Voici la liste des fichiers les plus importants :

Fichier Description
/usr/share/nmap/nmap-protocols Contient la liste des protocols reconnus par nmap.
/usr/share/nmap/nmap-service-probes Contient les règles de balayage utilisées par nmap pour identifier le service actif sur un port donné.
/usr/share/nmap/nmap-mac-prefixes Contient une liste de préfix d'adresses MAC par fabricant reconnu par nmap.
/usr/share/nmap/nmap-rpc Contient une liste des services RPC reconnus par nmap.

Scripts

nmap utilise des scripts pour accomplir certaines tâches allant de la découverte simple de ports ouverts jusqu'à l'intrusion :

[root@centos7 ~]# ls /usr/share/nmap/scripts/
acarsd-info.nse                       http-domino-enum-passwords.nse          ndmp-version.nse
address-info.nse                      http-drupal-enum-users.nse              nessus-brute.nse
afp-brute.nse                         http-drupal-modules.nse                 nessus-xmlrpc-brute.nse
afp-ls.nse                            http-email-harvest.nse                  netbus-auth-bypass.nse
afp-path-vuln.nse                     http-enum.nse                           netbus-brute.nse
afp-serverinfo.nse                    http-exif-spider.nse                    netbus-info.nse
afp-showmount.nse                     http-favicon.nse                        netbus-version.nse
ajp-auth.nse                          http-fileupload-exploiter.nse           nexpose-brute.nse
ajp-brute.nse                         http-form-brute.nse                     nfs-ls.nse
ajp-headers.nse                       http-form-fuzzer.nse                    nfs-showmount.nse
ajp-methods.nse                       http-frontpage-login.nse                nfs-statfs.nse
ajp-request.nse                       http-generator.nse                      nping-brute.nse
amqp-info.nse                         http-git.nse                            nrpe-enum.nse
asn-query.nse                         http-gitweb-projects-enum.nse           ntp-info.nse
auth-owners.nse                       http-google-malware.nse                 ntp-monlist.nse
auth-spoof.nse                        http-grep.nse                           omp2-brute.nse
backorifice-brute.nse                 http-headers.nse                        omp2-enum-targets.nse
backorifice-info.nse                  http-huawei-hg5xx-vuln.nse              openlookup-info.nse
banner.nse                            http-icloud-findmyiphone.nse            openvas-otp-brute.nse
bitcoin-getaddr.nse                   http-icloud-sendmsg.nse                 oracle-brute.nse
bitcoin-info.nse                      http-iis-webdav-vuln.nse                oracle-brute-stealth.nse
bitcoinrpc-info.nse                   http-joomla-brute.nse                   oracle-enum-users.nse
bittorrent-discovery.nse              http-litespeed-sourcecode-download.nse  oracle-sid-brute.nse
bjnp-discover.nse                     http-majordomo2-dir-traversal.nse       ovs-agent-version.nse
broadcast-ataoe-discover.nse          http-malware-host.nse                   p2p-conficker.nse
broadcast-avahi-dos.nse               http-methods.nse                        path-mtu.nse
broadcast-bjnp-discover.nse           http-method-tamper.nse                  pcanywhere-brute.nse
broadcast-db2-discover.nse            http-open-proxy.nse                     pgsql-brute.nse
broadcast-dhcp6-discover.nse          http-open-redirect.nse                  pjl-ready-message.nse
broadcast-dhcp-discover.nse           http-passwd.nse                         pop3-brute.nse
broadcast-dns-service-discovery.nse   http-phpmyadmin-dir-traversal.nse       pop3-capabilities.nse
broadcast-dropbox-listener.nse        http-phpself-xss.nse                    pptp-version.nse
broadcast-eigrp-discovery.nse         http-php-version.nse                    qscan.nse
broadcast-igmp-discovery.nse          http-proxy-brute.nse                    quake3-info.nse
broadcast-listener.nse                http-put.nse                            quake3-master-getservers.nse
broadcast-ms-sql-discover.nse         http-qnap-nas-info.nse                  rdp-enum-encryption.nse
broadcast-netbios-master-browser.nse  http-rfi-spider.nse                     rdp-vuln-ms12-020.nse
broadcast-networker-discover.nse      http-robots.txt.nse                     realvnc-auth-bypass.nse
broadcast-novell-locate.nse           http-robtex-reverse-ip.nse              redis-brute.nse
broadcast-pc-anywhere.nse             http-robtex-shared-ns.nse               redis-info.nse
broadcast-pc-duo.nse                  http-sitemap-generator.nse              resolveall.nse
broadcast-pim-discovery.nse           http-slowloris-check.nse                reverse-index.nse
broadcast-ping.nse                    http-slowloris.nse                      rexec-brute.nse
broadcast-pppoe-discover.nse          http-sql-injection.nse                  riak-http-info.nse
broadcast-rip-discover.nse            http-stored-xss.nse                     rlogin-brute.nse
broadcast-ripng-discover.nse          http-title.nse                          rmi-dumpregistry.nse
broadcast-sybase-asa-discover.nse     http-tplink-dir-traversal.nse           rmi-vuln-classloader.nse
broadcast-tellstick-discover.nse      http-trace.nse                          rpcap-brute.nse
broadcast-upnp-info.nse               http-traceroute.nse                     rpcap-info.nse
broadcast-versant-locate.nse          http-unsafe-output-escaping.nse         rpc-grind.nse
broadcast-wake-on-lan.nse             http-userdir-enum.nse                   rpcinfo.nse
broadcast-wpad-discover.nse           http-vhosts.nse                         rsync-brute.nse
broadcast-wsdd-discover.nse           http-virustotal.nse                     rsync-list-modules.nse
broadcast-xdmcp-discover.nse          http-vlcstreamer-ls.nse                 rtsp-methods.nse
cassandra-brute.nse                   http-vmware-path-vuln.nse               rtsp-url-brute.nse
cassandra-info.nse                    http-vuln-cve2009-3960.nse              samba-vuln-cve-2012-1182.nse
cccam-version.nse                     http-vuln-cve2010-0738.nse              script.db
citrix-brute-xml.nse                  http-vuln-cve2010-2861.nse              servicetags.nse
citrix-enum-apps.nse                  http-vuln-cve2011-3192.nse              sip-brute.nse
citrix-enum-apps-xml.nse              http-vuln-cve2011-3368.nse              sip-call-spoof.nse
citrix-enum-servers.nse               http-vuln-cve2012-1823.nse              sip-enum-users.nse
citrix-enum-servers-xml.nse           http-vuln-cve2013-0156.nse              sip-methods.nse
couchdb-databases.nse                 http-waf-detect.nse                     skypev2-version.nse
couchdb-stats.nse                     http-waf-fingerprint.nse                smb-brute.nse
creds-summary.nse                     http-wordpress-brute.nse                smb-check-vulns.nse
cups-info.nse                         http-wordpress-enum.nse                 smb-enum-domains.nse
cups-queue-info.nse                   http-wordpress-plugins.nse              smb-enum-groups.nse
cvs-brute.nse                         iax2-brute.nse                          smb-enum-processes.nse
cvs-brute-repository.nse              iax2-version.nse                        smb-enum-sessions.nse
daap-get-library.nse                  icap-info.nse                           smb-enum-shares.nse
daytime.nse                           ike-version.nse                         smb-enum-users.nse
db2-das-info.nse                      imap-brute.nse                          smb-flood.nse
db2-discover.nse                      imap-capabilities.nse                   smb-ls.nse
dhcp-discover.nse                     informix-brute.nse                      smb-mbenum.nse
dict-info.nse                         informix-query.nse                      smb-os-discovery.nse
distcc-cve2004-2687.nse               informix-tables.nse                     smb-print-text.nse
dns-blacklist.nse                     ip-forwarding.nse                       smb-psexec.nse
dns-brute.nse                         ip-geolocation-geobytes.nse             smb-security-mode.nse
dns-cache-snoop.nse                   ip-geolocation-geoplugin.nse            smb-server-stats.nse
dns-check-zone.nse                    ip-geolocation-ipinfodb.nse             smb-system-info.nse
dns-client-subnet-scan.nse            ip-geolocation-maxmind.nse              smbv2-enabled.nse
dns-fuzz.nse                          ipidseq.nse                             smb-vuln-ms10-054.nse
dns-ip6-arpa-scan.nse                 ipv6-node-info.nse                      smb-vuln-ms10-061.nse
dns-nsec3-enum.nse                    ipv6-ra-flood.nse                       smtp-brute.nse
dns-nsec-enum.nse                     irc-botnet-channels.nse                 smtp-commands.nse
dns-nsid.nse                          irc-brute.nse                           smtp-enum-users.nse
dns-random-srcport.nse                irc-info.nse                            smtp-open-relay.nse
dns-random-txid.nse                   irc-sasl-brute.nse                      smtp-strangeport.nse
dns-recursion.nse                     irc-unrealircd-backdoor.nse             smtp-vuln-cve2010-4344.nse
dns-service-discovery.nse             iscsi-brute.nse                         smtp-vuln-cve2011-1720.nse
dns-srv-enum.nse                      iscsi-info.nse                          smtp-vuln-cve2011-1764.nse
dns-update.nse                        isns-info.nse                           sniffer-detect.nse
dns-zeustracker.nse                   jdwp-exec.nse                           snmp-brute.nse
dns-zone-transfer.nse                 jdwp-info.nse                           snmp-hh3c-logins.nse
domcon-brute.nse                      jdwp-inject.nse                         snmp-interfaces.nse
domcon-cmd.nse                        jdwp-version.nse                        snmp-ios-config.nse
domino-enum-users.nse                 krb5-enum-users.nse                     snmp-netstat.nse
dpap-brute.nse                        ldap-brute.nse                          snmp-processes.nse
drda-brute.nse                        ldap-novell-getpass.nse                 snmp-sysdescr.nse
drda-info.nse                         ldap-rootdse.nse                        snmp-win32-services.nse
duplicates.nse                        ldap-search.nse                         snmp-win32-shares.nse
eap-info.nse                          lexmark-config.nse                      snmp-win32-software.nse
epmd-info.nse                         llmnr-resolve.nse                       snmp-win32-users.nse
eppc-enum-processes.nse               lltd-discovery.nse                      socks-auth-info.nse
finger.nse                            maxdb-info.nse                          socks-brute.nse
firewalk.nse                          mcafee-epo-agent.nse                    socks-open-proxy.nse
firewall-bypass.nse                   membase-brute.nse                       ssh2-enum-algos.nse
flume-master-info.nse                 membase-http-info.nse                   ssh-hostkey.nse
ftp-anon.nse                          memcached-info.nse                      sshv1.nse
ftp-bounce.nse                        metasploit-info.nse                     ssl-cert.nse
ftp-brute.nse                         metasploit-msgrpc-brute.nse             ssl-date.nse
ftp-libopie.nse                       metasploit-xmlrpc-brute.nse             ssl-enum-ciphers.nse
ftp-proftpd-backdoor.nse              mmouse-brute.nse                        ssl-google-cert-catalog.nse
ftp-vsftpd-backdoor.nse               mmouse-exec.nse                         ssl-known-key.nse
ftp-vuln-cve2010-4221.nse             modbus-discover.nse                     sslv2.nse
ganglia-info.nse                      mongodb-brute.nse                       stun-info.nse
giop-info.nse                         mongodb-databases.nse                   stun-version.nse
gkrellm-info.nse                      mongodb-info.nse                        stuxnet-detect.nse
gopher-ls.nse                         mrinfo.nse                              svn-brute.nse
gpsd-info.nse                         msrpc-enum.nse                          targets-asn.nse
hadoop-datanode-info.nse              ms-sql-brute.nse                        targets-ipv6-multicast-echo.nse
hadoop-jobtracker-info.nse            ms-sql-config.nse                       targets-ipv6-multicast-invalid-dst.nse
hadoop-namenode-info.nse              ms-sql-dac.nse                          targets-ipv6-multicast-mld.nse
hadoop-secondary-namenode-info.nse    ms-sql-dump-hashes.nse                  targets-ipv6-multicast-slaac.nse
hadoop-tasktracker-info.nse           ms-sql-empty-password.nse               targets-sniffer.nse
hbase-master-info.nse                 ms-sql-hasdbaccess.nse                  targets-traceroute.nse
hbase-region-info.nse                 ms-sql-info.nse                         teamspeak2-version.nse
hddtemp-info.nse                      ms-sql-query.nse                        telnet-brute.nse
hostmap-bfk.nse                       ms-sql-tables.nse                       telnet-encryption.nse
hostmap-ip2hosts.nse                  ms-sql-xp-cmdshell.nse                  tftp-enum.nse
hostmap-robtex.nse                    mtrace.nse                              tls-nextprotoneg.nse
http-adobe-coldfusion-apsa1301.nse    murmur-version.nse                      traceroute-geolocation.nse
http-affiliate-id.nse                 mysql-audit.nse                         unusual-port.nse
http-apache-negotiation.nse           mysql-brute.nse                         upnp-info.nse
http-auth-finder.nse                  mysql-databases.nse                     url-snarf.nse
http-auth.nse                         mysql-dump-hashes.nse                   ventrilo-info.nse
http-awstatstotals-exec.nse           mysql-empty-password.nse                versant-info.nse
http-axis2-dir-traversal.nse          mysql-enum.nse                          vmauthd-brute.nse
http-backup-finder.nse                mysql-info.nse                          vnc-brute.nse
http-barracuda-dir-traversal.nse      mysql-query.nse                         vnc-info.nse
http-brute.nse                        mysql-users.nse                         voldemort-info.nse
http-cakephp-version.nse              mysql-variables.nse                     vuze-dht-info.nse
http-chrono.nse                       mysql-vuln-cve2012-2122.nse             wdb-version.nse
http-coldfusion-subzero.nse           nat-pmp-info.nse                        whois.nse
http-comments-displayer.nse           nat-pmp-mapport.nse                     wsdd-discover.nse
http-config-backup.nse                nbstat.nse                              x11-access.nse
http-cors.nse                         ncp-enum-users.nse                      xdmcp-discover.nse
http-date.nse                         ncp-serverinfo.nse                      xmpp-brute.nse
http-default-accounts.nse             ndmp-fs-info.nse                        xmpp-info.nse

Les scripts sont regroupés dans des catégories : auth, broadcast, brute, default, discovery, dos, exploit, external, fuzzer, intrusive, malware, safe, version and vuln.

Important - Pour plus d'informations concernant ces catégories, consultez cette page.

La catégorie la plus utilisée est default qui est appelée par l'utilisation de l'option -sC. Cette catégorie contient une liste de scripts par défaut.

[root@centos7 ~]# nmap -v -sC localhost

Starting Nmap 6.40 ( http://nmap.org ) at 2017-08-05 14:20 CEST
NSE: Loaded 95 scripts for scanning.
NSE: Script Pre-scanning.
Initiating SYN Stealth Scan at 14:20
Scanning localhost (127.0.0.1) [1000 ports]
Discovered open port 22/tcp on 127.0.0.1
adjust_timeouts2: packet supposedly had rtt of -1500757317045342 microseconds.  Ignoring time.
adjust_timeouts2: packet supposedly had rtt of -1500757317045342 microseconds.  Ignoring time.
Discovered open port 25/tcp on 127.0.0.1
adjust_timeouts2: packet supposedly had rtt of -1500757317045486 microseconds.  Ignoring time.
adjust_timeouts2: packet supposedly had rtt of -1500757317045486 microseconds.  Ignoring time.
Discovered open port 111/tcp on 127.0.0.1
adjust_timeouts2: packet supposedly had rtt of -1500757317045504 microseconds.  Ignoring time.
adjust_timeouts2: packet supposedly had rtt of -1500757317045504 microseconds.  Ignoring time.
Discovered open port 631/tcp on 127.0.0.1
adjust_timeouts2: packet supposedly had rtt of -1500757274107480 microseconds.  Ignoring time.
adjust_timeouts2: packet supposedly had rtt of -1500757274107480 microseconds.  Ignoring time.
Completed SYN Stealth Scan at 14:20, 0.01s elapsed (1000 total ports)
NSE: Script scanning 127.0.0.1.
Initiating NSE at 14:20
Completed NSE at 14:20, 0.28s elapsed
Nmap scan report for localhost (127.0.0.1)
Host is up (0.0000060s latency).
rDNS record for 127.0.0.1: localhost.localdomain
Not shown: 996 closed ports
PORT    STATE SERVICE
22/tcp  open  ssh
| ssh-hostkey: 2048 17:21:e0:43:b1:66:22:22:b6:f8:2b:cc:08:68:38:59 (RSA)
|_256 19:cd:05:58:af:2c:10:82:52:ba:e3:31:df:bd:72:54 (ECDSA)
25/tcp  open  smtp
|_smtp-commands: centos7.fenestros.loc, PIPELINING, SIZE 10240000, VRFY, ETRN, ENHANCEDSTATUSCODES, 8BITMIME, DSN, 
111/tcp open  rpcbind
| rpcinfo: 
|   program version   port/proto  service
|   100000  2,3,4        111/tcp  rpcbind
|_  100000  2,3,4        111/udp  rpcbind
631/tcp open  ipp
| http-methods: GET HEAD OPTIONS POST PUT
| Potentially risky methods: PUT
|_See http://nmap.org/nsedoc/scripts/http-methods.html
| http-robots.txt: 1 disallowed entry 
|_/
|_http-title: Home - CUPS 1.6.3

NSE: Script Post-scanning.
Initiating NSE at 14:20
Completed NSE at 14:20, 0.00s elapsed
Read data files from: /usr/bin/../share/nmap
Nmap done: 1 IP address (1 host up) scanned in 0.43 seconds
           Raw packets sent: 1000 (44.000KB) | Rcvd: 2004 (84.176KB)

Attention - La catégorie par défaut default contient certains scripts de la catégorie intrusive. Vous ne devez donc jamais utiliser cette option sur un réseau sans avoir obtenu un accord au préalable.

4.2 - netcat

netcat est un couteau suisse. Il permet non seulement de scanner des ports mais aussi de lancer la connexion lors de la découverte d'un port ouvert.

Les options de cette commande sont :

[root@centos7 ~]# nc --help
Ncat 6.40 ( http://nmap.org/ncat )
Usage: ncat [options] [hostname] [port]

Options taking a time assume seconds. Append 'ms' for milliseconds,
's' for seconds, 'm' for minutes, or 'h' for hours (e.g. 500ms).
  -4                         Use IPv4 only
  -6                         Use IPv6 only
  -U, --unixsock             Use Unix domain sockets only
  -C, --crlf                 Use CRLF for EOL sequence
  -c, --sh-exec <command>    Executes the given command via /bin/sh
  -e, --exec <command>       Executes the given command
      --lua-exec <filename>  Executes the given Lua script
  -g hop1[,hop2,...]         Loose source routing hop points (8 max)
  -G <n>                     Loose source routing hop pointer (4, 8, 12, ...)
  -m, --max-conns <n>        Maximum <n> simultaneous connections
  -h, --help                 Display this help screen
  -d, --delay <time>         Wait between read/writes
  -o, --output <filename>    Dump session data to a file
  -x, --hex-dump <filename>  Dump session data as hex to a file
  -i, --idle-timeout <time>  Idle read/write timeout
  -p, --source-port port     Specify source port to use
  -s, --source addr          Specify source address to use (doesn't affect -l)
  -l, --listen               Bind and listen for incoming connections
  -k, --keep-open            Accept multiple connections in listen mode
  -n, --nodns                Do not resolve hostnames via DNS
  -t, --telnet               Answer Telnet negotiations
  -u, --udp                  Use UDP instead of default TCP
      --sctp                 Use SCTP instead of default TCP
  -v, --verbose              Set verbosity level (can be used several times)
  -w, --wait <time>          Connect timeout
      --append-output        Append rather than clobber specified output files
      --send-only            Only send data, ignoring received; quit on EOF
      --recv-only            Only receive data, never send anything
      --allow                Allow only given hosts to connect to Ncat
      --allowfile            A file of hosts allowed to connect to Ncat
      --deny                 Deny given hosts from connecting to Ncat
      --denyfile             A file of hosts denied from connecting to Ncat
      --broker               Enable Ncat's connection brokering mode
      --chat                 Start a simple Ncat chat server
      --proxy <addr[:port]>  Specify address of host to proxy through
      --proxy-type <type>    Specify proxy type ("http" or "socks4")
      --proxy-auth <auth>    Authenticate with HTTP or SOCKS proxy server
      --ssl                  Connect or listen with SSL
      --ssl-cert             Specify SSL certificate file (PEM) for listening
      --ssl-key              Specify SSL private key (PEM) for listening
      --ssl-verify           Verify trust and domain name of certificates
      --ssl-trustfile        PEM file containing trusted SSL certificates
      --version              Display Ncat's version information and exit

See the ncat(1) manpage for full options, descriptions and usage examples

Utilisation

Dans l'exemple qui suite, un scan est lancé sur le port 80 puis sur le port 25 :

[root@centos7 ~]# nc 127.0.0.1 80 -w 1 -vv
Ncat: Version 6.40 ( http://nmap.org/ncat )
libnsock nsi_new2(): nsi_new (IOD #1)
libnsock nsock_connect_tcp(): TCP connection requested to 127.0.0.1:80 (IOD #1) EID 8
libnsock nsock_trace_handler_callback(): Callback: CONNECT ERROR [Connection refused (111)] for EID 8 [127.0.0.1:80]
Ncat: Connection refused.

[root@centos7 ~]# nc 127.0.0.1 25 -w 1 -vv
Ncat: Version 6.40 ( http://nmap.org/ncat )
libnsock nsi_new2(): nsi_new (IOD #1)
libnsock nsock_connect_tcp(): TCP connection requested to 127.0.0.1:25 (IOD #1) EID 8
libnsock nsock_trace_handler_callback(): Callback: CONNECT SUCCESS for EID 8 [127.0.0.1:25]
Ncat: Connected to 127.0.0.1:25.
libnsock nsi_new2(): nsi_new (IOD #2)
libnsock nsock_read(): Read request from IOD #1 [127.0.0.1:25] (timeout: -1ms) EID 18
libnsock nsock_readbytes(): Read request for 0 bytes from IOD #2 [peer unspecified] EID 26
libnsock nsock_trace_handler_callback(): Callback: READ SUCCESS for EID 18 [127.0.0.1:25] (41 bytes): 220 centos7.fenestros.loc ESMTP Postfix..
220 centos7.fenestros.loc ESMTP Postfix
libnsock nsock_readbytes(): Read request for 0 bytes from IOD #1 [127.0.0.1:25] EID 34
^C

Important - Notez que netcat se connecte au port 25 qui est ouvert.

LAB #5 - Utilisation de tcpdump

Le logiciel tcpdump sert à écouter le réseau en interceptant les paquets.

Les options de cette commande sont :

[root@centos7 ~]# tcpdump --help
tcpdump version 4.9.2
libpcap version 1.5.3
OpenSSL 1.0.2k-fips  26 Jan 2017
Usage: tcpdump [-aAbdDefhHIJKlLnNOpqStuUvxX#] [ -B size ] [ -c count ]
		[ -C file_size ] [ -E algo:secret ] [ -F file ] [ -G seconds ]
		[ -i interface ] [ -j tstamptype ] [ -M secret ] [ --number ]
		[ -Q|-P in|out|inout ]
		[ -r file ] [ -s snaplen ] [ --time-stamp-precision precision ]
		[ --immediate-mode ] [ -T type ] [ --version ] [ -V file ]
		[ -w file ] [ -W filecount ] [ -y datalinktype ] [ -z postrotate-command ]
		[ -Z user ] [ expression ]

5.1 - Utilisation

L'option -i

Pour écouter sur une interface spécifique, utilisez l'option -i :

[root@centos7 ~]# tcpdump -i enp0s3
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on enp0s3, link-type EN10MB (Ethernet), capture size 262144 bytes
01:32:57.800710 IP centos7.fenestros.loc.ssh > gateway.36360: Flags [P.], seq 2207704927:2207705115, ack 23445380, win 40096, length 188
01:32:57.801785 IP gateway.36360 > centos7.fenestros.loc.ssh: Flags [.], ack 188, win 65535, length 0
01:32:57.805318 IP centos7.fenestros.loc.45319 > google-public-dns-a.google.com.domain: 62187+ PTR? 2.2.0.10.in-addr.arpa. (39)
01:32:57.862866 IP google-public-dns-a.google.com.domain > centos7.fenestros.loc.45319: 62187 NXDomain 0/0/0 (39)
01:32:57.873506 IP centos7.fenestros.loc.54658 > google-public-dns-a.google.com.domain: 6854+ PTR? 15.2.0.10.in-addr.arpa. (40)
01:32:57.934593 IP google-public-dns-a.google.com.domain > centos7.fenestros.loc.54658: 6854 NXDomain 0/0/0 (40)
01:32:57.947943 IP centos7.fenestros.loc.53477 > google-public-dns-a.google.com.domain: 63054+ PTR? 8.8.8.8.in-addr.arpa. (38)
01:32:57.948649 IP centos7.fenestros.loc.ssh > gateway.36360: Flags [P.], seq 188:464, ack 1, win 40096, length 276
01:32:57.958724 IP gateway.36360 > centos7.fenestros.loc.ssh: Flags [.], ack 464, win 65535, length 0
01:32:58.025768 IP google-public-dns-a.google.com.domain > centos7.fenestros.loc.53477: 63054 1/0/0 PTR google-public-dns-a.google.com. (82)
01:32:58.026959 IP centos7.fenestros.loc.ssh > gateway.36360: Flags [P.], seq 464:1476, ack 1, win 40096, length 1012
01:32:58.027640 IP centos7.fenestros.loc.ssh > gateway.36360: Flags [P.], seq 1476:1632, ack 1, win 40096, length 156
01:32:58.028108 IP gateway.36360 > centos7.fenestros.loc.ssh: Flags [.], ack 1476, win 65535, length 0
01:32:58.028146 IP gateway.36360 > centos7.fenestros.loc.ssh: Flags [.], ack 1632, win 65535, length 0
01:32:58.028313 IP centos7.fenestros.loc.ssh > gateway.36360: Flags [P.], seq 1632:1788, ack 1, win 40096, length 156
01:32:58.028822 IP centos7.fenestros.loc.ssh > gateway.36360: Flags [P.], seq 1788:2152, ack 1, win 40096, length 364
01:32:58.029240 IP gateway.36360 > centos7.fenestros.loc.ssh: Flags [.], ack 1788, win 65535, length 0
01:32:58.029273 IP gateway.36360 > centos7.fenestros.loc.ssh: Flags [.], ack 2152, win 65535, length 0
01:32:58.029710 IP centos7.fenestros.loc.ssh > gateway.36360: Flags [P.], seq 2152:2516, ack 1, win 40096, length 364
01:32:58.030217 IP gateway.36360 > centos7.fenestros.loc.ssh: Flags [.], ack 2516, win 65535, length 0
01:32:58.030773 IP centos7.fenestros.loc.ssh > gateway.36360: Flags [P.], seq 2516:2776, ack 1, win 40096, length 260
01:32:58.034485 IP gateway.36360 > centos7.fenestros.loc.ssh: Flags [.], ack 2776, win 65535, length 0
...

Notez qu'à la fin, un résumé vous est présenté, par exemple :

...
^C
767 packets captured
767 packets received by filter
0 packets dropped by kernel

L'option -x

Pour écouter sur une interface spécifique et voir le contenu en Hexadécimal, utilisez les options -i et -x :

[root@centos7 ~]# tcpdump -i enp0s3 -x
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on enp0s3, link-type EN10MB (Ethernet), capture size 262144 bytes
01:34:55.540011 IP centos7.fenestros.loc.ssh > gateway.36360: Flags [P.], seq 2208166651:2208166839, ack 23445916, win 40096, length 188
	0x0000:  4510 00e4 851c 4000 4006 9cd7 0a00 020f
	0x0010:  0a00 0202 0016 8e08 839d f2fb 0165 c19c
	0x0020:  5018 9ca0 18e7 0000 96d1 7d89 0022 fb31
	0x0030:  dec8 d6f4 1227 ceb3 4df9 1ed8 691b b0e4
	0x0040:  4561 6454 7f80 8928 1704 99a9 d4fe e565
	0x0050:  7d2e e55f eadc 7e0e 352c 2f65 dd2a ff02
	0x0060:  3a66 d1fa 3a15 9a4e 0054 91fe 7fe5 ce35
	0x0070:  7df4 371a 6363 1302 4037 2a7f dde1 3d76
	0x0080:  6ce5 069a 5855 cff6 18f5 dcf3 afff e525
	0x0090:  ec03 c13d c23c 9d4b e0b9 0661 4f59 cd11
	0x00a0:  cffb 1447 d6e6 7ab7 d7a8 d357 8fa6 ac7a
	0x00b0:  bcf5 257f 41dd 5064 ba0b 189b 1563 06fa
	0x00c0:  5364 9d6a 4f7c e99c 7a27 c3fc 3a2e 2618
	0x00d0:  1357 7e4c b62a 9e44 8350 71fa e9b8 a17f
	0x00e0:  a2be c731
01:34:55.540618 IP gateway.36360 > centos7.fenestros.loc.ssh: Flags [.], ack 188, win 65535, length 0
	0x0000:  4500 0028 061f 0000 4006 5ca1 0a00 0202
	0x0010:  0a00 020f 8e08 0016 0165 c19c 839d f3b7
	0x0020:  5010 ffff cf4e 0000 0000 0000 0000
^C01:34:55.543115 IP centos7.fenestros.loc.47568 > google-public-dns-a.google.com.domain: 37698+ PTR? 2.2.0.10.in-addr.arpa. (39)
	0x0000:  4500 0043 8ca3 4000 4011 91e8 0a00 020f
	0x0010:  0808 0808 b9d0 0035 002f 1c5f 9342 0100
	0x0020:  0001 0000 0000 0000 0132 0132 0130 0231
	0x0030:  3007 696e 2d61 6464 7204 6172 7061 0000
	0x0040:  0c00 01

3 packets captured
21 packets received by filter
0 packets dropped by kernel

L'option -X

Pour écouter sur une interface spécifique et voir le contenu en Hexadécimal et en ASCII, utilisez les options -i et -X :

[root@centos7 ~]# tcpdump -i enp0s3 -X
tcpdump: verbose output suppressed, use -v or -vv for full protocol decode
listening on enp0s3, link-type EN10MB (Ethernet), capture size 262144 bytes
01:35:56.671522 IP centos7.fenestros.loc.ssh > gateway.36360: Flags [P.], seq 2208168643:2208168831, ack 23446048, win 40096, length 188
	0x0000:  4510 00e4 8522 4000 4006 9cd1 0a00 020f  E...."@.@.......
	0x0010:  0a00 0202 0016 8e08 839d fac3 0165 c220  .............e..
	0x0020:  5018 9ca0 18e7 0000 d8cc 9fe4 3055 351c  P...........0U5.
	0x0030:  96a0 b2c0 650e 44e7 0016 b72e c990 4929  ....e.D.......I)
	0x0040:  0d05 e79b ef5b ccef aafc 607b b9a2 a714  .....[....`{....
	0x0050:  e1a0 36a1 b5f3 4a0a 5cdd 90bd 96cf b75d  ..6...J.\......]
	0x0060:  efa5 cc0b d195 d69a e933 48f2 74a5 ca6b  .........3H.t..k
	0x0070:  c803 fe4e 5832 2253 d6d9 178b c63a df8e  ...NX2"S.....:..
	0x0080:  62a3 6e67 91f8 cc50 f330 51da a285 1c3a  b.ng...P.0Q....:
	0x0090:  b074 a98f 95d6 f528 03e2 308a 31e8 5aa2  .t.....(..0.1.Z.
	0x00a0:  988b e3b1 444e ab24 e1b0 3eb8 ffa7 ae3f  ....DN.$..>....?
	0x00b0:  332f 221d 3bec d17a 1c8f 741a eaaf 5444  3/".;..z..t...TD
	0x00c0:  ea38 320e ea7f e9d2 035a 2531 e8f1 0757  .82......Z%1...W
	0x00d0:  0259 70b1 464b 51ea 9e6b 1b93 48ea 6f25  .Yp.FKQ..k..H.o%
	0x00e0:  d918 9027                                ...'
01:35:56.672680 IP gateway.36360 > centos7.fenestros.loc.ssh: Flags [.], ack 188, win 65535, length 0
	0x0000:  4500 0028 06cc 0000 4006 5bf4 0a00 0202  E..(....@.[.....
	0x0010:  0a00 020f 8e08 0016 0165 c220 839d fb7f  .........e......
	0x0020:  5010 ffff c702 0000 0000 0000 0000       P.............
^C01:35:56.674310 IP centos7.fenestros.loc.57986 > google-public-dns-a.google.com.domain: 33529+ PTR? 2.2.0.10.in-addr.arpa. (39)
	0x0000:  4500 0043 188e 4000 4011 05fe 0a00 020f  E..C..@.@.......
	0x0010:  0808 0808 e282 0035 002f 1c5f 82f9 0100  .......5./._....
	0x0020:  0001 0000 0000 0000 0132 0132 0130 0231  .........2.2.0.1
	0x0030:  3007 696e 2d61 6464 7204 6172 7061 0000  0.in-addr.arpa..
	0x0040:  0c00 01                                  ...

3 packets captured
13 packets received by filter
0 packets dropped by kernel

L'option -w

Pour écouter sur une interface spécifique et envoyer la sortie dans un fichier, utilisez les options -i et -w :

[root@centos7 ~]# tcpdump -i enp0s3 -w log.dump
tcpdump: listening on enp0s3, link-type EN10MB (Ethernet), capture size 262144 bytes
^C45 packets captured
45 packets received by filter
0 packets dropped by kernel

[root@centos7 ~]# ls -l log.dump
-rw-r--r--. 1 tcpdump tcpdump 8685 Jun  9 01:37 log.dump

Important - Pour générer le trafic, réactualisez simplement cette page web. Arrêtez la sortie de la commande à l'aide des touches ^C.

Notez que le fichier log.dump est au format libpcap et non au format texte. Il est donc inutile d'essayer de lire son contenu :

[root@centos7 ~]# file log.dump
log.dump: tcpdump capture file (little-endian) - version 2.4 (Ethernet, capture length 262144)

L'option -v

Tcpdump peut être utilisé avec un de trois modes verbose.

Mode Option
Light verbose -v
Medium verbose -vv
Full verbose -vvv
[root@centos7 ~]# tcpdump -i enp0s3 -v
tcpdump: listening on enp0s3, link-type EN10MB (Ethernet), capture size 262144 bytes
01:39:13.094781 IP (tos 0x10, ttl 64, id 39762, offset 0, flags [DF], proto TCP (6), length 164)
^C    centos7.fenestros.loc.ssh > gateway.36360: Flags [P.], cksum 0x18a7 (incorrect -> 0xd270), seq 2210981047:2210981171, ack 23448932, win 40096, length 124

1 packet captured
11 packets received by filter
0 packets dropped by kernel

5.2 - Filtrage à l'écoute

Tcpdump peut effectuer du filtrage lors de l'écoute.

Pour uniquement écouter les paquets en provenance de l'adresse IP 192.168.1.11, utilisez la condition src host :

# tcpdump src host 192.168.1.11 [Entrée]

Pour uniquement écouter les paquets en provenance de l'adresse IP 192.168.1.11 et vers l'adresse 192.168.1.2, utilisez les conditions src host et dst host :

# tcpdump src host 192.168.1.11 and dst host 192.168.1.2 [Entrée]

Pour uniquement écouter les paquets d'un port précis, utilisez la condition port :

# tcpdump -i eth0 port 80 [Entrée]

Pour uniquement écouter les paquets d'un protocole précis, utilisez une condition telle ip, icmp, arp, rarp, udp ou tcp:

# tcpdump -i eth0 udp [Entrée]

Pour uniquement écouter les paquets d'une taille inférieure à 100 octets, utilisez la condition less :

# tcpdump -i eth0 less 100 [Entrée]

Pour uniquement écouter les paquets d'une taille supérieure à 100 octets, utilisez la condition great :

# tcpdump -i eth0 greater 100 [Entrée]

L'utilisation des ses options et conditions peut être combinée pour donner des commandes telles :

# tcpdump -i eth0 -X src host 192.168.1.11 and dst host 192.168.1.2 and port 21 and ftp [Entrée]

Copyright © 2022 Hugh Norris.

Menu