DEV Community

Agnes
Agnes

Posted on • Originally published at Medium

Best practices for Container Security

Introduction

Containerization has become a key feature in modern software development and deployment. The methodology of building, deploying and running our applications has greatly changed because of containerization. Cloud infrastructure platforms like Civo , Amazon web services, Digital Ocean, among others, greatly help with simplifying the process of containerizing our applications. In this article, we are going to explore some comprehensive guides to follow to ensure the security of your containers.

Prerequisites

  • Kubernetes cluster
  • Basic Kubernetes knowledge

1. Using Role-based Access control (RBAC) to enhance container security

RBAC is a powerful tool used to enhance security in Kubernetes clusters by using the roles and roles binding system. Roles are used to define the specific permissions that different users have, while roles binding refers to the assignment of different roles to different individuals or groups. Role bindings bind Kubernetes cluster users to different roles.

For instance, a role called developer, which allows users to deploy their different applications but restricts them from accessing other applications and resources, can be created. Role binding can then be used to assign the developer role to a group called developers All the users in the developers group would have the same access and permissions granted to the developer role.We create YAML files, where we define our RBAC rules. For example, we can have a YAML file called rbac-config.yaml with the following definitions:

apiVersion: rbac.authorization.k8s.io/v1  
kind: Role  
metadata:  
  name: my-role  
  namespace: my-namespace  
rules:  
apiGroups: [""]  
  resources: ["pods"]  
  verbs: ["get", "list", "create", "delete"]
Enter fullscreen mode Exit fullscreen mode

In the above YAML file, a Kubernetes Role named my-roleis defined within the namespace. It means that accounts within the role have been granted the permission to get list create and deletepods in the named namespace.

Some of the ways Cloud service providers enhance container security through RBAC include:

a. Auditing user activity _
Cloud service providers Kubernetes RBAC can audit user activities within the Kubernetes. This information can be used to investigate and identify any suspicious behavior within the containerized application.

b. Preventing unauthorized changes

Cloud service providers Kubernetes RBAC prevents unauthorized access to different resources by allowing the creation of roles that can sometimes be set to read-only mode. Since the users are able to view the said resources and not edit, there are minimum chances of human error, hence preventing any security threats to the containerized application.

c. Limiting user access to different resources

Cloud service providers Kubernetes RBAC allows the creation and definition of custom roles that define different permissions for users. It ensures that some of the resources have limited access since users are only granted permissions to the resources they need to complete their tasks effectively. It, in turn, helps avert unnecessary security threats.

d. Least privilege principle
It is one of the most reliable methods of container security. Here, users are only granted permissions they need to complete their assigned tasks effectively, and not more. It goes a long way in minimizing any possible security threats due to unauthorized access.

2. Monitoring and Logging

Both monitoring and logging are key aspects in ensuring containers are protected against cyber threats. Monitoring refers to the ability to collect and analyze crucial container information, such as memory usage, network traffic and CPU usage. Monitoring of this crucial container information makes it easier to be able to identify and avoid any possible security threats. Logging, on the other hand, refers to the collection and storage of your container information. The combination of both monitoring and logging makes it easier for one to identify and curb any potential security threats more easily and efficiently. Some of the third party tools that help with logging and monitoring include Prometheus for logging , Grafana for monitoring , Fluentd and Elasticsearch for logging.

To enhance your security, you can also configure alerts in Prometheus and Grafana to notify you of any security breach and suspicious activity within your cluster.

Below are some of the ways Cloud service providers ensure container monitoring and logging is efficient :

a. Container metrics
When you containerize your applications , a number of container metrics such as CPU usage, network traffic and memory usage are collected. Users can examine these metrics to try and identify any suspicious activities, hence curbing or identifying any potential security threat.

b. Container logs
Cloud service providers are able to store logs from your containerized applications using third-party tools like Elasticsearch and Kibana, which makes it easy and efficient for users to pinpoint the exact cause of different problems encountered and also know how to fix them.

