Introduction

In June 2017, a cyber storm named NotPetya shook the digital world, using Docker containers to wreak havoc globally. Think of it like a sneaky villain—posing as ransomware but with a twist. It encrypted files and messed with systems across 60 countries, making recovery impossible, even if you paid the ransom. How did it do that? By exploiting a weakness in Docker containers, those handy tools DevOps engineers use.

Why does this matter for DevOps? Well, it’s like guarding your fort. NotPetya showed that our fort (containers) had a crack. DevOps engineers need to know this because they’re the defenders, the guardians of smooth operations. Let’s understand Docker’s weak spots and why it is crucial for DevOps superheroes to mitigate container-related vulnerabilities.

Major Threats

The major threats can be classified as follows:

1. Network Services:

– Example: Exploiting an exposed SSH service on a Docker container.

 docker run -p 2222:22 -d vulnerable-container
     ssh -p 2222 user@localhost  # Attacker gains unauthorized access

2. Protocol Flaws:

– Example: Intercepting Docker API communication.

# Capture Docker API requests
     tcpdump -i eth0 port 2375 -w captured_traffic.pcap

3. Kernel Exploits:

– Example: Using a kernel exploit within a container.

FROM vulnerable-base-image
     COPY malicious_code /usr/local/bin/
     CMD ["malicious_code"]

4. Network Management Backplane:

– Example: Exploiting Kubernetes API vulnerabilities.

kubectl expose deployment vulnerable-deployment --port=80 --target-port=8080

5. Container Escape:

– Example: Breaking out of a container and gaining control over the host.

 docker run -it --privileged --pid=host alpine sh

6. Other Containers via Network:

– Example: Attacking another container through the network.

docker exec -it attacker-container nc -zv target-container 80

7. Attacking Orchestration Tool via Network:

– Example: Exploiting a vulnerability in Kubernetes.

kubectl exec -it attacker-pod -- /bin/sh

8. Attacking the Host via Network:

– Example: Exploiting an open port on the host from within a Docker container.

docker run -it --rm -p 8000:8000 --name attacker-container attacker-image
     nc -zv host-machine 8000  # Attacker attempts unauthorized access

These were some examples of the threats. Let’s now look at some popular CVEs.

CVE-2021-41092: A problem in Docker CLI was discovered when logging into a private registry with a misconfigured config file. If the file listed something that couldn’t run correctly, the login details would mistakenly go to a different registry (registry-1.docker.io) instead of the intended private one.

CVE-2020-35467: The Docker Docs Docker image through 2020-12-14 contains a blank password for the root user. Systems deployed using affected versions of the Docker Docs container may allow a remote attacker to achieve root access with a blank password.

CVE-2019-5736: It is a critical security flaw in container runtimes like Docker. It lets attackers overwrite a crucial program, potentially giving them control over the entire system. This could lead to unauthorized access and malicious activities.

CVE-2021-21285: In Docker, before version 20.10.3, there was a vulnerability in which pulling an intentionally malformed Docker image manifest crashes the dockerd daemon by utilizing resources. 

Now, since we are serious about the threats, let’s see how we can mitigate these threats.

Risk Mitigation

1. User Mapping Safeguard: Enhancing Docker Security

Running applications as the almighty “root” user can be risky. If attackers manage to break free from your application, they might carry all the powerful privileges with them. To avoid this, it’s smart to run your microservices with the least power possible.

Here’s how you can secure user mapping:

1. Avoid The ‘–privileged’ Flag:

– When starting a Docker container, avoid using the ‘–privileged’ flag. This flag gives the container almost all the same privileges as the host system, and that’s not what we want for security.

 docker run --privileged -it my-container  # Avoid using --privileged

2. Configure User IDs Properly:

– Set up the right parameters for user IDs. This means that instead of running everything as “root,” give specific users the exact permissions they need.

FROM ubuntu
   RUN groupadd -r mygroup && useradd -r -g mygroup myuser
   USER myuser

3. Use Linux User Namespaces:

– Linux user namespaces help by isolating user and group IDs inside the container from the host. This adds an extra layer of security.

docker run --userns=host -it my-container  # Use Linux user namespaces

