Documentation ¶
Overview ¶
Package network contains network utilities for wrapping net.Conn into Themis SecureSession, or TLS wrapper, or provide unified interface for raw connection. ConnectionWrappers are used in most Acra components.
Index ¶
- Constants
- Variables
- func BuildConnectionString(protocol, host string, port int, path string) string
- func Dial(connectionString string) (net.Conn, error)
- func GetClientIDFromAuthInfo(authInfo credentials.AuthInfo, tlsExtractor TLSClientIDExtractor) ([]byte, error)
- func GetClientIDFromConnection(conn net.Conn, tlsExtractor TLSClientIDExtractor) ([]byte, bool)
- func GetClientIDFromHTTPContext(ctx context.Context) ([]byte, bool)
- func GetClientIDFromTLSConn(conn *tls.Conn, extractor TLSClientIDExtractor) ([]byte, error)
- func GetConnectionFromHTTPContext(ctx context.Context) net.Conn
- func GetDriverConnectionStringHost(connectionString string, useMySQL bool) (string, error)
- func IsClientBadRecordMacError(err error) bool
- func IsClientUnknownCAError(err error) bool
- func IsDatabaseUnknownCAError(err error) bool
- func IsMissingClientCertificate(err error) bool
- func IsSNIError(err error) bool
- func Listen(connectionString string) (net.Listener, error)
- func ListenerFileDescriptor(socket net.Listener) (uintptr, error)
- func NewTLSConfig(serverName string, caPath, keyPath, crtPath string, ...) (*tls.Config, error)
- func NewTLSConfigByName(extractor *args.ServiceExtractor, name, host string, ...) (*tls.Config, error)
- func NewTLSConfigFromBaseArgs() (*tls.Config, error)
- func ProxyWithTracing(context context.Context, connFrom, connTo net.Conn, errCh chan<- error)
- func RegisterCertVerifierArgs(flags *flag.FlagSet)
- func RegisterCertVerifierArgsForService(flags *flag.FlagSet, serviceName string, namerFunc CLIParamNameConstructorFunc)
- func RegisterTLSArgsForService(flags *flag.FlagSet, isClient bool, name string, ...)
- func RegisterTLSBaseArgs(flags *flag.FlagSet)
- func SNIOrHostname(sni, hostname string) string
- func SetClientIDToHTTPContext(ctx context.Context, clientID []byte) context.Context
- func SetConnectionToHTTPContext(ctx context.Context, conn net.Conn) context.Context
- func SetTLSBaseArgs(extractor *args.ServiceExtractor)
- func SplitConnectionString(connectionString string) (string, int, error)
- func UnwrapSafeCloseConnection(conn net.Conn) net.Conn
- func UnwrapSafeCloseListener(listener net.Listener) net.Listener
- func ValidateClientsAuthenticationCertificate(certificate *x509.Certificate) error
- type CLIParamNameConstructorFunc
- type CRLCache
- type CRLCacheItem
- type CRLClient
- type CRLConfig
- type CRLError
- type CallbackError
- type CertVerifier
- type CertVerifierAll
- type CertificateIdentifierExtractor
- type ClientIDToContextCallback
- type ConnectionCallback
- type ConnectionContextCallback
- type ConnectionManager
- type ConnectionMetadata
- type ConnectionMetadataBuilder
- func (builder *ConnectionMetadataBuilder) ClientID() ([]byte, bool)
- func (builder *ConnectionMetadataBuilder) SetClientID(c []byte) *ConnectionMetadataBuilder
- func (builder *ConnectionMetadataBuilder) SetSpanContext(c trace.SpanContext) *ConnectionMetadataBuilder
- func (builder *ConnectionMetadataBuilder) SpanContext() (trace.SpanContext, bool)
- type ConnectionMetric
- type ConnectionTimeoutWrapper
- type ConnectionToContextCallback
- type ConnectionWrapper
- type DeadlineListener
- type DefaultCRLClient
- type DefaultCRLVerifier
- type DefaultOCSPClient
- type DefaultOCSPVerifier
- type DistinguishedNameExtractor
- type GRPCConnectionClientIDExtractor
- type GRPCConnectionWrapper
- type HTTPServerConnectionChainWrapper
- func (wrapper *HTTPServerConnectionChainWrapper) Accept() (net.Conn, error)
- func (wrapper *HTTPServerConnectionChainWrapper) AddCallback(callback ConnectionCallback)
- func (wrapper *HTTPServerConnectionChainWrapper) AddConnectionContextCallback(callback ConnectionContextCallback)
- func (wrapper *HTTPServerConnectionChainWrapper) OnConnectionContext(ctx context.Context, c net.Conn) context.Context
- func (wrapper *HTTPServerConnectionChainWrapper) SetListener(listener net.Listener)
- func (wrapper *HTTPServerConnectionChainWrapper) Unwrap() net.Listener
- type HTTPServerConnectionWrapper
- type HexIdentifierConverter
- type IdentifierConverter
- type LRUCRLCache
- type ListenerWithFileDescriptor
- type ListenerWrapper
- type MetricConnectionCallback
- type OCSPClient
- type OCSPConfig
- type OnServerHandshakeCallback
- type RawConnectionWrapper
- type SafeCloseConnectionCallback
- type SerialNumberExtractor
- type TLSClientIDExtractor
- type TLSConnectionWrapper
- func NewTLSAuthenticationConnectionWrapper(useClientIDFromCertificate bool, clientConfig, serverConfig *tls.Config, ...) (*TLSConnectionWrapper, error)
- func NewTLSAuthenticationHTTP2ConnectionWrapper(useClientIDFromCertificate bool, clientConfig, serverConfig *tls.Config, ...) (*TLSConnectionWrapper, error)
- func NewTLSConnectionWrapper(clientID []byte, config *tls.Config) (*TLSConnectionWrapper, error)
- func (wrapper *TLSConnectionWrapper) AddOnServerHandshakeCallback(callback OnServerHandshakeCallback)
- func (wrapper *TLSConnectionWrapper) OnConnection(conn net.Conn) (net.Conn, error)
- func (wrapper *TLSConnectionWrapper) ServerHandshake(conn net.Conn) (net.Conn, credentials.AuthInfo, error)
- func (wrapper *TLSConnectionWrapper) WrapClient(ctx context.Context, conn net.Conn) (net.Conn, error)
- func (wrapper *TLSConnectionWrapper) WrapServer(ctx context.Context, conn net.Conn) (net.Conn, []byte, error)
- type WrappedConnection
Constants ¶
const ( // If certificate contains CRL distribution point(s), use them, _after_ trying configured URL CrlFromCertUseStr = "use" // If certificate contains CRL distribution point(s), use them, and don't use configured URL in this case CrlFromCertTrustStr = "trust" // If certificate contains CRL distribution point(s), use them, _before_ trying configured URL CrlFromCertPreferStr = "prefer" // Ignore CRL distribution points listed in certificate CrlFromCertIgnoreStr = "ignore" )
--tls_crl_from_cert=<use|trust|prefer|ignore>
const ( // CrlDefaultCacheSize is default value for `--tls_crl_cache_size` CrlDefaultCacheSize = 16 // CrlCacheSizeMax is max value for `--tls_crl_cache_size` CrlCacheSizeMax = 1_000_000 // CrlDisableCacheSize will disable caching if set in `--tls_crl_cache_size` CrlDisableCacheSize = 0 // CrlCacheTimeMax is max value for `--tls_crl_cache_time` CrlCacheTimeMax = 300 // CrlDisableCacheTime will disable caching if set in `--tls_crl_cache_time` CrlDisableCacheTime = 0 )
const ( // CrlHTTPClientDefaultTimeout is default timeout for HTTP client used to fetch CRLs CrlHTTPClientDefaultTimeout = time.Second * time.Duration(20) // SerialEncodeBase is base in which certificate serial is encoded, for being a key in map of revoked certificates SerialEncodeBase = 32 )
const ( DatabaseSideSNIErrorSuggestion = "" + "Acra-server configured with --db_host=<db_host> and --tls_database_sni=<sni> that don't " + "match \"Subject Alternative Name\" in database's certificate. Check which domains are present in the" + "certificate for database with command: \"openssl x509 -noout -ext subjectAltName -in <cert_path>>\" " + "and set one of the domains as acra-server's parameter \"--tls_database_sni\"" DatabaseSideUnknownCAErrorSuggestions = "" + "The database sent certificate that cannot be verified by CA certificate set in \"--tls_database_ca\" (\"--tls_ca\") " + "acra-server's parameters. Set the same CA certificate that you use for the database." ClientSideBadMacErrorSuggestion = "" + "Possible cause of the error is that the client application cannot verify acra-server's certificate. The application or its DB driver haven't " + "CA certificate related to acra-server's certificate. Configure your application to use acra-server's CA too." ClientSideUnknownCAErrorSuggestion = "" + "The client app has sent a certificate signed by unknown CA. Configure acra-server to use CA certificate used to sign client's " + "certificate with parameter \"--tls_client_ca=<path>\"." ClientSideNoCertificateErrorSuggestion = "The client application doesn't send TLS certificate. Check that the application configured with appropriate " + "SSLMODE that turn on usage TLS for connections, configured private key with certificate. Additionally, check that private " + "key has 0600 permissions, and the database supports TLS." CRLCheckErrorSuggestion = "Ensure that the CRL server is up and responding. Acra-server uses CRL server's configured with " + "--tls_crl_client_url | --tls_crl_database_url parameters and specified in client's/databases's " + "certificates. You can get CRL urls from certificates with command: \"openssl x509 -noout -ext crlDistributionPoints -in <path>\". " + "For test purposes you can disable CRL checks with \"--tls_crl_from_cert=ignore\" and empty " + "\"--tls_crl_url=\" parameters for acra-server." OCSPCheckErrorSuggestion = "Check that the OCSP server is up and responding. Acra-server uses OCSP server's configured with " + "--tls_ocsp_client_url | --tls_ocsp_database_url parameters and specified in client's/databases's " + "certificates. You can get OCSP urls from certificates with command: \"openssl x509 -noout -ocsp_uri -in <path>\". " + "For test purposes you can disable OCSP checks with \"--tls_ocsp_from_cert=ignore\" and empty " + "\"--tls_ocsp_url=\" parameters for acra-server." )
set of suggestions to TLS/x509 related errors
const ( // Deny certificates now known by OCSP server(s) OcspRequiredDenyUnknownStr = "denyUnknown" // Allow certificates not known by OCSP server(s) OcspRequiredAllowUnknownStr = "allowUnknown" // Effect of denyUnknown + all available OCSP servers (the one from config // and those listed in certificate) should respond, otherwise deny the certificate OcspRequiredGoodStr = "requireGood" )
Possible values for flag `--tls_ocsp_required`
const ( // Use OCSP servers listed in certificate (if any), try them after the one // configured from CLI/config OcspFromCertUseStr = "use" // Query servers listed in certificate and don't perform further requests // if one respons with "ok, valid" OcspFromCertTrustStr = "trust" // Query servers listed in certificate before the one from config OcspFromCertPreferStr = "prefer" // Ignore OCSP servers listed in certificates OcspFromCertIgnoreStr = "ignore" )
Possible values for flag `--tls_ocsp_from_cert`
const ( IdentifierExtractorTypeDistinguishedName = "distinguished_name" IdentifierExtractorTypeSerialNumber = "serial_number" DefaultIdentifierExtractorTypeDistinguishedName = IdentifierExtractorTypeDistinguishedName )
Set of constants with
const ( GRPCScheme = "grpc" HTTPScheme = "http" )
Custom connection schemes, used in AcraTranslator
const ( // DefaultNetworkTimeout default timeout for network related communication DefaultNetworkTimeout = time.Second * 60 )
const ( // OcspHTTPClientDefaultTimeout is default timeout for HTTP client used to perform OCSP queries OcspHTTPClientDefaultTimeout = time.Second * time.Duration(15) )
Variables ¶
var ( ErrCertWasRevoked = errors.New("certificate was revoked") ErrEmptyCertChain = errors.New("empty verified certificates chain") )
Errors common for OCSP and CRL verifiers
var ( // ErrCantExtractClientID used when can't extract ClientID from gRPC connection handshake ErrCantExtractClientID = errors.New("can't extract ClientID from gRPC connection") // ErrIncorrectGRPCConnectionAuthInfo used if gRPC connection AuthState has unsupported type ErrIncorrectGRPCConnectionAuthInfo = errors.New("incorrect auth info from gRPC connection") )
var ( ErrInvalidConfigCRLFromCert = errors.New("invalid `tls_crl_from_cert` value") ErrInvalidConfigCRLCacheSize = errors.New("invalid `tls_crl_cache_size` value") ErrInvalidConfigCRLCacheTime = errors.New("invalid `tls_crl_cache_time` value") ErrHTTPServerReturnedError = errors.New("server returned non-OK status") ErrFetchDeniedForLocalURL = errors.New("not allowed to fetch from local (file://) URLs") ErrFetchCRLUnsupportedURLScheme = errors.New("cannot fetch CRL, unsupported URL scheme") ErrCacheKeyNotFound = errors.New("cannot find cached CRL with given URL") ErrOutdatedCRL = errors.New("fetched CRLs NextUpdate is behind current time") ErrUnknownCRLExtensionOID = errors.New("unable to process unknown critical extension inside CRL") ErrUnimplementedCRLExtension = errors.New("handling of CRL extension is not yet implemented") )
Errors returned by CRL verifier
var ( ErrInvalidConfigOCSPRequired = errors.New("invalid `ocsp_required` value") ErrInvalidConfigOCSPFromCert = errors.New("invalid `ocsp_from_cert` value") ErrInvalidConfigAllRequiresURL = errors.New("when passing `--tls_ocsp_required=" + OcspRequiredGoodStr + "`, URL is mandatory") ErrOCSPRequiredAllButGotError = errors.New("cannot query OCSP server, but --tls_ocsp_required=" + OcspRequiredGoodStr + " was passed") ErrOCSPUnknownCertificate = errors.New("OCSP server doesn't know about certificate") ErrOCSPNoConfirms = errors.New("none of OCSP servers confirmed the certificate") )
Errors returned by OCSP verifier
var ( ErrNoPeerCertificate = errors.New("no peer tls certificate") ErrCACertificateUsed = errors.New("used CA certificate for authentication") ErrMissedAuthenticationKeyUsage = errors.New("peer certificate doesn't have DigitalSignature key usage or ClientAuth ExtKeyUsage values") )
Set of errors related to peer certificate validation
var CrlFromCertValuesList = []string{ CrlFromCertUseStr, CrlFromCertTrustStr, CrlFromCertPreferStr, CrlFromCertIgnoreStr, }
CrlFromCertValuesList contains all possible values for flag `--tls_crl_from_cert`
var ErrEmptyIdentifier = errors.New("empty identifier")
ErrEmptyIdentifier used when passed empty identifier with zero length
var ErrEmptyTLSConfig = errors.New("empty TLS clientConfig")
ErrEmptyTLSConfig if not TLS clientConfig found
var ErrInvalidIdentifierExtractorType = errors.New("invalid identifier extractor type")
ErrInvalidIdentifierExtractorType return when used invalid value of identifier extractor type
var ErrInvalidTLSConfiguration = errors.New("invalid auth_type for TLS config")
ErrInvalidTLSConfiguration used for invalid configurations for TLS connections
var ErrListenerNotSet = errors.New("listener not set to HTTPServerConnectionWrapper")
ErrListenerNotSet used if net.Listener wasn't set to HTTPServerConnectionWrapper
var ErrNilListener = errors.New("nil listener")
ErrNilListener used if listener is nil
var ErrUnsupportedListener = errors.New("unsupported network Listener type")
ErrUnsupportedListener represents net.Listener type unknown to Acra.
var IdentifierExtractorTypesList = []string{ IdentifierExtractorTypeDistinguishedName, IdentifierExtractorTypeSerialNumber, }
IdentifierExtractorTypesList list of all acceptable types for IdentifierExtractor
var OcspFromCertValuesList = []string{ OcspFromCertUseStr, OcspFromCertTrustStr, OcspFromCertPreferStr, OcspFromCertIgnoreStr, }
OcspFromCertValuesList contains all possible values for flag `--tls_ocsp_from_cert`
var OcspRequiredValuesList = []string{ OcspRequiredDenyUnknownStr, OcspRequiredAllowUnknownStr, OcspRequiredGoodStr, }
OcspRequiredValuesList contains all possible values for flag `--tls_ocsp_required`
Functions ¶
func BuildConnectionString ¶
BuildConnectionString as <protocol>://<host>:<port>/<path>
func Dial ¶
Dial connectionString like protocol://path where protocol is any supported via net.Dial (tcp|unix)
func GetClientIDFromAuthInfo ¶
func GetClientIDFromAuthInfo(authInfo credentials.AuthInfo, tlsExtractor TLSClientIDExtractor) ([]byte, error)
GetClientIDFromAuthInfo extracts clientID data from credentials.AuthInfo if it's saved by SecureSession or TLS wrappers In second case will be used tlsExtractor to extract clientID from TLS metadata
func GetClientIDFromConnection ¶
func GetClientIDFromConnection(conn net.Conn, tlsExtractor TLSClientIDExtractor) ([]byte, bool)
GetClientIDFromConnection extract clientID from conn if it's safeCloseConnection otherwise nil, false
func GetClientIDFromHTTPContext ¶
GetClientIDFromHTTPContext returns clientID if it was set into the context.
func GetClientIDFromTLSConn ¶
func GetClientIDFromTLSConn(conn *tls.Conn, extractor TLSClientIDExtractor) ([]byte, error)
GetClientIDFromTLSConn extracts clientID from tls.Conn metadata using extractor
func GetConnectionFromHTTPContext ¶
GetConnectionFromHTTPContext return net.Conn or nil if not found
func GetDriverConnectionStringHost ¶
GetDriverConnectionStringHost parses MySQL/PostgreSQL driver specific connection string to use as SNI PostgreSQL - postgresql://{user}:{password}@{host}:{port}/{dbname} MySQL - ({user}:{password}@tcp({host}:{port})/{dbname}
func IsClientBadRecordMacError ¶
IsClientBadRecordMacError return true if error related to bad MAC on client side
func IsClientUnknownCAError ¶
IsClientUnknownCAError return true if client's certificate signed by unknown CA
func IsDatabaseUnknownCAError ¶
IsDatabaseUnknownCAError return true if error related to certificate's signature signed by unknown CA
func IsMissingClientCertificate ¶
IsMissingClientCertificate return true if error related to missing client's certificate
func IsSNIError ¶
IsSNIError return true if error related to x509 error with SAN/SNI mismatch
func ListenerFileDescriptor ¶
ListenerFileDescriptor returns file descriptor if listener listens file
func NewTLSConfig ¶
func NewTLSConfig(serverName string, caPath, keyPath, crtPath string, authType tls.ClientAuthType, certVerifier CertVerifier) (*tls.Config, error)
NewTLSConfig creates x509 TLS clientConfig from provided params, tried to load system CA certificate
func NewTLSConfigByName ¶
func NewTLSConfigByName(extractor *args.ServiceExtractor, name, host string, namerFunc CLIParamNameConstructorFunc) (*tls.Config, error)
NewTLSConfigByName returns config related to flags registered via RegisterTLSArgsForService. `host` will be used as ServerName in tls.Config for connection as client to verify server's certificate. If <name>_tls_sni flag specified, then will be used SNI value.
func NewTLSConfigFromBaseArgs ¶
NewTLSConfigFromBaseArgs return new tls clientConfig with params passed by cli params
func ProxyWithTracing ¶
ProxyWithTracing reads data from connFrom, writes data to connTo and trace with OpenCensus
func RegisterCertVerifierArgs ¶
RegisterCertVerifierArgs register CLI args which allow to get CertVerifier by NewCertVerifier()
func RegisterCertVerifierArgsForService ¶
func RegisterCertVerifierArgsForService(flags *flag.FlagSet, serviceName string, namerFunc CLIParamNameConstructorFunc)
RegisterCertVerifierArgsForService register CLI args which allow to get CertVerifier by NewCertVerifier() for specified service
func RegisterTLSArgsForService ¶
func RegisterTLSArgsForService(flags *flag.FlagSet, isClient bool, name string, namerFunc CLIParamNameConstructorFunc)
RegisterTLSArgsForService register CLI args tls_ca|tls_key|tls_cert|tls_auth and flags for certificate verifier which allow to get tls.Config by NewTLSConfigByName function
func RegisterTLSBaseArgs ¶
RegisterTLSBaseArgs register CLI args tls_ca|tls_key|tls_cert|tls_auth which allow to get tls.Config by NewTLSConfigFromBaseArgs function
func SNIOrHostname ¶
SNIOrHostname return sni value if != "". otherwise return hostname without port
func SetClientIDToHTTPContext ¶
SetClientIDToHTTPContext returns new context with the clientID.
func SetConnectionToHTTPContext ¶
SetConnectionToHTTPContext set connection to context and may be used as ConnContext callback for http.Server
func SetTLSBaseArgs ¶
func SetTLSBaseArgs(extractor *args.ServiceExtractor)
SetTLSBaseArgs set global TLS flags from args.ServiceExtractor
func SplitConnectionString ¶
SplitConnectionString to host, port
func UnwrapSafeCloseConnection ¶
UnwrapSafeCloseConnection return wrapped Conn implementation or conn from parameter as is
func UnwrapSafeCloseListener ¶
UnwrapSafeCloseListener return wrapped listener or listener from parameter as is
func ValidateClientsAuthenticationCertificate ¶
func ValidateClientsAuthenticationCertificate(certificate *x509.Certificate) error
ValidateClientsAuthenticationCertificate check that peer's certificate acceptable to use for authentication purpose Check that KeyUsage has DigitalSignature mask or ClientAuth set in ExtKeyUsage list, deny CA certificates to use for peer authentication
Types ¶
type CLIParamNameConstructorFunc ¶
CLIParamNameConstructorFunc func compiles final parameter name for specified service name
func ClientNameConstructorFunc ¶
func ClientNameConstructorFunc() CLIParamNameConstructorFunc
ClientNameConstructorFunc returns CLIParamNameConstructorFunc with "_client_" suffix before parameter name
func DatabaseNameConstructorFunc ¶
func DatabaseNameConstructorFunc() CLIParamNameConstructorFunc
DatabaseNameConstructorFunc returns CLIParamNameConstructorFunc with "_database_" suffix before parameter name
type CRLCache ¶
type CRLCache interface { Get(key string) (*CRLCacheItem, error) Put(key string, value *CRLCacheItem) error Remove(key string) error }
CRLCache is used to store fetched CRLs to avoid downloading the same URL more than once, stores parsed and verified CRLs
type CRLCacheItem ¶
type CRLCacheItem struct { Fetched time.Time // When this CRL was fetched and cached CRL *pkix.CertificateList // Parsed CRL itself RevokedCertificates map[string]*pkix.RevokedCertificate // Copy of CRL.TBSCertList.RevokedCertificates with SerialNumber as key }
CRLCacheItem is combination of fetched+parsed+verified CRL with fetch time
type CRLClient ¶
type CRLClient interface { // Fetch fetches CRL from passed URL (can be either http:// or file://), // allowLocal controls whether file:// will be handled (should not be allowed for URLs from certificates) Fetch(url string, allowLocal bool) ([]byte, error) }
CRLClient is used to fetch CRL from some URL
type CRLConfig ¶
type CRLConfig struct { ClientAuthType tls.ClientAuthType // contains filtered or unexported fields }
CRLConfig contains configuration related to certificate validation using CRL
func NewCRLConfig ¶
func NewCRLConfig(url, fromCert string, checkOnlyLeafCertificate bool, cacheSize, cacheTime uint) (*CRLConfig, error)
NewCRLConfig creates new CRLConfig
func NewCRLConfigByName ¶
func NewCRLConfigByName(extractor *args.ServiceExtractor, name string, namerFunc CLIParamNameConstructorFunc) (*CRLConfig, error)
NewCRLConfigByName return initialized CRLConfig config using flags registered with RegisterCertVerifierArgsForService
type CRLError ¶
type CRLError struct {
// contains filtered or unexported fields
}
CRLError error wrapper to recognize CRL related errors
type CallbackError ¶
type CallbackError struct {
// contains filtered or unexported fields
}
CallbackError returned from OnConnection callbacks
func (CallbackError) Error ¶
func (e CallbackError) Error() string
Error return Error() of wrapped error
type CertVerifier ¶
type CertVerifier interface { // Verify checks whether the certificate is revoked. // The error is returned if: // - the certificate was revoked // - (for OCSP) the certificate is not known by OCSP server and we requested tls_ocsp_required == "denyUnknown" or "requireGood" // - (for OCSP) if we were unable to contact OCSP server(s) but we really need the response, tls_ocsp_required == "requireGood" Verify(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error }
CertVerifier is a generic certificate verifier
func NewCertVerifier ¶
func NewCertVerifier() (CertVerifier, error)
NewCertVerifier creates a CertVerifier based on passed OCSP and CRL command line flags. Ignores `--tls_{ocsp,crl}_{client,database}_url` flags, only uses `--tls_{ocsp,crl}_url` as URL source.
func NewCertVerifierFromConfigs ¶
func NewCertVerifierFromConfigs(ocspConfig *OCSPConfig, crlConfig *CRLConfig) (CertVerifier, error)
NewCertVerifierFromConfigs creates a CertVerifier based on passed OCSP and CRL configs
type CertVerifierAll ¶
type CertVerifierAll struct {
// contains filtered or unexported fields
}
CertVerifierAll is an implementation of CertVerifier that requires all verifiers to return success
func NewCertVerifierAll ¶
func NewCertVerifierAll(verifiers ...CertVerifier) CertVerifierAll
NewCertVerifierAll creates new CertVerifierAll, verifier that tries all internally contained verifiers
func (*CertVerifierAll) Push ¶
func (v *CertVerifierAll) Push(verifier CertVerifier)
Push append one more verifier to internal list
func (CertVerifierAll) Verify ¶
func (v CertVerifierAll) Verify(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
Verify returns number of confirmations or error
type CertificateIdentifierExtractor ¶
type CertificateIdentifierExtractor interface {
GetCertificateIdentifier(certificate *x509.Certificate) ([]byte, error)
}
CertificateIdentifierExtractor interface for implementations which should return identifier used for client's identification
func NewIdentifierExtractorByType ¶
func NewIdentifierExtractorByType(extractorType string) (CertificateIdentifierExtractor, error)
NewIdentifierExtractorByType return new CertificateIdentifierExtractor by type
type ClientIDToContextCallback ¶
type ClientIDToContextCallback struct {
ClientID []byte
}
ClientIDToContextCallback is a callback that sets the ClientID into the connection context. Is used in the TLS connections to specify static clientID, instead of extracting it from the certificate.
func (ClientIDToContextCallback) OnConnectionContext ¶
func (c ClientIDToContextCallback) OnConnectionContext(ctx context.Context, _ net.Conn) (context.Context, error)
OnConnectionContext returns connection context with the clientID saved.
type ConnectionCallback ¶
ConnectionCallback used to call callbacks on new accepted connections
type ConnectionContextCallback ¶
type ConnectionContextCallback interface {
OnConnectionContext(ctx context.Context, c net.Conn) (context.Context, error)
}
ConnectionContextCallback used to call callbacks for http.Server.ConnContext calls
type ConnectionManager ¶
type ConnectionManager struct { *sync.WaitGroup Counter int // contains filtered or unexported fields }
ConnectionManager counts connections and close them
func NewConnectionManager ¶
func NewConnectionManager() *ConnectionManager
NewConnectionManager returns new ConnectionManager
func (*ConnectionManager) AddConnection ¶
func (cm *ConnectionManager) AddConnection(conn net.Conn) error
AddConnection adds new connection, increases connections counter
func (*ConnectionManager) CloseConnections ¶
func (cm *ConnectionManager) CloseConnections() error
CloseConnections close all available connections and return first occurred error
func (*ConnectionManager) Done ¶
func (cm *ConnectionManager) Done()
Done marks connection as done, decreases connections counter
func (*ConnectionManager) Incr ¶
func (cm *ConnectionManager) Incr()
Incr increases connections counter
func (*ConnectionManager) RemoveConnection ¶
func (cm *ConnectionManager) RemoveConnection(conn net.Conn) error
RemoveConnection removes connection, marks it done, decreases connections counter
type ConnectionMetadata ¶
type ConnectionMetadata interface { SpanContext() (trace.SpanContext, bool) ClientID() ([]byte, bool) }
ConnectionMetadata connection metadata
type ConnectionMetadataBuilder ¶
type ConnectionMetadataBuilder struct {
// contains filtered or unexported fields
}
ConnectionMetadataBuilder builds connection metadata
func NewConnectionMetadataBuilder ¶
func NewConnectionMetadataBuilder() (*ConnectionMetadataBuilder, error)
NewConnectionMetadataBuilder return ConnectionMetadataBuilder which build ConnectionMetadata implementation
func (*ConnectionMetadataBuilder) ClientID ¶
func (builder *ConnectionMetadataBuilder) ClientID() ([]byte, bool)
ClientID return ClientID
func (*ConnectionMetadataBuilder) SetClientID ¶
func (builder *ConnectionMetadataBuilder) SetClientID(c []byte) *ConnectionMetadataBuilder
SetClientID set client id
func (*ConnectionMetadataBuilder) SetSpanContext ¶
func (builder *ConnectionMetadataBuilder) SetSpanContext(c trace.SpanContext) *ConnectionMetadataBuilder
SetSpanContext set SpanContext
func (*ConnectionMetadataBuilder) SpanContext ¶
func (builder *ConnectionMetadataBuilder) SpanContext() (trace.SpanContext, bool)
SpanContext return SpanContext and true if was set otherwise default SpanContext and false
type ConnectionMetric ¶
ConnectionMetric used to track connection time of life
func (*ConnectionMetric) Close ¶
func (conn *ConnectionMetric) Close() error
Close call Close() of wrapped connection and track time of connection life
func (*ConnectionMetric) Unwrap ¶
func (conn *ConnectionMetric) Unwrap() net.Conn
Unwrap returns wrapped connection
type ConnectionTimeoutWrapper ¶
ConnectionTimeoutWrapper interface
type ConnectionToContextCallback ¶
type ConnectionToContextCallback struct{}
ConnectionToContextCallback callback implements OnConnectionContextCallback interface and store connection in context
func (ConnectionToContextCallback) OnConnectionContext ¶
func (ConnectionToContextCallback) OnConnectionContext(ctx context.Context, c net.Conn) (context.Context, error)
OnConnectionContext return context with saved connection for future retrieving from context in http.Server handlers
type ConnectionWrapper ¶
type ConnectionWrapper interface { WrapClient(ctx context.Context, conn net.Conn) (net.Conn, error) WrapServer(ctx context.Context, conn net.Conn) (net.Conn, []byte, error) // conn, ClientID, error }
ConnectionWrapper interface
type DeadlineListener ¶
DeadlineListener is extended net.Listener interface with SetDeadline method that added for abstraction of calling SetDeadline between two listener types (TcpListener and UnixListener) that support this method
func CastListenerToDeadline ¶
func CastListenerToDeadline(listener net.Listener) (DeadlineListener, error)
CastListenerToDeadline casts any net.Listener to DeadlineListener or throws ErrUnsupportedListener error.
type DefaultCRLClient ¶
type DefaultCRLClient struct {
// contains filtered or unexported fields
}
DefaultCRLClient is a default implementation of CRLClient (as opposed to stub ones used in tests)
func NewDefaultCRLClient ¶
func NewDefaultCRLClient() DefaultCRLClient
NewDefaultCRLClient creates new DefaultCRLClient
type DefaultCRLVerifier ¶
DefaultCRLVerifier is a default implementation of CRLVerifier
func (DefaultCRLVerifier) Verify ¶
func (v DefaultCRLVerifier) Verify(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
Verify ensures configured CRLs do not contain certificate from passed chain
type DefaultOCSPClient ¶
type DefaultOCSPClient struct {
// contains filtered or unexported fields
}
DefaultOCSPClient is a default implementation of OCSPClient
func NewDefaultOCSPClient ¶
func NewDefaultOCSPClient() DefaultOCSPClient
NewDefaultOCSPClient creates new DefaultOCSPClient
func (DefaultOCSPClient) Query ¶
func (c DefaultOCSPClient) Query(commonName string, clientCert, issuerCert *x509.Certificate, ocspServerURL string) (*ocsp.Response, error)
Query generates OCSP request about specified certificate, sends it to server and returns the response
type DefaultOCSPVerifier ¶
type DefaultOCSPVerifier struct { Config OCSPConfig Client OCSPClient }
DefaultOCSPVerifier is a default OCSP verifier
func (DefaultOCSPVerifier) Verify ¶
func (v DefaultOCSPVerifier) Verify(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
Verify ensures certificate is not revoked by querying configured OCSP servers
type DistinguishedNameExtractor ¶
type DistinguishedNameExtractor struct{}
DistinguishedNameExtractor implementation for CertificateIdentifierExtractor interface, which return CommonName as client's identifier
func (DistinguishedNameExtractor) GetCertificateIdentifier ¶
func (e DistinguishedNameExtractor) GetCertificateIdentifier(certificate *x509.Certificate) ([]byte, error)
GetCertificateIdentifier return pkix.Name.String() which is DN in format according to RFC2253 (https://tools.ietf.org/html/rfc2253) To get DN in CLI with openssl: openssl x509 -in client.crt -subject -noout -nameopt RFC2253 | sed 's/subject=//'
type GRPCConnectionClientIDExtractor ¶
GRPCConnectionClientIDExtractor extract clientID from connection AuthInfo encapsulated in request context
type GRPCConnectionWrapper ¶
type GRPCConnectionWrapper interface { credentials.TransportCredentials AddOnServerHandshakeCallback(callback OnServerHandshakeCallback) }
GRPCConnectionWrapper interface implements credentials.TransportCredentials and allows to register callbacks for new connections after ServerHandshake call
type HTTPServerConnectionChainWrapper ¶
type HTTPServerConnectionChainWrapper struct { net.Listener // contains filtered or unexported fields }
HTTPServerConnectionChainWrapper wraps net.Listener and allow to register callbacks that will be called on every new connection after listener.Accept and implements http.Server.ConnContext handler signature and allow register callbacks that will be called on every new connection internally in http.Server
func NewHTTPServerConnectionWrapper ¶
func NewHTTPServerConnectionWrapper() (*HTTPServerConnectionChainWrapper, error)
NewHTTPServerConnectionWrapper returns new wrapped Listener
func (*HTTPServerConnectionChainWrapper) Accept ¶
func (wrapper *HTTPServerConnectionChainWrapper) Accept() (net.Conn, error)
Accept call wrapped listener's Accept method and call all registered callbacks. Because this wrapper used as http.Server's listener and http.Server will shutdown on any error Accept method. If wrapped listener successfully Accepted new connection but any callback returned error than this method will return wrapped connection without any error. But this connection will return error from callback on any call of net.Conn method to prevent future usage and to avoid http.Server shutdown
func (*HTTPServerConnectionChainWrapper) AddCallback ¶
func (wrapper *HTTPServerConnectionChainWrapper) AddCallback(callback ConnectionCallback)
AddCallback register new callback for new connection from http.Server
func (*HTTPServerConnectionChainWrapper) AddConnectionContextCallback ¶
func (wrapper *HTTPServerConnectionChainWrapper) AddConnectionContextCallback(callback ConnectionContextCallback)
AddConnectionContextCallback add callback for OnConnectionContext calls
func (*HTTPServerConnectionChainWrapper) OnConnectionContext ¶
func (wrapper *HTTPServerConnectionChainWrapper) OnConnectionContext(ctx context.Context, c net.Conn) context.Context
OnConnectionContext implements http.Server.ConnContext handler signature and call registered callbacks If some of callback will return error then connection will be closed to prevent future usage
func (*HTTPServerConnectionChainWrapper) SetListener ¶
func (wrapper *HTTPServerConnectionChainWrapper) SetListener(listener net.Listener)
SetListener sets listener that should be wrapped
func (*HTTPServerConnectionChainWrapper) Unwrap ¶
func (wrapper *HTTPServerConnectionChainWrapper) Unwrap() net.Listener
Unwrap returns wrapped listener
type HTTPServerConnectionWrapper ¶
type HTTPServerConnectionWrapper interface { net.Listener SetListener(net.Listener) AddCallback(callback ConnectionCallback) AddConnectionContextCallback(callback ConnectionContextCallback) OnConnectionContext(ctx context.Context, c net.Conn) context.Context }
HTTPServerConnectionWrapper implements net.Listener interface and allow to
type HexIdentifierConverter ¶
type HexIdentifierConverter struct {
// contains filtered or unexported fields
}
HexIdentifierConverter converts identifiers to hex value as string in lower case
func NewDefaultHexIdentifierConverter ¶
func NewDefaultHexIdentifierConverter() (*HexIdentifierConverter, error)
NewDefaultHexIdentifierConverter return new HexIdentifierConverter with sha512 as hash function used to fit output into acceptable size
func (HexIdentifierConverter) Convert ¶
func (c HexIdentifierConverter) Convert(identifier []byte) ([]byte, error)
Convert identifier to hex value in lower case. If len(identifier) == 1 then 0 inserted as start of identifier to match minimal length of clientID 4 bytes. If len(identifier) > (keystore.MaxClientIDLength / 2) than it longer than max acceptable length of clientID in hex format (256) In such case identifier passed through SHA512 and then converted to hex with 128 (64 * 2) bytes length
type IdentifierConverter ¶
IdentifierConverter converts identifiers from x509 certificates to clientID format acceptable by keystore, pass keystore.ValidateID check
type LRUCRLCache ¶
type LRUCRLCache struct {
// contains filtered or unexported fields
}
LRUCRLCache is an implementation of CRLCache that uses LRU cache inside
func NewLRUCRLCache ¶
func NewLRUCRLCache(maxEntries uint) *LRUCRLCache
NewLRUCRLCache creates new LRUCRLCache, able to store at most maxEntries values
func (*LRUCRLCache) Get ¶
func (c *LRUCRLCache) Get(key string) (*CRLCacheItem, error)
Get tries to get CRL from cache, returns error if failed
func (*LRUCRLCache) Put ¶
func (c *LRUCRLCache) Put(key string, value *CRLCacheItem) error
Put stores CRL in cache
func (*LRUCRLCache) Remove ¶
func (c *LRUCRLCache) Remove(key string) error
Remove removes item from cache
type ListenerWithFileDescriptor ¶
ListenerWithFileDescriptor listens to file
type ListenerWrapper ¶
ListenerWrapper interface allows to access wrapped listener by another listener implementation
type MetricConnectionCallback ¶
type MetricConnectionCallback struct {
// contains filtered or unexported fields
}
MetricConnectionCallback callback used for new incoming connections from gRPC or http.Server connection handlers and wraps new connections with time tracking of lifetime on Close calls
func NewMetricConnectionCallback ¶
func NewMetricConnectionCallback(connectionType string, counter *prometheus.CounterVec, histogram *prometheus.HistogramVec) *MetricConnectionCallback
NewMetricConnectionCallback return initialized MetricConnectionCallback with proper connectionType. When connection is processed, the counter is incremented and the histogram registers the duration of the connection.
func (*MetricConnectionCallback) OnConnection ¶
OnConnection callback for new connections for HTTPConnectionWrapper and http.Server connections
func (*MetricConnectionCallback) OnServerHandshake ¶
OnServerHandshake callback for new connections for HTTPConnectionWrapper and gRPC connections
type OCSPClient ¶
type OCSPClient interface { // Query generates OCSP request about specified certificate, sends it to server and returns the response Query(commonName string, clientCert, issuerCert *x509.Certificate, ocspServerURL string) (*ocsp.Response, error) }
OCSPClient is used to perform OCSP queries to some URL
type OCSPConfig ¶
type OCSPConfig struct { ClientAuthType tls.ClientAuthType // contains filtered or unexported fields }
OCSPConfig contains configuration related to certificate validation using OCSP
func NewOCSPConfig ¶
func NewOCSPConfig(url, required, fromCert string, checkOnlyLeafCertificate bool) (*OCSPConfig, error)
NewOCSPConfig creates new OCSPConfig
func NewOCSPConfigByName ¶
func NewOCSPConfigByName(extractor *args.ServiceExtractor, name string, namerFunc CLIParamNameConstructorFunc) (*OCSPConfig, error)
NewOCSPConfigByName return initialized OCSPConfig config using flags registered with RegisterCertVerifierArgsForService
func (*OCSPConfig) UseOCSP ¶
func (c *OCSPConfig) UseOCSP() bool
UseOCSP returns true if verification via OCSP is enabled
type OnServerHandshakeCallback ¶
OnServerHandshakeCallback interface used for callbacks on every ServerHandshake call in grpc connection handler
type RawConnectionWrapper ¶
RawConnectionWrapper doesn't add any encryption above connection
func (*RawConnectionWrapper) WrapClient ¶
func (wrapper *RawConnectionWrapper) WrapClient(ctx context.Context, conn net.Conn) (net.Conn, error)
WrapClient returns RawConnectionWrapper above client connection
type SafeCloseConnectionCallback ¶
type SafeCloseConnectionCallback struct{}
SafeCloseConnectionCallback callback that wraps connections with connection that call Close only once
func (SafeCloseConnectionCallback) OnConnection ¶
OnConnection wraps connection with connection that call Close only once
func (SafeCloseConnectionCallback) OnServerHandshake ¶
OnServerHandshake wrap conn with SafeCloseeConnection
type SerialNumberExtractor ¶
type SerialNumberExtractor struct{}
SerialNumberExtractor implementation for CertificateIdentifierExtractor interface, which return SerialNumber of certificate as client's identifier
func (SerialNumberExtractor) GetCertificateIdentifier ¶
func (e SerialNumberExtractor) GetCertificateIdentifier(certificate *x509.Certificate) ([]byte, error)
GetCertificateIdentifier return SerialNumber as client's identifier by tls certificate
type TLSClientIDExtractor ¶
type TLSClientIDExtractor interface {
ExtractClientID(certificate *x509.Certificate) ([]byte, error)
}
TLSClientIDExtractor complex component for extracting clientID from certificates using certificate identifier extractor and convertor
func NewDefaultTLSClientIDExtractor ¶
func NewDefaultTLSClientIDExtractor() (TLSClientIDExtractor, error)
NewDefaultTLSClientIDExtractor create new TLSClientIDExtractor implementation which use idExtractor and idConvertor to extract clientID
func NewTLSClientIDExtractor ¶
func NewTLSClientIDExtractor(idExtractor CertificateIdentifierExtractor, idConverter IdentifierConverter) (TLSClientIDExtractor, error)
NewTLSClientIDExtractor create new TLSClientIDExtractor implementation which use idExtractor and idConvertor to extract clientID
type TLSConnectionWrapper ¶
type TLSConnectionWrapper struct { credentials.TransportCredentials // contains filtered or unexported fields }
TLSConnectionWrapper for wrapping connection into TLS encryption
func NewTLSAuthenticationConnectionWrapper ¶
func NewTLSAuthenticationConnectionWrapper(useClientIDFromCertificate bool, clientConfig, serverConfig *tls.Config, extractor TLSClientIDExtractor) (*TLSConnectionWrapper, error)
NewTLSAuthenticationConnectionWrapper returns new TLSConnectionWrapper which use separate TLS configs for each side. Client's identifier will be fetched with idExtractor and converter with idConverter
func NewTLSAuthenticationHTTP2ConnectionWrapper ¶
func NewTLSAuthenticationHTTP2ConnectionWrapper(useClientIDFromCertificate bool, clientConfig, serverConfig *tls.Config, extractor TLSClientIDExtractor) (*TLSConnectionWrapper, error)
NewTLSAuthenticationHTTP2ConnectionWrapper returns new TLSConnectionWrapper which use separate TLS configs for each side. Client's identifier will be fetched with idExtractor and converter with idConverter. Additionally extends serverConfig with NextProtos = []string{"h2"} to support HTTP2
func NewTLSConnectionWrapper ¶
func NewTLSConnectionWrapper(clientID []byte, config *tls.Config) (*TLSConnectionWrapper, error)
NewTLSConnectionWrapper returns new TLSConnectionWrapper
func (*TLSConnectionWrapper) AddOnServerHandshakeCallback ¶
func (wrapper *TLSConnectionWrapper) AddOnServerHandshakeCallback(callback OnServerHandshakeCallback)
AddOnServerHandshakeCallback register callback that will be called on ServerHandshake call from grpc connection handler
func (*TLSConnectionWrapper) OnConnection ¶
OnConnection callback that wraps connection with tls encryption and return ClientIDConnection
func (*TLSConnectionWrapper) ServerHandshake ¶
func (wrapper *TLSConnectionWrapper) ServerHandshake(conn net.Conn) (net.Conn, credentials.AuthInfo, error)
ServerHandshake wraps connection with grpc's implementation of ServerHandshake and call all registered OnServerHandshakeCallbacks and return extended AuthInfo with wrapped connection with clientID information
func (*TLSConnectionWrapper) WrapClient ¶
func (wrapper *TLSConnectionWrapper) WrapClient(ctx context.Context, conn net.Conn) (net.Conn, error)
WrapClient wraps client connection into TLS
type WrappedConnection ¶
WrappedConnection interface implemented by connection wrappers to access to wrapped connection