cryptparse

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2024 License: BSD-3-Clause Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	MaxTlsCipher   uint16      = tls.TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
	MaxCurveId     tls.CurveID = tls.X25519 // 29
	MinTlsVer      uint16      = tls.VersionSSL30
	MaxTlsVer      uint16      = tls.VersionTLS13
	DefaultNetType string      = "tcp"
)
View Source
const (
	/*
		TlsUriParamCa specifies a path to a CA certificate PEM-encded DER file.

		It may be specified multiple times in a TLS URI.
	*/
	TlsUriParamCa string = "pki_ca"
	/*
		TlsUriParamCert specifies a path to a client certificate PEM-encded DER file.

		It may be specified multiple times in a TLS URI.
	*/
	TlsUriParamCert string = "pki_cert"
	/*
		TlsUriParamKey specifies a path to a private key as a PEM-encded file.

		It may be PKCS#1, PKCS#8, or PEM-encoded ASN.1 DER EC key.

		Supported private key types are RSA, ED25519, ECDSA, and ECDH.

		It may be specified multiple times in a TLS URI.
	*/
	TlsUriParamKey string = "pki_key"
	/*
		TlsUriParamNoVerify, if `1`, `yes`, `y`, or `true` indicate
		that the TLS connection should not require verification of
		the remote end (e.g. hostname matches, trusted chain, etc.).

		Any other value for this parameter will be parsed as "False"
		(meaning the remote end's certificate SHOULD be verified).

		Only the first defined instance is parsed.
	*/
	TlsUriParamNoVerify string = "no_verify"
	/*
		TlsUriParamSni indicates that the TLS connection should expect this hostname
		instead of the hostname specified in the URI itself.

		Only the first defined instance is parsed.
	*/
	TlsUriParamSni string = "sni"
	/*
		TlsUriParamCipher specifies one (or more) cipher(s)
		to specify for the TLS connection cipher negotiation.
		Note that TLS 1.3 has a fixed set of ciphers, and
		this list may not be respected by the remote end.

		The string may either be the name (as per
		https://www.iana.org/assignments/tls-parameters/tls-parameters.xml)
		or an int (normal, hex, etc. string representation).

		It may be specified multiple times in a TLS URI.
	*/
	TlsUriParamCipher string = "cipher"
	/*
		TlsUriParamCurve specifies one (or more) curve(s)
		to specify for the TLS connection cipher negotiation.

		It may be specified multiple times in a TLS URI.
	*/
	TlsUriParamCurve string = "curve"
	/*
		TlsUriParamMinTls defines the minimum version of the
		TLS protocol to use.
		It is recommended to use "TLS_1.3".

		Supported syntax formats include:

			* TLS_1.3
			* 1.3
			* v1.3
			* TLSv1.3
			* 0x0304 (legacy_version, see RFC8446 § 4.1.2)
			* 774 (0x0304 in int form)
			* 0o1404 (0x0304 in octal form)

		All evaluate to TLS 1.3 in this example.

		Only the first defined instance is parsed.
	*/
	TlsUriParamMinTls string = "min_tls"
	/*
		TlsUriParamMaxTls defines the minimum version of the
		TLS protocol to use.

		See TlsUriParamMinTls for syntax of the value.

		Only the first defined instance is parsed.
	*/
	TlsUriParamMaxTls string = "max_tls"
	/*
		TlsUriParamNet is used by TlsUri.ToConn and TlsUri.ToTlsConn to explicitly specify a network.

		The default is "tcp".

		See net.Dial()'s "network" parameter for valid network types.

		Only the first defined instance is parsed.
	*/
	TlsUriParamNet string = "net"
)

TlsUriParam* specifiy URL query parameters to parse a tls:// URI, and are used by TlsUri methods.

Variables

View Source
var (
	ErrBadTlsCipher  error = errors.New("invalid TLS cipher suite")
	ErrBadTlsCurve   error = errors.New("invalid TLS curve")
	ErrBadTlsVer     error = errors.New("invalid TLS version")
	ErrUnknownCipher error = errors.New("unknown TLS cipher")
	ErrUnknownKey    error = errors.New("unknown key type")
)

Functions

func IsMatchedPair

func IsMatchedPair(privKey crypto.PrivateKey, cert *x509.Certificate) (isMatched bool, err error)

IsMatchedPair returns true if the privateKey is paired with the cert.

func ParseCA

func ParseCA(certRaw []byte) (certPool *x509.CertPool, rootCerts []*x509.Certificate, intermediateCerts []*x509.Certificate, err error)

ParseCA parses PEM bytes and returns an *x509.CertPool in caCerts.

Concatenated PEM files are supported.

Any keys found will be filtered out, as will any leaf certificates.

