connect

package
v1.7.11 Latest Latest
Warning

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

Go to latest
Published: Dec 10, 2020 License: MPL-2.0 Imports: 26 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 AgentCN added in v1.7.0

func AgentCN(node, trustDomain string) string

AgentCN returns the common name for an agent certificate. See ServiceCN for more details on rationale.

Format is:

<sanitized_node_name>.agnt.<trust_domain_first_8>.consul

node name is sanitized by removing any chars that are not legal in a DNS
name and lower casing. It is truncated to the first X chars to keep the
total at 64.

trust domain is truncated to keep the whole name short

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. See ServiceCN for more details on rationale. 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 CNForCertURI added in v1.7.0

func CNForCertURI(uri CertURI) (string, error)

CNForCertURI returns the correct common name for a given cert URI type. It doesn't work for CA Signing IDs since more context is needed and CA Providers always know their CN from their own context.

func CalculateCertFingerprint

func CalculateCertFingerprint(pemValue string) (string, error)

CalculateCertFingerprint parses the x509 certificate from a PEM-encoded value and calculates the SHA-1 fingerprint.

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, commonName string, 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, commonName string, 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 DatacenterSNI added in v1.6.0

func DatacenterSNI(dc string, trustDomain string) string

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 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 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 ServiceCN added in v1.7.0

func ServiceCN(serviceName, namespace, trustDomain string) string

ServiceCN returns the common name for a service's certificate. We can't use SPIFFE URIs because some CAs require valid FQDN format. We can't use SNI values because they are often too long than the 64 bytes allowed by CommonNames. We could attempt to encode more information into this to make identifying which instance/node it was issued to in a management tool easier but that just introduces more complications around length. It's also strange that the Common Name would encode more information than the actual identifying URI we use to assert anything does and my lead to bad assumptions that the common name is in some way "secure" or verified - there is nothing inherently provable here except that the requestor had ACLs for that service name in that DC.

Format is:

<sanitized_service_name>.svc.<trust_domain_first_8>.consul

service name is sanitized by removing any chars that are not legal in a DNS
name and lower casing. It is truncated to the first X chars to keep the
total at 64.

trust domain is truncated to keep the whole name short

func ServiceSNI added in v1.6.0

func ServiceSNI(service string, subset string, namespace 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 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 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 {
	// Authorize tests the authorization for this URI as a client
	// for the given intention. The return value `auth` is only valid if
	// the second value `match` is true. If the second value `match` is
	// false, then the intention doesn't match this client and any
	// result should be ignored.
	Authorize(*structs.Intention) (auth bool, match bool)

	// 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
	Datacenter string
	Agent      string
}

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

func (*SpiffeIDAgent) Authorize added in v1.5.2

func (id *SpiffeIDAgent) Authorize(_ *structs.Intention) (bool, bool)

CertURI impl.

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
	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 (*SpiffeIDService) Authorize

func (id *SpiffeIDService) Authorize(ixn *structs.Intention) (bool, bool)

CertURI impl.

func (*SpiffeIDService) GetEnterpriseMeta added in v1.7.0

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

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

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(config *structs.CAConfiguration) *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) Authorize

func (id *SpiffeIDSigning) Authorize(ixn *structs.Intention) (bool, bool)

CertURI impl.

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 "whitelist" 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