DMCA.com Protection Status Trending Topics About Devops: 2024

Sunday, 29 September 2024

Kubernetes Security : 6 Best Practices for 4C Security Model

 Kubernetes is the most popular orchestrator for deploying and scaling containerized applications in production. While Kubernetes makes it easy to start new workloads, this convenience comes at a cost: the system isn’t secure by default, so your clusters and users could be at risk.

Container attacks are on the rise and insecure Kubernetes installations are a magnet for attackers. Fortunately you can protect your clusters by adhering to a few best practices. You can run containers in production without security issues, if you consciously implement protections around your deployments.

Kubernetes Security Best Practices

These steps help harden your environment to minimize your attack surface and defend against incoming threats. Implementing them all will give you the greatest protection by restricting network activity, encrypting data at rest, and preventing vulnerable workloads from reaching your cluster.

  1. Use RBAC
  2. Protect the Control Plane
  3. Harden Your Nodes
  4. Add Network Security Policies
  5. Use Pod-Level Security Features
  6. Harden Your Workloads

You can also take a look at how Spacelift helps you manage the complexities and compliance challenges of using Kubernetes. Anything that can be run via kubectl can be run within a Spacelift stack. Find out more about how Spacelift works with Kubernetes, and get started on your journey by creating a free trial account.

1. Use RBAC

Role-Based Access Control (RBAC) is a built-in Kubernetes feature. It lets you control what individual users and service accounts can do by assigning them one or more roles. Each role allows a combination of actions, such as creating and listing Pods but not deleting them.

You should use RBAC to assign appropriate roles to each user and service account that interacts with your cluster. Developers may not need as many roles as operators and administrators, while CI/CD systems and Pod service accounts can be granted the bare minimum permissions needed to run their jobs.

RBAC protects your cluster if credentials are lost or stolen. An attacker who acquires a token for an account will be restricted to just the roles you’ve specifically assigned.

Roles must be as granular as possible to have the greatest security effect. Over-privileged roles, configured with too many permissions, are a risk because they grant attackers extra capabilities without providing any benefit to the legitimate user.

2. Protect the Control Plane

The Kubernetes control plane is responsible for managing all cluster-level operations. It exposes the API server, schedules new Pods onto Nodes, and stores the system’s current state. Breaching the control plane could give attackers control of your cluster.

Implementing these strategies will help lockdown the control plane and limit the effects of any compromise that occurs.

  1. Restrict access to etcd. Kubernetes uses etcd to store your cluster’s data. This includes credentials, certificates, and the values of ConfigMaps and Secrets you create. The central positioning of etcd makes it an attractive target for attackers. You should isolate access to it behind a firewall which only your Kubernetes components can reach through. You can achieve this by running etcd on a dedicated Node and using a network policy engine like Calico to enforce traffic rules.
  2. Enable etcd encryption. Data within etcd is not encrypted by default. This option can be turned on by specifying an encryption provider when you start the Kubernetes API server. If you’re using a managed Kubernetes service in the cloud, check with your provider to see if encryption is already active and whether you can enable it. Encryption will help protect the credentials, secrets, and other sensitive information within your cluster if the control plane is successfully compromised.
  3. Set up external API server authentication. The Kubernetes API server is usually configured with simple certificate-based authentication. This makes it challenging to configure and maintain large user cohorts. Integrating Kubernetes with your existing OAuth or LDAP provider tightens security by separating user management from the control plane itself. You can use your provider’s existing controls to block malicious authentication attempts and enforce login policies such as multi-factor authentication. Anonymous Kubelet authentication should be disabled too. This will block requests to Kubelet from sources other than the Kubernetes API server instance that it’s connected to. Set the --anonymous-auth=false flag when you start Kubelet if you’re maintaining your own cluster.

3. Harden Your Nodes


Don’t forget your Nodes when you’re securing your environment. Basic misconfiguration at the Node-level could compromise your entire cluster in a worst case scenario. Gaining access to a Node grants attackers privileged access to the Kubernetes API server through abuse of the Kubelet worker process that all Nodes run.