Any *intermediate* CAs (the certificate is a CA but it is not self-signed) will be returned separate from certPool.

Ordering from the file is preserved in the returned slices.

func ParseLeafCert

func ParseLeafCert(certRaw []byte, keys []crypto.PrivateKey, intermediates ...*x509.Certificate) (tlsCerts []tls.Certificate, err error)

ParseLeafCert parses PEM bytes from a (client) certificate file, iterates over a slice of crypto.PrivateKey (finding one that matches), and returns one (or more) tls.Certificate.

The key may also be combined with the certificate in the same file.

If no private key matches or no client cert is found in the file, tlsCerts will be nil/missing that certificate but no error will be returned. This behavior can be avoided by passing a nil slice to keys.

Any leaf certificates ("server" certificate, as opposed to a signer/issuer) found in the file will be assumed to be the desired one(s).

Any additional/supplementary intermediates may be provided. Any present in the PEM bytes (certRaw) will be included.

Any *root* CAs found will be discarded. They should/can be extracted seperately via ParseCA.

The parsed and paired certificates and keys can be found in each respective tls.Certificate.Leaf and tls.Certificate.PrivateKey. Any certs without a corresponding key will be discarded.

func ParsePrivateKey

func ParsePrivateKey(keyRaw []byte) (keys []crypto.PrivateKey, err error)

ParsePrivateKey parses PEM bytes to a private key. Multiple keys may be concatenated in the same file.

Any public keys, certificates, etc. found will be discarded.

func ParseTlsCipher

func ParseTlsCipher(s string) (cipherSuite uint16, err error)

ParseTlsCipher parses string s and attempts to derive a TLS cipher suite (as a uint16) from it. Use ParseTlsCipherSuite if you wish for a tls.CipherSuite instead.