c. Container alerts

By creating alerts using third-party tools like Grafana and Prometheus, users can get notified on time in case of any suspicious behaviour, hence curbing and rectifying any possible security threats.

Benefits of proactive alerts

  • Reduced downtime By quickly responding and addressing the alerts sent, you are able to reduce or entirely prevent any possible downtime that might have affected your containerized application otherwise.
  • Early security threats

    Because users get notified almost immediately after suspicious activities in their containerized containers, they are able to quickly respond to possible security threats, hence averting any crisis.

  • Efficient incident response
    Alerts enable a more improved and efficient incident response. Because most of these alerts are based on container logs, experts are able to troubleshoot and fix specific issues based on the notifications.

3. secret management

Secrets refer to sensitive data such as API keys and tokens, among others, which are used to authorize and gain access to resources, as well as containerized applications. If your container secrets are compromised, sensitive data and information from your containerized application could be accessed, which could cause a lot of damage.

Most Cloud service providers offer a couple of ways in which the unauthorized access of these secrets could be curbed.

a. Secrets’ encryption

Most cloud service providers allow the encryption of secrets both at rest and in transit, which prompts users to enter an encryption key whenever they want to access them. Users without the encryption key are denied access, hence securing the secrets against unauthorized access.

b. Auditing

Cloud service providers secure secret management solutions audit all secrets’ access and use the information collected to investigate any suspicious access. It helps experts quickly troubleshoot any arising issues.

c. Secrets’ access control

Because Cloud service providers allow the creation of different user roles, you can give access to your secrets to just a few roles. It helps in preventing just anyone from accessing these secrets, which could later on lead to security threats.

We are going to have a sample YAML file to define our secrets. Create a secrets.yaml file and have the sample configuration below:

apiVersion: v1  
kind: Secret  
metadata:  
  name: my-secrets  
  namespace: my-namespace  
type: Opaque  
data:  
  username: <base64-encoded-username>  
  password: <base64-encoded-password>
Enter fullscreen mode Exit fullscreen mode

PS: Note that base64-encoded-username and base64-encoded-password should be replaced with your actual username and password values encoded in base64 format.

C. Application deployment _
During the deployment of your application to your Kubernetes cluster, you need to reference your secrets configuration in the YAML shown below:

apiVersion: apps/v1  
kind: Deployment  
metadata:  
  name: my-app  
  namespace: my-namespace  
spec:  
  replicas: 1  
  template:  
    spec:  
      containers:  
        - name: my-app-container  
          image: my-app-image  
          env:  
            - name: USERNAME  
              valueFrom:  
                secretKeyRef:  
                  name: my-secrets  
                  key: username  
            - name: PASSWORD  
              valueFrom:  
                secretKeyRef:  
                  name: my-secrets  
                  key: password
Enter fullscreen mode Exit fullscreen mode

Note that you should replacemy-app-imagewith your actual container image and also configure your environment variables as needed.

In your application code, you are going to be able to securely access your secrets from the /etc/secrets directory in your container.

By making use of RBAC rules, you can ensure that only authorized people can access the secrets.

We can conclude that Cloud service providers secure secret management solutions help curb security threats by:

  • Reducing the risk of a data breach through encryption.
  • Preventing unauthorized access through secrets’ access control.

4. Container firewall for network security

Container firewall is an extremely important tool for container security. Container firewall enables you to control traffic going in and out of your containerized application. Container firewall can be easily integrated into your Kubernetes cluster. It, in turn, helps protect your application from unauthorized access.

