cockroach: github.com/cockroachdb/cockroach/pkg/security Index | Files | Directories

package security

import "github.com/cockroachdb/cockroach/pkg/security"

Index

Package Files

auth.go certificate_loader.go certificate_manager.go certs.go password.go pem.go tls.go utils.go x509.go

Constants

const (
    // NodeUser is used by nodes for intra-cluster traffic.
    NodeUser = "node"
    // RootUser is the default cluster administrator.
    RootUser = "root"
)
const (
    EmbeddedCertsDir     = "test_certs"
    EmbeddedCACert       = "ca.crt"
    EmbeddedCAKey        = "ca.key"
    EmbeddedClientCACert = "ca-client.crt"
    EmbeddedClientCAKey  = "ca-client.key"
    EmbeddedUICACert     = "ca-ui.crt"
    EmbeddedUICAKey      = "ca-ui.key"
    EmbeddedNodeCert     = "node.crt"
    EmbeddedNodeKey      = "node.key"
    EmbeddedRootCert     = "client.root.crt"
    EmbeddedRootKey      = "client.root.key"
    EmbeddedTestUserCert = "client.testuser.crt"
    EmbeddedTestUserKey  = "client.testuser.key"
)

EmbeddedCertsDir is the certs directory inside embedded assets. Embedded*{Cert,Key} are the filenames for embedded certs.

const ErrPasswordUserAuthFailed = "password authentication failed for user %s"

ErrPasswordUserAuthFailed is the error template for failed password auth of a user. It should be used when the password is incorrect or the user does not exist.

Variables

var BcryptCost = bcrypt.DefaultCost

BcryptCost is the cost to use when hashing passwords. It is exposed for testing.

BcryptCost should increase along with computation power. For estimates, see: http://security.stackexchange.com/questions/17207/recommended-of-rounds-for-bcrypt For now, we use the library's default cost.

var ErrEmptyPassword = errors.New("empty passwords are not permitted")

ErrEmptyPassword indicates that an empty password was attempted to be set.

func CACertFilename Uses

func CACertFilename() string

CACertFilename returns the expected file name for the CA certificate.

func ClientCertFilename Uses

func ClientCertFilename(user string) string

ClientCertFilename returns the expected file name for the user's certificate.

func ClientKeyFilename Uses

func ClientKeyFilename(user string) string

ClientKeyFilename returns the expected file name for the user's key.

func CompareHashAndPassword Uses

func CompareHashAndPassword(hashedPassword []byte, password string) error

CompareHashAndPassword tests that the provided bytes are equivalent to the hash of the supplied password. If they are not equivalent, returns an error.

func CreateCAPair Uses

func CreateCAPair(
    certsDir, caKeyPath string,
    keySize int,
    lifetime time.Duration,
    allowKeyReuse bool,
    overwrite bool,
) error

CreateCAPair creates a general CA certificate and associated key.

func CreateClientCAPair Uses

func CreateClientCAPair(
    certsDir, caKeyPath string,
    keySize int,
    lifetime time.Duration,
    allowKeyReuse bool,
    overwrite bool,
) error

CreateClientCAPair creates a client CA certificate and associated key.

func CreateClientPair Uses

func CreateClientPair(
    certsDir, caKeyPath string,
    keySize int,
    lifetime time.Duration,
    overwrite bool,
    user string,
    wantPKCS8Key bool,
) error

CreateClientPair creates a node key and certificate. The CA cert and key must load properly. If multiple certificates exist in the CA cert, the first one is used. If a client CA exists, this is used instead. If wantPKCS8Key is true, the private key in PKCS#8 encoding is written as well.

func CreateNodePair Uses

func CreateNodePair(
    certsDir, caKeyPath string, keySize int, lifetime time.Duration, overwrite bool, hosts []string,
) error

CreateNodePair creates a node key and certificate. The CA cert and key must load properly. If multiple certificates exist in the CA cert, the first one is used.

func CreateUICAPair Uses

func CreateUICAPair(
    certsDir, caKeyPath string,
    keySize int,
    lifetime time.Duration,
    allowKeyReuse bool,
    overwrite bool,
) error

CreateUICAPair creates a UI CA certificate and associated key.

func CreateUIPair Uses

func CreateUIPair(
    certsDir, caKeyPath string, keySize int, lifetime time.Duration, overwrite bool, hosts []string,
) error