The string may either be the name (as per https://www.iana.org/assignments/tls-parameters/tls-parameters.xml) or an int (normal, hex, etc. string representation).

If none is found, the default is MaxTlsCipher.

func ParseTlsCipherStrict

func ParseTlsCipherStrict(s string) (cipherSuite uint16, err error)

ParseTlsCipherStrict is like ParseTlsCipher, but an ErrBadTlsCipher or ErrUnknownCipher error will be raised if no matching cipher is found.

func ParseTlsCipherSuite

func ParseTlsCipherSuite(s string) (cipherSuite *tls.CipherSuite, err error)

ParseTlsCipherSuite is like ParseTlsCipher but returns a *tls.CipherSuite instead of a uint16 TLS cipher identifier.

func ParseTlsCipherSuiteStrict

func ParseTlsCipherSuiteStrict(s string) (cipherSuite *tls.CipherSuite, err error)

ParseTlsCipherSuiteStrict is like ParseTlsCipherSuite, but an ErrBadTlsCipher or ErrUnknownCipher error will be raised if no matching cipher is found.

func ParseTlsCipherSuites

func ParseTlsCipherSuites(s string) (cipherSuites []*tls.CipherSuite, err error)

ParseTlsCipherSuites is like ParseTlsCiphers but returns a []*tls.CipherSuite instead of a []uint16 of TLS cipher identifiers.

func ParseTlsCiphers

func ParseTlsCiphers(s string) (cipherSuites []uint16)

ParseTlsCiphers parses s as a comma-separated list of cipher suite names/integers and returns a slice of suites.

See ParseTlsCipher for details, as this is mostly just a wrapper around it.

If no cipher suites are found, cipherSuites will only contain MaxTlsCipher.

func ParseTlsCurve

func ParseTlsCurve(s string) (curve tls.CurveID, err error)

ParseTlsCurve parses string s and attempts to derive a tls.CurveID from it.

The string may either be the name (as per // https://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-8) or an int (normal, hex, etc. string representation).

func ParseTlsCurves

func ParseTlsCurves(s string) (curves []tls.CurveID)

ParseTlsCurves parses s as a comma-separated list of tls.CurveID names/integers and returns a slice of tls.CurveID.

See ParseTlsCurve for details, as this is mostly just a wrapper around it.

If no curves are found, curves will only contain MaxCurveId.

func ParseTlsUri

func ParseTlsUri(tlsUri *url.URL) (tlsConf *tls.Config, err error)

ParseTlsUri parses a "TLS URI"'s query parameters. All certs and keys must be in PEM format.

You probably don't need this and should instead be using TlsUri.ToTlsConfig. It just wraps this, but is probably more convenient.

func ParseTlsVersion

func ParseTlsVersion(s string) (tlsVer uint16, err error)

ParseTlsVersion parses string s and attempts to derive a TLS version from it. If none is found, tlsVer will be 0.

func SplitPem

func SplitPem(pemRaw []byte) (blocks []*pem.Block, err error)

SplitPem splits a single block of bytes into one (or more) (encoding/)pem.Blocks. Currently err is not used, but is reserved for future use.

Types

type PemBlocks

type PemBlocks []*pem.Block

PemBlocks is a combined set of multiple pem.Blocks.

func SplitPemBlocks

func SplitPemBlocks(pemRaw []byte) (blocks *PemBlocks, err error)

SplitPemBlocks splits a single block of bytes into a PemBlocks. Currently err is not used, but is reserved for future use.

func (*PemBlocks) Bytes

func (p *PemBlocks) Bytes() (combined []byte)

Bytes returns a combined PEM bytes of all blocks in a PemBlocks. Any nil, empty, or otherwise invalid blocks are skipped.

func (*PemBlocks) BytesSplit

func (p *PemBlocks) BytesSplit() (pems [][]byte)

BytesSplit returns separate PEM bytes of each block in a PemBlocks. Any nil, empty, or otherwise invalid blocks are skipped.

func (*PemBlocks) BytesSplitStrict

func (p *PemBlocks) BytesSplitStrict() (pems [][]byte, err error)

BytesSplitStrict is like BytesSplit but is much more strict/safe (invalid/empty/nil blocks are not skipped) and will return any errors on encoding.

func (*PemBlocks) BytesStrict

func (p *PemBlocks) BytesStrict() (combined []byte, err error)

BytesStrict is like Bytes but is much more strict/safe (invalid/empty/nil blocks are not skipped) and will return any errors on encoding.

func (*PemBlocks) Split

func (p *PemBlocks) Split() (native []*pem.Block)

Split returns a more primitive-friendly representation of a PemBlocks.

type TlsFlat

type TlsFlat struct {
	XMLName xml.Name `xml:"tlsConfig" json:"-" yaml:"-" toml:"-"`
	// SniName represents the expected Server Name Indicator's name. See TlsUriParamSni.
	SniName string `json:"sni_name"  toml:"SNIName"  yaml:"SNI Name" xml:"sniName,attr" required:"true" validate:"required"`
	// SkipVerify, if true, will bypass certificate verification. You generally should not enable this. See TlsUriParamNoVerify.
	SkipVerify bool `json:"skip_verify,omitempty" toml:"SkipVerify,omitempty"  yaml:"Skip Verification,omitempty" xml:"skipVerify,attr,omitempty"`
	// Certs contains 0 or more TlsFlatCert certificate definitions. See TlsUriParamCert and TlsUriParamKey as well.
	Certs []*TlsFlatCert `` /* 127-byte string literal not displayed */
	// CaFiles contains filepaths to CA certificates/"trust anchors" in PEM format. They may be combined. See TlsUriParamCa.
	CaFiles []string `` /* 137-byte string literal not displayed */
	// CipherSuites represents desired ciphers/cipher suites for this TLS environment. See TlsUriParamCipher.
	CipherSuites []string `json:"cipher_suites,omitempty" toml:"CipherSuites,omitempty"  yaml:"Cipher Suites,omitempty" xml:"ciphers,omitempty"`
	// Curves specifies desired cryptographic curves to be used. See TlsUriParamCurve.
	Curves []string `` /* 126-byte string literal not displayed */
	// MinTlsProtocol specifies the minimum TLS version. See TlsUriParamMinTls.
	MinTlsProtocol *string `` /* 133-byte string literal not displayed */
	// MaxTlsProtocol specifies the maximum TLS version. See TlsUriParamMaxTls.
	MaxTlsProtocol *string `` /* 133-byte string literal not displayed */
}

TlsFlat provides an easy structure to marshal/unmarshal a tls.Config from/to a data structure (JSON, XML, etc.).

func (*TlsFlat) Normalize

func (t *TlsFlat) Normalize() (err error)

Normalize ensures that all specified filepaths are absolute, etc.

func (*TlsFlat) ToTlsConfig

func (t *TlsFlat) ToTlsConfig() (tlsConf *tls.Config, err error)

ToTlsConfig returns a tls.Config from a TlsFlat. Note that it will have Normalize called on it.

Unfortunately it's not possible for this library to do the reverse, as CA certificates are not able to be extracted from an x509.CertPool.

func (*TlsFlat) ToTlsUri

func (t *TlsFlat) ToTlsUri() (tlsUri *TlsUri, err error)

ToTlsUri returns a TlsUri from a TlsFlat.

type TlsFlatCert

type TlsFlatCert struct {
	XMLName xml.Name `xml:"cert" json:"-" yaml:"-" toml:"-"`
	// KeyFile is a filepath to a PEM-encoded key file. See TlsUriParamKey.
	KeyFile *string `json:"key,omitempty" xml:"key,attr,omitempty" yaml:"Key,omitempty" toml:"Key,omitempty" validate:"omitempty,filepath"`
	// CertFile is a filepath to a PEM-encoded certificate file. See TlsUriParamCert.
	CertFile string `json:"cert" xml:",chardata" yaml:"Certificate" toml:"Certificate" required:"true" validate:"required,filepath"`
}

TlsFlatCert represents a certificate (and, possibly, paired key).

type TlsPkiChain

type TlsPkiChain struct {
	/*
		Roots are all trust anchors/root certificates.

		Roots are certificates that are self-signed and can issue certificates/sign CSRs.
	*/
	Roots []*x509.Certificate
	// RootsPool is an x509.CertPool representation of Roots.
	RootsPool *x509.CertPool
	/*
		Intermediates are signers that should not be trusted directly, but instead included in the verification/validation chain.

		Intermediates are certificates that are NOT self-signed (they should be signed by at least one Roots/RootsPool)
		but CAN issue certificates/sign CSRs.
	*/
	Intermediates []*x509.Certificate
	// IntermediatesPool is an x509.CertPool representation of Intermediates.
	IntermediatesPool *x509.CertPool
	/*
		Certificates are "leaf certificates"; typically these are the certificates used directly by servers/users.

		A certificate is considered a Certificate here if it is NOT self-signed and is NOT able to issue certificates/sign CSRs.
	*/
	Certificates []*tls.Certificate
	// CertificatesPool is an x509.CertPool representation of Certificates.
	CertificatesPool *x509.CertPool
	/*
		UnmatchedCerts contains Certificates that:
			* Do not match any of Roots/RootsPool as its signer, and/or
			* Do not match any Intermediates/IntermediatesPool as its signer, and/or
			* Does not meet requirements for Roots/RootsPool, and/or
			* Does not meet requirements for Intermediates/IntermediatesPool, and/or
			* Has no matching crypto.PrivateKey found.

		These should generally *never* be used if they were parsed in.
		They represent "stray" certificates that have no logical chain/path found
		and are likely unusable for purposes of this environment.
	*/
	UnmatchedCerts []*x509.Certificate
	// UnmatchedCertsPool is an x509.CertPool representation of UnmatchedCerts.
	UnmatchedCertsPool *x509.CertPool
	/*
		UnmatchedKeys represent parsed private keys that have no matching corresponding certifificate.

		These should generally *never* be used if they were parsed in.
		They represent "stray" keys that have no logical chain/path found
		and are likely unusable for purposes of this environment.
	*/
	UnmatchedKeys []crypto.PrivateKey
	// DhParams represent any found DH parameters. This will usually be empty.
	DhParams []*dhparam.DH
}

TlsPkiChain contains a whole X.509 PKI chain -- Root CA(s) (trust anchors) which sign Intermediate(s) which sign Certificate(s).

type TlsUri

type TlsUri struct {
	*url.URL
}

func FromURL

func FromURL(u *url.URL) (t *TlsUri)

FromURL returns a *TlsUri from a *url.URL.

func (*TlsUri) ToConn

func (t *TlsUri) ToConn() (conn net.Conn, err error)

ToConn returns a "bare" net.Conn (already dialed) from a TlsUri.

Note that this does NOT include the TLS configured or initialized; use TlsUri.ToTlsConn for that. (A (crypto/)tls.Conn conforms to net.Conn.)

An error will be returned if no port is explicitly defined in the TlsUri.

func (*TlsUri) ToTlsConfig

func (t *TlsUri) ToTlsConfig() (cfg *tls.Config, err error)

ToTlsConfig returns a *tls.Config from a TlsUri.

Unfortunately it's not possible for this library to do the reverse, as CA certificates are not able to be extracted from an x509.CertPool.

func (*TlsUri) ToTlsConn

func (t *TlsUri) ToTlsConn() (conn *tls.Conn, err error)

ToTlsConn returns a (crypto/)tls.Conn (already dialed) from a TlsUri.

An error will be returned if no port is explicitly defined in the TlsUri.

func (*TlsUri) ToTlsFlat

func (t *TlsUri) ToTlsFlat() (tlsFlat *TlsFlat, err error)

ToTlsFlat returns a *TlsFlat from a TlsUri.

func (*TlsUri) ToURL

func (t *TlsUri) ToURL() (u *url.URL)

ToURL returns the *url.URL representation of a TlsUri. Note that the params will remain, so remove them explicitly if needed.

func (*TlsUri) WithConn

func (t *TlsUri) WithConn(underlying net.Conn) (conn *tls.Conn, err error)

WithConn returns a (crypto/)tls.Conn from an existing/already dialed net.Conn.

underlying should be a "bare" net.Conn; behavior is undefined/unknown if the underlying conn is already a (crypto/)tls.Conn.

Jump to

Keyboard shortcuts

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