security

package
v0.0.0-...-e7c9706 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 18, 2024 License: Apache-2.0 Imports: 23 Imported by: 11

Documentation

Index

Constants

View Source
const (

	// DefaultCertChainFilePath is the well-known path for an existing certificate chain file
	DefaultCertChainFilePath = "./etc/certs/cert-chain.pem"

	// DefaultKeyFilePath is the well-known path for an existing key file
	DefaultKeyFilePath = "./etc/certs/key.pem"

	// DefaultRootCertFilePath is the well-known path for an existing root certificate file
	DefaultRootCertFilePath = "./etc/certs/root-cert.pem"

	// WorkloadIdentityPath is the well-known path to the Unix Domain Socket for SDS.
	WorkloadIdentityPath = "./var/run/secrets/workload-spiffe-uds"

	// WorkloadIdentitySocketFile is the name of the UDS socket file
	// Istio's internal SDS server uses.
	DefaultWorkloadIdentitySocketFile = "socket"

	// CredentialNameSocketPath is the well-known path to the Unix Domain Socket for Credential Name.
	CredentialNameSocketPath = "./var/run/secrets/credential-uds/socket"

	// CredentialMetaDataName is the name in node meta data.
	CredentialMetaDataName = "credential"

	// SDSExternalClusterName is the name of the cluster for external SDS connections which is defined via CredentialNameSocketPath
	SDSExternalClusterName = "sds-external"

	// SDSExternalCredentialPrefix is the prefix for the credentialName which will utilize external SDS connections defined via CredentialNameSocketPath
	SDSExternalCredentialPrefix = "sds://"

	// WorkloadIdentityCredentialsPath is the well-known path to a folder with workload certificate files.
	WorkloadIdentityCredentialsPath = "./var/run/secrets/workload-spiffe-credentials"

	// WorkloadIdentityCertChainPath is the well-known path to a workload certificate chain file.
	WorkloadIdentityCertChainPath = WorkloadIdentityCredentialsPath + "/cert-chain.pem"

	// WorkloadIdentityKeyPath is the well-known path to a workload key file.
	WorkloadIdentityKeyPath = WorkloadIdentityCredentialsPath + "/key.pem"

	// WorkloadIdentityRootCertPath is the well-known path to a workload root certificate file.
	WorkloadIdentityRootCertPath = WorkloadIdentityCredentialsPath + "/root-cert.pem"

	// GkeWorkloadCertChainFilePath is the well-known path for the GKE workload certificate chain file.
	// Quoted from https://cloud.google.com/traffic-director/docs/security-proxyless-setup#create-service:
	// "On creation, each Pod gets a volume at /var/run/secrets/workload-spiffe-credentials."
	GkeWorkloadCertChainFilePath = WorkloadIdentityCredentialsPath + "/certificates.pem"

	// GkeWorkloadKeyFilePath is the well-known path for the GKE workload certificate key file
	GkeWorkloadKeyFilePath = WorkloadIdentityCredentialsPath + "/private_key.pem"

	// GkeWorkloadRootCertFilePath is the well-known path for the GKE workload root certificate file
	GkeWorkloadRootCertFilePath = WorkloadIdentityCredentialsPath + "/ca_certificates.pem"

	// SystemRootCerts is special case input for root cert configuration to use system root certificates.
	SystemRootCerts = "SYSTEM"

	// RootCertReqResourceName is resource name of discovery request for root certificate.
	RootCertReqResourceName = "ROOTCA"

	// WorkloadKeyCertResourceName is the resource name of the discovery request for workload
	// identity.
	WorkloadKeyCertResourceName = "default"

	// GCE is Credential fetcher type of Google plugin
	GCE = "GoogleComputeEngine"

	// JWT is a Credential fetcher type that reads from a JWT token file
	JWT = "JWT"

	// Mock is Credential fetcher type of mock plugin
	Mock = "Mock" // testing only

	// GoogleCAProvider uses the Google CA for workload certificate signing
	GoogleCAProvider = "GoogleCA"

	// GoogleCASProvider uses the Google certificate Authority Service to sign workload certificates
	GoogleCASProvider = "GoogleCAS"

	// GkeWorkloadCertificateProvider uses the GKE workload certificates
	GkeWorkloadCertificateProvider = "GkeWorkloadCertificate"

	// FileRootSystemCACert is a unique resource name signaling that the system CA certificate should be used
	FileRootSystemCACert = "file-root:system"
)
View Source
const (
	BearerTokenPrefix = "Bearer "

	K8sTokenPrefix = "Istio "

	// CertSigner info
	CertSigner = "CertSigner"

	// ImpersonatedIdentity declares the identity we are requesting a certificate on behalf of.
	// This is constrained to only allow identities in CATrustedNodeAccounts, and only to impersonate identities
	// on their node.
	ImpersonatedIdentity = "ImpersonatedIdentity"
)
View Source
const (
	ResourceSeparator = "~"
)