CreateUIPair creates a UI certificate and key using the UI CA. The CA cert and key must load properly. If multiple certificates exist in the CA cert, the first one is used.

func ExtKeyUsageToString Uses

func ExtKeyUsageToString(eku x509.ExtKeyUsage) string

ExtKeyUsageToString converts a x509.ExtKeyUsage to a string, returning "unknown" if the list is not up-to-date.

func GenerateCA Uses

func GenerateCA(signer crypto.Signer, lifetime time.Duration) ([]byte, error)

GenerateCA generates a CA certificate and signs it using the signer (a private key). It returns the DER-encoded certificate.

func GenerateClientCert Uses

func GenerateClientCert(
    caCert *x509.Certificate,
    caPrivateKey crypto.PrivateKey,
    clientPublicKey crypto.PublicKey,
    lifetime time.Duration,
    user string,
) ([]byte, error)

GenerateClientCert generates a client certificate and returns the cert bytes. Takes in the CA cert and private key, the client public key, the certificate lifetime, and the username.

func GenerateServerCert Uses

func GenerateServerCert(
    caCert *x509.Certificate,
    caPrivateKey crypto.PrivateKey,
    nodePublicKey crypto.PublicKey,
    lifetime time.Duration,
    hosts []string,
) ([]byte, error)

GenerateServerCert generates a server certificate and returns the cert bytes. Takes in the CA cert and private key, the node public key, the certificate lifetime, and the list of hosts/ip addresses this certificate applies to.

func GenerateUIServerCert Uses

func GenerateUIServerCert(
    caCert *x509.Certificate,
    caPrivateKey crypto.PrivateKey,
    certPublicKey crypto.PublicKey,
    lifetime time.Duration,
    hosts []string,
) ([]byte, error)

GenerateUIServerCert generates a server certificate for the Admin UI and returns the cert bytes. Takes in the CA cert and private key, the UI cert public key, the certificate lifetime, and the list of hosts/ip addresses this certificate applies to.

func GetCertificateUser Uses

func GetCertificateUser(tlsState *tls.ConnectionState) (string, error)

GetCertificateUser extract the username from a client certificate.

func HashPassword Uses

func HashPassword(password string) ([]byte, error)

HashPassword takes a raw password and returns a bcrypt hashed password.

func KeyUsageToString Uses

func KeyUsageToString(ku x509.KeyUsage) []string

KeyUsageToString returns the list of key usages described by the bitmask. This list may not up-to-date with https://golang.org/pkg/crypto/x509/#KeyUsage

func LoadClientTLSConfig Uses

func LoadClientTLSConfig(sslCA, sslCert, sslCertKey string) (*tls.Config, error)

LoadClientTLSConfig creates a client TLSConfig by loading the CA and client certs. The following paths must be passed: - sslCA: path to the CA certificate - sslCert: path to the client certificate - sslCertKey: path to the client key If the path is prefixed with "embedded=", load the embedded certs.

func LoadServerTLSConfig Uses

func LoadServerTLSConfig(sslCA, sslClientCA, sslCert, sslCertKey string) (*tls.Config, error)

LoadServerTLSConfig creates a server TLSConfig by loading the CA and server certs. The following paths must be passed: - sslCA: path to the CA certificate - sslClientCA: path to the CA certificate to verify client certificates,

can be the same as sslCA

- sslCert: path to the server certificate - sslCertKey: path to the server key If the path is prefixed with "embedded=", load the embedded certs.

func PEMContentsToX509 Uses

func PEMContentsToX509(contents []byte) ([]*x509.Certificate, error)

PEMContentsToX509 takes raw pem-encoded contents and attempts to parse into x509.Certificate objects.

func PEMToCertificates Uses

func PEMToCertificates(contents []byte) ([]*pem.Block, error)

PEMToCertificates parses multiple certificate PEM blocks and returns them. Each block must be a certificate. It is allowed to have zero certificates.

func PEMToPrivateKey Uses

func PEMToPrivateKey(contents []byte) (crypto.PrivateKey, error)

PEMToPrivateKey parses a PEM block and returns the private key.

func PrivateKeyToPEM Uses

func PrivateKeyToPEM(key crypto.PrivateKey) (*pem.Block, error)

PrivateKeyToPEM generates a PEM block from a private key.

func PrivateKeyToPKCS8 Uses