Securing Nodes used for Kubernetes is no different from protecting any other production server. You should monitor system logs regularly and keep the OS updated with new security patches, kernel revisions, and CPU microcode packages as they become available.

It’s best to dedicate your Nodes to Kubernetes. Avoid running other workloads directly on a Node, particularly network-exposed software, which could give attackers a foothold. Lockdown external access to sensitive protocols such as SSH.

4. Add Network Security Policies

Kubernetes defaults to allowing all Pods to communicate freely with each other. Compromising one Pod could let bad actors inspect its surroundings and then move laterally into other workloads. Breaching the Pod that serves your website allows an attacker to direct traffic straight to your database Pods, for example.

Kubernetes Network Policies defend against this risk by giving you precise control over the situations when Pods are allowed to communicate. You can specify at the Pod-level whether Ingress and Egress are allowed based on the other Pod’s identity, namespace, and IP address range. This lets you prevent access to sensitive services from containers that shouldn’t need to reach them.

Network policies are a Kubernetes resource type that you can apply to your cluster using YAML files. Here’s a simple example Policy that targets Pods with an app-component: database label:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: database-access
spec:
  podSelector:
    matchLabels:
      app-component: database
    policyTypes:
      - Ingress
    ingress:
      - from:
        - podSelector:
            matchLabels:
              app-component: api

This policy declares that incoming traffic to your database Pods can only originate from other Pods in the same namespace with the app-component: api label. Nefarious requests made from your frontend web server’s Pod labeled as app-component: frontend will be rejected at the network-level.

It’s possible to set up a default namespace-level network policy to guard against Pods being accidentally omitted from your rules. Using an empty podSelector field will apply the Policy to every Pod in the namespace:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: default-deny
  namespace: demo-namespace
spec:
  podSelector: {}
    policyTypes:
      - Ingress
      - Egress

This policy prevents both Ingress and Egress traffic to the namespace’s Pods, unless a more specific rule overrides it. You can block incoming or outbound traffic without affecting the other by changing the types listed under spec.policyTypes.

5. Use Pod-Level Security Features

Besides using networking policies to prevent unwanted traffic flows, Kubernetes has a few other Pod-level capabilities that protect your cluster and applications from vulnerabilities in each other.

All Pods should be assigned a security context that defines their privileges. You can use this mechanism to require that containers run with restricted Linux capabilities, avoid the use of HostPorts, and run with AppArmor, SELinux, and Seccomp enabled, among other controls. The security context can also define the user and group to run containers as:

apiVersion: v1
kind: Pod
metadata:
  name: nginx
spec:
  securityContext:
    runAsUser: 1000
    runAsNonRoot: true
    allowPrivilegeEscalation: false
    readOnlyRootFilesystem: true
  containers:
    - name: nginx
      image: nginx:latest

This security context makes containers in the Pod run as the user with UID 1000 while preventing privilege escalation. The runAsNonRoot: true declaration enforces that the container will run as a non-root user, while runAsUser: 1000 requires it to run with UID 1000. You can omit the UID and use runAsNonRoot alone in situations where it doesn’t matter which user runs the container, provided it’s not root.

The security context shown above also stipulates that containers will run with a read-only root filesystem. Setting securityContext.readOnlyRootFilesystem to true prevents workloads inside the container from writing to the container filesystem. It limits what attackers can achieve if the container is compromised as they’ll be unable to persist malicious binaries or tamper with existing files.

Security contexts can also be set at the container-level, as spec.containers[].securityContext, overriding any constraints set on their Pod. This allows you to further harden individual containers, or relax the rules for administrative workloads.

Pod Security admission rules, a replacement for the older PodSecurityPolicy system, allow you to enforce minimum security standards for the Pods in your cluster. This mechanism will reject any Pods that violate the configured Pod security standard, such as by omitting securityContext settings, binding HostPorts, or using HostPath volume mounts.