Variables

View Source
var AuthPlaintext = env.Register("XDS_AUTH_PLAINTEXT", false,
	"authenticate plain text requests - used if Istiod is running on a secure/trusted network").Get()

CARetryOptions returns the default retry options recommended for CA calls This includes 5 retries, with backoff from 100ms -> 1.6s with jitter.

View Source
var (
	// TokenAudiences specifies a list of audiences for SDS trustworthy JWT. This is to make sure that the CSR requests
	// contain the JWTs intended for Citadel.
	TokenAudiences = strings.Split(env.Register("TOKEN_AUDIENCES", "istio-ca",
		"A list of comma separated audiences to check in the JWT token before issuing a certificate. "+
			"The token is accepted if it matches with one of the audiences").Get(), ",")
)

TODO: For 1.8, make sure MeshConfig is updated with those settings, they should be dynamic to allow migrations without restart. Both are critical.

Functions

func CARetryInterceptor

func CARetryInterceptor() grpc.DialOption

CARetryInterceptor is a grpc UnaryInterceptor that adds retry options, as a convenience wrapper around CARetryOptions. If needed to chain with other interceptors, the CARetryOptions can be used directly.

func CheckWorkloadCertificate

func CheckWorkloadCertificate(certChainFilePath, keyFilePath, rootCertFilePath string) bool

CheckWorkloadCertificate returns true when the workload certificate files are present under the provided paths. Otherwise, return false.

func ExtractBearerToken

func ExtractBearerToken(ctx context.Context) (string, error)

func ExtractRequestToken

func ExtractRequestToken(req *http.Request) (string, error)

func GetConnectionAddress

func GetConnectionAddress(ctx context.Context) string

func GetIstioSDSServerSocketPath

func GetIstioSDSServerSocketPath() string

This is the fixed-path, fixed-filename location where Istio's default SDS workload identity server will put its socket.

func GetOSRootFilePath

func GetOSRootFilePath() string

GetOSRootFilePath returns the first file path detected from a list of known CA certificate file paths. If none of the known CA certificate files are found, a warning in printed and an empty string is returned.

func GetWorkloadSDSSocketListenPath

func GetWorkloadSDSSocketListenPath(sockfile string) string

This is the fixed-path, configurable filename location where the Istio agent will look for a SDS workload identity server socket.

If we are using Istio's SDS server, the SDS socket listen path == the serve path If we are not using Istio's SDS server, the SDS socket listen path may != the Istio SDS serve path

Types

type AuthContext

type AuthContext struct {
	// grpc context
	GrpcContext context.Context
	// http request
	Request *http.Request
}

func (*AuthContext) Header

func (ac *AuthContext) Header(header string) []string

Header returns the authenticated remote address from AuthContext.

func (*AuthContext) RemoteAddress

func (ac *AuthContext) RemoteAddress() string

RemoteAddress returns the authenticated remote address from AuthContext.

type AuthSource

type AuthSource int

AuthSource represents where authentication result is derived from.

const (
	AuthSourceClientCertificate AuthSource = iota
	AuthSourceIDToken
)

type Authenticator

type Authenticator interface {
	Authenticate(ctx AuthContext) (*Caller, error)
	AuthenticatorType() string
}

Authenticator determines the caller identity based on request context.

type Caller

type Caller struct {
	AuthSource AuthSource
	Identities []string

	KubernetesInfo KubernetesInfo
}

Caller carries the identity and authentication source of a caller.

func Authenticate

func Authenticate(ctx context.Context, authenticators []Authenticator) (*Caller, error)

Authenticate authenticates the ADS request using the configured authenticators. Returns the validated principals or an error. If no authenticators are configured, or if the request is on a non-secure stream ( 15010 ) - returns amn empty caller and no errors.