func PrivateKeyToPKCS8(key crypto.PrivateKey) ([]byte, error)

PrivateKeyToPKCS8 encodes a private key into PKCS#8.

func PromptForPassword Uses

func PromptForPassword() (string, error)

PromptForPassword prompts for a password. This is meant to be used when using a password.

func PromptForPasswordTwice Uses

func PromptForPasswordTwice() (string, error)

PromptForPasswordTwice prompts for a password twice, returning the read string if they match, or an error. This is meant to be used when setting a password.

func ResetAssetLoader Uses

func ResetAssetLoader()

ResetAssetLoader restores the asset loader to the default value.

func SafeWriteToFile Uses

func SafeWriteToFile(path string, mode os.FileMode, overwrite bool, contents []byte) error

SafeWriteToFile writes the passed-in bytes to a file. The file "path" is created with "mode" and WRONLY|CREATE. If overwrite is true, the file will be overwritten if it exists.

func SetAssetLoader Uses

func SetAssetLoader(al AssetLoader)

SetAssetLoader overrides the asset loader with the passed-in one.

func WritePEMToFile Uses

func WritePEMToFile(path string, mode os.FileMode, overwrite bool, blocks ...*pem.Block) error

WritePEMToFile writes an arbitrary number of PEM blocks to a file. The file "path" is created with "mode" and WRONLY|CREATE. If overwrite is true, the file will be overwritten if it exists.

type AssetLoader Uses

type AssetLoader struct {
    ReadDir  func(dirname string) ([]os.FileInfo, error)
    ReadFile func(filename string) ([]byte, error)
    Stat     func(name string) (os.FileInfo, error)
}

AssetLoader describes the functions necessary to read certificate and key files.

type CertInfo Uses

type CertInfo struct {
    // FileUsage describes the use of this certificate.
    FileUsage PemUsage

    // Filename is the base filename of the certificate.
    Filename string
    // FileContents is the raw cert file data.
    FileContents []byte

    // KeyFilename is the base filename of the key, blank if not found (CA certs only).
    KeyFilename string
    // KeyFileContents is the raw key file data.
    KeyFileContents []byte

    // Name is the blob in the middle of the filename. eg: username for client certs.
    Name string

    // Parsed certificates. This is used by debugging/printing/monitoring only,
    // TLS config objects are passed raw certificate file contents.
    // CA certs may contain (and use) more than one certificate.
    // Client/Server certs may contain more than one, but only the first certificate will be used.
    ParsedCertificates []*x509.Certificate

    // Expiration time is the latest "Not After" date across all parsed certificates.
    ExpirationTime time.Time

    // Error is any error encountered when loading the certificate/key pair.
    // For example: bad permissions on the key will be stored here.
    Error error
}

CertInfo describe a certificate file and optional key file. To obtain the full path, Filename and KeyFilename must be joined with the certs directory. The key may not be present if this is a CA certificate. If Err != nil, the CertInfo must NOT be used.

func CertInfoFromFilename Uses

func CertInfoFromFilename(filename string) (*CertInfo, error)

CertInfoFromFilename takes a filename and attempts to determine the certificate usage (ca, node, etc..).

type CertificateLoader Uses

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

CertificateLoader searches for certificates and keys in the certs directory.

func NewCertificateLoader Uses

func NewCertificateLoader(certsDir string) *CertificateLoader

NewCertificateLoader creates a new instance of the certificate loader.

func (*CertificateLoader) Certificates Uses

func (cl *CertificateLoader) Certificates() []*CertInfo

Certificates returns the loaded certificates.

func (*CertificateLoader) Load Uses

func (cl *CertificateLoader) Load() error

Load examines all .crt files in the certs directory, determines their usage, and looks for their keys. It populates the certificates field.

func (*CertificateLoader) MaybeCreateCertsDir Uses

func (cl *CertificateLoader) MaybeCreateCertsDir() error

MaybeCreateCertsDir creates the certificate directory if it does not exist. Returns an error if we could not stat or create the directory.

func (*CertificateLoader) TestDisablePermissionChecks Uses

func (cl *CertificateLoader) TestDisablePermissionChecks()

TestDisablePermissionChecks turns off permissions checks. Used by tests only.

type CertificateManager Uses

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

CertificateManager lives for the duration of the process and manages certificates and keys. It reloads all certificates when triggered and construct tls.Config objects for servers or clients.

