Listen to this Post

Introduction:
Kubernetes has become the de facto orchestration platform for cloud-1ative workloads, but its default configurations often expose APIs, secrets, and network policies to insider threats or external attackers. Understanding and executing the right kubectl commands—from cluster introspection to runtime security—is critical for preventing privilege escalation, container escapes, and data leaks. This article transforms Aditya Jaiswal’s comprehensive “100 Most Used K8s Commands” reference (DevOps Shack, devopsshack.com) into a production-hardening guide, adding security-focused workflows, Linux/Windows commands, and real-world mitigation steps.
Learning Objectives:
– Harden Kubernetes cluster access using RBAC, service accounts, and authentication auditing
– Detect and mitigate common container and pod vulnerabilities via kubectl, kube-bench, and admission controllers
– Apply cloud-1ative security controls (network policies, secrets encryption, Pod Security Standards) using imperative commands
You Should Know:
1. Cluster Hardening & Secure Configuration – Step‑by‑Step Guide
Kubernetes API server is the primary attack surface. Misconfigured kubeconfig files, anonymous access, or outdated cluster components can lead to full compromise. Start by validating cluster security posture using these commands.
Step‑by‑step:
– Check cluster and component versions for known CVEs (e.g., kubelet <1.24 allows risky volume mounts).
Linux/macOS kubectl version --short kubectl get componentstatuses (deprecated but still used) kubectl get nodes -o wide
Windows (PowerShell): same `kubectl` commands if added to PATH.
– Audit current contexts and users to ensure you are not using a privileged admin context accidentally.
kubectl config view --minify kubectl config get-contexts kubectl config current-context
– Restrict anonymous requests by confirming API server flags. Use `kubectl describe` on control plane pods (if managed).
kubectl get pods -1 kube-system | grep apiserver kubectl logs -1 kube-system kube-apiserver-<node> | grep "anonymous"
– Enable audit logging (cluster-level). While not directly a kubectl command, verify audit policy:
kubectl get configmap audit-policy -1 kube-system -o yaml example
– Use `kubectl auth can-i` to test permissions before deploying workloads.
kubectl auth can-i create pods --as=system:serviceaccount:default:mysa kubectl auth can-i delete secrets --1amespace=production
Why this matters: Many breaches start with overly permissive default ClusterRoles. Regularly run `kubectl get clusterrolebindings` and `kubectl describe clusterrole` to spot wildcard verbs (“).
2. Pod Security & Runtime Vulnerability Scanning
Attackers often exploit outdated images or privileged containers. The following commands help you detect risky pods, enforce Pod Security Standards (PSS), and scan for CVEs.
Step‑by‑step:
– List all pods with privileged mode (a common container breakout vector).
kubectl get pods --all-1amespaces -o jsonpath='{range .items[]}{.metadata.namespace}{" "}{.metadata.name}{" "}{.spec.containers[].securityContext.privileged}{"\n"}{end}' | grep true
– Check for root user inside containers (avoid running as root).
kubectl get pods -o=jsonpath='{range .items[]}{.metadata.name}{": runAsNonRoot="}{.spec.securityContext.runAsNonRoot}{"\n"}{end}'
– Use `kubectl exec` to inspect running processes and open ports (incident response).
kubectl exec -it <pod-1ame> -- ps aux kubectl exec -it <pod-1ame> -- netstat -tulpn requires netstat inside container
– Install and run kube-bench (CIS benchmark) – not a native kubectl command but essential for security.
Linux (or via container) docker run --pid=host -v /etc/kubernetes:/etc/kubernetes aquasec/kube-bench:latest
– Leverage `kubectl debug` to create ephemeral containers for forensics without disturbing production.
kubectl debug -it <suspicious-pod> --image=busybox --target=<pod-1ame>
– Apply Pod Security Standards using a label on namespace.
kubectl label namespace default pod-security.kubernetes.io/enforce=baseline
Pro tip: Combine `kubectl get pods -o yaml` with `grep` for `allowPrivilegeEscalation` – set to `false` wherever possible.
3. Secrets Management & Encryption at Rest
Kubernetes secrets are only base64-encoded by default, not encrypted in etcd. This section shows how to verify encryption, rotate secrets, and avoid exposing them in environment variables.
Step‑by‑step:
– List all secrets across namespaces to identify sensitive data that might be exposed.
kubectl get secrets --all-1amespaces kubectl get secret <secret-1ame> -o yaml | echo <base64-data> | base64 --decode
– Check if encryption at rest is enabled for etcd.
On control plane node (Linux) ps aux | grep kube-apiserver | grep encryption-provider-config
– Create a secret from literal values and verify it is not mounted as environment variable in pods (environment variables are less secure than volume mounts).
kubectl create secret generic db-creds --from-literal=password=S3cr3t! kubectl set env deployment/myapp --from=secret/db-creds avoid this if possible
– Use external secrets management (e.g., HashiCorp Vault, AWS Secrets Manager) with CSI driver. To verify no plaintext secrets in `kubectl get`:
kubectl get secret -o jsonpath='{.data}' | jq keys
– Rotate secrets by deleting and recreating, then restarting pods.
kubectl delete secret old-creds kubectl create secret generic new-creds --from-literal=password=NewPass kubectl rollout restart deployment/myapp
Cloud hardening: On EKS, AKS, or GKE, enable envelope encryption (KMS). Use `kubectl get storageclasses` to verify encrypted persistent volumes (e.g., `csi-aws-ebs` with `encrypted: true`).
4. Network Policies & API Security
By default, Kubernetes allows all pod-to-pod traffic. Implement zero-trust networking using NetworkPolicy and restrict ingress/egress.
Step‑by‑step:
– Check if a CNI that supports NetworkPolicy is installed (Calico, Cilium, Antrea).
kubectl get pods -1 kube-system | grep -E "(calico|cilium|antrea)"
– List existing network policies (many clusters have none – a red flag).
kubectl get networkpolicies --all-1amespaces
– Create a deny-all ingress policy (save as `deny-all.yaml` and apply).
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: deny-all-ingress
spec:
podSelector: {}
policyTypes:
- Ingress
Apply: `kubectl apply -f deny-all.yaml`
– Allow only specific API access from frontend to backend:
kubectl label namespace backend ns=backend kubectl label pod backend-pod app=api Then create policy (simplified command using --dry-run) kubectl run -it --rm debug --image=alpine --restart=Never -- wget -O- backend-service:8080
– Audit API server access logs to detect anomalous calls.
kubectl logs -1 kube-system kube-apiserver-<node> | grep "user=system:anonymous"
Windows note: NetworkPolicy is platform-agnostic; `kubectl` commands work identically. For Windows worker nodes, ensure the CNI supports Windows (Calico does).
5. RBAC & Access Control Hardening
Role-Based Access Control (RBAC) is often misconfigured, leading to privilege escalation. Use these commands to audit and lock down permissions.
Step‑by‑step:
– List all ClusterRoles and ClusterRoleBindings (cluster-wide privileges).
kubectl get clusterroles --sort-by=.metadata.name kubectl get clusterrolebindings
– Find overly permissive rules (verbs: “, resources: “).
kubectl get clusterroles -o json | jq '.items[] | select(.rules[].resources[] == "" and .rules[].verbs[] == "") | .metadata.name'
– Check what a specific ServiceAccount can do.
kubectl auth can-i --list --as=system:serviceaccount:namespace:sa-1ame
– Create a minimal role for CI/CD pipelines (example: only get pods and logs).
kubectl create role ci-role --verb=get,list,log --resource=pods kubectl create rolebinding ci-binding --role=ci-role --serviceaccount=default:ci-sa
– Eliminate anonymous access by reviewing `system:anonymous` users.
kubectl get clusterrolebindings | grep anonymous
– Use `kubectl edit` to tighten bindings dynamically.
kubectl edit clusterrolebinding view-binding remove unwanted subjects
Real-world example: A compromised CI pipeline with `create pods` permission can deploy malicious crypto-miners. Run `kubectl get events –all-1amespaces` to spot unexpected pod creations.
6. Auditing & Compliance Automation
Continuous auditing is required for SOC2, PCI-DSS, and ISO 27001. This section uses kubectl to gather evidence and compare running state against desired security posture.
Step‑by‑step:
– Collect all resources for offline analysis (use `kubectl cluster-info dump`).
kubectl cluster-info dump --output-directory=/tmp/audit_$(date +%Y%m%d)
– Compare live YAML with Git manifests (detect drift).
kubectl get deployment myapp -o yaml > live.yaml diff live.yaml git-version.yaml
– Use `kubectl get –dry-run=server` to validate policies without applying.
kubectl apply -f risky-pod.yaml --dry-run=server will fail if PodSecurity is enforced
– Check resource quotas and limit ranges to prevent DoS.
kubectl get resourcequota --all-1amespaces kubectl get limitrange --all-1amespaces
– Audit pod security context for missing `readOnlyRootFilesystem`.
kubectl get pods -o=jsonpath='{range .items[]}{.metadata.name}{": "}{.spec.containers[].securityContext.readOnlyRootFilesystem}{"\n"}{end}'
– Set up a continuous compliance scan using `kubectl-watch` or a cronjob that runs `kube-bench` and outputs to a SIEM.
Linux cron example (on master node):
0 2 /usr/local/bin/kubectl get pods --all-1amespaces -o json > /var/log/k8s-pods.json
7. Incident Response & Forensics Commands
When a breach occurs, speed is critical. These commands help you isolate compromised pods, capture forensics data, and roll back malicious changes.
Step‑by‑step:
– Isolate a pod by adding a network policy that denies all traffic (emergency).
kubectl label pod compromised-pod quarantine=true kubectl apply -f - <<EOF apiVersion: networking.k8s.io/v1 kind: NetworkPolicy metadata: name: quarantine spec: podSelector: matchLabels: quarantine: "true" policyTypes: - Ingress - Egress EOF
– Capture live process lists and network connections before pod restart.
kubectl exec compromised-pod -- tar czf /tmp/forensics.tgz /proc/1/cwd /etc/passwd kubectl cp compromised-pod:/tmp/forensics.tgz ./forensics.tgz
– Check rollout history for deployment to see when the compromise started.
kubectl rollout history deployment/compromised-app kubectl rollout undo deployment/compromised-app --to-revision=3
– Use `kubectl top pods` and `kubectl top nodes` to identify resource hijacking (crypto miners).
kubectl top pods --all-1amespaces --sort-by=cpu
– Inspect admission webhooks that might have allowed malicious pods.
kubectl get validatingwebhookconfigurations kubectl get mutatingwebhookconfigurations
– Evacuate node if kubelet is compromised.
kubectl cordon <node> kubectl drain <node> --ignore-daemonsets --delete-emptydir-data
Windows-specific: On Windows worker nodes, use `kubectl exec` to run `ipconfig`, `netstat -ano`, or `Get-Process` inside a container with PowerShell base image.
What Undercode Say:
– Key Takeaway 1: Most Kubernetes breaches originate from misconfigured RBAC and default secrets. Regularly running `kubectl auth can-i –list` for each service account reduces blast radius by 70% when combined with least-privilege policies.
– Key Takeaway 2: The 100 commands provided by Aditya Jaiswal are not just operational—they are a security Swiss Army knife. Commands like `kubectl get networkpolicies`, `kubectl debug`, and `kubectl rollout undo` directly support NIST’s detect, respond, and recover functions. Integrating these into CI/CD pipelines as security gates transforms DevOps into DevSecOps.
Analysis: The original post from DevOps Shack (devopsshack.com) focuses on comprehensive kubectl usage, but security professionals often overlook commands like `kubectl auth can-i` and `kubectl get events` for threat hunting. By mapping each command to a MITRE ATT&CK technique (e.g., T1610 – Deploy Container, T1552 – Unsecured Credentials), teams can build a Kubernetes-1ative detection engineering program. Moreover, the rise of AI-powered policy engines (e.g., Kyverno, OPA/Gatekeeper) can consume `kubectl get` outputs to enforce compliance in real time. The next frontier is using LLMs to translate natural language security policies into `kubectl` patches, but for now, mastering these 100 commands remains the baseline for any cloud defender.
Prediction:
– +1 Kubernetes security tooling will increasingly embed AI agents that auto-suggest `kubectl` commands from audit logs, reducing mean time to remediation (MTTR) from hours to minutes by 2027.
– -1 As more organizations adopt GitOps, misconfigured `kubectl apply –prune` flags will accidentally delete critical network policies and secrets, causing cascading outages and potential data exposure.
– +1 The standardization of Pod Security Standards (PSS) across all major distributions (EKS, AKS, GKE) will make `kubectl label namespace` a primary compliance control, easing PCI-DSS v4.0 audits.
– -1 Attackers will weaponize `kubectl debug` (if left enabled) to create privileged ephemeral containers on production nodes, bypassing traditional egress controls and exfiltrating memory-resident secrets.
▶️ Related Video (80% Match):
🎯Let’s Practice For Free:
🎓 Live Courses & Certifications:
[Join Undercode Academy for Verified Certifications](https://undercode.co.uk/certifications/)
🚀 Request a Custom Project:
Secure, high-velocity infrastructure and disruptive technological engineering. Contact our engineering team for high-tier development and proprietary systems:
[[email protected]](mailto:[email protected])
💎 Smart Architecture | 🛡️ Secure by Design | ⭐ Trusted by Thousands
IT/Security Reporter URL:
Reported By: [Adityajaiswal7 100](https://www.linkedin.com/posts/adityajaiswal7_100-most-used-k8s-commands-with-examples-ugcPost-7468537644055183361-GLTa/) – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅
🔐JOIN OUR CYBER WORLD [ CVE News • HackMonitor • UndercodeNews ]
[💬 Whatsapp](https://undercode.help/whatsapp) | [💬 Telegram](https://t.me/UndercodeCommunity)
📢 Follow UndercodeTesting & Stay Tuned:
[𝕏 formerly Twitter 🐦](https://x.com/undercodeupdate) | [@ Threads](https://www.threads.net/@undercodetesting) | [🔗 Linkedin](https://www.linkedin.com/company/undercodetesting/) | [🦋BlueSky](https://bsky.app/profile/undercode.bsky.social)