By following these steps, you make it harder for attackers to wreak havoc even if they manage to escape your container. Always aim for the least privilege to keep your Dockerized applications safe and sound.

2. Patch Management Strategy: Guarding Against Sneaky Exploits in Docker

In the world of Docker, keeping things up-to-date is like putting on armor to protect against potential attacks. Let’s break down a smart patch management strategy to keep your Docker fortress secure.

1. Patch Often and Automate:

– Regularly update your host, Docker technology, and any tools you use. Automation is your superhero here—it ensures updates happen without you having to manually intervene.

 sudo apt-get update && sudo apt-get upgrade -y  # Regularly update the host
   docker pull my-image:latest  # Keep Docker images up-to-date

2. Specify a Time Span for Regular Updates:

– Pick a timeframe for updates, like once a week or once a month. Regularity is key so potential vulnerabilities are fixed promptly.

3. Create Policies or Processes:

– Establish clear rules for updating different parts of your Docker setup. This could include the host, Docker itself, or any additional tools you’ve added.

# Example of updating Docker
   docker-compose pull  # Keep Docker Compose files updated

By having a solid patch management strategy, you’re essentially fortifying your Docker setup against potential security threats. Stay vigilant and update regularly, and your Dockerized applications will stand strong against any lurking vulnerabilities.

3. Firewall Strategies and Network Isolation: Defending Your Infrastructure

Network segmentation and firewalling are critical components in defending your container infrastructure against potential vulnerabilities. Implementing robust practices in this area is essential for maintaining a secure containerized environment.

1. Container Isolation:

– Ensure containers are isolated in separate networks.

docker network create tenant1
docker run --network=tenant1 my-container-1

2. Define Communication:

– Clearly define and restrict communication pathways.

# Docker Compose Example
services:
  web:
    networks:
      - tenant1

3.  Prevent Exposure of Management Interfaces:

– Shield management interfaces from the internet.

# Example with iptables
iptables -A INPUT -p tcp --dport 8080 -j DROP

4. Inbound and  Outbound Network Policy:

– Define inbound network policies for orchestrated environments and implement outbound network policies to restrict internet downloads.

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy

4. Secure Defaults and Hardening

Boosting the security of your Docker containers is paramount, and it starts with setting secure defaults and adopting robust hardening practices. Follow these guidelines across different layers to effectively reduce potential vulnerabilities and reinforce the overall resilience of your containerized infrastructure:

1.  Orchestration and Host Levels:

– Identify and disable unnecessary services, such as dashboard, etcd, and API, at both orchestration and host levels.

# Example: Disable OpenSSHD on the host
systemctl stop sshd
systemctl disable sshd

– Review services to assess their impact, configure authentication following the principle of least privilege, and narrow down access through appropriate configurations.

# Example: Restrict access to a service
iptables -A INPUT -p tcp --dport 8080 -s trusted-ip -j ACCEPT
iptables -A INPUT -p tcp --dport 8080 -j DROP

2. Container Level:

– Uninstall unnecessary packages within the container to minimize the attack surface.

# Example: Uninstall a package for alpine linux
apk del package-name

– Review syscalls for potential security issues affecting the host kernel.

# Example: Check syscalls using strace
strace -p <pid>

5.  Maintain a Different Environment

Preserving distinct security contexts is crucial for safeguarding containerized environments. By isolating production containers, separating sensitive data, and strategically placing critical components on different hosts, you establish tailored security measures. This proactive approach minimizes risks and ensures the integrity of systems across various developmental stages.

Isolate Production Containers:

  • Deploy production containers on dedicated host systems with restricted access, minimizing the risk of unauthorized interference.
  • Identify sensitive data types that demand extra protection and isolate containers accordingly, enhancing data security.

6. Protecting Microservice Access: Safeguarding Secrets

1. Encrypt Sensitive Information:

– Utilize strong encryption methods to secure passwords, tokens, private keys, and certificates.

encrypted_password = encrypt(pass)   # Example using cryptography library

2. Secure Storage Solutions:

– Employ secure storage mechanisms to protect sensitive data from unauthorized access.

# Store secrets securely using environment variables
export SECRET_KEY=mysecret

7.  Resource Protection: Safeguarding Container Resources