Important note: Load() performs some sanity checks (file pairs match, CA certs don't disappear), but these are by no means complete. Completeness is not required as nodes restarting have no fallback if invalid certs/keys are present.

The nomenclature for certificates is as follows, all within the certs-dir. - ca.crt main CA certificate.

Used to verify everything unless overridden by more specifica CAs.

- ca-client.crt CA certificate to verify client certificates. If it does not exist,

fall back on 'ca.crt'.

- node.crt node certificate.

Server-side certificate (always) and client-side certificate unless
client.node.crt is found.
Verified using 'ca.crt'.

- client.<user>.crt client certificate for 'user'. Verified using 'ca.crt', or 'ca-client.crt'. - client.node.crt client certificate for the 'node' user. If it does not exist,

fall back on 'node.crt'.

func NewCertificateManager Uses

func NewCertificateManager(certsDir string) (*CertificateManager, error)

NewCertificateManager creates a new certificate manager.

func NewCertificateManagerFirstRun Uses

func NewCertificateManagerFirstRun(certsDir string) (*CertificateManager, error)

NewCertificateManagerFirstRun creates a new certificate manager. The certsDir is created if it does not exist. This should only be called when generating certificates, the server has no business creating the certs directory.

func (*CertificateManager) CACert Uses

func (cm *CertificateManager) CACert() *CertInfo

CACert returns the CA cert. May be nil. Callers should check for an internal Error field.

func (*CertificateManager) CACertPath Uses

func (cm *CertificateManager) CACertPath() string

CACertPath returns the expected file path for the CA certificate.

func (*CertificateManager) ClientCACert Uses

func (cm *CertificateManager) ClientCACert() *CertInfo

ClientCACert returns the CA cert used to verify client certificates. May be nil. Callers should check for an internal Error field.

func (*CertificateManager) ClientCACertPath Uses

func (cm *CertificateManager) ClientCACertPath() string

ClientCACertPath returns the expected file path for the CA certificate used to verify client certificates.

func (*CertificateManager) ClientCertPath Uses

func (cm *CertificateManager) ClientCertPath(user string) string

ClientCertPath returns the expected file path for the user's certificate.

func (*CertificateManager) ClientCerts Uses

func (cm *CertificateManager) ClientCerts() map[string]*CertInfo

ClientCerts returns the Client certs. Callers should check for internal Error fields.

func (*CertificateManager) ClientKeyPath Uses

func (cm *CertificateManager) ClientKeyPath(user string) string

ClientKeyPath returns the expected file path for the user's key.

func (*CertificateManager) GetCACertPath Uses

func (cm *CertificateManager) GetCACertPath() (string, error)

GetCACertPath returns the path to the CA certificate.

func (*CertificateManager) GetClientCertPaths Uses

func (cm *CertificateManager) GetClientCertPaths(user string) (string, string, error)

GetClientCertPaths returns the paths to the client cert and key. Returns the node cert and key if user == NodeUser.

func (*CertificateManager) GetClientTLSConfig Uses

func (cm *CertificateManager) GetClientTLSConfig(user string) (*tls.Config, error)

GetClientTLSConfig returns the most up-to-date client tls.Config. Returns the dual-purpose node certs if user == NodeUser and there is no separate client cert for 'node'.

func (*CertificateManager) GetServerTLSConfig Uses

func (cm *CertificateManager) GetServerTLSConfig() (*tls.Config, error)

GetServerTLSConfig returns a server TLS config with a callback to fetch the latest TLS config. We still attempt to get the config to make sure the initial call has a valid config loaded.

func (*CertificateManager) GetUIClientTLSConfig Uses

func (cm *CertificateManager) GetUIClientTLSConfig() (*tls.Config, error)

GetUIClientTLSConfig returns the most up-to-date client tls.Config for Admin UI clients. It does not include a client certificate and uses the UI CA certificate if present.

func (*CertificateManager) GetUIServerTLSConfig Uses

func (cm *CertificateManager) GetUIServerTLSConfig() (*tls.Config, error)

GetUIServerTLSConfig returns a server TLS config for the Admin UI with a callback to fetch the latest TLS config. We still attempt to get the config to make sure the initial call has a valid config loaded.

func (*CertificateManager) ListCertificates Uses

func (cm *CertificateManager) ListCertificates() ([]*CertInfo, error)

ListCertificates returns all loaded certificates, or an error if not yet initialized.

func (*CertificateManager) LoadCertificates Uses

func (cm *CertificateManager) LoadCertificates() error

LoadCertificates creates a CertificateLoader to load all certs and keys. Upon success, it swaps the existing certificates for the new ones.

func (*CertificateManager) Metrics Uses

func (cm *CertificateManager) Metrics() CertificateMetrics

Metrics returns the metrics struct.

func (*CertificateManager) NodeCert Uses

func (cm *CertificateManager) NodeCert() *CertInfo

NodeCert returns the Node cert. May be nil. Callers should check for an internal Error field.

func (*CertificateManager) NodeCertPath Uses

func (cm *CertificateManager) NodeCertPath() string

NodeCertPath returns the expected file path for the node certificate.

func (*CertificateManager) NodeKeyPath Uses

func (cm *CertificateManager) NodeKeyPath() string

NodeKeyPath returns the expected file path for the node key.

func (*CertificateManager) RegisterSignalHandler Uses

func (cm *CertificateManager) RegisterSignalHandler(stopper *stop.Stopper)

RegisterSignalHandler registers a signal handler for SIGHUP, triggering a refresh of the certificates directory on notification.

func (*CertificateManager) UICACert Uses

func (cm *CertificateManager) UICACert() *CertInfo

UICACert returns the CA cert used to verify the Admin UI certificate. May be nil. Callers should check for an internal Error field.

func (*CertificateManager) UICACertPath Uses

func (cm *CertificateManager) UICACertPath() string

UICACertPath returns the expected file path for the CA certificate used to verify Admin UI certificates.

func (*CertificateManager) UICert Uses

func (cm *CertificateManager) UICert() *CertInfo

UICert returns the certificate used by the Admin UI. May be nil. Callers should check for an internal Error field.

func (*CertificateManager) UICertPath Uses

func (cm *CertificateManager) UICertPath() string

UICertPath returns the expected file path for the UI certificate.

func (*CertificateManager) UIKeyPath Uses

func (cm *CertificateManager) UIKeyPath() string

UIKeyPath returns the expected file path for the UI key.

type CertificateMetrics Uses

type CertificateMetrics struct {
    CAExpiration         *metric.Gauge
    ClientCAExpiration   *metric.Gauge
    UICAExpiration       *metric.Gauge
    NodeExpiration       *metric.Gauge
    NodeClientExpiration *metric.Gauge
    UIExpiration         *metric.Gauge
}

CertificateMetrics holds metrics about the various certificates. These are initialized when the certificate manager is created and updated on reload.

type Error Uses

type Error struct {
    Message string
    Err     error
}

Error is the error type for this package.

func (*Error) Error Uses

func (e *Error) Error() string

Error implements the error interface.

type PemUsage Uses

type PemUsage uint32

PemUsage indicates the purpose of a given certificate.

const (

    // CAPem describes the main CA certificate.
    CAPem PemUsage
    // ClientCAPem describes the CA certificate used to verify client certificates.
    ClientCAPem
    // UICAPem describes the CA certificate used to verify the Admin UI server certificate.
    UICAPem
    // NodePem describes the server certificate for the node, possibly a combined server/client
    // certificate for user Node if a separate 'client.node.crt' is not present.
    NodePem
    // UIPem describes the server certificate for the admin UI.
    UIPem
    // ClientPem describes a client certificate.
    ClientPem
)

func (PemUsage) String Uses

func (p PemUsage) String() string

type UserAuthHook Uses

type UserAuthHook func(string, bool) error

UserAuthHook authenticates a user based on their username and whether their connection originates from a client or another node in the cluster.

func UserAuthCertHook Uses

func UserAuthCertHook(insecureMode bool, tlsState *tls.ConnectionState) (UserAuthHook, error)

UserAuthCertHook builds an authentication hook based on the security mode and client certificate.

func UserAuthPasswordHook Uses

func UserAuthPasswordHook(insecureMode bool, password string, hashedPassword []byte) UserAuthHook

UserAuthPasswordHook builds an authentication hook based on the security mode, password, and its potentially matching hash.

Directories

PathSynopsis
securitytestPackage securitytest embeds the TLS test certificates.

Package security imports 31 packages (graph) and is imported by 69 packages. Updated 2019-08-27. Refresh now. Tools for package owners.