Policies can be enabled at the namespace or cluster-level. It’s good practice to use this system across your clusters. It guarantees that Pods with potentially dangerous weaknesses are prevented from running until you address their policy issues. If you need to run a Pod with elevated capabilities, you can use the Privileged profile to make your intentions explicit.

6. Harden Your Workloads

Kubernetes security isn’t all about your cluster. Applications need to be secure before they’re deployed, which means taking some basic steps to protect your container images.

First run automated security scanning tools to detect vulnerabilities in your code. Next, use a hardened base image and layer in your source. Finally, scan your built image with an analyzer like Clair or Trivy to identify outdated OS packages and known CVEs. You should rebuild the image to incorporate mitigations if issues are present.

In security-critical situations, think about starting from scratch so you can have certainty about what’s present in your containers. This lets you assemble your entire filesystem without relying on an upstream image that could contain lurking threats.

It’s also vital to use the security mechanisms that Kubernetes provides. Sensitive data such as database passwords, API keys, and certificates shouldn’t reside in plain-text ConfigMaps, or be hardcoded into container filesystems, for example. Kubernetes Secrets let you store these values securely, independently of your Pods. They don’t encrypt values by default, though, so it’s vital to enable etcd encryption wherever they’re used. Secrets can also integrate with external datastores to save credentials outside your cluster.

How The "4C" Model Protects Your Cluster

Using these best practices helps you adhere to the 4C model of cloud-native security. This simple mental picture sets out four security layers to protect yourself, each of them common words prefixed with “C”:

  • Cloud – Vulnerabilities in your cloud infrastructure, such as not enabling 2FA for your Azure, AWS, or Google Cloud accounts, give attackers a route to all your resources. Protect yourself by regularly auditing your environment and choosing a reputable provider with a good compliance record.
  • Cluster – Apply recommendations such as etcd encryption, RBAC controls, and Node isolation to protect your cluster from attack. Cluster-level compromise will expose all your applications and their data.
  • Container – Individual containers can be strengthened by using hardened base images, scanning for vulnerabilities, and avoiding use of privileged capabilities. Malware inside a single container might be able to break out to access other resources and the host Node.
  • Code – Code inside containers should be audited, scanned, and probed as it’s created to identify any weaknesses. Don’t underestimate attackers: while Kubernetes provides strong container isolation when configured correctly, weaknesses in your code could let intruders exploit zero-day vulnerabilities to escape the container and control your cluster.

Applying security protections across all four segments will give you the greatest protection. Only targeting a few areas could create weaknesses that let attackers move down the 4C pyramid and then laterally across your resources.

Read more about Container security best practices and solutions.

Key Points

Kubernetes makes it easy to start and run containers but using plain images in a fresh cluster can be a security risk. Your workloads and clusters need to be hardened to make them safe for critical production environments. While it can be tempting to skip these steps, you’ll be vulnerable to exploitation if bad actors find your cluster.

The steps we’ve shared above will help you use Kubernetes securely by following the 4C model of Cloud, Cluster, Container, and Code. Attackers can manipulate weaknesses in any of these areas to cause a security incident.

Although the techniques listed here are good starting points, they’re not an exhaustive list of measures you can take. You can uncover additional improvement opportunities by using automated tools like Kubescape. This policy-based cluster scanner detects Kubernetes misconfigurations, security vulnerabilities, and container image risks in a single scan of your cluster.

There’s growing industry interest in strengthening Kubernetes deployments, including from U.S. government bodies. The NSA/CISA Kubernetes hardening guide and the Center for Internet Security’s Kubernetes security benchmark are two references you can use to find threats in security-critical situations. We’ve also got more posts on the Spacelift blog about Kubernetes security, such as how to use secrets to store sensitive data in your cluster.

Useful Tricks For DevOps Engineers

