connect

package
v1.12.9 Latest Latest
Warning

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

Go to latest
Published: Jan 26, 2023 License: MPL-2.0 Imports: 28 Imported by: 174

Documentation

Index

Constants

View Source
const (
	DefaultPrivateKeyType      = "ec"
	DefaultPrivateKeyBits      = 256
	DefaultIntermediateCertTTL = 24 * 365 * time.Hour
)
View Source
const TestClusterID = "11111111-2222-3333-4444-555555555555"

TestClusterID is the Consul cluster ID for testing.

NOTE: this is duplicated in the api package as testClusterID

Variables

This section is empty.

Functions

func AuthorizeIntentionTarget added in v1.10.0

func AuthorizeIntentionTarget(
	target, targetNS, targetAP string,
	ixn *structs.Intention,
	matchType structs.IntentionMatchType,
) (auth bool, match bool)

AuthorizeIntentionTarget determines whether the destination is covered by the given intention and whether the intention action allows a connection. This is a generalized version of the old CertURI.Authorize(), and can be evaluated against sources or destinations.

The return value of `auth` is only valid if the second value `match` is true. If `match` is false, then the intention doesn't match this target and any result should be ignored.

func CACN added in v1.7.0

func CACN(provider, uniqueID, trustDomain string, primaryDC bool) string

CACN returns the common name for a CA certificate. A uniqueID is requires because some providers (e.g. Vault) cache by subject and so produce incorrect results - for example they won't cross-sign an older CA certificate with the same common name since they think they already have a valid cert for that CN and just return the current root.

This can be generated by any means but will be truncated to 8 chars and sanitised to DNS-safe chars. CompactUID generates suitable UIDs for this specific purpose.

Format is:

{provider}-{uniqueID_first8}.{pri|sec}.ca.<trust_domain_first_8>.consul

trust domain is truncated to keep the whole name short

func CalculateCertFingerprint

func CalculateCertFingerprint(cert []byte) string

CalculateCertFingerprint calculates the SHA-1 fingerprint from the cert bytes.

func CertSubjects added in v1.9.16

func CertSubjects(pem string) string

CertSubjects can be used in debugging to return the subject of each certificate in the PEM bundle. Each subject is separated by a newline.

func CompactUID added in v1.7.0

func CompactUID() (string, error)

CompactUID returns a crypto random Unique Identifier string consiting of 8 characters of base36 encoded random value. This has roughly 41 bits of entropy so is suitable for infrequently occuring events with low probability of collision. It is not suitable for UUIDs for very frequent events. It's main purpose is to assign unique values to CA certificate Common Names which need to be unique in some providers - see CACN - but without using up large amounts of the limited 64 character Common Name. It also makes the values more easily digestable by humans considering there are likely to be few of them ever in use.

func CreateCACSR added in v1.3.0

func CreateCACSR(uri CertURI, privateKey crypto.Signer) (string, error)

CreateCSR returns a CA CSR to sign the given service along with the PEM-encoded private key for this certificate.

func CreateCAExtension added in v1.3.0

func CreateCAExtension() (pkix.Extension, error)

CreateCAExtension creates a pkix.Extension for the x509 Basic Constraints IsCA field ()

func CreateCSR

func CreateCSR(uri CertURI, privateKey crypto.Signer,
	dnsNames []string, ipAddresses []net.IP, extensions ...pkix.Extension) (string, error)

CreateCSR returns a CSR to sign the given service with SAN entries along with the PEM-encoded private key for this certificate.

func EncodeSerialNumber added in v1.6.2

func EncodeSerialNumber(serial *big.Int) string

EncodeSerialNumber encodes the given serial number as a colon-hex encoded string.

func EncodeSigningKeyID added in v1.6.2

func EncodeSigningKeyID(keyID []byte) string

EncodeSigningKeyID encodes the given AuthorityKeyId or SubjectKeyId into a colon-hex encoded string suitable for using as a SigningKeyID value.

func GatewaySNI added in v1.11.0

