Tag: least privilege

  • Linux privilege escalation hygiene: the SUID bits, capabilities and sudo rules that quietly hand out root

    Linux privilege escalation hygiene: the SUID bits, capabilities and sudo rules that quietly hand out root

    Most local privilege escalation I run into on real systems isn’t a kernel exploit. It’s a configuration someone added three years ago to make a deploy script work, and nobody has looked at since. A binary with a stray setuid bit, a capability granted to an interpreter, a sudoers line with a wildcard in it. Each one is a perfectly legitimate way for an unprivileged user to become root, and the system is doing exactly what it was told.

    This post is about auditing those three places and tightening them. It’s defensive: run these on boxes you own.

    SUID and SGID binaries

    Before and after diagram. Before: an unprivileged user reaches root through a stray SUID binary, a cap_setuid interpreter and a sudo tee wildcard rule. After: nosuid mounts with baseline diff, AmbientCapabilities in the unit file and a validated wrapper script close those paths, leaving one narrow logged route.

    The diagram compares the three paths above before and after the controls described in this post.

    A file with the setuid bit runs with the owner’s UID instead of the caller’s. That is how passwd can write to /etc/shadow. It also means every bug in that binary is a root bug, and the bug can be reached by any user who can execute it, through arguments, environment variables, and files it opens.

    The history is bad. CVE-2021-4034 (PwnKit) was an out-of-bounds read and write in pkexec, a SUID-root binary shipped on essentially every mainstream distribution, and it sat there for about twelve years. CVE-2023-4911 (Looney Tunables) was a buffer overflow in glibc’s dynamic loader, triggered through the GLIBC_TUNABLES environment variable, which made every SUID binary on affected systems a way in. Neither needed a misconfiguration. The attack surface was just there.

    So the first job is an inventory, and a diff against it over time:

    find / -xdev -perm -4000 -type f 2>/dev/null | sort > suid.now
    find / -xdev -perm -2000 -type f 2>/dev/null | sort > sgid.now
    diff suid.baseline suid.now

    On a stock Ubuntu 24.04 container image the SUID list is short: chfn, chsh, gpasswd, mount, newgrp, passwd, su, umount. A full server install has more. Anything that isn’t in your baseline needs an owner and a reason.

    Three habits remove most of the risk. Mount /tmp, /var/tmp, /home and /dev/shm with nosuid,nodev, so a SUID file dropped by an attacker or a user is inert there. Remove the bit from binaries you don’t use (chfn and chsh are good candidates on a server with no local logins). And alert on new SUID files at creation time. With auditd, a rule on the chmod family catches the bit being set (04000 is 0x800):

    -a always,exit -F arch=b64 -S chmod,fchmod -F a1&0x800 -F auid>=1000 -F auid!=unset -k suid_set
    -a always,exit -F arch=b64 -S fchmodat -F a2&0x800 -F auid>=1000 -F auid!=unset -k suid_set

    That doesn’t catch a SUID file arriving inside a tarball extracted as root, so the periodic find-and-diff stays.

    File capabilities

    Capabilities split root into pieces, which sounds like a safe improvement. In practice, some of those pieces are root under another name. CAP_SETUID lets a process become any UID, including 0. CAP_DAC_READ_SEARCH bypasses file read permission checks, so it reads /etc/shadow and SSH host keys. CAP_SYS_ADMIN is so broad that the capabilities man page itself describes it as overloaded. CAP_SYS_PTRACE lets you inject into other processes.

    The classic mistake is giving a capability to something that can run arbitrary code. I reproduced it in a throwaway container for this post: copy the Python interpreter, give it cap_setuid, and an ordinary user can become root.

    Terminal output from a disposable Ubuntu 24.04 container: the SUID file list, getcap showing cap_setuid=ep on a copied python3 binary, and user alice (uid 1001) running it to get uid=0(root).

    The screenshot is a real run in a disposable Ubuntu 24.04 container, with the output rendered to an image. The user alice has UID 1001 until she calls os.setuid(0) through the capable interpreter. Nothing in that sequence is a vulnerability. The capability does what it says.

    To find these on a host:

    getcap -r / 2>/dev/null

    Expect a few legitimate entries, for example cap_net_bind_service on a web server binary or cap_net_raw on ping on distributions that use capabilities instead of SUID for it. Any capability on a shell, an interpreter, find, tar, cp, vim or an editor is a finding. Check these against GTFOBins, which lists which common binaries turn each capability into a shell or a file write.

    For services, don’t set file capabilities at all. Use AmbientCapabilities=CAP_NET_BIND_SERVICE and CapabilityBoundingSet= in the unit file, which scopes the grant to that service and leaves no tagged binary on disk for someone else to execute. I covered the systemd side in the sandboxing post earlier in this blog.

    Sudo rules

    Sudo is where I find the most variety. The pattern is always the same: a rule meant to allow one narrow action that allows a general one instead.

    Anything that can spawn a shell or write arbitrary files is root. NOPASSWD: /usr/bin/vim, less, find, awk, tar, git, man, any interpreter. A user runs the allowed program, then escapes to a shell from inside it, and the shell keeps root. The NOEXEC tag blocks some of these by intercepting execve through LD_PRELOAD, but the sudoers manual is clear that it’s not a defence against a determined user, so I don’t count on it.

    Wildcards are the other classic. In sudoers, * matches any characters including slashes and spaces. This rule looks like it restricts writes to a log directory:

    deploy ALL=(root) NOPASSWD: /usr/bin/tee /var/log/app/*

    It allows sudo tee /var/log/app/../../../etc/sudoers.d/x, and it allows extra arguments after the first path, so a second file can be named too. The fix is a wrapper script that validates its input, or better, a design that doesn’t need root for it, like a group-writable log directory.

    Sudo itself has had its moments. CVE-2021-3156 (Baron Samedit) was a heap overflow in sudo’s argument handling, exploitable by any local user without being in sudoers, affecting 1.8.2 through 1.8.31p2 and 1.9.0 through 1.9.5p1. CVE-2023-22809 let a user with sudoedit access edit extra files by smuggling them into the EDITOR variable after a --. Keeping sudo patched matters, and so does keeping the number of people with sudo rights small, because those bugs are only reachable by whoever can run it.

    Audit with these:

    sudo -l -U deploy
    grep -rEn 'NOPASSWD|\*|!|env_keep|SETENV' /etc/sudoers /etc/sudoers.d/
    visudo -c

    Things I’d rather see in a sudoers file: full paths only, sudoedit instead of a bare editor, no SETENV tag, Defaults use_pty and Defaults logfile= or shipped logs, and a Cmnd_Alias per task so a review can read intent. If a rule needs a wildcard, treat it as code and review it like code.

    Making it stick

    A one-time cleanup decays in a quarter. What has worked for me is boring: put the SUID and capability baselines into configuration management so the expected state is declared, run the find and getcap diffs on a schedule, and ship sudo’s logs and the auditd suid_set key to wherever you already alert. Lynis and OpenSCAP both check parts of this if you’d rather start from a tool than from scripts. Tools like linPEAS are worth running against your own hosts once, because they show you the same list an attacker’s first script sees.

    The rule I apply to every entry on these three lists is the same one: if you can’t say who needs it and why, it goes.

  • Kubernetes RBAC and admission control: how one compromised pod becomes a compromised cluster

    Kubernetes RBAC and admission control: how one compromised pod becomes a compromised cluster

    Most Kubernetes incident write-ups I read start the same way. Somebody finds a remote code execution bug in an ordinary web app, lands in a pod, and twenty minutes later they are reading secrets from every namespace. The bug in the app was a normal bug. The part that turned it into a cluster compromise was a handful of RBAC and admission settings nobody had looked at since the cluster was stood up.

    I’ll assume you already run Kubernetes and know what a Role is.

    What the attacker finds in the pod

    Flowchart of the attack chain from an application bug in a pod through a service account token, an RBAC grant, a privileged pod and the node, with the control that breaks each step

    The diagram shows the chain an attacker follows from an application bug to the node, and the control that breaks each step.

    Every pod gets a service account, and unless you say otherwise, a projected token for it is mounted at /var/run/secrets/kubernetes.io/serviceaccount/token. Since 1.24 that token is short-lived and bound to the pod, which is better than the old never-expiring secrets. It still works against the API server for as long as the pod lives, and the attacker lives inside the pod.

    The first thing they run is the equivalent of this:

    kubectl auth can-i --list

    You should run it yourself, from the outside, impersonating the service account of each workload:

    kubectl auth can-i --list \
      --as=system:serviceaccount:shop:web \
      -n shop

    Most web apps need no Kubernetes API access at all. If the answer is anything beyond the default discovery permissions, ask why. Then turn the token off where it isn’t needed:

    apiVersion: v1
    kind: ServiceAccount
    metadata:
      name: web
      namespace: shop
    automountServiceAccountToken: false

    The usual cause is a token nobody asked for and a RoleBinding inherited from a copy-pasted Helm chart.

    RBAC verbs that are really something else

    RBAC is purely additive. There are no deny rules, so the only way to be safe is to grant less. The documented behaviour that matters most is that the API stops you from creating or editing a Role that grants permissions you don’t hold yourself, unless you have the escalate verb on roles. The same goes for bind on creating RoleBindings. Hand those two out and you’ve handed out cluster-admin with extra steps. impersonate is the third one to grep for.

    The quieter problems are verbs that look read-only or small:

    • get, list and watch on secrets all return the secret data. A role that can list secrets in a namespace can read every secret in it. This is the one people get wrong because list sounds harmless.
    • create on pods in a namespace is, in practice, access to every secret and service account in that namespace. The attacker creates a pod that mounts the secret or runs as the more privileged service account. The Kubernetes docs call this out under privilege escalation via workload creation.
    • create on pods/exec is a shell in any pod in scope.
    • Wildcards. resources: ["*"] and verbs: ["*"] also match resources that don’t exist yet, including whatever the next CRD you install adds.

    The group system:masters bypasses RBAC entirely, so a client certificate with that group in the subject can’t be restricted by anything you write in a Role. Don’t issue those, and don’t bind cluster-admin to system:authenticated. That binding makes every authenticated identity an admin.

    A sane namespaced role for a controller that only needs to read config looks like this:

    apiVersion: rbac.authorization.k8s.io/v1
    kind: Role
    metadata:
      name: read-config
      namespace: shop
    rules:
      - apiGroups: [""]
        resources: ["configmaps"]
        resourceNames: ["web-config"]
        verbs: ["get", "watch"]

    Note resourceNames. It narrows a grant to specific objects, and it works for get but not for list or create, since the name isn’t known at request time (with a list it only works if the request uses a field selector on metadata.name).

    Admission is the second lock

    RBAC decides whether you may create a pod. It says nothing about what the pod is allowed to contain. A pod with privileged: true, hostPID: true or a hostPath mount of / is a node compromise waiting for a trigger, and from the node the attacker can read the kubelet credentials and every other pod’s tokens on that host.

    That’s what admission controllers are for. Pod Security Admission has been built in since it went stable in 1.25, replacing PodSecurityPolicy, which was removed in that release. It defines three profiles, privileged, baseline and restricted, applied per namespace through labels, in three modes: enforce, audit and warn.

    kubectl label --overwrite ns shop \
      pod-security.kubernetes.io/enforce=restricted \
      pod-security.kubernetes.io/enforce-version=latest

    Before enforcing on a namespace that already has workloads, ask the API server what would break. The documented way is a server-side dry run:

    kubectl label --dry-run=server --overwrite ns --all \
      pod-security.kubernetes.io/enforce=baseline
    Screenshot of the Kubernetes documentation page for Pod Security Admission labels, showing the enforce, audit and warn modes

    The screenshot is the real Kubernetes documentation page for the Pod Security Admission labels, listing what enforce, audit and warn each do.

    It returns warnings listing the pods that violate the profile. I roll out warn and audit first, fix what shows up, and only then flip to enforce. Going straight to enforce on a busy namespace breaks deploys at the worst moment.

    Baseline blocks the obvious things: privileged containers, host namespaces, hostPath volumes, most added capabilities. Restricted adds non-root, no privilege escalation, a seccomp profile and dropped capabilities. It breaks a lot of off-the-shelf images, which is a useful thing to find out early.

    When the built-in profiles aren’t enough

    Pod Security Admission is coarse on purpose. For rules like “images only from our registry” or “no hostNetwork unless labelled”, you need a policy engine. Kyverno and OPA Gatekeeper are the established options. Since 1.30 there is also ValidatingAdmissionPolicy, which is stable and runs CEL expressions inside the API server with no webhook to keep alive. A validating webhook that is down either blocks every deploy or, with failurePolicy: Ignore, silently stops protecting you.

    apiVersion: admissionregistration.k8s.io/v1
    kind: ValidatingAdmissionPolicy
    metadata:
      name: no-host-network
    spec:
      failurePolicy: Fail
      matchConstraints:
        resourceRules:
          - apiGroups: [""]
            apiVersions: ["v1"]
            operations: ["CREATE", "UPDATE"]
            resources: ["pods"]
      validations:
        - expression: "!has(object.spec.hostNetwork) || !object.spec.hostNetwork"
          message: "hostNetwork is not allowed"
    ---
    apiVersion: admissionregistration.k8s.io/v1
    kind: ValidatingAdmissionPolicyBinding
    metadata:
      name: no-host-network
    spec:
      policyName: no-host-network
      validationActions: ["Deny"]

    This matches pods directly. Deployments and Jobs create pods through their controllers, so the pod-level check still fires at that point, but the error shows up in the ReplicaSet events and not at kubectl apply, which confuses people the first time.

    A short audit I’d run this week

    Search every ClusterRoleBinding for subjects that are groups like system:authenticated or system:unauthenticated. List every Role and ClusterRole containing secrets with get, list or watch, plus escalate, bind, impersonate, pods/exec and *. Check each namespace for a pod-security.kubernetes.io/enforce label. Check which service accounts have a mounted token and no reason for one.

    None of this is clever. Each check removes a step from the chain in the diagram: app bug, token, a create-pods grant, a privileged pod, the node. Breaking one link stops the attacker at that point, and breaking several is cheap next to writing the incident report.

  • Least privilege with systemd sandboxing

    Least privilege with systemd sandboxing

    Part 2 of 4 in the Hardening a Linux server series. Previously: Part 1, SSH hardening beyond “disable root login”.

    Most services on a Linux box run with far more access than they need. A web app that reads a config file, writes to one data directory and listens on one port can, by default, read most of the filesystem, write anywhere its user owns, call every syscall the kernel offers and open any kind of socket. When that app gets popped through a deserialization bug, all of that becomes the attacker’s starting position.

    systemd has grown a large set of sandboxing directives that fix this with a few lines in a unit file. No containers, no AppArmor profiles to maintain, no code changes. I think they’re the best return on effort in Linux hardening right now, and they’re still rarely used outside of the units systemd itself ships.

    Measure first

    Bar chart: measured systemd-analyze security exposure score falling from 9.2 at baseline to 1.0 as filesystem, kernel, capability, syscall and network restrictions are added

    systemd-analyze security scores every running service from 0 (locked down) to 10 (wide open) and lists each check it applied:

    systemd-analyze security
    systemd-analyze security nginx.service

    The number is a heuristic, a weighted sum of which directives are set, so don’t treat 2.1 versus 2.4 as meaningful. It is very good at showing you the gaps. On most distributions the bulk of third-party services score 9 or above.

    Measured: one unit, hardened step by step

    I took a trivial unit (python3 -m http.server running as a dedicated user) and added directives in groups, scoring each version with systemd-analyze security on systemd 249. The chart near the top of this post shows the result. The baseline scored 9.2. The final unit scored 1.0.

    Here is roughly what that final unit looks like, adjusted for a real service:

    [Service]
    ExecStart=/opt/webapp/bin/webapp
    DynamicUser=yes
    StateDirectory=webapp
    ConfigurationDirectory=webapp
    
    NoNewPrivileges=yes
    ProtectSystem=strict
    ProtectHome=yes
    PrivateTmp=yes
    PrivateDevices=yes
    ProtectKernelTunables=yes
    ProtectKernelModules=yes
    ProtectKernelLogs=yes
    ProtectControlGroups=yes
    ProtectClock=yes
    ProtectHostname=yes
    ProtectProc=invisible
    
    CapabilityBoundingSet=CAP_NET_BIND_SERVICE
    AmbientCapabilities=CAP_NET_BIND_SERVICE
    
    SystemCallArchitectures=native
    SystemCallFilter=@system-service
    SystemCallFilter=~@privileged @resources
    SystemCallErrorNumber=EPERM
    
    RestrictAddressFamilies=AF_UNIX AF_INET  ""AF_INET6
    RestrictNamespaces=yes
    RestrictSUIDSGID=yes
    RestrictRealtime=yes
    LockPersonality=yes
    MemoryDenyWriteExecute=yes
    UMask"" =0077

    That looks like a lot. Each line is cheap, though, and they fall into a few families.

    Privilege escalation inside the service

    NoNewPrivileges=yes sets the kernel’s no_new_privs flag, so nothing the service executes can gain privileges through setuid binaries or file capabilities. An attacker with code execution as the service user can’t then run a vulnerable setuid helper to become root. Several other directives quietly turn it on as well, which is fine.

    Capabilities are the other half. CapabilityBoundingSet= with an empty value drops every capability for good. The example keeps exactly one, CAP_NET_BIND_SERVICE, and grants it as an ambient capability so a non-root process can bind port 443. That is the right shape for most daemons that historically started as root just to grab a low port.

    DynamicUser=yes allocates a throwaway UID when the service starts. It implies a stricter set of defaults (read-only system, private /tmp, no setuid), and combined with StateDirectory= systemd creates and chowns /var/lib/webapp for you. If the service doesn’t need a stable UID shared with other software, use it.

    Filesystem view

    ProtectSystem=strict mounts the entire filesystem read-only for the service, apart from the API filesystems like /proc and /sys. Writable paths are then opt-in through StateDirectory=, CacheDirectory=, LogsDirectory= or ReadWritePaths=. This is the directive that stops an attacker dropping a cron job, a systemd unit or a modified binary for persistence. ProtectHome=yes hides /home, /root and /run/user entirely, which matters more than people think, since home directories are where SSH keys and cloud credentials live.

    PrivateTmp=yes gives the service its own /tmp, which closes off the classic symlink and race games other local users can play in a shared /tmp.

    Kernel attack surface

    A sandbox that lives in userspace can’t save you from a kernel bug, but it can make most kernel bugs unreachable. SystemCallFilter=@system-service is an allowlist of syscalls that ordinary services use, curated by systemd. The second line then removes @privileged and @resources. By default a blocked syscall kills the process with SIGSYS; SystemCallErrorNumber=EPERM makes it fail with an error instead, which is friendlier while you’re tuning.

    RestrictNamespaces=yes deserves a specific mention. A good number of recent Linux privilege escalation bugs are only reachable by unprivileged users through user namespaces, because creating one hands you capabilities inside it. CVE-2022-0185, a heap overflow in the filesystem context code, is the textbook case: exploitation needed CAP_SYS_ADMIN in a user namespace, which any unprivileged user could get on distributions that allowed unprivileged user namespaces. A service that can’t create namespaces can’t reach that code path at all.

    PrivateDevices=yes, ProtectKernelModules=yes and ProtectKernelTunables=yes take away raw device nodes, module loading and writes to /proc/sys. SystemCallArchitectures=native blocks the 32-bit syscall ABI on 64-bit hosts, a path that has been used to dodge seccomp filters written for one ABI only.

    Network

    RestrictAddressFamilies= limits which socket types the service may open. Most need AF_UNIX, AF_INET and AF_INET6, nothing else, and certainly not AF_PACKET or AF_NETLINK. If you want per-service egress control, IPAddressDeny=any with a narrow IPAddressAllow= uses a cgroup BPF filter to drop traffic to anything else. A compromised internal API that can’t reach the internet is a lot less useful as a staging point.

    Rolling it out without breaking things

    Don’t edit vendor units. Use systemctl edit webapp.service to write a drop-in under /etc/systemd/system/webapp.service.d/, which survives package upgrades. You can try options on a throwaway command before committing to them:

    sudo systemd-run --pty --wait -p ProtectSystem=strict -p PrivateTmp=yes \
      -p SystemCallFilter=@system-service /opt/webapp/bin/webapp --selftest

    The usual breakage is predictable. MemoryDenyWriteExecute=yes breaks anything with a JIT, so Node, the JVM and PCRE’s JIT mode will fail in confusing ways. ProtectSystem=strict breaks services that write somewhere surprising, which the journal will show as EROFS errors. Syscall filters occasionally catch a library doing something unusual, and with SystemCallErrorNumber=EPERM the audit log or strace -f tells you which call. Add one family at a time and run your integration tests between each.

    This doesn’t replace patching or a proper MAC policy, and it isn’t a VM boundary. What it does is shrink the blast radius of the next RCE in your app from “the box” to “one directory and a socket”. Part 3 covers auditd, so that when something does get through you can see what it tried to do.

    Other parts of the Hardening a Linux server series: Part 1: SSH hardening beyond “disable root login”, Part 3: auditd and what to log, Part 4: Patching without fear.