open-vault/vault/policy_store.go

513 lines
13 KiB
Go
Raw Normal View History

2015-03-18 19:17:03 +00:00
package vault
import (
"context"
2015-03-18 19:17:03 +00:00
"fmt"
"strings"
2017-10-23 19:11:29 +00:00
"sync"
2015-04-08 23:43:17 +00:00
"time"
2015-03-18 19:17:03 +00:00
2015-04-08 23:43:17 +00:00
"github.com/armon/go-metrics"
"github.com/hashicorp/errwrap"
log "github.com/hashicorp/go-hclog"
2015-04-06 23:41:48 +00:00
"github.com/hashicorp/golang-lru"
"github.com/hashicorp/vault/helper/consts"
"github.com/hashicorp/vault/helper/strutil"
2015-03-18 19:17:03 +00:00
"github.com/hashicorp/vault/logical"
)
const (
// policySubPath is the sub-path used for the policy store
// view. This is nested under the system view.
2017-10-23 18:59:37 +00:00
policyACLSubPath = "policy/"
2015-04-06 23:41:48 +00:00
// policyCacheSize is the number of policies that are kept cached
policyCacheSize = 1024
2017-11-13 20:31:32 +00:00
// defaultPolicyName is the name of the default policy
defaultPolicyName = "default"
2016-09-29 04:01:28 +00:00
// responseWrappingPolicyName is the name of the fixed policy
responseWrappingPolicyName = "response-wrapping"
2017-11-13 20:31:32 +00:00
// controlGroupPolicyName is the name of the fixed policy for control group
// tokens
controlGroupPolicyName = "control-group"
2016-09-29 04:01:28 +00:00
// responseWrappingPolicy is the policy that ensures cubbyhole response
// wrapping can always succeed.
2016-09-29 04:01:28 +00:00
responseWrappingPolicy = `
path "cubbyhole/response" {
capabilities = ["create", "read"]
}
2016-09-29 04:01:28 +00:00
path "sys/wrapping/unwrap" {
capabilities = ["update"]
}
2016-08-08 22:33:31 +00:00
`
// defaultPolicy is the "default" policy
defaultPolicy = `
2016-09-29 04:01:28 +00:00
# Allow tokens to look up their own properties
2016-08-08 22:33:31 +00:00
path "auth/token/lookup-self" {
capabilities = ["read"]
}
2016-09-29 04:01:28 +00:00
# Allow tokens to renew themselves
2016-08-08 22:33:31 +00:00
path "auth/token/renew-self" {
capabilities = ["update"]
}
2016-09-29 04:01:28 +00:00
# Allow tokens to revoke themselves
2016-08-08 22:33:31 +00:00
path "auth/token/revoke-self" {
capabilities = ["update"]
}
2016-09-29 04:01:28 +00:00
# Allow a token to look up its own capabilities on a path
path "sys/capabilities-self" {
capabilities = ["update"]
}
# Allow a token to renew a lease via lease_id in the request body; old path for
# old clients, new path for newer
2016-09-29 04:01:28 +00:00
path "sys/renew" {
capabilities = ["update"]
}
path "sys/leases/renew" {
capabilities = ["update"]
}
# Allow looking up lease properties. This requires knowing the lease ID ahead
2017-05-04 00:25:55 +00:00
# of time and does not divulge any sensitive information.
path "sys/leases/lookup" {
capabilities = ["update"]
}
2016-09-29 04:01:28 +00:00
# Allow a token to manage its own cubbyhole
2016-08-08 22:33:31 +00:00
path "cubbyhole/*" {
capabilities = ["create", "read", "update", "delete", "list"]
}
# Allow a token to wrap arbitrary values in a response-wrapping token
path "sys/wrapping/wrap" {
capabilities = ["update"]
}
2016-09-29 04:01:28 +00:00
# Allow a token to look up the creation time and TTL of a given
# response-wrapping token
path "sys/wrapping/lookup" {
2016-08-08 22:33:31 +00:00
capabilities = ["update"]
}
2016-09-29 04:01:28 +00:00
# Allow a token to unwrap a response-wrapping token. This is a convenience to
# avoid client token swapping since this is also part of the response wrapping
# policy.
path "sys/wrapping/unwrap" {
2016-08-08 22:33:31 +00:00
capabilities = ["update"]
}
# Allow general purpose tools
path "sys/tools/hash" {
capabilities = ["update"]
}
path "sys/tools/hash/*" {
capabilities = ["update"]
}
path "sys/tools/random" {
capabilities = ["update"]
}
path "sys/tools/random/*" {
capabilities = ["update"]
}
`
)
var (
immutablePolicies = []string{
"root",
2016-09-29 04:01:28 +00:00
responseWrappingPolicyName,
2017-11-13 20:31:32 +00:00
controlGroupPolicyName,
}
nonAssignablePolicies = []string{
2016-09-29 04:01:28 +00:00
responseWrappingPolicyName,
2017-11-13 20:31:32 +00:00
controlGroupPolicyName,
}
)
2015-03-18 19:17:03 +00:00
// PolicyStore is used to provide durable storage of policy, and to
// manage ACLs associated with them.
type PolicyStore struct {
core *Core
2017-10-23 18:59:37 +00:00
aclView *BarrierView
tokenPoliciesLRU *lru.TwoQueueCache
// This is used to ensure that writes to the store (acl/rgp) or to the egp
// path tree don't happen concurrently. We are okay reading stale data so
// long as there aren't concurrent writes.
modifyLock *sync.RWMutex
// Stores whether a token policy is ACL or RGP
policyTypeMap sync.Map
// logger is the server logger copied over from core
logger log.Logger
2015-03-18 19:17:03 +00:00
}
// PolicyEntry is used to store a policy by name
type PolicyEntry struct {
Version int
Raw string
2017-10-23 19:11:29 +00:00
Type PolicyType
}
2015-03-18 19:17:03 +00:00
// NewPolicyStore creates a new PolicyStore that is backed
// using a given view. It used used to durable store and manage named policy.
func NewPolicyStore(ctx context.Context, core *Core, baseView *BarrierView, system logical.SystemView, logger log.Logger) *PolicyStore {
2017-10-23 18:59:37 +00:00
ps := &PolicyStore{
2017-10-23 19:11:29 +00:00
aclView: baseView.SubView(policyACLSubPath),
modifyLock: new(sync.RWMutex),
logger: logger,
core: core,
2015-03-18 19:17:03 +00:00
}
if !system.CachingDisabled() {
cache, _ := lru.New2Q(policyCacheSize)
2017-10-23 18:59:37 +00:00
ps.tokenPoliciesLRU = cache
}
keys, err := logical.CollectKeys(ctx, ps.aclView)
2017-10-23 18:59:37 +00:00
if err != nil {
ps.logger.Error("error collecting acl policy keys", "error", err)
2017-10-23 18:59:37 +00:00
return nil
}
for _, key := range keys {
ps.policyTypeMap.Store(ps.sanitizeName(key), PolicyTypeACL)
}
// Special-case root; doesn't exist on disk but does need to be found
ps.policyTypeMap.Store("root", PolicyTypeACL)
return ps
2015-03-18 19:17:03 +00:00
}
// setupPolicyStore is used to initialize the policy store
// when the vault is being unsealed.
func (c *Core) setupPolicyStore(ctx context.Context) error {
// Create the policy store
sysView := &dynamicSystemView{core: c}
c.policyStore = NewPolicyStore(ctx, c, c.systemBarrierView, sysView, c.logger.ResetNamed("policy"))
if c.ReplicationState().HasState(consts.ReplicationPerformanceSecondary) {
// Policies will sync from the primary
return nil
}
// Ensure that the default policy exists, and if not, create it
if err := c.policyStore.loadACLPolicy(ctx, defaultPolicyName, defaultPolicy); err != nil {
2017-11-13 20:31:32 +00:00
return err
}
2017-11-13 20:31:32 +00:00
// Ensure that the response wrapping policy exists
if err := c.policyStore.loadACLPolicy(ctx, responseWrappingPolicyName, responseWrappingPolicy); err != nil {
2017-11-13 20:31:32 +00:00
return err
}
return nil
}
// teardownPolicyStore is used to reverse setupPolicyStore
// when the vault is being sealed.
func (c *Core) teardownPolicyStore() error {
c.policyStore = nil
return nil
}
func (ps *PolicyStore) invalidate(ctx context.Context, name string, policyType PolicyType) {
2017-10-23 18:59:37 +00:00
// This may come with a prefixed "/" due to joining the file path
saneName := strings.TrimPrefix(name, "/")
// We don't lock before removing from the LRU here because the worst that
// can happen is we load again if something since added it
switch policyType {
case PolicyTypeACL:
if ps.tokenPoliciesLRU != nil {
ps.tokenPoliciesLRU.Remove(saneName)
}
default:
// Can't do anything
return
}
2017-10-23 18:59:37 +00:00
// Force a reload
_, err := ps.GetPolicy(ctx, name, policyType)
2017-10-23 18:59:37 +00:00
if err != nil {
ps.logger.Error("error fetching policy after invalidation", "name", saneName)
2017-10-23 18:59:37 +00:00
}
}
2015-03-18 19:17:03 +00:00
// SetPolicy is used to create or update the given policy
func (ps *PolicyStore) SetPolicy(ctx context.Context, p *Policy) error {
2015-04-08 23:43:17 +00:00
defer metrics.MeasureSince([]string{"policy", "set_policy"}, time.Now())
2017-10-23 18:59:37 +00:00
if p == nil {
return fmt.Errorf("nil policy passed in for storage")
}
2015-03-18 19:17:03 +00:00
if p.Name == "" {
return fmt.Errorf("policy name missing")
}
// Policies are normalized to lower-case
2017-10-23 18:59:37 +00:00
p.Name = ps.sanitizeName(p.Name)
2016-07-25 13:46:10 +00:00
if strutil.StrListContains(immutablePolicies, p.Name) {
return fmt.Errorf("cannot update %q policy", p.Name)
}
2015-03-18 19:17:03 +00:00
return ps.setPolicyInternal(ctx, p)
}
func (ps *PolicyStore) setPolicyInternal(ctx context.Context, p *Policy) error {
2017-10-23 18:59:37 +00:00
ps.modifyLock.Lock()
defer ps.modifyLock.Unlock()
// Create the entry
entry, err := logical.StorageEntryJSON(p.Name, &PolicyEntry{
2017-10-23 19:11:29 +00:00
Version: 2,
Raw: p.Raw,
Type: p.Type,
})
if err != nil {
return errwrap.Wrapf("failed to create entry: {{err}}", err)
2015-03-18 19:17:03 +00:00
}
2017-10-23 18:59:37 +00:00
switch p.Type {
case PolicyTypeACL:
if err := ps.aclView.Put(ctx, entry); err != nil {
2017-10-23 18:59:37 +00:00
return errwrap.Wrapf("failed to persist policy: {{err}}", err)
}
ps.policyTypeMap.Store(p.Name, PolicyTypeACL)
2015-04-06 23:41:48 +00:00
2017-10-23 18:59:37 +00:00
if ps.tokenPoliciesLRU != nil {
// Update the LRU cache
ps.tokenPoliciesLRU.Add(p.Name, p)
}
default:
return fmt.Errorf("unknown policy type, cannot set")
}
2017-10-23 18:59:37 +00:00
2015-03-18 19:17:03 +00:00
return nil
}
// GetPolicy is used to fetch the named policy
func (ps *PolicyStore) GetPolicy(ctx context.Context, name string, policyType PolicyType) (*Policy, error) {
2015-04-08 23:43:17 +00:00
defer metrics.MeasureSince([]string{"policy", "get_policy"}, time.Now())
2017-10-23 18:59:37 +00:00
// Policies are normalized to lower-case
name = ps.sanitizeName(name)
var cache *lru.TwoQueueCache
var view *BarrierView
switch policyType {
case PolicyTypeACL:
cache = ps.tokenPoliciesLRU
view = ps.aclView
case PolicyTypeToken:
cache = ps.tokenPoliciesLRU
val, ok := ps.policyTypeMap.Load(name)
if !ok {
// Doesn't exist
return nil, nil
}
policyType = val.(PolicyType)
switch policyType {
case PolicyTypeACL:
view = ps.aclView
default:
return nil, fmt.Errorf("invalid type of policy in type map: %q", policyType)
2017-10-23 18:59:37 +00:00
}
}
if cache != nil {
// Check for cached policy
2017-10-23 18:59:37 +00:00
if raw, ok := cache.Get(name); ok {
return raw.(*Policy), nil
}
2015-04-06 23:41:48 +00:00
}
2015-03-24 18:27:21 +00:00
// Special case the root policy
2017-10-23 18:59:37 +00:00
if policyType == PolicyTypeACL && name == "root" {
2015-03-24 18:27:21 +00:00
p := &Policy{Name: "root"}
2017-10-23 18:59:37 +00:00
if cache != nil {
cache.Add(p.Name, p)
}
2015-03-24 18:27:21 +00:00
return p, nil
}
2017-10-23 18:59:37 +00:00
ps.modifyLock.Lock()
defer ps.modifyLock.Unlock()
// See if anything has added it since we got the lock
if cache != nil {
if raw, ok := cache.Get(name); ok {
return raw.(*Policy), nil
}
}
out, err := view.Get(ctx, name)
2015-03-18 19:17:03 +00:00
if err != nil {
2017-10-23 18:59:37 +00:00
return nil, errwrap.Wrapf("failed to read policy: {{err}}", err)
2015-03-18 19:17:03 +00:00
}
2017-10-23 18:59:37 +00:00
2015-03-18 19:17:03 +00:00
if out == nil {
return nil, nil
}
policyEntry := new(PolicyEntry)
2017-10-23 18:59:37 +00:00
policy := new(Policy)
err = out.DecodeJSON(policyEntry)
if err != nil {
return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err)
}
// Set these up here so that they're available for loading into
// Sentinel
policy.Name = name
policy.Raw = policyEntry.Raw
policy.Type = policyEntry.Type
switch policyEntry.Type {
case PolicyTypeACL:
// Parse normally
2017-10-23 18:59:37 +00:00
p, err := ParseACLPolicy(policyEntry.Raw)
if err != nil {
2017-10-23 18:59:37 +00:00
return nil, errwrap.Wrapf("failed to parse policy: {{err}}", err)
}
2017-10-23 18:59:37 +00:00
policy.Paths = p.Paths
// Reset this in case they set the name in the policy itself
policy.Name = name
2017-10-23 18:59:37 +00:00
ps.policyTypeMap.Store(name, PolicyTypeACL)
default:
return nil, fmt.Errorf("unknown policy type %q", policyEntry.Type.String())
2015-03-18 19:17:03 +00:00
}
2015-04-06 23:43:05 +00:00
2017-10-23 18:59:37 +00:00
if cache != nil {
// Update the LRU cache
2017-10-23 18:59:37 +00:00
cache.Add(name, policy)
}
return policy, nil
2015-03-18 19:17:03 +00:00
}
// ListPolicies is used to list the available policies
func (ps *PolicyStore) ListPolicies(ctx context.Context, policyType PolicyType) ([]string, error) {
2015-04-08 23:43:17 +00:00
defer metrics.MeasureSince([]string{"policy", "list_policies"}, time.Now())
2015-03-18 19:17:03 +00:00
// Scan the view, since the policy names are the same as the
// key names.
2017-10-23 18:59:37 +00:00
var keys []string
var err error
switch policyType {
case PolicyTypeACL:
keys, err = logical.CollectKeys(ctx, ps.aclView)
2017-10-23 18:59:37 +00:00
default:
return nil, fmt.Errorf("unknown policy type %q", policyType)
2017-10-23 18:59:37 +00:00
}
2017-10-23 18:59:37 +00:00
// We only have non-assignable ACL policies at the moment
for _, nonAssignable := range nonAssignablePolicies {
deleteIndex := -1
//Find indices of non-assignable policies in keys
for index, key := range keys {
if key == nonAssignable {
// Delete collection outside the loop
deleteIndex = index
break
}
}
// Remove non-assignable policies when found
if deleteIndex != -1 {
keys = append(keys[:deleteIndex], keys[deleteIndex+1:]...)
}
}
return keys, err
2015-03-18 19:17:03 +00:00
}
// DeletePolicy is used to delete the named policy
func (ps *PolicyStore) DeletePolicy(ctx context.Context, name string, policyType PolicyType) error {
2015-04-08 23:43:17 +00:00
defer metrics.MeasureSince([]string{"policy", "delete_policy"}, time.Now())
2017-10-23 18:59:37 +00:00
ps.modifyLock.Lock()
defer ps.modifyLock.Unlock()
// Policies are normalized to lower-case
2017-10-23 18:59:37 +00:00
name = ps.sanitizeName(name)
switch policyType {
case PolicyTypeACL:
if strutil.StrListContains(immutablePolicies, name) {
return fmt.Errorf("cannot delete %q policy", name)
2017-10-23 18:59:37 +00:00
}
if name == "default" {
return fmt.Errorf("cannot delete default policy")
}
err := ps.aclView.Delete(ctx, name)
2017-10-23 18:59:37 +00:00
if err != nil {
return errwrap.Wrapf("failed to delete policy: {{err}}", err)
}
if ps.tokenPoliciesLRU != nil {
// Clear the cache
ps.tokenPoliciesLRU.Remove(name)
}
ps.policyTypeMap.Delete(name)
2015-04-06 23:41:48 +00:00
}
2015-03-18 19:17:03 +00:00
return nil
}
// ACL is used to return an ACL which is built using the
// named policies.
func (ps *PolicyStore) ACL(ctx context.Context, names ...string) (*ACL, error) {
2015-03-18 19:17:03 +00:00
// Fetch the policies
2017-10-23 18:59:37 +00:00
var policies []*Policy
2015-03-18 19:17:03 +00:00
for _, name := range names {
p, err := ps.GetPolicy(ctx, name, PolicyTypeToken)
2015-03-18 19:17:03 +00:00
if err != nil {
2017-10-23 18:59:37 +00:00
return nil, errwrap.Wrapf("failed to get policy: {{err}}", err)
2015-03-18 19:17:03 +00:00
}
2017-10-23 18:59:37 +00:00
policies = append(policies, p)
2015-03-18 19:17:03 +00:00
}
// Construct the ACL
2017-10-23 18:59:37 +00:00
acl, err := NewACL(policies)
2015-03-18 19:17:03 +00:00
if err != nil {
2017-10-23 18:59:37 +00:00
return nil, errwrap.Wrapf("failed to construct ACL: {{err}}", err)
2015-03-18 19:17:03 +00:00
}
return acl, nil
}
func (ps *PolicyStore) loadACLPolicy(ctx context.Context, policyName, policyText string) error {
2017-11-13 20:31:32 +00:00
// Check if the policy already exists
policy, err := ps.GetPolicy(ctx, policyName, PolicyTypeACL)
2017-11-13 20:31:32 +00:00
if err != nil {
2017-11-13 20:31:32 +00:00
return errwrap.Wrapf(fmt.Sprintf("error fetching %s policy from store: {{err}}", policyName), err)
}
2017-11-13 20:31:32 +00:00
if policy != nil {
if !strutil.StrListContains(immutablePolicies, policyName) || policyText == policy.Raw {
return nil
}
}
2017-11-13 20:31:32 +00:00
policy, err = ParseACLPolicy(policyText)
if err != nil {
2017-11-13 20:31:32 +00:00
return errwrap.Wrapf(fmt.Sprintf("error parsing %s policy: {{err}}", policyName), err)
}
if policy == nil {
return fmt.Errorf("parsing %q policy resulted in nil policy", policyName)
}
2017-11-13 20:31:32 +00:00
policy.Name = policyName
2017-10-23 18:59:37 +00:00
policy.Type = PolicyTypeACL
return ps.setPolicyInternal(ctx, policy)
}
2017-10-23 18:59:37 +00:00
func (ps *PolicyStore) sanitizeName(name string) string {
return strings.ToLower(strings.TrimSpace(name))
}