type Client

type Client interface {
	CSRSign(csrPEM []byte, certValidTTLInSec int64) ([]string, error)
	Close()
	// Retrieve CA root certs If CA publishes API endpoint for this
	GetRootCertBundle() ([]string, error)
}

Client interface defines the clients need to implement to talk to CA for CSR. The Agent will create a key pair and a CSR, and use an implementation of this interface to get back a signed certificate. There is no guarantee that the SAN in the request will be returned - server may replace it.

type CredFetcher

type CredFetcher interface {
	// GetPlatformCredential fetches workload credential provided by the platform.
	GetPlatformCredential() (string, error)

	// GetIdentityProvider returns the name of the IdentityProvider that can authenticate the workload credential.
	GetIdentityProvider() string

	// Stop releases resources and cleans up.
	Stop()
}

type DirectSecretManager

type DirectSecretManager struct {
	// contains filtered or unexported fields
}

func NewDirectSecretManager

func NewDirectSecretManager() *DirectSecretManager

func (*DirectSecretManager) GenerateSecret

func (d *DirectSecretManager) GenerateSecret(resourceName string) (*SecretItem, error)

func (*DirectSecretManager) Set

func (d *DirectSecretManager) Set(resourceName string, secret *SecretItem)

type FakeAuthenticator

type FakeAuthenticator struct {
	AllowedToken string
	AllowedCert  string
	Name         string

	Successes *atomic.Int32
	Failures  *atomic.Int32
	// contains filtered or unexported fields
}

func NewFakeAuthenticator

func NewFakeAuthenticator(name string) *FakeAuthenticator

func (*FakeAuthenticator) Authenticate

func (f *FakeAuthenticator) Authenticate(authCtx AuthContext) (*Caller, error)

func (*FakeAuthenticator) AuthenticatorType

func (f *FakeAuthenticator) AuthenticatorType() string

func (*FakeAuthenticator) Set

func (f *FakeAuthenticator) Set(token string, identity string) *FakeAuthenticator

type ImpersonatedIdentityContextKey

type ImpersonatedIdentityContextKey struct{}

type KubernetesInfo

type KubernetesInfo struct {
	PodName           string
	PodNamespace      string
	PodUID            string
	PodServiceAccount string
}

KubernetesInfo defines Kubernetes specific information extracted from the caller. This involves additional metadata about the caller beyond just its SPIFFE identity.

func (KubernetesInfo) String

func (k KubernetesInfo) String() string

type Options

type Options struct {
	// CAEndpoint is the CA endpoint to which node agent sends CSR request.
	CAEndpoint string

	// CAEndpointSAN overrides the ServerName extracted from CAEndpoint.
	CAEndpointSAN string

	// The CA provider name.
	CAProviderName string

	// TrustDomain corresponds to the trust root of a system.
	// https://github.com/spiffe/spiffe/blob/master/standards/SPIFFE-ID.md#21-trust-domain
	TrustDomain string

	// WorkloadRSAKeySize is the size of a private key for a workload certificate.
	WorkloadRSAKeySize int

	// Whether to generate PKCS#8 private keys.
	Pkcs8Keys bool

	// OutputKeyCertToDir is the directory for output the key and certificate
	OutputKeyCertToDir string

	// ProvCert is the directory for client to provide the key and certificate to CA server when authenticating
	// with mTLS. This is not used for workload mTLS communication, and is
	ProvCert string

	// ClusterID is the cluster where the agent resides.
	// Normally initialized from ISTIO_META_CLUSTER_ID - after a tortuous journey it
	// makes its way into the ClusterID metadata of Citadel gRPC request to create the cert.
	// Didn't find much doc - but I suspect used for 'central cluster' use cases - so should
	// match the cluster name set in the MC setup.
	ClusterID string

	// The type of Elliptical Signature algorithm to use
	// when generating private keys. Currently only ECDSA is supported.
	ECCSigAlg string

	// The type of curve to use when generating private keys with ECC. Currently only ECDSA is supported.
	ECCCurve string

	// FileMountedCerts indicates whether the proxy is using file
	// mounted certs created by a foreign CA. Refresh is managed by the external
	// CA, by updating the Secret or VM file. We will watch the file for changes
	// or check before the cert expires. This assumes the certs are in the
	// well-known ./etc/certs location.
	FileMountedCerts bool

	// PilotCertProvider is the provider of the Pilot certificate (PILOT_CERT_PROVIDER env)
	// Determines the root CA file to use for connecting to CA gRPC:
	// - istiod
	// - k8s.io/NAME
	// - custom - requires Istiod TLS certs to be available as files
	// - none
	//
	// This is used only in agent.
	PilotCertProvider string

	// secret TTL.
	SecretTTL time.Duration

	// The ratio of cert lifetime to refresh a cert. For example, at 0.10 and 1 hour TTL,
	// we would refresh 6 minutes before expiration.
	SecretRotationGracePeriodRatio float64

	// The amount of randomness to add to SecretRotationGracePeriodRatio. This is used
	// to prevent spikes in resource consumption when large fleets of proxies try to renew
	// their certs simultaneously.
	SecretRotationGracePeriodRatioJitter float64

	// STS port
	STSPort int

	// credential fetcher.
	CredFetcher CredFetcher

	// credential identity provider
	CredIdentityProvider string

	// Namespace corresponding to workload
	WorkloadNamespace string

	// Name of the Service Account
	ServiceAccount string

	// XDS auth provider
	XdsAuthProvider string

	// Cert signer info
	CertSigner string

	// Delay in reading certificates from file after the change is detected. This is useful in cases
	// where the write operation of key and cert take longer.
	FileDebounceDuration time.Duration

	// Root Cert read from the OS
	CARootPath string

	// The path for an existing certificate chain file
	CertChainFilePath string
	// The path for an existing key file
	KeyFilePath string
	// The path for an existing root certificate bundle
	RootCertFilePath string
}

