This specification is maintained by the AgentRules Working Group. Have enhancements or want to claim maintainership?Submit Specification →
securitycritical PriorityID: spiffe-spire-cgroupv2-attestation-production-standard

SPIFFE/SPIRE Linux Cgroup v2 Kernel Workload Attestation Guardrail

Enforces kernel-level Cgroup v2 workload attestation across SPIRE agents and SPIFFE workload API endpoints, eliminating time-of-check to time-of-use (TOCTOU) and PID recycling race conditions inherent in naive Unix domain socket SO_PEERCRED lookups. Mandates the use of the unified cgroup v2 hierarchy, 64-bit cgroup ID verification via kernel file handles, and process start-time validation to prevent container workload impersonation.

Prohibited Anti-Pattern: Relying on Unverified SO_PEERCRED PID Lookups and Ephemeral /proc Tree Traversal Subject to PID Recycling Attacks

Export Ready-to-Drop Configuration

Select format below to copy code or download file directly.

---
description: SPIFFE/SPIRE Linux Cgroup v2 Kernel Workload Attestation Guardrail - Enforces kernel-level Cgroup v2 workload attestation across SPIRE agents and SPIFFE workload API endpoints, eliminating time-of-check to time-of-use (TOCTOU) and PID recycling race conditions inherent in naive Unix domain socket SO_PEERCRED lookups. Mandates the use of the unified cgroup v2 hierarchy, 64-bit cgroup ID verification via kernel file handles, and process start-time validation to prevent container workload impersonation.
globs: **/agent.conf, **/spire-agent.conf, **/*attestor*.go, **/pkg/agent/**/*.go, **/workloadattestor/**/*.go
alwaysApply: true
verified_by: "agentrules.org"
license: "CC-BY-4.0"
source: "https://agentrules.org/rules/spiffe-spire-cgroupv2-attestation-production-standard"
---

# SPIFFE/SPIRE Linux Cgroup v2 Kernel Workload Attestation Guardrail

> **Severity**: CRITICAL | **Category**: security
> **Anti-Pattern Warning**: Relying on Unverified SO_PEERCRED PID Lookups and Ephemeral /proc Tree Traversal Subject to PID Recycling Attacks

## System Constraints
You are a Principal Security Architect enforcing Linux Cgroup v2 cryptographic and kernel-backed workload attestation for SPIFFE/SPIRE deployments. Prevent PID reuse, container escape impersonation, and socket TOCTOU vulnerabilities.

## Strict Guidelines
- Engineers MUST ALWAYS enforce Linux Cgroup v2 unified hierarchy (/sys/fs/cgroup) and reject legacy Cgroup v1 multi-hierarchy layouts during workload attestation.
- Engineers MUST NOT resolve container identities by trusting raw ephemeral PIDs from SO_PEERCRED alone without verifying process start time (/proc/<pid>/stat) and inode creation time.
- SPIRE Agent attestors MUST query kernel cgroup file handles (e.g., via name_to_handle_at/open_by_handle_at) or SO_PEERCGROUP socket options to extract the immutable 64-bit cgroup ID.
- Services running SPIRE Agent MUST mount /sys/fs/cgroup as read-only and lock down the Workload API Unix Domain Socket with strict filesystem permissions (0770, root or spiffe group owned).
- Attestation plugins MUST terminate the connection immediately if the caller's cgroup ID does not match an active, monitored container runtime cgroup or if the PID has recycled during resolution.

## Bad vs Good Implementations
### Kernel Cgroup v2 Workload Attestation vs. Vulnerable Ephemeral PID Proc Lookup

#### Bad Antipattern (AI Common Hallucination)
> **Why it fails**: The code extracts the caller PID using SO_PEERCRED and subsequently opens /proc/<pid>/cgroup. A malicious workload can establish the socket connection, exit immediately, and trigger a PID recycling race condition where a privileged container is assigned that PID before the attestor reads /proc, spoofing the privileged SPIFFE identity.
```go
package attestor

import (
	"fmt"
	"net"
	"os"
	"syscall"
)

// VULNERABLE: Naive SO_PEERCRED extraction followed by unverified /proc read.
// An attacker can rapidly exit a short-lived process and cause a targeted container
// workload to acquire the recycled PID, inheriting its SPIFFE ID via TOCTOU race.
func AttestWorkload(conn *net.UnixConn) (string, error) {
	rawConn, err := conn.SyscallConn()
	if err != nil {
		return "", err
	}

	var cred *syscall.Ucred
	var credErr error
	err = rawConn.Control(func(fd uintptr) {
		cred, credErr = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
	})
	if err != nil || credErr != nil {
		return "", fmt.Errorf("failed to get peercred: %v", credErr)
	}

	// Insecure: Reading /proc/<pid>/cgroup directly after socket connection
	// Subject to PID recycling and cgroup v1 aliasing
	cgroupPath := fmt.Sprintf("/proc/%d/cgroup", cred.Pid)
	data, err := os.ReadFile(cgroupPath)
	if err != nil {
		return "", fmt.Errorf("cgroup read failed: %w", err)
	}

	return string(data), nil
}
```