Some of the features provided by Cloud service providers to enhance container firewall security include:

  • Denial-of-Service(DoS) protection_** By limiting the amount of traffic that can be sent to your containerized application, Container firewall is able to reduce the chances of a DoS attack. It ensures that there is a reduced chance of your application being unavailable.
  • Log management Container firewall logs all incoming and outgoing traffic from your containerized application. It makes it easier to identify and manage any suspicious activities.
  • Intrusion detection and prevention(IDS/IDP)
    By monitoring traffic from already identified or known cyber attack signatures, Container firewall can help manage and reduce the threat of malicious access to your containerized application by blocking this traffic.

  • Rule-based filtering
    By enabling the creation of rules that manage both outgoing and incoming traffic, Cloud service provider container firewall gets the upper hand in detecting any malicious access to your containerized application. Some of the criteria used to define these rules include protocol , and IP address, among others.

In order to secure your network through container firewall for network security, you need to define what network traffic is allowed and which one is blocked. You can create a YAML file and have the sample configurations below:

apiVersion: civo.com/v1  
kind: Firewall  
metadata:  
  name: my-firewall-rules  
  clusterName: my-cluster-name  
spec:  
  rules:  
  - name: Allow HTTP  
    protocol: tcp  
    port: 80  
  - name: Allow HTTPS  
    protocol: tcp  
    port: 443  
  - name: Block All Other Incoming Traffic  
    protocol: all  
    action: drop
Enter fullscreen mode Exit fullscreen mode

The above configurations allow incoming HTTP and HTTPS traffic and then block out all the other incoming traffic.

Once done, apply the firewall configuration to your cluster .

We can then conclude that container firewall can help secure your container network security by:

  • Protecting against DoS attacks since traffic is controlled.
  • Protecting against malicious attacks by monitoring and blocking signatures from known or identified threats.
  • Protecting against unauthorized access by filtering incoming traffic.

5. Regular image updates

Users can rely on most cloud service providers to provide them with the ability to update their images using their API or CLI frequently. They also enable the scheduling of specific image updates, which it then does automatically, depending on the specified frequency. This regular image update goes a long way in ensuring that the images are up to date with the latest security patches, hence reducing the containerized applications’ vulnerabilities.By checking your container registry, you can identify which containers might use base images that have available new security updates. For every image that needs a security update, Update the image tag in your YAML file, depending on which image needs a security update, with the latest security fixes.

For instance, a YAML file named deployment.yaml has the following configuration :

spec:  
  containers:  
  - name: my-container  
    image: registry.example.com/my-image:latest
Enter fullscreen mode Exit fullscreen mode

The image field should be updated with the name of the new image tag.

The above changes should then be applied to your cluster .

6. Enhancing container images with multi-stage build

Image multi-stage build is extremely powerful when it comes to enhancing container security. Multi-stage build works by breaking down the container build process into multiple stages. It helps break the container images into smaller sizes by removing unnecessary dependencies. When the container images are in smaller sizes, they become less vulnerable to cyber attacks since the attack surface is reduced.

You can create multi-stage builds to enhance container security by following the steps below:

A.Docker installation

First, ensure that you have Docker installed by following the steps highlighted in its documentation here.

B.Dockerfile creation
After successfully installing Docker, create a Dockerfile for your application, where you will define the multi-stage build process for your container.

Below is an example of a Python Dockerfile :

FROM python:latest AS build  
RUN pip install --upgrade pip  
COPY requirements.txt .  
RUN pip install -r requirements.txt  
FROM python:latest  
COPY --from=build /dist .  
CMD ["python", "app.py"]
Enter fullscreen mode Exit fullscreen mode

The above Dockerfile defines two stages:

  • Python dependencies for the application are defined in the first stage.
  • The application files are copied from the first stage to the second stage, and the commands to run the applications are set.

The FROM keyword above specifies the latest image, which is used in the second stage. It helps to reduce the attack surface of the final image. A non-root user is also used in the second stage, which helps curb the application vulnerability by reducing the access privileges.

C.Building the Docker image

Next, run the command below to build the Docker image using a multi-stage build:

docker build -t my-app .
Enter fullscreen mode Exit fullscreen mode

Note that my-appshould be replaced with your actual image name.