Safeguard container resources by limiting memory and CPU usage. Containers share physical resources, necessitating precautions to prevent one container from impacting others. By setting precise limits, resource protection ensures fair distribution and prevents disruptions, maintaining stability in containerized environments.

1. Memory Limitation:

– Restrict the amount of memory a container can use to prevent resource monopolization.

docker run --memory 512m my-container

2. CPU Limitation:

– Control the amount of CPU a container can utilize to maintain fair resource distribution.

docker run --cpus 0.5 my-container

8. Container Image Integrity and Origin: Ensuring Trustworthy Foundations

When selecting the operating system for your code’s container, opt for a minimal OS from a reputable source. Enhance security by routinely scanning and monitoring all transfers and stored images. This practice ensures the integrity and origin of your container images, minimizing potential vulnerabilities and ensuring a trustworthy foundation.

Opt for a minimal, trusted operating system for your code’s container.

FROM alpine:latest         # Example using Alpine Linux

9. Read-Only Mode: Immutability

Launch containers in read-only mode, mitigating the risk of unauthorized write operations. This additional security layer reinforces the integrity of deployed containers and minimizes potential vulnerabilities.

# Start container in read-only mode
docker run --read-only my-container

10. Logging: Tracking Security Events

For a secure containerized environment, log key security events in container images, orchestration tools, and hosts; include system and API-level details. Also, enable remote logging in your application for comprehensive activity tracking and effective incident response.

Remote Logging in Application:

– Enable remote logging in your application for seamless tracking of activity.

# Example using Python's logging module for remote logging
import logging
logging.basicConfig(filename='remote_log.txt', level=logging.INFO)

11.  Avoid Excessive Permission

Containers should run with the least privilege necessary. If a container gains excessive permissions, an attacker might exploit this to gain unauthorized access to the host system or other containers.

For example in Dockerfile:

– Avoid executable permission to directory like /usr /etc /bin.

FROM nginx:latest
EXPOSE 80 
# Incorrectly set excessive permissions on a system directory 
RUN chmod -R 777 /usr # incorrectly set excessive permissions on a system directory

12. Checking Vulnerabilities with 3rd party apps like Snyk and Scout

Tools like Snyk and Scout simplify container security by scanning for vulnerabilities in third-party dependencies. They examine container images for known security issues, providing concise reports and suggestions for mitigation. These user-friendly tools integrate seamlessly into the development workflow, offering actionable insights during continuous integration and deployment. By leveraging Snyk and Scout, teams can promptly identify and address vulnerabilities, enhancing the overall security posture of containerized applications with minimal complexity.

#Install Snyk from the Link

Here is an example of node:16 docker image

docker pull node:16
snyk test --docker node:16

Sysdig’s findings are based on telemetry gathered from thousands of its customers’ cloud accounts, amounting to billions of containers. The high percentage of critical or high-severity vulnerabilities revealed that 87% of container images used in production have serious security issues, up from 75% last year.

These vulnerabilities pose a risk to the safety of software. The report suggests that even though fixes are available for most of these issues, only 15% are applied when needed. This shows a need for better security practices and faster application of fixes in the rush to use modern cloud technology. It’s essential to manage these vulnerabilities carefully to keep our software and data safe.

Sysdig’s findings are based on telemetry gathered from thousands of its customers’ cloud accounts, amounting to billions of containers. The high percentage of critical or high-severity vulnerabilities in containers.

Conclusion

As we wrap up this journey through the realms of Docker security, remember that safeguarding your containers is not just about setting up walls but about strategic defence. By implementing robust network segmentation, vigilant patch management, and a keen eye on container vulnerabilities, you’re laying the groundwork for a secure Docker kingdom.

At CloudZenia, we have years of experience and over 100 Docker secure customers; we understand the intricate dance of clouds, and Docker is no exception. Our expertise extends beyond the clouds, ensuring that your journey through the digital skies is not only secure but also seamless.

So, whether you’re a seasoned cloud voyager or just setting sail, let CloudZenia be your guiding star. As we say in the world of clouds, may your containers sail smoothly and your skies remain clear.

Safe travels and secure Dockering!

Contact CloudZenia for all your cloud endeavours. We’re not just experts, we’re your trusted allies in the ever-expanding digital horizon.

Jan 08, 2024