Options provides all of the configuration parameters for secret discovery service and CA configuration. Used in both Istiod and Agent. TODO: ProxyConfig should have most of those, and be passed to all components (as source of truth)

type SdsCertificateConfig

type SdsCertificateConfig struct {
	CertificatePath   string
	PrivateKeyPath    string
	CaCertificatePath string
}

func SdsCertificateConfigFromResourceName

func SdsCertificateConfigFromResourceName(resource string) (SdsCertificateConfig, bool)

SdsCertificateConfigFromResourceName converts the provided resource name into a SdsCertificateConfig If the resource name is not valid, false is returned.

func SdsCertificateConfigFromResourceNameForOSCACert

func SdsCertificateConfigFromResourceNameForOSCACert(resource string) (SdsCertificateConfig, bool)

SdsCertificateConfigFromResourceNameForOSCACert converts the OS resource name into a SdsCertificateConfig

func (SdsCertificateConfig) GetResourceName

func (s SdsCertificateConfig) GetResourceName() string

GetResourceName converts a SdsCertificateConfig to a string to be used as an SDS resource name

func (SdsCertificateConfig) GetRootResourceName

func (s SdsCertificateConfig) GetRootResourceName() string

GetRootResourceName converts a SdsCertificateConfig to a string to be used as an SDS resource name for the root

func (SdsCertificateConfig) IsKeyCertificate

func (s SdsCertificateConfig) IsKeyCertificate() bool

IsKeyCertificate returns true if this config represents key certificate config.

func (SdsCertificateConfig) IsRootCertificate

func (s SdsCertificateConfig) IsRootCertificate() bool

IsRootCertificate returns true if this config represents a root certificate config.

type SecretItem

type SecretItem struct {
	CertificateChain []byte
	PrivateKey       []byte

	RootCert []byte

	// ResourceName passed from envoy SDS discovery request.
	// "ROOTCA" for root cert request, "default" for key/cert request.
	ResourceName string

	CreatedTime time.Time

	ExpireTime time.Time
}

SecretItem is the cached item in in-memory secret store.

type SecretManager

type SecretManager interface {
	// GenerateSecret generates new secret for the given resource.
	//
	// The current implementation also watched the generated secret and trigger a callback when it is
	// near expiry. It will constructs the SAN based on the token's 'sub' claim, expected to be in
	// the K8S format. No other JWTs are currently supported due to client logic. If JWT is
	// missing/invalid, the resourceName is used.
	GenerateSecret(resourceName string) (*SecretItem, error)
}

SecretManager defines secrets management interface which is used by SDS.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL