2015-03-18 20:19:19 +00:00
package vault
import (
2018-01-08 18:31:38 +00:00
"context"
2015-03-18 20:19:19 +00:00
"encoding/json"
"fmt"
2017-07-18 16:02:03 +00:00
"sync"
2017-04-27 15:41:33 +00:00
"sync/atomic"
2017-04-26 20:11:23 +00:00
2015-04-15 21:24:07 +00:00
"regexp"
2015-03-24 22:10:46 +00:00
"strings"
"time"
2015-03-18 20:19:19 +00:00
2018-04-05 15:49:21 +00:00
"github.com/hashicorp/errwrap"
2018-04-03 00:46:59 +00:00
log "github.com/hashicorp/go-hclog"
2017-04-26 20:11:23 +00:00
2015-04-08 23:43:17 +00:00
"github.com/armon/go-metrics"
2016-12-16 20:29:27 +00:00
"github.com/hashicorp/go-multierror"
2015-12-16 17:56:20 +00:00
"github.com/hashicorp/go-uuid"
2017-05-12 17:52:33 +00:00
"github.com/hashicorp/vault/helper/consts"
2016-07-06 16:25:40 +00:00
"github.com/hashicorp/vault/helper/jsonutil"
2016-07-20 01:37:28 +00:00
"github.com/hashicorp/vault/helper/locksutil"
2017-03-07 21:06:05 +00:00
"github.com/hashicorp/vault/helper/parseutil"
2016-05-11 20:51:18 +00:00
"github.com/hashicorp/vault/helper/policyutil"
2015-10-30 14:59:26 +00:00
"github.com/hashicorp/vault/helper/salt"
2016-04-06 00:30:38 +00:00
"github.com/hashicorp/vault/helper/strutil"
2015-03-18 20:19:19 +00:00
"github.com/hashicorp/vault/logical"
2015-03-31 19:48:19 +00:00
"github.com/hashicorp/vault/logical/framework"
2015-04-07 21:16:35 +00:00
"github.com/mitchellh/mapstructure"
2015-03-18 20:19:19 +00:00
)
const (
// lookupPrefix is the prefix used to store tokens for their
// primary ID based index
lookupPrefix = "id/"
2016-03-09 14:05:04 +00:00
// accessorPrefix is the prefix used to store the index from
// Accessor to Token ID
accessorPrefix = "accessor/"
2015-03-18 20:19:19 +00:00
// parentPrefix is the prefix used to store tokens for their
// secondar parent based index
parentPrefix = "parent/"
2015-03-18 21:00:42 +00:00
// tokenSubPath is the sub-path used for the token store
// view. This is nested under the system view.
tokenSubPath = "token/"
2016-03-01 17:33:35 +00:00
// rolesPrefix is the prefix used to store role information
rolesPrefix = "roles/"
2016-12-16 18:11:55 +00:00
// tokenRevocationDeferred indicates that the token should not be used
// again but is currently fulfilling its final use
tokenRevocationDeferred = - 1
// tokenRevocationInProgress indicates that revocation of that token/its
// leases is ongoing
tokenRevocationInProgress = - 2
// tokenRevocationFailed indicates that revocation failed; the entry is
2016-12-16 20:29:27 +00:00
// kept around so that when the tidy function is run it can be tried
2016-12-16 18:11:55 +00:00
// again (or when the revocation function is run again), but all other uses
// will report the token invalid
tokenRevocationFailed = - 3
2015-03-18 20:19:19 +00:00
)
2015-04-15 21:24:07 +00:00
var (
// displayNameSanitize is used to sanitize a display name given to a token.
displayNameSanitize = regexp . MustCompile ( "[^a-zA-Z0-9-]" )
2016-02-29 18:27:31 +00:00
2016-03-01 20:30:37 +00:00
// pathSuffixSanitize is used to ensure a path suffix in a role is valid.
pathSuffixSanitize = regexp . MustCompile ( "\\w[\\w-.]+\\w" )
2016-12-16 18:11:55 +00:00
2018-01-19 06:44:44 +00:00
destroyCubbyhole = func ( ctx context . Context , ts * TokenStore , saltedID string ) error {
2016-12-16 18:11:55 +00:00
if ts . cubbyholeBackend == nil {
// Should only ever happen in testing
return nil
}
2018-01-19 06:44:44 +00:00
return ts . cubbyholeBackend . revoke ( ctx , salt . SaltID ( ts . cubbyholeBackend . saltUUID , saltedID , salt . SHA1Hash ) )
2016-12-16 18:11:55 +00:00
}
2015-04-15 21:24:07 +00:00
)
2015-03-18 20:19:19 +00:00
// TokenStore is used to manage client tokens. Tokens are used for
// clients to authenticate, and each token is mapped to an applicable
// set of policy which is used for authorization.
type TokenStore struct {
2015-03-31 19:48:19 +00:00
* framework . Backend
2015-03-18 20:19:19 +00:00
view * BarrierView
2015-04-03 18:40:08 +00:00
expiration * ExpirationManager
2015-09-10 01:58:09 +00:00
2015-09-15 17:49:53 +00:00
cubbyholeBackend * CubbyholeBackend
2015-10-07 19:30:54 +00:00
2015-11-06 16:36:40 +00:00
policyLookupFunc func ( string ) ( * Policy , error )
2016-05-02 07:11:14 +00:00
2017-03-07 16:21:32 +00:00
tokenLocks [ ] * locksutil . LockEntry
2016-12-16 18:11:55 +00:00
2018-01-19 06:44:44 +00:00
cubbyholeDestroyer func ( context . Context , * TokenStore , string ) error
2017-04-26 20:11:23 +00:00
logger log . Logger
2017-04-27 15:41:33 +00:00
2018-01-26 01:19:27 +00:00
saltLock sync . RWMutex
salt * salt . Salt
2017-07-18 16:02:03 +00:00
2017-04-27 15:41:33 +00:00
tidyLock int64
2015-03-18 20:19:19 +00:00
}
// NewTokenStore is used to construct a token store that is
// backed by the given barrier view.
2018-04-03 00:46:59 +00:00
func NewTokenStore ( ctx context . Context , logger log . Logger , c * Core , config * logical . BackendConfig ) ( * TokenStore , error ) {
2015-03-19 02:11:52 +00:00
// Create a sub-view
2015-09-04 20:58:12 +00:00
view := c . systemBarrierView . SubView ( tokenSubPath )
2015-03-19 02:11:52 +00:00
2015-03-18 20:19:19 +00:00
// Initialize the store
t := & TokenStore {
2016-12-16 18:11:55 +00:00
view : view ,
cubbyholeDestroyer : destroyCubbyhole ,
2018-04-03 00:46:59 +00:00
logger : logger ,
2017-04-26 20:11:23 +00:00
tokenLocks : locksutil . CreateLocks ( ) ,
2017-07-18 16:02:03 +00:00
saltLock : sync . RWMutex { } ,
2015-03-18 20:19:19 +00:00
}
2017-04-27 14:56:19 +00:00
if c . policyStore != nil {
2017-10-23 18:59:37 +00:00
t . policyLookupFunc = func ( name string ) ( * Policy , error ) {
2018-01-19 06:44:44 +00:00
return c . policyStore . GetPolicy ( ctx , name , PolicyTypeToken )
2017-10-23 18:59:37 +00:00
}
2017-04-27 14:56:19 +00:00
}
2015-03-31 19:48:19 +00:00
// Setup the framework endpoints
t . Backend = & framework . Backend {
2016-01-29 22:44:09 +00:00
AuthRenew : t . authRenew ,
2015-04-11 23:28:16 +00:00
2015-04-03 18:40:08 +00:00
PathsSpecial : & logical . Paths {
Root : [ ] string {
2015-09-16 13:22:15 +00:00
"revoke-orphan/*" ,
2016-07-29 22:20:38 +00:00
"accessors*" ,
2015-04-03 18:40:08 +00:00
} ,
2017-02-17 04:09:39 +00:00
// Most token store items are local since tokens are local, but a
// notable exception is roles
LocalStorage : [ ] string {
lookupPrefix ,
accessorPrefix ,
parentPrefix ,
2017-05-09 21:51:09 +00:00
salt . DefaultLocation ,
2017-02-17 04:09:39 +00:00
} ,
2015-04-03 18:40:08 +00:00
} ,
2015-03-31 19:48:19 +00:00
Paths : [ ] * framework . Path {
2015-11-03 20:10:46 +00:00
& framework . Path {
2016-02-29 18:27:31 +00:00
Pattern : "roles/?$" ,
Callbacks : map [ logical . Operation ] framework . OperationFunc {
logical . ListOperation : t . tokenStoreRoleList ,
} ,
2016-03-01 18:02:40 +00:00
HelpSynopsis : tokenListRolesHelp ,
HelpDescription : tokenListRolesHelp ,
2016-02-29 18:27:31 +00:00
} ,
2016-07-29 22:20:38 +00:00
& framework . Path {
2018-03-26 15:30:58 +00:00
Pattern : "accessors/$" ,
2016-07-29 22:20:38 +00:00
Callbacks : map [ logical . Operation ] framework . OperationFunc {
logical . ListOperation : t . tokenStoreAccessorList ,
} ,
2016-08-01 17:07:41 +00:00
HelpSynopsis : tokenListAccessorsHelp ,
HelpDescription : tokenListAccessorsHelp ,
2016-07-29 22:20:38 +00:00
} ,
2016-02-29 18:27:31 +00:00
& framework . Path {
Pattern : "roles/" + framework . GenericNameRegex ( "role_name" ) ,
Fields : map [ string ] * framework . FieldSchema {
"role_name" : & framework . FieldSchema {
Type : framework . TypeString ,
Description : "Name of the role" ,
} ,
"allowed_policies" : & framework . FieldSchema {
2017-12-04 17:47:05 +00:00
Type : framework . TypeCommaStringSlice ,
2016-03-03 16:04:05 +00:00
Description : tokenAllowedPoliciesHelp ,
2016-02-29 18:27:31 +00:00
} ,
2016-08-02 14:33:50 +00:00
"disallowed_policies" : & framework . FieldSchema {
2017-12-04 17:47:05 +00:00
Type : framework . TypeCommaStringSlice ,
2016-08-02 14:33:50 +00:00
Description : tokenDisallowedPoliciesHelp ,
} ,
2016-02-29 18:27:31 +00:00
"orphan" : & framework . FieldSchema {
2016-03-07 15:07:04 +00:00
Type : framework . TypeBool ,
Default : false ,
Description : tokenOrphanHelp ,
2016-02-29 18:27:31 +00:00
} ,
"period" : & framework . FieldSchema {
2016-03-03 16:04:05 +00:00
Type : framework . TypeDurationSecond ,
Default : 0 ,
Description : tokenPeriodHelp ,
2016-02-29 18:27:31 +00:00
} ,
2016-03-01 20:30:37 +00:00
"path_suffix" : & framework . FieldSchema {
2016-03-03 16:04:05 +00:00
Type : framework . TypeString ,
Default : "" ,
Description : tokenPathSuffixHelp + pathSuffixSanitize . String ( ) ,
2016-02-29 18:27:31 +00:00
} ,
2016-05-11 20:51:18 +00:00
"explicit_max_ttl" : & framework . FieldSchema {
Type : framework . TypeDurationSecond ,
Default : 0 ,
Description : tokenExplicitMaxTTLHelp ,
} ,
2016-06-08 19:17:22 +00:00
"renewable" : & framework . FieldSchema {
Type : framework . TypeBool ,
Default : true ,
Description : tokenRenewableHelp ,
} ,
2016-02-29 18:27:31 +00:00
} ,
Callbacks : map [ logical . Operation ] framework . OperationFunc {
logical . ReadOperation : t . tokenStoreRoleRead ,
2016-03-09 16:59:54 +00:00
logical . CreateOperation : t . tokenStoreRoleCreateUpdate ,
logical . UpdateOperation : t . tokenStoreRoleCreateUpdate ,
2016-02-29 18:27:31 +00:00
logical . DeleteOperation : t . tokenStoreRoleDelete ,
} ,
2016-03-09 16:59:54 +00:00
ExistenceCheck : t . tokenStoreRoleExistenceCheck ,
2016-03-01 18:02:40 +00:00
HelpSynopsis : tokenPathRolesHelp ,
HelpDescription : tokenPathRolesHelp ,
2016-02-29 18:27:31 +00:00
} ,
& framework . Path {
2016-02-29 19:56:04 +00:00
Pattern : "create-orphan$" ,
2015-11-03 20:10:46 +00:00
Callbacks : map [ logical . Operation ] framework . OperationFunc {
2016-01-07 15:30:47 +00:00
logical . UpdateOperation : t . handleCreateOrphan ,
2015-11-03 20:10:46 +00:00
} ,
HelpSynopsis : strings . TrimSpace ( tokenCreateOrphanHelp ) ,
HelpDescription : strings . TrimSpace ( tokenCreateOrphanHelp ) ,
} ,
2016-02-29 18:27:31 +00:00
& framework . Path {
Pattern : "create/" + framework . GenericNameRegex ( "role_name" ) ,
Fields : map [ string ] * framework . FieldSchema {
"role_name" : & framework . FieldSchema {
Type : framework . TypeString ,
Description : "Name of the role" ,
} ,
} ,
Callbacks : map [ logical . Operation ] framework . OperationFunc {
2016-03-01 20:30:37 +00:00
logical . UpdateOperation : t . handleCreateAgainstRole ,
2016-02-29 18:27:31 +00:00
} ,
2016-03-01 18:02:40 +00:00
HelpSynopsis : strings . TrimSpace ( tokenCreateRoleHelp ) ,
HelpDescription : strings . TrimSpace ( tokenCreateRoleHelp ) ,
2016-02-29 18:27:31 +00:00
} ,
2015-03-31 19:48:19 +00:00
& framework . Path {
Pattern : "create$" ,
Callbacks : map [ logical . Operation ] framework . OperationFunc {
2016-01-07 15:30:47 +00:00
logical . UpdateOperation : t . handleCreate ,
2015-03-31 19:48:19 +00:00
} ,
HelpSynopsis : strings . TrimSpace ( tokenCreateHelp ) ,
HelpDescription : strings . TrimSpace ( tokenCreateHelp ) ,
} ,
& framework . Path {
2016-08-29 19:15:57 +00:00
Pattern : "lookup" + framework . OptionalParamRegex ( "urltoken" ) ,
2015-03-31 19:51:00 +00:00
Fields : map [ string ] * framework . FieldSchema {
2016-08-29 19:15:57 +00:00
"urltoken" : & framework . FieldSchema {
Type : framework . TypeString ,
2018-03-19 15:47:42 +00:00
Description : "DEPRECATED: Token to lookup (URL parameter). Do not use this; use the POST version instead with the token in the body." ,
2016-08-29 19:15:57 +00:00
} ,
2015-03-31 19:51:00 +00:00
"token" : & framework . FieldSchema {
Type : framework . TypeString ,
2016-08-29 19:15:57 +00:00
Description : "Token to lookup (POST request body)" ,
2015-03-31 19:51:00 +00:00
} ,
} ,
Callbacks : map [ logical . Operation ] framework . OperationFunc {
2016-08-29 19:15:57 +00:00
logical . ReadOperation : t . handleLookup ,
2016-03-14 22:56:00 +00:00
logical . UpdateOperation : t . handleLookup ,
2015-03-31 19:51:00 +00:00
} ,
HelpSynopsis : strings . TrimSpace ( tokenLookupHelp ) ,
HelpDescription : strings . TrimSpace ( tokenLookupHelp ) ,
} ,
2016-03-08 20:13:29 +00:00
& framework . Path {
2016-08-29 19:15:57 +00:00
Pattern : "lookup-accessor" + framework . OptionalParamRegex ( "urlaccessor" ) ,
2016-03-08 20:13:29 +00:00
Fields : map [ string ] * framework . FieldSchema {
2016-08-29 19:15:57 +00:00
"urlaccessor" : & framework . FieldSchema {
Type : framework . TypeString ,
2018-03-19 15:47:42 +00:00
Description : "DEPRECATED: Accessor of the token to lookup (URL parameter). Do not use this; use the POST version instead with the accessor in the body." ,
2016-08-29 19:15:57 +00:00
} ,
2016-03-09 11:23:31 +00:00
"accessor" : & framework . FieldSchema {
2016-03-08 20:13:29 +00:00
Type : framework . TypeString ,
2016-08-29 19:15:57 +00:00
Description : "Accessor of the token to look up (request body)" ,
2016-03-08 20:13:29 +00:00
} ,
} ,
Callbacks : map [ logical . Operation ] framework . OperationFunc {
2016-03-09 14:48:32 +00:00
logical . UpdateOperation : t . handleUpdateLookupAccessor ,
2016-03-08 20:13:29 +00:00
} ,
2016-03-09 22:23:34 +00:00
HelpSynopsis : strings . TrimSpace ( tokenLookupAccessorHelp ) ,
HelpDescription : strings . TrimSpace ( tokenLookupAccessorHelp ) ,
2016-03-08 20:13:29 +00:00
} ,
2015-03-31 19:51:00 +00:00
& framework . Path {
Pattern : "lookup-self$" ,
2015-03-31 19:48:19 +00:00
Fields : map [ string ] * framework . FieldSchema {
"token" : & framework . FieldSchema {
Type : framework . TypeString ,
2016-08-29 19:47:14 +00:00
Description : "Token to look up (unused, does not need to be set)" ,
2015-03-31 19:48:19 +00:00
} ,
} ,
Callbacks : map [ logical . Operation ] framework . OperationFunc {
2016-08-24 19:59:43 +00:00
logical . UpdateOperation : t . handleLookupSelf ,
2016-08-29 19:15:57 +00:00
logical . ReadOperation : t . handleLookupSelf ,
2015-03-31 19:48:19 +00:00
} ,
HelpSynopsis : strings . TrimSpace ( tokenLookupHelp ) ,
HelpDescription : strings . TrimSpace ( tokenLookupHelp ) ,
} ,
2016-03-08 20:13:29 +00:00
& framework . Path {
2016-08-29 19:15:57 +00:00
Pattern : "revoke-accessor" + framework . OptionalParamRegex ( "urlaccessor" ) ,
2016-03-08 20:13:29 +00:00
2016-03-08 23:07:27 +00:00
Fields : map [ string ] * framework . FieldSchema {
2016-08-29 19:15:57 +00:00
"urlaccessor" : & framework . FieldSchema {
Type : framework . TypeString ,
2018-03-19 15:47:42 +00:00
Description : "DEPRECATED: Accessor of the token to revoke (URL parameter). Do not use this; use the POST version instead with the accessor in the body." ,
2016-08-29 19:15:57 +00:00
} ,
2016-03-09 11:23:31 +00:00
"accessor" : & framework . FieldSchema {
2016-03-08 23:07:27 +00:00
Type : framework . TypeString ,
2016-08-29 19:15:57 +00:00
Description : "Accessor of the token (request body)" ,
2016-03-08 23:07:27 +00:00
} ,
} ,
2016-03-08 20:13:29 +00:00
Callbacks : map [ logical . Operation ] framework . OperationFunc {
2016-03-09 14:48:32 +00:00
logical . UpdateOperation : t . handleUpdateRevokeAccessor ,
2016-03-08 20:13:29 +00:00
} ,
2016-03-09 22:23:34 +00:00
HelpSynopsis : strings . TrimSpace ( tokenRevokeAccessorHelp ) ,
HelpDescription : strings . TrimSpace ( tokenRevokeAccessorHelp ) ,
2016-03-08 20:13:29 +00:00
} ,
2015-09-17 17:22:30 +00:00
& framework . Path {
2015-10-07 16:49:13 +00:00
Pattern : "revoke-self$" ,
2015-09-17 17:22:30 +00:00
Callbacks : map [ logical . Operation ] framework . OperationFunc {
2016-01-07 15:30:47 +00:00
logical . UpdateOperation : t . handleRevokeSelf ,
2015-09-17 17:22:30 +00:00
} ,
HelpSynopsis : strings . TrimSpace ( tokenRevokeSelfHelp ) ,
HelpDescription : strings . TrimSpace ( tokenRevokeSelfHelp ) ,
} ,
2015-03-31 19:48:19 +00:00
& framework . Path {
2016-08-29 19:15:57 +00:00
Pattern : "revoke" + framework . OptionalParamRegex ( "urltoken" ) ,
2015-03-31 19:48:19 +00:00
Fields : map [ string ] * framework . FieldSchema {
2016-08-29 19:15:57 +00:00
"urltoken" : & framework . FieldSchema {
Type : framework . TypeString ,
2018-03-19 15:47:42 +00:00
Description : "DEPRECATED: Token to revoke (URL parameter). Do not use this; use the POST version instead with the token in the body." ,
2016-08-29 19:15:57 +00:00
} ,
2015-03-31 19:48:19 +00:00
"token" : & framework . FieldSchema {
Type : framework . TypeString ,
2016-08-29 19:15:57 +00:00
Description : "Token to revoke (request body)" ,
2015-03-31 19:48:19 +00:00
} ,
} ,
Callbacks : map [ logical . Operation ] framework . OperationFunc {
2016-01-07 15:30:47 +00:00
logical . UpdateOperation : t . handleRevokeTree ,
2015-03-31 19:48:19 +00:00
} ,
HelpSynopsis : strings . TrimSpace ( tokenRevokeHelp ) ,
HelpDescription : strings . TrimSpace ( tokenRevokeHelp ) ,
} ,
2015-04-03 19:11:49 +00:00
2015-03-31 19:48:19 +00:00
& framework . Path {
2016-08-29 19:15:57 +00:00
Pattern : "revoke-orphan" + framework . OptionalParamRegex ( "urltoken" ) ,
2015-03-31 19:48:19 +00:00
Fields : map [ string ] * framework . FieldSchema {
2016-08-29 19:15:57 +00:00
"urltoken" : & framework . FieldSchema {
Type : framework . TypeString ,
2018-03-19 15:47:42 +00:00
Description : "DEPRECATED: Token to revoke (URL parameter). Do not use this; use the POST version instead with the token in the body." ,
2016-08-29 19:15:57 +00:00
} ,
2015-03-31 19:48:19 +00:00
"token" : & framework . FieldSchema {
Type : framework . TypeString ,
2016-08-29 19:15:57 +00:00
Description : "Token to revoke (request body)" ,
2015-03-31 19:48:19 +00:00
} ,
} ,
Callbacks : map [ logical . Operation ] framework . OperationFunc {
2016-01-07 15:30:47 +00:00
logical . UpdateOperation : t . handleRevokeOrphan ,
2015-03-31 19:48:19 +00:00
} ,
HelpSynopsis : strings . TrimSpace ( tokenRevokeOrphanHelp ) ,
HelpDescription : strings . TrimSpace ( tokenRevokeOrphanHelp ) ,
} ,
2015-04-03 18:40:08 +00:00
2015-10-07 16:49:13 +00:00
& framework . Path {
Pattern : "renew-self$" ,
Fields : map [ string ] * framework . FieldSchema {
"token" : & framework . FieldSchema {
Type : framework . TypeString ,
2016-08-29 19:47:14 +00:00
Description : "Token to renew (unused, does not need to be set)" ,
2015-10-07 16:49:13 +00:00
} ,
"increment" : & framework . FieldSchema {
Type : framework . TypeDurationSecond ,
2016-03-01 17:33:35 +00:00
Default : 0 ,
2015-10-07 16:49:13 +00:00
Description : "The desired increment in seconds to the token expiration" ,
} ,
} ,
Callbacks : map [ logical . Operation ] framework . OperationFunc {
2016-01-07 15:30:47 +00:00
logical . UpdateOperation : t . handleRenewSelf ,
2015-10-07 16:49:13 +00:00
} ,
HelpSynopsis : strings . TrimSpace ( tokenRenewSelfHelp ) ,
HelpDescription : strings . TrimSpace ( tokenRenewSelfHelp ) ,
} ,
2015-04-03 19:11:49 +00:00
& framework . Path {
2016-08-29 19:15:57 +00:00
Pattern : "renew" + framework . OptionalParamRegex ( "urltoken" ) ,
2015-04-03 19:11:49 +00:00
Fields : map [ string ] * framework . FieldSchema {
2016-08-29 19:15:57 +00:00
"urltoken" : & framework . FieldSchema {
Type : framework . TypeString ,
2018-03-19 15:47:42 +00:00
Description : "DEPRECATED: Token to renew (URL parameter). Do not use this; use the POST version instead with the token in the body." ,
2016-08-29 19:15:57 +00:00
} ,
2015-04-03 19:11:49 +00:00
"token" : & framework . FieldSchema {
Type : framework . TypeString ,
2016-08-29 19:15:57 +00:00
Description : "Token to renew (request body)" ,
2015-04-03 19:11:49 +00:00
} ,
2015-04-09 21:23:37 +00:00
"increment" : & framework . FieldSchema {
2015-06-17 22:58:20 +00:00
Type : framework . TypeDurationSecond ,
2016-03-01 17:33:35 +00:00
Default : 0 ,
2015-04-09 21:23:37 +00:00
Description : "The desired increment in seconds to the token expiration" ,
} ,
2015-04-03 19:11:49 +00:00
} ,
Callbacks : map [ logical . Operation ] framework . OperationFunc {
2016-01-07 15:30:47 +00:00
logical . UpdateOperation : t . handleRenew ,
2015-04-03 19:11:49 +00:00
} ,
HelpSynopsis : strings . TrimSpace ( tokenRenewHelp ) ,
HelpDescription : strings . TrimSpace ( tokenRenewHelp ) ,
} ,
2016-12-16 20:29:27 +00:00
& framework . Path {
Pattern : "tidy$" ,
Callbacks : map [ logical . Operation ] framework . OperationFunc {
logical . UpdateOperation : t . handleTidy ,
} ,
HelpSynopsis : strings . TrimSpace ( tokenTidyHelp ) ,
HelpDescription : strings . TrimSpace ( tokenTidyDesc ) ,
} ,
2015-03-31 19:48:19 +00:00
} ,
}
2018-01-19 06:44:44 +00:00
t . Backend . Setup ( ctx , config )
2015-09-04 20:58:12 +00:00
2015-03-18 20:19:19 +00:00
return t , nil
}
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) Invalidate ( ctx context . Context , key string ) {
2018-04-03 00:46:59 +00:00
//ts.logger.Debug("invalidating key", "key", key)
2017-07-18 16:02:03 +00:00
switch key {
case tokenSubPath + salt . DefaultLocation :
ts . saltLock . Lock ( )
ts . salt = nil
ts . saltLock . Unlock ( )
}
}
2018-03-08 19:21:11 +00:00
func ( ts * TokenStore ) Salt ( ctx context . Context ) ( * salt . Salt , error ) {
2017-07-18 16:02:03 +00:00
ts . saltLock . RLock ( )
if ts . salt != nil {
defer ts . saltLock . RUnlock ( )
return ts . salt , nil
}
ts . saltLock . RUnlock ( )
ts . saltLock . Lock ( )
defer ts . saltLock . Unlock ( )
if ts . salt != nil {
return ts . salt , nil
}
2018-03-08 19:21:11 +00:00
salt , err := salt . NewSalt ( ctx , ts . view , & salt . Config {
2018-01-26 01:19:27 +00:00
HashFunc : salt . SHA1Hash ,
Location : salt . DefaultLocation ,
} )
2017-07-18 16:02:03 +00:00
if err != nil {
return nil , err
}
ts . salt = salt
return salt , nil
}
2015-03-18 20:19:19 +00:00
// TokenEntry is used to represent a given token
type TokenEntry struct {
2016-07-07 21:44:14 +00:00
// ID of this entry, generally a random UUID
2017-10-23 18:59:37 +00:00
ID string ` json:"id" mapstructure:"id" structs:"id" sentinel:"" `
2016-07-07 21:44:14 +00:00
// Accessor for this token, a random UUID
2017-10-23 18:59:37 +00:00
Accessor string ` json:"accessor" mapstructure:"accessor" structs:"accessor" sentinel:"" `
2016-07-07 21:44:14 +00:00
// Parent token, used for revocation trees
2017-10-23 18:59:37 +00:00
Parent string ` json:"parent" mapstructure:"parent" structs:"parent" sentinel:"" `
2016-07-07 21:44:14 +00:00
// Which named policies should be used
Policies [ ] string ` json:"policies" mapstructure:"policies" structs:"policies" `
// Used for audit trails, this is something like "auth/user/login"
Path string ` json:"path" mapstructure:"path" structs:"path" `
// Used for auditing. This could include things like "source", "user", "ip"
2017-10-23 18:59:37 +00:00
Meta map [ string ] string ` json:"meta" mapstructure:"meta" structs:"meta" sentinel:"meta" `
2016-07-07 21:44:14 +00:00
// Used for operators to be able to associate with the source
DisplayName string ` json:"display_name" mapstructure:"display_name" structs:"display_name" `
2016-12-16 18:11:55 +00:00
// Used to restrict the number of uses (zero is unlimited). This is to
// support one-time-tokens (generalized). There are a few special values:
// if it's -1 it has run through its use counts and is executing its final
// use; if it's -2 it is tainted, which means revocation is currently
// running on it; and if it's -3 it's also tainted but revocation
2016-12-16 20:29:27 +00:00
// previously ran and failed, so this hints the tidy function to try it
2016-12-16 18:11:55 +00:00
// again.
2016-07-07 21:44:14 +00:00
NumUses int ` json:"num_uses" mapstructure:"num_uses" structs:"num_uses" `
// Time of token creation
2017-10-23 18:59:37 +00:00
CreationTime int64 ` json:"creation_time" mapstructure:"creation_time" structs:"creation_time" sentinel:"" `
2016-07-07 21:44:14 +00:00
// Duration set when token was created
2017-10-23 18:59:37 +00:00
TTL time . Duration ` json:"ttl" mapstructure:"ttl" structs:"ttl" sentinel:"" `
2016-07-07 21:44:14 +00:00
// Explicit maximum TTL on the token
2017-10-23 18:59:37 +00:00
ExplicitMaxTTL time . Duration ` json:"explicit_max_ttl" mapstructure:"explicit_max_ttl" structs:"explicit_max_ttl" sentinel:"" `
2016-07-07 21:44:14 +00:00
// If set, the role that was used for parameters at creation time
Role string ` json:"role" mapstructure:"role" structs:"role" `
2016-08-13 01:01:30 +00:00
// If set, the period of the token. This is only used when created directly
// through the create endpoint; periods managed by roles or other auth
// backends are subject to those renewal rules.
2017-10-23 18:59:37 +00:00
Period time . Duration ` json:"period" mapstructure:"period" structs:"period" sentinel:"" `
2016-09-26 17:38:50 +00:00
// These are the deprecated fields
2017-10-23 18:59:37 +00:00
DisplayNameDeprecated string ` json:"DisplayName" mapstructure:"DisplayName" structs:"DisplayName" sentinel:"" `
NumUsesDeprecated int ` json:"NumUses" mapstructure:"NumUses" structs:"NumUses" sentinel:"" `
CreationTimeDeprecated int64 ` json:"CreationTime" mapstructure:"CreationTime" structs:"CreationTime" sentinel:"" `
ExplicitMaxTTLDeprecated time . Duration ` json:"ExplicitMaxTTL" mapstructure:"ExplicitMaxTTL" structs:"ExplicitMaxTTL" sentinel:"" `
2017-10-11 17:21:20 +00:00
EntityID string ` json:"entity_id" mapstructure:"entity_id" structs:"entity_id" `
2016-02-29 18:27:31 +00:00
}
2017-10-23 18:59:37 +00:00
func ( te * TokenEntry ) SentinelGet ( key string ) ( interface { } , error ) {
if te == nil {
return nil , nil
}
switch key {
case "period" :
return te . Period , nil
case "period_seconds" :
return int64 ( te . Period . Seconds ( ) ) , nil
case "explicit_max_ttl" :
return te . ExplicitMaxTTL , nil
case "explicit_max_ttl_seconds" :
return int64 ( te . ExplicitMaxTTL . Seconds ( ) ) , nil
case "creation_ttl" :
return te . TTL , nil
case "creation_ttl_seconds" :
return int64 ( te . TTL . Seconds ( ) ) , nil
case "creation_time" :
return time . Unix ( te . CreationTime , 0 ) . Format ( time . RFC3339Nano ) , nil
case "creation_time_unix" :
return time . Unix ( te . CreationTime , 0 ) , nil
case "meta" , "metadata" :
return te . Meta , nil
}
return nil , nil
}
2017-11-13 20:31:32 +00:00
func ( te * TokenEntry ) SentinelKeys ( ) [ ] string {
return [ ] string {
"period" ,
"period_seconds" ,
"explicit_max_ttl" ,
"explicit_max_ttl_seconds" ,
"creation_ttl" ,
"creation_ttl_seconds" ,
"creation_time" ,
"creation_time_unix" ,
"meta" ,
"metadata" ,
}
}
2016-02-29 18:27:31 +00:00
// tsRoleEntry contains token store role information
type tsRoleEntry struct {
// The name of the role. Embedded so it can be used for pathing
2016-02-29 19:13:09 +00:00
Name string ` json:"name" mapstructure:"name" structs:"name" `
2016-02-29 18:27:31 +00:00
// The policies that creation functions using this role can assign to a token,
// escaping or further locking down normal subset checking
2016-02-29 19:13:09 +00:00
AllowedPolicies [ ] string ` json:"allowed_policies" mapstructure:"allowed_policies" structs:"allowed_policies" `
2016-02-29 18:27:31 +00:00
2016-08-02 17:33:03 +00:00
// List of policies to be not allowed during token creation using this role
2016-08-02 14:33:50 +00:00
DisallowedPolicies [ ] string ` json:"disallowed_policies" mapstructure:"disallowed_policies" structs:"disallowed_policies" `
2016-02-29 18:27:31 +00:00
// If true, tokens created using this role will be orphans
2016-02-29 19:13:09 +00:00
Orphan bool ` json:"orphan" mapstructure:"orphan" structs:"orphan" `
2016-02-29 18:27:31 +00:00
// If non-zero, tokens created using this role will be able to be renewed
// forever, but will have a fixed renewal period of this value
2016-02-29 19:13:09 +00:00
Period time . Duration ` json:"period" mapstructure:"period" structs:"period" `
2016-02-29 18:27:31 +00:00
2016-03-01 20:30:37 +00:00
// If set, a suffix will be set on the token path, making it easier to
2016-05-11 20:51:18 +00:00
// revoke using 'revoke-prefix'
2016-03-01 20:30:37 +00:00
PathSuffix string ` json:"path_suffix" mapstructure:"path_suffix" structs:"path_suffix" `
2016-05-11 20:51:18 +00:00
2016-06-08 19:17:22 +00:00
// If set, controls whether created tokens are marked as being renewable
Renewable bool ` json:"renewable" mapstructure:"renewable" structs:"renewable" `
2016-05-11 20:51:18 +00:00
// If set, the token entry will have an explicit maximum TTL set, rather
// than deferring to role/mount values
ExplicitMaxTTL time . Duration ` json:"explicit_max_ttl" mapstructure:"explicit_max_ttl" structs:"explicit_max_ttl" `
2015-03-18 20:19:19 +00:00
}
2016-07-29 22:20:38 +00:00
type accessorEntry struct {
TokenID string ` json:"token_id" `
AccessorID string ` json:"accessor_id" `
}
2015-04-03 18:40:08 +00:00
// SetExpirationManager is used to provide the token store with
// an expiration manager. This is used to manage prefix based revocation
2016-12-16 20:29:27 +00:00
// of tokens and to tidy entries when removed from the token store.
2015-09-18 20:33:52 +00:00
func ( ts * TokenStore ) SetExpirationManager ( exp * ExpirationManager ) {
ts . expiration = exp
2015-04-03 18:40:08 +00:00
}
2016-05-15 16:58:36 +00:00
// SaltID is used to apply a salt and hash to an ID to make sure its not reversible
2018-03-08 19:21:11 +00:00
func ( ts * TokenStore ) SaltID ( ctx context . Context , id string ) ( string , error ) {
s , err := ts . Salt ( ctx )
2017-07-18 16:02:03 +00:00
if err != nil {
return "" , err
}
return s . SaltID ( id ) , nil
2015-03-18 20:19:19 +00:00
}
2015-03-24 00:16:37 +00:00
// RootToken is used to generate a new token with root privileges and no parent
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) rootToken ( ctx context . Context ) ( * TokenEntry , error ) {
2015-03-24 00:16:37 +00:00
te := & TokenEntry {
2015-09-18 20:33:52 +00:00
Policies : [ ] string { "root" } ,
Path : "auth/token/root" ,
DisplayName : "root" ,
CreationTime : time . Now ( ) . Unix ( ) ,
2015-03-24 00:16:37 +00:00
}
2018-01-19 06:44:44 +00:00
if err := ts . create ( ctx , te ) ; err != nil {
2015-03-24 00:16:37 +00:00
return nil , err
}
return te , nil
}
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) tokenStoreAccessorList ( ctx context . Context , req * logical . Request , d * framework . FieldData ) ( * logical . Response , error ) {
2018-01-19 06:44:44 +00:00
entries , err := ts . view . List ( ctx , accessorPrefix )
2016-07-29 22:20:38 +00:00
if err != nil {
return nil , err
}
resp := & logical . Response { }
ret := make ( [ ] string , 0 , len ( entries ) )
for _ , entry := range entries {
2018-01-19 06:44:44 +00:00
aEntry , err := ts . lookupBySaltedAccessor ( ctx , entry , false )
2016-07-29 22:20:38 +00:00
if err != nil {
resp . AddWarning ( "Found an accessor entry that could not be successfully decoded" )
continue
}
2016-08-01 17:07:41 +00:00
if aEntry . TokenID == "" {
resp . AddWarning ( fmt . Sprintf ( "Found an accessor entry missing a token: %v" , aEntry . AccessorID ) )
} else {
ret = append ( ret , aEntry . AccessorID )
}
2016-07-29 22:20:38 +00:00
}
resp . Data = map [ string ] interface { } {
"keys" : ret ,
}
return resp , nil
}
2016-03-09 14:31:09 +00:00
// createAccessor is used to create an identifier for the token ID.
2016-03-09 14:48:32 +00:00
// A storage index, mapping the accessor to the token ID is also created.
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) createAccessor ( ctx context . Context , entry * TokenEntry ) error {
2016-03-09 11:23:31 +00:00
defer metrics . MeasureSince ( [ ] string { "token" , "createAccessor" } , time . Now ( ) )
2016-03-08 17:51:38 +00:00
2016-03-09 14:05:04 +00:00
// Create a random accessor
2016-03-08 17:51:38 +00:00
accessorUUID , err := uuid . GenerateUUID ( )
if err != nil {
return err
}
2016-03-09 11:23:31 +00:00
entry . Accessor = accessorUUID
2016-03-08 18:12:53 +00:00
2016-03-09 14:31:09 +00:00
// Create index entry, mapping the accessor to the token ID
2018-03-08 19:21:11 +00:00
saltID , err := ts . SaltID ( ctx , entry . Accessor )
2017-07-18 16:02:03 +00:00
if err != nil {
return err
}
2016-07-29 22:23:55 +00:00
2017-10-23 18:59:37 +00:00
path := accessorPrefix + saltID
2016-07-29 22:23:55 +00:00
aEntry := & accessorEntry {
TokenID : entry . ID ,
AccessorID : entry . Accessor ,
}
aEntryBytes , err := jsonutil . EncodeJSON ( aEntry )
if err != nil {
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to marshal accessor index entry: {{err}}" , err )
2016-07-29 22:23:55 +00:00
}
le := & logical . StorageEntry { Key : path , Value : aEntryBytes }
2018-01-19 06:44:44 +00:00
if err := ts . view . Put ( ctx , le ) ; err != nil {
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to persist accessor index entry: {{err}}" , err )
2016-03-08 18:12:53 +00:00
}
2016-03-08 17:51:38 +00:00
return nil
}
2015-03-18 20:19:19 +00:00
// Create is used to create a new token entry. The entry is assigned
2015-03-24 21:22:50 +00:00
// a newly generated ID if not provided.
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) create ( ctx context . Context , entry * TokenEntry ) error {
2015-04-08 23:43:17 +00:00
defer metrics . MeasureSince ( [ ] string { "token" , "create" } , time . Now ( ) )
2015-03-24 21:22:50 +00:00
// Generate an ID if necessary
if entry . ID == "" {
2016-01-13 18:40:08 +00:00
entryUUID , err := uuid . GenerateUUID ( )
if err != nil {
return err
}
entry . ID = entryUUID
2015-03-24 21:22:50 +00:00
}
2015-12-30 19:30:02 +00:00
2018-04-03 16:20:20 +00:00
saltedID , err := ts . SaltID ( ctx , entry . ID )
2017-07-18 16:02:03 +00:00
if err != nil {
return err
}
2018-04-03 16:20:20 +00:00
exist , _ := ts . lookupSalted ( ctx , saltedID , true )
2017-06-24 00:52:48 +00:00
if exist != nil {
return fmt . Errorf ( "cannot create a token with a duplicate ID" )
}
2016-12-16 05:36:39 +00:00
entry . Policies = policyutil . SanitizePolicies ( entry . Policies , policyutil . DoNotAddDefaultPolicy )
2016-05-13 15:50:00 +00:00
2018-01-19 06:44:44 +00:00
err = ts . createAccessor ( ctx , entry )
2016-03-08 17:51:38 +00:00
if err != nil {
return err
}
2018-01-19 06:44:44 +00:00
return ts . storeCommon ( ctx , entry , true )
2015-12-30 19:30:02 +00:00
}
2016-01-04 21:43:07 +00:00
// Store is used to store an updated token entry without writing the
// secondary index.
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) store ( ctx context . Context , entry * TokenEntry ) error {
2015-12-30 19:30:02 +00:00
defer metrics . MeasureSince ( [ ] string { "token" , "store" } , time . Now ( ) )
2018-01-19 06:44:44 +00:00
return ts . storeCommon ( ctx , entry , false )
2015-12-30 19:30:02 +00:00
}
// storeCommon handles the actual storage of an entry, possibly generating
// secondary indexes
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) storeCommon ( ctx context . Context , entry * TokenEntry , writeSecondary bool ) error {
2018-04-03 16:20:20 +00:00
saltedID , err := ts . SaltID ( ctx , entry . ID )
2017-07-18 16:02:03 +00:00
if err != nil {
return err
}
2015-03-24 21:22:50 +00:00
// Marshal the entry
2015-03-18 20:19:19 +00:00
enc , err := json . Marshal ( entry )
if err != nil {
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to encode entry: {{err}}" , err )
2015-03-18 20:19:19 +00:00
}
2015-12-30 19:30:02 +00:00
if writeSecondary {
// Write the secondary index if necessary. This is done before the
// primary index because we'd rather have a dangling pointer with
// a missing primary instead of missing the parent index and potentially
// escaping the revocation chain.
if entry . Parent != "" {
// Ensure the parent exists
2018-01-19 06:44:44 +00:00
parent , err := ts . Lookup ( ctx , entry . Parent )
2015-12-30 19:30:02 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to lookup parent: {{err}}" , err )
2015-12-30 19:30:02 +00:00
}
if parent == nil {
return fmt . Errorf ( "parent token not found" )
}
2015-03-18 20:19:19 +00:00
2015-12-30 19:30:02 +00:00
// Create the index entry
2018-03-08 19:21:11 +00:00
parentSaltedID , err := ts . SaltID ( ctx , entry . Parent )
2017-07-18 16:02:03 +00:00
if err != nil {
return err
}
2018-04-03 16:20:20 +00:00
path := parentPrefix + parentSaltedID + "/" + saltedID
2015-12-30 19:30:02 +00:00
le := & logical . StorageEntry { Key : path }
2018-01-19 06:44:44 +00:00
if err := ts . view . Put ( ctx , le ) ; err != nil {
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to persist entry: {{err}}" , err )
2015-12-30 19:30:02 +00:00
}
2015-03-18 20:19:19 +00:00
}
}
// Write the primary ID
2018-04-03 16:20:20 +00:00
path := lookupPrefix + saltedID
2015-03-18 20:19:19 +00:00
le := & logical . StorageEntry { Key : path , Value : enc }
2017-11-06 18:10:36 +00:00
if len ( entry . Policies ) == 1 && entry . Policies [ 0 ] == "root" {
le . SealWrap = true
}
2018-01-19 06:44:44 +00:00
if err := ts . view . Put ( ctx , le ) ; err != nil {
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to persist entry: {{err}}" , err )
2015-03-18 20:19:19 +00:00
}
return nil
}
2016-05-02 07:11:14 +00:00
// UseToken is used to manage restricted use tokens and decrement their
// available uses. Returns two values: a potentially updated entry or, if the
// token has been revoked, nil; and whether an error was encountered. The
// locking here isn't perfect, as other parts of the code may update an entry,
// but usually none after the entry is already created...so this is pretty
// good.
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) UseToken ( ctx context . Context , te * TokenEntry ) ( * TokenEntry , error ) {
2016-05-02 07:11:14 +00:00
if te == nil {
return nil , fmt . Errorf ( "invalid token entry provided for use count decrementing" )
}
2016-05-02 18:57:17 +00:00
// This case won't be hit with a token with restricted uses because we go
// from 1 to -1. So it's a nice optimization to check this without a read
// lock.
2015-04-17 18:51:04 +00:00
if te . NumUses == 0 {
2016-05-02 07:11:14 +00:00
return te , nil
}
2017-11-13 20:31:32 +00:00
// If we are attempting to unwrap a control group request, don't use the token.
// It will be manually revoked by the handler.
if len ( te . Policies ) == 1 && te . Policies [ 0 ] == controlGroupPolicyName {
return te , nil
}
2017-03-07 16:21:32 +00:00
lock := locksutil . LockForKey ( ts . tokenLocks , te . ID )
2016-05-02 07:11:14 +00:00
lock . Lock ( )
defer lock . Unlock ( )
2016-05-02 18:57:17 +00:00
// Call lookupSalted instead of Lookup to avoid deadlocking since Lookup grabs a read lock
2018-03-08 19:21:11 +00:00
saltedID , err := ts . SaltID ( ctx , te . ID )
2017-07-18 16:02:03 +00:00
if err != nil {
return nil , err
}
2018-01-19 06:44:44 +00:00
te , err = ts . lookupSalted ( ctx , saltedID , false )
2016-05-02 07:11:14 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
return nil , errwrap . Wrapf ( "failed to refresh entry: {{err}}" , err )
2016-05-02 07:11:14 +00:00
}
2016-05-16 20:11:33 +00:00
// If it can't be found we shouldn't be trying to use it, so if we get nil
// back, it is because it has been revoked in the interim or will be
// revoked (NumUses is -1)
2016-05-02 07:11:14 +00:00
if te == nil {
2016-05-16 20:11:33 +00:00
return nil , fmt . Errorf ( "token not found or fully used already" )
2015-04-17 18:51:04 +00:00
}
2016-05-02 18:57:17 +00:00
// Decrement the count. If this is our last use count, we need to indicate
// that this is no longer valid, but revocation is deferred to the end of
// the call, so this will make sure that any Lookup that happens doesn't
2016-05-16 20:11:33 +00:00
// return an entry. This essentially acts as a write-ahead lock and is
// especially useful since revocation can end up (via the expiration
// manager revoking children) attempting to acquire the same lock
// repeatedly.
2016-05-02 18:57:17 +00:00
if te . NumUses == 1 {
2016-05-02 07:11:14 +00:00
te . NumUses = - 1
2016-05-02 18:57:17 +00:00
} else {
te . NumUses -= 1
2015-04-17 18:51:04 +00:00
}
2018-01-19 06:44:44 +00:00
err = ts . storeCommon ( ctx , te , false )
2015-04-17 18:51:04 +00:00
if err != nil {
2016-12-16 18:11:55 +00:00
return nil , err
2015-04-17 18:51:04 +00:00
}
2016-05-02 07:11:14 +00:00
return te , nil
2015-04-17 18:51:04 +00:00
}
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) UseTokenByID ( ctx context . Context , id string ) ( * TokenEntry , error ) {
te , err := ts . Lookup ( ctx , id )
2016-09-29 04:01:28 +00:00
if err != nil {
return te , err
}
2018-01-19 06:44:44 +00:00
return ts . UseToken ( ctx , te )
2016-09-29 04:01:28 +00:00
}
2016-05-02 07:11:14 +00:00
// Lookup is used to find a token given its ID. It acquires a read lock, then calls lookupSalted.
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) Lookup ( ctx context . Context , id string ) ( * TokenEntry , error ) {
2015-04-08 23:43:17 +00:00
defer metrics . MeasureSince ( [ ] string { "token" , "lookup" } , time . Now ( ) )
2015-03-18 20:21:16 +00:00
if id == "" {
return nil , fmt . Errorf ( "cannot lookup blank token" )
}
2016-05-02 07:11:14 +00:00
2017-03-07 16:21:32 +00:00
lock := locksutil . LockForKey ( ts . tokenLocks , id )
2016-05-02 07:11:14 +00:00
lock . RLock ( )
defer lock . RUnlock ( )
2018-03-08 19:21:11 +00:00
saltedID , err := ts . SaltID ( ctx , id )
2017-07-18 16:02:03 +00:00
if err != nil {
return nil , err
}
2018-01-19 06:44:44 +00:00
return ts . lookupSalted ( ctx , saltedID , false )
2015-03-18 20:19:19 +00:00
}
2017-11-13 20:31:32 +00:00
// lookupTainted is used to find a token that may or maynot be tainted given its
// ID. It acquires a read lock, then calls lookupSalted.
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) lookupTainted ( ctx context . Context , id string ) ( * TokenEntry , error ) {
2017-11-13 20:31:32 +00:00
defer metrics . MeasureSince ( [ ] string { "token" , "lookup" } , time . Now ( ) )
if id == "" {
return nil , fmt . Errorf ( "cannot lookup blank token" )
}
lock := locksutil . LockForKey ( ts . tokenLocks , id )
lock . RLock ( )
defer lock . RUnlock ( )
2018-03-08 19:21:11 +00:00
saltedID , err := ts . SaltID ( ctx , id )
2017-11-13 20:31:32 +00:00
if err != nil {
return nil , err
}
2018-01-19 06:44:44 +00:00
return ts . lookupSalted ( ctx , saltedID , true )
2017-11-13 20:31:32 +00:00
}
2016-12-16 18:11:55 +00:00
// lookupSalted is used to find a token given its salted ID. If tainted is
// true, entries that are in some revocation state (currently, indicated by num
// uses < 0), the entry will be returned anyways
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) lookupSalted ( ctx context . Context , saltedID string , tainted bool ) ( * TokenEntry , error ) {
2015-03-18 20:19:19 +00:00
// Lookup token
2017-09-05 15:09:00 +00:00
path := lookupPrefix + saltedID
2018-01-19 06:44:44 +00:00
raw , err := ts . view . Get ( ctx , path )
2015-03-18 20:19:19 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
return nil , errwrap . Wrapf ( "failed to read entry: {{err}}" , err )
2015-03-18 20:19:19 +00:00
}
// Bail if not found
if raw == nil {
return nil , nil
}
// Unmarshal the token
entry := new ( TokenEntry )
2016-07-06 16:25:40 +00:00
if err := jsonutil . DecodeJSON ( raw . Value , entry ) ; err != nil {
2018-04-05 15:49:21 +00:00
return nil , errwrap . Wrapf ( "failed to decode entry: {{err}}" , err )
2015-03-18 20:19:19 +00:00
}
2016-05-02 07:11:14 +00:00
2016-12-16 18:11:55 +00:00
// This is a token that is awaiting deferred revocation or tainted
if entry . NumUses < 0 && ! tainted {
2016-05-02 07:11:14 +00:00
return nil , nil
}
2017-09-05 15:09:00 +00:00
// If we are still restoring the expiration manager, we want to ensure the
// token is not expired
2017-09-05 16:01:02 +00:00
if ts . expiration == nil {
return nil , nil
}
2017-09-05 15:09:00 +00:00
check , err := ts . expiration . RestoreSaltedTokenCheck ( entry . Path , saltedID )
if err != nil {
2018-04-05 15:49:21 +00:00
return nil , errwrap . Wrapf ( "failed to check token in restore mode: {{err}}" , err )
2017-09-05 15:09:00 +00:00
}
if ! check {
return nil , nil
}
2016-09-26 17:38:50 +00:00
persistNeeded := false
// Upgrade the deprecated fields
if entry . DisplayNameDeprecated != "" {
2016-09-26 22:17:50 +00:00
if entry . DisplayName == "" {
2016-09-26 17:38:50 +00:00
entry . DisplayName = entry . DisplayNameDeprecated
}
entry . DisplayNameDeprecated = ""
persistNeeded = true
}
if entry . CreationTimeDeprecated != 0 {
if entry . CreationTime == 0 {
entry . CreationTime = entry . CreationTimeDeprecated
}
entry . CreationTimeDeprecated = 0
persistNeeded = true
}
if entry . ExplicitMaxTTLDeprecated != 0 {
if entry . ExplicitMaxTTL == 0 {
entry . ExplicitMaxTTL = entry . ExplicitMaxTTLDeprecated
}
entry . ExplicitMaxTTLDeprecated = 0
persistNeeded = true
}
if entry . NumUsesDeprecated != 0 {
if entry . NumUses == 0 || entry . NumUsesDeprecated < entry . NumUses {
entry . NumUses = entry . NumUsesDeprecated
}
entry . NumUsesDeprecated = 0
persistNeeded = true
}
// If fields are getting upgraded, store the changes
if persistNeeded {
2018-01-19 06:44:44 +00:00
if err := ts . storeCommon ( ctx , entry , false ) ; err != nil {
2018-04-05 15:49:21 +00:00
return nil , errwrap . Wrapf ( "failed to persist token upgrade: {{err}}" , err )
2016-09-26 17:38:50 +00:00
}
}
2015-03-18 20:19:19 +00:00
return entry , nil
}
// Revoke is used to invalidate a given token, any child tokens
// will be orphaned.
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) Revoke ( ctx context . Context , id string ) error {
2015-04-08 23:43:17 +00:00
defer metrics . MeasureSince ( [ ] string { "token" , "revoke" } , time . Now ( ) )
2015-03-18 20:21:16 +00:00
if id == "" {
return fmt . Errorf ( "cannot revoke blank token" )
}
2015-09-10 01:58:09 +00:00
2018-03-08 19:21:11 +00:00
saltedID , err := ts . SaltID ( ctx , id )
2017-07-18 16:02:03 +00:00
if err != nil {
return err
}
2018-01-19 06:44:44 +00:00
return ts . revokeSalted ( ctx , saltedID )
2015-03-18 20:19:19 +00:00
}
// revokeSalted is used to invalidate a given salted token,
// any child tokens will be orphaned.
2018-04-03 16:20:20 +00:00
func ( ts * TokenStore ) revokeSalted ( ctx context . Context , saltedID string ) ( ret error ) {
2016-12-16 18:11:55 +00:00
// Protect the entry lookup/writing with locks. The rub here is that we
// don't know the ID until we look it up once, so first we look it up, then
// do a locked lookup.
2018-04-03 16:20:20 +00:00
entry , err := ts . lookupSalted ( ctx , saltedID , true )
2016-12-16 18:11:55 +00:00
if err != nil {
return err
}
if entry == nil {
return nil
}
2017-03-07 16:21:32 +00:00
lock := locksutil . LockForKey ( ts . tokenLocks , entry . ID )
2016-12-16 18:11:55 +00:00
lock . Lock ( )
2015-03-18 20:19:19 +00:00
// Lookup the token first
2018-04-03 16:20:20 +00:00
entry , err = ts . lookupSalted ( ctx , saltedID , true )
2015-03-18 20:19:19 +00:00
if err != nil {
2016-12-16 18:11:55 +00:00
lock . Unlock ( )
2015-03-18 20:19:19 +00:00
return err
}
2016-12-16 18:11:55 +00:00
if entry == nil {
lock . Unlock ( )
return nil
}
// On failure we write -3, so if we hit -2 here we're already running a
// revocation operation. This can happen due to e.g. recursion into this
// function via the expiration manager's RevokeByToken.
if entry . NumUses == tokenRevocationInProgress {
lock . Unlock ( )
return nil
}
// This acts as a WAL. lookupSalted will no longer return this entry,
// so the token cannot be used, but this way we can keep the entry
// around until after the rest of this function is attempted, and a
2016-12-16 20:29:27 +00:00
// tidy function can key off of this value to try again.
2016-12-16 18:11:55 +00:00
entry . NumUses = tokenRevocationInProgress
2018-01-19 06:44:44 +00:00
err = ts . storeCommon ( ctx , entry , false )
2016-12-16 18:11:55 +00:00
lock . Unlock ( )
if err != nil {
return err
}
// If we are returning an error, mark the entry with -3 to indicate
// failed revocation. This way we don't try to clean up during active
// revocation (-2).
defer func ( ) {
if ret != nil {
lock . Lock ( )
defer lock . Unlock ( )
// Lookup the token again to make sure something else didn't
// revoke in the interim
2018-04-03 16:20:20 +00:00
entry , err := ts . lookupSalted ( ctx , saltedID , true )
2016-12-16 18:11:55 +00:00
if err != nil {
return
}
// If it exists just taint to -3 rather than trying to figure
// out what it means if it's already -3 after the -2 above
if entry != nil {
entry . NumUses = tokenRevocationFailed
2018-01-19 06:44:44 +00:00
ts . storeCommon ( ctx , entry , false )
2016-12-16 18:11:55 +00:00
}
}
} ( )
// Destroy the token's cubby. This should go first as it's a
// security-sensitive item.
2018-04-03 16:20:20 +00:00
err = ts . cubbyholeDestroyer ( ctx , ts , saltedID )
2016-12-16 18:11:55 +00:00
if err != nil {
return err
}
// Revoke all secrets under this token. This should go first as it's a
// security-sensitive item.
if err := ts . expiration . RevokeByToken ( entry ) ; err != nil {
return err
2015-03-18 20:19:19 +00:00
}
// Clear the secondary index if any
2016-12-16 18:11:55 +00:00
if entry . Parent != "" {
2018-03-08 19:21:11 +00:00
parentSaltedID , err := ts . SaltID ( ctx , entry . Parent )
2017-07-18 16:02:03 +00:00
if err != nil {
return err
}
2018-04-03 16:20:20 +00:00
path := parentPrefix + parentSaltedID + "/" + saltedID
2018-01-19 06:44:44 +00:00
if err = ts . view . Delete ( ctx , path ) ; err != nil {
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to delete entry: {{err}}" , err )
2015-03-18 20:19:19 +00:00
}
}
2015-04-10 22:12:04 +00:00
2016-03-09 14:05:04 +00:00
// Clear the accessor index if any
2016-12-16 18:11:55 +00:00
if entry . Accessor != "" {
2018-03-08 19:21:11 +00:00
accessorSaltedID , err := ts . SaltID ( ctx , entry . Accessor )
2017-07-18 16:02:03 +00:00
if err != nil {
return err
}
path := accessorPrefix + accessorSaltedID
2018-01-19 06:44:44 +00:00
if err = ts . view . Delete ( ctx , path ) ; err != nil {
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to delete entry: {{err}}" , err )
2016-03-08 19:04:20 +00:00
}
}
2018-03-27 15:12:06 +00:00
// Mark all children token as orphan by removing
// their parent index, and clear the parent entry.
//
// Marking the token as orphan is the correct behavior in here since
// revokeTreeSalted will ensure that they are deleted anyways if it's not an
// explicit call to orphan the child tokens (the delete occurs at the leaf
// node and uses parent prefix, not entry.Parent, to build the tree for
// traversal).
2018-04-03 16:20:20 +00:00
parentPath := parentPrefix + saltedID + "/"
2018-03-27 15:12:06 +00:00
children , err := ts . view . List ( ctx , parentPath )
if err != nil {
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to scan for children: {{err}}" , err )
2018-03-27 15:12:06 +00:00
}
for _ , child := range children {
entry , err := ts . lookupSalted ( ctx , child , true )
if err != nil {
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to get child token: {{err}}" , err )
2018-03-27 15:12:06 +00:00
}
lock := locksutil . LockForKey ( ts . tokenLocks , entry . ID )
lock . Lock ( )
entry . Parent = ""
err = ts . store ( ctx , entry )
if err != nil {
lock . Unlock ( )
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to update child token: {{err}}" , err )
2018-03-27 15:12:06 +00:00
}
lock . Unlock ( )
}
if err = logical . ClearView ( ctx , ts . view . SubView ( parentPath ) ) ; err != nil {
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to delete entry: {{err}}" , err )
2018-03-27 15:12:06 +00:00
}
2016-12-16 18:11:55 +00:00
// Now that the entry is not usable for any revocation tasks, nuke it
2018-04-03 16:20:20 +00:00
path := lookupPrefix + saltedID
2018-01-19 06:44:44 +00:00
if err = ts . view . Delete ( ctx , path ) ; err != nil {
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to delete entry: {{err}}" , err )
2015-09-10 01:58:09 +00:00
}
2015-03-18 20:19:19 +00:00
return nil
}
2018-03-20 18:54:10 +00:00
// RevokeTree is used to invalidate a given token and all
2015-03-18 20:19:19 +00:00
// child tokens.
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) RevokeTree ( ctx context . Context , id string ) error {
2015-04-08 23:43:17 +00:00
defer metrics . MeasureSince ( [ ] string { "token" , "revoke-tree" } , time . Now ( ) )
2015-03-18 20:21:16 +00:00
// Verify the token is not blank
if id == "" {
2017-04-26 18:06:45 +00:00
return fmt . Errorf ( "cannot tree-revoke blank token" )
2015-03-18 20:21:16 +00:00
}
2015-03-18 20:19:19 +00:00
// Get the salted ID
2018-04-03 16:20:20 +00:00
saltedID , err := ts . SaltID ( ctx , id )
2017-07-18 16:02:03 +00:00
if err != nil {
return err
}
2015-03-18 20:19:19 +00:00
2015-04-10 22:06:54 +00:00
// Nuke the entire tree recursively
2018-04-03 16:20:20 +00:00
return ts . revokeTreeSalted ( ctx , saltedID )
2015-03-18 20:19:19 +00:00
}
2017-12-11 21:51:37 +00:00
// revokeTreeSalted is used to invalidate a given token and all
2015-03-18 20:19:19 +00:00
// child tokens using a saltedID.
2017-12-11 21:51:37 +00:00
// Updated to be non-recursive and revoke child tokens
// before parent tokens(DFS).
2018-04-03 16:20:20 +00:00
func ( ts * TokenStore ) revokeTreeSalted ( ctx context . Context , saltedID string ) error {
2017-12-11 21:51:37 +00:00
var dfs [ ] string
2018-04-03 16:20:20 +00:00
dfs = append ( dfs , saltedID )
2015-03-18 20:19:19 +00:00
2017-12-11 21:51:37 +00:00
for l := len ( dfs ) ; l > 0 ; l = len ( dfs ) {
id := dfs [ 0 ]
path := parentPrefix + id + "/"
2018-01-19 06:44:44 +00:00
children , err := ts . view . List ( ctx , path )
2017-12-11 21:51:37 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to scan for children: {{err}}" , err )
2017-12-11 21:51:37 +00:00
}
// If the length of the children array is zero,
// then we are at a leaf node.
if len ( children ) == 0 {
2018-01-19 06:44:44 +00:00
if err := ts . revokeSalted ( ctx , id ) ; err != nil {
2018-04-05 15:49:21 +00:00
return errwrap . Wrapf ( "failed to revoke entry: {{err}}" , err )
2017-12-11 21:51:37 +00:00
}
// If the length of l is equal to 1, then the last token has been deleted
if l == 1 {
return nil
}
dfs = dfs [ 1 : ]
} else {
// If we make it here, there are children and they must
// be prepended.
dfs = append ( children , dfs ... )
2015-03-18 20:19:19 +00:00
}
}
return nil
}
2016-03-01 20:30:37 +00:00
// handleCreateAgainstRole handles the auth/token/create path for a role
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) handleCreateAgainstRole ( ctx context . Context , req * logical . Request , d * framework . FieldData ) ( * logical . Response , error ) {
2016-02-29 18:27:31 +00:00
name := d . Get ( "role_name" ) . ( string )
2018-01-19 06:44:44 +00:00
roleEntry , err := ts . tokenStoreRole ( ctx , name )
2016-02-29 18:27:31 +00:00
if err != nil {
return nil , err
}
if roleEntry == nil {
return logical . ErrorResponse ( fmt . Sprintf ( "unknown role %s" , name ) ) , nil
}
2018-01-19 06:44:44 +00:00
return ts . handleCreateCommon ( ctx , req , d , false , roleEntry )
2016-02-29 18:27:31 +00:00
}
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) lookupByAccessor ( ctx context . Context , accessor string , tainted bool ) ( accessorEntry , error ) {
2018-03-08 19:21:11 +00:00
saltedID , err := ts . SaltID ( ctx , accessor )
2017-07-18 16:02:03 +00:00
if err != nil {
return accessorEntry { } , err
}
2018-01-19 06:44:44 +00:00
return ts . lookupBySaltedAccessor ( ctx , saltedID , tainted )
2016-07-29 22:20:38 +00:00
}
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) lookupBySaltedAccessor ( ctx context . Context , saltedAccessor string , tainted bool ) ( accessorEntry , error ) {
entry , err := ts . view . Get ( ctx , accessorPrefix + saltedAccessor )
2016-07-29 22:20:38 +00:00
var aEntry accessorEntry
2016-03-08 23:07:27 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
return aEntry , errwrap . Wrapf ( "failed to read index using accessor: {{err}}" , err )
2016-03-08 23:07:27 +00:00
}
if entry == nil {
2017-02-17 04:09:39 +00:00
return aEntry , & logical . StatusBadRequest { Err : "invalid accessor" }
2016-07-29 22:20:38 +00:00
}
err = jsonutil . DecodeJSON ( entry . Value , & aEntry )
// If we hit an error, assume it's a pre-struct straight token ID
if err != nil {
2018-03-08 19:21:11 +00:00
saltedID , err := ts . SaltID ( ctx , string ( entry . Value ) )
2017-07-18 16:02:03 +00:00
if err != nil {
return accessorEntry { } , err
}
2018-01-19 06:44:44 +00:00
te , err := ts . lookupSalted ( ctx , saltedID , tainted )
2016-07-29 22:20:38 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
return accessorEntry { } , errwrap . Wrapf ( "failed to look up token using accessor index: {{err}}" , err )
2016-07-29 22:20:38 +00:00
}
2016-08-01 17:07:41 +00:00
// It's hard to reason about what to do here -- it may be that the
// token was revoked async, or that it's an old accessor index entry
// that was somehow not cleared up, or or or. A nonexistent token entry
// on lookup is nil, not an error, so we keep that behavior here to be
// safe...the token ID is simply not filled in.
if te != nil {
2017-05-03 16:36:10 +00:00
aEntry . TokenID = te . ID
2016-08-01 17:07:41 +00:00
aEntry . AccessorID = te . Accessor
}
2016-03-08 23:07:27 +00:00
}
2016-07-29 22:20:38 +00:00
return aEntry , nil
2016-03-08 23:07:27 +00:00
}
2016-12-16 20:29:27 +00:00
// handleTidy handles the cleaning up of leaked accessor storage entries and
// cleaning up of leases that are associated to tokens that are expired.
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) handleTidy ( ctx context . Context , req * logical . Request , data * framework . FieldData ) ( * logical . Response , error ) {
2016-12-16 20:29:27 +00:00
var tidyErrors * multierror . Error
2017-04-27 17:48:29 +00:00
if ! atomic . CompareAndSwapInt64 ( & ts . tidyLock , 0 , 1 ) {
2018-04-03 00:46:59 +00:00
ts . logger . Warn ( "tidy operation on tokens is already in progress" )
2017-04-27 17:48:29 +00:00
return nil , fmt . Errorf ( "tidy operation on tokens is already in progress" )
}
2016-12-16 20:29:27 +00:00
2017-04-27 17:48:29 +00:00
defer atomic . CompareAndSwapInt64 ( & ts . tidyLock , 1 , 0 )
2016-12-16 20:29:27 +00:00
2018-04-03 00:46:59 +00:00
ts . logger . Info ( "beginning tidy operation on tokens" )
defer ts . logger . Info ( "finished tidy operation on tokens" )
2017-05-05 14:48:12 +00:00
2017-04-27 17:48:29 +00:00
// List out all the accessors
2018-01-19 06:44:44 +00:00
saltedAccessorList , err := ts . view . List ( ctx , accessorPrefix )
2017-04-27 17:48:29 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
return nil , errwrap . Wrapf ( "failed to fetch accessor index entries: {{err}}" , err )
2017-04-27 17:48:29 +00:00
}
2017-04-27 15:20:36 +00:00
2017-04-27 17:48:29 +00:00
// First, clean up secondary index entries that are no longer valid
2018-01-19 06:44:44 +00:00
parentList , err := ts . view . List ( ctx , parentPrefix )
2017-04-27 17:48:29 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
return nil , errwrap . Wrapf ( "failed to fetch secondary index entries: {{err}}" , err )
2017-04-27 17:48:29 +00:00
}
2017-04-27 15:41:33 +00:00
2018-03-27 15:12:06 +00:00
var countParentEntries , deletedCountParentEntries , countParentList , deletedCountParentList int64
2017-04-27 15:41:33 +00:00
2017-04-27 17:48:29 +00:00
// Scan through the secondary index entries; if there is an entry
// with the token's salt ID at the end, remove it
for _ , parent := range parentList {
2018-03-27 15:12:06 +00:00
countParentEntries ++
// Get the children
2018-01-19 06:44:44 +00:00
children , err := ts . view . List ( ctx , parentPrefix + parent )
2017-04-27 17:48:29 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
tidyErrors = multierror . Append ( tidyErrors , errwrap . Wrapf ( "failed to read secondary index: {{err}}" , err ) )
2017-04-27 17:48:29 +00:00
continue
2016-12-16 20:29:27 +00:00
}
2018-03-27 15:12:06 +00:00
// First check if the salt ID of the parent exists, and if not mark this so
// that deletion of children later with this loop below applies to all
// children
originalChildrenCount := int64 ( len ( children ) )
exists , _ := ts . lookupSalted ( ctx , strings . TrimSuffix ( parent , "/" ) , true )
if exists == nil {
2018-04-03 00:46:59 +00:00
ts . logger . Debug ( "deleting invalid parent prefix entry" , "index" , parentPrefix + parent )
2018-03-27 15:12:06 +00:00
}
var deletedChildrenCount int64
2017-04-27 17:48:29 +00:00
for _ , child := range children {
2017-05-03 14:54:07 +00:00
countParentList ++
if countParentList % 500 == 0 {
2018-04-03 00:46:59 +00:00
ts . logger . Info ( "checking validity of tokens in secondary index list" , "progress" , countParentList )
2016-12-16 20:29:27 +00:00
}
2017-04-27 17:48:29 +00:00
// Look up tainted entries so we can be sure that if this isn't
// found, it doesn't exist. Doing the following without locking
// since appropriate locks cannot be held with salted token IDs.
2018-03-27 15:12:06 +00:00
// Also perform deletion if the parent doesn't exist any more.
2018-01-19 06:44:44 +00:00
te , _ := ts . lookupSalted ( ctx , child , true )
2018-03-27 15:12:06 +00:00
// If the child entry is not nil, but the parent doesn't exist, then turn
// that child token into an orphan token. Theres no deletion in this case.
if te != nil && exists == nil {
lock := locksutil . LockForKey ( ts . tokenLocks , te . ID )
lock . Lock ( )
te . Parent = ""
err = ts . store ( ctx , te )
if err != nil {
2018-04-05 15:49:21 +00:00
tidyErrors = multierror . Append ( tidyErrors , errwrap . Wrapf ( "failed to convert child token into an orphan token: {{err}}" , err ) )
2018-03-27 15:12:06 +00:00
}
lock . Unlock ( )
continue
}
// Otherwise, if the entry doesn't exist, or if the parent doesn't exist go
// on with the delete on the secondary index
if te == nil || exists == nil {
2017-05-03 19:09:13 +00:00
index := parentPrefix + parent + child
2018-04-03 00:46:59 +00:00
ts . logger . Debug ( "deleting invalid secondary index" , "index" , index )
2018-01-19 06:44:44 +00:00
err = ts . view . Delete ( ctx , index )
2017-04-27 15:41:33 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
tidyErrors = multierror . Append ( tidyErrors , errwrap . Wrapf ( "failed to delete secondary index: {{err}}" , err ) )
2018-03-27 15:12:06 +00:00
continue
2017-04-27 15:41:33 +00:00
}
2018-03-27 15:12:06 +00:00
deletedChildrenCount ++
2017-04-27 15:41:33 +00:00
}
2017-04-27 17:48:29 +00:00
}
2018-03-27 15:12:06 +00:00
// Add current children deleted count to the total count
deletedCountParentList += deletedChildrenCount
// N.B.: We don't call delete on the parent prefix since physical.Backend.Delete
// implementations should be in charge of deleting empty prefixes.
// If we deleted all the children, then add that to our deleted parent entries count.
if originalChildrenCount == deletedChildrenCount {
deletedCountParentEntries ++
}
2017-04-27 17:48:29 +00:00
}
2017-04-27 15:41:33 +00:00
2017-05-05 14:48:12 +00:00
var countAccessorList ,
deletedCountAccessorEmptyToken ,
deletedCountAccessorInvalidToken ,
deletedCountInvalidTokenInAccessor int64
2017-05-03 14:54:07 +00:00
2017-04-27 17:48:29 +00:00
// For each of the accessor, see if the token ID associated with it is
// a valid one. If not, delete the leases associated with that token
// and delete the accessor as well.
for _ , saltedAccessor := range saltedAccessorList {
2017-05-03 14:54:07 +00:00
countAccessorList ++
if countAccessorList % 500 == 0 {
2018-04-03 00:46:59 +00:00
ts . logger . Info ( "checking if accessors contain valid tokens" , "progress" , countAccessorList )
2017-04-27 17:48:29 +00:00
}
2017-04-27 15:41:33 +00:00
2018-01-19 06:44:44 +00:00
accessorEntry , err := ts . lookupBySaltedAccessor ( ctx , saltedAccessor , true )
2017-04-27 17:48:29 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
tidyErrors = multierror . Append ( tidyErrors , errwrap . Wrapf ( "failed to read the accessor index: {{err}}" , err ) )
2017-04-27 17:48:29 +00:00
continue
}
2017-04-27 15:41:33 +00:00
2017-04-27 17:48:29 +00:00
// A valid accessor storage entry should always have a token ID
// in it. If not, it is an invalid accessor entry and needs to
// be deleted.
if accessorEntry . TokenID == "" {
2017-05-03 16:58:10 +00:00
index := accessorPrefix + saltedAccessor
2017-04-27 17:48:29 +00:00
// If deletion of accessor fails, move on to the next
// item since this is just a best-effort operation
2018-01-19 06:44:44 +00:00
err = ts . view . Delete ( ctx , index )
2017-04-27 17:48:29 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
tidyErrors = multierror . Append ( tidyErrors , errwrap . Wrapf ( "failed to delete the accessor index: {{err}}" , err ) )
2017-04-27 17:48:29 +00:00
continue
}
2017-05-03 14:54:07 +00:00
deletedCountAccessorEmptyToken ++
2017-04-27 17:48:29 +00:00
}
2017-04-27 15:41:33 +00:00
2017-04-27 17:48:29 +00:00
lock := locksutil . LockForKey ( ts . tokenLocks , accessorEntry . TokenID )
lock . RLock ( )
// Look up tainted variants so we only find entries that truly don't
// exist
2018-04-03 16:20:20 +00:00
saltedID , err := ts . SaltID ( ctx , accessorEntry . TokenID )
2017-07-18 16:02:03 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
tidyErrors = multierror . Append ( tidyErrors , errwrap . Wrapf ( "failed to read salt id: {{err}}" , err ) )
2017-07-18 16:02:03 +00:00
lock . RUnlock ( )
continue
}
2018-04-03 16:20:20 +00:00
te , err := ts . lookupSalted ( ctx , saltedID , true )
2017-07-26 16:15:54 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
tidyErrors = multierror . Append ( tidyErrors , errwrap . Wrapf ( "failed to lookup tainted ID: {{err}}" , err ) )
2017-07-26 16:15:54 +00:00
lock . RUnlock ( )
continue
}
2017-04-27 17:48:29 +00:00
lock . RUnlock ( )
// If token entry is not found assume that the token is not valid any
// more and conclude that accessor, leases, and secondary index entries
// for this token should not exist as well.
if te == nil {
2018-04-03 16:20:20 +00:00
ts . logger . Info ( "deleting token with nil entry" , "salted_token" , saltedID )
2017-04-27 17:48:29 +00:00
// RevokeByToken expects a '*TokenEntry'. For the
// purposes of tidying, it is sufficient if the token
// entry only has ID set.
tokenEntry := & TokenEntry {
ID : accessorEntry . TokenID ,
}
2017-04-27 15:41:33 +00:00
2017-04-27 17:48:29 +00:00
// Attempt to revoke the token. This will also revoke
// the leases associated with the token.
err := ts . expiration . RevokeByToken ( tokenEntry )
if err != nil {
2018-04-05 15:49:21 +00:00
tidyErrors = multierror . Append ( tidyErrors , errwrap . Wrapf ( "failed to revoke leases of expired token: {{err}}" , err ) )
2017-04-27 17:48:29 +00:00
continue
}
2017-05-03 14:54:07 +00:00
deletedCountInvalidTokenInAccessor ++
2017-04-27 15:41:33 +00:00
2017-05-03 16:58:10 +00:00
index := accessorPrefix + saltedAccessor
2017-04-27 17:48:29 +00:00
// If deletion of accessor fails, move on to the next item since
// this is just a best-effort operation. We do this last so that on
// next run if something above failed we still have the accessor
// entry to try again.
2018-01-19 06:44:44 +00:00
err = ts . view . Delete ( ctx , index )
2017-04-27 17:48:29 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
tidyErrors = multierror . Append ( tidyErrors , errwrap . Wrapf ( "failed to delete accessor entry: {{err}}" , err ) )
2017-04-27 17:48:29 +00:00
continue
2016-12-16 20:29:27 +00:00
}
2017-05-03 14:54:07 +00:00
deletedCountAccessorInvalidToken ++
2016-12-16 20:29:27 +00:00
}
}
2018-04-03 00:46:59 +00:00
ts . logger . Info ( "number of entries scanned in parent prefix" , "count" , countParentEntries )
ts . logger . Info ( "number of entries deleted in parent prefix" , "count" , deletedCountParentEntries )
ts . logger . Info ( "number of tokens scanned in parent index list" , "count" , countParentList )
ts . logger . Info ( "number of tokens revoked in parent index list" , "count" , deletedCountParentList )
ts . logger . Info ( "number of accessors scanned" , "count" , countAccessorList )
ts . logger . Info ( "number of deleted accessors which had empty tokens" , "count" , deletedCountAccessorEmptyToken )
ts . logger . Info ( "number of revoked tokens which were invalid but present in accessors" , "count" , deletedCountInvalidTokenInAccessor )
ts . logger . Info ( "number of deleted accessors which had invalid tokens" , "count" , deletedCountAccessorInvalidToken )
2017-05-03 14:54:07 +00:00
2017-04-27 17:48:29 +00:00
return nil , tidyErrors . ErrorOrNil ( )
2016-12-16 20:29:27 +00:00
}
2016-03-09 14:48:32 +00:00
// handleUpdateLookupAccessor handles the auth/token/lookup-accessor path for returning
2016-03-09 14:05:04 +00:00
// the properties of the token associated with the accessor
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) handleUpdateLookupAccessor ( ctx context . Context , req * logical . Request , data * framework . FieldData ) ( * logical . Response , error ) {
2016-08-29 19:15:57 +00:00
var urlaccessor bool
2016-03-09 11:23:31 +00:00
accessor := data . Get ( "accessor" ) . ( string )
if accessor == "" {
2016-04-28 19:15:37 +00:00
accessor = data . Get ( "urlaccessor" ) . ( string )
if accessor == "" {
2017-02-17 04:09:39 +00:00
return nil , & logical . StatusBadRequest { Err : "missing accessor" }
2016-04-28 19:15:37 +00:00
}
2016-08-29 19:15:57 +00:00
urlaccessor = true
2016-03-08 22:38:19 +00:00
}
2018-01-19 06:44:44 +00:00
aEntry , err := ts . lookupByAccessor ( ctx , accessor , false )
2016-03-08 22:38:19 +00:00
if err != nil {
2016-03-08 23:07:27 +00:00
return nil , err
2016-03-08 22:38:19 +00:00
}
// Prepare the field data required for a lookup call
d := & framework . FieldData {
Raw : map [ string ] interface { } {
2016-07-29 22:20:38 +00:00
"token" : aEntry . TokenID ,
2016-03-08 22:38:19 +00:00
} ,
Schema : map [ string ] * framework . FieldSchema {
"token" : & framework . FieldSchema {
Type : framework . TypeString ,
Description : "Token to lookup" ,
} ,
} ,
}
2018-01-08 18:31:38 +00:00
resp , err := ts . handleLookup ( ctx , req , d )
2016-03-08 22:38:19 +00:00
if err != nil {
return nil , err
}
if resp == nil {
return nil , fmt . Errorf ( "failed to lookup the token" )
}
if resp . IsError ( ) {
return resp , nil
}
// Remove the token ID from the response
2016-03-09 14:05:04 +00:00
if resp . Data != nil {
2016-03-08 22:38:19 +00:00
resp . Data [ "id" ] = ""
}
2016-08-29 19:15:57 +00:00
if urlaccessor {
resp . AddWarning ( ` Using an accessor in the path is unsafe as the accessor can be logged in many places. Please use POST or PUT with the accessor passed in via the "accessor" parameter. ` )
}
2016-03-08 22:38:19 +00:00
return resp , nil
2016-03-08 20:13:29 +00:00
}
2016-03-09 14:48:32 +00:00
// handleUpdateRevokeAccessor handles the auth/token/revoke-accessor path for revoking
2016-03-09 14:05:04 +00:00
// the token associated with the accessor
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) handleUpdateRevokeAccessor ( ctx context . Context , req * logical . Request , data * framework . FieldData ) ( * logical . Response , error ) {
2016-08-29 19:15:57 +00:00
var urlaccessor bool
2016-03-09 11:23:31 +00:00
accessor := data . Get ( "accessor" ) . ( string )
if accessor == "" {
2016-04-28 19:15:37 +00:00
accessor = data . Get ( "urlaccessor" ) . ( string )
if accessor == "" {
2017-02-17 04:09:39 +00:00
return nil , & logical . StatusBadRequest { Err : "missing accessor" }
2016-04-28 19:15:37 +00:00
}
2016-08-29 19:15:57 +00:00
urlaccessor = true
2016-03-08 23:07:27 +00:00
}
2018-01-19 06:44:44 +00:00
aEntry , err := ts . lookupByAccessor ( ctx , accessor , true )
2016-03-08 23:07:27 +00:00
if err != nil {
return nil , err
}
// Revoke the token and its children
2018-01-19 06:44:44 +00:00
if err := ts . RevokeTree ( ctx , aEntry . TokenID ) ; err != nil {
2016-03-08 23:07:27 +00:00
return logical . ErrorResponse ( err . Error ( ) ) , logical . ErrInvalidRequest
}
2016-08-29 19:15:57 +00:00
if urlaccessor {
resp := & logical . Response { }
resp . AddWarning ( ` Using an accessor in the path is unsafe as the accessor can be logged in many places. Please use POST or PUT with the accessor passed in via the "accessor" parameter. ` )
return resp , nil
}
2016-03-08 20:13:29 +00:00
return nil , nil
}
2015-11-03 20:10:46 +00:00
// handleCreate handles the auth/token/create path for creation of new orphan
// tokens
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) handleCreateOrphan ( ctx context . Context , req * logical . Request , d * framework . FieldData ) ( * logical . Response , error ) {
2018-01-19 06:44:44 +00:00
return ts . handleCreateCommon ( ctx , req , d , true , nil )
2015-11-03 20:10:46 +00:00
}
// handleCreate handles the auth/token/create path for creation of new non-orphan
// tokens
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) handleCreate ( ctx context . Context , req * logical . Request , d * framework . FieldData ) ( * logical . Response , error ) {
2018-01-19 06:44:44 +00:00
return ts . handleCreateCommon ( ctx , req , d , false , nil )
2015-11-03 20:10:46 +00:00
}
// handleCreateCommon handles the auth/token/create path for creation of new tokens
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) handleCreateCommon ( ctx context . Context , req * logical . Request , d * framework . FieldData , orphan bool , role * tsRoleEntry ) ( * logical . Response , error ) {
2015-03-24 22:10:46 +00:00
// Read the parent policy
2018-01-19 06:44:44 +00:00
parent , err := ts . Lookup ( ctx , req . ClientToken )
2015-03-24 22:10:46 +00:00
if err != nil || parent == nil {
return logical . ErrorResponse ( "parent token lookup failed" ) , logical . ErrInvalidRequest
}
2015-04-17 18:34:25 +00:00
// A token with a restricted number of uses cannot create a new token
// otherwise it could escape the restriction count.
if parent . NumUses > 0 {
return logical . ErrorResponse ( "restricted use token cannot generate child tokens" ) ,
logical . ErrInvalidRequest
}
2015-09-21 14:04:03 +00:00
// Check if the client token has sudo/root privileges for the requested path
2018-01-19 06:44:44 +00:00
isSudo := ts . System ( ) . SudoPrivilege ( ctx , req . MountPoint + req . Path , req . ClientToken )
2015-03-24 22:10:46 +00:00
// Read and parse the fields
2015-04-07 21:16:35 +00:00
var data struct {
2015-11-09 22:30:50 +00:00
ID string
Policies [ ] string
Metadata map [ string ] string ` mapstructure:"meta" `
NoParent bool ` mapstructure:"no_parent" `
NoDefaultPolicy bool ` mapstructure:"no_default_policy" `
Lease string
TTL string
2016-06-08 15:14:30 +00:00
Renewable * bool
2016-06-08 18:49:48 +00:00
ExplicitMaxTTL string ` mapstructure:"explicit_max_ttl" `
2015-11-09 22:30:50 +00:00
DisplayName string ` mapstructure:"display_name" `
NumUses int ` mapstructure:"num_uses" `
2016-08-13 01:01:30 +00:00
Period string
2015-04-07 21:16:35 +00:00
}
if err := mapstructure . WeakDecode ( req . Data , & data ) ; err != nil {
return logical . ErrorResponse ( fmt . Sprintf (
"Error decoding request: %s" , err ) ) , logical . ErrInvalidRequest
}
2015-03-24 22:10:46 +00:00
2015-04-17 18:34:25 +00:00
// Verify the number of uses is positive
if data . NumUses < 0 {
return logical . ErrorResponse ( "number of uses cannot be negative" ) ,
logical . ErrInvalidRequest
}
2015-03-24 22:10:46 +00:00
// Setup the token entry
te := TokenEntry {
2016-04-07 15:39:46 +00:00
Parent : req . ClientToken ,
// The mount point is always the same since we have only one token
// store; using req.MountPoint causes trouble in tests since they don't
// have an official mount
Path : fmt . Sprintf ( "auth/token/%s" , req . Path ) ,
2015-09-18 20:33:52 +00:00
Meta : data . Metadata ,
DisplayName : "token" ,
NumUses : data . NumUses ,
CreationTime : time . Now ( ) . Unix ( ) ,
2015-04-15 21:24:07 +00:00
}
2016-06-08 15:14:30 +00:00
renewable := true
if data . Renewable != nil {
renewable = * data . Renewable
}
2016-03-07 15:07:04 +00:00
// If the role is not nil, we add the role name as part of the token's
// path. This makes it much easier to later revoke tokens that were issued
// by a role (using revoke-prefix). Users can further specify a PathSuffix
// in the role; that way they can use something like "v1", "v2" to indicate
// role revisions, and revoke only tokens issued with a previous revision.
2016-02-29 18:27:31 +00:00
if role != nil {
te . Role = role . Name
2016-06-08 19:17:22 +00:00
// If renewable hasn't been disabled in the call and the role has
// renewability disabled, set renewable false
if renewable && ! role . Renewable {
renewable = false
}
2016-03-01 20:30:37 +00:00
if role . PathSuffix != "" {
te . Path = fmt . Sprintf ( "%s/%s" , te . Path , role . PathSuffix )
2016-02-29 18:27:31 +00:00
}
}
2015-04-15 21:24:07 +00:00
// Attach the given display name if any
if data . DisplayName != "" {
full := "token-" + data . DisplayName
full = displayNameSanitize . ReplaceAllString ( full , "-" )
full = strings . TrimSuffix ( full , "-" )
te . DisplayName = full
2015-03-24 22:10:46 +00:00
}
2015-09-18 23:59:06 +00:00
// Allow specifying the ID of the token if the client has root or sudo privileges
2015-04-07 21:16:35 +00:00
if data . ID != "" {
2015-09-18 23:59:06 +00:00
if ! isSudo {
return logical . ErrorResponse ( "root or sudo privileges required to specify token id" ) ,
2015-03-24 22:10:46 +00:00
logical . ErrInvalidRequest
}
2015-04-07 21:16:35 +00:00
te . ID = data . ID
2015-03-24 22:10:46 +00:00
}
2016-08-02 14:33:50 +00:00
resp := & logical . Response { }
2016-12-16 05:36:39 +00:00
var addDefault bool
// N.B.: The logic here uses various calculations as to whether default
// should be added. In the end we decided that if NoDefaultPolicy is set it
// should be stripped out regardless, *but*, the logic of when it should
// and shouldn't be added is kept because we want to do subset comparisons
// based on adding default when it's correct to do so.
2016-02-29 18:27:31 +00:00
switch {
2016-12-16 05:36:39 +00:00
case role != nil && ( len ( role . AllowedPolicies ) > 0 || len ( role . DisallowedPolicies ) > 0 ) :
// Holds the final set of policies as they get munged
var finalPolicies [ ] string
// We don't make use of the global one because roles with allowed or
// disallowed set do their own policy rules
var localAddDefault bool
// If the request doesn't say not to add "default" and if "default"
// isn't in the disallowed list, add it. This is in line with the idea
// that roles, when allowed/disallowed ar set, allow a subset of
// policies to be set disjoint from the parent token's policies.
if ! data . NoDefaultPolicy && ! strutil . StrListContains ( role . DisallowedPolicies , "default" ) {
localAddDefault = true
2016-08-02 14:33:50 +00:00
}
2016-05-11 20:51:18 +00:00
2016-12-16 05:36:39 +00:00
// Start with passed-in policies as a baseline, if they exist
if len ( data . Policies ) > 0 {
finalPolicies = policyutil . SanitizePolicies ( data . Policies , localAddDefault )
2016-02-29 18:27:31 +00:00
}
2016-12-16 05:36:39 +00:00
var sanitizedRolePolicies [ ] string
// First check allowed policies; if policies are specified they will be
// checked, otherwise if an allowed set exists that will be the set
// that is used
if len ( role . AllowedPolicies ) > 0 {
// Note that if "default" is already in allowed, and also in
// disallowed, this will still result in an error later since this
// doesn't strip out default
sanitizedRolePolicies = policyutil . SanitizePolicies ( role . AllowedPolicies , localAddDefault )
if len ( finalPolicies ) == 0 {
finalPolicies = sanitizedRolePolicies
} else {
if ! strutil . StrListSubset ( sanitizedRolePolicies , finalPolicies ) {
return logical . ErrorResponse ( fmt . Sprintf ( "token policies (%v) must be subset of the role's allowed policies (%v)" , finalPolicies , sanitizedRolePolicies ) ) , logical . ErrInvalidRequest
}
}
} else {
2017-01-18 21:11:25 +00:00
// Assign parent policies if none have been requested. As this is a
// role, add default unless explicitly disabled.
2016-12-16 05:36:39 +00:00
if len ( finalPolicies ) == 0 {
finalPolicies = policyutil . SanitizePolicies ( parent . Policies , localAddDefault )
}
2016-08-02 14:33:50 +00:00
}
2016-12-16 05:36:39 +00:00
if len ( role . DisallowedPolicies ) > 0 {
// We don't add the default here because we only want to disallow it if it's explicitly set
2017-04-04 15:54:18 +00:00
sanitizedRolePolicies = strutil . RemoveDuplicates ( role . DisallowedPolicies , true )
2016-08-02 14:33:50 +00:00
2016-12-16 05:36:39 +00:00
for _ , finalPolicy := range finalPolicies {
if strutil . StrListContains ( sanitizedRolePolicies , finalPolicy ) {
return logical . ErrorResponse ( fmt . Sprintf ( "token policy %q is disallowed by this role" , finalPolicy ) ) , logical . ErrInvalidRequest
}
2016-08-02 14:33:50 +00:00
}
}
2016-12-16 05:36:39 +00:00
data . Policies = finalPolicies
// No policies specified, inherit parent
2016-02-29 18:27:31 +00:00
case len ( data . Policies ) == 0 :
2016-12-16 05:36:39 +00:00
// Only inherit "default" if the parent already has it, so don't touch addDefault here
data . Policies = policyutil . SanitizePolicies ( parent . Policies , policyutil . DoNotAddDefaultPolicy )
2016-02-29 18:27:31 +00:00
2016-12-16 05:36:39 +00:00
// When a role is not in use or does not specify allowed/disallowed, only
// permit policies to be a subset unless the client has root or sudo
// privileges. Default is added in this case if the parent has it, unless
// the client specified for it not to be added.
2016-05-11 20:51:18 +00:00
case ! isSudo :
// Sanitize passed-in and parent policies before comparison
2016-12-16 05:36:39 +00:00
sanitizedInputPolicies := policyutil . SanitizePolicies ( data . Policies , policyutil . DoNotAddDefaultPolicy )
sanitizedParentPolicies := policyutil . SanitizePolicies ( parent . Policies , policyutil . DoNotAddDefaultPolicy )
2016-05-11 20:51:18 +00:00
if ! strutil . StrListSubset ( sanitizedParentPolicies , sanitizedInputPolicies ) {
return logical . ErrorResponse ( "child policies must be subset of parent" ) , logical . ErrInvalidRequest
}
2016-12-16 05:36:39 +00:00
// If the parent has default, and they haven't requested not to get it,
// add it. Note that if they have explicitly put "default" in
// data.Policies it will still be added because NoDefaultPolicy
// controls *automatic* adding.
if ! data . NoDefaultPolicy && strutil . StrListContains ( parent . Policies , "default" ) {
addDefault = true
}
// Add default by default in this case unless requested not to
case isSudo :
addDefault = ! data . NoDefaultPolicy
2015-03-24 22:10:46 +00:00
}
2015-12-30 20:18:30 +00:00
2016-12-16 05:36:39 +00:00
te . Policies = policyutil . SanitizePolicies ( data . Policies , addDefault )
// Yes, this is a little inefficient to do it like this, but meh
if data . NoDefaultPolicy {
te . Policies = strutil . StrListDelete ( te . Policies , "default" )
}
2015-03-24 22:10:46 +00:00
2016-08-13 01:01:30 +00:00
// Prevent internal policies from being assigned to tokens
for _ , policy := range te . Policies {
if strutil . StrListContains ( nonAssignablePolicies , policy ) {
2016-09-29 04:01:28 +00:00
return logical . ErrorResponse ( fmt . Sprintf ( "cannot assign policy %q" , policy ) ) , nil
2016-08-13 01:01:30 +00:00
}
}
// Prevent attempts to create a root token without an actual root token as parent.
// This is to thwart privilege escalation by tokens having 'sudo' privileges.
if strutil . StrListContains ( data . Policies , "root" ) && ! strutil . StrListContains ( parent . Policies , "root" ) {
return logical . ErrorResponse ( "root tokens may not be created without parent token being root" ) , logical . ErrInvalidRequest
}
//
// NOTE: Do not modify policies below this line. We need the checks above
// to be the last checks as they must look at the final policy set.
//
2016-02-29 18:27:31 +00:00
switch {
case role != nil :
if role . Orphan {
te . Parent = ""
}
case data . NoParent :
// Only allow an orphan token if the client has sudo policy
2015-09-18 23:59:06 +00:00
if ! isSudo {
return logical . ErrorResponse ( "root or sudo privileges required to create orphan token" ) ,
2015-03-24 22:10:46 +00:00
logical . ErrInvalidRequest
}
2015-04-07 21:16:35 +00:00
te . Parent = ""
2016-02-29 18:27:31 +00:00
default :
2015-11-03 20:10:46 +00:00
// This comes from create-orphan, which can be properly ACLd
if orphan {
te . Parent = ""
}
2015-03-24 22:10:46 +00:00
}
2017-10-11 17:21:20 +00:00
// At this point, it is clear whether the token is going to be an orphan or
// not. If the token is not going to be an orphan, inherit the parent's
// entity identifier into the child token.
if te . Parent != "" {
te . EntityID = parent . EntityID
}
2018-04-03 16:20:20 +00:00
var explicitMaxTTLToUse time . Duration
2016-06-08 18:49:48 +00:00
if data . ExplicitMaxTTL != "" {
2017-03-07 16:21:22 +00:00
dur , err := parseutil . ParseDurationSecond ( data . ExplicitMaxTTL )
2016-06-08 18:49:48 +00:00
if err != nil {
return logical . ErrorResponse ( err . Error ( ) ) , logical . ErrInvalidRequest
2015-03-24 22:10:46 +00:00
}
2016-06-08 18:49:48 +00:00
if dur < 0 {
return logical . ErrorResponse ( "explicit_max_ttl must be positive" ) , logical . ErrInvalidRequest
2016-02-29 18:27:31 +00:00
}
2016-06-08 18:49:48 +00:00
te . ExplicitMaxTTL = dur
2018-04-03 16:20:20 +00:00
explicitMaxTTLToUse = dur
2016-06-08 18:49:48 +00:00
}
2015-09-18 20:33:52 +00:00
2016-08-16 20:47:46 +00:00
var periodToUse time . Duration
2016-08-13 01:01:30 +00:00
if data . Period != "" {
2017-03-07 16:21:22 +00:00
dur , err := parseutil . ParseDurationSecond ( data . Period )
2016-08-13 01:01:30 +00:00
if err != nil {
return logical . ErrorResponse ( err . Error ( ) ) , logical . ErrInvalidRequest
}
2018-02-01 17:01:46 +00:00
switch {
case dur < 0 :
2016-08-13 01:01:30 +00:00
return logical . ErrorResponse ( "period must be positive" ) , logical . ErrInvalidRequest
2018-02-01 17:01:46 +00:00
case dur == 0 :
default :
if ! isSudo {
return logical . ErrorResponse ( "root or sudo privileges required to create periodic token" ) ,
logical . ErrInvalidRequest
}
te . Period = dur
periodToUse = dur
2016-08-13 01:01:30 +00:00
}
}
2016-06-08 18:49:48 +00:00
// Parse the TTL/lease if any
if data . TTL != "" {
2017-03-07 16:21:22 +00:00
dur , err := parseutil . ParseDurationSecond ( data . TTL )
2016-06-08 18:49:48 +00:00
if err != nil {
return logical . ErrorResponse ( err . Error ( ) ) , logical . ErrInvalidRequest
}
if dur < 0 {
return logical . ErrorResponse ( "ttl must be positive" ) , logical . ErrInvalidRequest
}
te . TTL = dur
} else if data . Lease != "" {
// This block is compatibility
dur , err := time . ParseDuration ( data . Lease )
if err != nil {
return logical . ErrorResponse ( err . Error ( ) ) , logical . ErrInvalidRequest
}
if dur < 0 {
return logical . ErrorResponse ( "lease must be positive" ) , logical . ErrInvalidRequest
2016-02-29 18:27:31 +00:00
}
2016-06-08 18:49:48 +00:00
te . TTL = dur
2015-03-24 22:10:46 +00:00
}
2016-08-13 01:01:30 +00:00
// Set the lesser period/explicit max TTL if defined both in arguments and in role
if role != nil {
if role . ExplicitMaxTTL != 0 {
switch {
2018-04-03 16:20:20 +00:00
case explicitMaxTTLToUse == 0 :
explicitMaxTTLToUse = role . ExplicitMaxTTL
2016-08-13 01:01:30 +00:00
default :
2018-04-03 16:20:20 +00:00
if role . ExplicitMaxTTL < explicitMaxTTLToUse {
explicitMaxTTLToUse = role . ExplicitMaxTTL
2016-08-13 01:01:30 +00:00
}
2018-04-03 16:20:20 +00:00
resp . AddWarning ( fmt . Sprintf ( "Explicit max TTL specified both during creation call and in role; using the lesser value of %d seconds" , int64 ( explicitMaxTTLToUse . Seconds ( ) ) ) )
2016-08-13 01:01:30 +00:00
}
}
if role . Period != 0 {
switch {
2016-08-16 20:47:46 +00:00
case periodToUse == 0 :
periodToUse = role . Period
2016-08-13 01:01:30 +00:00
default :
2016-08-16 20:47:46 +00:00
if role . Period < periodToUse {
periodToUse = role . Period
2016-08-13 01:01:30 +00:00
}
2016-08-16 20:47:46 +00:00
resp . AddWarning ( fmt . Sprintf ( "Period specified both during creation call and in role; using the lesser value of %d seconds" , int64 ( periodToUse . Seconds ( ) ) ) )
2016-06-08 18:49:48 +00:00
}
}
}
2016-05-11 20:51:18 +00:00
2016-06-08 18:49:48 +00:00
sysView := ts . System ( )
2018-04-03 16:20:20 +00:00
// Only calculate a TTL if you are A) periodic, B) have a TTL, C) do not have a TTL and are not a root token
if periodToUse > 0 || te . TTL > 0 || ( te . TTL == 0 && ! strutil . StrListContains ( te . Policies , "root" ) ) {
ttl , warnings , err := framework . CalculateTTL ( sysView , 0 , te . TTL , periodToUse , 0 , explicitMaxTTLToUse , time . Unix ( te . CreationTime , 0 ) )
if err != nil {
return nil , err
2016-08-13 01:01:30 +00:00
}
2018-04-03 16:20:20 +00:00
for _ , warning := range warnings {
resp . AddWarning ( warning )
2016-08-13 01:01:30 +00:00
}
2018-04-03 16:20:20 +00:00
te . TTL = ttl
2016-08-13 01:01:30 +00:00
}
2018-04-03 16:20:20 +00:00
// Root tokens are still bound by explicit max TTL
if te . TTL == 0 && explicitMaxTTLToUse > 0 {
te . TTL = explicitMaxTTLToUse
2016-06-08 18:49:48 +00:00
}
2016-05-11 20:51:18 +00:00
2016-08-05 15:15:25 +00:00
// Don't advertise non-expiring root tokens as renewable, as attempts to renew them are denied
if te . TTL == 0 {
2016-08-10 00:32:40 +00:00
if parent . TTL != 0 {
return logical . ErrorResponse ( "expiring root tokens cannot create non-expiring root tokens" ) , logical . ErrInvalidRequest
}
2016-08-05 15:15:25 +00:00
renewable = false
}
2016-08-08 20:44:29 +00:00
// Create the token
2018-01-19 06:44:44 +00:00
if err := ts . create ( ctx , & te ) ; err != nil {
2016-08-08 20:44:29 +00:00
return logical . ErrorResponse ( err . Error ( ) ) , logical . ErrInvalidRequest
}
2015-03-24 22:10:46 +00:00
// Generate the response
2016-05-11 20:51:18 +00:00
resp . Auth = & logical . Auth {
2017-03-08 22:36:50 +00:00
NumUses : te . NumUses ,
2016-05-11 20:51:18 +00:00
DisplayName : te . DisplayName ,
Policies : te . Policies ,
Metadata : te . Meta ,
LeaseOptions : logical . LeaseOptions {
TTL : te . TTL ,
2016-06-08 15:14:30 +00:00
Renewable : renewable ,
2015-03-24 22:10:46 +00:00
} ,
2018-04-03 16:20:20 +00:00
ClientToken : te . ID ,
Accessor : te . Accessor ,
EntityID : te . EntityID ,
Period : periodToUse ,
ExplicitMaxTTL : explicitMaxTTLToUse ,
2015-03-24 22:10:46 +00:00
}
2015-03-31 03:26:39 +00:00
2015-10-07 19:30:54 +00:00
if ts . policyLookupFunc != nil {
2015-11-06 16:36:40 +00:00
for _ , p := range te . Policies {
policy , err := ts . policyLookupFunc ( p )
if err != nil {
return logical . ErrorResponse ( fmt . Sprintf ( "could not look up policy %s" , p ) ) , nil
2015-10-07 19:30:54 +00:00
}
2015-11-06 16:36:40 +00:00
if policy == nil {
2016-08-02 20:53:06 +00:00
resp . AddWarning ( fmt . Sprintf ( "Policy %q does not exist" , p ) )
2015-10-07 19:30:54 +00:00
}
}
}
2015-03-24 22:10:46 +00:00
return resp , nil
}
2015-09-17 17:22:30 +00:00
// handleRevokeSelf handles the auth/token/revoke-self path for revocation of tokens
// in a way that revokes all child tokens. Normally, using sys/revoke/leaseID will revoke
// the token and all children anyways, but that is only available when there is a lease.
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) handleRevokeSelf ( ctx context . Context , req * logical . Request , data * framework . FieldData ) ( * logical . Response , error ) {
2015-09-17 17:22:30 +00:00
// Revoke the token and its children
2018-01-19 06:44:44 +00:00
if err := ts . RevokeTree ( ctx , req . ClientToken ) ; err != nil {
2015-09-17 17:22:30 +00:00
return logical . ErrorResponse ( err . Error ( ) ) , logical . ErrInvalidRequest
}
return nil , nil
}
2015-03-24 22:30:09 +00:00
// handleRevokeTree handles the auth/token/revoke/id path for revocation of tokens
2015-04-08 20:35:32 +00:00
// in a way that revokes all child tokens. Normally, using sys/revoke/leaseID will revoke
2015-03-24 22:30:09 +00:00
// the token and all children anyways, but that is only available when there is a lease.
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) handleRevokeTree ( ctx context . Context , req * logical . Request , data * framework . FieldData ) ( * logical . Response , error ) {
2016-08-29 19:15:57 +00:00
var urltoken bool
2015-03-31 19:48:19 +00:00
id := data . Get ( "token" ) . ( string )
2015-03-24 22:30:09 +00:00
if id == "" {
2016-08-29 19:15:57 +00:00
id = data . Get ( "urltoken" ) . ( string )
if id == "" {
return logical . ErrorResponse ( "missing token ID" ) , logical . ErrInvalidRequest
}
urltoken = true
2015-03-24 22:30:09 +00:00
}
// Revoke the token and its children
2018-01-19 06:44:44 +00:00
if err := ts . RevokeTree ( ctx , id ) ; err != nil {
2015-03-24 22:30:09 +00:00
return logical . ErrorResponse ( err . Error ( ) ) , logical . ErrInvalidRequest
}
2016-08-29 19:15:57 +00:00
if urltoken {
resp := & logical . Response { }
resp . AddWarning ( ` Using a token in the path is unsafe as the token can be logged in many places. Please use POST or PUT with the token passed in via the "token" parameter. ` )
return resp , nil
}
2015-03-24 22:30:09 +00:00
return nil , nil
}
2015-03-24 22:10:46 +00:00
// handleRevokeOrphan handles the auth/token/revoke-orphan/id path for revocation of tokens
2015-04-08 20:35:32 +00:00
// in a way that leaves child tokens orphaned. Normally, using sys/revoke/leaseID will revoke
2015-03-24 22:10:46 +00:00
// the token and all children.
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) handleRevokeOrphan ( ctx context . Context , req * logical . Request , data * framework . FieldData ) ( * logical . Response , error ) {
2016-08-29 19:15:57 +00:00
var urltoken bool
2015-03-24 22:30:09 +00:00
// Parse the id
2015-03-31 19:48:19 +00:00
id := data . Get ( "token" ) . ( string )
2015-03-24 22:30:09 +00:00
if id == "" {
2016-08-29 19:15:57 +00:00
id = data . Get ( "urltoken" ) . ( string )
if id == "" {
return logical . ErrorResponse ( "missing token ID" ) , logical . ErrInvalidRequest
}
urltoken = true
2015-03-24 22:30:09 +00:00
}
2018-01-19 06:44:44 +00:00
parent , err := ts . Lookup ( ctx , req . ClientToken )
2015-09-16 13:22:15 +00:00
if err != nil {
return logical . ErrorResponse ( fmt . Sprintf ( "parent token lookup failed: %s" , err . Error ( ) ) ) , logical . ErrInvalidRequest
}
if parent == nil {
return logical . ErrorResponse ( "parent token lookup failed" ) , logical . ErrInvalidRequest
}
2015-09-21 14:04:03 +00:00
// Check if the client token has sudo/root privileges for the requested path
2018-01-19 06:44:44 +00:00
isSudo := ts . System ( ) . SudoPrivilege ( ctx , req . MountPoint + req . Path , req . ClientToken )
2015-09-16 13:22:15 +00:00
2015-09-18 23:59:06 +00:00
if ! isSudo {
return logical . ErrorResponse ( "root or sudo privileges required to revoke and orphan" ) ,
2015-09-16 13:22:15 +00:00
logical . ErrInvalidRequest
}
2015-03-24 22:30:09 +00:00
// Revoke and orphan
2018-01-19 06:44:44 +00:00
if err := ts . Revoke ( ctx , id ) ; err != nil {
2015-03-24 22:30:09 +00:00
return logical . ErrorResponse ( err . Error ( ) ) , logical . ErrInvalidRequest
}
2016-08-29 19:15:57 +00:00
if urltoken {
resp := & logical . Response { }
resp . AddWarning ( ` Using a token in the path is unsafe as the token can be logged in many places. Please use POST or PUT with the token passed in via the "token" parameter. ` )
return resp , nil
}
2015-03-20 20:54:57 +00:00
return nil , nil
}
2015-03-24 22:10:46 +00:00
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) handleLookupSelf ( ctx context . Context , req * logical . Request , data * framework . FieldData ) ( * logical . Response , error ) {
2016-04-28 19:15:37 +00:00
data . Raw [ "token" ] = req . ClientToken
2018-01-08 18:31:38 +00:00
return ts . handleLookup ( ctx , req , data )
2016-04-28 19:15:37 +00:00
}
2015-03-24 22:39:33 +00:00
// handleLookup handles the auth/token/lookup/id path for querying information about
// a particular token. This can be used to see which policies are applicable.
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) handleLookup ( ctx context . Context , req * logical . Request , data * framework . FieldData ) ( * logical . Response , error ) {
2016-08-29 19:15:57 +00:00
var urltoken bool
2015-03-31 19:48:19 +00:00
id := data . Get ( "token" ) . ( string )
2016-08-29 19:15:57 +00:00
if id == "" {
id = data . Get ( "urltoken" ) . ( string )
if id != "" {
urltoken = true
}
}
2015-03-31 19:50:07 +00:00
if id == "" {
id = req . ClientToken
}
2015-03-24 22:39:33 +00:00
if id == "" {
return logical . ErrorResponse ( "missing token ID" ) , logical . ErrInvalidRequest
}
2017-03-07 16:21:32 +00:00
lock := locksutil . LockForKey ( ts . tokenLocks , id )
2016-12-16 18:11:55 +00:00
lock . RLock ( )
defer lock . RUnlock ( )
2015-03-24 22:39:33 +00:00
// Lookup the token
2018-04-03 16:20:20 +00:00
saltedID , err := ts . SaltID ( ctx , id )
2017-07-18 16:02:03 +00:00
if err != nil {
return logical . ErrorResponse ( err . Error ( ) ) , logical . ErrInvalidRequest
}
2018-04-03 16:20:20 +00:00
out , err := ts . lookupSalted ( ctx , saltedID , true )
2015-03-24 22:39:33 +00:00
if err != nil {
return logical . ErrorResponse ( err . Error ( ) ) , logical . ErrInvalidRequest
}
if out == nil {
2015-06-19 01:30:18 +00:00
return logical . ErrorResponse ( "bad token" ) , logical . ErrPermissionDenied
2015-03-24 22:39:33 +00:00
}
// Generate a response. We purposely omit the parent reference otherwise
2015-10-02 17:33:19 +00:00
// you could escalate your privileges.
2015-03-24 22:39:33 +00:00
resp := & logical . Response {
Data : map [ string ] interface { } {
2016-05-11 20:51:18 +00:00
"id" : out . ID ,
"accessor" : out . Accessor ,
"policies" : out . Policies ,
"path" : out . Path ,
"meta" : out . Meta ,
"display_name" : out . DisplayName ,
"num_uses" : out . NumUses ,
"orphan" : false ,
"creation_time" : int64 ( out . CreationTime ) ,
"creation_ttl" : int64 ( out . TTL . Seconds ( ) ) ,
2017-05-04 02:03:42 +00:00
"expire_time" : nil ,
2016-05-11 20:51:18 +00:00
"ttl" : int64 ( 0 ) ,
"explicit_max_ttl" : int64 ( out . ExplicitMaxTTL . Seconds ( ) ) ,
2017-10-11 17:21:20 +00:00
"entity_id" : out . EntityID ,
2015-03-24 22:39:33 +00:00
} ,
}
2015-11-09 18:19:59 +00:00
if out . Parent == "" {
resp . Data [ "orphan" ] = true
}
2016-08-13 01:01:30 +00:00
if out . Role != "" {
resp . Data [ "role" ] = out . Role
2016-08-16 20:47:46 +00:00
}
if out . Period != 0 {
2016-08-13 01:01:30 +00:00
resp . Data [ "period" ] = int64 ( out . Period . Seconds ( ) )
}
2016-01-04 21:43:07 +00:00
// Fetch the last renewal time
leaseTimes , err := ts . expiration . FetchLeaseTimesByToken ( out . Path , out . ID )
if err != nil {
return logical . ErrorResponse ( err . Error ( ) ) , logical . ErrInvalidRequest
}
2016-02-01 16:16:32 +00:00
if leaseTimes != nil {
if ! leaseTimes . LastRenewalTime . IsZero ( ) {
resp . Data [ "last_renewal_time" ] = leaseTimes . LastRenewalTime . Unix ( )
2017-05-04 02:03:42 +00:00
resp . Data [ "last_renewal" ] = leaseTimes . LastRenewalTime
2016-02-01 16:16:32 +00:00
}
if ! leaseTimes . ExpireTime . IsZero ( ) {
2017-05-04 02:03:42 +00:00
resp . Data [ "expire_time" ] = leaseTimes . ExpireTime
resp . Data [ "ttl" ] = leaseTimes . ttl ( )
2016-06-01 21:30:31 +00:00
}
2017-05-04 02:03:42 +00:00
renewable , _ := leaseTimes . renewable ( )
resp . Data [ "renewable" ] = renewable
resp . Data [ "issue_time" ] = leaseTimes . IssueTime
2016-01-04 21:43:07 +00:00
}
2016-08-29 19:15:57 +00:00
if urltoken {
resp . AddWarning ( ` Using a token in the path is unsafe as the token can be logged in many places. Please use POST or PUT with the token passed in via the "token" parameter. ` )
}
2015-03-24 22:39:33 +00:00
return resp , nil
}
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) handleRenewSelf ( ctx context . Context , req * logical . Request , data * framework . FieldData ) ( * logical . Response , error ) {
2015-10-07 16:49:13 +00:00
data . Raw [ "token" ] = req . ClientToken
2018-01-08 18:31:38 +00:00
return ts . handleRenew ( ctx , req , data )
2015-10-07 16:49:13 +00:00
}
2015-04-03 19:11:49 +00:00
// handleRenew handles the auth/token/renew/id path for renewal of tokens.
// This is used to prevent token expiration and revocation.
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) handleRenew ( ctx context . Context , req * logical . Request , data * framework . FieldData ) ( * logical . Response , error ) {
2016-08-29 19:15:57 +00:00
var urltoken bool
2015-04-03 19:11:49 +00:00
id := data . Get ( "token" ) . ( string )
if id == "" {
2016-08-29 19:15:57 +00:00
id = data . Get ( "urltoken" ) . ( string )
if id == "" {
return logical . ErrorResponse ( "missing token ID" ) , logical . ErrInvalidRequest
}
urltoken = true
2015-04-03 19:11:49 +00:00
}
2015-04-09 21:23:37 +00:00
incrementRaw := data . Get ( "increment" ) . ( int )
// Convert the increment
increment := time . Duration ( incrementRaw ) * time . Second
2015-04-03 19:11:49 +00:00
// Lookup the token
2018-01-19 06:44:44 +00:00
te , err := ts . Lookup ( ctx , id )
2015-04-03 19:11:49 +00:00
if err != nil {
return logical . ErrorResponse ( err . Error ( ) ) , logical . ErrInvalidRequest
}
// Verify the token exists
2015-12-30 19:30:02 +00:00
if te == nil {
2015-04-03 19:11:49 +00:00
return logical . ErrorResponse ( "token not found" ) , logical . ErrInvalidRequest
}
2015-10-09 21:11:31 +00:00
// Renew the token and its children
2016-08-29 19:15:57 +00:00
resp , err := ts . expiration . RenewToken ( req , te . Path , te . ID , increment )
if urltoken {
resp . AddWarning ( ` Using a token in the path is unsafe as the token can be logged in many places. Please use POST or PUT with the token passed in via the "token" parameter. ` )
}
return resp , err
2015-04-03 19:11:49 +00:00
}
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) destroyCubbyhole ( ctx context . Context , saltedID string ) error {
2015-09-15 17:49:53 +00:00
if ts . cubbyholeBackend == nil {
2015-09-15 15:28:07 +00:00
// Should only ever happen in testing
return nil
}
2018-01-19 06:44:44 +00:00
return ts . cubbyholeBackend . revoke ( ctx , salt . SaltID ( ts . cubbyholeBackend . saltUUID , saltedID , salt . SHA1Hash ) )
2015-09-15 15:28:07 +00:00
}
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) authRenew ( ctx context . Context , req * logical . Request , d * framework . FieldData ) ( * logical . Response , error ) {
2016-02-29 18:27:31 +00:00
if req . Auth == nil {
return nil , fmt . Errorf ( "request auth is nil" )
}
2016-01-29 22:44:09 +00:00
2018-01-19 06:44:44 +00:00
te , err := ts . Lookup ( ctx , req . Auth . ClientToken )
2016-02-29 18:27:31 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
return nil , errwrap . Wrapf ( "error looking up token: {{err}}" , err )
2016-02-29 18:27:31 +00:00
}
if te == nil {
return nil , fmt . Errorf ( "no token entry found during lookup" )
}
if te . Role == "" {
2018-04-03 16:20:20 +00:00
req . Auth . Period = te . Period
req . Auth . ExplicitMaxTTL = te . ExplicitMaxTTL
return & logical . Response { Auth : req . Auth } , nil
2016-02-29 18:27:31 +00:00
}
2018-01-19 06:44:44 +00:00
role , err := ts . tokenStoreRole ( ctx , te . Role )
2016-02-29 18:27:31 +00:00
if err != nil {
2018-04-05 15:49:21 +00:00
return nil , errwrap . Wrapf ( fmt . Sprintf ( "error looking up role %q: {{err}}" , te . Role ) , err )
2016-02-29 18:27:31 +00:00
}
if role == nil {
2018-04-05 15:49:21 +00:00
return nil , fmt . Errorf ( "original token role %q could not be found, not renewing" , te . Role )
2016-02-29 18:27:31 +00:00
}
2018-04-03 16:20:20 +00:00
req . Auth . Period = role . Period
req . Auth . ExplicitMaxTTL = role . ExplicitMaxTTL
return & logical . Response { Auth : req . Auth } , nil
2016-01-29 22:44:09 +00:00
}
2018-01-19 06:44:44 +00:00
func ( ts * TokenStore ) tokenStoreRole ( ctx context . Context , name string ) ( * tsRoleEntry , error ) {
entry , err := ts . view . Get ( ctx , fmt . Sprintf ( "%s%s" , rolesPrefix , name ) )
2016-02-29 18:27:31 +00:00
if err != nil {
return nil , err
}
if entry == nil {
return nil , nil
}
var result tsRoleEntry
if err := entry . DecodeJSON ( & result ) ; err != nil {
return nil , err
}
return & result , nil
}
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) tokenStoreRoleList ( ctx context . Context , req * logical . Request , d * framework . FieldData ) ( * logical . Response , error ) {
2018-01-19 06:44:44 +00:00
entries , err := ts . view . List ( ctx , rolesPrefix )
2016-02-29 18:27:31 +00:00
if err != nil {
return nil , err
}
2016-02-29 19:13:09 +00:00
ret := make ( [ ] string , len ( entries ) )
for i , entry := range entries {
2016-03-01 17:33:35 +00:00
ret [ i ] = strings . TrimPrefix ( entry , rolesPrefix )
2016-02-29 19:13:09 +00:00
}
return logical . ListResponse ( ret ) , nil
2016-02-29 18:27:31 +00:00
}
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) tokenStoreRoleDelete ( ctx context . Context , req * logical . Request , data * framework . FieldData ) ( * logical . Response , error ) {
2018-01-19 06:44:44 +00:00
err := ts . view . Delete ( ctx , fmt . Sprintf ( "%s%s" , rolesPrefix , data . Get ( "role_name" ) . ( string ) ) )
2016-02-29 18:27:31 +00:00
if err != nil {
return nil , err
}
return nil , nil
}
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) tokenStoreRoleRead ( ctx context . Context , req * logical . Request , data * framework . FieldData ) ( * logical . Response , error ) {
2018-01-19 06:44:44 +00:00
role , err := ts . tokenStoreRole ( ctx , data . Get ( "role_name" ) . ( string ) )
2016-02-29 18:27:31 +00:00
if err != nil {
return nil , err
}
if role == nil {
return nil , nil
}
resp := & logical . Response {
2016-05-11 20:51:18 +00:00
Data : map [ string ] interface { } {
2016-08-02 14:33:50 +00:00
"period" : int64 ( role . Period . Seconds ( ) ) ,
"explicit_max_ttl" : int64 ( role . ExplicitMaxTTL . Seconds ( ) ) ,
"disallowed_policies" : role . DisallowedPolicies ,
"allowed_policies" : role . AllowedPolicies ,
"name" : role . Name ,
"orphan" : role . Orphan ,
"path_suffix" : role . PathSuffix ,
"renewable" : role . Renewable ,
2016-05-11 20:51:18 +00:00
} ,
2016-04-14 10:10:22 +00:00
}
2016-02-29 18:27:31 +00:00
return resp , nil
}
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) tokenStoreRoleExistenceCheck ( ctx context . Context , req * logical . Request , data * framework . FieldData ) ( bool , error ) {
2016-03-09 16:59:54 +00:00
name := data . Get ( "role_name" ) . ( string )
if name == "" {
return false , fmt . Errorf ( "role name cannot be empty" )
}
2018-01-19 06:44:44 +00:00
role , err := ts . tokenStoreRole ( ctx , name )
2016-03-09 16:59:54 +00:00
if err != nil {
return false , err
}
return role != nil , nil
}
2018-01-08 18:31:38 +00:00
func ( ts * TokenStore ) tokenStoreRoleCreateUpdate ( ctx context . Context , req * logical . Request , data * framework . FieldData ) ( * logical . Response , error ) {
2016-02-29 18:27:31 +00:00
name := data . Get ( "role_name" ) . ( string )
if name == "" {
return logical . ErrorResponse ( "role name cannot be empty" ) , nil
}
2018-01-19 06:44:44 +00:00
entry , err := ts . tokenStoreRole ( ctx , name )
2016-03-09 16:59:54 +00:00
if err != nil {
return nil , err
}
2016-02-29 18:27:31 +00:00
2016-03-09 16:59:54 +00:00
// Due to the existence check, entry will only be nil if it's a create
// operation, so just create a new one
if entry == nil {
entry = & tsRoleEntry {
Name : name ,
2016-02-29 18:27:31 +00:00
}
}
2016-03-09 16:59:54 +00:00
// In this series of blocks, if we do not find a user-provided value and
// it's a creation operation, we call data.Get to get the appropriate
// default
orphanInt , ok := data . GetOk ( "orphan" )
if ok {
entry . Orphan = orphanInt . ( bool )
} else if req . Operation == logical . CreateOperation {
entry . Orphan = data . Get ( "orphan" ) . ( bool )
}
periodInt , ok := data . GetOk ( "period" )
if ok {
entry . Period = time . Second * time . Duration ( periodInt . ( int ) )
} else if req . Operation == logical . CreateOperation {
entry . Period = time . Second * time . Duration ( data . Get ( "period" ) . ( int ) )
2016-02-29 18:27:31 +00:00
}
2016-06-08 19:17:22 +00:00
renewableInt , ok := data . GetOk ( "renewable" )
if ok {
entry . Renewable = renewableInt . ( bool )
} else if req . Operation == logical . CreateOperation {
entry . Renewable = data . Get ( "renewable" ) . ( bool )
}
2016-05-11 20:51:18 +00:00
var resp * logical . Response
explicitMaxTTLInt , ok := data . GetOk ( "explicit_max_ttl" )
if ok {
entry . ExplicitMaxTTL = time . Second * time . Duration ( explicitMaxTTLInt . ( int ) )
} else if req . Operation == logical . CreateOperation {
entry . ExplicitMaxTTL = time . Second * time . Duration ( data . Get ( "explicit_max_ttl" ) . ( int ) )
}
if entry . ExplicitMaxTTL != 0 {
sysView := ts . System ( )
if sysView . MaxLeaseTTL ( ) != time . Duration ( 0 ) && entry . ExplicitMaxTTL > sysView . MaxLeaseTTL ( ) {
if resp == nil {
resp = & logical . Response { }
}
resp . AddWarning ( fmt . Sprintf (
"Given explicit max TTL of %d is greater than system/mount allowed value of %d seconds; until this is fixed attempting to create tokens against this role will result in an error" ,
2017-05-02 03:34:10 +00:00
int64 ( entry . ExplicitMaxTTL . Seconds ( ) ) , int64 ( sysView . MaxLeaseTTL ( ) . Seconds ( ) ) ) )
2016-05-11 20:51:18 +00:00
}
}
2016-03-09 16:59:54 +00:00
pathSuffixInt , ok := data . GetOk ( "path_suffix" )
if ok {
pathSuffix := pathSuffixInt . ( string )
if pathSuffix != "" {
matched := pathSuffixSanitize . MatchString ( pathSuffix )
if ! matched {
2016-05-11 20:51:18 +00:00
return logical . ErrorResponse ( fmt . Sprintf (
"given role path suffix contains invalid characters; must match %s" ,
pathSuffixSanitize . String ( ) ) ) , nil
2016-03-09 16:59:54 +00:00
}
entry . PathSuffix = pathSuffix
}
} else if req . Operation == logical . CreateOperation {
entry . PathSuffix = data . Get ( "path_suffix" ) . ( string )
}
2017-05-12 17:52:33 +00:00
if strings . Contains ( entry . PathSuffix , ".." ) {
return logical . ErrorResponse ( fmt . Sprintf ( "error registering path suffix: %s" , consts . ErrPathContainsParentReferences ) ) , nil
}
2017-12-04 17:47:05 +00:00
allowedPoliciesRaw , ok := data . GetOk ( "allowed_policies" )
2016-03-09 16:59:54 +00:00
if ok {
2017-12-04 17:47:05 +00:00
entry . AllowedPolicies = policyutil . SanitizePolicies ( allowedPoliciesRaw . ( [ ] string ) , policyutil . DoNotAddDefaultPolicy )
2016-08-02 14:33:50 +00:00
} else if req . Operation == logical . CreateOperation {
2017-12-04 17:47:05 +00:00
entry . AllowedPolicies = policyutil . SanitizePolicies ( data . Get ( "allowed_policies" ) . ( [ ] string ) , policyutil . DoNotAddDefaultPolicy )
2016-08-02 14:33:50 +00:00
}
2017-12-04 17:47:05 +00:00
disallowedPoliciesRaw , ok := data . GetOk ( "disallowed_policies" )
2016-08-02 14:33:50 +00:00
if ok {
2017-12-04 17:47:05 +00:00
entry . DisallowedPolicies = strutil . RemoveDuplicates ( disallowedPoliciesRaw . ( [ ] string ) , true )
2016-03-09 16:59:54 +00:00
} else if req . Operation == logical . CreateOperation {
2017-12-04 17:47:05 +00:00
entry . DisallowedPolicies = strutil . RemoveDuplicates ( data . Get ( "disallowed_policies" ) . ( [ ] string ) , true )
2016-02-29 18:27:31 +00:00
}
// Store it
2016-03-01 17:33:35 +00:00
jsonEntry , err := logical . StorageEntryJSON ( fmt . Sprintf ( "%s%s" , rolesPrefix , name ) , entry )
2016-02-29 18:27:31 +00:00
if err != nil {
return nil , err
}
2018-01-19 06:44:44 +00:00
if err := ts . view . Put ( ctx , jsonEntry ) ; err != nil {
2016-02-29 18:27:31 +00:00
return nil , err
}
2016-05-11 20:51:18 +00:00
return resp , nil
2016-02-29 18:27:31 +00:00
}
2015-03-24 22:10:46 +00:00
const (
2016-12-16 20:29:27 +00:00
tokenTidyHelp = `
This endpoint performs cleanup tasks that can be run if certain error
conditions have occurred .
`
tokenTidyDesc = `
This endpoint performs cleanup tasks that can be run to clean up token and
lease entries after certain error conditions . Usually running this is not
necessary , and is only required if upgrade notes or support personnel suggest
it .
`
2015-03-24 22:10:46 +00:00
tokenBackendHelp = ` The token credential backend is always enabled and builtin to Vault .
Client tokens are used to identify a client and to allow Vault to associate policies and ACLs
which are enforced on every request . This backend also allows for generating sub - tokens as well
2015-09-12 01:08:32 +00:00
as revocation of tokens . The tokens are renewable if associated with a lease . `
2016-03-03 16:04:05 +00:00
tokenCreateHelp = ` The token create path is used to create new tokens. `
tokenCreateOrphanHelp = ` The token create path is used to create new orphan tokens. `
tokenCreateRoleHelp = ` This token create path is used to create new tokens adhering to the given role. `
tokenListRolesHelp = ` This endpoint lists configured roles. `
2016-03-09 22:23:34 +00:00
tokenLookupAccessorHelp = ` This endpoint will lookup a token associated with the given accessor and its properties. Response will not contain the token ID. `
2016-03-03 16:04:05 +00:00
tokenLookupHelp = ` This endpoint will lookup a token and its properties. `
tokenPathRolesHelp = ` This endpoint allows creating, reading, and deleting roles. `
2016-03-09 22:23:34 +00:00
tokenRevokeAccessorHelp = ` This endpoint will delete the token associated with the accessor and all of its child tokens. `
2016-03-03 16:04:05 +00:00
tokenRevokeHelp = ` This endpoint will delete the given token and all of its child tokens. `
tokenRevokeSelfHelp = ` This endpoint will delete the token used to call it and all of its child tokens. `
tokenRevokeOrphanHelp = ` This endpoint will delete the token and orphan its child tokens. `
tokenRenewHelp = ` This endpoint will renew the given token and prevent expiration. `
tokenRenewSelfHelp = ` This endpoint will renew the token used to call it and prevent expiration. `
2016-08-02 20:33:22 +00:00
tokenAllowedPoliciesHelp = ` If set , tokens can be created with any subset of the policies in this
list , rather than the normal semantics of tokens being a subset of the
calling token ' s policies . The parameter is a comma - delimited string of
2016-12-16 05:36:39 +00:00
policy names . `
2016-08-02 20:33:22 +00:00
tokenDisallowedPoliciesHelp = ` If set , successful token creation via this role will require that
2016-12-16 05:36:39 +00:00
no policies in the given list are requested . The parameter is a comma - delimited string of policy names . `
2016-03-07 15:07:04 +00:00
tokenOrphanHelp = ` If true , tokens created via this role
will be orphan tokens ( have no parent ) `
2016-03-03 16:04:05 +00:00
tokenPeriodHelp = ` If set , tokens created via this role
will have no max lifetime ; instead , their
renewal period will be fixed to this value .
This takes an integer number of seconds ,
or a string duration ( e . g . "24h" ) . `
tokenPathSuffixHelp = ` If set , tokens created via this role
will contain the given suffix as a part of
their path . This can be used to assist use
of the ' revoke - prefix ' endpoint later on .
The given suffix must match the regular
2016-05-11 20:51:18 +00:00
expression . `
tokenExplicitMaxTTLHelp = ` If set , tokens created via this role
carry an explicit maximum TTL . During renewal ,
the current maximum TTL values of the role
and the mount are not checked for changes ,
and any updates to these values will have
no effect on the token being renewed . `
2016-06-08 19:17:22 +00:00
tokenRenewableHelp = ` Tokens created via this role will be
renewable or not according to this value .
Defaults to "true" . `
2016-08-01 17:07:41 +00:00
tokenListAccessorsHelp = ` List token accessors , which can then be
2018-03-20 18:54:10 +00:00
be used to iterate and discover their properties
2016-08-01 17:07:41 +00:00
or revoke them . Because this can be used to
cause a denial of service , this endpoint
requires ' sudo ' capability in addition to
' list ' . `
2015-03-24 22:10:46 +00:00
)