setcap-static
is a statically linked trimmed down version of setcap(8). It sets the capabilities of the given filename to the capabilities specified.
KubeSec security guidelines suggest that the running image should be "run as a non-root user to ensure the least privilege." However, if the containerized application needs some root
privileges (like binding to a port less than 1024) and runs in a scratch
image, this will not be straightforward.
The issue is that Docker's COPY
command does not preserve the extended attributes; therefore, you cannot do something like this:
FROM alpine:3.13 as build
# ...
RUN \
apk add --no-cache libcap \
&& setcap 'cap_net_bind_service=+ep' my-cool-application \
&& apk del --no-cache libcap
# ...
FROM scratch
COPY --from=build /path/to/my-cool-application /my-cool-application
In the target image, my-cool-application
will not have the capabilities set in the build
image. Therefore, if you need to grant some capabilities to your application, you have to do it in the target image. You cannot just copy setcap
from Alpine — because it is a dynamically linked executable (it depends on ld-musl, libcap, libc.musl).
Here comes libcap-static
. It is a lightweight version of libcap
: it can only set the capabilities on a file, it does not support all other options of libcap
.
Unlike libcap
, libcap-static
has an option to delete itself: this can be handy for scratch
images if you don't want to leave any other executables than your application visible to the user (or an attacker). If libcap-static
detects that the first two characters of argv[0]
are /!
, it will delete itself after the successful operation.
For example,
FROM scratch
COPY --from=wildwildangel/setcap-static /setcap-static /!setcap-static
COPY --from=build /build/build/tiny-ssh-honeypot /tiny-ssh-honeypot
RUN ["/!setcap-static", "cap_net_bind_service=+ep", "/tiny-ssh-honeypot"]
After granting the CAP_NET_BIND_SERVICE
capability to tiny-ssh-honeypot
, libcap-static
will delete itself.
Build dependencies:
- Alpine: cmake, make, libcap-dev, libcap-static
- Ubuntu: cmake, make, libcap-dev
cmake -S . -B build -DCMAKE_BUILD_TYPE=MinSizeRel
cmake --build build --config MinSizeRel
setcap-static capabilities filename
capabilities
is the list of capabilities in the form supported bycap_from_text(3)
(or bysetcap
)filename
is the name of the file to operate on; it must not refer to a symlink.