2016-05-02 04:08:07 +00:00
package vault
import (
2018-01-08 18:31:38 +00:00
"context"
2018-05-31 00:30:50 +00:00
"errors"
2016-09-29 04:01:28 +00:00
"fmt"
2016-05-02 04:08:07 +00:00
"strings"
2019-03-05 19:55:07 +00:00
"sync/atomic"
2016-05-02 04:08:07 +00:00
"time"
2019-01-09 00:48:57 +00:00
metrics "github.com/armon/go-metrics"
2018-08-10 13:59:58 +00:00
"github.com/hashicorp/errwrap"
2019-01-09 00:48:57 +00:00
multierror "github.com/hashicorp/go-multierror"
2018-05-31 00:30:50 +00:00
sockaddr "github.com/hashicorp/go-sockaddr"
2020-10-12 18:56:24 +00:00
"github.com/hashicorp/shared-secure-libs/configutil"
"github.com/hashicorp/shared-secure-libs/metricsutil"
2019-04-13 07:44:06 +00:00
"github.com/hashicorp/vault/helper/identity"
2020-10-12 18:56:24 +00:00
vaultmetrics "github.com/hashicorp/vault/helper/metricsutil"
2019-04-13 07:44:06 +00:00
"github.com/hashicorp/vault/helper/namespace"
"github.com/hashicorp/vault/sdk/framework"
2019-04-12 21:54:35 +00:00
"github.com/hashicorp/vault/sdk/helper/consts"
"github.com/hashicorp/vault/sdk/helper/errutil"
"github.com/hashicorp/vault/sdk/helper/jsonutil"
2019-04-12 22:08:46 +00:00
"github.com/hashicorp/vault/sdk/helper/policyutil"
2019-04-12 21:54:35 +00:00
"github.com/hashicorp/vault/sdk/helper/strutil"
"github.com/hashicorp/vault/sdk/helper/wrapping"
"github.com/hashicorp/vault/sdk/logical"
2020-06-26 21:13:16 +00:00
"github.com/hashicorp/vault/vault/quotas"
2019-10-15 04:55:31 +00:00
uberAtomic "go.uber.org/atomic"
2016-05-02 04:08:07 +00:00
)
2017-10-23 18:59:37 +00:00
const (
2020-09-22 21:47:13 +00:00
replTimeout = 1 * time . Second
2017-10-23 18:59:37 +00:00
)
2018-07-24 21:50:49 +00:00
var (
// DefaultMaxRequestDuration is the amount of time we'll wait for a request
// to complete, unless overridden on a per-handler basis
2018-08-01 19:07:37 +00:00
DefaultMaxRequestDuration = 90 * time . Second
2018-09-18 03:03:00 +00:00
egpDebugLogging bool
2018-07-24 21:50:49 +00:00
)
2018-08-02 01:39:39 +00:00
// HandlerProperties is used to seed configuration into a vaulthttp.Handler.
2018-07-06 19:44:56 +00:00
// It's in this package to avoid a circular dependency
type HandlerProperties struct {
2020-05-14 13:19:27 +00:00
Core * Core
ListenerConfig * configutil . Listener
DisablePrintableCheck bool
RecoveryMode bool
RecoveryToken * uberAtomic . String
2018-07-06 19:44:56 +00:00
}
2018-05-31 00:30:50 +00:00
// fetchEntityAndDerivedPolicies returns the entity object for the given entity
// ID. If the entity is merged into a different entity object, the entity into
// which the given entity ID is merged into will be returned. This function
// also returns the cumulative list of policies that the entity is entitled to.
// This list includes the policies from the entity itself and from all the
// groups in which the given entity ID is a member of.
2018-09-18 03:03:00 +00:00
func ( c * Core ) fetchEntityAndDerivedPolicies ( ctx context . Context , tokenNS * namespace . Namespace , entityID string ) ( * identity . Entity , map [ string ] [ ] string , error ) {
2018-05-31 00:30:50 +00:00
if entityID == "" || c . identityStore == nil {
return nil , nil , nil
}
//c.logger.Debug("entity set on the token", "entity_id", te.EntityID)
// Fetch the entity
entity , err := c . identityStore . MemDBEntityByID ( entityID , false )
if err != nil {
c . logger . Error ( "failed to lookup entity using its ID" , "error" , err )
return nil , nil , err
}
if entity == nil {
// If there was no corresponding entity object found, it is
// possible that the entity got merged into another entity. Try
// finding entity based on the merged entity index.
entity , err = c . identityStore . MemDBEntityByMergedEntityID ( entityID , false )
if err != nil {
c . logger . Error ( "failed to lookup entity in merged entity ID index" , "error" , err )
return nil , nil , err
}
}
2018-09-18 03:03:00 +00:00
policies := make ( map [ string ] [ ] string )
2018-05-31 00:30:50 +00:00
if entity != nil {
//c.logger.Debug("entity successfully fetched; adding entity policies to token's policies to create ACL")
// Attach the policies on the entity
2018-09-18 03:03:00 +00:00
if len ( entity . Policies ) != 0 {
policies [ entity . NamespaceID ] = append ( policies [ entity . NamespaceID ] , entity . Policies ... )
}
2018-05-31 00:30:50 +00:00
groupPolicies , err := c . identityStore . groupPoliciesByEntityID ( entity . ID )
if err != nil {
c . logger . Error ( "failed to fetch group policies" , "error" , err )
return nil , nil , err
}
2018-09-18 03:03:00 +00:00
// Filter and add the policies to the resultant set
for nsID , nsPolicies := range groupPolicies {
ns , err := NamespaceByID ( ctx , nsID , c )
if err != nil {
return nil , nil , err
}
if ns == nil {
return nil , nil , namespace . ErrNoNamespace
}
if tokenNS . Path != ns . Path && ! ns . HasParent ( tokenNS ) {
continue
}
nsPolicies = strutil . RemoveDuplicates ( nsPolicies , false )
if len ( nsPolicies ) != 0 {
policies [ nsID ] = append ( policies [ nsID ] , nsPolicies ... )
}
}
2018-05-31 00:30:50 +00:00
}
return entity , policies , err
}
2018-09-18 03:03:00 +00:00
func ( c * Core ) fetchACLTokenEntryAndEntity ( ctx context . Context , req * logical . Request ) ( * ACL , * logical . TokenEntry , * identity . Entity , map [ string ] [ ] string , error ) {
2018-05-31 00:30:50 +00:00
defer metrics . MeasureSince ( [ ] string { "core" , "fetch_acl_and_token" } , time . Now ( ) )
// Ensure there is a client token
if req . ClientToken == "" {
2018-06-14 13:49:33 +00:00
return nil , nil , nil , nil , fmt . Errorf ( "missing client token" )
2018-05-31 00:30:50 +00:00
}
if c . tokenStore == nil {
c . logger . Error ( "token store is unavailable" )
2018-06-14 13:49:33 +00:00
return nil , nil , nil , nil , ErrInternalError
2018-05-31 00:30:50 +00:00
}
// Resolve the token policy
2018-06-08 21:24:27 +00:00
var te * logical . TokenEntry
switch req . TokenEntry ( ) {
case nil :
var err error
2018-09-18 03:03:00 +00:00
te , err = c . tokenStore . Lookup ( ctx , req . ClientToken )
2018-06-08 21:24:27 +00:00
if err != nil {
c . logger . Error ( "failed to lookup token" , "error" , err )
2018-06-14 13:49:33 +00:00
return nil , nil , nil , nil , ErrInternalError
2018-06-08 21:24:27 +00:00
}
2018-12-03 16:57:53 +00:00
// Set the token entry here since it has not been cached yet
req . SetTokenEntry ( te )
2018-06-08 21:24:27 +00:00
default :
te = req . TokenEntry ( )
2018-05-31 00:30:50 +00:00
}
// Ensure the token is valid
if te == nil {
2018-06-14 13:49:33 +00:00
return nil , nil , nil , nil , logical . ErrPermissionDenied
2018-05-31 00:30:50 +00:00
}
// CIDR checks bind all tokens except non-expiring root tokens
if te . TTL != 0 && len ( te . BoundCIDRs ) > 0 {
var valid bool
remoteSockAddr , err := sockaddr . NewSockAddr ( req . Connection . RemoteAddr )
if err != nil {
if c . Logger ( ) . IsDebug ( ) {
c . Logger ( ) . Debug ( "could not parse remote addr into sockaddr" , "error" , err , "remote_addr" , req . Connection . RemoteAddr )
}
2018-06-14 13:49:33 +00:00
return nil , nil , nil , nil , logical . ErrPermissionDenied
2018-05-31 00:30:50 +00:00
}
for _ , cidr := range te . BoundCIDRs {
if cidr . Contains ( remoteSockAddr ) {
valid = true
break
}
}
if ! valid {
2018-06-14 13:49:33 +00:00
return nil , nil , nil , nil , logical . ErrPermissionDenied
2018-05-31 00:30:50 +00:00
}
}
2018-09-18 03:03:00 +00:00
policies := make ( map [ string ] [ ] string )
// Add tokens policies
policies [ te . NamespaceID ] = append ( policies [ te . NamespaceID ] , te . Policies ... )
tokenNS , err := NamespaceByID ( ctx , te . NamespaceID , c )
2018-05-31 00:30:50 +00:00
if err != nil {
2018-09-18 03:03:00 +00:00
c . logger . Error ( "failed to fetch token namespace" , "error" , err )
return nil , nil , nil , nil , ErrInternalError
}
if tokenNS == nil {
c . logger . Error ( "failed to fetch token namespace" , "error" , namespace . ErrNoNamespace )
2018-06-14 13:49:33 +00:00
return nil , nil , nil , nil , ErrInternalError
2018-05-31 00:30:50 +00:00
}
2018-09-18 03:03:00 +00:00
// Add identity policies from all the namespaces
entity , identityPolicies , err := c . fetchEntityAndDerivedPolicies ( ctx , tokenNS , te . EntityID )
if err != nil {
return nil , nil , nil , nil , ErrInternalError
}
for nsID , nsPolicies := range identityPolicies {
policies [ nsID ] = append ( policies [ nsID ] , nsPolicies ... )
}
2018-05-31 00:30:50 +00:00
2018-09-18 03:03:00 +00:00
// Attach token's namespace information to the context. Wrapping tokens by
// should be able to be used anywhere, so we also special case behavior.
var tokenCtx context . Context
if len ( policies ) == 1 &&
len ( policies [ te . NamespaceID ] ) == 1 &&
( policies [ te . NamespaceID ] [ 0 ] == responseWrappingPolicyName ||
policies [ te . NamespaceID ] [ 0 ] == controlGroupPolicyName ) &&
( strings . HasSuffix ( req . Path , "sys/wrapping/unwrap" ) ||
strings . HasSuffix ( req . Path , "sys/wrapping/lookup" ) ||
strings . HasSuffix ( req . Path , "sys/wrapping/rewrap" ) ) {
// Use the request namespace; will find the copy of the policy for the
// local namespace
tokenCtx = ctx
} else {
// Use the token's namespace for looking up policy
tokenCtx = namespace . ContextWithNamespace ( ctx , tokenNS )
}
// Construct the corresponding ACL object. ACL construction should be
// performed on the token's namespace.
acl , err := c . policyStore . ACL ( tokenCtx , entity , policies )
2018-05-31 00:30:50 +00:00
if err != nil {
2018-08-15 18:42:56 +00:00
if errwrap . ContainsType ( err , new ( TemplateError ) ) {
2019-01-24 23:29:22 +00:00
c . logger . Warn ( "permission denied due to a templated policy being invalid or containing directives not satisfied by the requestor" , "error" , err )
return nil , nil , nil , nil , logical . ErrPermissionDenied
2018-08-15 18:42:56 +00:00
}
2018-05-31 00:30:50 +00:00
c . logger . Error ( "failed to construct ACL" , "error" , err )
2018-06-14 13:49:33 +00:00
return nil , nil , nil , nil , ErrInternalError
2018-05-31 00:30:50 +00:00
}
2018-06-14 13:49:33 +00:00
return acl , te , entity , identityPolicies , nil
2018-05-31 00:30:50 +00:00
}
2018-06-08 21:24:27 +00:00
func ( c * Core ) checkToken ( ctx context . Context , req * logical . Request , unauth bool ) ( * logical . Auth , * logical . TokenEntry , error ) {
2018-05-31 00:30:50 +00:00
defer metrics . MeasureSince ( [ ] string { "core" , "check_token" } , time . Now ( ) )
var acl * ACL
2018-06-08 21:24:27 +00:00
var te * logical . TokenEntry
2018-05-31 00:30:50 +00:00
var entity * identity . Entity
2018-09-18 03:03:00 +00:00
var identityPolicies map [ string ] [ ] string
2018-05-31 00:30:50 +00:00
var err error
// Even if unauth, if a token is provided, there's little reason not to
// gather as much info as possible for the audit log and to e.g. control
// trace mode for EGPs.
if ! unauth || ( unauth && req . ClientToken != "" ) {
2018-09-18 03:03:00 +00:00
acl , te , entity , identityPolicies , err = c . fetchACLTokenEntryAndEntity ( ctx , req )
2018-05-31 00:30:50 +00:00
// In the unauth case we don't want to fail the command, since it's
// unauth, we just have no information to attach to the request, so
// ignore errors...this was best-effort anyways
if err != nil && ! unauth {
return nil , te , err
}
}
if entity != nil && entity . Disabled {
2018-06-19 16:57:19 +00:00
c . logger . Warn ( "permission denied as the entity on the token is disabled" )
return nil , te , logical . ErrPermissionDenied
}
if te != nil && te . EntityID != "" && entity == nil {
2019-01-25 19:08:42 +00:00
if c . perfStandby {
return nil , nil , logical . ErrPerfStandbyPleaseForward
}
2018-06-19 16:57:19 +00:00
c . logger . Warn ( "permission denied as the entity on the token is invalid" )
2018-05-31 00:30:50 +00:00
return nil , te , logical . ErrPermissionDenied
}
// Check if this is a root protected path
2018-09-18 03:03:00 +00:00
rootPath := c . router . RootPath ( ctx , req . Path )
2018-05-31 00:30:50 +00:00
if rootPath && unauth {
return nil , nil , errors . New ( "cannot access root path in unauthenticated request" )
}
2019-02-11 18:08:15 +00:00
// At this point we won't be forwarding a raw request; we should delete
// authorization headers as appropriate
switch req . ClientTokenSource {
case logical . ClientTokenFromVaultHeader :
delete ( req . Headers , consts . AuthHeaderName )
case logical . ClientTokenFromAuthzHeader :
if headers , ok := req . Headers [ "Authorization" ] ; ok {
retHeaders := make ( [ ] string , 0 , len ( headers ) )
for _ , v := range headers {
if strings . HasPrefix ( v , "Bearer " ) {
continue
}
retHeaders = append ( retHeaders , v )
}
req . Headers [ "Authorization" ] = retHeaders
}
}
2018-05-31 00:30:50 +00:00
// When we receive a write of either type, rather than require clients to
// PUT/POST and trust the operation, we ask the backend to give us the real
// skinny -- if the backend implements an existence check, it can tell us
// whether a particular resource exists. Then we can mark it as an update
// or creation as appropriate.
if req . Operation == logical . CreateOperation || req . Operation == logical . UpdateOperation {
2018-10-15 16:56:24 +00:00
existsResp , checkExists , resourceExists , err := c . router . RouteExistenceCheck ( ctx , req )
2018-05-31 00:30:50 +00:00
switch err {
case logical . ErrUnsupportedPath :
// fail later via bad path to avoid confusing items in the log
checkExists = false
case nil :
2018-10-15 16:56:24 +00:00
if existsResp != nil && existsResp . IsError ( ) {
return nil , te , existsResp . Error ( )
}
// Otherwise, continue on
2018-05-31 00:30:50 +00:00
default :
c . logger . Error ( "failed to run existence check" , "error" , err )
if _ , ok := err . ( errutil . UserError ) ; ok {
2018-10-15 16:56:24 +00:00
return nil , te , err
2018-05-31 00:30:50 +00:00
} else {
2018-10-15 16:56:24 +00:00
return nil , te , ErrInternalError
2018-05-31 00:30:50 +00:00
}
}
switch {
case checkExists == false :
// No existence check, so always treat it as an update operation, which is how it is pre 0.5
req . Operation = logical . UpdateOperation
case resourceExists == true :
// It exists, so force an update operation
req . Operation = logical . UpdateOperation
case resourceExists == false :
// It doesn't exist, force a create operation
req . Operation = logical . CreateOperation
default :
panic ( "unreachable code" )
}
}
// Create the auth response
auth := & logical . Auth {
2018-09-18 03:03:00 +00:00
ClientToken : req . ClientToken ,
Accessor : req . ClientTokenAccessor ,
2018-05-31 00:30:50 +00:00
}
if te != nil {
2018-09-18 03:03:00 +00:00
auth . IdentityPolicies = identityPolicies [ te . NamespaceID ]
2018-06-14 13:49:33 +00:00
auth . TokenPolicies = te . Policies
2018-09-18 03:03:00 +00:00
auth . Policies = append ( te . Policies , identityPolicies [ te . NamespaceID ] ... )
2018-05-31 00:30:50 +00:00
auth . Metadata = te . Meta
auth . DisplayName = te . DisplayName
auth . EntityID = te . EntityID
2018-09-18 03:03:00 +00:00
delete ( identityPolicies , te . NamespaceID )
auth . ExternalNamespacePolicies = identityPolicies
2018-05-31 00:30:50 +00:00
// Store the entity ID in the request object
req . EntityID = te . EntityID
2018-10-15 16:56:24 +00:00
auth . TokenType = te . Type
2020-05-29 17:30:47 +00:00
auth . TTL = te . TTL
if te . CreationTime > 0 {
auth . IssueTime = time . Unix ( te . CreationTime , 0 )
}
2018-05-31 00:30:50 +00:00
}
// Check the standard non-root ACLs. Return the token entry if it's not
// allowed so we can decrement the use count.
authResults := c . performPolicyChecks ( ctx , acl , te , req , entity , & PolicyCheckOpts {
Unauth : unauth ,
RootPrivsRequired : rootPath ,
} )
2018-09-18 03:03:00 +00:00
2018-05-31 00:30:50 +00:00
if ! authResults . Allowed {
2018-08-11 02:32:10 +00:00
retErr := authResults . Error
2019-04-03 21:16:49 +00:00
// If we get a control group error and we are a performance standby,
// restore the client token information to the request so that we can
// forward this request properly to the active node.
if retErr . ErrorOrNil ( ) != nil && checkErrControlGroupTokenNeedsCreated ( retErr ) &&
c . perfStandby && len ( req . ClientToken ) != 0 {
switch req . ClientTokenSource {
case logical . ClientTokenFromVaultHeader :
req . Headers [ consts . AuthHeaderName ] = [ ] string { req . ClientToken }
case logical . ClientTokenFromAuthzHeader :
req . Headers [ "Authorization" ] = append ( req . Headers [ "Authorization" ] , fmt . Sprintf ( "Bearer %s" , req . ClientToken ) )
}
// We also return the appropriate error so that the caller can forward the
// request to the active node
return auth , te , logical . ErrPerfStandbyPleaseForward
}
2018-08-11 01:05:10 +00:00
if authResults . Error . ErrorOrNil ( ) == nil || authResults . DeniedError {
2018-08-11 02:32:10 +00:00
retErr = multierror . Append ( retErr , logical . ErrPermissionDenied )
2018-08-10 13:59:58 +00:00
}
2018-08-11 02:32:10 +00:00
return auth , te , retErr
2018-05-31 00:30:50 +00:00
}
return auth , te , nil
}
2016-05-02 04:08:07 +00:00
// HandleRequest is used to handle a new incoming request
2018-07-24 21:50:49 +00:00
func ( c * Core ) HandleRequest ( httpCtx context . Context , req * logical . Request ) ( resp * logical . Response , err error ) {
2019-04-08 18:57:14 +00:00
return c . switchedLockHandleRequest ( httpCtx , req , true )
}
func ( c * Core ) switchedLockHandleRequest ( httpCtx context . Context , req * logical . Request , doLocking bool ) ( resp * logical . Response , err error ) {
if doLocking {
c . stateLock . RLock ( )
2019-06-19 13:40:57 +00:00
defer c . stateLock . RUnlock ( )
2019-04-08 18:57:14 +00:00
}
2018-07-24 20:57:25 +00:00
if c . Sealed ( ) {
2017-02-16 20:15:02 +00:00
return nil , consts . ErrSealed
2016-05-02 04:08:07 +00:00
}
2018-09-18 03:03:00 +00:00
if c . standby && ! c . perfStandby {
2017-02-16 20:15:02 +00:00
return nil , consts . ErrStandby
2016-05-02 04:08:07 +00:00
}
2019-06-28 00:35:01 +00:00
if c . activeContext == nil || c . activeContext . Err ( ) != nil {
return nil , errors . New ( "active context canceled after getting state lock" )
}
2018-01-19 06:44:44 +00:00
ctx , cancel := context . WithCancel ( c . activeContext )
2018-08-28 01:21:54 +00:00
go func ( ctx context . Context , httpCtx context . Context ) {
2018-07-24 21:50:49 +00:00
select {
case <- ctx . Done ( ) :
case <- httpCtx . Done ( ) :
cancel ( )
}
2018-08-28 01:21:54 +00:00
} ( ctx , httpCtx )
2018-07-24 21:50:49 +00:00
2018-12-03 19:35:20 +00:00
ns , err := namespace . FromContext ( httpCtx )
if err != nil {
cancel ( )
return nil , errwrap . Wrapf ( "could not parse namespace from http context: {{err}}" , err )
}
ctx = namespace . ContextWithNamespace ( ctx , ns )
resp , err = c . handleCancelableRequest ( ctx , ns , req )
req . SetTokenEntry ( nil )
cancel ( )
return resp , err
}
func ( c * Core ) handleCancelableRequest ( ctx context . Context , ns * namespace . Namespace , req * logical . Request ) ( resp * logical . Response , err error ) {
2016-05-02 04:08:07 +00:00
// Allowing writing to a path ending in / makes it extremely difficult to
2017-09-15 13:02:29 +00:00
// understand user intent for the filesystem-like backends (kv,
2016-05-02 04:08:07 +00:00
// cubbyhole) -- did they want a key named foo/ or did they want to write
// to a directory foo/ with no (or forgotten) key, or...? It also affects
// lookup, because paths ending in / are considered prefixes by some
// backends. Basically, it's all just terrible, so don't allow it.
if strings . HasSuffix ( req . Path , "/" ) &&
( req . Operation == logical . UpdateOperation ||
req . Operation == logical . CreateOperation ) {
return logical . ErrorResponse ( "cannot write to a path ending in '/'" ) , nil
}
2018-09-18 03:03:00 +00:00
err = waitForReplicationState ( ctx , c , req )
if err != nil {
return nil , err
}
if ! hasNamespaces ( c ) && ns . Path != "" {
return nil , logical . CodedError ( 403 , "namespaces feature not enabled" )
}
2016-05-02 04:08:07 +00:00
var auth * logical . Auth
2018-09-18 03:03:00 +00:00
if c . router . LoginPath ( ctx , req . Path ) {
2018-01-08 18:31:38 +00:00
resp , auth , err = c . handleLoginRequest ( ctx , req )
2016-05-02 04:08:07 +00:00
} else {
2018-01-08 18:31:38 +00:00
resp , auth , err = c . handleRequest ( ctx , req )
2016-05-02 04:08:07 +00:00
}
// Ensure we don't leak internal data
if resp != nil {
if resp . Secret != nil {
resp . Secret . InternalData = nil
}
if resp . Auth != nil {
resp . Auth . InternalData = nil
}
}
// We are wrapping if there is anything to wrap (not a nil response) and a
2016-09-29 04:01:28 +00:00
// TTL was specified for the token. Errors on a call should be returned to
// the caller, so wrapping is turned off if an error is hit and the error
// is logged to the audit log.
wrapping := resp != nil &&
err == nil &&
! resp . IsError ( ) &&
resp . WrapInfo != nil &&
2017-11-13 20:31:32 +00:00
resp . WrapInfo . TTL != 0 &&
resp . WrapInfo . Token == ""
2016-05-02 04:08:07 +00:00
2016-05-16 20:11:33 +00:00
if wrapping {
2018-01-08 18:31:38 +00:00
cubbyResp , cubbyErr := c . wrapInCubbyhole ( ctx , req , resp , auth )
2016-05-16 20:11:33 +00:00
// If not successful, returns either an error response from the
2016-09-29 04:01:28 +00:00
// cubbyhole backend or an error; if either is set, set resp and err to
// those and continue so that that's what we audit log. Otherwise
// finish the wrapping and audit log that.
if cubbyResp != nil || cubbyErr != nil {
resp = cubbyResp
err = cubbyErr
} else {
wrappingResp := & logical . Response {
WrapInfo : resp . WrapInfo ,
2017-06-05 14:52:43 +00:00
Warnings : resp . Warnings ,
2016-09-29 04:01:28 +00:00
}
resp = wrappingResp
2016-05-02 04:08:07 +00:00
}
}
2016-09-29 19:03:47 +00:00
auditResp := resp
// When unwrapping we want to log the actual response that will be written
// out. We still want to return the raw value to avoid automatic updating
// to any of it.
if req . Path == "sys/wrapping/unwrap" &&
resp != nil &&
resp . Data != nil &&
resp . Data [ logical . HTTPRawBody ] != nil {
// Decode the JSON
Fix response wrapping from K/V version 2 (#4511)
This takes place in two parts, since working on this exposed an issue
with response wrapping when there is a raw body set. The changes are (in
diff order):
* A CurrentWrappingLookupFunc has been added to return the current
value. This is necessary for the lookahead call since we don't want the
lookahead call to be wrapped.
* Support for unwrapping < 0.6.2 tokens via the API/CLI has been
removed, because we now have backends returning 404s with data and can't
rely on the 404 trick. These can still be read manually via
cubbyhole/response.
* KV preflight version request now ensures that its calls is not
wrapped, and restores any given function after.
* When responding with a raw body, instead of always base64-decoding a
string value and erroring on failure, on failure we assume that it
simply wasn't a base64-encoded value and use it as is.
* A test that fails on master and works now that ensures that raw body
responses that are wrapped and then unwrapped return the expected
values.
* A flag for response data that indicates to the wrapping handling that
the data contained therein is already JSON decoded (more later).
* RespondWithStatusCode now defaults to a string so that the value is
HMAC'd during audit. The function always JSON encodes the body, so
before now it was always returning []byte which would skip HMACing. We
don't know what's in the data, so this is a "better safe than sorry"
issue. If different behavior is needed, backends can always manually
populate the data instead of relying on the helper function.
* We now check unwrapped data after unwrapping to see if there were raw
flags. If so, we try to detect whether the value can be unbase64'd. The
reason is that if it can it was probably originally a []byte and
shouldn't be audit HMAC'd; if not, it was probably originally a string
and should be. In either case, we then set the value as the raw body and
hit the flag indicating that it's already been JSON decoded so not to
try again before auditing. Doing it this way ensures the right typing.
* There is now a check to see if the data coming from unwrapping is
already JSON decoded and if so the decoding is skipped before setting
the audit response.
2018-05-10 19:40:03 +00:00
if resp . Data [ logical . HTTPRawBodyAlreadyJSONDecoded ] != nil {
delete ( resp . Data , logical . HTTPRawBodyAlreadyJSONDecoded )
} else {
httpResp := & logical . HTTPResponse { }
err := jsonutil . DecodeJSON ( resp . Data [ logical . HTTPRawBody ] . ( [ ] byte ) , httpResp )
if err != nil {
c . logger . Error ( "failed to unmarshal wrapped HTTP response for audit logging" , "error" , err )
return nil , ErrInternalError
}
2016-09-29 19:03:47 +00:00
Fix response wrapping from K/V version 2 (#4511)
This takes place in two parts, since working on this exposed an issue
with response wrapping when there is a raw body set. The changes are (in
diff order):
* A CurrentWrappingLookupFunc has been added to return the current
value. This is necessary for the lookahead call since we don't want the
lookahead call to be wrapped.
* Support for unwrapping < 0.6.2 tokens via the API/CLI has been
removed, because we now have backends returning 404s with data and can't
rely on the 404 trick. These can still be read manually via
cubbyhole/response.
* KV preflight version request now ensures that its calls is not
wrapped, and restores any given function after.
* When responding with a raw body, instead of always base64-decoding a
string value and erroring on failure, on failure we assume that it
simply wasn't a base64-encoded value and use it as is.
* A test that fails on master and works now that ensures that raw body
responses that are wrapped and then unwrapped return the expected
values.
* A flag for response data that indicates to the wrapping handling that
the data contained therein is already JSON decoded (more later).
* RespondWithStatusCode now defaults to a string so that the value is
HMAC'd during audit. The function always JSON encodes the body, so
before now it was always returning []byte which would skip HMACing. We
don't know what's in the data, so this is a "better safe than sorry"
issue. If different behavior is needed, backends can always manually
populate the data instead of relying on the helper function.
* We now check unwrapped data after unwrapping to see if there were raw
flags. If so, we try to detect whether the value can be unbase64'd. The
reason is that if it can it was probably originally a []byte and
shouldn't be audit HMAC'd; if not, it was probably originally a string
and should be. In either case, we then set the value as the raw body and
hit the flag indicating that it's already been JSON decoded so not to
try again before auditing. Doing it this way ensures the right typing.
* There is now a check to see if the data coming from unwrapping is
already JSON decoded and if so the decoding is skipped before setting
the audit response.
2018-05-10 19:40:03 +00:00
auditResp = logical . HTTPResponseToLogicalResponse ( httpResp )
}
2016-09-29 19:03:47 +00:00
}
2018-03-02 17:18:39 +00:00
var nonHMACReqDataKeys [ ] string
var nonHMACRespDataKeys [ ] string
2018-09-18 03:03:00 +00:00
entry := c . router . MatchingMountEntry ( ctx , req . Path )
2018-03-02 17:18:39 +00:00
if entry != nil {
// Get and set ignored HMAC'd value. Reset those back to empty afterwards.
if rawVals , ok := entry . synthesizedConfigCache . Load ( "audit_non_hmac_request_keys" ) ; ok {
nonHMACReqDataKeys = rawVals . ( [ ] string )
}
// Get and set ignored HMAC'd value. Reset those back to empty afterwards.
if auditResp != nil {
if rawVals , ok := entry . synthesizedConfigCache . Load ( "audit_non_hmac_response_keys" ) ; ok {
nonHMACRespDataKeys = rawVals . ( [ ] string )
}
}
}
2016-05-02 04:08:07 +00:00
// Create an audit trail of the response
2018-09-18 03:03:00 +00:00
if ! isControlGroupRun ( req ) {
2020-05-21 13:20:05 +00:00
switch req . Path {
case "sys/replication/dr/status" , "sys/replication/performance/status" , "sys/replication/status" :
default :
logInput := & logical . LogInput {
Auth : auth ,
Request : req ,
Response : auditResp ,
OuterErr : err ,
NonHMACReqDataKeys : nonHMACReqDataKeys ,
NonHMACRespDataKeys : nonHMACRespDataKeys ,
}
if auditErr := c . auditBroker . LogResponse ( ctx , logInput , c . auditedHeaders ) ; auditErr != nil {
c . logger . Error ( "failed to audit response" , "request_path" , req . Path , "error" , auditErr )
return nil , ErrInternalError
}
2018-09-18 03:03:00 +00:00
}
2016-05-02 04:08:07 +00:00
}
return
}
2018-09-18 03:03:00 +00:00
func isControlGroupRun ( req * logical . Request ) bool {
return req . ControlGroup != nil
}
2019-03-05 19:55:07 +00:00
func ( c * Core ) doRouting ( ctx context . Context , req * logical . Request ) ( * logical . Response , error ) {
// If we're replicating and we get a read-only error from a backend, need to forward to primary
resp , err := c . router . Route ( ctx , req )
2019-07-05 22:12:34 +00:00
if shouldForward ( c , resp , err ) {
return forward ( ctx , c , req )
2019-03-05 19:55:07 +00:00
}
atomic . AddUint64 ( c . counters . requests , 1 )
return resp , err
}
2018-01-08 18:31:38 +00:00
func ( c * Core ) handleRequest ( ctx context . Context , req * logical . Request ) ( retResp * logical . Response , retAuth * logical . Auth , retErr error ) {
2016-05-02 04:08:07 +00:00
defer metrics . MeasureSince ( [ ] string { "core" , "handle_request" } , time . Now ( ) )
2018-03-02 17:18:39 +00:00
var nonHMACReqDataKeys [ ] string
2018-09-18 03:03:00 +00:00
entry := c . router . MatchingMountEntry ( ctx , req . Path )
2018-03-02 17:18:39 +00:00
if entry != nil {
2020-07-06 16:17:41 +00:00
// Set here so the audit log has it even if authorization fails
2020-07-14 19:28:11 +00:00
req . MountType = entry . Type
2018-03-02 17:18:39 +00:00
// Get and set ignored HMAC'd value.
if rawVals , ok := entry . synthesizedConfigCache . Load ( "audit_non_hmac_request_keys" ) ; ok {
nonHMACReqDataKeys = rawVals . ( [ ] string )
}
}
2018-09-18 03:03:00 +00:00
ns , err := namespace . FromContext ( ctx )
if err != nil {
c . logger . Error ( "failed to get namespace from context" , "error" , err )
retErr = multierror . Append ( retErr , ErrInternalError )
return
}
2016-05-02 04:08:07 +00:00
// Validate the token
2018-01-08 18:31:38 +00:00
auth , te , ctErr := c . checkToken ( ctx , req , false )
2019-01-25 19:08:42 +00:00
if ctErr == logical . ErrPerfStandbyPleaseForward {
return nil , nil , ctErr
}
// We run this logic first because we want to decrement the use count even
// in the case of an error (assuming we can successfully look up; if we
// need to forward, we exit before now)
2018-09-18 03:03:00 +00:00
if te != nil && ! isControlGroupRun ( req ) {
2016-05-02 07:11:14 +00:00
// Attempt to use the token (decrement NumUses)
var err error
2018-01-19 06:44:44 +00:00
te , err = c . tokenStore . UseToken ( ctx , te )
2016-05-02 07:11:14 +00:00
if err != nil {
2018-04-03 00:46:59 +00:00
c . logger . Error ( "failed to use token" , "error" , err )
2016-05-16 20:11:33 +00:00
retErr = multierror . Append ( retErr , ErrInternalError )
return nil , nil , retErr
2016-05-02 07:11:14 +00:00
}
if te == nil {
// Token has been revoked by this point
2016-05-16 20:11:33 +00:00
retErr = multierror . Append ( retErr , logical . ErrPermissionDenied )
return nil , nil , retErr
2016-05-02 07:11:14 +00:00
}
2018-05-10 19:50:02 +00:00
if te . NumUses == tokenRevocationPending {
2016-05-02 07:11:14 +00:00
// We defer a revocation until after logic has run, since this is a
// valid request (this is the token's final use). We pass the ID in
// directly just to be safe in case something else modifies te later.
defer func ( id string ) {
2018-09-18 03:03:00 +00:00
nsActiveCtx := namespace . ContextWithNamespace ( c . activeContext , ns )
leaseID , err := c . expiration . CreateOrFetchRevocationLeaseByToken ( nsActiveCtx , te )
2018-05-10 19:50:02 +00:00
if err == nil {
2018-08-02 01:39:39 +00:00
err = c . expiration . LazyRevoke ( ctx , leaseID )
2018-05-10 19:50:02 +00:00
}
2016-05-02 07:11:14 +00:00
if err != nil {
2018-04-03 00:46:59 +00:00
c . logger . Error ( "failed to revoke token" , "error" , err )
2016-05-02 07:11:14 +00:00
retResp = nil
retAuth = nil
2016-05-16 20:11:33 +00:00
retErr = multierror . Append ( retErr , ErrInternalError )
2016-05-02 07:11:14 +00:00
}
if retResp != nil && retResp . Secret != nil &&
// Some backends return a TTL even without a Lease ID
retResp . Secret . LeaseID != "" {
retResp = logical . ErrorResponse ( "Secret cannot be returned; token had one use left, so leased credentials were immediately revoked." )
return
}
} ( te . ID )
}
2016-05-02 04:08:07 +00:00
}
2018-09-18 03:03:00 +00:00
2016-05-02 07:11:14 +00:00
if ctErr != nil {
2018-09-18 03:03:00 +00:00
newCtErr , cgResp , cgAuth , cgRetErr := checkNeedsCG ( ctx , c , req , auth , ctErr , nonHMACReqDataKeys )
switch {
case newCtErr != nil :
2019-01-10 01:39:58 +00:00
ctErr = newCtErr
2018-09-18 03:03:00 +00:00
case cgResp != nil || cgAuth != nil :
if cgRetErr != nil {
retErr = multierror . Append ( retErr , cgRetErr )
}
return cgResp , cgAuth , retErr
}
2016-05-02 04:08:07 +00:00
// If it is an internal error we return that, otherwise we
// return invalid request so that the status codes can be correct
2018-08-10 13:59:58 +00:00
switch {
case ctErr == ErrInternalError ,
errwrap . Contains ( ctErr , ErrInternalError . Error ( ) ) ,
ctErr == logical . ErrPermissionDenied ,
errwrap . Contains ( ctErr , logical . ErrPermissionDenied . Error ( ) ) :
switch ctErr . ( type ) {
case * multierror . Error :
retErr = ctErr
default :
retErr = multierror . Append ( retErr , ctErr )
}
default :
retErr = multierror . Append ( retErr , logical . ErrInvalidRequest )
2016-05-02 04:08:07 +00:00
}
2018-09-18 03:03:00 +00:00
if ! isControlGroupRun ( req ) {
2019-05-22 22:52:53 +00:00
logInput := & logical . LogInput {
2018-09-18 03:03:00 +00:00
Auth : auth ,
Request : req ,
OuterErr : ctErr ,
NonHMACReqDataKeys : nonHMACReqDataKeys ,
}
if err := c . auditBroker . LogRequest ( ctx , logInput , c . auditedHeaders ) ; err != nil {
c . logger . Error ( "failed to audit request" , "path" , req . Path , "error" , err )
}
2016-05-02 04:08:07 +00:00
}
2018-08-10 13:59:58 +00:00
if errwrap . Contains ( retErr , ErrInternalError . Error ( ) ) {
2017-08-15 20:44:16 +00:00
return nil , auth , retErr
}
2017-06-05 22:04:31 +00:00
return logical . ErrorResponse ( ctErr . Error ( ) ) , auth , retErr
2016-05-02 04:08:07 +00:00
}
// Attach the display name
req . DisplayName = auth . DisplayName
// Create an audit trail of the request
2018-09-18 03:03:00 +00:00
if ! isControlGroupRun ( req ) {
2019-05-22 22:52:53 +00:00
logInput := & logical . LogInput {
2018-09-18 03:03:00 +00:00
Auth : auth ,
Request : req ,
NonHMACReqDataKeys : nonHMACReqDataKeys ,
}
if err := c . auditBroker . LogRequest ( ctx , logInput , c . auditedHeaders ) ; err != nil {
c . logger . Error ( "failed to audit request" , "path" , req . Path , "error" , err )
retErr = multierror . Append ( retErr , ErrInternalError )
return nil , auth , retErr
}
2016-05-02 04:08:07 +00:00
}
2020-06-26 21:13:16 +00:00
leaseGenerated := false
quotaResp , quotaErr := c . applyLeaseCountQuota ( & quotas . Request {
Path : req . Path ,
MountPath : strings . TrimPrefix ( req . MountPoint , ns . Path ) ,
NamespacePath : ns . Path ,
} )
if quotaErr != nil {
c . logger . Error ( "failed to apply quota" , "path" , req . Path , "error" , err )
retErr = multierror . Append ( retErr , quotaErr )
return nil , auth , retErr
}
if ! quotaResp . Allowed {
if c . logger . IsTrace ( ) {
c . logger . Trace ( "request rejected due to lease count quota violation" , "request_path" , req . Path )
}
retErr = multierror . Append ( retErr , errwrap . Wrapf ( fmt . Sprintf ( "request path %q: {{err}}" , req . Path ) , quotas . ErrLeaseCountQuotaExceeded ) )
return nil , auth , retErr
}
defer func ( ) {
if quotaResp . Access != nil {
quotaAckErr := c . ackLeaseQuota ( quotaResp . Access , leaseGenerated )
if quotaAckErr != nil {
retErr = multierror . Append ( retErr , quotaAckErr )
}
}
} ( )
2016-05-02 04:08:07 +00:00
// Route the request
2019-03-05 19:55:07 +00:00
resp , routeErr := c . doRouting ( ctx , req )
2016-05-16 20:11:33 +00:00
if resp != nil {
2019-03-05 19:55:07 +00:00
2016-11-11 20:12:11 +00:00
// If wrapping is used, use the shortest between the request and response
var wrapTTL time . Duration
2017-08-02 22:28:58 +00:00
var wrapFormat , creationPath string
2017-11-09 17:47:42 +00:00
var sealWrap bool
2016-05-16 20:11:33 +00:00
2016-11-11 20:12:11 +00:00
// Ensure no wrap info information is set other than, possibly, the TTL
if resp . WrapInfo != nil {
if resp . WrapInfo . TTL > 0 {
wrapTTL = resp . WrapInfo . TTL
}
2017-01-04 21:44:03 +00:00
wrapFormat = resp . WrapInfo . Format
2017-08-02 22:28:58 +00:00
creationPath = resp . WrapInfo . CreationPath
2017-11-09 17:47:42 +00:00
sealWrap = resp . WrapInfo . SealWrap
2016-11-11 20:12:11 +00:00
resp . WrapInfo = nil
}
2017-01-04 21:44:03 +00:00
if req . WrapInfo != nil {
if req . WrapInfo . TTL > 0 {
switch {
case wrapTTL == 0 :
wrapTTL = req . WrapInfo . TTL
case req . WrapInfo . TTL < wrapTTL :
wrapTTL = req . WrapInfo . TTL
}
}
// If the wrap format hasn't been set by the response, set it to
// the request format
if req . WrapInfo . Format != "" && wrapFormat == "" {
wrapFormat = req . WrapInfo . Format
2016-11-11 20:12:11 +00:00
}
}
if wrapTTL > 0 {
2017-04-24 19:15:01 +00:00
resp . WrapInfo = & wrapping . ResponseWrapInfo {
2017-08-02 22:28:58 +00:00
TTL : wrapTTL ,
Format : wrapFormat ,
CreationPath : creationPath ,
2017-11-09 17:47:42 +00:00
SealWrap : sealWrap ,
2016-05-16 20:11:33 +00:00
}
}
}
2016-05-02 04:08:07 +00:00
// If there is a secret, we must register it with the expiration manager.
// We exclude renewal of a lease, since it does not need to be re-registered
2017-06-20 16:34:00 +00:00
if resp != nil && resp . Secret != nil && ! strings . HasPrefix ( req . Path , "sys/renew" ) &&
! strings . HasPrefix ( req . Path , "sys/leases/renew" ) {
2017-09-15 13:02:29 +00:00
// KV mounts should return the TTL but not register
2016-05-02 04:08:07 +00:00
// for a lease as this provides a massive slowdown
registerLease := true
2018-03-21 19:04:27 +00:00
2018-09-18 03:03:00 +00:00
matchingMountEntry := c . router . MatchingMountEntry ( ctx , req . Path )
2018-03-21 19:04:27 +00:00
if matchingMountEntry == nil {
2018-04-03 00:46:59 +00:00
c . logger . Error ( "unable to retrieve kv mount entry from router" )
2016-05-16 20:11:33 +00:00
retErr = multierror . Append ( retErr , ErrInternalError )
return nil , auth , retErr
2016-05-02 04:08:07 +00:00
}
2018-03-21 19:04:27 +00:00
switch matchingMountEntry . Type {
case "kv" , "generic" :
// If we are kv type, first see if we are an older passthrough
// backend, and otherwise check the mount entry options.
2018-09-18 03:03:00 +00:00
matchingBackend := c . router . MatchingBackend ( ctx , req . Path )
2018-03-21 19:04:27 +00:00
if matchingBackend == nil {
2018-04-03 00:46:59 +00:00
c . logger . Error ( "unable to retrieve kv backend from router" )
2018-03-21 19:04:27 +00:00
retErr = multierror . Append ( retErr , ErrInternalError )
return nil , auth , retErr
}
if ptbe , ok := matchingBackend . ( * PassthroughBackend ) ; ok {
if ! ptbe . GeneratesLeases ( ) {
registerLease = false
resp . Secret . Renewable = false
}
} else if matchingMountEntry . Options == nil || matchingMountEntry . Options [ "leased_passthrough" ] != "true" {
registerLease = false
resp . Secret . Renewable = false
}
case "plugin" :
// If we are a plugin type and the plugin name is "kv" check the
// mount entry options.
2018-11-19 23:23:48 +00:00
if matchingMountEntry . Config . PluginName == "kv" && ( matchingMountEntry . Options == nil || matchingMountEntry . Options [ "leased_passthrough" ] != "true" ) {
2016-05-02 04:08:07 +00:00
registerLease = false
resp . Secret . Renewable = false
}
}
if registerLease {
2018-09-18 03:03:00 +00:00
sysView := c . router . MatchingSystemView ( ctx , req . Path )
2018-04-03 16:20:20 +00:00
if sysView == nil {
2018-04-10 01:14:23 +00:00
c . logger . Error ( "unable to look up sys view for login path" , "request_path" , req . Path )
2018-04-03 16:20:20 +00:00
return nil , nil , ErrInternalError
}
ttl , warnings , err := framework . CalculateTTL ( sysView , 0 , resp . Secret . TTL , 0 , resp . Secret . MaxTTL , 0 , time . Time { } )
if err != nil {
return nil , nil , err
}
for _ , warning := range warnings {
resp . AddWarning ( warning )
}
resp . Secret . TTL = ttl
2018-09-18 03:03:00 +00:00
registerFunc , funcGetErr := getLeaseRegisterFunc ( c )
if funcGetErr != nil {
retErr = multierror . Append ( retErr , funcGetErr )
return nil , auth , retErr
}
leaseID , err := registerFunc ( ctx , req , resp )
2016-05-02 04:08:07 +00:00
if err != nil {
2018-04-03 00:46:59 +00:00
c . logger . Error ( "failed to register lease" , "request_path" , req . Path , "error" , err )
2016-05-16 20:11:33 +00:00
retErr = multierror . Append ( retErr , ErrInternalError )
return nil , auth , retErr
2016-05-02 04:08:07 +00:00
}
2020-06-26 21:13:16 +00:00
leaseGenerated = true
2016-05-02 04:08:07 +00:00
resp . Secret . LeaseID = leaseID
2018-10-15 16:56:24 +00:00
2020-06-18 20:36:21 +00:00
// Count the lease creation
ttl_label := metricsutil . TTLBucket ( resp . Secret . TTL )
2020-07-14 19:28:11 +00:00
mountPointWithoutNs := ns . TrimmedPath ( req . MountPoint )
2020-06-18 20:36:21 +00:00
c . MetricSink ( ) . IncrCounterWithLabels (
[ ] string { "secret" , "lease" , "creation" } ,
1 ,
[ ] metrics . Label {
2020-10-12 18:56:24 +00:00
vaultmetrics . NamespaceLabel ( ns ) ,
2020-06-18 20:36:21 +00:00
{ "secret_engine" , req . MountType } ,
2020-07-14 19:28:11 +00:00
{ "mount_point" , mountPointWithoutNs } ,
2020-06-18 20:36:21 +00:00
{ "creation_ttl" , ttl_label } ,
} ,
)
2016-05-02 04:08:07 +00:00
}
}
// Only the token store is allowed to return an auth block, for any
2020-03-31 20:36:45 +00:00
// other request this is an internal error.
if resp != nil && resp . Auth != nil {
2016-05-02 04:08:07 +00:00
if ! strings . HasPrefix ( req . Path , "auth/token/" ) {
2018-04-03 00:46:59 +00:00
c . logger . Error ( "unexpected Auth response for non-token backend" , "request_path" , req . Path )
2016-05-16 20:11:33 +00:00
retErr = multierror . Append ( retErr , ErrInternalError )
return nil , auth , retErr
2016-05-02 04:08:07 +00:00
}
2018-09-18 03:03:00 +00:00
// Fetch the namespace to which the token belongs
tokenNS , err := NamespaceByID ( ctx , te . NamespaceID , c )
if err != nil {
c . logger . Error ( "failed to fetch token's namespace" , "error" , err )
retErr = multierror . Append ( retErr , err )
return nil , auth , retErr
}
if tokenNS == nil {
c . logger . Error ( namespace . ErrNoNamespace . Error ( ) )
retErr = multierror . Append ( retErr , namespace . ErrNoNamespace )
return nil , auth , retErr
}
_ , identityPolicies , err := c . fetchEntityAndDerivedPolicies ( ctx , tokenNS , resp . Auth . EntityID )
2018-06-14 13:49:33 +00:00
if err != nil {
2019-11-08 21:14:03 +00:00
// Best-effort clean up on error, so we log the cleanup error as a
// warning but still return as internal error.
if err := c . tokenStore . revokeOrphan ( ctx , resp . Auth . ClientToken ) ; err != nil {
c . logger . Warn ( "failed to clean up token lease from entity and policy lookup failure" , "request_path" , req . Path , "error" , err )
}
2018-06-14 13:49:33 +00:00
return nil , nil , ErrInternalError
}
2020-03-31 20:36:45 +00:00
// We skip expiration manager registration for token renewal since it
// does not need to be re-registered
if strings . HasPrefix ( req . Path , "auth/token/renew" ) {
// We build the "policies" list to be returned by starting with
// token policies, and add identity policies right after this
// conditional
resp . Auth . Policies = policyutil . SanitizePolicies ( resp . Auth . TokenPolicies , policyutil . DoNotAddDefaultPolicy )
} else {
resp . Auth . TokenPolicies = policyutil . SanitizePolicies ( resp . Auth . Policies , policyutil . DoNotAddDefaultPolicy )
switch resp . Auth . TokenType {
case logical . TokenTypeBatch :
case logical . TokenTypeService :
if err := c . expiration . RegisterAuth ( ctx , & logical . TokenEntry {
TTL : auth . TTL ,
Policies : auth . TokenPolicies ,
Path : resp . Auth . CreationPath ,
NamespaceID : ns . ID ,
} , resp . Auth ) ; err != nil {
// Best-effort clean up on error, so we log the cleanup error as
// a warning but still return as internal error.
if err := c . tokenStore . revokeOrphan ( ctx , resp . Auth . ClientToken ) ; err != nil {
c . logger . Warn ( "failed to clean up token lease during auth/token/ request" , "request_path" , req . Path , "error" , err )
}
c . logger . Error ( "failed to register token lease during auth/token/ request" , "request_path" , req . Path , "error" , err )
retErr = multierror . Append ( retErr , ErrInternalError )
return nil , auth , retErr
2019-11-08 21:14:03 +00:00
}
2020-06-26 21:13:16 +00:00
leaseGenerated = true
2018-10-15 16:56:24 +00:00
}
2016-05-02 04:08:07 +00:00
}
2018-07-24 19:03:11 +00:00
// We do these later since it's not meaningful for backends/expmgr to
// have what is purely a snapshot of current identity policies, and
// plugins can be confused if they are checking contents of
// Auth.Policies instead of Auth.TokenPolicies
2018-09-18 03:03:00 +00:00
resp . Auth . Policies = policyutil . SanitizePolicies ( append ( resp . Auth . Policies , identityPolicies [ te . NamespaceID ] ... ) , policyutil . DoNotAddDefaultPolicy )
resp . Auth . IdentityPolicies = policyutil . SanitizePolicies ( identityPolicies [ te . NamespaceID ] , policyutil . DoNotAddDefaultPolicy )
delete ( identityPolicies , te . NamespaceID )
resp . Auth . ExternalNamespacePolicies = identityPolicies
2016-05-02 04:08:07 +00:00
}
2016-09-29 04:01:28 +00:00
if resp != nil &&
req . Path == "cubbyhole/response" &&
len ( te . Policies ) == 1 &&
te . Policies [ 0 ] == responseWrappingPolicyName {
2016-09-29 21:44:15 +00:00
resp . AddWarning ( "Reading from 'cubbyhole/response' is deprecated. Please use sys/wrapping/unwrap to unwrap responses, as it provides additional security checks and other benefits." )
2016-09-29 04:01:28 +00:00
}
2016-05-02 04:08:07 +00:00
// Return the response and error
2017-02-17 04:09:39 +00:00
if routeErr != nil {
retErr = multierror . Append ( retErr , routeErr )
2016-05-16 20:11:33 +00:00
}
2017-11-02 20:05:48 +00:00
2016-05-16 20:11:33 +00:00
return resp , auth , retErr
2016-05-02 04:08:07 +00:00
}
// handleLoginRequest is used to handle a login request, which is an
// unauthenticated request to the backend.
2018-01-08 18:31:38 +00:00
func ( c * Core ) handleLoginRequest ( ctx context . Context , req * logical . Request ) ( retResp * logical . Response , retAuth * logical . Auth , retErr error ) {
2016-05-02 04:08:07 +00:00
defer metrics . MeasureSince ( [ ] string { "core" , "handle_login_request" } , time . Now ( ) )
2017-10-23 18:59:37 +00:00
req . Unauthenticated = true
2017-10-23 20:49:46 +00:00
2019-04-29 20:14:26 +00:00
var nonHMACReqDataKeys [ ] string
entry := c . router . MatchingMountEntry ( ctx , req . Path )
if entry != nil {
2020-07-06 16:17:41 +00:00
// Set here so the audit log has it even if authorization fails
2020-07-14 19:28:11 +00:00
req . MountType = entry . Type
2019-04-29 20:14:26 +00:00
// Get and set ignored HMAC'd value.
if rawVals , ok := entry . synthesizedConfigCache . Load ( "audit_non_hmac_request_keys" ) ; ok {
nonHMACReqDataKeys = rawVals . ( [ ] string )
}
}
2018-09-18 03:03:00 +00:00
// Do an unauth check. This will cause EGP policies to be checked
2019-04-29 20:14:26 +00:00
var auth * logical . Auth
2018-09-18 03:03:00 +00:00
var ctErr error
auth , _ , ctErr = c . checkToken ( ctx , req , true )
2019-01-25 19:08:42 +00:00
if ctErr == logical . ErrPerfStandbyPleaseForward {
return nil , nil , ctErr
}
2018-09-18 03:03:00 +00:00
if ctErr != nil {
// If it is an internal error we return that, otherwise we
// return invalid request so that the status codes can be correct
var errType error
switch ctErr {
case ErrInternalError , logical . ErrPermissionDenied :
errType = ctErr
default :
errType = logical . ErrInvalidRequest
}
2019-05-22 22:52:53 +00:00
logInput := & logical . LogInput {
2018-09-18 03:03:00 +00:00
Auth : auth ,
Request : req ,
OuterErr : ctErr ,
NonHMACReqDataKeys : nonHMACReqDataKeys ,
}
if err := c . auditBroker . LogRequest ( ctx , logInput , c . auditedHeaders ) ; err != nil {
2018-10-09 16:43:17 +00:00
c . logger . Error ( "failed to audit request" , "path" , req . Path , "error" , err )
2018-09-18 03:03:00 +00:00
return nil , nil , ErrInternalError
}
if errType != nil {
retErr = multierror . Append ( retErr , errType )
}
if ctErr == ErrInternalError {
return nil , auth , retErr
}
return logical . ErrorResponse ( ctErr . Error ( ) ) , auth , retErr
}
2020-05-21 13:20:05 +00:00
switch req . Path {
case "sys/replication/dr/status" , "sys/replication/performance/status" , "sys/replication/status" :
default :
// Create an audit trail of the request. Attach auth if it was returned,
// e.g. if a token was provided.
logInput := & logical . LogInput {
Auth : auth ,
Request : req ,
NonHMACReqDataKeys : nonHMACReqDataKeys ,
}
if err := c . auditBroker . LogRequest ( ctx , logInput , c . auditedHeaders ) ; err != nil {
c . logger . Error ( "failed to audit request" , "path" , req . Path , "error" , err )
return nil , nil , ErrInternalError
}
2016-05-02 04:08:07 +00:00
}
2016-08-08 21:32:37 +00:00
// The token store uses authentication even when creating a new token,
// so it's handled in handleRequest. It should not be reached here.
if strings . HasPrefix ( req . Path , "auth/token/" ) {
2018-04-03 00:46:59 +00:00
c . logger . Error ( "unexpected login request for token backend" , "request_path" , req . Path )
2016-08-08 21:56:14 +00:00
return nil , nil , ErrInternalError
2016-08-08 21:32:37 +00:00
}
2016-05-02 04:08:07 +00:00
// Route the request
2019-03-05 19:55:07 +00:00
resp , routeErr := c . doRouting ( ctx , req )
2016-07-05 15:46:21 +00:00
if resp != nil {
2016-11-11 20:12:11 +00:00
// If wrapping is used, use the shortest between the request and response
var wrapTTL time . Duration
2017-08-02 22:28:58 +00:00
var wrapFormat , creationPath string
2017-11-09 17:47:42 +00:00
var sealWrap bool
2016-07-05 15:46:21 +00:00
2016-11-11 20:12:11 +00:00
// Ensure no wrap info information is set other than, possibly, the TTL
if resp . WrapInfo != nil {
if resp . WrapInfo . TTL > 0 {
wrapTTL = resp . WrapInfo . TTL
}
2017-01-04 21:44:03 +00:00
wrapFormat = resp . WrapInfo . Format
2017-08-02 22:28:58 +00:00
creationPath = resp . WrapInfo . CreationPath
2017-11-09 17:47:42 +00:00
sealWrap = resp . WrapInfo . SealWrap
2016-11-11 20:12:11 +00:00
resp . WrapInfo = nil
}
2017-01-04 21:44:03 +00:00
if req . WrapInfo != nil {
if req . WrapInfo . TTL > 0 {
switch {
case wrapTTL == 0 :
wrapTTL = req . WrapInfo . TTL
case req . WrapInfo . TTL < wrapTTL :
wrapTTL = req . WrapInfo . TTL
}
}
if req . WrapInfo . Format != "" && wrapFormat == "" {
wrapFormat = req . WrapInfo . Format
2016-11-11 20:12:11 +00:00
}
}
if wrapTTL > 0 {
2017-04-24 19:15:01 +00:00
resp . WrapInfo = & wrapping . ResponseWrapInfo {
2017-08-02 22:28:58 +00:00
TTL : wrapTTL ,
Format : wrapFormat ,
CreationPath : creationPath ,
2017-11-09 17:47:42 +00:00
SealWrap : sealWrap ,
2016-07-05 15:46:21 +00:00
}
}
}
2016-05-02 04:08:07 +00:00
// A login request should never return a secret!
if resp != nil && resp . Secret != nil {
2018-04-03 00:46:59 +00:00
c . logger . Error ( "unexpected Secret response for login path" , "request_path" , req . Path )
2016-05-02 04:08:07 +00:00
return nil , nil , ErrInternalError
}
// If the response generated an authentication, then generate the token
if resp != nil && resp . Auth != nil {
2020-06-26 21:13:16 +00:00
ns , err := namespace . FromContext ( ctx )
if err != nil {
c . logger . Error ( "failed to get namespace from context" , "error" , err )
retErr = multierror . Append ( retErr , ErrInternalError )
return
}
leaseGenerated := false
// The request successfully authenticated itself. Run the quota checks
// before creating lease.
quotaResp , quotaErr := c . applyLeaseCountQuota ( & quotas . Request {
Path : req . Path ,
MountPath : strings . TrimPrefix ( req . MountPoint , ns . Path ) ,
NamespacePath : ns . Path ,
} )
if quotaErr != nil {
c . logger . Error ( "failed to apply quota" , "path" , req . Path , "error" , err )
retErr = multierror . Append ( retErr , quotaErr )
return
}
if ! quotaResp . Allowed {
if c . logger . IsTrace ( ) {
c . logger . Trace ( "request rejected due to lease count quota violation" , "request_path" , req . Path )
}
retErr = multierror . Append ( retErr , errwrap . Wrapf ( fmt . Sprintf ( "request path %q: {{err}}" , req . Path ) , quotas . ErrLeaseCountQuotaExceeded ) )
return
}
defer func ( ) {
if quotaResp . Access != nil {
quotaAckErr := c . ackLeaseQuota ( quotaResp . Access , leaseGenerated )
if quotaAckErr != nil {
retErr = multierror . Append ( retErr , quotaAckErr )
}
}
} ( )
2018-05-09 22:39:55 +00:00
2017-10-11 17:21:20 +00:00
var entity * identity . Entity
2016-05-02 04:08:07 +00:00
auth = resp . Auth
2018-09-18 03:03:00 +00:00
mEntry := c . router . MatchingMountEntry ( ctx , req . Path )
2018-04-23 17:46:14 +00:00
2018-04-25 03:10:22 +00:00
if auth . Alias != nil &&
mEntry != nil &&
! mEntry . Local &&
c . identityStore != nil {
2017-10-11 17:21:20 +00:00
// Overwrite the mount type and mount path in the alias
// information
auth . Alias . MountType = req . MountType
auth . Alias . MountAccessor = req . MountAccessor
if auth . Alias . Name == "" {
return nil , nil , fmt . Errorf ( "missing name in alias" )
}
var err error
2018-02-09 15:40:56 +00:00
// Fetch the entity for the alias, or create an entity if one
// doesn't exist.
2018-09-18 03:03:00 +00:00
entity , err = c . identityStore . CreateOrFetchEntity ( ctx , auth . Alias )
if err != nil {
entity , err = possiblyForwardAliasCreation ( ctx , c , err , auth , entity )
}
2017-10-11 17:21:20 +00:00
if err != nil {
return nil , nil , err
}
if entity == nil {
2018-02-09 15:40:56 +00:00
return nil , nil , fmt . Errorf ( "failed to create an entity for the authenticated alias" )
2017-10-11 17:21:20 +00:00
}
2018-04-14 01:49:40 +00:00
if entity . Disabled {
2018-04-23 20:50:04 +00:00
return nil , nil , logical . ErrPermissionDenied
2018-04-14 01:49:40 +00:00
}
2017-10-11 17:21:20 +00:00
auth . EntityID = entity . ID
2020-03-23 22:00:26 +00:00
validAliases , err := c . identityStore . refreshExternalGroupMembershipsByEntityID ( ctx , auth . EntityID , auth . GroupAliases )
if err != nil {
return nil , nil , err
2017-11-02 20:05:48 +00:00
}
2020-03-23 22:00:26 +00:00
auth . GroupAliases = validAliases
2017-10-11 17:21:20 +00:00
}
2016-05-02 04:08:07 +00:00
// Determine the source of the login
2018-09-18 03:03:00 +00:00
source := c . router . MatchingMount ( ctx , req . Path )
2016-05-02 04:08:07 +00:00
source = strings . TrimPrefix ( source , credentialRoutePrefix )
source = strings . Replace ( source , "/" , "-" , - 1 )
// Prepend the source to the display name
auth . DisplayName = strings . TrimSuffix ( source + auth . DisplayName , "-" )
2018-09-18 03:03:00 +00:00
sysView := c . router . MatchingSystemView ( ctx , req . Path )
2016-05-02 04:08:07 +00:00
if sysView == nil {
2018-04-03 00:46:59 +00:00
c . logger . Error ( "unable to look up sys view for login path" , "request_path" , req . Path )
2016-05-02 04:08:07 +00:00
return nil , nil , ErrInternalError
}
2018-04-03 16:20:20 +00:00
tokenTTL , warnings , err := framework . CalculateTTL ( sysView , 0 , auth . TTL , auth . Period , auth . MaxTTL , auth . ExplicitMaxTTL , time . Time { } )
if err != nil {
return nil , nil , err
}
for _ , warning := range warnings {
resp . AddWarning ( warning )
2016-05-02 04:08:07 +00:00
}
2018-09-18 03:03:00 +00:00
_ , identityPolicies , err := c . fetchEntityAndDerivedPolicies ( ctx , ns , auth . EntityID )
2018-06-14 13:49:33 +00:00
if err != nil {
return nil , nil , ErrInternalError
}
2019-06-14 14:17:04 +00:00
auth . TokenPolicies = policyutil . SanitizePolicies ( auth . Policies , ! auth . NoDefaultPolicy )
2018-09-18 03:03:00 +00:00
allPolicies := policyutil . SanitizePolicies ( append ( auth . TokenPolicies , identityPolicies [ ns . ID ] ... ) , policyutil . DoNotAddDefaultPolicy )
2016-08-08 21:32:37 +00:00
2018-06-14 13:49:33 +00:00
// Prevent internal policies from being assigned to tokens. We check
// this on auth.Policies including derived ones from Identity before
// actually making the token.
2018-07-24 19:03:11 +00:00
for _ , policy := range allPolicies {
2018-06-14 13:49:33 +00:00
if policy == "root" {
return logical . ErrorResponse ( "auth methods cannot create root tokens" ) , nil , logical . ErrInvalidRequest
}
2016-09-29 04:01:28 +00:00
if strutil . StrListContains ( nonAssignablePolicies , policy ) {
return logical . ErrorResponse ( fmt . Sprintf ( "cannot assign policy %q" , policy ) ) , nil , logical . ErrInvalidRequest
}
}
2018-10-15 16:56:24 +00:00
var registerFunc RegisterAuthFunc
var funcGetErr error
// Batch tokens should not be forwarded to perf standby
if auth . TokenType == logical . TokenTypeBatch {
registerFunc = c . RegisterAuth
} else {
registerFunc , funcGetErr = getAuthRegisterFunc ( c )
}
2018-09-18 03:03:00 +00:00
if funcGetErr != nil {
retErr = multierror . Append ( retErr , funcGetErr )
return nil , auth , retErr
2016-05-02 04:08:07 +00:00
}
2018-09-18 03:03:00 +00:00
err = registerFunc ( ctx , tokenTTL , req . Path , auth )
switch {
case err == nil :
2020-06-26 21:13:16 +00:00
if auth . TokenType != logical . TokenTypeBatch {
leaseGenerated = true
}
2018-09-18 03:03:00 +00:00
case err == ErrInternalError :
return nil , auth , err
default :
return logical . ErrorResponse ( err . Error ( ) ) , auth , logical . ErrInvalidRequest
2016-05-02 04:08:07 +00:00
}
2018-09-18 03:03:00 +00:00
auth . IdentityPolicies = policyutil . SanitizePolicies ( identityPolicies [ ns . ID ] , policyutil . DoNotAddDefaultPolicy )
delete ( identityPolicies , ns . ID )
auth . ExternalNamespacePolicies = identityPolicies
2018-07-24 19:03:11 +00:00
auth . Policies = allPolicies
2016-05-02 04:08:07 +00:00
// Attach the display name, might be used by audit backends
req . DisplayName = auth . DisplayName
2018-09-18 03:03:00 +00:00
2020-06-02 18:40:54 +00:00
// Count the successful token creation
ttl_label := metricsutil . TTLBucket ( tokenTTL )
2020-07-14 19:28:11 +00:00
// Do not include namespace path in mount point; already present as separate label.
mountPointWithoutNs := ns . TrimmedPath ( req . MountPoint )
2020-06-02 18:40:54 +00:00
c . metricSink . IncrCounterWithLabels (
[ ] string { "token" , "creation" } ,
1 ,
[ ] metrics . Label {
2020-10-12 18:56:24 +00:00
vaultmetrics . NamespaceLabel ( ns ) ,
2020-06-02 18:40:54 +00:00
{ "auth_method" , req . MountType } ,
2020-07-14 19:28:11 +00:00
{ "mount_point" , mountPointWithoutNs } ,
2020-06-02 18:40:54 +00:00
{ "creation_ttl" , ttl_label } ,
{ "token_type" , auth . TokenType . String ( ) } ,
} ,
)
2016-05-02 04:08:07 +00:00
}
2017-02-17 04:09:39 +00:00
return resp , auth , routeErr
2016-05-02 04:08:07 +00:00
}
2018-09-18 03:03:00 +00:00
2019-11-08 21:14:03 +00:00
// RegisterAuth uses a logical.Auth object to create a token entry in the token
// store, and registers a corresponding token lease to the expiration manager.
2018-09-18 03:03:00 +00:00
func ( c * Core ) RegisterAuth ( ctx context . Context , tokenTTL time . Duration , path string , auth * logical . Auth ) error {
// We first assign token policies to what was returned from the backend
// via auth.Policies. Then, we get the full set of policies into
// auth.Policies from the backend + entity information -- this is not
// stored in the token, but we perform sanity checks on it and return
// that information to the user.
// Generate a token
ns , err := namespace . FromContext ( ctx )
if err != nil {
return err
}
te := logical . TokenEntry {
2018-09-21 21:31:29 +00:00
Path : path ,
Meta : auth . Metadata ,
DisplayName : auth . DisplayName ,
CreationTime : time . Now ( ) . Unix ( ) ,
TTL : tokenTTL ,
NumUses : auth . NumUses ,
EntityID : auth . EntityID ,
BoundCIDRs : auth . BoundCIDRs ,
Policies : auth . TokenPolicies ,
NamespaceID : ns . ID ,
ExplicitMaxTTL : auth . ExplicitMaxTTL ,
2018-10-15 16:56:24 +00:00
Type : auth . TokenType ,
2018-09-18 03:03:00 +00:00
}
2019-11-05 21:11:13 +00:00
if te . TTL == 0 && ( len ( te . Policies ) != 1 || te . Policies [ 0 ] != "root" ) {
c . logger . Error ( "refusing to create a non-root zero TTL token" )
return ErrInternalError
}
2018-09-18 03:03:00 +00:00
if err := c . tokenStore . create ( ctx , & te ) ; err != nil {
c . logger . Error ( "failed to create token" , "error" , err )
return ErrInternalError
}
// Populate the client token, accessor, and TTL
auth . ClientToken = te . ID
auth . Accessor = te . Accessor
auth . TTL = te . TTL
2019-03-04 22:32:09 +00:00
auth . Orphan = te . Parent == ""
2018-09-18 03:03:00 +00:00
2018-10-15 16:56:24 +00:00
switch auth . TokenType {
case logical . TokenTypeBatch :
// Ensure it's not marked renewable since it isn't
auth . Renewable = false
case logical . TokenTypeService :
// Register with the expiration manager
if err := c . expiration . RegisterAuth ( ctx , & te , auth ) ; err != nil {
2019-11-08 21:14:03 +00:00
if err := c . tokenStore . revokeOrphan ( ctx , te . ID ) ; err != nil {
c . logger . Warn ( "failed to clean up token lease during login request" , "request_path" , path , "error" , err )
}
c . logger . Error ( "failed to register token lease during login request" , "request_path" , path , "error" , err )
2018-10-15 16:56:24 +00:00
return ErrInternalError
}
2018-09-18 03:03:00 +00:00
}
return nil
}