func GatewaySNI(dc string, partition, trustDomain string) string

func GeneratePrivateKey

func GeneratePrivateKey() (crypto.Signer, string, error)

func GeneratePrivateKeyWithConfig added in v1.6.0

func GeneratePrivateKeyWithConfig(keyType string, keyBits int) (crypto.Signer, string, error)

GeneratePrivateKey generates a new Private key

func HackSANExtensionForCSR added in v1.11.0

func HackSANExtensionForCSR(template *x509.CertificateRequest)

HackSANExtensionForCSR will create a SAN extension on the CSR off of the convenience fields (DNSNames, EmailAddresses, IPAddresses, URIs) and appropriately marks that SAN extension as critical if the CSR has an empty subject.

This is basically attempting to repeat this blob of code from the stdlib ourselves:

https://github.com/golang/go/blob/0e67ce3d28320e816dd8e7cf7d701c1804fb977e/src/crypto/x509/x509.go#L1088

func HexString

func HexString(input []byte) string

HexString returns a standard colon-separated hex value for the input byte slice. This should be used with cert serial numbers and so on.

func IsHexString added in v1.6.2

func IsHexString(input []byte) bool

IsHexString returns true if the input is the output of HexString(). Meant for use in tests.

func KeyId

func KeyId(raw interface{}) ([]byte, error)

KeyId returns a x509 KeyId from the given signing key. The key must be an *ecdsa.PublicKey currently, but may support more types in the future.

func KeyInfoFromCert added in v1.7.0

func KeyInfoFromCert(cert *x509.Certificate) (keyType string, keyBits int, err error)

KeyInfoFromCert returns the key type and key bit length for the key used by the certificate.

func ParseCSR

func ParseCSR(pemValue string) (*x509.CertificateRequest, error)

ParseCSR parses a CSR from a PEM-encoded value. The certificate request must be the the first block in the PEM value.

func ParseCert

func ParseCert(pemValue string) (*x509.Certificate, error)

ParseCert parses the x509 certificate from a PEM-encoded value.

func ParseLeafCerts added in v1.6.2

func ParseLeafCerts(pemValue string) (*x509.Certificate, *x509.CertPool, error)

ParseLeafCerts parses all of the x509 certificates from a PEM-encoded value under the assumption that the first cert is a leaf (non-CA) cert and the rest are intermediate CA certs.

If no certificates are found this returns an error.

func ParseSigner

func ParseSigner(pemValue string) (crypto.Signer, error)

ParseSigner parses a crypto.Signer from a PEM-encoded key. The private key is expected to be the first block in the PEM value.

func QuerySNI added in v1.6.0

func QuerySNI(service string, datacenter string, trustDomain string) string

func ServiceSNI added in v1.6.0

func ServiceSNI(service string, subset string, namespace string, partition string, datacenter string, trustDomain string) string

func SigAlgoForKey added in v1.7.0

func SigAlgoForKey(key crypto.Signer) x509.SignatureAlgorithm

SigAlgoForKey returns the preferred x509.SignatureAlgorithm for a given key based on it's type. If the key type is not supported we return ECDSAWithSHA256 on the basis that it will fail anyway and we've already type checked keys by the time we call this in general.

func SigAlgoForKeyType added in v1.7.0

func SigAlgoForKeyType(keyType string) x509.SignatureAlgorithm

SigAlgoForKeyType returns the preferred x509.SignatureAlgorithm for a given key type string from configuration or an existing cert. If the key type is not supported we return ECDSAWithSHA256 on the basis that it will fail anyway and we've already type checked config by the time we call this in general.

func TargetSNI added in v1.6.0

func TargetSNI(target *structs.DiscoveryTarget, trustDomain string) string

func TestAgentLeaf added in v1.8.1

func TestAgentLeaf(t testing.T, node string, datacenter string, root *structs.CARoot, expiration time.Duration) (string, string, error)

func TestCA

func TestCA(t testing.T, xc *structs.CARoot) *structs.CARoot

TestCA creates a test CA certificate and signing key and returns it in the CARoot structure format. The returned CA will be set as Active = true.

If xc is non-nil, then the returned certificate will have a signing cert that is cross-signed with the previous cert, and this will be set as SigningCert.

func TestCAConfigSet

func TestCAConfigSet(t testing.T, a TestAgentRPC,
	ca *structs.CARoot) *structs.CARoot

TestCAConfigSet sets a CARoot returned by TestCA into the TestAgent state. It requires that TestAgent had connect enabled in it's config. If ca is nil, a new CA is created.

It returns the CARoot passed or created.

Note that we have to use an interface for the TestAgent.RPC method since we can't introduce an import cycle by importing `agent.TestAgent` here directly. It also means this will work in a few other places we mock that method.

func TestCAConfigSetWithKeyType added in v1.6.0

func TestCAConfigSetWithKeyType(t testing.T, a TestAgentRPC,
	ca *structs.CARoot, keyType string, keyBits int) *structs.CARoot

TestCAConfigSetWithKeyType is similar to TestCAConfigSet, except that it takes two additional arguments to override the default private key type and size.

func TestCAWithKeyType added in v1.6.0

func TestCAWithKeyType(t testing.T, xc *structs.CARoot, keyType string, keyBits int) *structs.CARoot

TestCAWithKeyType is similar to TestCA, except that it takes two additional arguments to override the default private key type and size.

func TestCAWithTTL added in v1.8.7

func TestCAWithTTL(t testing.T, xc *structs.CARoot, ttl time.Duration) *structs.CARoot

TestCAWithTTL is similar to TestCA, except that it takes a custom duration for the lifetime of the certificate.

func TestCSR

func TestCSR(t testing.T, uri CertURI) (string, string)

TestCSR returns a CSR to sign the given service along with the PEM-encoded private key for this certificate.

func TestLeaf

func TestLeaf(t testing.T, service string, root *structs.CARoot) (string, string)

TestLeaf returns a valid leaf certificate and it's private key for the named service with the given CA Root.

func TestLeafWithNamespace added in v1.7.0

func TestLeafWithNamespace(t testing.T, service, namespace string, root *structs.CARoot) (string, string)

func UpstreamSNI added in v1.6.0

func UpstreamSNI(u *structs.Upstream, subset string, dc string, trustDomain string) string

func ValidateLeaf added in v1.7.0

func ValidateLeaf(caPEM string, leafPEM string, intermediatePEMs []string) error

ValidateLeaf is a convenience helper that returns an error if the certificate provided in leadPEM does not validate against the CAs provided. If there is an intermediate CA then it's cert must be in caPEMs as well as the root.

Types

type CertURI

type CertURI interface {
	// URI is the valid URI value used in the cert.
	URI() *url.URL
}

CertURI represents a Connect-valid URI value for a TLS certificate. The user should type switch on the various implementations in this package to determine the type of URI and the data encoded within it.

Note that the current implementations of this are all also SPIFFE IDs. However, we anticipate that we may accept URIs that are also not SPIFFE compliant and therefore the interface is named as such.

func ParseCertURI

func ParseCertURI(input *url.URL) (CertURI, error)

ParseCertURI parses a the URI value from a TLS certificate.

func ParseCertURIFromString added in v1.3.0

func ParseCertURIFromString(input string) (CertURI, error)

ParseCertURIFromString attempts to parse a string representation of a certificate URI as a convenience helper around ParseCertURI.

type SpiffeIDAgent added in v1.5.2

type SpiffeIDAgent struct {
	Host       string
	Partition  string
	Datacenter string
	Agent      string
}

SpiffeIDService is the structure to represent the SPIFFE ID for an agent.

func (SpiffeIDAgent) GetEnterpriseMeta added in v1.11.0

func (id SpiffeIDAgent) GetEnterpriseMeta() *acl.EnterpriseMeta

GetEnterpriseMeta will synthesize an EnterpriseMeta struct from the SpiffeIDAgent. in OSS this just returns an empty (but never nil) struct pointer

