// unsealPart takes in a key share, and returns the master key if the threshold
// is met. If recovery keys are supported, recovery key shares may be provided.
555541
func (c *Core) unsealPart(ctx context.Context, seal Seal, key []byte, useRecoveryKeys bool) ([]byte, error) {
	// Check if we already have this piece
	if c.unlockInfo != nil {
		for _, existing := range c.unlockInfo.Parts {
			if subtle.ConstantTimeCompare(existing, key) == 1 {
				return nil, nil
			}
		}
	} else {
		uuid, err := uuid.GenerateUUID()
		if err != nil {
			return nil, err
		}
		c.unlockInfo = &unlockInformation{
			Nonce: uuid,
		}
	}

	// Store this key
	c.unlockInfo.Parts = append(c.unlockInfo.Parts, key)

	var config *SealConfig
	var err error
	if seal.RecoveryKeySupported() && (useRecoveryKeys || c.migrationSeal != nil) {
		config, err = seal.RecoveryConfig(ctx)
	} else {
		config, err = seal.BarrierConfig(ctx)
	}
	if err != nil {
		return nil, err
	}

	// Check if we don't have enough keys to unlock, proceed through the rest of
	// the call only if we have met the threshold
	if len(c.unlockInfo.Parts) < config.SecretThreshold {
		if c.logger.IsDebug() {
			c.logger.Debug("cannot unseal, not enough keys", "keys", len(c.unlockInfo.Parts), "threshold", config.SecretThreshold, "nonce", c.unlockInfo.Nonce)
		}
		return nil, nil
	}

	// Best-effort memzero of unlock parts once we're done with them
	defer func() {
		for i := range c.unlockInfo.Parts {
			memzero(c.unlockInfo.Parts[i])
		}
		c.unlockInfo = nil
	}()

	// Recover the split key. recoveredKey is the shamir combined
	// key, or the single provided key if the threshold is 1.
	var recoveredKey []byte
	var masterKey []byte
	var recoveryKey []byte
	if config.SecretThreshold == 1 {
		recoveredKey = make([]byte, len(c.unlockInfo.Parts[0]))
		copy(recoveredKey, c.unlockInfo.Parts[0])
	} else {
		recoveredKey, err = shamir.Combine(c.unlockInfo.Parts)
		if err != nil {
			return nil, errwrap.Wrapf("failed to compute master key: {{err}}", err)
		}
	}

	if seal.RecoveryKeySupported() && (useRecoveryKeys || c.migrationSeal != nil) {
		// Verify recovery key
		if err := seal.VerifyRecoveryKey(ctx, recoveredKey); err != nil {
			return nil, err
		}
		recoveryKey = recoveredKey

		// Get stored keys and shamir combine into single master key. Unsealing with
		// recovery keys currently does not support: 1) mixed stored and non-stored
		// keys setup, nor 2) seals that support recovery keys but not stored keys.
		// If insufficient shares are provided, shamir.Combine will error, and if
		// no stored keys are found it will return masterKey as nil.
		if seal.StoredKeysSupported() {
			masterKeyShares, err := seal.GetStoredKeys(ctx)
			if err != nil {
				return nil, errwrap.Wrapf("unable to retrieve stored keys: {{err}}", err)
			}

			switch len(masterKeyShares) {
			case 0:
				return nil, errors.New("seal returned no master key shares")
			case 1:
				masterKey = masterKeyShares[0]
			default:
				masterKey, err = shamir.Combine(masterKeyShares)
				if err != nil {
					return nil, errwrap.Wrapf("failed to compute master key: {{err}}", err)
				}
			}
		}
	} else {
		masterKey = recoveredKey
	}

	// If we have a migration seal, now's the time!
	if c.migrationSeal != nil {
		// Unseal the barrier so we can rekey
		if err := c.barrier.Unseal(ctx, masterKey); err != nil {
			return nil, errwrap.Wrapf("error unsealing barrier with constructed master key: {{err}}", err)
		}
		defer c.barrier.Seal()

		switch {
		case c.migrationSeal.RecoveryKeySupported() && c.seal.RecoveryKeySupported():
			// Set the recovery and barrier keys to be the same.
			recoveryKey, err := c.migrationSeal.RecoveryKey(ctx)
			if err != nil {
				return nil, errwrap.Wrapf("error getting recovery key to set on new seal: {{err}}", err)
			}

			if err := c.seal.SetRecoveryKey(ctx, recoveryKey); err != nil {
				return nil, errwrap.Wrapf("error setting new recovery key information during migrate: {{err}}", err)
			}

			barrierKeys, err := c.migrationSeal.GetStoredKeys(ctx)
			if err != nil {
				return nil, errwrap.Wrapf("error getting stored keys to set on new seal: {{err}}", err)
			}

			if err := c.seal.SetStoredKeys(ctx, barrierKeys); err != nil {
				return nil, errwrap.Wrapf("error setting new barrier key information during migrate: {{err}}", err)
			}

		case c.migrationSeal.RecoveryKeySupported():
			// Auto to Shamir, since recovery key isn't supported on new seal

			// In this case we have to ensure that the recovery information was
			// set properly.
			if recoveryKey == nil {
				return nil, errors.New("did not get expected recovery information to set new seal during migration")
			}

			// We have recovery keys; we're going to use them as the new
			// barrier key.
			if err := c.barrier.Rekey(ctx, recoveryKey); err != nil {
				return nil, errwrap.Wrapf("error rekeying barrier during migration: {{err}}", err)
			}

			if err := c.barrier.Delete(ctx, StoredBarrierKeysPath); err != nil {
				// Don't actually exit here as successful deletion isn't critical
				c.logger.Error("error deleting stored barrier keys after migration; continuing anyways", "error", err)
			}

			masterKey = recoveryKey

		case c.seal.RecoveryKeySupported():
			// The new seal will have recovery keys; we set it to the existing
			// master key, so barrier key shares -> recovery key shares
			if err := c.seal.SetRecoveryKey(ctx, masterKey); err != nil {
				return nil, errwrap.Wrapf("error setting new recovery key information: {{err}}", err)
			}

			// Generate a new master key
			newMasterKey, err := c.barrier.GenerateKey()
			if err != nil {
				return nil, errwrap.Wrapf("error generating new master key: {{err}}", err)
			}

			// Rekey the barrier
			if err := c.barrier.Rekey(ctx, newMasterKey); err != nil {
				return nil, errwrap.Wrapf("error rekeying barrier during migration: {{err}}", err)
			}

			// Store the new master key
			if err := c.seal.SetStoredKeys(ctx, [][]byte{newMasterKey}); err != nil {
				return nil, errwrap.Wrapf("error storing new master key: {[err}}", err)
			}

			// Return the new key so it can be used to unlock the barrier
			masterKey = newMasterKey

		default:
			return nil, errors.New("unhandled migration case (shamir to shamir)")
		}

		// At this point we've swapped things around and need to ensure we
		// don't migrate again
		c.migrationSeal = nil

		// Ensure we populate the new values
		bc, err := c.seal.BarrierConfig(ctx)
		if err != nil {
			return nil, errwrap.Wrapf("error fetching barrier config after migration: {{err}}", err)
		}
		if err := c.seal.SetBarrierConfig(ctx, bc); err != nil {
			return nil, errwrap.Wrapf("error storing barrier config after migration: {{err}}", err)
		}

		if c.seal.RecoveryKeySupported() {
			rc, err := c.seal.RecoveryConfig(ctx)
			if err != nil {
				return nil, errwrap.Wrapf("error fetching recovery config after migration: {{err}}", err)
			}
			if err := c.seal.SetRecoveryConfig(ctx, rc); err != nil {
				return nil, errwrap.Wrapf("error storing recovery config after migration: {{err}}", err)
			}
		}
	}

	return masterKey, nil
}
122115
func (n *nomadFSM) applyACLPolicyUpsert(buf []byte, index uint64) interface{} {
	defer metrics.MeasureSince([]string{"nomad", "fsm", "apply_acl_policy_upsert"}, time.Now())
	var req structs.ACLPolicyUpsertRequest
	if err := structs.Decode(buf, &req); err != nil {
		panic(fmt.Errorf("failed to decode request: %v", err))
	}

	if err := n.state.UpsertACLPolicies(index, req.Policies); err != nil {
		n.logger.Error("UpsertACLPolicies failed", "error", err)
		return err
	}
	return nil
}
757363
func (c *Core) RekeyVerifyRestart(recovery bool) logical.HTTPCodedError {
	c.stateLock.RLock()
	defer c.stateLock.RUnlock()
	if c.Sealed() {
		return logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error())
	}
	if c.standby {
		return logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error())
	}

	c.rekeyLock.Lock()
	defer c.rekeyLock.Unlock()

	// Attempt to generate a new nonce, but don't bail if it doesn't succeed
	// (which is extraordinarily unlikely)
	nonce, nonceErr := uuid.GenerateUUID()

	// Clear any progress or config
	if recovery {
		c.recoveryRekeyConfig.VerificationProgress = nil
		if nonceErr == nil {
			c.recoveryRekeyConfig.VerificationNonce = nonce
		}
	} else {
		c.barrierRekeyConfig.VerificationProgress = nil
		if nonceErr == nil {
			c.barrierRekeyConfig.VerificationNonce = nonce
		}
	}

	return nil
}
148375
func unmarshalAccounts(m [][]interface{}) []*Account {

	accts := []*Account{}
	for i := range m {
		a := Account{}
		for j := range m[i] {
			switch v := m[i][j].(type) {
			case []interface{}:
				a.Repos = unmarshalRepos(v)
			case map[string]interface{}:
				a.User = unmarshalUser(v)
			default: // Unknown...return error?
			}
		}
		accts = append(accts, &a)
	}

	return accts
}
556308
func (container *Container) UnmountSecrets() error {
	p, err := container.SecretMountPath()
	if err != nil {
		return err
	}
	return os.RemoveAll(p)
}
619346
func (api *PublicWhisperAPI) DeleteKeyPair(ctx context.Context, key string) (bool, error) {
	if ok := api.w.DeleteKeyPair(key); ok {
		return true, nil
	}
	return false, fmt.Errorf("key pair %s not found", key)
}
527059
func (c *Core) BarrierRekeyInit(config *SealConfig) logical.HTTPCodedError {
	if c.seal.StoredKeysSupported() {
		c.logger.Warn("stored keys supported, forcing rekey shares/threshold to 1")
		config.SecretShares = 1
		config.SecretThreshold = 1
		config.StoredShares = 1
	}

	if config.StoredShares > 0 {
		if !c.seal.StoredKeysSupported() {
			return logical.CodedError(http.StatusBadRequest, "storing keys not supported by barrier seal")
		}
		if len(config.PGPKeys) > 0 {
			return logical.CodedError(http.StatusBadRequest, "PGP key encryption not supported when using stored keys")
		}
		if config.Backup {
			return logical.CodedError(http.StatusBadRequest, "key backup not supported when using stored keys")
		}

		if c.seal.RecoveryKeySupported() {
			if config.VerificationRequired {
				return logical.CodedError(http.StatusBadRequest, "requiring verification not supported when rekeying the barrier key with recovery keys")
			}
			c.logger.Debug("using recovery seal configuration to rekey barrier key")
		}
	}

	// Check if the seal configuration is valid
	if err := config.Validate(); err != nil {
		c.logger.Error("invalid rekey seal configuration", "error", err)
		return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("invalid rekey seal configuration: {{err}}", err).Error())
	}

	c.stateLock.RLock()
	defer c.stateLock.RUnlock()
	if c.Sealed() {
		return logical.CodedError(http.StatusServiceUnavailable, consts.ErrSealed.Error())
	}
	if c.standby {
		return logical.CodedError(http.StatusBadRequest, consts.ErrStandby.Error())
	}

	c.rekeyLock.Lock()
	defer c.rekeyLock.Unlock()

	// Prevent multiple concurrent re-keys
	if c.barrierRekeyConfig != nil {
		return logical.CodedError(http.StatusBadRequest, "rekey already in progress")
	}

	// Copy the configuration
	c.barrierRekeyConfig = config.Clone()

	// Initialize the nonce
	nonce, err := uuid.GenerateUUID()
	if err != nil {
		c.barrierRekeyConfig = nil
		return logical.CodedError(http.StatusInternalServerError, errwrap.Wrapf("error generating nonce for procedure: {{err}}", err).Error())
	}
	c.barrierRekeyConfig.Nonce = nonce

	if c.logger.IsInfo() {
		c.logger.Info("rekey initialized", "nonce", c.barrierRekeyConfig.Nonce, "shares", c.barrierRekeyConfig.SecretShares, "threshold", c.barrierRekeyConfig.SecretThreshold, "validation_required", c.barrierRekeyConfig.VerificationRequired)
	}
	return nil
}
595976
func (d *AllocDir) UnmountAll() error {
	d.mu.RLock()
	defer d.mu.RUnlock()

	var mErr multierror.Error
	for _, dir := range d.TaskDirs {
		// Check if the directory has the shared alloc mounted.
		if pathExists(dir.SharedTaskDir) {
			if err := unlinkDir(dir.SharedTaskDir); err != nil {
				mErr.Errors = append(mErr.Errors,
					fmt.Errorf("failed to unmount shared alloc dir %q: %v", dir.SharedTaskDir, err))
			} else if err := os.RemoveAll(dir.SharedTaskDir); err != nil {
				mErr.Errors = append(mErr.Errors,
					fmt.Errorf("failed to delete shared alloc dir %q: %v", dir.SharedTaskDir, err))
			}
		}

		if pathExists(dir.SecretsDir) {
			if err := removeSecretDir(dir.SecretsDir); err != nil {
				mErr.Errors = append(mErr.Errors,
					fmt.Errorf("failed to remove the secret dir %q: %v", dir.SecretsDir, err))
			}
		}

		// Unmount dev/ and proc/ have been mounted.
		if err := dir.unmountSpecialDirs(); err != nil {
			mErr.Errors = append(mErr.Errors, err)
		}
	}

	return mErr.ErrorOrNil()
}
339191
func UnmarshalPubkey(pub []byte) (*ecdsa.PublicKey, error) {
	x, y := elliptic.Unmarshal(S256(), pub)
	if x == nil {
		return nil, errInvalidPubkey
	}
	return &ecdsa.PublicKey{Curve: S256(), X: x, Y: y}, nil
}
555349
func (c *Core) UnsealWithStoredKeys(ctx context.Context) error {
	c.unsealWithStoredKeysLock.Lock()
	defer c.unsealWithStoredKeysLock.Unlock()

	if !c.seal.StoredKeysSupported() {
		return nil
	}

	// Disallow auto-unsealing when migrating
	if c.IsInSealMigration() {
		return NewNonFatalError(errors.New("cannot auto-unseal during seal migration"))
	}

	sealed := c.Sealed()
	if !sealed {
		c.Logger().Warn("attempted unseal with stored keys, but vault is already unsealed")
		return nil
	}

	c.Logger().Info("stored unseal keys supported, attempting fetch")
	keys, err := c.seal.GetStoredKeys(ctx)
	if err != nil {
		return NewNonFatalError(errwrap.Wrapf("fetching stored unseal keys failed: {{err}}", err))
	}

	// This usually happens when auto-unseal is configured, but the servers have
	// not been initialized yet.
	if len(keys) == 0 {
		return NewNonFatalError(errors.New("stored unseal keys are supported, but none were found"))
	}

	unsealed := false
	keysUsed := 0
	for _, key := range keys {
		unsealed, err = c.Unseal(key)
		if err != nil {
			return NewNonFatalError(errwrap.Wrapf("unseal with stored key failed: {{err}}", err))
		}
		keysUsed++
		if unsealed {
			break
		}
	}

	if !unsealed {
		// This most likely means that the user configured Vault to only store a
		// subset of the required threshold of keys. We still consider this a
		// "success", since trying again would yield the same result.
		c.Logger().Warn("vault still sealed after using stored unseal keys", "stored_keys_used", keysUsed)
	} else {
		c.Logger().Info("unsealed with stored keys", "stored_keys_used", keysUsed)
	}

	return nil
}
319331
func (c *Core) postUnseal(ctx context.Context, ctxCancelFunc context.CancelFunc, unsealer UnsealStrategy) (retErr error) {
	defer metrics.MeasureSince([]string{"core", "post_unseal"}, time.Now())

	// Clear any out
	c.postUnsealFuncs = nil

	// Create a new request context
	c.activeContext = ctx
	c.activeContextCancelFunc.Store(ctxCancelFunc)

	defer func() {
		if retErr != nil {
			ctxCancelFunc()
			c.preSeal()
		}
	}()
	c.logger.Info("post-unseal setup starting")

	// Enable the cache
	c.physicalCache.Purge(ctx)
	if !c.cachingDisabled {
		c.physicalCache.SetEnabled(true)
	}

	// Purge these for safety in case of a rekey
	c.seal.SetBarrierConfig(ctx, nil)
	if c.seal.RecoveryKeySupported() {
		c.seal.SetRecoveryConfig(ctx, nil)
	}

	if err := unsealer.unseal(ctx, c.logger, c); err != nil {
		return err
	}

	c.metricsCh = make(chan struct{})
	go c.emitMetrics(c.metricsCh)

	// This is intentionally the last block in this function. We want to allow
	// writes just before allowing client requests, to ensure everything has
	// been set up properly before any writes can have happened.
	for _, v := range c.postUnsealFuncs {
		v()
	}

	c.logger.Info("post-unseal setup complete")
	return nil
}
1100647
func (eu ErrorUnwrapper) UnwrapError(arg interface{}) (appError, dispatchError error) {
	targ, ok := arg.(*Status)
	if !ok {
		dispatchError = errors.New("Error converting status to keybase1.Status object")
		return nil, dispatchError
	}
	if targ == nil {
		return nil, nil
	}
	if targ.Code == int(StatusCode_SCOk) {
		return nil, nil
	}

	if eu.Upcaster != nil {
		appError = eu.Upcaster(*targ)
	} else {
		appError = *targ
	}
	return appError, nil
}
1054585
func (mvcc *MVCCLevelDB) ReverseScan(startKey, endKey []byte, limit int, startTS uint64, isoLevel kvrpcpb.IsolationLevel) []Pair {
	mvcc.mu.RLock()
	defer mvcc.mu.RUnlock()

	var mvccEnd []byte
	if len(endKey) != 0 {
		mvccEnd = mvccEncode(endKey, lockVer)
	}
	iter := mvcc.db.NewIterator(&util.Range{
		Limit: mvccEnd,
	}, nil)
	defer iter.Release()

	succ := iter.Last()
	currKey, _, err := mvccDecode(iter.Key())
	// TODO: return error.
	terror.Log(errors.Trace(err))
	helper := reverseScanHelper{
		startTS:  startTS,
		isoLevel: isoLevel,
		currKey:  currKey,
	}

	for succ && len(helper.pairs) < limit {
		key, ver, err := mvccDecode(iter.Key())
		if err != nil {
			break
		}
		if bytes.Compare(key, startKey) < 0 {
			break
		}

		if !bytes.Equal(key, helper.currKey) {
			helper.finishEntry()
			helper.currKey = key
		}
		if ver == lockVer {
			var lock mvccLock
			err = lock.UnmarshalBinary(iter.Value())
			helper.entry.lock = &lock
		} else {
			var value mvccValue
			err = value.UnmarshalBinary(iter.Value())
			helper.entry.values = append(helper.entry.values, value)
		}
		if err != nil {
			logutil.Logger(context.Background()).Error("unmarshal fail", zap.Error(err))
			break
		}
		succ = iter.Prev()
	}
	if len(helper.pairs) < limit {
		helper.finishEntry()
	}
	return helper.pairs
}
745934
func GMapPut(key string, value interface{}) (interface{}, bool) {
	gmap.lock.Lock()
	defer gmap.lock.Unlock()

	checkGMap(true)
	v, ok := gmap.gm[key]
	gmap.gm[key] = value
	return v, ok
}
959276
func RecursiveUnmount(target string) error {
	mounts, err := parseMountTable(PrefixFilter(target))
	if err != nil {
		return err
	}

	// Make the deepest mount be first
	sort.Slice(mounts, func(i, j int) bool {
		return len(mounts[i].Mountpoint) > len(mounts[j].Mountpoint)
	})

	for i, m := range mounts {
		logrus.Debugf("Trying to unmount %s", m.Mountpoint)
		err = unmount(m.Mountpoint, mntDetach)
		if err != nil {
			if i == len(mounts)-1 { // last mount
				if mounted, e := Mounted(m.Mountpoint); e != nil || mounted {
					return err
				}
			} else {
				// This is some submount, we can ignore this error for now, the final unmount will fail if this is a real problem
				logrus.WithError(err).Warnf("Failed to unmount submount %s", m.Mountpoint)
			}
		}

		logrus.Debugf("Unmounted %s", m.Mountpoint)
	}
	return nil
}
832326
func (c *Ctx) UnwrapKey(sh SessionHandle, m []*Mechanism, unwrappingkey ObjectHandle, wrappedkey []byte, a []*Attribute) (ObjectHandle, error) {
	var key C.CK_OBJECT_HANDLE
	attrarena, ac, aclen := cAttributeList(a)
	defer attrarena.Free()
	mecharena, mech := cMechanism(m)
	defer mecharena.Free()
	e := C.UnwrapKey(c.ctx, C.CK_SESSION_HANDLE(sh), mech, C.CK_OBJECT_HANDLE(unwrappingkey), C.CK_BYTE_PTR(unsafe.Pointer(&wrappedkey[0])), C.CK_ULONG(len(wrappedkey)), ac, aclen, &key)
	return ObjectHandle(key), toError(e)
}
699176
func EncryptPasswordObject(ctx context.Context, password string, currentMasterKey *[]byte) (*primitive.UserPassword, *primitive.MasterKey, error) {
	pw := &primitive.UserPassword{
		Alg: Scrypt,
	}

	// Generate 128 bit (16 byte) salt for password
	salt := make([]byte, saltBytes) // 16
	_, err := rand.Read(salt)
	if err != nil {
		return nil, nil, err
	}

	// Encode salt bytes to base64url
	pw.Salt = base64.RawURLEncoding.EncodeToString(salt)

	// Create password hash bytes
	pwh, err := derivePassword(ctx, []byte(password), pw.Salt)
	if err != nil {
		return nil, nil, err
	}

	// Encode password value to base64url
	pw.Value = base64url.New(pwh)

	m, err := CreateMasterKeyObject(ctx, []byte(password), currentMasterKey)
	if err != nil {
		return nil, nil, err
	}

	return pw, m, nil
}