Table des matières
Version : 2026.01
Dernière mise-à-jour : 2025/12/04 09:27
LDF409 - Gestion de la Sécurité de Docker
Contenu du Module
- LDF409 - Gestion de la Sécurité de Docker
- Contenu du Module
- Présentation de Docker
- LAB #1 - Travailler avec Docker
- 1.1 - Installer docker
- 1.2 - Démarrer un Conteneur
- 1.3 - Consulter la Liste des Conteneurs et Images
- 1.4 - Rechercher une Image dans un Dépôt
- 1.5 - Supprimer un Conteneur d'une Image
- 1.6 - Créer une Image à partir d'un Conteneur Modifié
- 1.7 - Supprimer une Image
- 1.8 - Créer un Conteneur avec un Nom Spécifique
- 1.9 - Exécuter une Commande dans un Conteneur
- 1.10 - Injecter des Variables d'Environnement dans un Conteneur
- 1.11 - Modifier le Nom d'Hôte d'un Conteneur
- 1.12 - Mapper des Ports d'un Conteneur
- 1.13 - Démarrer un Conteneur en mode Détaché
- 1.14 - Accéder aux Services d'un Conteneur de l'Extérieur
- 1.15 - Arrêter et Démarrer un Conteneur
- 1.16 - Utiliser des Signaux avec un Conteneur
- 1.17 - Forcer la Suppression d'un Conteneur en cours d'Exécution
- 1.18 - Utilisation Simple d'un Volume
- 1.19 - Télécharger une image sans créer un conteneur
- 1.20 - S'attacher à un conteneur en cours d'exécution
- 1.21 - Installer un logiciel dans le conteneur
- 1.22 - Utilisation de la commande docker commit
- 1.23 - Se connecter au serveur du conteneur de l'extérieur
- LAB #2 - Création d'un Utilisateur de Confiance pour Contrôler le Daemon Docker
- LAB #3 - Le Script docker-bench-security.sh
- LAB #4 - Sécurisation de la Configuration de l'Hôte Docker
- 4.1 - [WARN] 1.2.1 - Ensure a separate partition for containers has been created
- 4.2 - [WARN] 1.2.3 - Ensure auditing is configured for the Docker daemon
- LAB #5 - Sécurisation de la Configuration du daemon Docker
- 5.1 - [WARN] 2.1 - Ensure network traffic is restricted between containers on the default bridge
- 5.2 - [WARN] 2.8 - Enable user namespace support
- 5.3 - [WARN] 2.11 - Ensure that authorization for Docker client commands is enabled
- 5.4 - [WARN] 2.12 - Ensure centralized and remote logging is configured
- 5.5 - [WARN] 2.14 - Ensure Userland Proxy is Disabled
- 5.6 - [WARN] 2.17 - Ensure containers are restricted from acquiring new privileges
- 5.7 - Le Fichier /etc/docker/daemon.json
- LAB #6 - Sécurisation des Images et les Fichiers de Construction
- 6.1 - [WARN] 4.1 - Ensure a user for the container has been created
- 6.2 - [WARN] 4.5 - Ensure Content trust for Docker is Enabled
- 6.3 - [WARN] 4.6 - Ensure that HEALTHCHECK instructions have been added to container images
- LAB #7 - Sécurisation du Container Runtime
- 7.1 - [WARN] 5.1 - Ensure AppArmor Profile is Enabled
- 7.2 - [WARN] 5.2 - Ensure SELinux security options are set, if applicable
- 7.3 - [WARN] 5.10 - Ensure memory usage for container is limited
- 7.4 - [WARN] 5.11 - Ensure CPU priority is set appropriately on the container
- 7.5 - [WARN] 5.12 - Ensure the container's root filesystem is mounted as read only
- 7.6 - [WARN] 5.14 - Ensure 'on-failure' container restart policy is set to '5'
- 7.7 - [WARN] 5.25 - Ensure the container is restricted from acquiring additional privileges
- 7.8 - [WARN] 5.26 - Ensure container health is checked at runtime
- 7.9 - [WARN] 5.28 - Ensure PIDs cgroup limit is used
- LAB #8 - Sécurisation des Images avec Docker Content Trust
- 8.1 - DOCKER_CONTENT_TRUST
- 8.2 - DCT et la commande docker pull
- L'option disable-content-trust
- 8.3 - DCT et la commande docker push
- 8.4 - DCT et la commande docker build
- Créer un deuxième Repositry
- Supprimer une Signature
Présentation de Docker
Docker est une application de virtualisation légère qui utilise des images et des conteneurs.
Une image est un paquet exécutable contenant tout ce qu'il est necessaire afin d'exécuter un logiciel donné, incluant :
- le code
- un runtime
- des bibliothèques,
- des variables d'environnement
- des fichiers de configuration
Un conteneur est une instance de l'image en cours d'exécution en mémoire. Elle est isolée de l'environnement de l'hôte par défaut mais peut accéder à des fichiers et de ports de l'hôte selon la configuration.
Les conteneurs exécutent des applications nativement en utilisant le noyau de la machine hôte. De ce fait les performances d'un conteneur sont supérieures à celles d'une machine virtuelle qui doit passer par un hyperviseur pour accéder aux ressources de la machine hôte.
Docker existe en deux versions Docker-CE (Docker Community Edition) et Docker-EE (Docker Enterprise Edition). Pour consulter les différences entre les deux versions, consultez le lien https://docs.docker.com/engine/installation/.
LAB #1 - Travailler avec Docker
1.1 - Installer docker
Installer Docker-CE sur votre ordinateur :
Mac
- Voir le lien https://docs.docker.com/docker-for-mac/install/ ou le lien kitematic.
Linux
- Ubuntu - voir le lien https://docs.docker.com/engine/installation/linux/docker-ce/ubuntu/,
- Debian - voir le lien https://docs.docker.com/engine/installation/linux/docker-ce/debian/,
- CentOS - voir le lien https://docs.docker.com/engine/installation/linux/docker-ce/centos/,
- Fedora - voir le lien https://docs.docker.com/engine/installation/linux/docker-ce/fedora/,
Windows 7, 8
- Téléchargez Docker Toolbox à partir de cette page https://docs.docker.com/toolbox/toolbox_install_windows/
- Fermez toutes les machines virtuelles ainsi que VirtualBox,
- Installez DockerToolBox.exe (décochez VirtualBox dans la liste de produits à installer),
- Exécutez Docker Toolbox et laissez l'application créer une machine virtuelle,
- Ouvrez VirtualBox. Vous verrez une machine virtuelle Default,
- Ouvrez cmd.
Windows 10
- Voir le lien https://docs.docker.com/docker-for-windows/install/.
1.2 - Démarrer un Conteneur
Démarrez un conteneur de l'image hello-world :
root@debian9:~# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
1b930d010525: Pull complete
Digest: sha256:2557e3c07ed1e38f26e389462d03ed943586f744621577a99efb77324b0fe535
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image which runs the
executable that produces the output you are currently reading.
4. The Docker daemon streamed that output to the Docker client, which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://hub.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/get-started/
Important - Notez que si l'image servant à générer le conteneur n'est pas présente sur le système hôte, celle-ci est téléchargée automatiquement depuis un dépôt ( par défaut le dépôt docker.io ) en utilisant la commande docker pull.
Démarrez un conteneur de l'image ubuntu:latest en mode interactif grâce à l'utilisation des options -i et -t en lui passant en argument bash pour que celui-ci soient lancé au démarrage du conteneur :
root@debian9:~# docker run -it ubuntu bash Unable to find image 'ubuntu:latest' locally latest: Pulling from library/ubuntu 898c46f3b1a1: Pull complete 63366dfa0a50: Pull complete 041d4cd74a92: Pull complete 6e1bee0f8701: Pull complete Digest: sha256:017eef0b616011647b269b5c65826e2e2ebddbe5d1f8c1e56b3599fb14fabec8 Status: Downloaded newer image for ubuntu:latest root@3a3f9bda6cbd:/# ls bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var root@3a3f9bda6cbd:/# cat /etc/lsb-release DISTRIB_ID=Ubuntu DISTRIB_RELEASE=18.04 DISTRIB_CODENAME=bionic DISTRIB_DESCRIPTION="Ubuntu 18.04.2 LTS"
Important - Notez que dans ce cas le conteneur est lancé avec comme argument bash qui lancera /bin/bash dans le conteneur.
Consulter la liste des paquets installés dans le conteneur ubuntu :
root@835001339e79:/# dpkg -l Desired=Unknown/Install/Remove/Purge/Hold | Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend |/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad) ||/ Name Version Architecture Description +++-====================================-=======================-=======================-============================================================================= ii adduser 3.116ubuntu1 all add and remove users and groups ii apt 1.6.8 amd64 commandline package manager ii base-files 10.1ubuntu2.4 amd64 Debian base system miscellaneous files ii base-passwd 3.5.44 amd64 Debian base system master password and group files ii bash 4.4.18-2ubuntu1 amd64 GNU Bourne Again SHell ii bsdutils 1:2.31.1-0.4ubuntu3.3 amd64 basic utilities from 4.4BSD-Lite ii bzip2 1.0.6-8.1 amd64 high-quality block-sorting file compressor - utilities ii coreutils 8.28-1ubuntu1 amd64 GNU core utilities ii dash 0.5.8-2.10 amd64 POSIX-compliant shell ii debconf 1.5.66 all Debian configuration management system ii debianutils 4.8.4 amd64 Miscellaneous utilities specific to Debian ii diffutils 1:3.6-1 amd64 File comparison utilities ii dpkg 1.19.0.5ubuntu2.1 amd64 Debian package management system ii e2fsprogs 1.44.1-1ubuntu1.1 amd64 ext2/ext3/ext4 file system utilities ii fdisk 2.31.1-0.4ubuntu3.3 amd64 collection of partitioning utilities ii findutils 4.6.0+git+20170828-2 amd64 utilities for finding files--find, xargs ii gcc-8-base:amd64 8.2.0-1ubuntu2~18.04 amd64 GCC, the GNU Compiler Collection (base package) ii gpgv 2.2.4-1ubuntu1.2 amd64 GNU privacy guard - signature verification tool ii grep 3.1-2 amd64 GNU grep, egrep and fgrep ii gzip 1.6-5ubuntu1 amd64 GNU compression utilities ii hostname 3.20 amd64 utility to set/show the host name or domain name ii init-system-helpers 1.51 all helper tools for all init systems ii libacl1:amd64 2.2.52-3build1 amd64 Access control list shared library ii libapt-pkg5.0:amd64 1.6.8 amd64 package management runtime library ii libattr1:amd64 1:2.4.47-2build1 amd64 Extended attribute shared library ii libaudit-common 1:2.8.2-1ubuntu1 all Dynamic library for security auditing - common files ii libaudit1:amd64 1:2.8.2-1ubuntu1 amd64 Dynamic library for security auditing ii libblkid1:amd64 2.31.1-0.4ubuntu3.3 amd64 block device ID library ii libbz2-1.0:amd64 1.0.6-8.1 amd64 high-quality block-sorting file compressor library - runtime ii libc-bin 2.27-3ubuntu1 amd64 GNU C Library: Binaries ii libc6:amd64 2.27-3ubuntu1 amd64 GNU C Library: Shared libraries ii libcap-ng0:amd64 0.7.7-3.1 amd64 An alternate POSIX capabilities library ii libcom-err2:amd64 1.44.1-1ubuntu1.1 amd64 common error description library ii libdb5.3:amd64 5.3.28-13.1ubuntu1 amd64 Berkeley v5.3 Database Libraries [runtime] ii libdebconfclient0:amd64 0.213ubuntu1 amd64 Debian Configuration Management System (C-implementation library) ii libext2fs2:amd64 1.44.1-1ubuntu1.1 amd64 ext2/ext3/ext4 file system libraries ii libfdisk1:amd64 2.31.1-0.4ubuntu3.3 amd64 fdisk partitioning library ii libffi6:amd64 3.2.1-8 amd64 Foreign Function Interface library runtime ii libgcc1:amd64 1:8.2.0-1ubuntu2~18.04 amd64 GCC support library ii libgcrypt20:amd64 1.8.1-4ubuntu1.1 amd64 LGPL Crypto library - runtime library ii libgmp10:amd64 2:6.1.2+dfsg-2 amd64 Multiprecision arithmetic library ii libgnutls30:amd64 3.5.18-1ubuntu1 amd64 GNU TLS library - main runtime library ii libgpg-error0:amd64 1.27-6 amd64 library for common error values and messages in GnuPG components ii libhogweed4:amd64 3.4-1 amd64 low level cryptographic library (public-key cryptos) ii libidn2-0:amd64 2.0.4-1.1build2 amd64 Internationalized domain names (IDNA2008/TR46) library ii liblz4-1:amd64 0.0~r131-2ubuntu3 amd64 Fast LZ compression algorithm library - runtime ii liblzma5:amd64 5.2.2-1.3 amd64 XZ-format compression library ii libmount1:amd64 2.31.1-0.4ubuntu3.3 amd64 device mounting library ii libncurses5:amd64 6.1-1ubuntu1.18.04 amd64 shared libraries for terminal handling ii libncursesw5:amd64 6.1-1ubuntu1.18.04 amd64 shared libraries for terminal handling (wide character support) ii libnettle6:amd64 3.4-1 amd64 low level cryptographic library (symmetric and one-way cryptos) ii libp11-kit0:amd64 0.23.9-2 amd64 library for loading and coordinating access to PKCS#11 modules - runtime ii libpam-modules:amd64 1.1.8-3.6ubuntu2.18.04. amd64 Pluggable Authentication Modules for PAM ii libpam-modules-bin 1.1.8-3.6ubuntu2.18.04. amd64 Pluggable Authentication Modules for PAM - helper binaries ii libpam-runtime 1.1.8-3.6ubuntu2.18.04. all Runtime support for the PAM library ii libpam0g:amd64 1.1.8-3.6ubuntu2.18.04. amd64 Pluggable Authentication Modules library ii libpcre3:amd64 2:8.39-9 amd64 Old Perl 5 Compatible Regular Expression Library - runtime files ii libprocps6:amd64 2:3.3.12-3ubuntu1.1 amd64 library for accessing process information from /proc ii libseccomp2:amd64 2.3.1-2.1ubuntu4 amd64 high level interface to Linux seccomp filter ii libselinux1:amd64 2.7-2build2 amd64 SELinux runtime shared libraries ii libsemanage-common 2.7-2build2 all Common files for SELinux policy management libraries ii libsemanage1:amd64 2.7-2build2 amd64 SELinux policy management library ii libsepol1:amd64 2.7-1 amd64 SELinux library for manipulating binary security policies ii libsmartcols1:amd64 2.31.1-0.4ubuntu3.3 amd64 smart column output alignment library ii libss2:amd64 1.44.1-1ubuntu1.1 amd64 command-line interface parsing library ii libstdc++6:amd64 8.2.0-1ubuntu2~18.04 amd64 GNU Standard C++ Library v3 ii libsystemd0:amd64 237-3ubuntu10.13 amd64 systemd utility library ii libtasn1-6:amd64 4.13-2 amd64 Manage ASN.1 structures (runtime) ii libtinfo5:amd64 6.1-1ubuntu1.18.04 amd64 shared low-level terminfo library for terminal handling ii libudev1:amd64 237-3ubuntu10.13 amd64 libudev shared library ii libunistring2:amd64 0.9.9-0ubuntu1 amd64 Unicode string library for C ii libuuid1:amd64 2.31.1-0.4ubuntu3.3 amd64 Universally Unique ID library ii libzstd1:amd64 1.3.3+dfsg-2ubuntu1 amd64 fast lossless compression algorithm ii login 1:4.5-1ubuntu1 amd64 system login tools ii lsb-base 9.20170808ubuntu1 all Linux Standard Base init script functionality ii mawk 1.3.3-17ubuntu3 amd64 a pattern scanning and text processing language ii mount 2.31.1-0.4ubuntu3.3 amd64 tools for mounting and manipulating filesystems ii ncurses-base 6.1-1ubuntu1.18.04 all basic terminal type definitions ii ncurses-bin 6.1-1ubuntu1.18.04 amd64 terminal-related programs and man pages ii passwd 1:4.5-1ubuntu1 amd64 change and administer password and group data ii perl-base 5.26.1-6ubuntu0.3 amd64 minimal Perl system ii procps 2:3.3.12-3ubuntu1.1 amd64 /proc file system utilities ii sed 4.4-2 amd64 GNU stream editor for filtering/transforming text ii sensible-utils 0.0.12 all Utilities for sensible alternative selection ii sysvinit-utils 2.88dsf-59.10ubuntu1 amd64 System-V-like utilities ii tar 1.29b-2ubuntu0.1 amd64 GNU version of the tar archiving utility ii ubuntu-keyring 2018.09.18.1~18.04.0 all GnuPG keys of the Ubuntu archive ii util-linux 2.31.1-0.4ubuntu3.3 amd64 miscellaneous system utilities ii zlib1g:amd64 1:1.2.11.dfsg-0ubuntu2 amd64 compression library - runtime root@835001339e79:/# exit exit root@debian9:~#
Les options de la commande docker run peuvent être visualisées avec la commande :
root@debian9:~# docker run --help
Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
Run a command in a new container
Options:
--add-host list Add a custom host-to-IP mapping (host:ip)
-a, --attach list Attach to STDIN, STDOUT or STDERR
--blkio-weight uint16 Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
--blkio-weight-device list Block IO weight (relative device weight) (default [])
--cap-add list Add Linux capabilities
--cap-drop list Drop Linux capabilities
--cgroup-parent string Optional parent cgroup for the container
--cidfile string Write the container ID to the file
--cpu-period int Limit CPU CFS (Completely Fair Scheduler) period
--cpu-quota int Limit CPU CFS (Completely Fair Scheduler) quota
--cpu-rt-period int Limit CPU real-time period in microseconds
--cpu-rt-runtime int Limit CPU real-time runtime in microseconds
-c, --cpu-shares int CPU shares (relative weight)
--cpus decimal Number of CPUs
--cpuset-cpus string CPUs in which to allow execution (0-3, 0,1)
--cpuset-mems string MEMs in which to allow execution (0-3, 0,1)
-d, --detach Run container in background and print container ID
--detach-keys string Override the key sequence for detaching a container
--device list Add a host device to the container
--device-cgroup-rule list Add a rule to the cgroup allowed devices list
--device-read-bps list Limit read rate (bytes per second) from a device (default [])
--device-read-iops list Limit read rate (IO per second) from a device (default [])
--device-write-bps list Limit write rate (bytes per second) to a device (default [])
--device-write-iops list Limit write rate (IO per second) to a device (default [])
--disable-content-trust Skip image verification (default true)
--dns list Set custom DNS servers
--dns-option list Set DNS options
--dns-search list Set custom DNS search domains
--entrypoint string Overwrite the default ENTRYPOINT of the image
-e, --env list Set environment variables
--env-file list Read in a file of environment variables
--expose list Expose a port or a range of ports
--group-add list Add additional groups to join
--health-cmd string Command to run to check health
--health-interval duration Time between running the check (ms|s|m|h) (default 0s)
--health-retries int Consecutive failures needed to report unhealthy
--health-start-period duration Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
--health-timeout duration Maximum time to allow one check to run (ms|s|m|h) (default 0s)
--help Print usage
-h, --hostname string Container host name
--init Run an init inside the container that forwards signals and reaps processes
-i, --interactive Keep STDIN open even if not attached
--ip string IPv4 address (e.g., 172.30.100.104)
--ip6 string IPv6 address (e.g., 2001:db8::33)
--ipc string IPC mode to use
--isolation string Container isolation technology
--kernel-memory bytes Kernel memory limit
-l, --label list Set meta data on a container
--label-file list Read in a line delimited file of labels
--link list Add link to another container
--link-local-ip list Container IPv4/IPv6 link-local addresses
--log-driver string Logging driver for the container
--log-opt list Log driver options
--mac-address string Container MAC address (e.g., 92:d0:c6:0a:29:33)
-m, --memory bytes Memory limit
--memory-reservation bytes Memory soft limit
--memory-swap bytes Swap limit equal to memory plus swap: '-1' to enable unlimited swap
--memory-swappiness int Tune container memory swappiness (0 to 100) (default -1)
--mount mount Attach a filesystem mount to the container
--name string Assign a name to the container
--network string Connect a container to a network (default "default")
--network-alias list Add network-scoped alias for the container
--no-healthcheck Disable any container-specified HEALTHCHECK
--oom-kill-disable Disable OOM Killer
--oom-score-adj int Tune host's OOM preferences (-1000 to 1000)
--pid string PID namespace to use
--pids-limit int Tune container pids limit (set -1 for unlimited)
--privileged Give extended privileges to this container
-p, --publish list Publish a container's port(s) to the host
-P, --publish-all Publish all exposed ports to random ports
--read-only Mount the container's root filesystem as read only
--restart string Restart policy to apply when a container exits (default "no")
--rm Automatically remove the container when it exits
--runtime string Runtime to use for this container
--security-opt list Security Options
--shm-size bytes Size of /dev/shm
--sig-proxy Proxy received signals to the process (default true)
--stop-signal string Signal to stop a container (default "SIGTERM")
--stop-timeout int Timeout (in seconds) to stop a container
--storage-opt list Storage driver options for the container
--sysctl map Sysctl options (default map[])
--tmpfs list Mount a tmpfs directory
-t, --tty Allocate a pseudo-TTY
--ulimit ulimit Ulimit options (default [])
-u, --user string Username or UID (format: <name|uid>[:<group|gid>])
--userns string User namespace to use
--uts string UTS namespace to use
-v, --volume list Bind mount a volume
--volume-driver string Optional volume driver for the container
--volumes-from list Mount volumes from the specified container(s)
-w, --workdir string Working directory inside the container
1.3 - Consulter la Liste des Conteneurs et Images
Pour consulter tous les conteneurs, utilisez la commande docker ps avec l'option -a :
root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 3a3f9bda6cbd ubuntu "bash" About a minute ago Exited (127) 3 seconds ago wizardly_buck 26ef17bd115d hello-world "/hello" 8 minutes ago Exited (0) 8 minutes ago angry_chaplygin
Important - Notez que chaque conteneur peut être référencé par son CONTAINER ID ou par son NAME.
Pour consulter la liste des images, utilisez la commande docker images :
root@debian9:~# docker images REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu latest 94e814e2efa8 4 weeks ago 88.9MB hello-world latest fce289e99eb9 3 months ago 4.84kB
Important - Notez que chaque image est référencée par son IMAGE ID.
1.4 - Rechercher une Image dans un Dépôt
Pour rechercher une image docker dans le dépôt par défaut, utilisez la commande docker search :
root@debian9:~# docker search --filter=stars=5 centos NAME DESCRIPTION STARS OFFICIAL AUTOMATED centos The official build of CentOS. 5288 [OK] ansible/centos7-ansible Ansible on Centos7 121 [OK] jdeathe/centos-ssh CentOS-6 6.10 x86_64 / CentOS-7 7.5.1804 x86… 107 [OK] consol/centos-xfce-vnc Centos container with "headless" VNC session… 84 [OK] imagine10255/centos6-lnmp-php56 centos6-lnmp-php56 53 [OK] centos/mysql-57-centos7 MySQL 5.7 SQL database server 50 tutum/centos Simple CentOS docker image with SSH access 44 gluster/gluster-centos Official GlusterFS Image [ CentOS-7 + Glust… 40 [OK] openshift/base-centos7 A Centos7 derived base image for Source-To-I… 40 centos/postgresql-96-centos7 PostgreSQL is an advanced Object-Relational … 37 centos/python-35-centos7 Platform for building and running Python 3.5… 34 kinogmt/centos-ssh CentOS with SSH 26 [OK] centos/httpd-24-centos7 Platform for running Apache httpd 2.4 or bui… 22 centos/php-56-centos7 Platform for building and running PHP 5.6 ap… 20 openshift/jenkins-2-centos7 A Centos7 based Jenkins v2.x image for use w… 20 pivotaldata/centos-gpdb-dev CentOS image for GPDB development. Tag names… 10 openshift/wildfly-101-centos7 A Centos7 based WildFly v10.1 image for use … 6
Important - Notez que chaque image est référencée par la colonne NAME. Le NAME est sous le format repository/mainteneur/nom sauf dans le cas où il s'agit de l'image “officielle” de l'éditeur au quel cas le format est simplement repository/nom. La notion de STARS ( étoiles ) vient de Docker Hub et est une indication de la satisfaction de la communauté.
1.5 - Supprimer un Conteneur d'une Image
Pour supprimer un conteneur d'une image, il convient d'utiliser la commande docker rm en référencant le conteneur soit par son NAME soit par son CONTAINER ID :
root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 3a3f9bda6cbd ubuntu "bash" 7 minutes ago Exited (127) 5 minutes ago wizardly_buck 26ef17bd115d hello-world "/hello" 13 minutes ago Exited (0) 13 minutes ago angry_chaplygin root@debian9:~# docker rm wizardly_buck wizardly_buck root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 26ef17bd115d hello-world "/hello" 14 minutes ago Exited (0) 14 minutes ago angry_chaplygin root@debian9:~# docker images REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu latest 94e814e2efa8 4 weeks ago 88.9MB hello-world latest fce289e99eb9 3 months ago 4.84kB
Important - Notez que dans le cas de l'utilisation du CONTAINER ID, il n'est pas necéssaire d'utiliser la totalité de l'ID. Par exemple, dans le cas ci-dessus, le CONTAINER ID du conteneur wizardly_buck était 3a3f9bda6cbd. La commande de suppression aurait pu utilisé 3a3f9bda6cbd, 3a3f9b ou même 3a3.
1.6 -Créer une Image à partir d'un Conteneur Modifié
Modifier un conteneur d'une image :
root@debian9:~# docker run -it ubuntu root@54b0dae2f3a9:/# ls bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var root@54b0dae2f3a9:/# rm -rf /home root@54b0dae2f3a9:/# ls bin boot dev etc lib lib64 media mnt opt proc root run sbin srv sys tmp usr var root@54b0dae2f3a9:/# exit exit root@debian9:~#
Important - Notez ici la suppression du répertoire home dans le conteneur 54b0dae2f3a9.
Consultez la différence entre le conteneur et l'image de base :
root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 54b0dae2f3a9 ubuntu "/bin/bash" About a minute ago Exited (0) About a minute ago tender_mendeleev 26ef17bd115d hello-world "/hello" 18 minutes ago Exited (0) 18 minutes ago angry_chaplygin root@debian9:~# docker diff tender_mendeleev C /root A /root/.bash_history D /home
Important - La sortie de la commande docker diff comporte des lettres dont les significations sont les suivantes : C = Create, D = Delete, A = Add.
Créez un autre conteneur à partir de l'image de base :
root@debian9:~# docker run -it ubuntu root@92f0d4bb7967:/# ls bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var root@92f0d4bb7967:/# exit exit root@debian9:~#
Important - Dans ce nouveau conteneur, le répertoire /home est présent compte tenu du fait qu'il a été généré à partir de l'image d'origine, inchangée depuis sa compilation.
Créez maintenant l'image ubuntu_1 à partir du conteneur competent_pasteur en utilisant la commande docker commit :
root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 92f0d4bb7967 ubuntu "/bin/bash" 39 seconds ago Exited (0) 32 seconds ago musing_benz 54b0dae2f3a9 ubuntu "/bin/bash" 3 minutes ago Exited (0) 3 minutes ago tender_mendeleev 26ef17bd115d hello-world "/hello" 19 minutes ago Exited (0) 19 minutes ago angry_chaplygin root@debian9:~# docker commit tender_mendeleev ubuntu_1 sha256:2ba8e0ec5e38332c8ab15c4b33fd140a9c74d72231d05a6965c40a39fbb44584 root@debian9:~# docker images REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu_1 latest 2ba8e0ec5e38 15 seconds ago 88.9MB ubuntu latest 94e814e2efa8 4 weeks ago 88.9MB hello-world latest fce289e99eb9 3 months ago 4.84kB
1.7 - Supprimer une Image
Créez maintenant un conteneur à partir de la nouvelle image ubuntu_1 :
root@debian9:~# docker run -it ubuntu_1 root@904215fb79b4:/# ls bin boot dev etc lib lib64 media mnt opt proc root run sbin srv sys tmp usr var root@904215fb79b4:/# exit exit root@debian9:~#
Important - Notez l'absence du répertoire home dans le conteneur 904215fb79b4.
Essayez de supprimer l'image ubuntu_1 :
root@debian9:~# docker rmi ubuntu_1 Error response from daemon: conflict: unable to remove repository reference "ubuntu_1" (must force) - container 904215fb79b4 is using its referenced image 2ba8e0ec5e38 root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 904215fb79b4 ubuntu_1 "/bin/bash" About a minute ago Exited (0) 49 seconds ago priceless_swirles 92f0d4bb7967 ubuntu "/bin/bash" 2 minutes ago Exited (0) 2 minutes ago musing_benz 54b0dae2f3a9 ubuntu "/bin/bash" 6 minutes ago Exited (0) 5 minutes ago tender_mendeleev 26ef17bd115d hello-world "/hello" 22 minutes ago Exited (0) 22 minutes ago angry_chaplygin
Important - Notez qu'il n'est pas possible de supprimer l'image ubuntu_1 tant que le conteneur priceless_swirles soit actif.
Supprimez donc le conteneur priceless_swirles ainsi que l'image ubuntu_1 :
root@debian9:~# docker rm priceless_swirles priceless_swirles root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 92f0d4bb7967 ubuntu "/bin/bash" 4 minutes ago Exited (0) 3 minutes ago musing_benz 54b0dae2f3a9 ubuntu "/bin/bash" 7 minutes ago Exited (0) 6 minutes ago tender_mendeleev 26ef17bd115d hello-world "/hello" 23 minutes ago Exited (0) 23 minutes ago angry_chaplygin root@debian9:~# docker rmi ubuntu_1 Untagged: ubuntu_1:latest Deleted: sha256:2ba8e0ec5e38332c8ab15c4b33fd140a9c74d72231d05a6965c40a39fbb44584 Deleted: sha256:308e9761a8fc84661e46eff564b0bbca12b458e71bdf77bf4abbb59b21efdbbe root@debian9:~# docker images REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu latest 94e814e2efa8 4 weeks ago 88.9MB hello-world latest fce289e99eb9 3 months ago 1.84kB
Pour pouvoir supprimer tous les conteneurs, listez-les par leur Container ID :
root@debian9:~# docker ps -aq 92f0d4bb7967 54b0dae2f3a9 26ef17bd115d
Supprimer toutes les conteneurs :
root@debian9:~# docker rm `docker ps -aq` 92f0d4bb7967 54b0dae2f3a9 26ef17bd115d root@debian9:~# docker ps -aq root@debian9:~#
Pour supprimer un conteneur dès la fin de son exécution, utilisez l'option –rm :
root@debian9:~# docker run -it --rm ubuntu root@d123b0112fc2:/# ls bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var root@d123b0112fc2:/# exit exit root@debian9:~# docker ps -aq root@debian9:~#
1.8 - Créer un Conteneur avec un Nom Spécifique
Créez maintenant un conteneur avec un nom spécifique :
root@debian9:~# docker run -it --name=i2tch ubuntu root@04b5ab87539a:/# ls bin boot dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var root@04b5ab87539a:/# exit exit root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 04b5ab87539a ubuntu "/bin/bash" 11 seconds ago Exited (0) 4 seconds ago i2tch
Pour obtenir de l'information concernant un conteneur, utilisez la commande docker inspect :
root@debian9:~# docker inspect i2tch
[
{
"Id": "04b5ab87539aed114cbfc3ba15d10be61cd88b9cffc88c6de9bd26e203b363b5",
"Created": "2019-04-09T14:22:45.623162229Z",
"Path": "/bin/bash",
"Args": [],
"State": {
"Status": "exited",
"Running": false,
"Paused": false,
"Restarting": false,
"OOMKilled": false,
"Dead": false,
"Pid": 0,
"ExitCode": 0,
"Error": "",
"StartedAt": "2019-04-09T14:22:46.301514689Z",
"FinishedAt": "2019-04-09T14:22:51.91071787Z"
},
"Image": "sha256:94e814e2efa8845d95b2112d54497fbad173e45121ce9255b93401392f538499",
"ResolvConfPath": "/var/lib/docker/containers/04b5ab87539aed114cbfc3ba15d10be61cd88b9cffc88c6de9bd26e203b363b5/resolv.conf",
"HostnamePath": "/var/lib/docker/containers/04b5ab87539aed114cbfc3ba15d10be61cd88b9cffc88c6de9bd26e203b363b5/hostname",
"HostsPath": "/var/lib/docker/containers/04b5ab87539aed114cbfc3ba15d10be61cd88b9cffc88c6de9bd26e203b363b5/hosts",
"LogPath": "/var/lib/docker/containers/04b5ab87539aed114cbfc3ba15d10be61cd88b9cffc88c6de9bd26e203b363b5/04b5ab87539aed114cbfc3ba15d10be61cd88b9cffc88c6de9bd26e203b363b5-json.log",
"Name": "/i2tch",
"RestartCount": 0,
"Driver": "overlay2",
"Platform": "linux",
"MountLabel": "",
"ProcessLabel": "",
"AppArmorProfile": "",
"ExecIDs": null,
"HostConfig": {
"Binds": null,
"ContainerIDFile": "",
"LogConfig": {
"Type": "json-file",
"Config": {}
},
"NetworkMode": "default",
"PortBindings": {},
"RestartPolicy": {
"Name": "no",
"MaximumRetryCount": 0
},
"AutoRemove": false,
"VolumeDriver": "",
"VolumesFrom": null,
"CapAdd": null,
"CapDrop": null,
"Dns": [],
"DnsOptions": [],
"DnsSearch": [],
"ExtraHosts": null,
"GroupAdd": null,
"IpcMode": "shareable",
"Cgroup": "",
"Links": null,
"OomScoreAdj": 0,
"PidMode": "",
"Privileged": false,
"PublishAllPorts": false,
"ReadonlyRootfs": false,
"SecurityOpt": null,
"UTSMode": "",
"UsernsMode": "",
"ShmSize": 67108864,
"Runtime": "runc",
"ConsoleSize": [
0,
0
],
"Isolation": "",
"CpuShares": 0,
"Memory": 0,
"NanoCpus": 0,
"CgroupParent": "",
"BlkioWeight": 0,
"BlkioWeightDevice": [],
"BlkioDeviceReadBps": null,
"BlkioDeviceWriteBps": null,
"BlkioDeviceReadIOps": null,
"BlkioDeviceWriteIOps": null,
"CpuPeriod": 0,
"CpuQuota": 0,
"CpuRealtimePeriod": 0,
"CpuRealtimeRuntime": 0,
"CpusetCpus": "",
"CpusetMems": "",
"Devices": [],
"DeviceCgroupRules": null,
"DiskQuota": 0,
"KernelMemory": 0,
"MemoryReservation": 0,
"MemorySwap": 0,
"MemorySwappiness": null,
"OomKillDisable": false,
"PidsLimit": 0,
"Ulimits": null,
"CpuCount": 0,
"CpuPercent": 0,
"IOMaximumIOps": 0,
"IOMaximumBandwidth": 0,
"MaskedPaths": [
"/proc/asound",
"/proc/acpi",
"/proc/kcore",
"/proc/keys",
"/proc/latency_stats",
"/proc/timer_list",
"/proc/timer_stats",
"/proc/sched_debug",
"/proc/scsi",
"/sys/firmware"
],
"ReadonlyPaths": [
"/proc/bus",
"/proc/fs",
"/proc/irq",
"/proc/sys",
"/proc/sysrq-trigger"
]
},
"GraphDriver": {
"Data": {
"LowerDir": "/var/lib/docker/overlay2/1151d32cdd4dda25ee299fe2c2a8df9dcb1b7fc4c47701c2925c437fb7c3a616-init/diff:/var/lib/docker/overlay2/84bcc6977e49ee3d477255450d69b98195b721b017124194b376f6e6c0645233/diff:/var/lib/docker/overlay2/eee0d6bc849e0c074de73e17eaf11b296dd860a0fb17097f37f9af86d28dcf9b/diff:/var/lib/docker/overlay2/0deb30449649adfed4d1abb678939b2409c4804976ceea4cb75508d0fdf415b6/diff:/var/lib/docker/overlay2/a156bf77423d93e38ef326b3ca6a1d0248ce801733800dad2767070380d682b6/diff",
"MergedDir": "/var/lib/docker/overlay2/1151d32cdd4dda25ee299fe2c2a8df9dcb1b7fc4c47701c2925c437fb7c3a616/merged",
"UpperDir": "/var/lib/docker/overlay2/1151d32cdd4dda25ee299fe2c2a8df9dcb1b7fc4c47701c2925c437fb7c3a616/diff",
"WorkDir": "/var/lib/docker/overlay2/1151d32cdd4dda25ee299fe2c2a8df9dcb1b7fc4c47701c2925c437fb7c3a616/work"
},
"Name": "overlay2"
},
"Mounts": [],
"Config": {
"Hostname": "04b5ab87539a",
"Domainname": "",
"User": "",
"AttachStdin": true,
"AttachStdout": true,
"AttachStderr": true,
"Tty": true,
"OpenStdin": true,
"StdinOnce": true,
"Env": [
"PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
],
"Cmd": [
"/bin/bash"
],
"ArgsEscaped": true,
"Image": "ubuntu",
"Volumes": null,
"WorkingDir": "",
"Entrypoint": null,
"OnBuild": null,
"Labels": {}
},
"NetworkSettings": {
"Bridge": "",
"SandboxID": "304fc54e6d23247d4faf08995b65646967670def542812d902d2ee33d178794d",
"HairpinMode": false,
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"Ports": {},
"SandboxKey": "/var/run/docker/netns/304fc54e6d23",
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"EndpointID": "",
"Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"MacAddress": "",
"Networks": {
"bridge": {
"IPAMConfig": null,
"Links": null,
"Aliases": null,
"NetworkID": "f2d947904cba4a871af3e50d6e1ec0a3a055849185bf7ba473b2e028880bd8a9",
"EndpointID": "",
"Gateway": "",
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"MacAddress": "",
"DriverOpts": null
}
}
}
}
]
1.9 - Exécuter une Commande dans un Conteneur
Pour exécuter une commande spécifique dans un conteneur, passez la commande en argument :
root@debian9:~# docker run --rm ubuntu env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin HOSTNAME=77bb110031aa HOME=/root root@debian9:~#
1.10 - Injecter des Variables d'Environnement dans un Conteneur
Pour injecter une ou des variables d'environnement dans un conteneur, utilisez un fichier pré-établi :
root@debian9:~# vi env.list root@debian9:~# cat env.list EDITOR=vim HOSTNAME=ubuntudocker
root@debian9:~# docker run --rm --env-file=env.list ubuntu env PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin HOSTNAME=ubuntudocker EDITOR=vim HOME=/root root@debian9:~#
1.11 - Modifier le Nom d'Hôte d'un Conteneur
Pour modifier le nom d'hôte d'un conteneur, utilisez l'option -h :
root@debian9:~# docker run -it --rm -h ubuntudocker ubuntu root@ubuntudocker:/# hostname ubuntudocker root@ubuntudocker:/# exit exit root@debian9:~#
1.12 - Mapper des Ports d'un Conteneur
Démarrer un conteneur de nginx sur le port localhost 81 :
root@debian9:~# docker run -it -p 81:80 nginx Unable to find image 'nginx:latest' locally latest: Pulling from library/nginx 27833a3ba0a5: Pull complete e83729dd399a: Pull complete ebc6a67df66d: Pull complete Digest: sha256:c8a861b8a1eeef6d48955a6c6d5dff8e2580f13ff4d0f549e082e7c82a8617a2 Status: Downloaded newer image for nginx:latest ^Croot@debian9:~#
Notez que c'est bloquant. Le fait d'avoir utiliser ^C a interrompu le processus du conteneur :
^Croot@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 4f157e179134 nginx "nginx -g 'daemon of…" 32 seconds ago Exited (0) 21 seconds ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 5 minutes ago Exited (0) 5 minutes ago i2tch
1.13 - Démarrer un Conteneur en mode Détaché
Démarrez maintenant le conteneur de nginx en mode détaché grâce à l'utilisation de l'option -d :
root@debian9:~# docker run -d -p 81:80 nginx aabb064d4b0ade1f19216b6174631fa32a2053f6aa9d59bd724ea90ce534b004 root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES aabb064d4b0a nginx "nginx -g 'daemon of…" 12 seconds ago Up 11 seconds 0.0.0.0:81->80/tcp eager_lewin 4f157e179134 nginx "nginx -g 'daemon of…" About a minute ago Exited (0) About a minute ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 6 minutes ago Exited (0) 6 minutes ago i2tch
1.14 - Accèder aux Services d'un Conteneur de l'Extérieur
Installez le navigateur texte lynx :
root@debian9:~# apt-get install lynx Lecture des listes de paquets... Fait Construction de l'arbre des dépendances Lecture des informations d'état... Fait The following additional packages will be installed: lynx-common Les NOUVEAUX paquets suivants seront installés : lynx lynx-common 0 mis à jour, 2 nouvellement installés, 0 à enlever et 94 non mis à jour. Il est nécessaire de prendre 1 730 ko dans les archives. Après cette opération, 5 590 ko d'espace disque supplémentaires seront utilisés. Souhaitez-vous continuer ? [O/n] o Réception de:1 http://ftp.fr.debian.org/debian stretch/main amd64 lynx-common all 2.8.9dev11-1 [1 098 kB] Réception de:2 http://ftp.fr.debian.org/debian stretch/main amd64 lynx amd64 2.8.9dev11-1 [632 kB] 1 730 ko réceptionnés en 6s (283 ko/s) Sélection du paquet lynx-common précédemment désélectionné. (Lecture de la base de données... 113082 fichiers et répertoires déjà installés.) Préparation du dépaquetage de .../lynx-common_2.8.9dev11-1_all.deb ... Dépaquetage de lynx-common (2.8.9dev11-1) ... Sélection du paquet lynx précédemment désélectionné. Préparation du dépaquetage de .../lynx_2.8.9dev11-1_amd64.deb ... Dépaquetage de lynx (2.8.9dev11-1) ... Traitement des actions différées (« triggers ») pour mime-support (3.60) ... Traitement des actions différées (« triggers ») pour man-db (2.7.6.1-2) ... Paramétrage de lynx-common (2.8.9dev11-1) ... Paramétrage de lynx (2.8.9dev11-1) ... update-alternatives: utilisation de « /usr/bin/lynx » pour fournir « /usr/bin/www-browser » (www-browser) en mode automatique
Vérifiez que nginx répond aux requetes :
root@debian9:~# lynx --dump http://localhost:81
Welcome to nginx!
If you see this page, the nginx web server is successfully installed
and working. Further configuration is required.
For online documentation and support please refer to [1]nginx.org.
Commercial support is available at [2]nginx.com.
Thank you for using nginx.
Références
1. http://nginx.org/
2. http://nginx.com/
1.15 - Arrêter et Démarrer un Conteneur
Arrêtez le conteneur nginx :
root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES aabb064d4b0a nginx "nginx -g 'daemon of…" 2 minutes ago Up 2 minutes 0.0.0.0:81->80/tcp eager_lewin 4f157e179134 nginx "nginx -g 'daemon of…" 4 minutes ago Exited (0) 3 minutes ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 8 minutes ago Exited (0) 8 minutes ago i2tch root@debian9:~# docker stop aabb aabb root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES aabb064d4b0a nginx "nginx -g 'daemon of…" 2 minutes ago Exited (0) 2 seconds ago eager_lewin 4f157e179134 nginx "nginx -g 'daemon of…" 4 minutes ago Exited (0) 4 minutes ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 8 minutes ago Exited (0) 8 minutes ago i2tch
Démarrez de nouveau le conteneur de nginx :
root@debian9:~# docker start aabb aabb root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES aabb064d4b0a nginx "nginx -g 'daemon of…" 3 minutes ago Up 3 seconds 0.0.0.0:81->80/tcp eager_lewin 4f157e179134 nginx "nginx -g 'daemon of…" 4 minutes ago Exited (0) 4 minutes ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 9 minutes ago Exited (0) 8 minutes ago i2tch
1.16 - Utiliser des Signaux avec un Conteneur
Utilisez un signal pour tuer le processus du conteneur de nginx :
root@debian9:~# docker kill -s 9 aabb aabb root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES aabb064d4b0a nginx "nginx -g 'daemon of…" 2 hours ago Exited (137) 2 seconds ago eager_lewin 4f157e179134 nginx "nginx -g 'daemon of…" 2 hours ago Exited (0) 2 hours ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 2 hours ago Exited (0) 2 hours ago i2tch
Redémarrez un conteneur en cours :
root@debian9:~# docker start aabb aabb root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES aabb064d4b0a nginx "nginx -g 'daemon of…" 2 hours ago Up 1 second 0.0.0.0:81->80/tcp eager_lewin 4f157e179134 nginx "nginx -g 'daemon of…" 2 hours ago Exited (0) 2 hours ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 2 hours ago Exited (0) 2 hours ago i2tch root@debian9:~# docker restart aabb aabb root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES aabb064d4b0a nginx "nginx -g 'daemon of…" 2 hours ago Up 2 seconds 0.0.0.0:81->80/tcp eager_lewin 4f157e179134 nginx "nginx -g 'daemon of…" 2 hours ago Exited (0) 2 hours ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 2 hours ago Exited (0) 2 hours ago i2tch
1.17 - Forcer la Suppression d'un Conteneur en cours d'Exécution
Supprimez un conteneur en cours d'exécution :
root@debian9:~# docker rm aabb Error response from daemon: You cannot remove a running container aabb064d4b0ade1f19216b6174631fa32a2053f6aa9d59bd724ea90ce534b004. Stop the container before attempting removal or force remove root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES aabb064d4b0a nginx "nginx -g 'daemon of…" 2 hours ago Up About a minute 0.0.0.0:81->80/tcp eager_lewin 4f157e179134 nginx "nginx -g 'daemon of…" 2 hours ago Exited (0) 2 hours ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 2 hours ago Exited (0) 2 hours ago i2tch root@debian9:~# docker rm -f aabb aabb root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 4f157e179134 nginx "nginx -g 'daemon of…" 2 hours ago Exited (0) 2 hours ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 2 hours ago Exited (0) 2 hours ago i2tch
1.18 - Utilisation Simple d'un Volume
Créez le fichier index.html et placez-le dans le répertoire /root/www :
root@debian9:~# mkdir /root/www root@debian9:~# vi index.html root@debian9:~# cat index.html <html> <body> <center>Accueil du site nginx</center> </body> </html> root@debian9:~# mv index.html www/
Indiquez au conteneur que son répertoire /usr/share/nginx/html/ est remplacé par le répertoire /root/www/ de la machine hôte :
root@debian9:~# docker run -d -p 81:80 -v /root/www:/usr/share/nginx/html:ro nginx
c080793965de8a6a60db212d7e4d96de84b55352c224c054dced75b409e39bf2
root@debian9:~# lynx --dump http://localhost:81
Accueil du site nginx
root@debian9:~#
Important - Notez ici l'utilisation de ro - lecture seule.
1.19 - Télécharger une image sans créer un conteneur
Téléchargez l'image de centos sans créer un conteneur :
root@debian9:~# docker pull centos Using default tag: latest latest: Pulling from library/centos 8ba884070f61: Pull complete Digest: sha256:8d487d68857f5bc9595793279b33d082b03713341ddec91054382641d14db861 Status: Downloaded newer image for centos:latest
Vérifiez le contenu de l'image en créant un conteneur :
root@debian9:~# docker run -it centos bash [root@86252a3f00f4 /]# cat /etc/redhat-release CentOS Linux release 7.6.1810 (Core) [root@86252a3f00f4 /]# rpm -qa | more bind-license-9.9.4-73.el7_6.noarch bash-4.2.46-31.el7.x86_64 glibc-common-2.17-260.el7_6.3.x86_64 nss-softokn-freebl-3.36.0-5.el7_5.x86_64 filesystem-3.2-25.el7.x86_64 glibc-2.17-260.el7_6.3.x86_64 nspr-4.19.0-1.el7_5.x86_64 popt-1.13-16.el7.x86_64 libcom_err-1.42.9-13.el7.x86_64 libcap-2.22-9.el7.x86_64 libstdc++-4.8.5-36.el7.x86_64 info-5.1-5.el7.x86_64 gawk-4.0.2-4.el7_3.1.x86_64 libselinux-2.5-14.1.el7.x86_64 grep-2.20-3.el7.x86_64 keyutils-libs-1.5.8-3.el7.x86_64 libverto-0.2.5-4.el7.x86_64 p11-kit-trust-0.23.5-3.el7.x86_64 openssl-libs-1.0.2k-16.el7.x86_64 krb5-libs-1.15.1-37.el7_6.x86_64 xz-libs-5.2.2-1.el7.x86_64 libdb-5.3.21-24.el7.x86_64 libgpg-error-1.12-3.el7.x86_64 libgcrypt-1.5.3-14.el7.x86_64 lua-5.1.4-15.el7.x86_64 libuuid-2.23.2-59.el7.x86_64 libmount-2.23.2-59.el7.x86_64 shared-mime-info-1.8-4.el7.x86_64 gzip-1.5-10.el7.x86_64 findutils-4.5.11-6.el7.x86_64 diffutils-3.3-4.el7.x86_64 expat-2.1.0-10.el7_3.x86_64 audit-libs-2.8.4-4.el7.x86_64 pam-1.1.8-22.el7.x86_64 nss-softokn-3.36.0-5.el7_5.x86_64 nss-3.36.0-7.1.el7_6.x86_64 libassuan-2.1.0-3.el7.x86_64 nss-tools-3.36.0-7.1.el7_6.x86_64 gobject-introspection-1.56.1-1.el7.x86_64 --More--
1.20 - S'attacher à un conteneur en cours d'exécution
Arretez le conteneur. Démarrez le conteneur puis rattachez-vous au conteneur :
[root@86252a3f00f4 /]# exit exit root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 86252a3f00f4 centos "bash" About a minute ago Exited (127) 6 seconds ago vibrant_mccarthy c080793965de nginx "nginx -g 'daemon of…" 4 minutes ago Up 4 minutes 0.0.0.0:81->80/tcp suspicious_sanderson 4f157e179134 nginx "nginx -g 'daemon of…" 3 hours ago Exited (0) 3 hours ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 3 hours ago Exited (0) 3 hours ago i2tch root@debian9:~# docker start 8625 8625 root@debian9:~# docker attach 8625 [root@86252a3f00f4 /]# ls anaconda-post.log bin dev etc home lib lib64 media mnt opt proc root run sbin srv sys tmp usr var [root@86252a3f00f4 /]#
1.21 - Installer un logiciel dans le conteneur
Créez le fichier /etc/yum.repos.d/mongodb-org-4.2.repo :
[root@86252a3f00f4 /]# vi /etc/yum.repos.d/mongodb-org-4.2.repo [root@86252a3f00f4 /]# cat /etc/yum.repos.d/mongodb-org-4.2.repo [mongodb-org-4.2] name=MongoDB Repository baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.2/x86_64/ gpgcheck=1 enabled=1 gpgkey=https://www.mongodb.org/static/pgp/server-4.2.asc [root@86252a3f00f4 /]#
Installez mongo :
[root@86252a3f00f4 /]# yum install -y mongodb-org
Démarrez mongod :
[root@86252a3f00f4 /]# mongod --config /etc/mongod.conf & [1] 82 [root@86252a3f00f4 /]# about to fork child process, waiting until server is ready for connections. forked process: 84 child process started successfully, parent exiting [1]+ Done mongod --config /etc/mongod.conf [root@86252a3f00f4 /]#
Vérifiez que mongod est démarré :
[root@86252a3f00f4 /]# ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.1 11828 2996 pts/0 Ss 16:57 0:00 bash root 84 1.2 2.2 294692 46716 ? Sl 17:16 0:00 mongod --config /etc/mongod.conf root 103 0.0 0.1 51748 3444 pts/0 R+ 17:17 0:00 ps aux
Utilisez le client mongo pour se connecter au serveur :
[root@86252a3f00f4 /]# mongo MongoDB shell version: 4.2.2 connecting to: test Welcome to the MongoDB shell. For interactive help, type "help". For more comprehensive documentation, see http://docs.mongodb.org/ Questions? Try the support group http://groups.google.com/group/mongodb-user Server has startup warnings: 2019-04-09T17:16:26.951+0000 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended. 2019-04-09T17:16:26.951+0000 I CONTROL [initandlisten] >
Sortez de mongo et du conteneur :
> exit bye [root@86252a3f00f4 /]# exit exit root@debian9:~#
1.22 - Utilisation de la commande docker commit
Créez maintenant une nouvelle image à partir de votre conteneur :
root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 86252a3f00f4 centos "bash" 23 minutes ago Exited (0) 56 seconds ago vibrant_mccarthy c080793965de nginx "nginx -g 'daemon of…" 26 minutes ago Up 26 minutes 0.0.0.0:81->80/tcp suspicious_sanderson 4f157e179134 nginx "nginx -g 'daemon of…" 3 hours ago Exited (0) 3 hours ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 3 hours ago Exited (0) 3 hours ago i2tch root@debian9:~# docker commit 8625 i2tch/mongodb sha256:67afc80e1424a6d99179911ee499f6bf264faf2bc3c7ff4ac4a01ff9c23050a9
Supprimez le conteneur utilisé pour créer l'image :
root@debian9:~# docker rm 8625 8625 root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c080793965de nginx "nginx -g 'daemon of…" 28 minutes ago Up 28 minutes 0.0.0.0:81->80/tcp suspicious_sanderson 4f157e179134 nginx "nginx -g 'daemon of…" 3 hours ago Exited (0) 3 hours ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 3 hours ago Exited (0) 3 hours ago i2tch
Utilisez la nouvelle image pour lancer un conteneur nommé mongo :
root@debian9:~# docker run -it --name mongo i2tch/mongodb [root@d20fb56a38b0 /]# ls /usr/bin/mongo* /usr/bin/mongo /usr/bin/mongodump /usr/bin/mongofiles /usr/bin/mongooplog /usr/bin/mongorestore /usr/bin/mongostat /usr/bin/mongod /usr/bin/mongoexport /usr/bin/mongoimport /usr/bin/mongoperf /usr/bin/mongos /usr/bin/mongotop [root@d20fb56a38b0 /]# ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.1 0.1 11828 2972 pts/0 Ss 17:22 0:00 bash root 15 0.0 0.1 51748 3468 pts/0 R+ 17:23 0:00 ps aux
Editez le fichier /etc/bashrc :
[root@d20fb56a38b0 /]# echo "/usr/bin/mongod --config /etc/mongod.conf &" >> /etc/bashrc
[root@d20fb56a38b0 /]# tail /etc/bashrc
. "$i" >/dev/null
fi
fi
done
unset i
unset -f pathmunge
fi
# vim:ts=4:sw=4
/usr/bin/mongod --config /etc/mongod.conf &
Consultez la liste des conteneurs et relevez le CONTAINER ID du conteneur mongo :
[root@d20fb56a38b0 /]# exit exit root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d20fb56a38b0 i2tch/mongodb "bash" 2 minutes ago Exited (0) 4 seconds ago mongo c080793965de nginx "nginx -g 'daemon of…" 32 minutes ago Up 32 minutes 0.0.0.0:81->80/tcp suspicious_sanderson 4f157e179134 nginx "nginx -g 'daemon of…" 3 hours ago Exited (0) 3 hours ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 3 hours ago Exited (0) 3 hours ago i2tch
Utilisez la commande commit pour “sauvegarder” la modification dans l'image :
root@debian9:~# docker commit d20f i2tch/mongodb sha256:620057baa411b78a0030e192fdfbde0bb0c5ceae7bdeb115892d9946e542ee07
Démarrez de nouveau le conteneur pour vérifier que mongod fonctionne :
root@debian9:~# docker rm d20f d20f root@debian9:~# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES c080793965de nginx "nginx -g 'daemon of…" 33 minutes ago Up 33 minutes 0.0.0.0:81->80/tcp suspicious_sanderson 4f157e179134 nginx "nginx -g 'daemon of…" 3 hours ago Exited (0) 3 hours ago stoic_roentgen 04b5ab87539a ubuntu "/bin/bash" 3 hours ago Exited (0) 3 hours ago i2tch root@debian9:~# docker run -it --name mongo i2tch/mongodb [root@bcec3f27ed58 /]# about to fork child process, waiting until server is ready for connections. forked process: 16 child process started successfully, parent exiting [1]+ Done /usr/bin/mongod --config /etc/mongod.conf [root@bcec3f27ed58 /]# ps aux USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND root 1 0.0 0.1 11828 2920 pts/0 Ss 17:26 0:00 bash root 16 2.0 2.4 298788 49276 ? Sl 17:26 0:01 /usr/bin/mongod --config /etc/mongod.conf root 39 0.0 0.1 51748 3476 pts/0 R+ 17:27 0:00 ps aux [root@bcec3f27ed58 /]#
1.23 - Se connecter au serveur du conteneur de l'extérieur
Pour pouvoir se connecter à mongodb depuis la machine hôte, il convient d'éditer le fichier /etc/mongod.conf :
[root@bcec3f27ed58 /]# vi /etc/mongod.conf [root@bcec3f27ed58 /]# cat /etc/mongod.conf | grep bindIp bindIp: 0.0.0.0
Sortez du conteneur, re-créez une image, supprimez le conteneur utilisé et relancez de nouveau le conteneur :
[root@bcec3f27ed58 /]# exit exit root@debian9:~# docker commit mongo i2tch/mongodb sha256:eca7835d4fe6a3a769046bd735ef4ad7534ac1f9bb37832d6da5db3b938d258f root@debian9:~# docker rm mongo mongo root@debian9:~# docker run -it --name mongo i2tch/mongodb [root@d2ddb4f8ca8a /]# about to fork child process, waiting until server is ready for connections. forked process: 16 [root@d2ddb4f8ca8a /]# child process started successfully, parent exiting [1]+ Done /usr/bin/mongod --config /etc/mongod.conf [root@d2ddb4f8ca8a /]#
Dans votre machine hôte, configurez le dépôt de mongodb :
[root@f5b45072b831 /]# exit root@debian9:~# root@debian9:~# apt-get install dirmngr root@debian9:~# root@debian9:~# apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4 Executing: /tmp/apt-key-gpghome.xMuszKS6JM/gpg.1.sh --keyserver hkp://keyserver.ubuntu.com:80 --recv 9DA31620334BD75D9DCB49F368818C72E52529D4 gpg: key 68818C72E52529D4: public key "MongoDB 4.0 Release Signing Key <packaging@mongodb.com>" imported gpg: Total number processed: 1 gpg: imported: 1 root@debian9:~# root@debian9:~# echo "deb http://repo.mongodb.org/apt/debian stretch/mongodb-org/4.0 main" | tee /etc/apt/sources.list.d/mongodb-org-4.0.list deb http://repo.mongodb.org/apt/debian stretch/mongodb-org/4.0 main root@debian9:~# root@debian9:~# apt-get update
Cette fois, installez uniquement le client de mongodb :
root@debian9:~# apt-get install mongodb-org-shell Lecture des listes de paquets... Fait Construction de l'arbre des dépendances Lecture des informations d'état... Fait Les NOUVEAUX paquets suivants seront installés : mongodb-org-shell 0 mis à jour, 1 nouvellement installés, 0 à enlever et 95 non mis à jour. Il est nécessaire de prendre 9 809 ko dans les archives. Après cette opération, 39,8 Mo d'espace disque supplémentaires seront utilisés. Réception de:1 http://repo.mongodb.org/apt/debian stretch/mongodb-org/4.0/main amd64 mongodb-org-shell amd64 4.0.8 [9 809 kB] 9 809 ko réceptionnés en 7s (1 245 ko/s) Sélection du paquet mongodb-org-shell précédemment désélectionné. (Lecture de la base de données... 91513 fichiers et répertoires déjà installés.) Préparation du dépaquetage de .../mongodb-org-shell_4.0.8_amd64.deb ... Dépaquetage de mongodb-org-shell (4.0.8) ... Paramétrage de mongodb-org-shell (4.0.8) ... Traitement des actions différées (« triggers ») pour man-db (2.7.6.1-2) ...
Notez qu'à ce stade le conteneur ne possède pas d'adresse IP car il n'est pas démarré :
root@debian9:~# docker inspect mongo | grep IP
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"IPAMConfig": null,
"IPAddress": "",
"IPPrefixLen": 0,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
Démarrez donc le conteneur et cherchez l'adresse IP de celui-ci :
root@debian9:~# docker start mongo
mongo
root@debian9:~# docker inspect mongo | grep IP
"LinkLocalIPv6Address": "",
"LinkLocalIPv6PrefixLen": 0,
"SecondaryIPAddresses": null,
"SecondaryIPv6Addresses": null,
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
"IPAddress": "172.17.0.3",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"IPAMConfig": null,
"IPAddress": "172.17.0.3",
"IPPrefixLen": 16,
"IPv6Gateway": "",
"GlobalIPv6Address": "",
"GlobalIPv6PrefixLen": 0,
Connectez-vous maintenant à votre mongodb à partir de la machine hôte :
root@debian9:~# mongo --host 172.17.0.3 MongoDB shell version v4.0.8 connecting to: mongodb://172.17.0.3:27017/?gssapiServiceName=mongodb WARNING: No implicit session: Logical Sessions are only supported on server versions 3.6 and greater. Implicit session: dummy session MongoDB server version: 4.2.2 WARNING: shell and server versions do not match Welcome to the MongoDB shell. For interactive help, type "help". For more comprehensive documentation, see http://docs.mongodb.org/ Questions? Try the support group http://groups.google.com/group/mongodb-user Server has startup warnings: 2019-04-09T17:31:33.827+0000 I CONTROL [initandlisten] ** WARNING: You are running this process as the root user, which is not recommended. 2019-04-09T17:31:33.827+0000 I CONTROL [initandlisten] >
LAB #2 - Création d'un Utilisateur de Confiance pour Contrôler le Daemon Docker
Au contraire des solutions classiques de gestion de machines virtuelles où l'accès est souvent conditionné à l'attribution de rôles, Docker ne possède pas ce type de mécanisme. De ce fait toute personne ayant accès à l'hôte soit par sudo soit en étant membre du groupe docker peut accéder à tous les conteneurs voire les arrêter, supprimer et en créer d'autres.
root@debian9:~# cat /etc/group | grep docker docker:x:999: root@debian9:~# usermod -aG docker trainee root@debian9:~# exit déconnexion trainee@manager:~$ docker ps Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Get http://%2Fvar%2Frun%2Fdocker.sock/v1.40/containers/json: dial unix /var/run/docker.sock: connect: permission denied trainee@manager:~$ newgrp docker trainee@manager:~$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES d02c6115724c alpine "/bin/sh" 6 days ago Exited (0) 6 days ago alpine1 trainee@manager:~$ docker rm alpine1 alpine1 trainee@manager:~$ docker run -d --name alpine1 alpine sleep 99999 a214e2df0499c97e8da25a6c9ea751ac75344c9bcd7d238f8cb8d5c777510ab9 trainee@manager:~$ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES a214e2df0499 alpine "/bin/sh" 6 seconds ago Up 5 seconds alpine1
LAB #3 - Le Script docker-bench-security.sh
Le Center for Internet Security (CIS) est une organisation indépendante à but non-lucratif qui publie des best practices dans de nombreux domaines de l'informatique. Le guide pour Docker peut être téléchargé à partir de l'adresse https://www.cisecurity.org/benchmark/docker/.
Le guide est divisé en plusieurs sections :
- La configuration de l'hôte Docker,
- La configuration du daemon Docker,
- Les fichiers de configuration du daemon Docker,
- Les images ainsi que les fichiers servant à la construction des images,
- Le container runtime,
- Les opérations sécuritaires relatives à Docker,
- La configuration de Docker Swarm.
Ce guide est à utiliser avec le script Docker Benchmark Security.
Clonez le script docker-bench-security.sh en utilisant git :
trainee@manager:~$ su - Mot de passe : fenestros root@debian9:~# git clone https://github.com/docker/docker-bench-security.git Clonage dans 'docker-bench-security'... remote: Enumerating objects: 18, done. remote: Counting objects: 100% (18/18), done. remote: Compressing objects: 100% (16/16), done. remote: Total 1921 (delta 5), reused 6 (delta 2), pack-reused 1903 Réception d'objets: 100% (1921/1921), 2.90 MiB | 908.00 KiB/s, fait. Résolution des deltas: 100% (1339/1339), fait.
Exécutez maintenant le script Docker Benchmark Security :
root@debian9:~# cd docker-bench-security/ root@debian9:~/docker-bench-security# ./docker-bench-security.sh # ------------------------------------------------------------------------------ # Docker Bench for Security v1.3.5 # # Docker, Inc. (c) 2015- # # Checks for dozens of common best-practices around deploying Docker containers in production. # Inspired by the CIS Docker Benchmark v1.2.0. # ------------------------------------------------------------------------------ Initializing vendredi 8 novembre 2019, 12:12:03 (UTC+0100) [INFO] 1 - Host Configuration [INFO] 1.1 - General Configuration [NOTE] 1.1.1 - Ensure the container host has been Hardened [INFO] 1.1.2 - Ensure Docker is up to date [INFO] * Using 19.03.4, verify is it up to date as deemed necessary [INFO] * Your operating system vendor may provide support and security maintenance for Docker [INFO] 1.2 - Linux Hosts Specific Configuration [WARN] 1.2.1 - Ensure a separate partition for containers has been created ...
Ce script sert à automatiser le contrôle des points précédemment cités et produit un rapport contenant des annotations :
- [PASS] : Concerne les points qui n'ont pas besoin d'être modifiés,
- [WARN] : Concerne les points qui doivent être modifiés,
- [INFO] : Concerne les points qui doivent être passés en revue selon les besoins de votre configuration,
- [NOTE] : Vous informe d'un best practice.
LAB #4 - Sécurisation de la Configuration de l'Hôte Docker
Lors de l'exécution du script, vous devez obtenir un résultat similaire à ceci en ce qui concerne la Sécurité de la Configuration de l'hôte Docker :
... [INFO] 1 - Host Configuration [INFO] 1.1 - General Configuration [NOTE] 1.1.1 - Ensure the container host has been Hardened [INFO] 1.1.2 - Ensure Docker is up to date [INFO] * Using 19.03.4, verify is it up to date as deemed necessary [INFO] * Your operating system vendor may provide support and security maintenance for Docker [INFO] 1.2 - Linux Hosts Specific Configuration [WARN] 1.2.1 - Ensure a separate partition for containers has been created [INFO] 1.2.2 - Ensure only trusted users are allowed to control Docker daemon [INFO] * docker:x:999:trainee [WARN] 1.2.3 - Ensure auditing is configured for the Docker daemon [WARN] 1.2.4 - Ensure auditing is configured for Docker files and directories - /var/lib/docker [WARN] 1.2.5 - Ensure auditing is configured for Docker files and directories - /etc/docker [WARN] 1.2.6 - Ensure auditing is configured for Docker files and directories - docker.service [WARN] 1.2.7 - Ensure auditing is configured for Docker files and directories - docker.socket [WARN] 1.2.8 - Ensure auditing is configured for Docker files and directories - /etc/default/docker [INFO] 1.2.9 - Ensure auditing is configured for Docker files and directories - /etc/sysconfig/docker [INFO] * File not found [INFO] 1.2.10 - Ensure auditing is configured for Docker files and directories - /etc/docker/daemon.json [INFO] * File not found [WARN] 1.2.11 - Ensure auditing is configured for Docker files and directories - /usr/bin/containerd [INFO] 1.2.12 - Ensure auditing is configured for Docker files and directories - /usr/sbin/runc [INFO] * File not found ...
Les problèmes de sécurité qu'il convient à résoudre sont indiqués par les annotations [WARN].
4.1 - [WARN] 1.2.1 - Ensure a separate partition for containers has been created
Par défaut, tous les fichiers de Docker sont stockés dans le répertoire /var/lib/docker, y compris toutes les images, tous les conteneurs et tous les volumes. Sur un système hôte n'ayant qu'une seule partition il y a un risque, tous comme le risque lié au répertoire /var/log/, que le disque devient saturé.
4.2 - [WARN] 1.2.3 - Ensure auditing is configured for the Docker daemon
[WARN] 1.2.4 - Ensure auditing is configured for Docker files and directories - /var/lib/docker [WARN] 1.2.5 - Ensure auditing is configured for Docker files and directories - /etc/docker [WARN] 1.2.6 - Ensure auditing is configured for Docker files and directories - docker.service [WARN] 1.2.7 - Ensure auditing is configured for Docker files and directories - docker.socket [WARN] 1.2.8 - Ensure auditing is configured for Docker files and directories - /etc/default/docker [WARN] 1.2.11 - Ensure auditing is configured for Docker files and directories - /usr/bin/containerd
Ces avertissements sont présents parce que auditd n'est pas installé et parce qu'il n'y a pas de règles spécifiques au daemon Docker et ses répertoires et fichiers associés.
Pour installer auditd, utilisez apt-get :
root@debian9:~/docker-bench-security# apt-get install auditd
Modifiez ensuite le fichier /etc/audit/rules.d/audit.rules :
root@debian9:~/docker-bench-security# vi /etc/audit/rules.d/audit.rules root@debian9:~/docker-bench-security# cat /etc/audit/rules.d/audit.rules ## First rule - delete all -D ## Increase the buffers to survive stress events. ## Make this bigger for busy systems -b 8192 ## This determine how long to wait in burst of events --backlog_wait_time 0 ## Set failure mode to syslog -f 1 ##Docker -w /usr/bin/docker -p wa -w /var/lib/docker -p wa -w /etc/docker -p wa -w /lib/systemd/system/docker.service -p wa -w /lib/systemd/system/docker.socket -p wa -w /etc/default/docker -p wa -w /etc/docker/daemon.json -p wa -w /usr/bin/docker-containerd -p wa -w /usr/bin/docker-runc -p wa -w /usr/bin/containerd -p wa
Important : L'option -w indique watch et concerne le fichier qui suit. L'option -p journalise les modifications éventuelles.
Re-démarrez ensuite auditd :
root@debian9:~/docker-bench-security# systemctl restart auditd
Vérifiez ensuite la prise en charge des règles :
root@debian9:~/docker-bench-security# cat /etc/audit/audit.rules ## This file is automatically generated from /etc/audit/rules.d -D -b 8192 -f 1 --backlog_wait_time 0 -w /usr/bin/docker -p wa -w /var/lib/docker -p wa -w /etc/docker -p wa -w /lib/systemd/system/docker.service -p wa -w /lib/systemd/system/docker.socket -p wa -w /etc/default/docker -p wa -w /etc/docker/daemon.json -p wa -w /usr/bin/docker-containerd -p wa -w /usr/bin/docker-runc -p wa -w /usr/bin/containerd -p wa
Important - Pour plus d'information concernant la création de règles personalisées avec auditd, consultez cette page.
Ré-exécutez le script Docker Benchmark Security :
root@debian9:~/docker-bench-security# ./docker-bench-security.sh ... [PASS] 1.2.4 - Ensure auditing is configured for Docker files and directories - /var/lib/docker [PASS] 1.2.5 - Ensure auditing is configured for Docker files and directories - /etc/docker [PASS] 1.2.6 - Ensure auditing is configured for Docker files and directories - docker.service [PASS] 1.2.7 - Ensure auditing is configured for Docker files and directories - docker.socket [PASS] 1.2.8 - Ensure auditing is configured for Docker files and directories - /etc/default/docker ... [PASS] 1.2.11 - Ensure auditing is configured for Docker files and directories - /usr/bin/containerd ...
LAB #5 - Sécurisation de la Configuration du daemon Docker
Exécutez de nouveau le script docker-bench-security.sh. Vous devez obtenir un résultat similaire à ceci en ce qui concerne la sécurité de la configuration du daemon Docker :
... [INFO] 2 - Docker daemon configuration [WARN] 2.1 - Ensure network traffic is restricted between containers on the default bridge [PASS] 2.2 - Ensure the logging level is set to 'info' [PASS] 2.3 - Ensure Docker is allowed to make changes to iptables [PASS] 2.4 - Ensure insecure registries are not used [PASS] 2.5 - Ensure aufs storage driver is not used [INFO] 2.6 - Ensure TLS authentication for Docker daemon is configured [INFO] * Docker daemon not listening on TCP [INFO] 2.7 - Ensure the default ulimit is configured appropriately [INFO] * Default ulimit doesn't appear to be set [WARN] 2.8 - Enable user namespace support [PASS] 2.9 - Ensure the default cgroup usage has been confirmed [PASS] 2.10 - Ensure base device size is not changed until needed [WARN] 2.11 - Ensure that authorization for Docker client commands is enabled [WARN] 2.12 - Ensure centralized and remote logging is configured [PASS] 2.13 - Ensure live restore is Enabled (Incompatible with swarm mode) [WARN] 2.14 - Ensure Userland Proxy is Disabled [PASS] 2.15 - Ensure that a daemon-wide custom seccomp profile is applied if appropriate [PASS] 2.16 - Ensure that experimental features are not implemented in production [WARN] 2.17 - Ensure containers are restricted from acquiring new privileges ...
Les problèmes de sécurité qu'il convient à résoudre sont indiqués par les annotations [WARN].
5.1 - [WARN] 2.1 - Ensure network traffic is restricted between containers on the default bridge
Par défaut Docker permet un trafic réseau sans restrictions entre des conteneurs sur le même hôte. Il est cependant possible de modifier la configuration par défaut. Pour empêcher ceci, il faut fixer la valeur de icc à false. De cette façon, docker crée des conteneurs qui peuvent communiquer entre eux uniquement s'il existe un lien.
Pour plus d'informations, consultez cette page.
5.2 - [WARN] 2.8 - Enable user namespace support
Cet avertissement nous indique que l'utilisation des user namespaces n'est pas activée. Le support des user namespaces du noyau Linux permet d'attribuer une plage d'UIDs et de GIDs unique à un processus et donc à un conteneur, en dehors de la plage traditionnelle utilisée par l'hôte Docker. L'avantage ici est que les processus ayant l'UID de root dans le conteneur seront mappés à un UID sans privilèges dans l'hôte Docker. Pour utiliser user namespace, il faut fixer la valeur de userns-remap à default. Dans ce cas précis Docker crée un utilisateur dénommé dockremap. Notez qu'il est aussi possible de fixer vos propres valeurs avec “userns-remap”: “user:group”.
Pour plus d'informations, consultez cette page.
5.3 - [WARN] 2.11 - Ensure that authorization for Docker client commands is enabled
Par défaut, Docker permet un accès sans restrictions aux daemon Docker. Il est possible de restreindre l'accès à des utilisateurs authentifiés en utilisant un plug-in. Cette ligne est sans importance parce que l'accès au socket local Docker est limité aux membres du groupe docker (voir DOF202 - La Sécurité de la Configuration de l'Hôte Docker)
Pour plus d'informations, consultez cette page.
5.4 - [WARN] 2.12 - Ensure centralized and remote logging is configured
Cet avertissement indique que la configuration de rsyslog ne permet pas l'envoie des traces vers un serveur de journalisation distant. Elle indique aussi que la valeur de log-driver n'a pas été spécifiée. Pour activer cette configuration, il faut fixer la valeur de log-driver à syslog puis configurer syslog ainsi que la valeur de log-opts correctement.
Pour plus d'informations, consultez cette page.
5.5 - [WARN] 2.14 - Ensure Userland Proxy is Disabled
Il existe deux méthodes pour qu'un conteneur puisse router vers l'extérieur :
- le mode Hairpin NAT,
- Userland Proxy.
Il est préférable d'utiliser le mode Hairpin NAT qui peut utilise Iptables et qui possède de meilleures performances. La plupart des systèmes d'opération modernes peuvent utiliser le mode Hairpin NAT. Pour désactiver Userland Proxy, il faut fixer la valeur de userland-proxy à false.
Pour plus d'informations, consultez cette page.
5.6 - [WARN] 2.17 - Ensure containers are restricted from acquiring new privileges
Par défaut un conteneur peut obtenir une escalade de privilèges en utilisant les binaires setuid ou setgid. Pour interdire ceci il faut fixer la valeur de no-new-privileges à true.
Pour plus d'informations, consultez cette page.
5.7 - Le Fichier /etc/docker/daemon.json
Créez le fichier /etc/docker/daemon.json :
root@debian9:~/docker-bench-security# vi /etc/docker/daemon.json
root@debian9:~/docker-bench-security# cat /etc/docker/daemon.json
{
"icc": false,
"userns-remap": "default",
"log-driver": "syslog",
"live-restore": true,
"userland-proxy": false,
"no-new-privileges": true
}
Notez ici que live-restore est fixé à true. Ceci permet aux conteneurs de continuer à fonctionner même quand le daemon Docker ne fonctionne pas. Ceci est utile pendant la mise-à-jour de Docker.
Re-démarrez le service Docker :
root@debian9:~/docker-bench-security# systemctl restart docker
Vérifiez la présence de l'utilisateur dénommé dockremap :
root@debian9:~/docker-bench-security# id dockremap uid=116(dockremap) gid=121(dockremap) groupes=121(dockremap)
Ré-exécutez le script Docker Benchmark Security :
root@debian9:~# cd docker-bench-security/ root@debian9:~/docker-bench-security# ./docker-bench-security.sh ... [PASS] 2.1 - Ensure network traffic is restricted between containers on the default bridge ... [PASS] 2.8 - Enable user namespace support ... [WARN] 2.11 - Ensure that authorization for Docker client commands is enabled [PASS] 2.12 - Ensure centralized and remote logging is configured ... [PASS] 2.14 - Ensure Userland Proxy is Disabled ... [PASS] 2.17 - Ensure containers are restricted from acquiring new privileges ...
Pour plus d'informations, consultez cette page.
LAB #6 - Sécurisation des Images et les Fichiers de Construction
Créez le conteneur mysql :
root@debian9:~/docker-bench-security# docker container run -d --name mysql -e MYSQL_ROOT_PASSWORD=password mysql Unable to find image 'mysql:latest' locally latest: Pulling from library/mysql 80369df48736: Pull complete e8f52315cb10: Pull complete cf2189b391fc: Pull complete cc98f645c682: Pull complete 27a27ac83f74: Pull complete fa1f04453414: Pull complete d45bf7d22d33: Pull complete 3dbac26e409c: Pull complete 9017140fb8c1: Pull complete b76dda2673ae: Pull complete bea9eb46d12a: Pull complete e1f050a38d0f: Pull complete Digest: sha256:7345ce4ce6f0c1771d01fa333b8edb2c606ca59d385f69575f8e3e2ec6695eee Status: Downloaded newer image for mysql:latest 54606c03c52c5e3ec0328029d69b869d4b285fb433015576dedc8b8dd4ad0494 root@debian9:~/docker-bench-security# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 54606c03c52c mysql "docker-entrypoint.s…" 5 seconds ago Up 4 seconds 3306/tcp, 33060/tcp mysql
Exécutez de nouveau le script docker-bench-security.sh. Vous devez obtenir un résultat similaire à ceci en ce qui concerne la sécurité des images et les fichiers de leur construction :
root@debian9:~/docker-bench-security# ./docker-bench-security.sh ... [INFO] 4 - Container Images and Build File [WARN] 4.1 - Ensure a user for the container has been created [WARN] * Running as root: mysql [NOTE] 4.2 - Ensure that containers use only trusted base images [NOTE] 4.3 - Ensure that unnecessary packages are not installed in the container [NOTE] 4.4 - Ensure images are scanned and rebuilt to include security patches [WARN] 4.5 - Ensure Content trust for Docker is Enabled [WARN] 4.6 - Ensure that HEALTHCHECK instructions have been added to container images [WARN] * No Healthcheck found: [alpine:latest] [WARN] * No Healthcheck found: [mysql:latest] [INFO] 4.7 - Ensure update instructions are not use alone in the Dockerfile [INFO] * Update instruction found: [mysql:latest] [NOTE] 4.8 - Ensure setuid and setgid permissions are removed [PASS] 4.9 - Ensure that COPY is used instead of ADD in Dockerfiles [NOTE] 4.10 - Ensure secrets are not stored in Dockerfiles [NOTE] 4.11 - Ensure only verified packages are installed ...
6.1 - [WARN] 4.1 - Ensure a user for the container has been created
Les processus dans le conteneur root-nginx tourne sous l'UID de root. Ceci est l'action par défaut de Docker.
Pour plus d'informations, consultez cette page.
6.2 - [WARN] 4.5 - Ensure Content trust for Docker is Enabled
Cette ligne indique que le support de Content trust n'a pas été activé. Content trust permet de s'assurer de la provenance des images utilisées car celles-ci sont signées.
Pour activer le Content trust, il faut positionner la valeur de la variable DOCKER_CONTENT_TRUST à 1 :
root@debian9:~/docker-bench-security# echo "DOCKER_CONTENT_TRUST=1" | sudo tee -a /etc/environment DOCKER_CONTENT_TRUST=1 root@debian9:~/docker-bench-security# source /etc/environment
Re-démarrez la machine virtuelle Manager et démarrez le conteneur mysql :
root@debian9:~/docker-bench-security# docker container start mysql mysql root@debian9:~/docker-bench-security# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 54606c03c52c mysql "docker-entrypoint.s…" 10 minutes ago Up 2 seconds 3306/tcp, 33060/tcp mysql
Exécutez de nouveau le script et notez le contenu de la section 4 :
root@debian9:~/docker-bench-security# ./docker-bench-security.sh ... [INFO] 4 - Container Images and Build File [WARN] 4.1 - Ensure a user for the container has been created [WARN] * Running as root: mysql [NOTE] 4.2 - Ensure that containers use only trusted base images [NOTE] 4.3 - Ensure that unnecessary packages are not installed in the container [NOTE] 4.4 - Ensure images are scanned and rebuilt to include security patches [PASS] 4.5 - Ensure Content trust for Docker is Enabled [WARN] 4.6 - Ensure that HEALTHCHECK instructions have been added to container images [WARN] * No Healthcheck found: [alpine:latest] [WARN] * No Healthcheck found: [mysql:latest] [INFO] 4.7 - Ensure update instructions are not use alone in the Dockerfile [INFO] * Update instruction found: [mysql:latest] [NOTE] 4.8 - Ensure setuid and setgid permissions are removed [PASS] 4.9 - Ensure that COPY is used instead of ADD in Dockerfiles [NOTE] 4.10 - Ensure secrets are not stored in Dockerfiles [NOTE] 4.11 - Ensure only verified packages are installed ...
Pour plus d'informations, consultez cette page.
6.3 - [WARN] 4.6 - Ensure that HEALTHCHECK instructions have been added to container images
Quand une image est construite, il est possible d'y mettre un HEALTHCHECK dont le statut peut être vérifié par Docker afin de relancer le conteneur si nécessaire.
Pour mettre en place un HEALTHCHECK, il conviendrait, par exemple, d'inclure la ligne suivante dans le fichier DOCKERFILE servant à construire l'image :
HEALTHCHECK --interval=20s --timeout=3s CMD curl -f http://localhost:8000/ || exit 1
Ce test permet de vérifier que le conteneur peut atteindre l'URL indiqué tous les 20 secondes et produit une erreur au bout de 3 secondes.
Pour plus d'informations, consultez cette page.
LAB #7 - Sécurisation du Container Runtime
Exécutez de nouveau le script docker-bench-security.sh, vous devez obtenir un résultat similaire à ceci en ce qui concerne la sécurité du Container Runtime :
root@debian9:~/docker-bench-security# ./docker-bench-security.sh ... [INFO] 5 - Container Runtime [WARN] 5.1 - Ensure that, if applicable, an AppArmor Profile is enabled [WARN] * No AppArmorProfile Found: mysql [WARN] 5.2 - Ensure that, if applicable, SELinux security options are set [WARN] * No SecurityOptions Found: mysql [PASS] 5.3 - Ensure Linux Kernel Capabilities are restricted within containers [PASS] 5.4 - Ensure that privileged containers are not used [PASS] 5.5 - Ensure sensitive host system directories are not mounted on containers [PASS] 5.6 - Ensure sshd is not run within containers [PASS] 5.7 - Ensure privileged ports are not mapped within containers [NOTE] 5.8 - Ensure that only needed ports are open on the container [PASS] 5.9 - Ensure the host's network namespace is not shared [WARN] 5.10 - Ensure that the memory usage for containers is limited [WARN] * Container running without memory restrictions: mysql [WARN] 5.11 - Ensure CPU priority is set appropriately on the container [WARN] * Container running without CPU restrictions: mysql [WARN] 5.12 - Ensure that the container's root filesystem is mounted as read only [WARN] * Container running with root FS mounted R/W: mysql [PASS] 5.13 - Ensure that incoming container traffic is bound to a specific host interface [WARN] 5.14 - Ensure that the 'on-failure' container restart policy is set to '5' [WARN] * MaximumRetryCount is not set to 5: mysql [PASS] 5.15 - Ensure the host's process namespace is not shared [PASS] 5.16 - Ensure the host's IPC namespace is not shared [PASS] 5.17 - Ensure that host devices are not directly exposed to containers [INFO] 5.18 - Ensure that the default ulimit is overwritten at runtime if needed [INFO] * Container no default ulimit override: mysql [PASS] 5.19 - Ensure mount propagation mode is not set to shared [PASS] 5.20 - Ensure the host's UTS namespace is not shared [PASS] 5.21 - Ensure the default seccomp profile is not Disabled [NOTE] 5.22 - Ensure docker exec commands are not used with privileged option [NOTE] 5.23 - Ensure that docker exec commands are not used with the user=root option [PASS] 5.24 - Ensure that cgroup usage is confirmed [WARN] 5.25 - Ensure that the container is restricted from acquiring additional privileges [WARN] * Privileges not restricted: mysql [WARN] 5.26 - Ensure that container health is checked at runtime [WARN] * Health check not set: mysql [INFO] 5.27 - Ensure that Docker commands always make use of the latest version of their image [WARN] 5.28 - Ensure that the PIDs cgroup limit is used [WARN] * PIDs limit not set: mysql [INFO] 5.29 - Ensure that Docker's default bridge 'docker0' is not used [INFO] * Container in docker0 network: mysql [PASS] 5.30 - Ensure that the host's user namespaces are not shared [PASS] 5.31 - Ensure that the Docker socket is not mounted inside any containers ...
Les problèmes de sécurité qu'il convient à résoudre sont indiqués par les annotations [WARN].
7.1 - [WARN] 5.1 - Ensure AppArmor Profile is Enabled
Cet avertissement est présent parce que le conteneur n'utilise pas AppArmor.
Pour plus d'informations, consultez cette page.
7.2 - [WARN] 5.2 - Ensure SELinux security options are set, if applicable
Cet avertissement est présent parce que le conteneur n'utilise pas SELinux.
Pour plus d'informations, consultez cette page.
7.3 - [WARN] 5.10 - Ensure memory usage for container is limited
Cet avertissement est du au fait que les conteneurs ont automatiquement accès à la totalité de la RAM de l'hôte Docker :
root@debian9:~# docker run -d -p 8081:80 nginx b04b2a6f0dd93da21a8b7640afc319406e42868a141f90936dbcf52ab5bffb0d root@debian9:~# docker stats CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS b04b2a6f0dd9 dazzling_blackburn 0.00% 1.789MiB / 1.957GiB 0.09% 2.38kB / 0B 0B / 0B 2 ^C
Supprimez le conteneur et re-créez le avec une limite de mémoire :
root@debian9:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
b04b2a6f0dd9 nginx "nginx -g 'daemon of…" About a minute ago Up About a minute 0.0.0.0:8081->80/tcp dazzling_blackburn
5b31fe1e13bc ubuntu "bash -c ':() { : | …" 14 minutes ago Exited (254) 13 minutes ago pensive_fermat
7788c67c3b69 mysql "docker-entrypoint.s…" About an hour ago Exited (255) 18 minutes ago 3306/tcp, 33060/tcp mysql
root@debian9:~# docker rm -f b0
b0
root@debian9:~# docker run -d -p 8081:80 --memory="256m" nginx
095472e5096a57277230ff94822d9bd0ad479ad26a33cbf83ec381cdb02910e1
root@debian9:~# docker stats
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS
095472e5096a affectionate_goldstine 0.00% 1.805MiB / 256MiB 0.70% 2.38kB / 0B 0B / 0B 2
^C
Pour plus d'informations, consultez cette page.
7.4 - [WARN] 5.11 - Ensure CPU priority is set appropriately on the container
Cet avertissement est du au fait que les conteneurs ont automatiquement accès à tous les CPU de l'hôte Docker. Pour limiter cet accès, plusieurs options sont possibles dont le plus couramment utilisée est –cpu-shares.
La valeur de cpu-shares est relative à la valeur par défaut de 1024. Un valeur de 512 permet au conteneur d'accéder à 50% des cycles du CPU mais uniquement quand les cycles sont limités. Quand les cycles de CPU ne sont par restreints, chaque conteneur utilise autant qu'il en a besoin.
Pour plus d'informations, consultez cette page.
7.5 - [WARN] 5.12 - Ensure the container's root filesystem is mounted as read only
Afin de minimiser le risque de compromettre un conteneur par la présence de code malicieux, il est conseillé de démarrer les conteneurs en lecture seule, sauf pour les volumes qui nécessitent un accès en écriture/lecture.
Créez le fichier write_a_file dans le conteneur mysql :
root@debian9:~/docker-bench-security# docker container exec mysql touch /write_a_file
La Commande docker container diff indique les différences apportées au conteneur par rapport à l'image dont il est issu :
root@debian9:~/docker-bench-security# docker container diff mysql A /write_a_file C /run C /run/mysqld A /run/mysqld/mysqld.sock A /run/mysqld/mysqld.sock.lock A /run/mysqld/mysqlx.sock A /run/mysqld/mysqlx.sock.lock A /run/mysqld/mysqld.pid
Important : Notez que la sortie indique les changements apportés au conteneur.
Arrêtez et supprimez le conteneur :
root@debian9:~/docker-bench-security# docker container stop mysql mysql root@debian9:~/docker-bench-security# docker container rm mysql mysql
Lancez un conteneur mysql en lecture seule :
root@debian9:~/docker-bench-security# docker container run -d --name mysql --read-only -v /var/lib/mysql -v /tmp -v /var/run/mysqld -e MYSQL_ROOT_PASSWORD=password mysql 7788c67c3b692515f63f4659a8f40af397bfbde97485e2e40c500c16b158045b root@debian9:~/docker-bench-security# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 7788c67c3b69 mysql "docker-entrypoint.s…" 5 seconds ago Up 5 seconds 3306/tcp, 33060/tcp mysql
Créez le fichier write_a_file dans le conteneur mysql :
root@debian9:~/docker-bench-security# docker container exec mysql touch /write_a_file touch: cannot touch '/write_a_file': Read-only file system
Important : Notez l'erreur touch: cannot touch '/write_a_file': Read-only file system.
Exécutez la commande docker container diff :
root@debian9:~/docker-bench-security# docker container diff mysql root@debian9:~/docker-bench-security#
Important : Notez que la commande ne retourne aucune sortie. En effet le conteneur étant en lecture seule, aucun changement ne peut intervenir.
7.6 - [WARN] 5.14 - Ensure 'on-failure' container restart policy is set to '5'
Cet avertissement concerne la politique de re-démarrage du conteneur. La politique on-failure[:max-retries] implique que le conteneur est re-démarré en cas d'arrêt du à une erreur qui se manifeste en tant que code de retour autre que zéro. La valeur de max-retries est le nombre de fois que Docker va essayer de re-démarrer le conteneur. Cette politique peut être mise en place au démarrage du conteneur, par exemple :
# docker container run -d --name mysql --read-only --restart on-failure:5 -v /var/lib/mysql -v /tmp -v /var/run/mysqld -e MYSQL_ROOT_PASSWORD=password mysql
Pour plus d'informations, consultez cette page.
7.7 - [WARN] 5.25 - Ensure the container is restricted from acquiring additional privileges
Pour complémenter la configuration précédemment mise en place, il convient de lancer le conteneur en utilisant l'option –security-opt :
# docker container run -d --name mysql --read-only --restart on-failure:5 --security-opt="no-new-privileges:true" -v /var/lib/mysql -v /tmp -v /var/run/mysqld -e MYSQL_ROOT_PASSWORD=password mysql
Pour plus d'informations, consultez cette page.
7.8 - [WARN] 5.26 - Ensure container health is checked at runtime
Voir l'avertissement 4.6.
7.9 - [WARN] 5.28 - Ensure PIDs cgroup limit is used
Sans l'utilisation de l'option –pids-limit un conteneur pourrait être victime d'une attaque de type Fork Bomb, un type spécifique de dénie de service. Ce type d'attaque peut faire crasher l'hôte Docker et le seul remède est de re-démarrer l'hôte. Voici un exemple d'un Fork Bomb :
root@debian9:~/docker-bench-security# docker run -u 1000 ubuntu bash -c ":() { : | : & }; :; while [[ true ]]; do sleep 1; done"
L'hôte Docker manager crash. Après avoir re-démarrer la machine virtuelle, créez de nouveau le conteneur en utilisant l'option –pids-limit :
root@debian9:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
05b11e44e595 ubuntu "bash -c ':() { : | …" 6 minutes ago Exited (255) 3 minutes ago upbeat_turing
...
root@debian9:~# docker rm 05
05
root@debian9:~# docker run -u 1000 --pids-limit 100 ubuntu bash -c ":() { : | : & }; :; while [[ true ]]; do sleep 1; done"
environment: fork: retry: Resource temporarily unavailable
environment: fork: retry: Resource temporarily unavailable
environment: fork: retry: Resource temporarily unavailable
environment: fork: retry: Resource temporarily unavailable
environment: fork: retry: Resource temporarily unavailable
environment: fork: retry: Resource temporarily unavailable
^C
Pour plus d'informations, consultez cette page.
Supprimez maintenant tous les conteneurs déjà créées :
root@debian9:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
095472e5096a nginx "nginx -g 'daemon of…" 13 minutes ago Up 13 minutes 0.0.0.0:8081->80/tcp affectionate_goldstine
5b31fe1e13bc ubuntu "bash -c ':() { : | …" 28 minutes ago Exited (254) 28 minutes ago pensive_fermat
7788c67c3b69 mysql "docker-entrypoint.s…" About an hour ago Exited (255) 33 minutes ago 3306/tcp, 33060/tcp mysql
root@debian9:~# docker stop 095
095
root@debian9:~# docker rm `docker ps -aq`
5b31fe1e13bc
7788c67c3b69
095472e5096a
root@debian9:~# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
Re-créez le conteneur mysql en intégrant les points vus ci-dessus :
root@debian9:~# cd docker-bench-security/ root@debian9:~/docker-bench-security# docker container run -d --name mysql --read-only --restart on-failure:5 --security-opt="no-new-privileges:true" --pids-limit 100 --memory="256m" --cpu-shares 512 -v /var/lib/mysql -v /tmp -v /var/run/mysqld -e MYSQL_ROOT_PASSWORD=password mysql df54974ebc11fe357f6e8e9b0f8499aee2658af435e32a45058a1e49fcd3dc24 root@debian9:~/docker-bench-security# docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES df54974ebc11 mysql "docker-entrypoint.s…" 5 seconds ago Up 4 seconds 3306/tcp, 33060/tcp mysql
Exécutez de nouveau le script docker-bench-security.sh, vous devez obtenir un résultat similaire à ceci en ce qui concerne la sécurité du Container Runtime :
root@debian9:~/docker-bench-security# ./docker-bench-security.sh ... [INFO] 5 - Container Runtime [WARN] 5.1 - Ensure that, if applicable, an AppArmor Profile is enabled [WARN] * No AppArmorProfile Found: mysql [PASS] 5.2 - Ensure that, if applicable, SELinux security options are set [PASS] 5.3 - Ensure Linux Kernel Capabilities are restricted within containers [PASS] 5.4 - Ensure that privileged containers are not used [PASS] 5.5 - Ensure sensitive host system directories are not mounted on containers [PASS] 5.6 - Ensure sshd is not run within containers [PASS] 5.7 - Ensure privileged ports are not mapped within containers [NOTE] 5.8 - Ensure that only needed ports are open on the container [PASS] 5.9 - Ensure the host's network namespace is not shared [PASS] 5.10 - Ensure that the memory usage for containers is limited [PASS] 5.11 - Ensure CPU priority is set appropriately on the container [PASS] 5.12 - Ensure that the container's root filesystem is mounted as read only [PASS] 5.13 - Ensure that incoming container traffic is bound to a specific host interface [PASS] 5.14 - Ensure that the 'on-failure' container restart policy is set to '5' [PASS] 5.15 - Ensure the host's process namespace is not shared [PASS] 5.16 - Ensure the host's IPC namespace is not shared [PASS] 5.17 - Ensure that host devices are not directly exposed to containers [INFO] 5.18 - Ensure that the default ulimit is overwritten at runtime if needed [INFO] * Container no default ulimit override: mysql [PASS] 5.19 - Ensure mount propagation mode is not set to shared [PASS] 5.20 - Ensure the host's UTS namespace is not shared [PASS] 5.21 - Ensure the default seccomp profile is not Disabled [NOTE] 5.22 - Ensure docker exec commands are not used with privileged option [NOTE] 5.23 - Ensure that docker exec commands are not used with the user=root option [PASS] 5.24 - Ensure that cgroup usage is confirmed [PASS] 5.25 - Ensure that the container is restricted from acquiring additional privileges [WARN] 5.26 - Ensure that container health is checked at runtime [WARN] * Health check not set: mysql [INFO] 5.27 - Ensure that Docker commands always make use of the latest version of their image [PASS] 5.28 - Ensure that the PIDs cgroup limit is used [INFO] 5.29 - Ensure that Docker's default bridge 'docker0' is not used [INFO] * Container in docker0 network: mysql [PASS] 5.30 - Ensure that the host's user namespaces are not shared [PASS] 5.31 - Ensure that the Docker socket is not mounted inside any containers ...
LAB #8 - Sécurisation des Images avec Docker Content Trust
Docker Content Trust (DCT) a été introduit avec Docker Engine 1.8 et Docker CS Engine 1.9.0. DCT permet la vérification de l'authenticité, de l'intégrité et la date de publication d'une image Docker dans un registry. Par défaut, DCT est désactivé.
DCT est utilisé par le Docker Hub Registry mais peut aussi être mis en place dans des Registry privés, notamment grâce à la mise en place du Docker Container Registry qui est inclus avec Docker Enterprise.
DCT est basé sur l'utilisation de l'outil Docker Notary pour publier et gérer du contenu ainsi que The Update Framework (TUF).
Pour plus d'information concernant DCT, consultez cette page.
8.1 - DOCKER_CONTENT_TRUST
Pour utiliser Docker Content Trust (DCT), il convient de vérifier que la valeur de la variable DOCKER_CONTENT_TRUST est 1 :
root@debian9:~# echo $DOCKER_CONTENT_TRUST 1
Dans le cas contraire, il faut fixer la valeur de la variable à 1 :
root@debian9:~# export DOCKER_CONTENT_TRUST=1 root@debian9:~# echo $DOCKER_CONTENT_TRUST 1
8.2 - DCT et la commande docker pull
Afin d'utiliser un registry privé du Docker Hub, il est nécessaire de se connecter :
root@debian9:~# docker login Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one. Username: <votre_compte> Password: <votre_mot_de_passe> WARNING! Your password will be stored unencrypted in /root/.docker/config.json. Configure a credential helper to remove this warning. See https://docs.docker.com/engine/reference/commandline/login/#credentials-store Login Succeeded
Pour constater l'impact de l'utilisation de DCT, il convient simplement de faire un pull d'une image non-signée :
root@debian9:~# docker image pull i2tch/docker:unsigned Error: remote trust data does not exist for docker.io/i2tch/docker: notary.docker.io does not have trust data for docker.io/i2tch/docker
Important : Notez l'erreur Error: remote trust data does not exist for docker.io/i2tch/docker …. En effet Docker Trust empêche l'utilisation des images non-signées.
Par contre, toutes les images de type official sont signées :
root@debian9:~# docker image pull centos Using default tag: latest Pull (1 of 1): centos:latest@sha256:f94c1d992c193b3dc09e297ffd54d8a4f1dc946c37cbeceb26d35ce1647f88d9 sha256:f94c1d992c193b3dc09e297ffd54d8a4f1dc946c37cbeceb26d35ce1647f88d9: Pulling from library/centos 729ec3a6ada3: Pull complete Digest: sha256:f94c1d992c193b3dc09e297ffd54d8a4f1dc946c37cbeceb26d35ce1647f88d9 Status: Downloaded newer image for centos@sha256:f94c1d992c193b3dc09e297ffd54d8a4f1dc946c37cbeceb26d35ce1647f88d9 Tagging centos@sha256:f94c1d992c193b3dc09e297ffd54d8a4f1dc946c37cbeceb26d35ce1647f88d9 as centos:latest docker.io/library/centos:latest
Cette image est maintenant présente sur manager.i2tch.loc :
root@debian9:~# docker images REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu latest 775349758637 9 days ago 64.2MB nginx latest 540a289bab6c 2 weeks ago 126MB alpine latest 965ea09ff2eb 2 weeks ago 5.55MB mysql latest c8ee894bd2bd 3 weeks ago 456MB centos latest 0f3e07c0138f 5 weeks ago 220MB
L'option disable-content-trust
Il est aussi possible d'activer ou de désactiver l'utilisation de DCT avec les options –disable-content-trust=false/true lors de l'utilisation des commandes docker build, docker push et docker pull, docker create et docker run :
root@debian9:~# docker image pull --disable-content-trust=true i2tch/docker:unsigned unsigned: Pulling from i2tch/docker 10d70a43a9f9: Pull complete 4f4fb700ef54: Pull complete 8951e3a91277: Pull complete d1814ff35b8b: Pull complete ff2a2bbf6141: Pull complete b7205da5c3c9: Pull complete 458ea241cc75: Pull complete 74d1c0702786: Pull complete c66f3692932d: Pull complete 9224bd1b9757: Pull complete Digest: sha256:885fc831cb853700ded04029b4fa70ed502947042f6f154e432395cb35619d11 Status: Downloaded newer image for i2tch/docker:unsigned docker.io/i2tch/docker:unsigned root@debian9:~# docker image ls REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu latest 775349758637 9 days ago 64.2MB nginx latest 540a289bab6c 2 weeks ago 126MB alpine latest 965ea09ff2eb 2 weeks ago 5.55MB mysql latest c8ee894bd2bd 3 weeks ago 456MB centos latest 0f3e07c0138f 5 weeks ago 220MB i2tch/docker unsigned 9b915a241e29 3 years ago 212MB root@debian9:~# docker rmi i2tch/docker:unsigned Untagged: i2tch/docker:unsigned Untagged: i2tch/docker@sha256:885fc831cb853700ded04029b4fa70ed502947042f6f154e432395cb35619d11 Deleted: sha256:9b915a241e29dc2767980445e3109412b1905b6f1617aea7098e7ac1e5837ae2 Deleted: sha256:27eb08aec7b41dbfa2fd49bc2b3fad9b020fe40b0bc8289af7f53770f0843e7d Deleted: sha256:7ad0aff4b88909fcff6372fdd26c24d688803b06845426b5a90bcd2f2cae93f4 Deleted: sha256:b93bcd594116ac8886f2daa0fc8d75a59da00161731dab24ababea853d031908 Deleted: sha256:54eda0a22e4b2a1b166cf996eb0651a4f53dec7e9dfad3549bbfe6078f2238a4 Deleted: sha256:36575f1e2764d54fdb92b5296cf4e993499836d6dd9a006f32e173865835070e Deleted: sha256:27074774f844bdeba18e786585604c8b6352e925a7bd560deb66252bc8ccb861 Deleted: sha256:0da68695f8bc66fcea8f09004b5cb078861f5d99748f8b7ed035690e02c41477 Deleted: sha256:5dbda9873cdda8ff912b0ae5c34790ee06d7117fa27b193610fa2f7063bf55ff Deleted: sha256:149690c37bdc8680ec66b0e2cc138f6d63caad74b091acf86a2a18111b90ea79 Deleted: sha256:2caf8a80130d6e9f4ed22e1ec1c3abd2c3f4330d2df9ec62f3b751300190b9e4 Deleted: sha256:1445a9131f2b28a12ff6396faebd6b4beb2cccd7af8eae28d5ff659d65de03ad Deleted: sha256:4d9799a0754804f5cd623ab744757d16ec81862ee6e5d6986d9d1b0c5e5d5637 Deleted: sha256:dd833146402e8e6e67c48a6ae79a3c86101123e3d6ab1fc7999685eeea06ccba Deleted: sha256:08d8e6ed6c3a5ac1bfee00f7b11f0a870d6bdc4af6d34169fa1e032c241a63a6 Deleted: sha256:0f3637356bb908638dda037c9c6aa4a2be8a19dbcf452a00cd733a8a456077ac Deleted: sha256:aedb1b3b3b6e70ae4a342dfdcea874495b9d095ed6ba8eb4bc08f90ad9e83125 Deleted: sha256:05903cd969529ea56beec880bbeb7e90f1bdc281882f1cf3755760e41b181409 Deleted: sha256:d124781fc06a73b05a8644958397994bae668aba2f06f397fe1387c676b0d86f
8.3 - DCT et la commande docker push
Pour envoyer l'image dont l'IMAGE ID est 965ea09ff2eb dans le registry privé, le tag de l'image doit être modifié :
root@debian9:~# docker image tag alpine:latest <votre_compte>/docker:alpine
L'image dont l'IMAGE ID est 965ea09ff2eb a maintenant deux tags alpine:latest et <votre_compte>/docker:alpine :
root@debian9:~# docker image ls REPOSITORY TAG IMAGE ID CREATED SIZE ubuntu latest 775349758637 9 days ago 64.2MB nginx latest 540a289bab6c 2 weeks ago 126MB <votre_compte>/docker alpine 965ea09ff2eb 2 weeks ago 5.55MB alpine latest 965ea09ff2eb 2 weeks ago 5.55MB mysql latest c8ee894bd2bd 3 weeks ago 456MB centos latest 0f3e07c0138f 5 weeks ago 220MB
Lors du push vers le registry privé, il faut créer des passphrases pour deux clefs :
- la root key aussi connue sous le nom offline key (ID 192fc7e), qui est uniquement demandée la première fois après la mise en place de DCT lors de la création d'un repositry,
- la repository key aussi connue sous le nom tagging key (ID 168c754), utilisée pour signer l'image en y apposant un tag. La signature est spécifique au repositry.
root@debian9:~# docker push <votre_compte>/docker:alpine The push refers to repository [docker.io/<votre_compte>/docker] 77cae8ab23bf: Mounted from library/alpine alpine: digest: sha256:e4355b66995c96b4b468159fc5c7e3540fcef961189ca13fee877798649f531a size: 528 Signing and pushing trust metadata You are about to create a new root signing key passphrase. This passphrase will be used to protect the most sensitive key in your signing system. Please choose a long, complex passphrase and be careful to keep the password and the key file itself secure and backed up. It is highly recommended that you use a password manager to generate the passphrase and keep it safe. There will be no way to recover this key. You can find the key in your config directory. Enter passphrase for new root key with ID 192fc7e: fenestros Repeat passphrase for new root key with ID 192fc7e: fenestros Enter passphrase for new repository key with ID 168c754: fenestros Repeat passphrase for new repository key with ID 168c754: fenestros Finished initializing "docker.io/<votre_compte>/docker" Successfully signed docker.io/<votre_compte>/docker:alpine
Les clefs sont stockées dans le répertoire ~/.docker/trust/private :
root@debian9:~# ls -l ~/.docker/trust total 8 drwx------ 2 root root 4096 nov. 10 14:49 private drwx------ 3 root root 4096 nov. 8 13:48 tuf root@debian9:~# ls -l ~/.docker/trust/private total 8 -rw------- 1 root root 447 nov. 10 14:49 168c754ea8f36ce7fbcbe2299b6d91fc0f4d594c9ed9b86916687b618d8438ac.key -rw------- 1 root root 416 nov. 10 14:49 192fc7ed9543ad4bceec58886ab1d605b7433c35f7462d7343d0780d8fddf1db.key root@debian9:~# cat ~/.docker/trust/private/168c754ea8f36ce7fbcbe2299b6d91fc0f4d594c9ed9b86916687b618d8438ac.key -----BEGIN ENCRYPTED PRIVATE KEY----- gun: docker.io/i2tch/docker role: targets MIHuMEkGCSqGSIb3DQEFDTA8MBsGCSqGSIb3DQEFDDAOBAhm7HwR0y8FFAICCAAw HQYJYIZIAWUDBAEqBBC729tU73wKHFQSbmZ1EVZaBIGgmGiFSs4lM5tElSGukl1B HrELT9aFooFgW7oSXNLM8aFfF/vJ+BSjsgfqWLdvuH+DUXXdUidxcoGMEWnVZNIC 3m40g3MywHilW4rUcjoHVTTUXABGXUQ3f7h+nI15CXcZ11qRLyWbf2uywE9yYH9O M7GLUcE+pTENJKfZAhRGBEL+LgXNfGI1aAVqaEbBDcDnKKf4Uj1Xu4oLJ7je8+nT dg== -----END ENCRYPTED PRIVATE KEY----- root@debian9:~# cat ~/.docker/trust/private/192fc7ed9543ad4bceec58886ab1d605b7433c35f7462d7343d0780d8fddf1db.key -----BEGIN ENCRYPTED PRIVATE KEY----- role: root MIHuMEkGCSqGSIb3DQEFDTA8MBsGCSqGSIb3DQEFDDAOBAiAtCzEar3AhgICCAAw HQYJYIZIAWUDBAEqBBAO7hHWVoqOo6xcETQQDXRdBIGgPUoLzTz07Ajx8K3D8+Vv 2NUiflMYhH/0I9PL6iA2JJCmD0l+8Ueljy+vHRCu7UAIyWXyIHFN5Aab40mk9/Pg V2BwSlXp7t1Cnqp/ah7g0T40+OnT64JkTS+l3cS0CaCf2E4l6nY8g4cl40hZIFJz KREO8uEq3v7HcSBBqFm0+TU+92d7hVuDApPaj0lZYP+3f7H6AjUOqu6hUoK8Ck/Y Ig== -----END ENCRYPTED PRIVATE KEY-----
8.4 - DCT et la commande docker build
L'exemple suivant démontre un Dockerfile qui référence une image parente non signée :
root@debian9:~# mkdir nottrusted root@debian9:~# cd nottrusted/ root@debian9:~/nottrusted# vi Dockerfile root@debian9:~/nottrusted# cat Dockerfile FROM docker/trusttest:latest RUN echo
Lors du build de l'image <votre_compte>/docker:nottrusted qui utilise ce Dockerfile, une erreur est retournée car sa création n'est pas conforme à l'utilisation de DCT :
root@debian9:~/nottrusted# docker build -t <votre_compte>/docker:nottrusted . Sending build context to Docker daemon error during connect: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.40/build?buildargs=%7B%7D&cachefrom=%5B%5D&cgroupparent=&cpuperiod=0&cpuquota=0&cpusetcpus=&cpusetmems=&cpushares=0&dockerfile=Dockerfile&labels=%7B%7D&memory=0&memswap=0&networkmode=default&rm=1&shmsize=0&t=i2tch%2Fdocker%3Anottrusted&target=&ulimits=null&version=1: Error: remote trust data does not exist for docker.io/docker/trusttest: notary.docker.io does not have trust data for docker.io/docker/trusttest
L'utilisation de l'option –disable-content-trust permet la construction de l'image <votre_compte>/docker:nottrusted :
root@debian9:~/nottrusted# docker build --disable-content-trust -t <votre_compte>/docker:nottrusted . Sending build context to Docker daemon 2.048kB Step 1/2 : FROM docker/trusttest:latest latest: Pulling from docker/trusttest Image docker.io/docker/trusttest:latest uses outdated schema1 manifest format. Please upgrade to a schema2 image for better future compatibility. More information at https://docs.docker.com/registry/spec/deprecated-schema-v1/ aac0c133338d: Pull complete a3ed95caeb02: Pull complete Digest: sha256:50c0cdd0577cc7ab7c78e73a0a89650b222f6ce2b87d10130ecff055981b702f Status: Downloaded newer image for docker/trusttest:latest ---> cc7629d1331a Step 2/2 : RUN echo ---> Running in 694e79d3cd88 Removing intermediate container 694e79d3cd88 ---> 686e85ee76b8 Successfully built 686e85ee76b8 Successfully tagged <votre_compte>/docker:nottrusted
Lors du push de l'image <votre_compte>/docker:nottrusted vers le repositry distant, celle-ci est signée :
root@debian9:~/nottrusted# docker push <votre_compte>/docker:nottrusted The push refers to repository [docker.io/<votre_compte>/docker] 5f70bf18a086: Layer already exists c22f7bc058a9: Mounted from docker/trusttest nottrusted: digest: sha256:1183c62a5d31e202b5f5f528e9e7cdc36140aa3212c938e1d471c6b3b59f01bc size: 734 Signing and pushing trust metadata Enter passphrase for repository key with ID 168c754: fenestros Successfully signed docker.io/<votre_compte>/docker:nottrusted
Important : Notez l'utilisation de la même root key que lors du push de l'image <votre_compte>/docker:alpine car il s'agit du même repositry.
Créer un deuxième Repositry
Par contre en modifiant le tag de l'image <votre_compte>/docker:nottrusted à <votre_compte>/otherimage:latest, un autre repositry sera créé lors du push de l'image renommée :
root@debian9:~/nottrusted# docker tag <votre_compte>/docker:nottrusted <votre_compte>/otherimage:latest root@debian9:~/nottrusted# docker images REPOSITORY TAG IMAGE ID CREATED SIZE <votre_compte>/docker nottrusted 686e85ee76b8 9 minutes ago 5.03MB <votre_compte>/otherimage latest 686e85ee76b8 9 minutes ago 5.03MB ubuntu latest 775349758637 9 days ago 64.2MB nginx latest 540a289bab6c 2 weeks ago 126MB <votre_compte>/docker alpine 965ea09ff2eb 2 weeks ago 5.55MB alpine latest 965ea09ff2eb 2 weeks ago 5.55MB mysql latest c8ee894bd2bd 3 weeks ago 456MB centos latest 0f3e07c0138f 5 weeks ago 220MB docker/trusttest latest cc7629d1331a 4 years ago 5.03MB root@debian9:~/nottrusted# docker push docker.io/<votre_compte>/otherimage:latest The push refers to repository [docker.io/<votre_compte>/otherimage] 5f70bf18a086: Mounted from <votre_compte>/docker c22f7bc058a9: Mounted from <votre_compte>/docker latest: digest: sha256:1183c62a5d31e202b5f5f528e9e7cdc36140aa3212c938e1d471c6b3b59f01bc size: 734 Signing and pushing trust metadata Enter passphrase for root key with ID 192fc7e: fenestros Enter passphrase for new repository key with ID 7b13d02: fenestros Repeat passphrase for new repository key with ID 7b13d02: fenestros Finished initializing "docker.io/<votre_compte>/otherimage" Successfully signed docker.io/<votre_compte>/otherimage:latest
Important : Notez la création d'une deuxième repositry key (ID 7b13d02 au lieu de ID 168c754) lors du push de l'image <votre_compte>/otherimage:latest car il s'agit d'un autre repositry.
La présence de cette deuxième repositry key (7b13d02d74264624fb201e7ae13ae694286b9f761aa86adddefd0408c7234a58.key) peut être constatée dans le répertoire ~/.docker/trust/private :
root@debian9:~/nottrusted# ls -l ~/.docker/trust/private total 12 -rw------- 1 root root 447 nov. 10 14:49 168c754ea8f36ce7fbcbe2299b6d91fc0f4d594c9ed9b86916687b618d8438ac.key -rw------- 1 root root 416 nov. 10 14:49 192fc7ed9543ad4bceec58886ab1d605b7433c35f7462d7343d0780d8fddf1db.key -rw------- 1 root root 451 nov. 10 17:37 7b13d02d74264624fb201e7ae13ae694286b9f761aa86adddefd0408c7234a58.key
En inspectant les clefs des images créées, l'utilisation des différentes clefs est démontrées très clairement :
root@debian9:~/nottrusted# docker trust inspect <votre_compte>/docker:alpine
[
{
"Name": "<votre_compte>/docker:alpine",
"SignedTags": [
{
"SignedTag": "alpine",
"Digest": "e4355b66995c96b4b468159fc5c7e3540fcef961189ca13fee877798649f531a",
"Signers": [
"Repo Admin"
]
}
],
"Signers": [],
"AdministrativeKeys": [
{
"Name": "Root",
"Keys": [
{
"ID": "d4074334a4ff5a9a43ebd1320ad77c2df88c990ec812f90eb045c603c01ab698"
}
]
},
{
"Name": "Repository",
"Keys": [
{
"ID": "168c754ea8f36ce7fbcbe2299b6d91fc0f4d594c9ed9b86916687b618d8438ac"
}
]
}
]
}
]
root@debian9:~/nottrusted# docker trust inspect <votre_compte>/docker:nottrusted
[
{
"Name": "<votre_compte>/docker:nottrusted",
"SignedTags": [
{
"SignedTag": "nottrusted",
"Digest": "1183c62a5d31e202b5f5f528e9e7cdc36140aa3212c938e1d471c6b3b59f01bc",
"Signers": [
"Repo Admin"
]
}
],
"Signers": [],
"AdministrativeKeys": [
{
"Name": "Root",
"Keys": [
{
"ID": "d4074334a4ff5a9a43ebd1320ad77c2df88c990ec812f90eb045c603c01ab698"
}
]
},
{
"Name": "Repository",
"Keys": [
{
"ID": "168c754ea8f36ce7fbcbe2299b6d91fc0f4d594c9ed9b86916687b618d8438ac"
}
]
}
]
}
]
Important : Notez que les clefs utilisées sont les mêmes pour les deux images.
root@debian9:~/nottrusted# docker trust inspect <votre_compte>/otherimage:latest
[
{
"Name": "<votre_compte>/otherimage:latest",
"SignedTags": [
{
"SignedTag": "latest",
"Digest": "1183c62a5d31e202b5f5f528e9e7cdc36140aa3212c938e1d471c6b3b59f01bc",
"Signers": [
"Repo Admin"
]
}
],
"Signers": [],
"AdministrativeKeys": [
{
"Name": "Root",
"Keys": [
{
"ID": "26f00698f51be2824c6fe85a14722c279bbd487125fe8fa18c0fc8f76dd6280d"
}
]
},
{
"Name": "Repository",
"Keys": [
{
"ID": "7b13d02d74264624fb201e7ae13ae694286b9f761aa86adddefd0408c7234a58"
}
]
}
]
}
]
Important : Notez que les clefs utilisées sont différentes.
Supprimer une Signature
Dernièrement il est possible de supprimer la signature d'une image avec la commande docker trust revoke :
root@debian9:~# docker trust revoke <votre_compte>/docker:alpine
Enter passphrase for repository key with ID 168c754:
Successfully deleted signature for <votre_compte>/docker:alpine
root@debian9:~# docker trust inspect <votre_compte>/docker:alpine
[
{
"Name": "<votre_compte>/docker:alpine",
"SignedTags": [],
"Signers": [],
"AdministrativeKeys": [
{
"Name": "Root",
"Keys": [
{
"ID": "d4074334a4ff5a9a43ebd1320ad77c2df88c990ec812f90eb045c603c01ab698"
}
]
},
{
"Name": "Repository",
"Keys": [
{
"ID": "168c754ea8f36ce7fbcbe2299b6d91fc0f4d594c9ed9b86916687b618d8438ac"
}
]
}
]
}
]
Copyright © 2025 Hugh NORRIS