func (SpiffeIDAgent) PartitionOrDefault added in v1.11.0

func (id SpiffeIDAgent) PartitionOrDefault() string

func (SpiffeIDAgent) URI added in v1.5.2

func (id SpiffeIDAgent) URI() *url.URL

URI returns the *url.URL for this SPIFFE ID.

type SpiffeIDService

type SpiffeIDService struct {
	Host       string
	Partition  string
	Namespace  string
	Datacenter string
	Service    string
}

SpiffeIDService is the structure to represent the SPIFFE ID for a service.

func TestSpiffeIDService

func TestSpiffeIDService(t testing.T, service string) *SpiffeIDService

TestSpiffeIDService returns a SPIFFE ID representing a service.

func TestSpiffeIDServiceWithHost

func TestSpiffeIDServiceWithHost(t testing.T, service, host string) *SpiffeIDService

TestSpiffeIDServiceWithHost returns a SPIFFE ID representing a service with the specified trust domain.

func TestSpiffeIDServiceWithHostDC added in v1.8.7

func TestSpiffeIDServiceWithHostDC(t testing.T, service, host, datacenter string) *SpiffeIDService

TestSpiffeIDServiceWithHostDC returns a SPIFFE ID representing a service with the specified trust domain for the given datacenter.

func (SpiffeIDService) GetEnterpriseMeta added in v1.7.0

func (id SpiffeIDService) GetEnterpriseMeta() *acl.EnterpriseMeta

GetEnterpriseMeta will synthesize an EnterpriseMeta struct from the SpiffeIDService. in OSS this just returns an empty (but never nil) struct pointer

func (SpiffeIDService) MatchesPartition added in v1.11.0

func (id SpiffeIDService) MatchesPartition(partition string) bool

func (SpiffeIDService) NamespaceOrDefault added in v1.11.0

func (id SpiffeIDService) NamespaceOrDefault() string

func (SpiffeIDService) PartitionOrDefault added in v1.11.0

func (id SpiffeIDService) PartitionOrDefault() string

func (SpiffeIDService) URI

func (id SpiffeIDService) URI() *url.URL

URI returns the *url.URL for this SPIFFE ID.

type SpiffeIDSigning

type SpiffeIDSigning struct {
	ClusterID string // Unique cluster ID
	Domain    string // The domain, usually "consul"
}

SpiffeIDSigning is the structure to represent the SPIFFE ID for a signing certificate (not a leaf service).

func SpiffeIDSigningForCluster

func SpiffeIDSigningForCluster(clusterID string) *SpiffeIDSigning

SpiffeIDSigningForCluster returns the SPIFFE signing identifier (trust domain) representation of the given CA config. If config is nil this function will panic.

NOTE(banks): we intentionally fix the tld `.consul` for now rather than tie this to the `domain` config used for DNS because changing DNS domain can't break all certificate validation. That does mean that DNS prefix might not match the identity URIs and so the trust domain might not actually resolve which we would like but don't actually need.

func (SpiffeIDSigning) CanSign

func (id SpiffeIDSigning) CanSign(cu CertURI) bool

CanSign takes any CertURI and returns whether or not this signing entity is allowed to sign CSRs for that entity (i.e. represents the trust domain for that entity).

I choose to make this a fixed centralized method here for now rather than a method on CertURI interface since we don't intend this to be extensible outside and it's easier to reason about the security properties when they are all in one place with "allowlist" semantics.

func (SpiffeIDSigning) Host

func (id SpiffeIDSigning) Host() string

Host is the canonical representation as a DNS-compatible hostname.

func (SpiffeIDSigning) URI

func (id SpiffeIDSigning) URI() *url.URL

URI returns the *url.URL for this SPIFFE ID.

type TestAgentRPC

type TestAgentRPC interface {
	RPC(method string, args interface{}, reply interface{}) error
}

TestAgentRPC is an interface that an RPC client must implement. This is a helper interface that is implemented by the agent delegate so that test helpers can make RPCs without introducing an import cycle on `agent`.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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