Once the image build is finished, you can now deploy it to your Kubernetes cluster .

By using a multi-stage build for your images, you enhance security by:

  • Reducing your container attack surface since the final image contains only the necessary files required to run the application.
  • Reducing any chances of vulnerability attacks since the final image does not contain the source code.
  • Discarding the build environment after the build is complete, hence reducing the attack surface.

D. Container isolation

Container isolation plays a major role in enhancing security within your Kubernetes clusters. It is a fundamental security practice that ensures each container runs in its’ own separate environment, separated from other containers and its host system. The container isolation practice aids in preventing performance issues and malicious attacks.

Below are some of the techniques Cloud service providers employ for container isolation:

  • Resource limiting
    Resource limiting gives users the ability to control the resource specifications, for example, memory, disk space and CPU, per container. Because each container has its own specified resource specification, it needs help to hog the other containers’ resources or even impact their performance on the host system.

  • Namespaces
    Containers in different namespaces are prohibited from interacting with each other.

  • SecurityContext
    The SecurityContext technique allows users to have the ability to add an extra layer of security to their containers. Some of the additional security measures users can implement include group IDs or user IDs that the container will run as.

Additionally, Cloud service providers also provides additional features to enhance container isolation. Some of these features include :

  • Pod Security Policies (PSPs)
    PSPSs can be used to enhance techniques like resource limits and even SecurityContext by giving users the ability to define security policies for pods.

  • NetworkPolicy
    NetworkPolicy helps separate your applications from each other and also controls network traffic that flows to and from pods.

  • Audit Logging
    By studying this information and tracking the changes inside the Kubernetes clusters, experts can easily identify any suspicious activities.

Using the above information, users can use container isolation to secure their container applications by :

  • Using namespaces to isolate the different environments, that is, the development, staging and production environment. It will reduce the chances of human error in your container. For instance, accidental changes to the production environment will be curbed.

  • Using resource limiting to avoid affecting the performance of the rest of the containers and hindering their performance.

  • Using SecurityContext to prevent unauthorized access to your containers by setting up both user and group IDs. You can define the SecurityContextfor your container inside a deployment manifest.

Below is an instance of a deployment manifest:

apiVersion: v1  
kind: Pod  
metadata:  
  name: my-pod  
spec:  
  containers:  
  - name: my-container  
    image: your-image:tag  
    securityContext:  
      runAsUser: 1000   # Set the desired user ID here  
      runAsGroup: 1000  # Set the desired group ID here
Enter fullscreen mode Exit fullscreen mode

Replace the imagetag with the name of the actual image you want to run.

Ensure that you set both user and group IDs in the runAsGroupand runAsUser fields accordingly. These user IDs properly correspond to the users/groups that are supposed to run in your container.

Once done, apply the manifest to your Kubernetes cluster.

8. Training the team involved on best practices to adhere to for best container security.

Last but not least, you can train your team on ways the best practices to secure your containerized applications. Below are some tips on how to go about this:

  • Prepare the delivery in an engaging and captivating way. You could use presentations for the training.

  • Research and identify key security threats to your containers, for example, image vulnerabilities, unauthorized container access, and DoS attacks, among others.

  • Prepare training material that provides best practices and solutions to the identified security threats. Some of the best practices available are listed in this article.

  • Have regular security training for your team, that is, the developers, DevOps engineers, and system administrators. It is because the best practices for container security are constantly evolving.

In addition to the container security training for your team, it is also important to use security tools in your container, implement security policies and create an awareness culture within your team.

Conclusion

Securing your containers is an important practice to protect against cyber threats and attacks. You can ensure a robust structure for your containerized applications by following the above best security practices. It, in turn, ensures your application data confidentiality. Ensuring container security is a never-ending process, so it is important to remain watchful so that we can avert any imminent cyber attack.

By exploring third-party tools like Docker, you can get a lot of insights into general container security.

Top comments (0)