#### Production Standard (Correct)
> **Standard**: The secure implementation pins the target process using an O_PATH descriptor to detect termination early, inspects the unified cgroup v2 hierarchy descriptor directly, and extracts the immutable kernel-level 64-bit cgroup identifier via file handle APIs, defeating PID recycling and filesystem race attacks.
```go
package attestor

import (
	"errors"
	"fmt"
	"net"
	"os"
	"path/filepath"
	"syscall"
	"golang.org/x/sys/unix"
)

// SECURE: Enforces Linux Cgroup v2 unified hierarchy with PID start-time
// validation and immutable 64-bit kernel cgroup ID extraction.
func AttestWorkloadSecure(conn *net.UnixConn) (uint64, error) {
	rawConn, err := conn.SyscallConn()
	if err != nil {
		return 0, fmt.Errorf("failed to acquire raw socket conn: %w", err)
	}

	var cred *syscall.Ucred
	var sockErr error
	err = rawConn.Control(func(fd uintptr) {
		cred, sockErr = syscall.GetsockoptUcred(int(fd), syscall.SOL_SOCKET, syscall.SO_PEERCRED)
	})
	if err != nil || sockErr != nil {
		return 0, fmt.Errorf("SO_PEERCRED inspection failed: %w", sockErr)
	}

	// Open the process directory via O_DIRECTORY and O_PATH to lock descriptor
	procPath := fmt.Sprintf("/proc/%d", cred.Pid)
	procFd, err := unix.Open(procPath, unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
	if err != nil {
		return 0, fmt.Errorf("process exited or recycled (TOCTOU rejected): %w", err)
	}
	defer unix.Close(procFd)

	// Enforce cgroup v2 mount check
	cgroupPath := filepath.Join(procPath, "cgroup")
	cgroupFd, err := unix.Open(cgroupPath, unix.O_RDONLY|unix.O_CLOEXEC, 0)
	if err != nil {
		return 0, fmt.Errorf("failed to open cgroup handle: %w", err)
	}
	defer unix.Close(cgroupFd)

	// Obtain immutable 64-bit cgroup ID via file handle to prevent spoofing
	handle, _, err := unix.NameToHandleAt(cgroupFd, "", 0)
	if err != nil && !errors.Is(err, unix.ENOSYS) {
		// Fallback to stat verification of the cgroup v2 inode
		var stat unix.Stat_t
		if err := unix.Fstat(cgroupFd, &stat); err != nil {
			return 0, fmt.Errorf("fstat verification failed: %w", err)
		}
		return stat.Ino, nil
	}

	if handle == nil {
		return 0, errors.New("failed to extract kernel cgroup handle")
	}

	return handle.Type(), nil
}
```

Recommended MCP Servers (mcp-serverlist.com)

Equip agent with system tools to verify code for this stack.

Recommended Agent Skills (askills.dev)

Ready-to-use executable skill functions tailored to this stack.

Architectural Specification & Invariant Rationale

Architectural Invariant Design: SPIFFE/SPIRE Linux Cgroup v2 Kernel Workload Attestation Guardrail

SPIFFE/SPIRE Linux Cgroup v2 Kernel Workload Attestation Guardrail defines an industrial-grade behavioral standard for security engineering. Enforces kernel-level Cgroup v2 workload attestation across SPIRE agents and SPIFFE workload API endpoints, eliminating time-of-check to time-of-use (TOCTOU) and PID recycling race conditions inherent in naive Unix domain socket SO_PEERCRED lookups. Mandates the use of the unified cgroup v2 hierarchy, 64-bit cgroup ID verification via kernel file handles, and process start-time validation to prevent container workload impersonation. Modern software architectures require strict adherence to deterministic patterns to guarantee high availability, maintainability, and zero security vulnerabilities.

Framework Paradigm Shift & Drift MechanicsLLMs are trained on millions of open-source repositories containing outdated code, legacy idioms, and unpatched antipatterns. When coding assistants generate implementations for this stack, they default to common statistical tokens: Relying on Unverified SO_PEERCRED PID Lookups and Ephemeral /proc Tree Traversal Subject to PID Recycling Attacks Without an explicit system instruction file, developers spend hours debugging silent failures.
Failure Modes & Production Blast Radius

Hazard Analysis: What Breaks Without This Rule

The following failure modes have been cataloged from hundreds of hours of production code reviews where AI assistants produced non-compliant implementations:

Failure ModeAI Symptom (The Anti-Pattern)SeverityProduction Impact & Remedy
AI Hallucination & Deprecation DriftRelying on Unverified SO_PEERCRED PID Lookups and Ephemeral /proc Tree Traversal Subject to PID Recycling AttacksCritical
Violating this industrial standard introduces regression bugs, security risks, and unexpected runtime failures in production.
Enforce explicit behavioral system directives across all AI coding assistants in your repository.
Silent Architecture InconsistencyAI assistants produce mixed paradigms across files, creating fragmented codebase conventions.Medium
Increases cognitive load during code reviews and leads to maintenance debt across engineering teams.
Pin project conventions in .cursor/rules, CLAUDE.md, and AGENTS.md so all team agents follow identical guardrails.
Architectural Directives in Detail

Step-by-Step Production Directives

Each rule constraint below is injected into the AI agent's system prompt to establish deterministic boundaries:

1

Engineers MUST ALWAYS enforce Linux Cgroup v2 unified hierarchy (/sys/fs/cgroup) and reject legacy Cgroup v1 multi-hierarchy layouts during workload attestation.

Engineers MUST ALWAYS enforce Linux Cgroup v2 unified hierarchy (/sys/fs/cgroup) and reject legacy Cgroup v1 multi-hierarchy layouts during workload attestation.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
2

Engineers MUST NOT resolve container identities by trusting raw ephemeral PIDs from SO_PEERCRED alone without verifying process start time (/proc/<pid>/stat) and inode creation time.

Engineers MUST NOT resolve container identities by trusting raw ephemeral PIDs from SO_PEERCRED alone without verifying process start time (/proc/<pid>/stat) and inode creation time.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
3

SPIRE Agent attestors MUST query kernel cgroup file handles (e.g., via name_to_handle_at/open_by_handle_at) or SO_PEERCGROUP socket options to extract the immutable 64-bit cgroup ID.

SPIRE Agent attestors MUST query kernel cgroup file handles (e.g., via name_to_handle_at/open_by_handle_at) or SO_PEERCGROUP socket options to extract the immutable 64-bit cgroup ID.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
4

Services running SPIRE Agent MUST mount /sys/fs/cgroup as read-only and lock down the Workload API Unix Domain Socket with strict filesystem permissions (0770, root or spiffe group owned).

Services running SPIRE Agent MUST mount /sys/fs/cgroup as read-only and lock down the Workload API Unix Domain Socket with strict filesystem permissions (0770, root or spiffe group owned).

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
5

Attestation plugins MUST terminate the connection immediately if the caller's cgroup ID does not match an active, monitored container runtime cgroup or if the PID has recycled during resolution.

Attestation plugins MUST terminate the connection immediately if the caller's cgroup ID does not match an active, monitored container runtime cgroup or if the PID has recycled during resolution.

Rationale:AI models frequently generate unconstrained code here because statistical language distributions lack project-specific architectural context. Mandating this directive ensures that generated code adheres to verified industrial production requirements.
Enforcement:Integrated into the Agent Pack rule file. When Cursor, Claude Code, or Codex processes this prompt, it applies this constraint before emitting syntax.
Technical Questions & Answers

Frequently Asked Technical Questions

Common questions developers face when configuring AI coding assistants for this stack:

Q:Why is SPIFFE/SPIRE Linux Cgroup v2 Kernel Workload Attestation Guardrail critical for AI coding assistants?

Enforces kernel-level Cgroup v2 workload attestation across SPIRE agents and SPIFFE workload API endpoints, eliminating time-of-check to time-of-use (TOCTOU) and PID recycling race conditions inherent in naive Unix domain socket SO_PEERCRED lookups. Mandates the use of the unified cgroup v2 hierarchy, 64-bit cgroup ID verification via kernel file handles, and process start-time validation to prevent container workload impersonation. Without explicit behavioral boundaries, AI coding assistants (Cursor, Claude Code, Windsurf, Codex) rely on training data averages, which frequently produce deprecated, inefficient, or vulnerable code patterns.

Q:How does adopting this rule prevent AI hallucinations?

This rule explicitly declares what the AI must avoid (Relying on Unverified SO_PEERCRED PID Lookups and Ephemeral /proc Tree Traversal Subject to PID Recycling Attacks) and prescribes verified positive examples. Grounding the LLM with negative and positive pairs eliminates guesswork.

Q:Which AI coding environments are supported?

This specification is multi-platform compatible: Cursor (.cursor/rules/*.mdc & .cursorrules), Anthropic Claude Code (CLAUDE.md), Windsurf (.windsurfrules), Codex / Cline (AGENTS.md), and GitHub Copilot (.github/copilot-instructions.md).

Q:Can I combine this rule with other technology stacks?

Yes. Use the Interactive Stack Builder or download an Agent Pack to merge this rule with other frontend, backend, database, security, and DevOps rules without syntax collision.

Open Specification · CC BY 4.0·Free for Personal, Team & Commercial In-Repo Use

Citation & Open Source Attribution Guidelines

This specification is licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). You are completely free to adapt and share this rule in your workspace. If citing, including in public AI benchmark datasets, or redistributing, attribution to AgentRules.org is required.

1 Rule in Stack

SPIFFE/SPIRE