Documentation
¶
Index ¶
- Constants
- func AmbiguousRequestBodyReason(err error) string
- func CanonicalGID(s string) bool
- func ContainerNamespaceRef(mode string) (ref string, ok bool)
- func DockerBoolQueryValue(value string) bool
- func EvaluateWithBodyState(rules []*CompiledRule, r *http.Request) (Action, int, string, BodyState)
- func FoldedArrays(m map[string]any, key string) [][]any
- func FoldedObjects(m map[string]any, key string) []map[string]any
- func FoldedStringEquals(m map[string]any, key, want string) bool
- func FoldedStrings(m map[string]any, key string) []string
- func FormatBody(body map[string][]string) string
- func FormatQuery(query map[string][]string) string
- func GlobToRegexString(pattern string) string
- func HasVersionPrefix(p string) bool
- func InspectJSONValueKeys(v any) (repeated, divergent error)
- func IsBuildkitTunnelPath(normalizedPath string) bool
- func IsBuiltinRegistryAlias(host string) bool
- func IsCanonicalHostMountPath(source string) bool
- func IsHijackCandidatePath(method, normalizedPath string) bool
- func IsNumericUserSpec(user string) bool
- func IsPodmanVolumeListPath(normPath string) bool
- func IsPodmanVolumePrunePath(normPath string) bool
- func IsQualifiedCDIDevice(name string) bool
- func KnownPodmanBuildControl(name string) bool
- func LogEndpointOptionKeys() []string
- func MiddlewareWithOptions(rules []*CompiledRule, logger *slog.Logger, opts Options) func(http.Handler) http.Handler
- func NestedObject(decoded map[string]any, key string) (map[string]any, error)
- func NestedObjectPath(decoded map[string]any, keys ...string) (map[string]any, error)
- func NormalizePath(p string) string
- func NormalizePodmanRoutePath(p string) string
- func ParseExtraHost(entry string) (host, address string, ok bool)
- func ParseExtraHostPattern(entry string) (host, address string, ok bool)
- func PodmanVolumeFilterDenyReason(filters map[string][]string) (string, bool)
- func RejectDuplicateCaseVariantJSONKeys(body []byte) error
- func RejectDuplicateCaseVariantJSONKeysStrict(body []byte) error
- func RejectDuplicateCaseVariantJSONValue(v any) error
- func RejectRepeatedJSONKeys(body []byte) error
- func ResourceLimitGuardWithOptions(logger *slog.Logger, opts ResourceLimitGuardOptions) func(http.Handler) http.Handler
- func ResponseBodyLimit() int64
- func ResponseTooLargeMessage() string
- func SetResponseBodyLimit(n int64)
- func StampWorkloadCreateLabel(w http.ResponseWriter, r *http.Request, key, value string) error
- func SubmittedWorkloadLabels(w http.ResponseWriter, r *http.Request) (sets []map[string]string, applies bool, err error)
- func ValidContainerArchiveAllowedPath(value string) bool
- func ValidateBodyConstraints(body map[string][]string) error
- func ValidateQueryConstraints(query map[string][]string) error
- type Action
- type AllowedDeviceRequestEntry
- type ApprovalOptions
- type BindSourceRemapMutationOptions
- type BodyState
- type BuildOptions
- type BuildkitOptions
- type CompiledRule
- type ConfigOptions
- type ContainerArchiveOptions
- type ContainerCreateOptions
- type ContainerRemoveOptions
- type ContainerUpdateInspectFunc
- type ContainerUpdateInspectResult
- type ContainerUpdateOptions
- type DenialResponse
- type DenyResponseVerbosity
- type EndpointConfigOptions
- type ExecInspectFunc
- type ExecInspectResult
- type ExecOptions
- type ExecSessionRegistry
- type ExecSessionRegistryOptions
- type ExecTargetInspectFunc
- type ExecTargetInspectResult
- type ImageLoadOptions
- type ImagePullOptions
- type ImagePushOptions
- type ImageRemapMutationOptions
- type ImageTrustOptions
- type InjectLabelsMutationOptions
- type KeylessOptions
- type LibpodContainerCreateOptions
- type LibpodPlayKubeOptions
- type LibpodPodCreateOptions
- type LibpodUnscopeableRead
- type LibpodUnscopeableWrite
- type MutationOptions
- type MutationRuleOptions
- type NetworkExposureOptions
- type NetworkInspectFunc
- type NetworkInspectResult
- type NetworkOptions
- type NodeInspectFunc
- type NodeInspectResult
- type NodeOptions
- type OfflineBodyResult
- type OpaqueWorkload
- type Options
- type PluginOptions
- type Policy
- type PolicyConfig
- type ResourceLimitGuardOptions
- type Rule
- type SecretOptions
- type ServiceInspectFunc
- type ServiceInspectResult
- type ServiceOptions
- type SigningKeyOptions
- type SubmittedWorkload
- type SwarmOptions
- type VolumeOptions
Constants ¶
const ( // DefaultExecSessionTTL is how long an admitted exec session stays in the // registry without being used by its admitting profile. DefaultExecSessionTTL = time.Hour // DefaultExecSessionMaxEntries bounds the registry when no limit is given. DefaultExecSessionMaxEntries = 4096 )
const ( LibpodManifestExistsPath = "/libpod/manifests/sockguard-test/exists" LibpodManifestJSONPath = "/libpod/manifests/sockguard-test/json" )
LibpodManifestExistsPath and LibpodManifestJSONPath are representative normalized paths for Podman's two dynamic manifest-read route families. Podman routes both with `{name:.*}`, so LookupLibpodUnscopeableRead matches every non-empty name, including namespaced references, while these stable values name the families in the shared catalog and its policy tests.
const ( LibpodGenerateKubePath = "/libpod/generate/kube" LibpodKubeGeneratePath = "/libpod/kube/generate" )
const ( LibpodQuadletFilePath = "/libpod/quadlets/sockguard-test.container/file" LibpodQuadletExistsPath = "/libpod/quadlets/sockguard-test.container/exists" LibpodArtifactJSONPath = "/libpod/artifacts/sockguard-test/json" LibpodArtifactExtractPath = "/libpod/artifacts/sockguard-test/extract" LibpodQuadletReadDenyReason = "libpod quadlet read denied: unit files and their inventory carry no owner labels and have no per-unit isolation check" LibpodArtifactReadDenyReason = "libpod artifact read denied: artifact content and inventory have no owner-label or per-artifact isolation check" )
const ( LibpodQuadletsPath = "/libpod/quadlets" LibpodArtifactRemovePath = "/libpod/artifacts/remove" LibpodQuadletRemovePath = "/libpod/quadlets/sockguard-test.container" LibpodArtifactSingleRemovePath = "/libpod/artifacts/sockguard-test" LibpodArtifactPushPath = "/libpod/artifacts/sockguard-test/push" LibpodQuadletWriteDenyReason = "" /* 156-byte string literal not displayed */ LibpodArtifactRemoveDenyReason = "" /* 146-byte string literal not displayed */ LibpodArtifactWriteDenyReason = "libpod artifact write denied: artifacts have no owner-label scope or per-artifact ownership check" )
LibpodQuadletsPath and LibpodArtifactRemovePath are native batch writes registered by Podman v6.0.0's register_quadlets.go and register_artifacts.go.
const ( LibpodManifestWritePath = "/libpod/manifests/sockguard-test" LibpodVolumeRenamePath = "/libpod/volumes/sockguard-test/rename" LibpodManifestWriteDenyReason = "" /* 188-byte string literal not displayed */ LibpodVolumeRenameDenyReason = "" /* 141-byte string literal not displayed */ )
LibpodManifestWritePath and LibpodVolumeRenamePath are representative normalized paths for two dynamic write route families.
Podman registers every manifest list write under /libpod/manifests/{name:.*} (create, POST/PUT/DELETE {name}, {name}/add, {name}/registry/{destination:.*} and {name}/push), so the name is greedy and one prefix covers all seven. A manifest list is an image in Podman's store, but it is not one the ownership layer can check by path: create and add take image references in the query or body, push and registry send it to a caller-named destination, and a list carries no owner label that create could stamp. The reads on the same family are already refused for that reason, so the writes are too.
Volume rename (Podman 6.2) names the new volume in a parameter nothing here reads. Letting it through would move an owned volume onto a name chosen without a collision or ownership check against the other owners' volumes, so it is refused rather than half-checked.
const ( PodmanVolumeListPath = "/volumes" PodmanVolumeLibpodListPath = "/libpod/volumes/json" )
PodmanVolumeListPath and PodmanVolumeLibpodListPath are the normalized paths of the Docker-compat and native volume list routes.
const ( ReasonCodeMatchedDenyRule = reasonCodeMatchedDenyRule ReasonCodeMatchedHoldRule = reasonCodeMatchedHoldRule ReasonCodeNoMatchingAllowRule = reasonCodeNoMatchingAllowRule )
ReasonCodeMatchedDenyRule, ReasonCodeMatchedHoldRule and ReasonCodeNoMatchingAllowRule are the reason_code values the rule layer writes to the access log. They are exported for tooling that reads the log (sockguard policy suggest), which must tell a rule-layer miss, one an allow rule can fix, from every other guard's deny.
const ( ReasonCodeApprovalPending = reasonCodeApprovalPending ReasonCodeApprovalDenied = reasonCodeApprovalDenied ReasonCodeApprovalExpired = reasonCodeApprovalExpired ReasonCodeApprovalCancelled = reasonCodeApprovalCancelled ReasonCodeApprovalQueueFull = reasonCodeApprovalQueueFull ReasonCodeApprovalRateLimited = reasonCodeApprovalRateLimited ReasonCodeApprovalNotHoldable = reasonCodeApprovalNotHoldable ReasonCodeApprovalStale = reasonCodeApprovalStale ReasonCodeApprovedByOperator = reasonCodeApprovedByOperator )
The reason_code values of the operator-approval hold flow. They are exported for the admin API and for tooling that reads the log.
const ( // ApprovalOutcomeNotHoldable is a request that matched a hold rule but // cannot be held, and was denied without an ask. ApprovalOutcomeNotHoldable = "not_holdable" )
Outcomes ApprovalOptions.Observe is told about. The registry reports every other outcome itself.
const LibpodAutoUpdateDenyReason = "libpod auto-update denied: " +
"POST /libpod/autoupdate pulls and restarts every auto-update labeled systemd unit on the host and accepts no owner scope, " +
"so it cannot be scoped to one caller"
LibpodAutoUpdateDenyReason is reported when owner isolation refuses POST /libpod/autoupdate.
Podman's handler (pkg/api/handlers/libpod/autoupdate.go) runs the `podman auto-update` machinery: it checks every running, systemd-managed container carrying an auto-update label, pulls the image reference stored on it and restarts the whole systemd unit when the image changed. It accepts `authfile`, `dryRun` and `rollback`, so there is no argument that narrows it to one owner's containers, and a unit restart takes down every container in the unit, owned by the caller or not. The refusal is unconditional for the reason the pod prune one is. A caller under owner isolation updates one container by recreating it, which the ownership layer checks.
const LibpodAutoUpdatePath = "/libpod/autoupdate"
LibpodAutoUpdatePath is the normalized path of Podman's native POST /libpod/autoupdate endpoint.
const LibpodContainerStatsDenyReason = "libpod container stats denied: " +
"GET /libpod/containers/stats streams live resource usage keyed by container ID for every running " +
"container on the host, carries no labels, and accepts no filters, so it cannot be scoped to one caller"
LibpodContainerStatsDenyReason is reported when either middleware refuses GET /libpod/containers/stats.
The query struct in pkg/api/handlers/libpod/containers_stats.go at v5.8.1 is {Containers []string `schema:"containers"`; Stream bool; Interval int; All bool}. There is no `filters` member, so the label-filter injection that scopes /libpod/containers/json has nothing to attach to, and the report items are libpod/define.ContainerStats — AvgCPU, ContainerID, Name, PerCPU, CPU, CPUNano, CPUSystemNano, SystemNano, MemUsage, MemLimit, MemPerc, Network, BlockInput, BlockOutput, PIDs, UpTime, Duration — with no Labels field and no owner field, so neither the selector axes nor the name/image pattern axes have anything to read. Every entry does carry ContainerID and Name, so the stream is a live cross-owner enumeration on top of being a resource-usage disclosure.
The refusal covers the `containers=` spelling too, not just the bare enumeration. Checking each named container against the owner would be possible in principle — ownership already inspects a named container on every other libpod route — but nothing here does it, and half a check is worse than none: a request that named one owned container and one that was not would still be forwarded whole. Refusing the path is the honest shape until a per-name check exists. GET /libpod/containers/{name}/stats is the route that has one.
const LibpodContainerStatsPath = "/libpod/containers/stats"
LibpodContainerStatsPath is the normalized path of Podman's native collection-level GET /libpod/containers/stats endpoint. Registered at pkg/api/server/register_containers.go:1190 (v5.8.1) as VersionedPath("/libpod/containers/stats") → libpod.StatsContainer, versioned spelling only.
It is the collection endpoint, not the per-container one: with no `containers` parameter and all=false, abi.ContainerEngine.ContainerStats takes its `default:` branch and calls GetRunningContainers, so the plain request streams every running container on the host; all=true swaps that for GetAllContainers.
The per-container GET /libpod/containers/{name}/stats is a different route (register_containers.go:1157) and stays allowed, because {name} is an identifier the ownership and visibility layers already check. Podman's own swagger marks that route "DEPRECATED. This endpoint will be removed with the next major release. Please use /libpod/containers/stats instead." — so the only owner-scopeable spelling of a stats read is the one upstream intends to delete, which is worth knowing before building on it.
const LibpodGenerateKubeDenyReason = "libpod kube generation denied: " +
"GET /libpod/generate/kube resolves each name as a pod, container or volume with no owner check, " +
"and the generated YAML carries the resource definition including environment; " +
"no compound reference check scopes it to one caller"
LibpodGenerateKubeDenyReason explains the refusal of both kube generation spellings.
const LibpodGenerateSystemdDenyReason = "libpod systemd generation denied: " +
"the name may resolve to a pod or container and the generated units carry no labels; " +
"no compound reference check scopes the generated configuration to one caller"
LibpodGenerateSystemdDenyReason explains the refusal until a compound pod/container reference check can validate every resource represented by the generated units.
const LibpodGenerateSystemdPath = "/libpod/generate/sockguard-test/systemd"
LibpodGenerateSystemdPath represents Podman's dynamic systemd generation route.
const LibpodKubeDownDenyReason = "libpod kube down denied: " +
"DELETE /libpod/play/kube and /libpod/kube/play remove the pods, secrets and volumes named in a YAML body " +
"that is not parsed, so the request cannot be scoped to one caller"
LibpodKubeDownDenyReason is reported when owner isolation refuses kube down, DELETE /libpod/play/kube and its DELETE /libpod/kube/play alias.
Podman 5.8.6 serves both from one handler (pkg/api/server/register_kube.go:180-181), whose only query parameter is `force`. What it removes is named in the request body: the pods, secrets and volumes of a Kubernetes YAML (pkg/domain/infra/abi/play.go:1678-1819), which nothing in sockguard parses. So the request takes no `filters`, the URL names no resource to check an owner on, and a client can name another owner's pod, secret or volume in the YAML and have it removed.
The refusal is unconditional for the reason the pod prune one is. A caller under owner isolation removes its pods through DELETE /libpod/pods/{name}, which names a pod the ownership layer checks.
const LibpodManifestExistsDenyReason = "libpod manifest exists denied: " +
"GET /libpod/manifests/{name}/exists reveals whether a manifest list exists in local storage, carries no " +
"labels, and accepts no filters, so it cannot be scoped to one caller"
LibpodManifestExistsDenyReason is reported when either middleware refuses GET /libpod/manifests/{name}/exists. The endpoint reveals whether a manifest list exists in local storage but exposes no label or owner metadata and accepts no filter that could constrain the lookup.
const LibpodManifestJSONDenyReason = "libpod manifest inspect denied: " +
"GET /libpod/manifests/{name}/json returns local manifest content or fetches a caller-named remote " +
"manifest, carries no labels, and accepts no filters, so it cannot be scoped to one caller"
LibpodManifestJSONDenyReason is reported when either middleware refuses GET /libpod/manifests/{name}/json. Podman inspects a local manifest list when one exists, but falls back to fetching the caller-named reference from a registry when it does not. Neither response carries policy labels and the endpoint accepts no filter, so there is no narrower truthful response the ownership or visibility middleware can produce.
const LibpodPodPruneDenyReason = "libpod pod prune denied: " +
"POST /libpod/pods/prune removes every prunable pod on the host, accepts no filters at all, and reports " +
"what it removed only after removing it, so it cannot be scoped to one caller"
LibpodPodPruneDenyReason is reported when owner isolation refuses POST /libpod/pods/prune.
It is the one prune route in the libpod family with nothing to scope it by. The other four — containers, images, networks and volumes — document a `filters` query parameter that takes `label`, and Podman reads it through util.PrepareFilters in each handler, so the owner label is injected into them the same way it is into their Docker-compat twins. This endpoint documents no parameters at all, and pkg/api/handlers/libpod/pods.go's PodPruneHelper at v5.8.1 is two lines: it calls runtime.PrunePods(r.Context()) with no options and turns the result map into a report. There is no argument to narrow it with.
Forwarding it under owner isolation would delete every prunable pod on the host regardless of owner, so the refusal is unconditional and does not honor RequestMeta.AllowsPassThrough the way a request-side owner verdict does. Warn mode buys an operator a measurement of what enforcement would cost; there is no measurement to take after another tenant's pods are gone. A deployment that wants host-wide pod pruning runs it without owner isolation, or removes pods one at a time through DELETE /libpod/pods/{name}, which names a pod the ownership layer checks.
const LibpodPodPrunePath = "/libpod/pods/prune"
LibpodPodPrunePath is the normalized path of Podman's native POST /libpod/pods/prune endpoint. Registered at pkg/api/server/register_pods.go:81 (v5.8.1) as VersionedPath("/libpod/pods/prune") -> libpod.PodPrune, versioned spelling only.
const LibpodPodStatsDenyReason = "libpod pod stats denied: " +
"GET /libpod/pods/stats reports resource usage for every running pod on the host by default, carries no " +
"labels, and accepts no filters, so it cannot be scoped to one caller"
LibpodPodStatsDenyReason is reported when either middleware refuses GET /libpod/pods/stats.
The query struct in pkg/api/handlers/libpod/pods.go at v5.8.1 is {NamesOrIDs []string `schema:"namesOrIDs"`; All bool; Stream bool; Delay int} — again no `filters` member. The report items are pkg/domain/entities/types.PodStatsReport (CPU, MemUsage, MemUsageBytes, Mem, NetIO, BlockIO, PIDS, Pod, CID, Name), which carries no labels and no owner field; Pod, CID and Name identify the resource without saying whose it is, so filtering has nothing to decide on and the body is an enumeration.
Pods are the case where the gap is widest. A pod's labels live on the pod, not on this report, and libpodNeedsOwnerFilter can scope GET /libpod/pods/json because that endpoint does take `filters`. This one does not, so the same deployment that gets a correctly scoped pod LIST gets an unscoped pod STATS unless it is refused.
const LibpodPodStatsPath = "/libpod/pods/stats"
LibpodPodStatsPath is the normalized path of Podman's native GET /libpod/pods/stats endpoint. Registered at pkg/api/server/register_pods.go:351 (v5.8.1) as VersionedPath("/libpod/pods/stats") → libpod.PodStats, versioned spelling only.
A request that names nothing enumerates the whole host by design rather than by omission: entities.ValidatePodStatsOptions sets options.All = true when neither namesOrIDs, all nor latest is given, commented "Podman v1 compat: if nothing's specified get all running pods".
There is no per-pod counterpart to fall back to. Podman registers no /libpod/pods/{name}/stats route at all, which is why libpodPodIdentifier reserves "stats" alongside "json": the only spelling of a pod stats read is the collection one.
const LibpodSecretListDenyReason = "libpod secret list denied: " +
"GET /libpod/secrets/json accepts only name and id filters and answers 500 for any other key, so the label " +
"filter that scopes every other libpod list cannot be pushed upstream, and no response-side owner filter " +
"exists for its shape, so it cannot be scoped to one caller"
LibpodSecretListDenyReason is reported when either middleware refuses GET /libpod/secrets/json.
This entry is the exception the membership note at the top of this file names, and it is worth being precise about why. The report items are entities.SecretInfoReport (pkg/domain/entities/types/secrets.go at v5.8.1: ID, CreatedAt, UpdatedAt, Spec, SecretData), and Spec is a SecretSpec that DOES carry a Labels map. So unlike showmounted or either stats collection, a selector has a field it could read here, and a response-side filter of the GET /system/df kind could in principle scope this list.
What it cannot be is scoped UPSTREAM, which is what both isolation layers do for every other libpod list. Podman evaluates this endpoint's filters with utils.IfPassesSecretsFilter (pkg/domain/utils/secrets_filters.go at v5.8.1), whose switch accepts "name" and "id" and returns fmt.Errorf("invalid filter %q", key) on anything else. compat.ListSecrets turns that error into utils.InternalServerError, so the injected `label` key that scopes GET /libpod/containers/json does not merely fail to narrow this list, it turns every request into a 500. Injecting it was the behavior this refusal replaces.
That leaves forward-unfiltered or refuse, and forwarding is a cross-owner enumeration of every secret ID and name on the host. Refusing is the honest shape until a response-side filter over Spec.Labels exists, the same call LibpodContainerStatsDenyReason makes about the `containers=` spelling: half a check is worse than none. Implementing that filter is what would move this entry back out of the table.
const LibpodSecretListPath = "/libpod/secrets/json" // #nosec G101 -- a URL path, not a credential; "secrets" is Podman's route segment.
LibpodSecretListPath is the normalized path of Podman's native GET /libpod/secrets/json endpoint. Registered at pkg/api/server/register_secrets.go:72 (v5.8.1) as VersionedPath("/libpod/secrets/json") -> compat.ListSecrets, versioned spelling only.
const LibpodShowMountedDenyReason = "libpod show mounted denied: " +
"GET /libpod/containers/showmounted returns every mounted container on the host keyed by ID with the " +
"daemon host's mount path as the value, carries no labels, and accepts no filters, so it cannot be " +
"scoped to one caller"
LibpodShowMountedDenyReason is reported when either middleware refuses GET /libpod/containers/showmounted.
The endpoint is refused for the same reason /libpod/system/df is: the body cannot be classified per caller, not merely that filtering it was unimplemented. libpod.ShowMountedContainers at v5.8.1 walks runtime.GetAllContainers() and answers with a bare map[string]string of container ID to host mount point — no labels, no owner field, and no per-item envelope a selector could read. It accepts no query parameters at all, so the label-filter injection that scopes /libpod/containers/json has nothing to attach to either.
Two disclosures ride in that one body, and dropping either alone leaves the other. The values are absolute paths on the DAEMON HOST's filesystem (the container's storage mount point), which is the same class of detail redact_mount_paths exists to strip from an inspect response. The keys are the full container ID set of every mounted container on the host, regardless of owner, which is the enumeration owner isolation exists to deny. Redacting the values would still hand over the enumeration, and there is no field left to decide an entry by.
Emptying the map was rejected for the same reason an emptied /libpod/system/df report was: "no containers are mounted" is a legitimate answer from this endpoint, so a rewritten body is indistinguishable from the truthful one and would sell an isolation guarantee the shape cannot support. A refusal names the endpoint that could not be scoped.
const LibpodShowMountedPath = "/libpod/containers/showmounted"
LibpodShowMountedPath is the normalized path of Podman's native GET /libpod/containers/showmounted endpoint.
It has no Docker-compat counterpart at all — dockerd serves nothing at /containers/showmounted — so unlike /libpod/system/df there is no compat spelling of it that gets filtered normally instead. Only the versioned route is registered (pkg/api/server/register_containers.go at v5.8.1 wires VersionedPath("/libpod/containers/showmounted") to libpod.ShowMountedContainers), so a Podman binding issues /v5.8.1/libpod/containers/showmounted; NormalizePath strips the version prefix but not the /libpod segment, so that spelling normalizes here.
const LibpodSystemCheckDenyReason = "libpod system check denied: " +
"POST /libpod/system/check checks the host's storage and can repair it by removing damaged containers and images " +
"whoever owns them, so it cannot be scoped to one caller"
LibpodSystemCheckDenyReason is reported when owner isolation refuses POST /libpod/system/check.
It runs a storage consistency check over the whole host and can repair it, removing damaged containers and images whoever owns them, so it names no resource an owner check could inspect and cannot be scoped to one caller. The refusal is unconditional for the reason the pod prune one is.
const LibpodSystemCheckPath = "/libpod/system/check"
LibpodSystemCheckPath is the normalized path of Podman's native POST /libpod/system/check endpoint.
const LibpodSystemPruneDenyReason = "libpod system prune denied: " +
"POST /libpod/system/prune removes unused pods, containers, images and optionally volumes across the whole host in one call, " +
"so it cannot be scoped to one caller"
LibpodSystemPruneDenyReason is reported when owner isolation refuses POST /libpod/system/prune.
It prunes pods, containers and images in one call, and volumes too when the client asks for them. That is several resource types behind one handler, so the single optional `filters` parameter cannot be shown to scope every one of them to an owner label, and the removal has happened by the time the report comes back. The refusal is unconditional for the reason the pod prune one is. A caller under owner isolation prunes with the per-type routes (containers, images, networks, volumes), which the ownership layer scopes by injecting the owner label.
const LibpodSystemPrunePath = "/libpod/system/prune"
LibpodSystemPrunePath is the normalized path of Podman's native POST /libpod/system/prune endpoint.
const MaxResponseBodyBytes = 8 << 20 // 8 MiB
MaxResponseBodyBytes is the default upper bound for Docker API response bodies that sockguard inspects and optionally redacts. Responses larger than the limit in force are rejected to avoid unbounded memory allocation. The limit in force is ResponseBodyLimit, which response.max_buffered_body sets.
const MaxResponseBodyBytesCeiling = 256 << 20 // 256 MiB
MaxResponseBodyBytesCeiling is the largest response.max_buffered_body the config validator accepts. Every buffered response is held in memory, so the cap stays well under anything that could take the proxy down.
const PodmanCompatSecretListDenyReason = "compat secret list denied: " +
"this upstream is Podman, which serves GET /secrets from the same handler as GET /libpod/secrets/json; it " +
"accepts only name and id filters and answers 500 for any other key, so the label filter that scopes every " +
"other list cannot be pushed upstream, and no response-side owner filter exists for its shape, so it cannot " +
"be scoped to one caller"
PodmanCompatSecretListDenyReason is reported when either middleware refuses GET (or HEAD) /secrets because the upstream is Podman.
The shape argument is LibpodSecretListDenyReason's, verbatim, because it is the same handler. abi.SecretList runs every secret through utils.IfPassesSecretsFilter (pkg/domain/utils/secrets_filters.go at v5.8.1), whose switch accepts "name" and "id" and returns fmt.Errorf("invalid filter %q", key) on anything else, and compat.ListSecrets turns that error into utils.InternalServerError. So the `label` filter that owner isolation and visibility inject into every other list does not merely fail to narrow this one, it answers 500 for every request. That 500 is the behavior this refusal replaces.
Dropping the injection instead would forward a cross-owner enumeration of every secret ID and name on the host, which is the disclosure both layers exist to deny.
A response-side filter is the third option and is not taken here, for the reason LibpodSecretListDenyReason gives about its own path. The items do carry Spec.Labels — entities.SecretInfoReportCompat embeds entities.SecretInfoReport, whose Spec is a SecretSpec{Name, Driver, Labels}, so the compat body carries the same label map the libpod body does — and a filter of the GET /system/df kind could scope either. Building one for the compat spelling alone would leave one Podman handler answering 403 through its native path and a filtered list through its compat path off the same policy, which is exactly the drift the shared reason strings exist to prevent. Implementing that filter is what moves BOTH entries out, together.
A Docker upstream is untouched: dockerd's swarm secret list honors `label` conjunctively like every other list it serves, so the injection is correct there and neither layer consults this constant.
const PodmanCompatSecretListPath = "/secrets" // #nosec G101 -- a URL path, not a credential; "secrets" is the Docker API's route segment.
PodmanCompatSecretListPath is the normalized path of the Docker-compat secret list. It is the spelling every Docker client sends, and on a Podman upstream it is served by the same handler as GET /libpod/secrets/json: pkg/api/server/register_secrets.go at v5.8.1 wires VersionedPath("/secrets"), the bare "/secrets", and VersionedPath("/libpod/secrets/json") all onto compat.ListSecrets, which branches on utils.IsLibpodRequest only when it comes to writing the response envelope. The filter grammar is reached before that branch, so both spellings share it exactly.
const ReasonCodeRequestBodyAmbiguous = reasonCodeRequestBodyAmbiguous
ReasonCodeRequestBodyAmbiguous is the reason code a body is refused under for a key the engines' decoders could read two ways. Exported for the owner isolation layer, which finds such a key in the body it decodes and reports it the way the inspectors do.
const ReasonDivergentPathViews = "request path resolves to different routes under policy"
ReasonDivergentPathViews is the reason on a denial for a libpod image-SCP request whose canonical and encoded path views reach different rules while one of them is a hold. Such a request is not holdable, so it is denied.
const ReasonNoMatchingAllowRule = "no matching allow rule"
ReasonNoMatchingAllowRule is the human-readable reason stamped on the default-deny outcome (no rule matched). Exported so the reason-code classifier can compare against a constant rather than a magic string; changing this string requires updating both this constant and the downstream classifier.
Variables ¶
This section is empty.
Functions ¶
func AmbiguousRequestBodyReason ¶
AmbiguousRequestBodyReason words that refusal for err, the error one of the key checks returned.
func CanonicalGID ¶ added in v3.2.0
CanonicalGID reports whether s is a canonical numeric gid: ASCII digits only, no leading zeros except "0" itself, and within uint32.
func ContainerNamespaceRef ¶
ContainerNamespaceRef reports whether mode has the form "container:<ref>" — Docker's syntax for joining another container's network/PID/IPC/user namespace — and, if so, returns the trimmed ref. The "container:" prefix is matched case-insensitively (as Docker itself does); the ref's case is preserved, since container IDs and names are case-sensitive. An empty ref ("container:" alone, or all-whitespace after the prefix) is rejected. Exported so the ownership package can reuse this exact parser instead of duplicating it.
func DockerBoolQueryValue ¶ added in v3.2.0
DockerBoolQueryValue mirrors Moby's httputils.BoolValue. Docker treats only the five normalized values below as false and treats every other value as true. Podman's compat routes decode with NewCompatAPIDecoder, which registers a converter that copies this same function, so they agree on the spellings: no 400 on "no", "none" or "yes", and an empty value sets false.
func EvaluateWithBodyState ¶ added in v3.2.0
EvaluateWithBodyState is Evaluate plus the body state the rule walk used.
func FoldedArrays ¶
FoldedArrays returns every array value in m whose key case-folds to key.
func FoldedObjects ¶
FoldedObjects returns every object value in m whose key case-folds to key, in map-iteration order. Docker decodes duplicate case-variant keys and lets the last one win, so a read-side security check must inspect every variant rather than an exact-case single lookup.
func FoldedStringEquals ¶
FoldedStringEquals reports whether any string value in m whose key case-folds to key case-insensitively equals want (after trimming whitespace).
func FoldedStrings ¶
FoldedStrings returns every string value in m whose key case-folds to key.
func FormatBody ¶ added in v3.2.0
FormatBody renders body constraints in a stable, human-readable form for rule listings, e.g. `name=team-app-*`. Empty when there are none.
func FormatQuery ¶
FormatQuery renders the constraints in a stable, human-readable form for rule listings, e.g. `signal=USR1|SIGUSR1`. Empty when there are none.
func GlobToRegexString ¶
GlobToRegexString converts the sockguard glob dialect to a regex string. Kept as a thin re-export of glob.ToRegexString for callers that already depend on the filter package.
func HasVersionPrefix ¶
HasVersionPrefix reports whether p begins with a daemon API version prefix (e.g. "/v1.45/") that NormalizePath strips before rule matching. A rule pattern carrying such a prefix can never match real traffic — the request path is normalized first — so it is almost always an authoring mistake worth flagging. Thin wrapper over apipath.HasVersionPrefix.
func InspectJSONValueKeys ¶
InspectJSONValueKeys is RejectDuplicateCaseVariantJSONValue with its two refusals reported apart, for a caller that doesn't treat them alike.
repeated is a key an engine could read as given twice. A body re-marshaled through a map can't be forwarded with one, in any rollout mode: json.Marshal sorts the keys, and their order decides which of the two the engine honors. That is two sibling keys that case-fold together, which is the check this has always made, and two that lowercase together; see loweredSiblingKeys.
divergent is a key holding a decoder-divergent character. Re-marshaling leaves such a key and its value as the client sent them, so once repeated is nil the body can be forwarded or refused as the rollout mode says. Of several such keys it names the one that sorts first.
func IsBuildkitTunnelPath ¶
IsBuildkitTunnelPath reports whether normalizedPath is one of the two REAL h2c-upgrade-bearing BuildKit tunnel endpoints — POST /session or POST /grpc, the only two paths sockguard ever hijacks (see internal/buildkitproxy.Mediator and cmd/serve.go's withBuildkitMediator). Deliberately narrower than matchesBuildkitTunnelInspection above, which also matches the literal /moby.buildkit.v1.Control/* probe path: that path carries no upgrade at all (see buildkit.go's inspect doc comment below) and is never handed to the mediator, so it must not be reported here.
func IsBuiltinRegistryAlias ¶
IsBuiltinRegistryAlias reports whether host is one of the Docker Hub spellings the push policy always resolves to docker.io, or docker.io itself. Config validation uses it to refuse an operator alias that could never apply.
func IsCanonicalHostMountPath ¶
IsCanonicalHostMountPath reports whether a mount path is an absolute POSIX path in the exact form used by host mount authorization.
func IsHijackCandidatePath ¶
IsHijackCandidatePath reports whether method+normalizedPath is one of the connection-upgrade endpoints — Docker-compat or libpod — that internal/proxy's hijack layer must recognize identically to this package's own routing.
Thin wrapper over apipath.IsHijackCandidatePath, which owns the definition so both sides of the filter/proxy package split read one matcher rather than each keeping its own. The name stays here because internal/proxy already calls it, and because the cross-package parity invariant test in internal/proxy exercises the real production matchers through it.
func IsNumericUserSpec ¶ added in v3.2.0
IsNumericUserSpec reports whether user is a plain numeric uid or uid:gid, each part ASCII digits that fit an unsigned 32-bit id. It is stricter than the root check on purpose and does not trim: a padded " 1000", a signed "+1000", a name, an empty part, or a third ":" field is something the engine may resolve through the image's passwd or group file instead, so none of them count as numeric.
func IsPodmanVolumeListPath ¶
IsPodmanVolumeListPath reports whether normPath is a volume list route.
func IsPodmanVolumePrunePath ¶
IsPodmanVolumePrunePath reports whether normPath is a volume prune route.
func IsQualifiedCDIDevice ¶
IsQualifiedCDIDevice reports whether name is a fully qualified CDI device name (vendor/class=name).
func KnownPodmanBuildControl ¶
KnownPodmanBuildControl validates the exact, versioned query-key grants.
func LogEndpointOptionKeys ¶
func LogEndpointOptionKeys() []string
LogEndpointOptionKeys returns the destination option names, sorted, that allowed_log_endpoint_options may list.
func MiddlewareWithOptions ¶
func MiddlewareWithOptions(rules []*CompiledRule, logger *slog.Logger, opts Options) func(http.Handler) http.Handler
MiddlewareWithOptions returns HTTP middleware that evaluates each request against compiled rules and allows deny response detail to be configured.
func NestedObject ¶
NestedObject returns the object stored under key in decoded, creating it when absent. Key matching is case-INSENSITIVE and collision-collapsing: Docker decodes JSON object keys case-insensitively and, on duplicate case-variant keys, lets the last one win. A client could otherwise smuggle a lowercase "labels" alongside a proxy-injected "Labels" and — because json.Marshal emits map keys in sorted order, placing "labels" after "Labels" — have Docker prefer the client's forged value over the one the proxy verified. To close that spoof, every key that case-folds to key is merged into a single object stored under the exact canonical key, and all variant keys are removed, so the re-encoded body carries exactly one unambiguous key that Docker reads verbatim.
Exported so both the admission-mutation engine (mutation.go) and internal/ownership's owner-label stamping share one reviewed implementation instead of two independently-maintained copies of the same security-critical fold/merge logic.
func NestedObjectPath ¶
NestedObjectPath walks/creates a chain of nested objects via NestedObject, e.g. NestedObjectPath(decoded, "TaskTemplate", "ContainerSpec", "Labels").
func NormalizePath ¶
NormalizePath canonicalizes a request path into the form policy rules are matched against. It is a thin wrapper over apipath.NormalizePath, which owns the definition and documents why the path is never percent-decoded a second time; the name stays here because most of this package and five others outside it already call it.
func NormalizePodmanRoutePath ¶
NormalizePodmanRoutePath keeps the trailing slash that gorilla/mux includes in route matching while applying the same API-version and clean-path rules used for policy paths. It is a thin wrapper over apipath.NormalizePodmanRoutePath, which owns the definition and documents why that trailing slash is security-significant on Podman's anchored push/tag/untag routes; the name stays here because the rule evaluator and the ownership middleware both already call it.
This is the only path shape rule matching ever sees with a trailing slash, and every matcher kind treats that slash as a real, empty final segment. See matchGlobSegments for why the segment walker has to agree with the regex there rather than absorb the slash.
func ParseExtraHost ¶ added in v3.2.0
ParseExtraHost parses a request "host:address" entry. It splits on the first colon only, because an IPv6 address carries colons of its own. The host must be a plain hostname (see validExtraHostName) and the address an IP or host-gateway. Podman splits the host part on ";" into several names, so anything outside the hostname charset is malformed, not a glob. The returned address is canonical (netip form) so equivalent IPv6 spellings compare equal.
func ParseExtraHostPattern ¶ added in v3.2.0
ParseExtraHostPattern parses a configured allowed_extra_hosts entry: the same grammar as ParseExtraHost, with "*" also allowed in the host as a glob.
func PodmanVolumeFilterDenyReason ¶
PodmanVolumeFilterDenyReason reports whether a decoded volume filter set carries a key other than `label`, and if so the operator-facing reason.
Podman before 6.0 combines volume filters of different keys with OR (libpod/runtime_volume.go accumulates `include = include || filter(vol)`), so any extra key (driver, name, label!, until, dangling, ...) widens the result past an injected `label` selector, and on prune removes other owners' unused volumes. Callers apply this to old or unverified Podman versions; every endpoint must positively report a released version >=6 before the volume-filter capability bypasses this refusal.
func RejectDuplicateCaseVariantJSONKeys ¶
RejectDuplicateCaseVariantJSONKeys returns an error if body contains any JSON object with two sibling keys that case-fold to the same name (e.g. "HostConfig" and "hostconfig"). The daemon decodes object keys case-insensitively and lets the last duplicate win, whereas sockguard inspects a create/update body via a struct decode and then may re-marshal it (owner-label stamping, image-digest pinning) through a map whose keys json.Marshal re-sorts on the way out. That re-sort can move a shadow lowercase key into last position, so the daemon acts on a value the filter never checked — a bypass of every body-inspection rule. No legitimate Docker client emits duplicate case-variant keys, so any body that does is rejected fail-closed before it can be re-marshaled and forwarded.
Two keys that are byte-identical are rejected on the same grounds, and are the reason this walks the raw bytes instead of a decoded tree. A decode collapses "X" and "X" into one map entry, so the old tree-walking form could not see them at all — yet Go's struct decode MERGES the two objects under a repeated key while a re-marshal through map[string]json.RawMessage keeps only the last. That is the same split view the case-variant check exists to close: sockguard validates the union, the daemon receives the last one, and a body like {"HostConfig":{"Memory":N},"HostConfig":{}} passes require_memory_limit here and arrives at the daemon with no limit at all.
Every caller of this form (container-create and libpod-create image pinning, service image pinning, the resource-limit guard) decodes the same bytes again immediately afterwards into a shape this check cannot supply — map[string]json.RawMessage for the byte-preserving rewrites, a typed patch struct for the guard — so there is no decoded tree to share with them, and building a throwaway map[string]any here only to walk it doubles the parse. The scan below reads the body once and allocates nothing for a body without escaped object keys, up to the sibling count at which it swaps the pairwise duplicate check for a hashed one to stay linear — see caseVariantFoldFanoutLimit, which sits far above the widest object in the Docker API request types.
It deliberately validates only what it must to locate object keys correctly: a malformed body may be reported as a syntax error or walked past, because every caller re-parses the same bytes with encoding/json on the next line and rejects there. What it may never do is miss a duplicate in a body that parses.
It also refuses any object key, a data map's included, that holds a character the engines' JSON decoders don't all match to a field name the same way; see isDecoderDivergentKeyRune. And since readBoundedBody runs it through rejectAmbiguousBodyKeys, it now sees every body an inspector decodes, not only the ones about to be rewritten.
func RejectDuplicateCaseVariantJSONKeysStrict ¶ added in v3.2.0
RejectDuplicateCaseVariantJSONKeysStrict is RejectDuplicateCaseVariantJSONKeys with the data-map exemption withdrawn: a data map's sibling keys are weighed for repeats exactly as a struct level's are. The exemption exists for the inspectors, whose engines all read a map's keys the same way whatever the spelling; a body whose repeated keys sit only inside a data map forwards fine. The rule matcher promises something stricter — it will not guess at any body holding a repeated key — and weighs these bodies unread.
func RejectDuplicateCaseVariantJSONValue ¶
RejectDuplicateCaseVariantJSONValue is RejectDuplicateCaseVariantJSONKeys against a body that has already been decoded — same sibling fold-check, same data-map exemption, without parsing the same bytes a second time.
A caller that has to decode a body for its own reasons (internal/ownership decodes every create body it stamps an owner label into) would otherwise pay for a second full parse per request whose result it throws away. Decode with json.Decoder.UseNumber so the value handed here is the same shape the walk expects.
This form cannot see byte-identical duplicate keys, which the decode that produced v has already collapsed; only the byte-taking form above rejects those. It does refuse the same decoder-divergent key characters.
func RejectRepeatedJSONKeys ¶
RejectRepeatedJSONKeys checks the original bytes for repeated struct-level keys while leaving decoder-divergent keys to the caller's rollout policy.
func ResourceLimitGuardWithOptions ¶
func ResourceLimitGuardWithOptions(logger *slog.Logger, opts ResourceLimitGuardOptions) func(http.Handler) http.Handler
ResourceLimitGuardWithOptions returns the #152 resource-limit guard middleware. See the package-level doc comment above for placement and rationale.
func ResponseBodyLimit ¶
func ResponseBodyLimit() int64
ResponseBodyLimit returns the byte limit for buffered response bodies: response.max_buffered_body, or MaxResponseBodyBytes when it is unset.
func ResponseTooLargeMessage ¶
func ResponseTooLargeMessage() string
ResponseTooLargeMessage is the client-facing text for a response that was too big to buffer. It names the setting that governs the limit, because the alternative is a bare 502 and an operator guessing at what to raise.
func SetResponseBodyLimit ¶
func SetResponseBodyLimit(n int64)
SetResponseBodyLimit sets the buffered response body limit. A value that is not positive restores the default. The handler chain build calls it on startup and on every hot reload, so a reload applies a changed limit to the requests that follow it.
func StampWorkloadCreateLabel ¶ added in v3.2.0
StampWorkloadCreateLabel writes a proxy-managed label after admission has validated a Docker container, libpod container or libpod pod create.
func SubmittedWorkloadLabels ¶ added in v3.2.0
func SubmittedWorkloadLabels(w http.ResponseWriter, r *http.Request) (sets []map[string]string, applies bool, err error)
SubmittedWorkloadLabels returns the label maps a workload-creating request asks the daemon to store, so a caller's own client ACL can be compared with the ACL labels it is handing to a new workload. It covers POST /containers/create, POST /libpod/containers/create and the Swarm service create and update writes. A request that is none of those returns applies=false and is not read.
A service carries labels in two places. The task container's labels (TaskTemplate.ContainerSpec.Labels) are what the daemon stamps on every task container, so they are the ones a label ACL later trusts. The service's own labels are returned as well so neither spelling is left unexamined. The maps are returned separately because one label key may appear in both with different values.
The body is read with the same cap, ambiguous-key refusal and read deadline the policy inspectors use, and is put back so the rest of the chain sees the untouched request. Decoding goes through encoding/json, whose case-insensitive field match is the one the daemon applies, so a spelling the daemon would read as Labels is read here too. A body that cannot be read or decoded returns an error: the caller cannot tell what the daemon would store and has to fail closed.
func ValidContainerArchiveAllowedPath ¶ added in v3.2.0
ValidContainerArchiveAllowedPath reports whether an request_body.container_archive.allowed_paths entry normalizes to a usable container path. Config validation uses it so an unusable entry is rejected at startup and reload instead of being silently dropped.
func ValidateBodyConstraints ¶ added in v3.2.0
ValidateBodyConstraints reports why a rule's body constraint map cannot be compiled, or nil. Shared by the config validator and CompileRule so an authoring mistake gets the same wording wherever it is caught. Two names that fold to the same field are rejected with it: the matcher resolves a name case-insensitively, so two such keys would both address the single field the engine sees, and their patterns would AND across one value.
func ValidateQueryConstraints ¶
ValidateQueryConstraints reports why a rule's query constraint map cannot be compiled, or nil. The config validator and CompileRule share it so an authoring mistake is refused with the same wording wherever it is caught. The returned error names the offending key; callers prefix their own field path.
Types ¶
type Action ¶
type Action string
Action represents the result of a rule evaluation.
func EnforceReadExfiltrationAcknowledgment ¶
func EnforceReadExfiltrationAcknowledgment(action Action, method, normalizedPath string, acknowledged bool) (Action, string, bool)
EnforceReadExfiltrationAcknowledgment applies the hard process-list gate shared by the runtime middleware and offline rule matcher. normalizedPath must already be canonicalized with NormalizePath. The returned reason is non-empty only when the gate replaces an allow decision.
func Evaluate ¶
Evaluate evaluates a request against an ordered list of compiled rules. Returns the action and the matched rule index. If no rule matches, returns deny.
func EvaluateStatic ¶
EvaluateStatic evaluates rules the way the startup exposure analyses need: query and body constraints are ignored in the direction that over-reports. A constrained allow rule matches on method and path alone, and a constrained deny rule is skipped, so a conditional allow is never reported as unreachable and a conditional deny never shadows an allow.
type AllowedDeviceRequestEntry ¶
type AllowedDeviceRequestEntry struct {
Driver string
AllowedCapabilities [][]string
MaxCount *int
// DeviceIDs, when non-empty, pins the request to an exact set of device
// IDs (for example CDI names such as nvidia.com/gpu=0). Every ID in the
// request must equal a listed ID byte for byte, and a request with no IDs
// or with a non-zero Count (Docker rejects both together) is refused.
DeviceIDs []string
// Count, when non-nil, requires the request Count to equal it exactly.
Count *int
// Options, when non-empty, lists the only DeviceRequest Options entries a
// request may carry. Each request key and value must equal a listed pair
// byte for byte; a request with no Options still matches.
Options map[string]string
}
AllowedDeviceRequestEntry is the public wire type that operators populate in YAML to allowlist GPU/accelerator HostConfig.DeviceRequests entries.
type ApprovalOptions ¶ added in v3.2.0
type ApprovalOptions struct {
// Registry holds the asks. It is process-scoped and outlives chain
// rebuilds; each rebuilt chain gets the same one.
Registry *approvals.Registry
// Epoch is the policy epoch of the chain these options belong to. The
// registry refuses an ask from an epoch it has moved past.
Epoch uint64
// Wait is how long a held request blocks for a decision. Zero never
// blocks: the client gets approval_pending at once.
Wait time.Duration
// GrantTTL is only used to tell the client how long an approval waits for
// its retry.
GrantTTL time.Duration
// MaxBodyBytes is the largest request body a held request may carry.
MaxBodyBytes int64
// Principal names the client without its pid, so a retry from a new
// process is the same client. A failure makes the request not holdable.
Principal func(*http.Request) (string, error)
// IsStreaming reports an open-ended stream. filter cannot import proxy, so
// the caller passes proxy.MayStreamForApproval in. Nil treats
// nothing as streaming.
IsStreaming func(http.ResponseWriter, *http.Request) bool
// UpstreamIndex is the pinned upstream endpoint's index.
UpstreamIndex func(*http.Request) int
// PolicyVersion is the policy generation this chain was built for. It is
// stored on each ask so the audit records of its life name it.
PolicyVersion int64
// Gates names the checks that still run after an approval and have not
// run yet when the operator is asked, such as ownership.
Gates []string
// Observe is told about the outcomes only the filter knows. Optional.
Observe func(profile, outcome string)
}
ApprovalOptions turns on operator approval for requests that match a hold rule. Nil leaves hold rules as the plain denies they compile to.
type BindSourceRemapMutationOptions ¶
BindSourceRemapMutationOptions rewrites a bind-mount source prefix.
type BodyState ¶ added in v3.2.0
type BodyState struct {
// contains filtered or unexported fields
}
BodyState is the body witness the rule walk used for a request: whether a body was read at all and whether it parsed into readable fields. Reporting callers need it to tell a rule that matched its constraints from one that matched fail-closed over an unread body, and they must not reach for a second read to find out: the evaluation's own witness is the one that decided the request.
type BuildOptions ¶
type BuildOptions struct {
AllowedPodmanControls []string
PodmanUpstream bool
AllowRemoteContext bool
AllowHostNetwork bool
AllowRunInstructions bool
// AllowBlindWrites acknowledges Podman build controls that can expose
// host paths but do not have a narrower request_body.build policy.
AllowBlindWrites bool
}
BuildOptions configures request-body/query inspection for POST /build and POST /libpod/build.
type BuildkitOptions ¶
type BuildkitOptions struct {
// TunnelConfigured is true when the operator configured
// request_body.buildkit (top-level or on this client profile) — see
// config.BuildkitRequestBodyConfig and buildkitproxy.Policy.Configured.
TunnelConfigured bool
}
BuildkitOptions carries the ONE signal Phase 1 of issue #185 (BuildKit gRPC mediation) needs at the request-handling hot path: whether request_body.buildkit is configured for the active policy (global or a named client profile). It deliberately does NOT carry the richer buildkitproxy.Policy translation — Phase 1 ships no transport/mediator, so there is nothing here yet to make a per-field decision with. See buildkitPolicy.inspect below and cmd/rules.go's validateBuildkitTunnelRulesForPolicy for the startup-time half of this.
type CompiledRule ¶
type CompiledRule struct {
// Action is returned when this rule matches.
Action Action
// Reason is attached to the decision metadata when this rule matches.
Reason string
// Index is the original position of the source rule in the configured rule list.
Index int
// Hold is true for a rule configured as action: hold. Action is
// ActionDeny for those, so matching is deny-like: a constrained hold rule
// matches when its query or body cannot be evaluated, exactly as a deny
// rule does, and nothing can dodge it with an unreadable request.
Hold bool
// contains filtered or unexported fields
}
CompiledRule is a rule with pre-compiled matchers for efficient evaluation.
func CompileRule ¶
func CompileRule(r Rule) (*CompiledRule, error)
CompileRule compiles a Rule into a CompiledRule for efficient matching.
func ProjectHoldToAllow ¶ added in v3.2.0
func ProjectHoldToAllow(rules []*CompiledRule) []*CompiledRule
ProjectHoldToAllow returns rules with every hold rule read as an allow rule. The startup exposure analyses (body-blind writes, read exfiltration, BuildKit tunnels) use it: whatever an operator can approve must already be something the operator was allowed to configure as allow. The input is not modified; rules without a hold are shared, not copied.
func (*CompiledRule) HasBody ¶ added in v3.2.0
func (cr *CompiledRule) HasBody() bool
HasBody reports whether the rule carries body constraints.
func (*CompiledRule) HasQuery ¶
func (cr *CompiledRule) HasQuery() bool
HasQuery reports whether the rule carries query constraints.
func (*CompiledRule) HoldScopeHolds ¶ added in v3.2.0
func (cr *CompiledRule) HoldScopeHolds(rawQuery string, body []byte) bool
HoldScopeHolds reports whether a hold rule's query and body constraints still pass when read as an allow rule would read them. A hold rule matches like a deny rule so a request cannot dodge it with something unreadable, but an approval has to be scoped by what the operator can actually see: the body must have been readable, the constrained query keys must appear once each, and every occurrence must satisfy the rule. rawQuery and body are the request as it arrived. A rule that is not a hold never holds.
type ConfigOptions ¶
ConfigOptions configures request-body policy checks for POST /configs/create.
type ContainerArchiveOptions ¶
type ContainerArchiveOptions struct {
AllowedPaths []string
AllowSetID bool
AllowDeviceNodes bool
AllowEscapingLinks bool
}
ContainerArchiveOptions configures request-body/query inspection for PUT /containers/{id}/archive.
type ContainerCreateOptions ¶
type ContainerCreateOptions struct {
AllowedCommands [][]string
AllowedEntrypoints [][]string
AllowedEnvVars []string
DeniedEnvVars []string
AllowedEnvValues []string
// AllowedImages is an opt-in exact image reference allowlist.
AllowedImages []string
AllowPrivileged bool
AllowHostNetwork bool
AllowHostPID bool
AllowHostIPC bool
AllowedBindMounts []string
AllowMountSourceMutation bool
AllowAllDevices bool
AllowedDevices []string
AllowDeviceRequests bool
AllowedDeviceRequests []AllowedDeviceRequestEntry
AllowDeviceCgroupRules bool
AllowedDeviceCgroupRules []string
// AllowedGroupAdd lists the canonical numeric gids HostConfig.GroupAdd may
// carry; AllowedExtraHosts lists the host:address entries HostConfig.ExtraHosts
// may carry (host may be a glob, address matched exactly). Empty denies the
// field outright.
AllowedGroupAdd []string
AllowedExtraHosts []string
RequireNoNewPrivileges bool
RequireNonRootUser bool
// RequireNumericUser, under RequireNonRootUser, accepts only a numeric
// uid[:gid] User and denies a name: the engine resolves a name through the
// image's passwd file, which Sockguard can't read, so a non-root-looking
// name may still be UID 0. Default false keeps names accepted.
RequireNumericUser bool
RequireReadonlyRootfs bool
RequireDropAllCapabilities bool
AllowAllCapabilities bool
AllowedCapabilities []string
RequireMemoryLimit bool
RequireCPULimit bool
// RequireCPULimitHard narrows RequireCPULimit to accept only a genuine
// CPU-time cap (NanoCpus or CpuQuota); CpuShares alone does not satisfy
// it. Independent of RequireCPULimit — see hasHardCPULimit.
RequireCPULimitHard bool
RequirePidsLimit bool
AllowedSeccompProfiles []string
DenyUnconfinedSeccomp bool
AllowedAppArmorProfiles []string
DenyUnconfinedAppArmor bool
AllowHostUserNS bool
AllowHostCgroupNS bool
// AllowHostCgroupNSOnCgroupV1 allows CgroupnsMode "host" (not ns:<path>)
// only while UpstreamCgroupV1 is true. Ignored when AllowHostCgroupNS is
// already set.
AllowHostCgroupNSOnCgroupV1 bool
// UpstreamCgroupV1 is set by the serve layer from the startup GET /info
// probe: true only when every upstream endpoint reported CgroupVersion
// "1". It is not a config key.
UpstreamCgroupV1 bool
// UpstreamCgroupV1Func, when set, is read on every container create in
// place of UpstreamCgroupV1 so the serve layer can refresh the probe result
// (periodic re-probe, health change, hot reload) without rebuilding the
// policy. It must be safe for concurrent use and cheap.
UpstreamCgroupV1Func func() bool
// RestrictNamespaceSharing gates HostConfig.NetworkMode/PidMode/IpcMode/
// UTSMode/UsernsMode/CgroupnsMode values of the form "container:<ref>"
// (join another container's namespace) against
// AllowedNamespaceSharingContainers. Default false: container:<ref>
// values continue to pass through unchecked, matching today's behavior
// exactly — an independent, orthogonal gate from
// AllowHostNetwork/PID/IPC/UserNS/CgroupNS, which gate "host" and
// "ns:<path>". While true it also refuses "ns:<path>" on the same
// fields, since a path can name another container's namespace.
RestrictNamespaceSharing bool
// AllowedNamespaceSharingContainers allowlists the container:<ref>
// targets permitted when RestrictNamespaceSharing is true. Only
// consulted when RestrictNamespaceSharing is true; empty denies every
// container: ref. Mirrors the AllowDeviceRequests/AllowedDeviceRequests
// bool-escape-hatch-plus-allowlist shape, not AllowedRuntimes (which
// denies non-empty values by default) — this field defaults to
// pass-through, not deny-by-default.
AllowedNamespaceSharingContainers []string
// DenyNamespacePathMode denies HostConfig.NetworkMode values with an
// "ns:" prefix (case-insensitive) even when AllowHostNetwork is true.
// With AllowHostNetwork false the value is already refused, as
// "ns:<path>" is on every namespace mode whose host gate is off (see
// denyNamespacePathReason). Scoped to NetworkMode only. Default false.
DenyNamespacePathMode bool
RequiredLabels []string
// AllowedRuntimes allowlists HostConfig.Runtime values. An empty Runtime
// selects the daemon default and is always permitted; any other (non-empty)
// runtime is denied unless listed here. This prevents a client from silently
// selecting an alternate OCI runtime with different (or absent) seccomp/
// AppArmor defaults to escape the profile policy enforced for the default
// runtime. Runtime names are matched case-sensitively (as in daemon.json).
AllowedRuntimes []string
// AllowSysctls permits setting kernel parameters via HostConfig.Sysctls.
// Default false: any non-empty Sysctls map is denied.
AllowSysctls bool
// DenySelinuxDisable prevents label=disable (and label:disable) which
// turns off SELinux confinement for the container. Default false
// (pass-through) for backward-compatibility.
DenySelinuxDisable bool
// DenySelinuxLabelOverride denies label=user:, label=role:, label=type:,
// label=level: SecurityOpt entries that customize the SELinux context.
// Default false (pass-through). Independent of DenySelinuxDisable.
DenySelinuxLabelOverride bool
// DenyUnconfinedSystemPaths prevents systempaths=unconfined in SecurityOpt
// AND rejects any request that supplies MaskedPaths or ReadonlyPaths, empty
// or not (the direct-API equivalent of systempaths=unconfined). Default false
// for backward-compatibility.
DenyUnconfinedSystemPaths bool
// ImageTrust configures cosign-backed signature verification.
ImageTrust ImageTrustOptions
// AllowTmpfsPrivilegedOptions permits tmpfs mount options that re-enable
// exec/dev/suid semantics: "exec", "dev", "suid" in
// HostConfig.Tmpfs or HostConfig.Mounts[].TmpfsOptions.Options (Engine
// API 1.46+). Default false. Legacy comma-separated flags use Docker's
// last-wins ordering, so "exec,noexec" remains allowed.
AllowTmpfsPrivilegedOptions bool
// PodmanUpstream is set from the resolved upstream flavor, not from
// config. Podman leaves a tmpfs executable and gives /dev no default
// options, so on a Podman upstream with AllowTmpfsPrivilegedOptions off a
// tmpfs (HostConfig.Tmpfs) must carry the bare option noexec, and a /dev
// tmpfs noexec,nosuid,nodev, since Podman adds nosuid,nodev itself
// elsewhere. A Mounts tmpfs entry is refused outright, because Podman's
// compat handler drops its TmpfsOptions.Options. dockerd already defaults
// every tmpfs to noexec,nosuid,nodev.
PodmanUpstream bool
// AllowLogPath permits a HostConfig.LogConfig.Config key a Podman
// upstream reads as the container's log path. Default false. See
// denyLogPathReason.
AllowLogPath bool
// AllowRuntimeAnnotations permits HostConfig.Annotations keys under run.oci.
// (refused on every upstream, since dockerd forwards them to the OCI
// runtime) and the io.podman.annotations. keys Podman acts on (refused
// unless the upstream is known to be dockerd). Default false. See
// runtimeAnnotationsDenyReason.
AllowRuntimeAnnotations bool
// AllowedLogDrivers is an opt-in allowlist for HostConfig.LogConfig.Type
// (and a "driver" entry in LogConfig.Config, which a Podman upstream reads
// as the driver). Empty, the default, enforces nothing. An empty Type
// selects the daemon default and is always allowed. While it is set, the
// destination options in logEndpointOptionKeys (syslog-address and the
// like) are refused unless AllowedLogEndpointOptions lists them. See
// logDriverPolicy.
AllowedLogDrivers []string
AllowedLogEndpointOptions []string
// DockerUpstream is set when the upstream is known to be dockerd, which
// never rebuilds a mount into the comma-joined string a Podman upstream
// re-splits. It turns off the Podman-only comma refusal on HostConfig.Mounts
// fields (denyCompatMountFieldInjectionReason). The zero value keeps the
// refusal on, so a construction site that doesn't know the engine stays
// closed. The server sets it from the resolved upstream flavor.
DockerUpstream bool
// NetworkExposure holds the opt-in published-port and network gates. They
// run in the resource-limit guard, which can ask the daemon what a network
// reference resolves to. Zero value: unrestricted.
NetworkExposure NetworkExposureOptions
// AllowEndpointConfig permits static IP, MAC address, Links, and
// DriverOpts in NetworkingConfig.EndpointsConfig entries carried on
// POST /containers/create. Docker connects every entry here the same way
// POST /networks/*/connect does, so without this the same fields
// network.AllowEndpointConfig gates at connect time were an unchecked
// bypass via create's NetworkingConfig — put the same config on the
// primary network at create instead of a follow-up connect call, and it
// sailed through. Shares a single config knob
// (request_body.network.allow_endpoint_config) with the network
// inspector; see config.RequestBodyConfig.ToFilterOptions. Aliases are
// never gated regardless of this flag — see denyEndpointConfigReason.
AllowEndpointConfig bool
// EndpointConfig narrows AllowEndpointConfig into per-field gates (#186),
// cross-wired from request_body.network.endpoint_config the same way
// AllowEndpointConfig is cross-wired from request_body.network.allow_endpoint_config.
// Only consulted when AllowEndpointConfig is false.
EndpointConfig EndpointConfigOptions
}
ContainerCreateOptions configures request-body policy checks for POST /containers/create.
type ContainerRemoveOptions ¶
type ContainerRemoveOptions struct {
AllowForce bool
AllowRemoveVolumes bool
AllowRemoveLinks bool
}
ContainerRemoveOptions configures query inspection for container removal, including slash-bearing names used by Docker's legacy link-removal route. AllowForce and AllowRemoveVolumes also gate Podman's pod removal and kube down, which remove containers and their volumes.
type ContainerUpdateInspectFunc ¶
type ContainerUpdateInspectFunc func(ctx context.Context, id string) (ContainerUpdateInspectResult, bool, error)
ContainerUpdateInspectFunc looks up a container's current resource state by ID. found=false with err=nil means the container does not exist (404).
func NewDockerContainerUpdateInspectorWithRoundTripper ¶
func NewDockerContainerUpdateInspectorWithRoundTripper(rt http.RoundTripper) ContainerUpdateInspectFunc
NewDockerContainerUpdateInspectorWithRoundTripper returns a container resource-state inspector that issues its GET through the shared upstream RoundTripper (typically an *upstream.Resolver), so it follows the same active endpoint as the update request it guards under failover. Mirrors NewDockerExecInspectorWithRoundTripper's shape (exec.go).
type ContainerUpdateInspectResult ¶
type ContainerUpdateInspectResult struct {
// ID is the immutable container ID the daemon resolved the requested name
// to. The guard forwards the update to this ID, so the limits it judged are
// those of the container that receives the write. Empty when the daemon
// sent none, which the guard treats as an unusable lookup.
ID string
Memory int64
NanoCpus int64
CpuQuota int64
CpuPeriod int64
PidsLimit *int64
}
ContainerUpdateInspectResult carries the container-update-relevant subset of GET /containers/{id}/json's HostConfig.
type ContainerUpdateOptions ¶
type ContainerUpdateOptions struct {
AllowPrivileged bool
AllowAllDevices bool
AllowCapabilities bool
AllowRestartPolicy bool
AllowResourceUpdates bool
// AllowBlindWrites acknowledges native libpod update fields that cannot
// be constrained by the structured container-update gates. Runtime wiring
// supplies it from the global insecure_allow_body_blind_writes setting.
AllowBlindWrites bool
// RequireMemoryLimit/RequireCPULimit/RequireCPULimitHard/RequirePidsLimit
// are enforced by ResourceLimitGuard (resource_limit_guard.go), not by
// containerUpdatePolicy.inspect below — they revalidate the container's
// EFFECTIVE post-update resource state, which requires a daemon lookup
// that only runs post-ownership. They are carried on this struct purely
// so config.ContainerUpdateRequestBodyConfig.ToFilterOptions has a single
// destination field per config leaf; containerUpdatePolicy itself never
// reads them.
RequireMemoryLimit bool
RequireCPULimit bool
RequireCPULimitHard bool
RequirePidsLimit bool
}
ContainerUpdateOptions configures request-body policy checks for POST /containers/{id}/update.
type DenialResponse ¶
type DenialResponse struct {
Message string `json:"message"`
Method string `json:"method,omitempty"`
Path string `json:"path,omitempty"`
Reason string `json:"reason,omitempty"`
}
DenialResponse is the JSON body returned when a request is denied.
type DenyResponseVerbosity ¶
type DenyResponseVerbosity string
DenyResponseVerbosity controls how much detail filter denial responses include.
const ( // DenyResponseVerbosityVerbose includes request details in the denial response body. DenyResponseVerbosityVerbose DenyResponseVerbosity = "verbose" // DenyResponseVerbosityMinimal returns only a generic denial message. DenyResponseVerbosityMinimal DenyResponseVerbosity = "minimal" )
func ParseDenyResponseVerbosity ¶
func ParseDenyResponseVerbosity(value string) DenyResponseVerbosity
ParseDenyResponseVerbosity normalizes a configured deny verbosity value. Empty or unknown values default to DenyResponseVerbosityMinimal so the proxy never leaks the raw request path on an unknown or missing config — verbose is an explicit opt-in for rule authoring and dev work only.
type EndpointConfigOptions ¶
type EndpointConfigOptions struct {
// AllowStaticAddressing permits every field endpointHasStaticAddressFields
// checks: IPAMConfig.IPv4Address/IPv6Address and the deprecated top-level
// Gateway/IPAddress/IPPrefixLen/IPv6Gateway/GlobalIPv6Address/
// GlobalIPv6PrefixLen fields. Default false.
AllowStaticAddressing bool
// AllowLinkLocalIPs permits IPAMConfig.LinkLocalIPs, independent of
// AllowStaticAddressing. Default false.
AllowLinkLocalIPs bool
// AllowMACPinning permits MacAddress — shared by network connect's
// EndpointConfig and container-create's deprecated top-level MacAddress
// field (see container_create.go's denyRootMacAddressReason). Default false.
AllowMACPinning bool
// AllowGwPriority permits GwPriority (Engine API 1.55+). Default false.
AllowGwPriority bool
// DenyAliases denies Aliases when true. Inverted polarity (unlike every
// other field here) so a zero-value EndpointConfigOptions reproduces the
// historical, unconditional "Aliases always allowed" behavior exactly —
// see denyEndpointConfigReason's doc comment for why Aliases is never
// gated by default. config.EndpointConfigRequestBodyConfig exposes this
// to operators as allow_aliases (default true) and inverts it during
// ToFilterOptions.
DenyAliases bool
}
EndpointConfigOptions narrows AllowEndpointConfig into independent per-field gates on Docker's EndpointSettings object (#186), so an operator can admit a benign field (e.g. Aliases) without also admitting address pinning. Only consulted when AllowEndpointConfig is false — see denyEndpointConfigReason's precedence doc comment. Fields with no gate here (Links, DriverOpts) have no individual escape hatch: only AllowEndpointConfig: true can admit them, fail-closed by design.
type ExecInspectFunc ¶
ExecInspectFunc looks up an existing exec instance by id.
func NewDockerExecInspector ¶
func NewDockerExecInspector(upstreamSocket string) ExecInspectFunc
NewDockerExecInspector returns an exec inspector backed by the Docker unix socket. It is the single-local-socket shorthand; the multi-endpoint/remote path uses NewDockerExecInspectorWithRoundTripper.
func NewDockerExecInspectorWithRoundTripper ¶
func NewDockerExecInspectorWithRoundTripper(rt http.RoundTripper) ExecInspectFunc
NewDockerExecInspectorWithRoundTripper returns an exec inspector that issues its short JSON GET through the shared upstream RoundTripper (typically an *upstream.Resolver), so exec-identity inspection follows the same active endpoint as the exec-create/start it guards under failover.
func NewLibpodExecInspector ¶
func NewLibpodExecInspector(upstreamSocket string) ExecInspectFunc
NewLibpodExecInspector returns an exec inspector backed by the Podman unix socket, querying GET /libpod/exec/{id}/json rather than the Docker-compat GET /exec/{id}/json NewDockerExecInspector uses. It is the single-local-socket shorthand; the multi-endpoint/remote path uses NewLibpodExecInspectorWithRoundTripper. Both libpod and Docker-compat exec-start requests are checked against the SAME execPolicy/ExecOptions (#148 design doc decision C3) — this constructor only changes which upstream URL family the exec-start re-check queries, wired based on which path triggered the request (see execStartIdentifier).
func NewLibpodExecInspectorWithRoundTripper ¶
func NewLibpodExecInspectorWithRoundTripper(rt http.RoundTripper) ExecInspectFunc
NewLibpodExecInspectorWithRoundTripper is NewDockerExecInspectorWithRoundTripper's libpod-path counterpart: same failover-aware transport, GET /libpod/exec/{id}/json instead of GET /exec/{id}/json. Podman routes both URLs to the identical compat.ExecInspectHandler internally (confirmed against Podman's own route table, pkg/api/server/register_exec.go), so the response shape decoded here is byte-identical to the Docker-compat path — see execInspectResponse, shared by both constructors.
type ExecInspectResult ¶
type ExecInspectResult struct {
ContainerID string
Command []string
Privileged bool
User string
Env []string
// WorkingDir is the exec's WorkingDir override. Like Env it is populated
// only on the exec-create path: GET /exec/{id}/json does not report it.
WorkingDir string
}
ExecInspectResult captures the effective exec command metadata Docker stores after POST /containers/{id}/exec and returns from GET /exec/{id}/json.
Env and WorkingDir are populated only on the exec-create path: Docker's GET /exec/{id}/json ProcessConfig does not expose the exec's environment or working directory, so the exec-start re-check (inspectExisting) always leaves them empty. For a session created through this proxy that is safe rather than a gap — exec instances are immutable after creation (same reasoning already documented for Cmd/Privileged/User above inspectExisting), so there is nothing for a start-time re-check to catch that create-time didn't already see. A session created some other way, with a different policy or no proxy, carries no admission record, and start cannot read the Env or WorkingDir it was given.
type ExecOptions ¶
type ExecOptions struct {
AllowPrivileged bool
AllowRootUser bool
// AllowedUsers, when non-empty, pins the exec User to these exact values.
// Each entry is trimmed; the request's User is compared byte for
// byte and case-sensitively, so a padded User never matches and "app" does not admit "app:wheel" and "1000" does not
// admit "01000". The empty string is a real entry meaning "User unset":
// Docker then runs the exec as the container's configured user. It is
// checked in addition to AllowRootUser, not instead of it. Default empty
// means no pin.
AllowedUsers []string
// RequireNumericUser accepts only a numeric uid[:gid] exec User wherever
// AllowRootUser:false or AllowedUsers would otherwise judge it by name, and
// denies a name: the engine resolves it through the target image's passwd
// file, which Sockguard can't read, so a non-root-looking name may still be
// UID 0. An unset User is left to those two checks. Default false keeps
// names accepted.
RequireNumericUser bool
// AllowedCommands is an allowlist of exec argv templates. Each token is a
// sockguard glob (see internal/glob): "*" matches a run of non-slash
// characters, "**" matches any sequence. A command is allowed when its
// token count equals an entry's and every token matches the glob at that
// position. Empty (the default) denies every exec unless AllowBlindWrites
// is also set.
AllowedCommands [][]string
// AllowedEnvVars, when non-empty, restricts the exec-create Env array to
// these variable names. Matching is by name only — the substring before
// the first "=" in each Env entry — exact string comparison,
// case-sensitive; the value is never inspected. Default empty means no
// restriction: unlike AllowedCommands, an empty AllowedEnvVars does NOT
// deny all Env content — this is a deliberate zero-behavior-change
// default, since enabling exec command allowlisting should not also
// silently start denying every exec session's environment.
AllowedEnvVars []string
// DeniedEnvVars variable names are always blocked and are checked before
// AllowedEnvVars, so a name present in both lists is denied — fail
// closed on operator misconfiguration. Default empty means nothing is
// blocked.
DeniedEnvVars []string
// AllowedEnvValues pins selected variables to exact NAME=VALUE entries.
// When at least one entry is configured for a name, every occurrence of
// that name must exactly match one of those entries. Values are never
// included in denial reasons or logs. Default empty means no value checks.
AllowedEnvValues []string
// AllowBlindWrites wires the top-level insecure_allow_body_blind_writes
// config flag: when true AND AllowedCommands is empty, exec create/start
// is no longer hard-denied purely for lacking a command allowlist. This
// ONLY lifts the "no commands are allowlisted" gate — AllowPrivileged,
// AllowRootUser, and the AllowedEnvVars/DeniedEnvVars gates below still
// apply exactly as configured, matching the documented scope of the
// blind-write opt-in (it acknowledges "we cannot pin the argv", not "skip
// every other exec check"). When AllowedCommands is non-empty this field
// has no effect: an operator who pinned commands is inspecting the body,
// so the blind-write concern the flag addresses does not apply.
AllowBlindWrites bool
InspectStart ExecInspectFunc
InspectTarget ExecTargetInspectFunc
// InspectStartLibpod is InspectStart's counterpart for the libpod
// exec-start path (POST /libpod/exec/{id}/start). It exists as a
// separate field — rather than reusing InspectStart for both routes —
// because the two constructors issue their upstream GET against
// different URL families (GET /exec/{id}/json vs.
// GET /libpod/exec/{id}/json); which one a given exec-start request
// needs is decided by which path triggered it, not by anything
// ExecInspectFunc's (context, id) signature carries. The exec-create
// side needs no such split: it never calls upstream, it decodes the
// POST body directly (see inspectCreate), and libpod exec-create bodies
// decode with the identical Go handler Docker-compat exec-create bodies
// do (#148 design doc decision C3) — see isLibpodExecCreatePath's
// call site in inspect below.
InspectStartLibpod ExecInspectFunc
// contains filtered or unexported fields
}
ExecOptions configures request-body policy checks for exec creation/start.
type ExecSessionRegistry ¶ added in v3.2.0
type ExecSessionRegistry struct {
// contains filtered or unexported fields
}
ExecSessionRegistry remembers the exec sessions this proxy admitted and the client profile each was admitted under. Docker's GET /exec/{id}/json omits the session's Env and WorkingDir, so an exec start cannot be re-checked against what the create carried. With the registry enabled, start and resize only proceed for a session that this process saw created through the filter by the same profile, which is what makes the create-time Env check binding.
The registry is in memory and per process: a restart empties it, and a session created through another sockguard instance, or straight against the daemon, is unknown here and is refused. That is the documented tradeoff of the opt-in.
It is bounded by MaxEntries and a sliding TTL, and safe for concurrent use. A nil *ExecSessionRegistry is valid and means the feature is off.
func NewExecSessionRegistry ¶ added in v3.2.0
func NewExecSessionRegistry(opts ExecSessionRegistryOptions) *ExecSessionRegistry
NewExecSessionRegistry builds an empty registry.
func (*ExecSessionRegistry) Admit ¶ added in v3.2.0
func (r *ExecSessionRegistry) Admit(id, profile string)
Admit records id as created by profile, evicting expired entries first and then the least recently used one when the registry is full.
func (*ExecSessionRegistry) Authorize ¶ added in v3.2.0
func (r *ExecSessionRegistry) Authorize(id, profile string) bool
Authorize reports whether id was admitted under profile and has not expired. A successful check renews the entry's TTL; a failed one changes nothing.
func (*ExecSessionRegistry) Len ¶ added in v3.2.0
func (r *ExecSessionRegistry) Len() int
Len reports how many live sessions are tracked.
func (*ExecSessionRegistry) ModifyResponse ¶ added in v3.2.0
func (r *ExecSessionRegistry) ModifyResponse(resp *http.Response) error
ModifyResponse records the session ID of a successful exec create. It is meant to run in the reverse proxy's response hook, before the response reaches the client, so an ID the client can use is always already recorded. It never fails the response: a body it cannot read or parse records nothing, and the client's later start is then refused.
type ExecSessionRegistryOptions ¶ added in v3.2.0
type ExecSessionRegistryOptions struct {
// TTL is how long an entry lives without a successful use. Each admitted
// start or resize renews it. Zero or negative selects DefaultExecSessionTTL.
TTL time.Duration
// MaxEntries bounds the registry. When it is full the least recently used
// entry is evicted to make room. Zero or negative selects
// DefaultExecSessionMaxEntries.
MaxEntries int
// ResolveProfile names the client profile of a request, the same function
// the filter middleware uses to select a policy. Nil means every request
// is the one unnamed default profile.
ResolveProfile func(*http.Request) (string, bool)
// Now overrides the clock for tests. Nil means time.Now.
Now func() time.Time
}
ExecSessionRegistryOptions configures NewExecSessionRegistry.
type ExecTargetInspectFunc ¶
ExecTargetInspectFunc resolves an exec target and its protection label.
func NewExecTargetInspectorWithRoundTripper ¶
func NewExecTargetInspectorWithRoundTripper(rt http.RoundTripper) ExecTargetInspectFunc
NewExecTargetInspectorWithRoundTripper reads target labels from the daemon. Podman exposes this compatibility inspect route for native exec targets too.
type ExecTargetInspectResult ¶
type ExecTargetInspectResult struct {
ContainerID string
Protected bool
// ConfigUser is the container's configured Config.User. Docker stores it
// as the User of any exec created without one, so the exec-start re-check
// reads it back to tell "unset" from an explicit user.
ConfigUser string
}
ExecTargetInspectResult identifies the container whose exec policy was read.
type ImageLoadOptions ¶
type ImageLoadOptions struct {
AllowAllRegistries bool
AllowOfficial bool
AllowedRegistries []string
AllowUntagged bool
// AllowBlindWrites wires the top-level insecure_allow_body_blind_writes
// acknowledgment, which is the only thing that admits
// POST /libpod/local/images/load — the archive-by-daemon-host-path
// variant this policy cannot read. It is not part of a request_body
// block; internal/cmd/serve.go's attachRuntimeInspectors sets it, the
// same way it does for BuildOptions and ExecOptions.
AllowBlindWrites bool
// OwnerLabelKey is the label owner isolation reads an image's owner from.
// Set only when ownership is active: the inspector then reads that label
// out of every image config the archive carries and hands the values to
// the ownership layer on the request metadata. Empty reads nothing.
OwnerLabelKey string
}
ImageLoadOptions configures request-body inspection for POST /images/load and its libpod counterpart POST /libpod/images/load.
type ImagePullOptions ¶
type ImagePullOptions struct {
AllowImports bool
AllowAllRegistries bool
AllowOfficial bool
AllowedRegistries []string
// PodmanUpstream is set from the resolved upstream flavor, not from
// config. An unqualified name is Docker Hub on dockerd. On Podman it is
// resolved through registries.conf, which sockguard cannot read, so a
// registry restriction cannot be applied to it and it is refused. The
// native libpod pull route is Podman by definition and always behaves this
// way. The zero value is dockerd.
PodmanUpstream bool
}
ImagePullOptions configures query inspection for POST /images/create.
type ImagePushOptions ¶
type ImagePushOptions struct {
// AllowedRegistries are bare registry hosts a push may target.
AllowedRegistries []string
// RegistryAliases maps a host a client may name to the host the daemon
// actually reaches for it (a registries.conf mirror, a split-horizon name).
// The target is what AllowedRegistries is checked against. Single level
// only: a target is never itself looked up again.
RegistryAliases map[string]string
// PodmanUpstream is set from the resolved upstream flavor, not from
// config. An unqualified name is Docker Hub on dockerd. On Podman it is
// resolved through registries.conf, which sockguard cannot read, so it is
// refused there. The zero value is dockerd, like every other flavor flag.
PodmanUpstream bool
}
ImagePushOptions configures the registry allowlist for image, plugin and manifest pushes (request_body.image_push).
The policy is active only when AllowedRegistries is non-empty. An inactive policy inspects nothing, which is the behavior before this option existed: pushes stay gated by insecure_allow_read_exfiltration and owner isolation.
type ImageRemapMutationOptions ¶
ImageRemapMutationOptions rewrites a matched image reference.
type ImageTrustOptions ¶
type ImageTrustOptions struct {
// Mode is "off" | "warn" | "enforce". Default: off.
Mode string
// AllowedSigningKeys lists PEM-encoded public keys trusted to sign images.
AllowedSigningKeys []SigningKeyOptions
// AllowedKeyless lists Fulcio-backed identity patterns.
AllowedKeyless []KeylessOptions
// RequireRekorInclusion requires a Rekor tlog entry for keyless bundles.
RequireRekorInclusion bool
// VerifyTimeout overrides the default end-to-end image-trust deadline.
VerifyTimeout string
// AllowAllRegistries permits signature discovery against any registry the
// client names.
AllowAllRegistries bool
// AllowOfficial permits Docker Hub official images (docker.io/library/*).
AllowOfficial bool
// AllowedRegistries lists registry hosts signature discovery may contact.
AllowedRegistries []string
}
ImageTrustOptions configures cosign signature verification for images referenced in POST /containers/create.
type InjectLabelsMutationOptions ¶
InjectLabelsMutationOptions unconditionally sets/replaces the configured labels on every request matching the rule's surfaces.
type KeylessOptions ¶
KeylessOptions is one allowed keyless identity entry.
type LibpodContainerCreateOptions ¶
type LibpodContainerCreateOptions struct {
AllowedCommands [][]string
AllowedEntrypoints [][]string
AllowedEnvVars []string
DeniedEnvVars []string
AllowedEnvValues []string
// AllowedImages is an opt-in exact image reference allowlist.
AllowedImages []string
AllowPrivileged bool
// AllowHostNetwork/PID/IPC/UserNS/UTS/CgroupNS each permit that
// namespace object's nsmode "host" and "path", and while false refuse
// any nsmode this package doesn't know (see libpod_namespace.go).
AllowHostNetwork bool
AllowHostPID bool
AllowHostIPC bool
AllowHostUserNS bool
AllowHostUTS bool
AllowHostCgroupNS bool
AllowedBindMounts []string
AllowMountSourceMutation bool
AllowAllDevices bool
AllowedDevices []string
// AllowedGroupAdd and AllowedExtraHosts gate groups and hostadd, same
// grammar as container_create's. Empty denies the field outright.
AllowedGroupAdd []string
AllowedExtraHosts []string
// RestrictNamespaceSharing gates netns/pidns/ipcns/userns/utsns/cgroupns
// objects of the form {"nsmode":"container","value":"<ref>"} (join another
// container's namespace) against AllowedNamespaceSharingContainers.
// Default false: such values pass through unchecked, mirroring
// ContainerCreateOptions.RestrictNamespaceSharing's default exactly.
// While true it also refuses nsmode "path" on the same fields.
RestrictNamespaceSharing bool
AllowedNamespaceSharingContainers []string
AllowAllCapabilities bool
AllowedCapabilities []string
AllowedSeccompProfiles []string
DenyUnconfinedSeccomp bool
AllowedAppArmorProfiles []string
DenyUnconfinedAppArmor bool
DenySelinuxDisable bool
RequireNonRootUser bool
// RequireNumericUser, under RequireNonRootUser, accepts only a numeric
// uid[:gid] User and denies a name: the engine resolves a name through the
// image's passwd file, which Sockguard can't read, so a non-root-looking
// name may still be UID 0. Default false keeps names accepted.
RequireNumericUser bool
RequireReadonlyRootfs bool
RequireMemoryLimit bool
RequireCPULimit bool
// RequireCPULimitHard narrows RequireCPULimit to accept only a genuine
// CPU-time cap (resource_limits.cpu.quota); shares alone does not
// satisfy it — mirrors ContainerCreateOptions.RequireCPULimitHard.
RequireCPULimitHard bool
RequirePidsLimit bool
AllowSysctls bool
// ImageTrust configures cosign-backed signature verification, reusing
// the identical machinery container_create.go uses against the "image"
// field.
ImageTrust ImageTrustOptions
// AllowSystemdMode permits POST /libpod/containers/create with a
// "systemd" value other than "false" (SpecGenerator's own default, sent
// even when --systemd was never passed on the CLI — see
// testdata/libpod/basic_create.json — is "true"). systemd=true/always
// enables Podman's systemd-aware mount/cgroup elevation for the
// container's init process; there is no Docker Engine API analog.
// Default false: every create is denied unless the body explicitly
// carries "false" or this is set.
AllowSystemdMode bool
// AllowCustomIDMappings permits a non-default idmappings.UIDMap/GIDMap
// or AutoUserNs (podman --uidmap/--gidmap/--userns=auto). A blunt gate
// for v1.6 — no range-overlap or host-UID-collision analysis; see the
// design doc's "Deferred past v1.6" list. Default false.
AllowCustomIDMappings bool
// AllowLogPath permits log_configuration.path and a healthLogDestination
// that names a directory, the two log destinations a create can put on
// the daemon host. Default false. See denyLogPathReason.
AllowLogPath bool
// NetworkExposure holds the opt-in published-port and network gates. They
// run in the resource-limit guard, which can ask the daemon what a network
// reference resolves to. Zero value: unrestricted.
NetworkExposure NetworkExposureOptions
// AllowedLogDrivers and AllowedLogEndpointOptions are the libpod
// spelling of the same-named ContainerCreateOptions fields, checked
// against log_configuration.driver and .options. Default empty: off.
AllowedLogDrivers []string
AllowedLogEndpointOptions []string
// AllowTmpfsPrivilegedOptions permits mounts[] entries of type tmpfs whose
// options end with exec, dev or suid enabled. Last option wins, as it does
// for ContainerCreateOptions.AllowTmpfsPrivilegedOptions. Default false.
AllowTmpfsPrivilegedOptions bool
// AllowedRuntimes allowlists oci_runtime values, mirroring
// ContainerCreateOptions.AllowedRuntimes: an empty oci_runtime selects
// the daemon default and is always permitted.
AllowedRuntimes []string
// AllowDeviceCgroupRules/AllowedDeviceCgroupRules gate device_cgroup_rule,
// and AllowDeviceRequests gates gpus, each mirroring the same-named
// ContainerCreateOptions field. There is no structured form for gpus
// (the body carries no driver, count or capability sets to match an
// AllowedDeviceRequests entry against), so only the blanket opt-in
// permits it.
AllowDeviceCgroupRules bool
AllowedDeviceCgroupRules []string
AllowDeviceRequests bool
// AllowedGPUs is the exact-match allowlist for gpus entries and
// AllowedCDIDevices the one for fully qualified CDI names in the
// top-level devices array. Both are compared byte for byte; AllowDeviceRequests
// and AllowAllDevices remain the blanket opt-ins that skip them.
AllowedGPUs []string
AllowedCDIDevices []string
// DenyUnconfinedSystemPaths denies unmask, the libpod spelling of
// systempaths=unconfined. Mirrors ContainerCreateOptions.
DenyUnconfinedSystemPaths bool
// AllowUnifiedCgroupSettings permits a non-empty "unified" map, raw
// cgroup v2 knobs written straight into the container's cgroup. Default
// false. See denyUnifiedCgroupReason.
AllowUnifiedCgroupSettings bool
// AllowEnvHost permits "env_host": true, which copies the Podman
// daemon's own environment into the container. Default false. See
// denyEnvHostReason.
AllowEnvHost bool
// AllowStorageOpts permits a non-empty "storage_opts" map. Default false.
// See denyStorageOptsReason.
AllowStorageOpts bool
// AllowRuntimeAnnotations permits "annotations" keys under run.oci.
// Default false. See denyRuntimeAnnotationsReason.
AllowRuntimeAnnotations bool
}
LibpodContainerCreateOptions configures request-body policy checks for POST /libpod/containers/create. Field names mirror ContainerCreateOptions where the underlying semantics map onto a libpod equivalent, so operator knowledge transfers between the Docker-compat and native surfaces; two fields (AllowSystemdMode, AllowCustomIDMappings) have no Docker analog, and AllowHostUTS has no compat option to mirror, because the compat create refuses a host UTS namespace unconditionally.
type LibpodPlayKubeOptions ¶
type LibpodPlayKubeOptions struct {
// AllowedLogDrivers allowlists the logDriver query parameter, and
// AllowedLogEndpointOptions lists the destination options the logOptions
// parameter may carry. Default empty: off. An absent logDriver selects
// the daemon default and is always allowed. See logDriverPolicy.
AllowedLogDrivers []string
AllowedLogEndpointOptions []string
}
LibpodPlayKubeOptions configures query checks for POST /libpod/play/kube and its /libpod/kube/play alias.
The YAML body is opaque to sockguard, which is why the route also sits in the blind-write catalog. Only the two query parameters that pick the log driver for every container the YAML creates are inspected here, so this block never counts as body inspection for that catalog.
type LibpodPodCreateOptions ¶
type LibpodPodCreateOptions struct {
// AllowHostNetwork permits a pod-level NetNS of {"nsmode":"host"} — the
// pod (and every container that joins it) shares the host network
// namespace — or of {"nsmode":"path"}, which joins whatever network
// namespace the path names. While false, an nsmode this package doesn't
// know is refused too. Mirrors container_create.AllowHostNetwork's
// posture for the pod-wide equivalent. Default false.
AllowHostNetwork bool
// AllowHostPID/IPC/UserNS/UTS each permit that namespace object's nsmode
// "host" and "path" on the pod, and while false refuse any nsmode this
// package doesn't know (see libpod_namespace.go). The pod's pidns, ipcns,
// userns and utsns are the infra container's, and a container that
// joins the pod can end up in them. PodSpecGenerator has no cgroupns
// field, so there is no cgroup gate here. Default false.
AllowHostPID bool
AllowHostIPC bool
AllowHostUserNS bool
AllowHostUTS bool
// list, letting every container in the pod see (and signal) every other
// container's processes — the pod-wide analog of container_create's
// PidMode: host, scoped to the pod rather than the host. Default false.
AllowSharedPIDNamespace bool
// AllowedInfraImageRegistries allowlists the registry the pod's
// infra_image reference resolves to, reusing the same host-allowlist
// shape as ImagePullOptions.AllowedRegistries (see normalizeRegistryHost
// / parseImageReference in image_pull.go). An empty infra_image
// (Podman's built-in default pause image) is always allowed regardless
// of this list. Default empty: any explicit infra_image is denied.
AllowedInfraImageRegistries []string
// Container is the libpod_container_create policy the pod's inherited
// host-affecting fields (mounts, pod_devices, security_opt, sysctl, and
// a container-joined namespace) are held to. The infra container and
// every member inherit them, so they get the container create gates, not
// a second set of lists. Its ImageTrust is not read here.
Container LibpodContainerCreateOptions
}
LibpodPodCreateOptions configures request-body policy checks for POST /libpod/pods/create — Podman's native pod-create endpoint. Pods have no Docker-compat equivalent, so this is its own inspector rather than an extension of container_create. See #148 and the design doc's C6 note on what is deliberately NOT covered here yet.
type LibpodUnscopeableRead ¶
type LibpodUnscopeableRead struct {
// Path is the normalized request path, i.e. what NormalizePath returns.
// It strips the API version prefix but not the /libpod segment, so a
// Podman binding's /v5.8.1/libpod/... spelling normalizes to this.
Path string
// ReasonCodeStem is the middle of the structured reason code each
// middleware logs: ownership logs "owner_libpod_" + stem +
// "_unscopeable", visibility logs "visibility_libpod_" + stem +
// "_unscopeable". Both packages assert the assembled strings as literals
// in their own tests, so adding an entry here without deciding what its
// two codes are fails those tests rather than inventing a code silently.
ReasonCodeStem string
// Reason is the operator-facing explanation both layers report in the 403
// body and the access log.
Reason string
}
LibpodUnscopeableRead describes one refused endpoint.
func LibpodUnscopeableReads ¶
func LibpodUnscopeableReads() []LibpodUnscopeableRead
LibpodUnscopeableReads returns the whole set, for tests that need to assert both middlewares cover every entry and that no shipped preset admits one.
func LookupLibpodUnscopeableRead ¶
func LookupLibpodUnscopeableRead(normPath string) (LibpodUnscopeableRead, bool)
LookupLibpodUnscopeableRead reports whether normPath is a libpod read both isolation layers refuse. Callers must have already established the method is GET or HEAD. Every entry is a GET-only route, so refusing anything else here would answer 403 where the daemon answers 405; HEAD is the exception because there is no body-filtering step it could legitimately need, and forwarding it is the same unscoped disclosure the GET refusal exists to prevent.
type LibpodUnscopeableWrite ¶
type LibpodUnscopeableWrite struct {
// Method is the HTTP method Podman routes the refused operation on.
// Matching it exactly matters: refusing another method would answer 403
// where the daemon answers 405, or refuse a different operation Podman
// serves on the same path, as kube play is on the kube down paths.
Method string
// Path is the normalized request path, i.e. what NormalizePath returns.
// It strips the API version prefix but not the /libpod segment, so a
// Podman binding's /v5.8.1/libpod/... spelling normalizes to this.
Path string
// ReasonCodeStem is the middle of the structured reason code ownership
// logs: "owner_libpod_" + stem + "_unscopeable", the same assembly the
// read catalog uses.
ReasonCodeStem string
// Reason is the operator-facing explanation reported in the 403 body and
// the access log.
Reason string
}
LibpodUnscopeableWrite describes one refused endpoint.
func LibpodUnscopeableWrites ¶
func LibpodUnscopeableWrites() []LibpodUnscopeableWrite
LibpodUnscopeableWrites returns the whole set, for tests that need to assert the ownership middleware covers every entry.
func LookupLibpodUnscopeableWrite ¶
func LookupLibpodUnscopeableWrite(method, normPath string) (LibpodUnscopeableWrite, bool)
LookupLibpodUnscopeableWrite reports whether method and normPath name a libpod write owner isolation refuses. Unlike the read lookup it takes the method itself rather than trusting the caller to have checked it, because these paths are not GET-family routes an unconditional refusal could be safe on: POST /libpod/pods/prune is a write and GET on the same path is a route Podman does not serve, and POST on the kube down paths is kube play, a different operation.
type MutationOptions ¶
type MutationOptions struct {
Rules []MutationRuleOptions
}
MutationOptions configures declarative admission-mutation rules. It is global — carried on filter.Options, not filter.PolicyConfig — because mutation config is not part of per-client-profile overrides (v1 has a single mutation authority; see config.MutationsConfig's doc comment).
type MutationRuleOptions ¶
type MutationRuleOptions struct {
ID string
Mode string // "enforce" | "warn" | "audit"; empty defaults to "enforce"
Surfaces []string
InjectLabels *InjectLabelsMutationOptions
RemapImage *ImageRemapMutationOptions
// RemapBindSource rewrites a bind-mount source prefix. See mutation_bind.go.
RemapBindSource *BindSourceRemapMutationOptions
}
MutationRuleOptions is one compiled-from-config declarative admission rule: exactly one of InjectLabels/RemapImage is expected to be set — config validation enforces this before it ever reaches the filter package.
type NetworkExposureOptions ¶
type NetworkExposureOptions struct {
// DenyPublishedPorts refuses any published port.
DenyPublishedPorts bool
// AllowedPortHostIPs, when non-empty and ports are published, requires
// every binding's host IP to be listed. An empty host IP binds every
// interface and counts as 0.0.0.0.
AllowedPortHostIPs []string
// AllowedNetworks, when non-empty, requires every network joined to
// resolve to a listed network name.
AllowedNetworks []string
}
NetworkExposureOptions are the three gates one surface carries. The zero value enforces nothing.
type NetworkInspectFunc ¶
type NetworkInspectFunc func(ctx context.Context, target string) (NetworkInspectResult, bool, error)
NetworkInspectFunc resolves a network reference (ID, ID prefix or name) the way the daemon does. found=false with err=nil means no network matches.
func NewDockerNetworkInspectorWithRoundTripper ¶
func NewDockerNetworkInspectorWithRoundTripper(rt http.RoundTripper) NetworkInspectFunc
NewDockerNetworkInspectorWithRoundTripper returns a network inspector that issues its GET through the shared upstream RoundTripper.
type NetworkInspectResult ¶
NetworkInspectResult carries the part of GET /networks/{target} the host network check needs.
type NetworkOptions ¶
type NetworkOptions struct {
AllowCustomDrivers bool
AllowSwarmScope bool
AllowIngress bool
AllowAttachable bool
AllowConfigOnly bool
AllowConfigFrom bool
AllowCustomIPAMDrivers bool
AllowCustomIPAMConfig bool
AllowIPAMOptions bool
AllowDriverOptions bool
AllowEndpointConfig bool
// EndpointConfig narrows AllowEndpointConfig into per-field gates (#186).
// Only consulted when AllowEndpointConfig is false.
EndpointConfig EndpointConfigOptions
AllowDisconnectForce bool
// AllowDisableIPv4 permits POST /networks/create with EnableIPv4
// explicitly false (Engine API 1.48+). Default false.
AllowDisableIPv4 bool
// AllowDNSServers permits a request to set or remove a network's own DNS
// resolvers: `network_dns_servers` on POST /libpod/networks/create and
// both `adddnsservers` and `removednsservers` on
// POST /libpod/networks/{name}/update. Libpod-only — Docker networks have
// no per-network resolver concept and no update endpoint at all, so the
// Docker-compat inspector never consults this. Default false, because
// pointing an existing network's resolver at a host the caller controls
// changes what names resolve to inside every container already attached
// to it, including containers the caller does not own. See
// networkPolicy.inspectLibpodUpdate.
AllowDNSServers bool
}
NetworkOptions configures request-body policy checks for network write endpoints.
type NodeInspectFunc ¶ added in v3.2.0
NodeInspectFunc looks a node up by ID or name. found=false with err=nil means the node does not exist (404).
func NewDockerNodeInspectorWithRoundTripper ¶ added in v3.2.0
func NewDockerNodeInspectorWithRoundTripper(rt http.RoundTripper) NodeInspectFunc
NewDockerNodeInspectorWithRoundTripper returns a node inspector that issues GET /nodes/{id} through the shared upstream RoundTripper.
type NodeInspectResult ¶ added in v3.2.0
NodeInspectResult is the part of GET /nodes/{id} a label check needs.
type NodeOptions ¶
type NodeOptions struct {
AllowNameChange bool
AllowRoleChange bool
AllowAvailabilityChange bool
AllowLabelMutation bool
AllowedLabelKeys []string
// InspectNode reads the node's current version and labels. A node update
// replaces the whole label map, so with allow_label_mutation off the
// submitted map can only be judged against the labels it replaces. A nil
// value fails closed for any update that reaches the label check.
InspectNode NodeInspectFunc
}
NodeOptions configures request-body inspection for node updates.
type OfflineBodyResult ¶
type OfflineBodyResult struct {
// Inspected is false when no inspector covers the request's method and
// route, so the body was never read.
Inspected bool
// Denied is set when an inspector refused the request.
Denied bool
// Reason is the inspector's refusal text, empty unless Denied.
Reason string
// ReasonCode is the stable machine-readable code for the refusal
// (request_body_policy_denied, request_body_too_large, ...).
ReasonCode string
// Status is the HTTP status the proxy would answer with, zero unless Denied.
Status int
// Hard is set when a warn or audit rollout would not pass the refusal through.
Hard bool
// NotEvaluated lists the checks that need the daemon and were skipped.
NotEvaluated []string
}
OfflineBodyResult is the outcome of running the request-body inspectors against a request without a daemon behind them.
func InspectBodyOffline ¶
func InspectBodyOffline(logger *slog.Logger, r *http.Request, cfg PolicyConfig, mutation MutationOptions) OfflineBodyResult
InspectBodyOffline runs the same inspector table the middleware runs, for one request, against cfg. normalizedPath must come from NormalizePath. The exec inspectors' live lookups (target protection label, existing exec instance) stay unset, so they are reported in NotEvaluated instead of guessed at. A POST /exec/{id}/start body carries nothing the policy decides on, so it is not inspected at all.
type OpaqueWorkload ¶ added in v3.2.0
type OpaqueWorkload uint8
OpaqueWorkload identifies an operation whose created containers' labels cannot be read from the request.
const ( InspectableWorkload OpaqueWorkload = iota KubeWorkload CheckpointWorkload )
type Options ¶
type Options struct {
PolicyConfig
// AllowReadExfiltration carries the global
// insecure_allow_read_exfiltration acknowledgment into request-time
// enforcement. It is intentionally not part of PolicyConfig because named
// client profiles cannot weaken or override this top-level setting.
AllowReadExfiltration bool
// Profiles defines named per-client policy overrides selected at request time.
Profiles map[string]Policy
// ResolveProfile returns the named policy to apply for the request.
ResolveProfile func(*http.Request) (string, bool)
// Mutation configures declarative admission-mutation rules. Global —
// applied identically regardless of which client profile is active —
// because mutation config is not part of PolicyConfig/per-profile
// overrides (v1 has a single mutation authority).
Mutation MutationOptions
// ExecSessions, when non-nil, turns on the exec session registry: exec
// start and resize are refused for a session this proxy did not admit
// under the same client profile. It is global, shared by the default policy
// and every profile, because the point is to tell profiles apart. Nil
// (the default) leaves exec start and resize unchanged. The caller owns
// recording sessions, by running ExecSessionRegistry.ModifyResponse on
// the upstream responses.
ExecSessions *ExecSessionRegistry
// Approvals, when non-nil, holds a request that matches a hold rule for an
// operator's decision instead of denying it outright. Nil leaves hold rules
// as the plain denies they compile to. It is global, shared by the default
// policy and every profile.
Approvals *ApprovalOptions
}
Options configures filter middleware behavior.
type PluginOptions ¶
type PluginOptions struct {
AllowHostNetwork bool
AllowHostIPC bool
AllowHostPID bool
AllowAllDevices bool
AllowedBindMounts []string
AllowedDevices []string
AllowAllCapabilities bool
AllowedCapabilities []string
AllowAllRegistries bool
AllowOfficial bool
AllowedRegistries []string
AllowedSetEnvPrefixes []string
}
PluginOptions configures request-body/query inspection for plugin writes.
type Policy ¶
type Policy struct {
Rules []*CompiledRule
PolicyConfig
}
Policy defines a named request policy profile that can override the global rules and request-body inspection options for a single request.
type PolicyConfig ¶
type PolicyConfig struct {
// DenyResponseVerbosity controls how much detail denied requests include in
// the JSON response body.
DenyResponseVerbosity DenyResponseVerbosity
// ContainerCreate configures request-body policy checks for
// POST /containers/create.
ContainerCreate ContainerCreateOptions
// LibpodContainerCreate configures request-body policy checks for
// POST /libpod/containers/create (Podman's native SpecGenerator create
// endpoint, distinct from the Docker-compat ContainerCreate above).
LibpodContainerCreate LibpodContainerCreateOptions
// Exec configures request-body policy checks for exec create/start.
Exec ExecOptions
// ImagePull configures request/query inspection for POST /images/create.
ImagePull ImagePullOptions
// ImagePush configures the registry allowlist for image, plugin and
// manifest pushes. Inactive unless AllowedRegistries is non-empty.
ImagePush ImagePushOptions
// Build configures request-body/query inspection for POST /build.
Build BuildOptions
// ContainerUpdate configures request-body inspection for
// POST /containers/*/update.
ContainerUpdate ContainerUpdateOptions
// ContainerRemove configures query inspection for
// DELETE /containers/{id} and DELETE /libpod/containers/{id}, and the
// gates on DELETE /libpod/pods/{name} and kube down.
ContainerRemove ContainerRemoveOptions
// ContainerArchive configures request-body inspection for
// PUT /containers/*/archive.
ContainerArchive ContainerArchiveOptions
// ImageLoad configures request-body inspection for POST /images/load.
ImageLoad ImageLoadOptions
// Volume configures request-body inspection for POST /volumes/create.
Volume VolumeOptions
// Network configures request-body inspection for network writes.
Network NetworkOptions
// Secret configures request-body inspection for POST /secrets/create.
Secret SecretOptions
// Config configures request-body inspection for POST /configs/create.
Config ConfigOptions
// Service configures request-body inspection for service create/update.
Service ServiceOptions
// Swarm configures request-body inspection for swarm writes.
Swarm SwarmOptions
// Node configures request-body inspection for node update.
Node NodeOptions
// Plugin configures request-body inspection for plugin write endpoints.
Plugin PluginOptions
// LibpodPodCreate configures request-body inspection for
// POST /libpod/pods/create. #148.
LibpodPodCreate LibpodPodCreateOptions
// LibpodPlayKube configures the log driver allowlist for the logDriver and
// logOptions query parameters of POST /libpod/play/kube. The YAML body is
// not inspected.
LibpodPlayKube LibpodPlayKubeOptions
// LibpodVolume configures request-body inspection for
// POST /libpod/volumes/create. #148.
LibpodVolume VolumeOptions
// LibpodNetwork configures request-body inspection for the libpod
// network write surface: POST /libpod/networks/create (#148) plus
// POST /libpod/networks/{name}/connect and .../disconnect, whose
// endpoint-config and disconnect-force gates are the same ones
// Network applies to the Docker-compat spellings.
LibpodNetwork NetworkOptions
// LibpodSecret configures request-body inspection for
// POST /libpod/secrets/create. #148.
LibpodSecret SecretOptions
// Buildkit carries #185 phase 1's single deny-only signal for the
// opaque BuildKit tunnel endpoints (POST /session, POST /grpc) — see
// buildkitPolicy.inspect's doc comment in buildkit.go for why this
// exists and why it is deliberately not the richer buildkitproxy.Policy
// translation.
Buildkit BuildkitOptions
}
PolicyConfig configures deny-response behavior plus request-body inspection policies shared by the default middleware policy and named client profiles.
type ResourceLimitGuardOptions ¶
type ResourceLimitGuardOptions struct {
PolicyConfig
// Profiles mirrors filter.Options.Profiles — the same compiled per-client
// policy map the filter/ownership/visibility layers use, so a profile's
// require_* flags apply identically here.
Profiles map[string]Policy
// ResolveProfile mirrors filter.Options.ResolveProfile (typically
// clientacl.RequestProfile).
ResolveProfile func(*http.Request) (string, bool)
// InspectContainer resolves a container's current compatibility-inspect
// resource fields for the endpoint-specific update merge. Required for
// require_{memory,cpu,cpu_hard,pids}_limit on container update; a nil
// value with an active requirement fails closed (does not panic).
InspectContainer ContainerUpdateInspectFunc
// InspectService resolves a service's current Version/Spec/PreviousSpec
// for rollback validation. Required for require_cpu_limit(_hard) on
// ?rollback=previous or an automatic-rollback-capable update; a nil value
// with an active requirement fails closed (does not panic).
InspectService ServiceInspectFunc
// CheckStoredServiceMounts enables the exact host grant policy on the
// daemon-owned spec reactivated by either service rollback path. It
// requires an inspector that returns the stored container mount data.
CheckStoredServiceMounts bool
// InspectNetwork resolves a service's network targets (ID, ID prefix or
// name) so allow_host_network: false also holds for the host network
// named by ID. A nil value fails closed (502) for any service that
// names a network.
InspectNetwork NetworkInspectFunc
}
ResourceLimitGuardOptions configures ResourceLimitGuardWithOptions. It mirrors filter.Options' shape (PolicyConfig + Profiles + ResolveProfile) so the guard selects the same per-client policy the request-body inspectors and rule evaluator already resolved, plus the runtime daemon inspectors only this layer needs.
type Rule ¶
type Rule struct {
Methods []string
Pattern string
Action Action
Reason string
Index int
// Hold marks a deny rule that asks an operator instead of refusing
// outright (config action: hold). The rule's Action stays ActionDeny, so
// every site that only knows allow and deny reads a hold as a deny, the
// fail-closed default. CompileRule rejects Hold on any other Action.
Hold bool
// Query constrains the request query: every key must be present and every
// occurrence of it must match one of its patterns. See CompiledRule.matchesQuery.
Query map[string][]string
// Body constrains the request body: it must be a JSON object carrying each
// named top-level field with a value matching one of its patterns. See
// CompiledRule.matchesBody.
Body map[string][]string
}
Rule represents a single access control rule.
type SecretOptions ¶
SecretOptions configures request-body policy checks for POST /secrets/create.
type ServiceInspectFunc ¶
ServiceInspectFunc looks up a service's current version/spec/previous-spec resource state by ID. found=false with err=nil means the service does not exist (404).
func NewDockerServiceInspectorWithRoundTripper ¶
func NewDockerServiceInspectorWithRoundTripper(rt http.RoundTripper) ServiceInspectFunc
NewDockerServiceInspectorWithRoundTripper returns a service resource-state inspector that issues its GET through the shared upstream RoundTripper.
type ServiceInspectResult ¶
type ServiceInspectResult struct {
Version uint64
SpecNanoCPUs int64
HasPreviousSpec bool
PreviousSpecNanoCPUs int64
// PreviousSpecNetworkTargets lists PreviousSpec.TaskTemplate.Networks and
// PreviousSpec.Networks targets, which a manual rollback re-applies.
PreviousSpecNetworkTargets []string
// SpecNetworkTargets lists the current Spec.TaskTemplate.Networks and
// Spec.Networks targets, which an automatic rollback re-applies when an
// update fails.
SpecNetworkTargets []string
// SpecPublishedPorts and PreviousSpecPublishedPorts count the entries of
// Spec.EndpointSpec.Ports and PreviousSpec.EndpointSpec.Ports, which the
// same two rollbacks re-apply.
SpecPublishedPorts int
PreviousSpecPublishedPorts int
// contains filtered or unexported fields
}
ServiceInspectResult carries the resource-limit-relevant subset of GET /services/{id}: the optimistic-concurrency version plus the current and (if any) previous spec's TaskTemplate.Resources.Limits.NanoCPUs.
type ServiceOptions ¶
type ServiceOptions struct {
// AllowedImages is an opt-in exact image reference allowlist.
AllowedImages []string
AllowHostNetwork bool
AllowedBindMounts []string
// AllowTmpfsPrivilegedOptions permits ContainerSpec tmpfs mounts whose
// TmpfsOptions.Options turn on exec, dev or suid. It is not a key of its
// own: ToFilterOptions cross-wires container_create's, since a service
// mount carries the same flags. Default false.
AllowTmpfsPrivilegedOptions bool
AllowAllRegistries bool
AllowOfficial bool
AllowedRegistries []string
// AllowAllCapabilities / AllowedCapabilities mirror the container-create
// CapabilityAdd allowlist for swarm task containers (ContainerSpec).
AllowAllCapabilities bool
AllowedCapabilities []string
// AllowSysctls permits ContainerSpec.Sysctls; default false denies any.
AllowSysctls bool
// RequireNonRootUser / RequireNoNewPrivileges / RequireReadonlyRootfs /
// RequireDropAllCapabilities mirror the container-create hardening rails for
// swarm task containers, enforced against ContainerSpec.User,
// ContainerSpec.Privileges.NoNewPrivileges, ContainerSpec.ReadOnly, and
// ContainerSpec.CapabilityDrop respectively.
RequireNonRootUser bool
// RequireNumericUser, under RequireNonRootUser, accepts only a numeric
// uid[:gid] User and denies a name: the engine resolves a name through the
// image's passwd file, which Sockguard can't read, so a non-root-looking
// name may still be UID 0. Default false keeps names accepted.
RequireNumericUser bool
RequireNoNewPrivileges bool
RequireReadonlyRootfs bool
RequireDropAllCapabilities bool
// DenyUnconfinedSeccomp denies service create/update when
// ContainerSpec.Privileges.Seccomp.Mode == "unconfined". Default false.
// Note: does not automatically deny Mode=="custom" — see DenyCustomSeccompProfiles.
DenyUnconfinedSeccomp bool
// DenyCustomSeccompProfiles denies service create/update when
// ContainerSpec.Privileges.Seccomp.Mode == "custom". Operators who use
// carefully vetted custom seccomp profiles must leave this false.
// When both DenyUnconfinedSeccomp and DenyCustomSeccompProfiles are true,
// only Mode=="default" (or an absent Seccomp block) is permitted.
DenyCustomSeccompProfiles bool
// DenyUnconfinedAppArmor denies service create/update when
// ContainerSpec.Privileges.AppArmor.Mode == "disabled". Swarm has no
// "unconfined" AppArmor mode; "disabled" is the equivalent. Default false.
DenyUnconfinedAppArmor bool
// DenySelinuxDisable denies service create/update when
// ContainerSpec.Privileges.SELinuxContext.Disable is true — the swarm
// equivalent of the container-create SecurityOpt label=disable that turns off
// SELinux confinement. Default false (opt-in).
DenySelinuxDisable bool
// DenySelinuxLabelOverride denies service create/update that customizes the
// SELinux context via any of ContainerSpec.Privileges.SELinuxContext.{User,
// Role,Type,Level} — the swarm equivalent of the container-create SecurityOpt
// label=user:/role:/type:/level: override. Default false. Independent of
// DenySelinuxDisable.
DenySelinuxLabelOverride bool
// ImageTrust applies cosign verification to ContainerSpec.Image, matching
// the container-create path so swarm services cannot escape image trust.
ImageTrust ImageTrustOptions
// RequireCPULimit/RequireCPULimitHard are enforced by ResourceLimitGuard
// (resource_limit_guard.go), not by servicePolicy.inspect below — service
// create, ordinary update, and rollback all need the guard's post-ownership
// placement (rollback validation requires a daemon lookup). Carried on this
// struct only so config.ServiceRequestBodyConfig.ToFilterOptions has a
// single destination field per config leaf; servicePolicy itself never
// reads them.
RequireCPULimit bool
RequireCPULimitHard bool
// NetworkExposure holds the opt-in published-port and network gates. They
// run in the resource-limit guard, which can ask the daemon what a network
// reference resolves to. Zero value: unrestricted.
NetworkExposure NetworkExposureOptions
// AllowedLogDrivers allowlists TaskTemplate.LogDriver.Name, and
// AllowedLogEndpointOptions lists the destination options
// (logEndpointOptionKeys) it may carry. Default empty: off. An empty
// LogDriver selects the swarm default and is always allowed. See
// logDriverPolicy.
AllowedLogDrivers []string
AllowedLogEndpointOptions []string
}
ServiceOptions configures request-body inspection for service create/update.
type SigningKeyOptions ¶
type SigningKeyOptions struct {
PEM string
}
SigningKeyOptions is one allowed signing key entry.
type SubmittedWorkload ¶ added in v3.2.0
type SubmittedWorkload struct {
// Labels are the label maps the request submits. For a container or pod
// create there is exactly one, and it is what the daemon layers over the
// image's baked labels. A service carries two (see SubmittedWorkloadLabels).
Labels []map[string]string
// Image is the image reference a container create (or a pod's infra
// image) names, or "" when it names none. The daemon copies that image's
// labels onto the child's Config.Labels beneath Labels, so a caller that
// can build or pull an image can bake ACL labels into it.
Image string
// Opaque identifies an operation whose child labels cannot be read.
// Its body is not read.
Opaque OpaqueWorkload
// Service marks a Swarm service create or update. The task containers
// inherit labels from an image the nodes pull, which this request's
// labels and Image cannot show, so the image's baked labels are unknown.
Service bool
}
SubmittedWorkload is what a workload-creating request asks the daemon to build, as far as the client ACL delegation check needs it.
func SubmittedWorkloadSpec ¶ added in v3.2.0
func SubmittedWorkloadSpec(w http.ResponseWriter, r *http.Request) (spec SubmittedWorkload, applies bool, err error)
SubmittedWorkloadSpec is SubmittedWorkloadLabels plus the image a container create names and a flag for requests whose labels cannot be read at all. It also covers POST /libpod/pods/create (the pod's labels and its infra image) and recognizes kube play and libpod container restore as opaque without reading their bodies. Everything else about the body handling is as documented on SubmittedWorkloadLabels.
type SwarmOptions ¶
type SwarmOptions struct {
AllowForceNewCluster bool
AllowExternalCA bool
AllowedJoinRemoteAddrs []string
AllowTokenRotation bool
AllowManagerUnlockKeyRotation bool
AllowAutoLockManagers bool
AllowSigningCAUpdate bool
AllowUnlock bool
}
SwarmOptions configures request-body inspection for swarm writes.
type VolumeOptions ¶
type VolumeOptions struct {
AllowCustomDrivers bool
AllowDriverOpts bool
// AllowedBindMounts is the container-create bind-mount allowlist, not a
// key of its own: a local-driver volume whose options ask for a bind
// reaches the same host path a HostConfig.Binds entry would, so it is
// checked against the same list. RequestBodyConfig.ToFilterOptions
// cross-wires it. Only consulted when AllowDriverOpts is true, since
// otherwise every driver options map is already denied outright.
AllowedBindMounts []string
// AllowTmpfsPrivilegedOptions is the tmpfs knob, cross-wired like
// AllowedBindMounts: a local-driver volume of type tmpfs carries the same
// exec/suid/dev flags a tmpfs mount does, in "o". Only consulted when
// AllowDriverOpts is true. Default false.
AllowTmpfsPrivilegedOptions bool
// AllowClusterVolumeSecrets permits ClusterVolumeSpec.Secrets on
// PUT /volumes/{name}. Default false, and deliberately its own knob
// rather than a reuse of AllowDriverOpts: driver options are a routine
// setting on ordinary local volumes, so overloading that flag would
// silently open secret rewriting for every operator who already sets it.
// Each entry names a Swarm secret the daemon then hands to the CSI
// plugin, so a caller who can rewrite the list can point the plugin at a
// secret it was never granted. AllowClusterVolumeUpdates does NOT admit
// Secrets — this is the only flag that does.
AllowClusterVolumeSecrets bool
// AllowClusterVolumeUpdates permits every OTHER ClusterVolumeSpec field
// on PUT /volumes/{name}: Availability, Group, AccessMode,
// CapacityRange and AccessibilityRequirements. Default false.
AllowClusterVolumeUpdates bool
}
VolumeOptions configures request-body policy checks for POST /volumes/create and PUT /volumes/{name}.
Source Files
¶
- approval_hold.go
- body_read.go
- build.go
- buildkit.go
- cdi_device_policy.go
- container_archive.go
- container_create.go
- container_create_legacy_hostconfig.go
- container_create_types.go
- container_remove.go
- container_start.go
- container_update.go
- create_image_allowlist.go
- create_launch_policy.go
- create_list_allowlist.go
- driver_create.go
- exec.go
- exec_sessions.go
- exec_target.go
- hijack_paths.go
- image_load.go
- image_pull.go
- image_push.go
- io_deps.go
- json_key_parity.go
- json_mutate.go
- json_subset.go
- libpod_container_create.go
- libpod_container_create_residual.go
- libpod_container_create_rootfs.go
- libpod_container_create_types.go
- libpod_container_update.go
- libpod_hosts_file.go
- libpod_namespace.go
- libpod_network.go
- libpod_normalize.go
- libpod_play_kube.go
- libpod_pod_create.go
- libpod_pod_create_inherited.go
- libpod_secret.go
- libpod_unscopeable_reads.go
- libpod_unscopeable_writes.go
- libpod_volume.go
- local_volume_bind.go
- log_driver.go
- middleware.go
- mount_source_policy.go
- mutation.go
- mutation_bind.go
- network.go
- network_exposure.go
- node.go
- normalize.go
- offline.go
- overlay_mount_options.go
- plugin.go
- podman_build_controls.go
- podman_compat_secret_list.go
- podman_volume_filters.go
- query_param.go
- reason_codes_export.go
- registry_auth.go
- request_rejection.go
- resource_limit_guard.go
- rule_body.go
- rule_query.go
- rules.go
- service.go
- service_network_guard.go
- service_stored_mount_guard.go
- spool_budget.go
- swarm.go
- tmpfs_options.go
- volume.go
- workload_labels.go