* Key Rotation/Destruction (#2477) * fix: Correct kms.CreateKeys comment This method does not return anything. * feat(kms): Add new ListKeys method The new ListKeys method wraps the underlying KMS wrapper, returning all the keys in the scope specified. * feat(scopes): Add new scope actions for key management Adds list-keys, rotate-keys and revoke-keys actions for scopes. * feat(scopes): Add ListKeys API endpoint This new endpoint lists all keys in a scope * feat(api): Add ListKeys to Scopes client This has to be a custom function because it is a custom action and doesn't map well to any of the existing templates, or generalises well in a way that would make it reasonable to create a new template. * feat(cli): Add new scopes list-keys command * add RotateKeys function to the kms repository * Add Rotate Keys Endpoint to Scopes Api (#2360) * add rotate keys endpoint * add tests for RotateKeys endpoint * remove that one comment I forgot about * addressing more PR comments * Add Rotate Keys CLI Command (#2395) * add cli command and client * add bats tests * fix some info text and pr comments * write a new rotate keys description * Add Missing DEK Foreign Keys (#2408) * add missing fks * mark key as nullable in gorm * update tests to use a new wrapper with a real key_id * fix formatting in test and add keys for auth_token test * replace key values * revert postgres_40_01_test.go * style: reformat sql for readability * refactor: change type of key_id columns to kms_private_id * Store key_id and scope_id with oplog entries, re-type columns referencing data key version (#2431) * fix(db): Correct types of data key version referencers * fix(oplog): Fix missing error handling * feat(oplog): Store key_id and scope_id with oplog entries This migration truncates all existing oplog entries, as migrating existing data would have been complex and likely unnecessary. * Update view references * Always delete oplog entries when dropping keys * Fix rebase issues * Fix sql tests * Add schema for new kms destruction jobs (#2479) * feat: Add schema for new kms destruction jobs The schema lets us manage destruction jobs per-table while providing a guarantee that only one run is running at a time. * Apply suggestions from code review Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com> * Fix table reference and tests Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com> * update domain, api, and cli to all include key versions in outputs (#2472) * update domain, api, and cli to all include key versions in outputs * fix go sum * add migration to fix immutable error * fix final test issue as well as make gen issue * rebase and fix * address johan pr comments * make gen, didn't realize comments were included * update migrations based on new migration 55 file 03 * Move migrations to 56 * feat: Add key version rewrapping function registry (#2478) The new RegisterTableRewrapFn can be used by a domain to register a callback to use when rewrapping data in a specific table name. * feat(kms): Add scopeId to RewrapFn (#2539) This makes it much easier for rewrap functions to look up the correct wrapper and limit the number of rows searched. * Update Root Cert Proto Definition (#2542) * update root cert proto definition to properly identify public_key as the table primary key * add the test fix as well * Rewrap Functions for Encrypted Tables (#2532) * add oidc rewrap * add argon2 config rewrap * add auth token rewrapping * add worker auth cert rewrapping * check the err * add username password credential rewrapping * add ssh private key credential rewrapping * add vault client certificate rewrap function * add host catalog secret rewrap function * cleanup a little * add host vault token rewrap function * add session credential rewrap function * add session rewrap function * add worker auth rewrap function * update test to include full assert gamut * add session rewrap function TEST * bring all tests up to current standards, make more readable, and include full assert gamut * rework all rewrap functions to utilize scope id * update comments, queries, sql refs, etc, in response to PR comments * forgot a comment * remove hmac updates and fix a couple comments again * Rewrapping Registered Tables Test (#2555) * add the registered table test as well as the two missing rewrap functions * address pr comments, add db r/w conversions, cmp.diff, sql comment, remove (now) faulty immutable test * Add ability to list key version destruction jobs, recurring jobs and destroying key versions (#2498) * feat(kms): Add ability to list data key version destruction jobs * feat(scopes): Add ListKeyVersionDestructionJobs * feat(cli): Add list-key-version-destruction-jobs * feat(kms): Add recurring job that performs table rewrapping The new recurring job runs for each job table with a registered rewrapping callback. It attempts to become the running run and start its rewrapping, gracefully handling sudden interruptions by resuming it's work if it finds evidence of sudden interruption. * feat(kms): Add recurring job for destroying key versions The new job monitors the database for data key version destruction jobs that have finished rewrapping all its data, performing the final data key version revocation. * feat(kms): Add DestroyKeyVersion DestroyKeyVersion immediately destroys a key version if it is a root key version or a data key version which encrypts no data. If the data key version encrypts data which needs to be rewrapped, it queues an asynchronous job to complete the rewrapping operation. * feat(scopes): Add DestroyKeyVersion API endpoint * feat(cli): Add scopes destroy-key-version CLI command * Ensure all secret updates include key ID (#2556) * feat(all): Ensure all secret updates include key ID When updating a secret, it is paramount that the key ID is also updated, as it is the only means we have of ensuring that we only destroy keys once there is no more data associated with the key. * Remove fix to session repository for now This breaks the current private key derivation method * add new encrypt/decrypt funcs and made necessary proto changes (#2557) * add new encrypt/decrypt funcs and made necessary proto changes * address all PR comments * fix test panic * add param checking to rewraps * fix(schema): Correctly organize migrations again * Review comments part 1 * Review comments part 2 * Review comments part 3 * Store cert private key, encrypt tofu token (#2583) * fix(session): store cert private key, encrypt tofu token Previously, we would derive a session certificate private key from the session key used in each project, and not store the key. We would also encrypt the tofu token with the database key but not store a reference to this key in the database. This change fixes this by replacing our key derivation with a key generation step, and instead store the generated key, encrypted, in the database. We also ensure that any new tofu tokens are encrypted with the same key. To handle existing sessions, we lazily rewrite the sessions whenever a user lists them. There is a minor risk that a user could end up destroying the database key that encrypts the tofu token before that session has been rewrapped, but this is going to be rare and temporary. * feat(session): Allow the random source for secrets to be configured * Review comments * Minor fixes * More minor fixes * More small fixes Co-authored-by: Danielle Miu <dani.miu@hashicorp.com> Co-authored-by: Danielle <29378233+DanielleMiu@users.noreply.github.com> Co-authored-by: Michael Gaffney <mike@gaffney.cc> Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com> * fix(session): Unset session key ID when scope is deleted Unsetting the key ID allows the session to live beyond the lifetime of the scope, while allowing the scope to cascade delete its keys. * fix(migrations): Rewrite migration 56 tests These tests can no longer use the normal test helpers as they try to use the new oplog table structure, so we have to manually write all the interactions. * fix(migrations): Rename migration 58 file name This was the name used in the release branch, update it to the new migration number. * fix(e2e): Add some comments and debug to kms tests * fix(session): Handle empty project and user IDs in read When a project or user is deleted, the session is automatically canceled and the respective field on the session is unset. LookupSession did not handle this case gracefully, and would error on decryption in this state. Skip decrypting sessions that do not have either a user or project to avoid this error. The decrypted values are not used for a canceled session. * Fix worker test * Increase test timeout Co-authored-by: Danielle Miu <dani.miu@hashicorp.com> Co-authored-by: Danielle <29378233+DanielleMiu@users.noreply.github.com> Co-authored-by: Michael Gaffney <mike@gaffney.cc> Co-authored-by: Michael Gaffney <mgaffney@users.noreply.github.com>
551 lines
21 KiB
Go
551 lines
21 KiB
Go
package session
|
|
|
|
import (
|
|
"context"
|
|
"crypto/ed25519"
|
|
"crypto/x509"
|
|
"io"
|
|
"math/big"
|
|
mathrand "math/rand"
|
|
"net"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/hashicorp/boundary/internal/boundary"
|
|
"github.com/hashicorp/boundary/internal/db"
|
|
"github.com/hashicorp/boundary/internal/db/timestamp"
|
|
"github.com/hashicorp/boundary/internal/errors"
|
|
"github.com/hashicorp/boundary/internal/util"
|
|
wrapping "github.com/hashicorp/go-kms-wrapping/v2"
|
|
"github.com/hashicorp/go-kms-wrapping/v2/extras/structwrapping"
|
|
"google.golang.org/protobuf/types/known/timestamppb"
|
|
)
|
|
|
|
const (
|
|
defaultSessionTableName = "session"
|
|
)
|
|
|
|
// ComposedOf defines the boundary data that is referenced to compose a session.
|
|
type ComposedOf struct {
|
|
// UserId of the session
|
|
UserId string
|
|
// HostId of the session
|
|
HostId string
|
|
// TargetId of the session
|
|
TargetId string
|
|
// HostSetId of the session
|
|
HostSetId string
|
|
// AuthTokenId of the session
|
|
AuthTokenId string
|
|
// ProjectId of the session
|
|
ProjectId string
|
|
// Endpoint. This is generated by the target, but is not stored in the
|
|
// warehouse as the worker may need to e.g. resolve DNS. This is to round
|
|
// trip the information to the worker when it validates a session.
|
|
Endpoint string
|
|
// Expiration time for the session
|
|
ExpirationTime *timestamp.Timestamp
|
|
// Max connections for the session
|
|
ConnectionLimit int32
|
|
// Worker filter. Active filter when the session was created, used to
|
|
// validate the session via the same set of rules at consumption time as
|
|
// existed at creation time. Round tripping it through here saves a lookup
|
|
// in the DB. It is not stored in the warehouse.
|
|
WorkerFilter string
|
|
// DynamicCredentials are dynamic credentials that will be retrieved
|
|
// for the session. DynamicCredentials optional.
|
|
DynamicCredentials []*DynamicCredential
|
|
// StaticCredentials are static credentials that will be retrieved
|
|
// for the session. StaticCredentials optional.
|
|
StaticCredentials []*StaticCredential
|
|
}
|
|
|
|
// Session contains information about a user's session with a target
|
|
type Session struct {
|
|
// PublicId is used to access the session via an API
|
|
PublicId string `json:"public_id,omitempty" gorm:"primary_key"`
|
|
// UserId for the session
|
|
UserId string `json:"user_id,omitempty" gorm:"default:null"`
|
|
// HostId of the session
|
|
HostId string `json:"host_id,omitempty" gorm:"default:null"`
|
|
// TargetId for the session
|
|
TargetId string `json:"target_id,omitempty" gorm:"default:null"`
|
|
// HostSetId for the session
|
|
HostSetId string `json:"host_set_id,omitempty" gorm:"default:null"`
|
|
// AuthTokenId for the session
|
|
AuthTokenId string `json:"auth_token_id,omitempty" gorm:"default:null"`
|
|
// ProjectId for the session
|
|
ProjectId string `json:"project_id,omitempty" gorm:"default:null"`
|
|
// Certificate to use when connecting (or if using custom certs, to
|
|
// serve as the "login"). Raw DER bytes.
|
|
Certificate []byte `json:"certificate,omitempty" gorm:"default:null"`
|
|
// CtCertificatePrivateKey is the ciphertext certificate private key which is stored in the database
|
|
CtCertificatePrivateKey []byte `json:"ct_certificate_private_key,omitempty" gorm:"column:certificate_private_key;default:null" wrapping:"ct,certificate_private_key"`
|
|
// CertificatePrivateKey is the certificate private key in plaintext.
|
|
// This may not be set for some sessions, in which case the private
|
|
// key should be derived from the encryption key referenced in key_id.
|
|
CertificatePrivateKey []byte `json:"certificate_private_key,omitempty" gorm:"-" wrapping:"pt,certificate_private_key"`
|
|
// ExpirationTime - after this time the connection will be expired, e.g. forcefully terminated
|
|
ExpirationTime *timestamp.Timestamp `json:"expiration_time,omitempty" gorm:"default:null"`
|
|
// CtTofuToken is the ciphertext Tofutoken value stored in the database
|
|
CtTofuToken []byte `json:"ct_tofu_token,omitempty" gorm:"column:tofu_token;default:null" wrapping:"ct,tofu_token"`
|
|
// TofuToken - plain text of the "trust on first use" token for session
|
|
TofuToken []byte `json:"tofu_token,omitempty" gorm:"-" wrapping:"pt,tofu_token"`
|
|
// termination_reason for the session
|
|
TerminationReason string `json:"termination_reason,omitempty" gorm:"default:null"`
|
|
// CreateTime from the RDBMS
|
|
CreateTime *timestamp.Timestamp `json:"create_time,omitempty" gorm:"default:current_timestamp"`
|
|
// UpdateTime from the RDBMS
|
|
UpdateTime *timestamp.Timestamp `json:"update_time,omitempty" gorm:"default:current_timestamp"`
|
|
// Version for the session
|
|
Version uint32 `json:"version,omitempty" gorm:"default:null"`
|
|
// Endpoint
|
|
Endpoint string `json:"-" gorm:"default:null"`
|
|
// Maximum number of connections in a session
|
|
ConnectionLimit int32 `json:"connection_limit,omitempty" gorm:"default:null"`
|
|
// Worker filter
|
|
WorkerFilter string `json:"-" gorm:"default:null"`
|
|
|
|
// key_id is the ID of the key version used to encrypt any fields in this struct
|
|
KeyId string `json:"key_id,omitempty" gorm:"default:null"`
|
|
|
|
// States for the session which are for read only and are ignored during
|
|
// write operations
|
|
States []*State `gorm:"-"`
|
|
|
|
// DynamicCredentials for the session.
|
|
DynamicCredentials []*DynamicCredential `gorm:"-"`
|
|
|
|
// StaticCredentials for the session.
|
|
StaticCredentials []*StaticCredential `gorm:"-"`
|
|
|
|
// Connections for the session are for read only and are ignored during write operations
|
|
Connections []*Connection `gorm:"-"`
|
|
|
|
tableName string `gorm:"-"`
|
|
}
|
|
|
|
func (s Session) GetPublicId() string {
|
|
return s.PublicId
|
|
}
|
|
|
|
func (s Session) GetProjectId() string {
|
|
return s.ProjectId
|
|
}
|
|
|
|
func (s Session) GetUserId() string {
|
|
return s.UserId
|
|
}
|
|
|
|
var (
|
|
_ Cloneable = (*Session)(nil)
|
|
_ db.VetForWriter = (*Session)(nil)
|
|
_ boundary.AuthzProtectedEntity = (*Session)(nil)
|
|
)
|
|
|
|
// New creates a new in memory session.
|
|
func New(c ComposedOf, _ ...Option) (*Session, error) {
|
|
const op = "session.New"
|
|
s := Session{
|
|
UserId: c.UserId,
|
|
HostId: c.HostId,
|
|
TargetId: c.TargetId,
|
|
HostSetId: c.HostSetId,
|
|
AuthTokenId: c.AuthTokenId,
|
|
ProjectId: c.ProjectId,
|
|
Endpoint: c.Endpoint,
|
|
ExpirationTime: c.ExpirationTime,
|
|
ConnectionLimit: c.ConnectionLimit,
|
|
WorkerFilter: c.WorkerFilter,
|
|
DynamicCredentials: c.DynamicCredentials,
|
|
StaticCredentials: c.StaticCredentials,
|
|
}
|
|
if err := s.validateNewSession(); err != nil {
|
|
return nil, errors.WrapDeprecated(err, op)
|
|
}
|
|
return &s, nil
|
|
}
|
|
|
|
// AllocSession will allocate a Session
|
|
func AllocSession() Session {
|
|
return Session{}
|
|
}
|
|
|
|
// Clone creates a clone of the Session
|
|
func (s *Session) Clone() any {
|
|
clone := &Session{
|
|
PublicId: s.PublicId,
|
|
UserId: s.UserId,
|
|
HostId: s.HostId,
|
|
TargetId: s.TargetId,
|
|
HostSetId: s.HostSetId,
|
|
AuthTokenId: s.AuthTokenId,
|
|
ProjectId: s.ProjectId,
|
|
TerminationReason: s.TerminationReason,
|
|
Version: s.Version,
|
|
Endpoint: s.Endpoint,
|
|
ConnectionLimit: s.ConnectionLimit,
|
|
WorkerFilter: s.WorkerFilter,
|
|
KeyId: s.KeyId,
|
|
}
|
|
if len(s.States) > 0 {
|
|
clone.States = make([]*State, 0, len(s.States))
|
|
for _, ss := range s.States {
|
|
cp := ss.Clone().(*State)
|
|
clone.States = append(clone.States, cp)
|
|
}
|
|
}
|
|
if len(s.DynamicCredentials) > 0 {
|
|
clone.DynamicCredentials = make([]*DynamicCredential, 0, len(s.DynamicCredentials))
|
|
for _, sc := range s.DynamicCredentials {
|
|
cp := sc.clone()
|
|
clone.DynamicCredentials = append(clone.DynamicCredentials, cp)
|
|
}
|
|
}
|
|
if len(s.StaticCredentials) > 0 {
|
|
clone.StaticCredentials = make([]*StaticCredential, 0, len(s.StaticCredentials))
|
|
for _, sc := range s.StaticCredentials {
|
|
cp := sc.clone()
|
|
clone.StaticCredentials = append(clone.StaticCredentials, cp)
|
|
}
|
|
}
|
|
if s.TofuToken != nil {
|
|
clone.TofuToken = make([]byte, len(s.TofuToken))
|
|
copy(clone.TofuToken, s.TofuToken)
|
|
}
|
|
if s.CtTofuToken != nil {
|
|
clone.CtTofuToken = make([]byte, len(s.CtTofuToken))
|
|
copy(clone.CtTofuToken, s.CtTofuToken)
|
|
}
|
|
if s.Certificate != nil {
|
|
clone.Certificate = make([]byte, len(s.Certificate))
|
|
copy(clone.Certificate, s.Certificate)
|
|
}
|
|
if s.CertificatePrivateKey != nil {
|
|
clone.CertificatePrivateKey = make([]byte, len(s.CertificatePrivateKey))
|
|
copy(clone.CertificatePrivateKey, s.CertificatePrivateKey)
|
|
}
|
|
if s.CtCertificatePrivateKey != nil {
|
|
clone.CtCertificatePrivateKey = make([]byte, len(s.CtCertificatePrivateKey))
|
|
copy(clone.CtCertificatePrivateKey, s.CtCertificatePrivateKey)
|
|
}
|
|
if s.ExpirationTime != nil {
|
|
clone.ExpirationTime = ×tamp.Timestamp{
|
|
Timestamp: ×tamppb.Timestamp{
|
|
Seconds: s.ExpirationTime.Timestamp.Seconds,
|
|
Nanos: s.ExpirationTime.Timestamp.Nanos,
|
|
},
|
|
}
|
|
}
|
|
if s.CreateTime != nil {
|
|
clone.CreateTime = ×tamp.Timestamp{
|
|
Timestamp: ×tamppb.Timestamp{
|
|
Seconds: s.CreateTime.Timestamp.Seconds,
|
|
Nanos: s.CreateTime.Timestamp.Nanos,
|
|
},
|
|
}
|
|
}
|
|
if s.UpdateTime != nil {
|
|
clone.UpdateTime = ×tamp.Timestamp{
|
|
Timestamp: ×tamppb.Timestamp{
|
|
Seconds: s.UpdateTime.Timestamp.Seconds,
|
|
Nanos: s.UpdateTime.Timestamp.Nanos,
|
|
},
|
|
}
|
|
}
|
|
return clone
|
|
}
|
|
|
|
// VetForWrite implements db.VetForWrite() interface and validates the session
|
|
// before it's written.
|
|
func (s *Session) VetForWrite(ctx context.Context, _ db.Reader, opType db.OpType, opt ...db.Option) error {
|
|
const op = "session.(Session).VetForWrite"
|
|
opts := db.GetOpts(opt...)
|
|
if s.PublicId == "" {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "missing public id")
|
|
}
|
|
switch opType {
|
|
case db.CreateOp:
|
|
if err := s.validateNewSession(); err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
if len(s.Certificate) == 0 {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "missing certificate")
|
|
}
|
|
case db.UpdateOp:
|
|
switch {
|
|
case contains(opts.WithFieldMaskPaths, "PublicId"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "public id is immutable")
|
|
case contains(opts.WithFieldMaskPaths, "UserId"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "user id is immutable")
|
|
case contains(opts.WithFieldMaskPaths, "HostId"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "host id is immutable")
|
|
case contains(opts.WithFieldMaskPaths, "TargetId"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "target id is immutable")
|
|
case contains(opts.WithFieldMaskPaths, "HostSetId"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "host set id is immutable")
|
|
case contains(opts.WithFieldMaskPaths, "AuthTokenId"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "auth token id is immutable")
|
|
case contains(opts.WithFieldMaskPaths, "Certificate"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "certificate is immutable")
|
|
case contains(opts.WithFieldMaskPaths, "CreateTime"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "create time is immutable")
|
|
case contains(opts.WithFieldMaskPaths, "UpdateTime"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "update time is immutable")
|
|
case contains(opts.WithFieldMaskPaths, "Endpoint"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "endpoint is immutable")
|
|
case contains(opts.WithFieldMaskPaths, "ExpirationTime"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "expiration time is immutable")
|
|
case contains(opts.WithFieldMaskPaths, "ConnectionLimit"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "connection limit is immutable")
|
|
case contains(opts.WithFieldMaskPaths, "WorkerFilter"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "worker filter is immutable")
|
|
case contains(opts.WithFieldMaskPaths, "DynamicCredentials"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "dynamic credentials are immutable")
|
|
case contains(opts.WithFieldMaskPaths, "StaticCredentials"):
|
|
return errors.New(ctx, errors.InvalidParameter, op, "static credentials are immutable")
|
|
case contains(opts.WithFieldMaskPaths, "TerminationReason"):
|
|
if _, err := convertToReason(s.TerminationReason); err != nil {
|
|
return errors.Wrap(ctx, err, op)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// TableName returns the tablename to override the default gorm table name
|
|
func (s *Session) TableName() string {
|
|
if s.tableName != "" {
|
|
return s.tableName
|
|
}
|
|
return defaultSessionTableName
|
|
}
|
|
|
|
// SetTableName sets the tablename and satisfies the ReplayableMessage
|
|
// interface. If the caller attempts to set the name to "" the name will be
|
|
// reset to the default name.
|
|
func (s *Session) SetTableName(n string) {
|
|
s.tableName = n
|
|
}
|
|
|
|
// validateNewSession checks everything but the session's PublicId
|
|
func (s *Session) validateNewSession() error {
|
|
const op = "session.(Session).validateNewSession"
|
|
if s.UserId == "" {
|
|
return errors.NewDeprecated(errors.InvalidParameter, op, "missing user id")
|
|
}
|
|
if s.HostId == "" {
|
|
return errors.NewDeprecated(errors.InvalidParameter, op, "missing host id")
|
|
}
|
|
if s.TargetId == "" {
|
|
return errors.NewDeprecated(errors.InvalidParameter, op, "missing target id")
|
|
}
|
|
if s.HostSetId == "" {
|
|
return errors.NewDeprecated(errors.InvalidParameter, op, "missing host set id")
|
|
}
|
|
if s.AuthTokenId == "" {
|
|
return errors.NewDeprecated(errors.InvalidParameter, op, "missing auth token id")
|
|
}
|
|
if s.ProjectId == "" {
|
|
return errors.NewDeprecated(errors.InvalidParameter, op, "missing project id")
|
|
}
|
|
if s.Endpoint == "" {
|
|
return errors.NewDeprecated(errors.InvalidParameter, op, "missing endpoint")
|
|
}
|
|
if s.ExpirationTime.GetTimestamp().AsTime().IsZero() {
|
|
return errors.NewDeprecated(errors.InvalidParameter, op, "missing expiration time")
|
|
}
|
|
if s.TerminationReason != "" {
|
|
return errors.NewDeprecated(errors.InvalidParameter, op, "termination reason must be empty")
|
|
}
|
|
if s.TofuToken != nil {
|
|
return errors.NewDeprecated(errors.InvalidParameter, op, "tofu token must be empty")
|
|
}
|
|
if s.CtTofuToken != nil {
|
|
return errors.NewDeprecated(errors.InvalidParameter, op, "ct must be empty")
|
|
}
|
|
// It is okay for the worker filter to be empty, so it is not checked here.
|
|
return nil
|
|
}
|
|
|
|
func contains(ss []string, t string) bool {
|
|
for _, s := range ss {
|
|
if strings.EqualFold(s, t) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
// newCert creates a new session certificate. If addresses are supplied, they will be parsed and added to IP or DNS SANs as appropriate.
|
|
func newCert(ctx context.Context, jobId string, addresses []string, exp time.Time, rand io.Reader) (ed25519.PrivateKey, []byte, error) {
|
|
const op = "session.newCert"
|
|
if jobId == "" {
|
|
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing job id")
|
|
}
|
|
if len(addresses) == 0 {
|
|
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing addresses")
|
|
}
|
|
if exp.IsZero() {
|
|
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing expiry")
|
|
}
|
|
if util.IsNil(rand) {
|
|
return nil, nil, errors.New(ctx, errors.InvalidParameter, op, "missing random data source")
|
|
}
|
|
pubKey, privKey, err := ed25519.GenerateKey(rand)
|
|
if err != nil {
|
|
return nil, nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
template := &x509.Certificate{
|
|
ExtKeyUsage: []x509.ExtKeyUsage{
|
|
x509.ExtKeyUsageServerAuth,
|
|
x509.ExtKeyUsageClientAuth,
|
|
},
|
|
DNSNames: []string{jobId},
|
|
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment | x509.KeyUsageKeyAgreement | x509.KeyUsageCertSign,
|
|
SerialNumber: big.NewInt(mathrand.Int63()),
|
|
NotBefore: time.Now().Add(-1 * time.Minute),
|
|
NotAfter: exp,
|
|
BasicConstraintsValid: true,
|
|
IsCA: true,
|
|
}
|
|
|
|
for _, addr := range addresses {
|
|
// First ensure we aren't looking at ports, regardless of IP or not
|
|
host, _, err := net.SplitHostPort(addr)
|
|
if err != nil {
|
|
if strings.Contains(err.Error(), "missing port") {
|
|
host = addr
|
|
} else {
|
|
return nil, nil, errors.Wrap(ctx, err, op)
|
|
}
|
|
}
|
|
// Now figure out if it's an IP address or not. If ParseIP likes it, add
|
|
// to IP SANs. Otherwise DNS SANs.
|
|
ip := net.ParseIP(host)
|
|
switch ip {
|
|
case nil:
|
|
template.DNSNames = append(template.DNSNames, host)
|
|
default:
|
|
template.IPAddresses = append(template.IPAddresses, ip)
|
|
}
|
|
}
|
|
|
|
certBytes, err := x509.CreateCertificate(rand, template, template, pubKey, privKey)
|
|
if err != nil {
|
|
return nil, nil, errors.Wrap(ctx, err, op, errors.WithCode(errors.GenCert))
|
|
}
|
|
return privKey, certBytes, nil
|
|
}
|
|
|
|
func (s *Session) encrypt(ctx context.Context, cipher wrapping.Wrapper) error {
|
|
const op = "session.(Session).encrypt"
|
|
if util.IsNil(cipher) {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "missing cipher")
|
|
}
|
|
// Split encryption per field since they can be independently nil.
|
|
if len(s.TofuToken) > 0 {
|
|
type tofuToken struct {
|
|
TofuToken []byte `wrapping:"pt,tofu_token"`
|
|
CtTofuToken []byte `wrapping:"ct,tofu_token"`
|
|
}
|
|
v := &tofuToken{
|
|
TofuToken: s.TofuToken,
|
|
}
|
|
if err := structwrapping.WrapStruct(ctx, cipher, v); err != nil {
|
|
return errors.Wrap(ctx, err, op, errors.WithCode(errors.Encrypt), errors.WithMsg("failed to encrypt tofu token"))
|
|
}
|
|
s.CtTofuToken = v.CtTofuToken
|
|
}
|
|
if len(s.CertificatePrivateKey) > 0 {
|
|
type certPk struct {
|
|
CertificatePrivateKey []byte `wrapping:"pt,certificate_private_key"`
|
|
CtCertificatePrivateKey []byte `wrapping:"ct,certificate_private_key"`
|
|
}
|
|
v := &certPk{
|
|
CertificatePrivateKey: s.CertificatePrivateKey,
|
|
}
|
|
if err := structwrapping.WrapStruct(ctx, cipher, v); err != nil {
|
|
return errors.Wrap(ctx, err, op, errors.WithCode(errors.Encrypt), errors.WithMsg("failed to encrypt certificate private key"))
|
|
}
|
|
s.CtCertificatePrivateKey = v.CtCertificatePrivateKey
|
|
}
|
|
keyId, err := cipher.KeyId(ctx)
|
|
if err != nil {
|
|
return errors.Wrap(ctx, err, op, errors.WithCode(errors.Encrypt), errors.WithMsg("error getting cipher key id"))
|
|
}
|
|
s.KeyId = keyId
|
|
return nil
|
|
}
|
|
|
|
func (s *Session) decrypt(ctx context.Context, cipher wrapping.Wrapper) error {
|
|
const op = "session.(Session).decrypt"
|
|
if util.IsNil(cipher) {
|
|
return errors.New(ctx, errors.InvalidParameter, op, "missing cipher")
|
|
}
|
|
// Split decryption per field since they can be independently nil.
|
|
if len(s.CtTofuToken) > 0 {
|
|
type tofuToken struct {
|
|
TofuToken []byte `wrapping:"pt,tofu_token"`
|
|
CtTofuToken []byte `wrapping:"ct,tofu_token"`
|
|
}
|
|
v := &tofuToken{
|
|
CtTofuToken: s.CtTofuToken,
|
|
}
|
|
if err := structwrapping.UnwrapStruct(ctx, cipher, v); err != nil {
|
|
return errors.Wrap(ctx, err, op, errors.WithCode(errors.Decrypt), errors.WithMsg("failed to decrypt tofu token"))
|
|
}
|
|
s.TofuToken = v.TofuToken
|
|
}
|
|
if len(s.CtCertificatePrivateKey) > 0 {
|
|
type certPk struct {
|
|
CertificatePrivateKey []byte `wrapping:"pt,certificate_private_key"`
|
|
CtCertificatePrivateKey []byte `wrapping:"ct,certificate_private_key"`
|
|
}
|
|
v := &certPk{
|
|
CtCertificatePrivateKey: s.CtCertificatePrivateKey,
|
|
}
|
|
if err := structwrapping.UnwrapStruct(ctx, cipher, v); err != nil {
|
|
return errors.Wrap(ctx, err, op, errors.WithCode(errors.Decrypt), errors.WithMsg("failed to decrypt certificate private key"))
|
|
}
|
|
s.CertificatePrivateKey = v.CertificatePrivateKey
|
|
}
|
|
|
|
return nil
|
|
}
|
|
|
|
type sessionListView struct {
|
|
// Session fields
|
|
PublicId string `json:"public_id,omitempty" gorm:"primary_key"`
|
|
UserId string `json:"user_id,omitempty" gorm:"default:null"`
|
|
HostId string `json:"host_id,omitempty" gorm:"default:null"`
|
|
TargetId string `json:"target_id,omitempty" gorm:"default:null"`
|
|
HostSetId string `json:"host_set_id,omitempty" gorm:"default:null"`
|
|
AuthTokenId string `json:"auth_token_id,omitempty" gorm:"default:null"`
|
|
ProjectId string `json:"project_id,omitempty" gorm:"default:null"`
|
|
Certificate []byte `json:"certificate,omitempty" gorm:"default:null"`
|
|
CtCertificatePrivateKey []byte `json:"ct_certificate_private_key,omitempty" gorm:"column:certificate_private_key;default:null" wrapping:"ct,certificate_private_key"`
|
|
CertificatePrivateKey []byte `json:"certificate_private_key,omitempty" gorm:"-" wrapping:"pt,certificate_private_key"`
|
|
ExpirationTime *timestamp.Timestamp `json:"expiration_time,omitempty" gorm:"default:null"`
|
|
CtTofuToken []byte `json:"ct_tofu_token,omitempty" gorm:"column:tofu_token;default:null" wrapping:"ct,tofu_token"`
|
|
TofuToken []byte `json:"tofu_token,omitempty" gorm:"-" wrapping:"pt,tofu_token"`
|
|
TerminationReason string `json:"termination_reason,omitempty" gorm:"default:null"`
|
|
CreateTime *timestamp.Timestamp `json:"create_time,omitempty" gorm:"default:current_timestamp"`
|
|
UpdateTime *timestamp.Timestamp `json:"update_time,omitempty" gorm:"default:current_timestamp"`
|
|
Version uint32 `json:"version,omitempty" gorm:"default:null"`
|
|
Endpoint string `json:"-" gorm:"default:null"`
|
|
ConnectionLimit int32 `json:"connection_limit,omitempty" gorm:"default:null"`
|
|
KeyId string `json:"key_id,omitempty" gorm:"default:null"`
|
|
|
|
// State fields
|
|
Status string `json:"state,omitempty" gorm:"column:state"`
|
|
PreviousEndTime *timestamp.Timestamp `json:"previous_end_time,omitempty" gorm:"default:current_timestamp"`
|
|
StartTime *timestamp.Timestamp `json:"start_time,omitempty" gorm:"default:current_timestamp;primary_key"`
|
|
EndTime *timestamp.Timestamp `json:"end_time,omitempty" gorm:"default:current_timestamp"`
|
|
}
|
|
|
|
// TableName returns the tablename to override the default gorm table name
|
|
func (s *sessionListView) TableName() string {
|
|
return "session_list"
|
|
}
|