Tricks of the trade, hacks, trade secrets, cheat sheets, best practices, call them what you will. Every industry has them, and anyone who sticks around long enough builds an arsenal of techniques and finely tuned tools to excel at their job.

Some things simply take time to master. My dad, a retired builder, could tile a medium-sized bathroom in under an astonishing three hours, while it would take me a full day just to do the grouting afterwards. Experience is key for certain skills, but there are also tips that don’t require years of practice to acquire.

DevOps is no different. There are no shortcuts to becoming a god-tier DevOps savant, put the years in and you might just get there. Having said that, there are some tricks of the trade, life hacks and useful tooling that are sure to give you an instant boost in productivity.

Here is my non-comprehensive list of life hacks guaranteed to make any DevOps engineer’s life easier.

The list is broken down into:

  • Tooling 🧰
  • Skills 🤸
  • Habits šŸ”
  • Scripts, configs and extensions šŸ’»

Tooling: 🧰

Did you know that if you really want to get somebodies attention in Germany, sending a fax is your best bet?
Also, in Japan up until this year, floppy disks were still in use by government institutions.

Knowing which context you find yourself in is essential to then choose the best tools for the job. Even though it’s important not to obsess over having the best, newest, or shiniest tool on the market. The following tools can be real game-changers for DevOps engineers.

“You don’t need to be the sharpest tool in the shed to use the sharpest tools in the shed” — Anonymous (I might have made it up)

1. k9s

K9s is a terminal-based UI for interacting with your Kubernetes clusters. It takes very little time to get accustomed to navigating, observing, and managing your live applications through the tool. And once you do, you might never go back. K9s continually monitors Kubernetes for changes and offers many useful commands to interact with your observed resources.

Link to instal.

2. tmux

tmux is a powerful terminal multiplexer that enhances productivity by allowing session persistence, window and pane management, and customization through key bindings and configuration files. It supports scripting for automation, facilitates collaboration with shared sessions, and integrates well with various shells and tools.

3. Glasskube

Glasskube is an Open Source package manager for Kubernetes. It makes deploying, updating, and configuring packages on Kubernetes 20 times faster than tools like Helm or Kustomize. Inspired by the simplicity of Homebrew and npm. You can decide if you want to use the Glasskube UI, CLI, or directly deploy packages via GitOps.

Care to support us?

If this is the first time you’ve heard of Glasskube, we are working to build the next generation Package Manager for Kubernetes.

If you like our content and want to support us on this mission, we’d appreciate it if you could give us a star ⭐️ on GitHub.

⭐️ Star us on GitHub šŸ™

4. ripgrep

Riggrep is a powerful search tool known for its speed, flexibility, and user-friendly output. It quickly processes large codebases using advanced algorithms, supports a wide range of search patterns, and presents clear, highlighted results. Riggrep integrates well with other tools, is cross-platform, and customizable.

5. Firefox containers for multi cloud account access

Firefox Multi-Account Containers is a such an underestimated browser extension for it’s utility. It helps manage online activity by separating websites into different containers or tabs, preventing sessions tracking across sites. It’s most useful feature is that it allows users to log into multiple accounts simultaneously within the same browser. By isolating sessions through cookie separation, it protects personal data and improves the overall browsing experience. Have multiple AWS accounts? Not an issues, you can log in to all of them from the same browser window.

6. VPA

Vertical Pod Autoscaler (VPA) frees users from the necessity of setting up-to-date resource limits and requests for the containers in their pods. When configured, it will set the requests automatically based on usage and there after allow proper scheduling onto nodes so that appropriate resource amounts are available for each pod.

Install it here.

Example config:

apiVersion: autoscaling.k8s.io/v1
kind: VerticalPodAutoscaler
metadata:
name: my-app-vpa
spec:
targetRef:
apiVersion: "apps/v1"
kind: Deployment
name: my-app
updatePolicy:
updateMode: "Auto"

7. Kctx and Kubens

Is just hand’s down the most useful CLI tool for Kubernetes context and Namespace switching.

Install it here

8. ChatGPT for guidance

Use ChatGPT as if it were a senior member on your team who is never busy and always happy to answer all of your questions. Make sure your intention is deeper understanding and not blind task resolution.

Prime ChatGPT to be a senior team member with a prompt like this:

You will act as a Senior DevOps Engineer to provide life hacks and tips on how to excel in the field of DevOps. You will also be ready to help junior team members with any questions they might have. Please include practical advice, recommended tools, and best practices for managing infrastructure and continuous integration/continuous deployment (CI/CD) pipelines. Write the output using my communication style, which is clear, concise, and practical. Here are examples of my communication style:

  • “Focus on automating repetitive tasks to save time and reduce errors.”
  • “Leverage tools like Docker and Kubernetes for containerization and orchestration.”
  • “Always monitor system performance and be proactive in identifying potential issues.”
  • “When mentoring juniors, be patient and explain concepts in simple terms.”

Here are some questions you can ask ChatGPT to further fine tune the prompt:

  1. Do you want the advice and explanations to cater more to beginner-level juniors or those with some experience in DevOps?
  2. Could you provide more detailed examples of your communication style, especially in scenarios where you explain complex concepts to juniors?
  3. Are there specific challenges or areas of focus within DevOps (e.g., automation, monitoring, security) that you want to prioritize for the advice and junior support?

Skills: 🤸

It’s no surprise that skills can’t be absorbed instantly, they require time and effort. In the ever-evolving tech world, determining which skills to cultivate can be confusing. However, as DevOps engineers, you can’t go wrong with mastering scripting and prioritizing documentation.

“Build your skills not your resume.” — Sheryl Sandberg

9. Scripting

Scripting is like a swiss army knife for DevOps engineers because it automates repetitive tasks, provides essential glue between processes, and ensures consistency across environments. Learning and practicing scripting involves familiarizing yourself with tools like Makefiles, regular expressions (regex) for efficient text processing, and Bash scripting for powerful command-line operations.

Don’t feel like you have to master scripting before implementing it at work. Look for manual steps in your current software or infrastructure delivery processes and try to script automations that make sense. Leverage an LLM for help if needed.

10. Documentation

Write everything down. It’s the best way to take care of your future you.

Try out a few note taking solutions here are a few:

It doesn’t matter which one you choose as long as you only choose one and you stick to it.

šŸ¤” Don’t fall into the trap of spending too much time organising and optimising your notes. Notes don’t have to be perfect only functional. Spending too much time on note maintenance is meta-work.

Habits: šŸ”

You will never get far if you rely solely on pure motivation to get things done and improve. Well-defined and consistent habits are the glue that keep you growing and effective, even when your motivation wanes. Habits seamlessly integrate tools and skills, ensuring you are effective at your job.

“Motivation is what gets you started. Habits is what keeps you going.” — Jim Ryun

11. Don’t write to-do lists, block time.

I’ve been heavily influenced by Cal Newport’s writing on Deep Work and I’m quite convinced that efforts to preserve a certain amount of time per week dedicated to uninterrupted deep work is crucial for an individual who wants to contributor meaningfully to a team.

To-do list on their own are just wish lists. Once you plot them on a calendar, that’s when you have a plan.

It’s important to point out that I know very few people who execute on their time block plans with 100% fidelity every day of the week. Use them as north stars, schedule rest time when you need it. Update the list throughout the day even. But at least hold yourself to a plan.

12. Reciprocal meeting blocks

Unless you are your own boss, you’re most likely not 100% in charge of the meetings and commitments you might be obliged to participate in. Reciprocal meeting blocks is a way to counteract unexpected time commitments that just pop up in your calendar.
The idea here to reserve an equivalent deep work block every time a new meeting is added to you calendar. That way you can stay flexible and relatively available without having to compromise on your weekly deep work quota.

13. Have a shutdown routine

Especially useful if you are a remote worker. A shutdown routine is a series of questions and steps your run through to finish your working day. Ideally once you complete the checklist you should be able to forget about your work until the next day.

What I track is the following:

  • Did I exercise?
  • Did I address all of the miscellaneous tasks I had?
  • Do I have any open conversations?
  • Do I need to push any tasks to the next day?
  • Did I write a diary entry? (not work related but I like to get it done before I leave the desk)
  • How many deep hours did I do?
  • Did I check the metrics I’m tracking one last time before I close the laptop for the day?

14. Take notes during meetings

Taking notes during meetings and sharing them afterward should ideally be a common practice in your organization. If it isn’t, this is a perfect opportunity for you to start. Not only does it ensure that no important details slip through your fingers, but it also provides a great service to your team.

15. Test run outages

Test run outages are essential for DevOps engineers to prepare for real incidents. You have to know exactly how to swiftly and efficiently connect to your clusters or VMs before an unexpected 1 a.m. alert for example, you can’t be caught off guard.

Familiarize yourself with moving files, retrieving container logs, and other critical tasks. Setting up SSH keys, kubeconfigs, and other access tools in advance will save valuable time and reduce stress during actual outages. Proactively testing and optimizing these processes ensures that you are ready to respond effectively to any disruption.

Scripts, configs and extensions: šŸ’»

If you have to do something more than once, automate it. Why write out a full command when you can save time by using an alias? Over a long career, it might be hard to calculate exactly how much time is saved by typing “k” instead of “kubectl.” One thing is for sure: it’s a lot, and it’s well worth it.

“You’re either the one that creates the automation or you’re getting automated.” — Tom Preston-Werner

16. Use helpful aliases

Don’t waste time typing out the full commands you write every day.

Here is a small snippet of a few of my configured aliases:

k=kubectl
kctx='kubectl ctx'
kgp='kubectl get pods'
kns='kubectl ns'
l='ls -lah'
la='ls -lAh'
ll='ls -lh'
ls='ls -G'
lsa='ls -lah'
md='mkdir -p'
rd=rmdir
run-help=man

17. Efficiently cleaning up finished jobs with TTL controller

You can specify the lifespan of finished jobs or pods before they are automatically removed by setting the .spec.ttlSecondsAfterFinished field. If you working in a job heavy environment finished jobs can quickly accumulate and become quite resource heavy.

Example config:

apiVersion: batch/v1
kind: Job
metadata:
name: test-ttl-job
spec:
ttlSecondsAfterFinished: 100
...

18. Git script to keep synced with the upstream

git remote add upstream <upstream-url>
git fetch upstream
git rebase upstream/main
git push --force-with-lease

19. Kubectl auto complete

Kubectl autocompletion lets you create an alias for kubectl. This feature saves time by reducing the need for cheat sheets and is especially useful for managing Kubernetes clusters. It’s also recommended for the CKA exam due to its time efficiency.

Set up for Linux:

# install bash-completion
sudo apt-get install bash-completion
# Add the completion script to your .bashrc file
echo 'source <(kubectl completion bash)' >>~/.bashrc
# Apply changes
source ~/.bashrc

Check out other installation methods here.

20. Visual Studio Code Remote — SSH

The Remote — SSH extension lets you use any SSH-enabled remote machine for development, making it easier to develop on the same OS you deploy to, use powerful hardware, switch between environments, and debug applications remotely.

Install it here.

Final thoughts

There’s no magic formula for becoming a top 1% DevOps engineer. Like in most professions, it’s a matter of time, dedication, and experience that will gradually shape you into a highly effective professional. Over time, you’ll get much better at recognizing patterns, recalling past situations, and finding quick solutions to recurring issues. So, don’t expect any single life hack from this list to instantly earn you a 50% raise and a promotion.

However, if you consistently focus on refining your tools, honing your skills, refusing to break good habits, and implementing smart automations, you’ll be well on your way to rapidly evolving and surpassing your current self. And who knows, maybe that promotion is just around the corner.