Commit Graph

497 Commits

Author SHA1 Message Date
Nick Cabatoff 342b61984a
Move version out of SDK. (#14229)
Move version out of SDK.  For now it's a copy rather than move: the part not addressed by this change is sdk/helper/useragent.String, which we'll want to remove in favour of PluginString.  That will have to wait until we've removed uses of useragent.String from all builtins.
2022-12-07 13:29:51 -05:00
Matt Schultz b2a7cf158f
Add ManagedMACKey interface to SDK. (#18231) 2022-12-05 17:26:16 -06:00
Anton Averchenkov a54678fb6b
Add logic to generate openapi response structures (#18192) 2022-12-05 11:11:06 -05:00
Christopher Swenson eba490ccef
Check if sys view is missing in GRPC sys view (#18210)
And return an error instead of panicking.

This situation can occur if a plugin attempts to access the system
view during setup when Vault is checking the plugin metadata.

Fixes #17878.
2022-12-02 10:12:05 -08:00
Violet Hynes 3d7f9a402f
VAULT-6368 Metrics-only listener for Agent (#18101)
* VAULT-6368 Metrics-only listener for Agent

* VAULT-6368 changelog

* VAULT-6368 Update config to use string instead of bool

* VAULT-6368 Fix leftover code

* VAULT-6368 Fix changelog

* VAULT-6368 fix typo

* VAULT-6368 recommended doc update

* VAULT-6368 use != over !(==)
2022-11-25 16:00:56 -05:00
Scott Miller b51b2a7027
Add cached OCSP client support to Cert Auth (#17093)
* wip

* Add cached OCSP client support to Cert Auth

* ->pointer

* Code cleanup

* Fix unit tests

* Use an LRU cache, and only persist up to 1000 of the most recently used values to stay under the storage entry limit

* Fix caching, add fail open mode parameter to cert auth roles

* reduce logging

* Add the retry client and GET then POST logic

* Drop persisted cache, make cache size configurable, allow for parallel testing of multiple servers

* dead code

* Update builtin/credential/cert/path_certs.go

Co-authored-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Hook invalidate to reinit the ocsp cache size

* locking

* Conditionally init the ocsp client

* Remove cache size config from cert configs, it's a backend global

* Add field

* Remove strangely complex validity logic

* Address more feedback

* Rework error returning logic

* More edge cases

* MORE edge cases

* Add a test matrix with a builtin responder

* changelog

* Use an atomic for configUpdated

* Actually use ocsp_enabled, and bind to a random port for testing

* Update builtin/credential/cert/path_login.go

Co-authored-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Refactor unit tests

* Add status to cache

* Make some functions private

* Rename for testing, and attribute

* Up to date gofumpt

* remove hash from key, and disable the vault dependent unit test

* Comment out TestMultiOCSP

* imports

* more imports

* Address semgrep results

* Attempt to pass some sort of logging to test_responder

* fix overzealous search&replace

Co-authored-by: Alexander Scheel <alex.scheel@hashicorp.com>
2022-11-21 10:39:24 -06:00
Steven Clark 610a4ede82
certutil.ParseHexFormatted fails parsing 80 hex and above (#18018)
- Switch to using ParseUint of 8 bits to parse the hex values properly
   as ParseInt limited to 8 bits will only handle values up to 127
   decimal or 7F.
2022-11-17 15:04:37 -05:00
AnPucel b554a453e2
Make request objects required (#17909) 2022-11-11 14:05:12 -08:00
Anton Averchenkov f9fac68980
Revert "Add mount path into the default generated openapi.json spec (#17839)" (#17890)
This reverts commit 02064eccb42bb2ec1a3d12ec0d49c661312acd2d.
2022-11-10 15:39:53 -08:00
Anton Averchenkov f3aea876b9
Add mount path into the default generated openapi.json spec (#17839)
The current behaviour is to only add mount paths into the generated `opeanpi.json` spec if a `generic_mount_paths` flag is added to the request. This means that we would have to maintain two different `openapi.json` files, which is not ideal. The new solution in this PR is to add `{mount_path}` into every path with a default value specified:

```diff
--    "/auth/token/accessors/": {
++    "/auth/{mount_path}/accessors/": {
      "parameters": [
        {
          "name": "mount_path",
          "description": "....",
          "in": "path",
          "schema": {
            "type": "string",
++          "default": "token"
          }
        }
      ],
```

Additionally, fixed the logic to generate the `operationId` (used to generate method names in the code generated from OpenAPI spec). It had a bug where the ID had `mountPath` in it. The new ID will look like this:

```diff
-- "operationId": "listAuthMountpathAccessors",
++ "operationId": "listTokenAccessors",
```
2022-11-10 15:44:43 -05:00
Peter Wilson 469c102fd3
Removed the legacy env var: LOGXI_FORMAT (#17822)
* Removed the legacy env var: LOGXI_FORMAT

* Added changelog

* Actually filled in the CL

* Added the name of legacy env var
2022-11-04 22:16:18 +00:00
akshya96 2945924b2b
Vault 8305 Prevent Brute Forcing in Auth methods : Setting user lockout configuration (#17338)
* config file changes

* lockout config changes

* auth tune r/w and auth tune

* removing changes at enable

* removing q.Q

* go mod tidy

* removing comments

* changing struct name for config file

* fixing mount tune

* adding test file for user lockout

* fixing comments and add changelog

* addressing comments

* fixing mount table updates

* updating consts in auth_tune

* small fixes

* adding hcl parse test

* fixing config compare

* fixing github comments

* optimize userlockouts.go

* fixing test

* minor changes

* adding comments

* adding sort to flaky test

* fix flaky test
2022-11-01 11:02:07 -07:00
John-Michael Faircloth b92d42af2e
update vault sdk and api go-plugin version to v1.4.5 (#17734)
* update sdk's go-plugin version

* update api go.mod

* update api go.mod go version and go mod tidy
2022-10-31 08:52:04 -05:00
Alexander Scheel 1733d2a3d6
Add support for PKCSv1_5_NoOID signatures (#17636)
* Add support for PKCSv1_5_NoOID signatures

This assumes a pre-hashed input has been provided to Vault, but we do
not write the hash's OID into the signature stream. This allows us to
generate the alternative PKCSv1_5_NoOID signature type rather than the
existing PKCSv1_5_DERnull signature type we presently use.

These are specified in RFC 3447 Section 9.2.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add changelog

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Exclude new none type from PSS based tests

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add tests for PKCS#1v1.5 signatures

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>
2022-10-27 08:26:20 -04:00
akshya96 1e189016e2
update protoc version to 3.21.7 oss (#17499)
* update protoc to 3.21.7

* adding changelog
2022-10-26 16:49:44 -07:00
Luis (LT) Carbonell 3425f8b36c
Add Paging Interface for LDAP Connection (#17640) 2022-10-26 14:05:53 -05:00
Alexander Scheel 09939f0ba9
Add AD mode to Transit's AEAD ciphers (#17638)
* Allow passing AssociatedData factories in keysutil

This allows the high-level, algorithm-agnostic Encrypt/Decrypt with
Factory to pass in AssociatedData, and potentially take multiple
factories (to allow KMS keys to work). On AEAD ciphers with a relevant
factory, an AssociatedData factory will be used to populate the
AdditionalData field of the SymmetricOpts struct, using it in the AEAD
Seal process.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add associated_data to Transit Encrypt/Decrypt API

This allows passing the associated_data (the last AD in AEAD) to
Transit's encrypt/decrypt when using an AEAD cipher (currently
aes128-gcm96, aes256-gcm96, and chacha20-poly1305). We err if this
parameter is passed on non-AEAD ciphers presently.

This associated data can be safely transited in plaintext, without risk
of modifications. In the event of tampering with either the ciphertext
or the associated data, decryption will fail.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add changelog

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add to documentation

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>
2022-10-24 13:41:02 -04:00
Violet Hynes 5861c51e70
VAULT-8719 Support data array for alias clash error response so UI/machines can understand error (#17459)
* VAULT-8719 Support data array for alias clash error response so UI can understand error

* VAULT-8719 Changelog

* VAULT-8719 Update alias mount update logic

* VAULT-8719 Further restrict IsError()
2022-10-17 14:46:25 -04:00
Violet Hynes 4ba81e4174
Delete empty test (#17467) 2022-10-07 14:11:52 -04:00
Ruben De Visscher 1f0cf558a9
Fix for duplicate SANs in signed certificates (#16700)
* Fix for duplicate SANs in signed certificates when othernames are present in the CSR SAN extension and UseCSRValues is true.

When UseCSRValues is true (as is the case on the sign-verbatim endpoint), all extensions including Subject Alternative Names are copied from the CSR to the final certificate.
If the Subject Alternative Name in question contains any othernames (such as a Microsoft UPN) the SAN extension is added again as a workaround for an encoding issue (in function HandleOtherSANs).
Having duplicate x509v3 extensions is invalid and is rejected by openssl on Ubuntu 20.04, and also by Go since https://github.com/golang/go/issues/50988 (including in Go 1.19).

In this fix I do not add the extension from the CSR if it will be added during HandleOtherSANs.

* Added unittest and changelog entry.
2022-10-07 12:19:08 -04:00
Alexander Scheel 412603befd
Fix RevocationSigAlg provisioning in GCP (#17449)
* Fix RevocationSigAlg provisioning in GCP

GCP restricts keys to a certain type of signature, including hash
algorithm, so we must provision our RevocationSigAlg from the root
itself unconditionally in order for GCP to work.

This does change the default, but only for newly created certificates.

Additionally, we clarify that CRL building is not fatal to the import
process.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add inverse mapping for SignatureAlgorithm

By default we'd use .String() on x509.SignatureAlgorithm, but this
doesn't round-trip. Switch to a custom map that is round-trippable
and matches the constant name as there is no other way to get this info
presently.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add test to ensure root creation sets rev_sig_alg

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Test round-tripping of SigAlgoNames, InvSigAlgoNames

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Fix failing Default Update test

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>
2022-10-06 17:50:49 -04:00
Tom Proctor 3aa2fe8d8f
Plugins: Tighten requirements for multiplexing (#17403)
Change the multiplexing key to use all `PluginRunner` config (converted to a struct which is comparable), so that plugins with the same name but different env, args, types, versions etc are not incorrectly multiplexed together.

Co-authored-by: Christopher Swenson <christopher.swenson@hashicorp.com>
2022-10-05 09:29:29 +01:00
Steven Clark 10ecf10248
PKI: Add support for signature_bits param to the intermediate/generate api (#17388)
* PKI: Add support for signature_bits param to the intermediate/generate api

 - Mainly to work properly with GCP backed managed keys, we need to
   issue signatures that would match the GCP key algorithm.
 - At this time due to https://github.com/golang/go/issues/45990 we
   can't issue PSS signed CSRs, as the libraries in Go always request
   a PKCS1v15.
 - Add an extra check in intermediate/generate that validates the CSR's
   signature before providing it back to the client in case we generated
   a bad signature such as if an end-user used a GCP backed managed key
   with a RSA PSS algorithm.
   - GCP ignores the requested signature type and always signs with the
     key's algorithm which can lead to a CSR that says it is signed with
     a PKCS1v15 algorithm but is actually a RSA PSS signature

* Add cl

* PR feedback
2022-10-03 12:39:54 -04:00
vinay-gopalan c88d53c708
fix: remove premature GRPC client connection close from vault (#17321) 2022-09-29 14:11:34 -07:00
Steven Clark 1f459a2df6
PKI: Fix managed key signatures when using specified signature_bits (#17328)
* PKI: Fix managed key signatures when using specified signature_bits

 - When calling sign-intermediate and other apis with signature_bits
   value overridden with a backing managed key we did not use that
   value as tests for the private key type were not working.

* Add cl
2022-09-28 09:08:23 -04:00
akshya96 542570c289
Return errInvalidCredentials when wrong credentials is provided for existent users (#17104)
* adding errInvalidCredentials

* fixing tests

* add changelog

* fixing fmt errors

* test if routeErr is seen externally and fixing error comment

* adding fmt changes

* adding comments
2022-09-27 16:49:14 -07:00
Violet Hynes 5bcd0c31cb
VAULT-6938 Remove license from being cache exempt (#17265)
* VAULT-6938 Remove license from being cache exempt

* VAULT-6938 Add changelog

* VAULT-6938 Typo in changelog name

* Update changelog/17265.txt

Co-authored-by: Nick Cabatoff <ncabatoff@hashicorp.com>

Co-authored-by: Nick Cabatoff <ncabatoff@hashicorp.com>
2022-09-26 10:26:07 -04:00
Alexander Scheel 3015689848
Update tlsutil to v0.1.2 for ecdsa algo naming (#17282)
* Update tlsutil in sdk

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Update tlsutil in API

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Update tlsutil to v0.1.2 for ecdsa algo naming

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>
2022-09-23 08:28:40 -04:00
Tom Proctor e21995fa27
Plugins: Update running version everywhere running sha256 is set (#17292) 2022-09-23 11:19:38 +01:00
Christopher Swenson 2c8e88ab67
Check if plugin version matches running version (#17182)
Check if plugin version matches running version

When registering a plugin, we check if the request version matches the
self-reported version from the plugin. If these do not match, we log a
warning.

This uncovered a few missing pieces for getting the database version
code fully working.

We added an environment variable that helps us unit test the running
version behavior as well, but only for approle, postgresql, and consul
plugins.

Return 400 on plugin not found or version mismatch

Populate the running SHA256 of plugins in the mount and auth tables (#17217)
2022-09-21 12:25:04 -07:00
Austin Gebauer 65b851bc2c
Fixes concurrent map writes in GRPC plugin server setup (#17247)
* Fixes concurrent map writes in GRPC plugin server setup

* move lock closer to critical section
2022-09-21 11:04:20 -07:00
Steven Clark e5319bcc3c
Bump version in SDK to 1.13 for next major release (#17233) 2022-09-20 15:40:06 -04:00
Steven Clark dae2ef535b
Update protos to match update of protobuf go library (#17215) 2022-09-19 16:45:44 -04:00
Steven Clark 05a5928b8d
Update missing go-kms-wrapping v2 dep and address some ENT->OSS drift (#17178)
* Update missing go-kms-wrapping v2 dep and address some ENT->OSS drift

* Bump go-kms-wrapping/wrappers/gcpckms/v2 to v2.0.1
2022-09-19 10:23:40 -04:00
Christopher Swenson b136a7ecd8
Add plugin version to GRPC interface (#17088)
Add plugin version to GRPC interface

Added a version interface in the sdk/logical so that it can be shared between all plugin types, and then wired it up to RunningVersion in the mounts, auth list, and database systems.

I've tested that this works with auth, database, and secrets plugin types, with the following logic to populate RunningVersion:

If a plugin has a PluginVersion() method implemented, then that is used
If not, and the plugin is built into the Vault binary, then the go.mod version is used
Otherwise, the it will be the empty string.
My apologies for the length of this PR.

* Placeholder backend should be external

We use a placeholder backend (previously a framework.Backend) before a
GRPC plugin is lazy-loaded. This makes us later think the plugin is a
builtin plugin.

So we added a `placeholderBackend` type that overrides the
`IsExternal()` method so that later we know that the plugin is external,
and don't give it a default builtin version.
2022-09-15 16:37:59 -07:00
Josh Black 1e6401a8eb
make proto (#17120) 2022-09-13 16:06:11 -04:00
Josh Black 6d94dd991d
merkle sync undo logs (#17103) 2022-09-13 10:03:19 -07:00
Hamid Ghaf ed0a9feb7f
running make proto (#17106) 2022-09-13 09:40:12 -04:00
Mike Palmiotto 9849af8663
Add deprecation status to plugin api and cli (#17077)
* api: Add deprecation status to plugin endpoints

* cli: Add -detailed flag to `plugin list`

* docs: Update plugin list/info docs
2022-09-09 16:03:07 -04:00
Tom Proctor 65adf42d48
Support running versioned plugins from the catalog (#17015) 2022-09-09 18:14:26 +01:00
Tom Proctor aa50e42fca
Support version selection for database plugins (#16982)
* Support version selection for database plugins
* Don't consider unversioned plugins for version selection algorithm
* Added version to 'plugin not found' error
* Add PluginFactoryVersion function to avoid changing sdk/ API
2022-09-09 17:32:28 +01:00
Max Coulombe f9b5d1a563
Multiplexing opt out flag (#16972)
* added mplexing opt-out flag
2022-09-08 11:32:46 -04:00
Josh Black d8e0a13aae
update gofumpt to 0.3.1 and reformat the repo (#17055)
* update gofumpt to 0.3.1 and reformat the repo

* output the version of the formatter we're using
2022-09-07 17:31:20 -07:00
Mike Palmiotto bf744e3bde
Handle deprecated builtins (#17005)
* core: Handle deprecated mounts on enable and unseal
* changelog: Deprecation Status handling
* core: Add Pending Removal override var
* core: Add some documentation for Pending Removal override
2022-09-06 15:49:35 -04:00
Steven Clark 98fffbe949
Address failures in FIPS builds around new transit RSA PSS tests (#17024)
- When we added new tests that validate the RSA PSS feature, they
   work properly on normal Go builds, but tests underneath the Boring
   Crypto fips implementations fail due to a lack of SHA3 support in
   FIPS 140-2.
2022-09-06 13:40:13 -04:00
Scott Miller 606edb66d6
Add support for a dedicated HMAC type in Transit. (#16668)
* Get import correct

* limits, docs

* changelog

* unit tests

* And fix import for hmac unit test

* typo

* Update website/content/api-docs/secret/transit.mdx

Co-authored-by: Matt Schultz <975680+schultz-is@users.noreply.github.com>

* Update builtin/logical/transit/path_keys.go

Co-authored-by: Matt Schultz <975680+schultz-is@users.noreply.github.com>

* Validate key sizes a bit more carefully

* Update sdk/helper/keysutil/policy.go

Co-authored-by: Matt Schultz <975680+schultz-is@users.noreply.github.com>

Co-authored-by: Matt Schultz <975680+schultz-is@users.noreply.github.com>
2022-09-06 10:17:58 -05:00
Christopher Swenson 09ad6ab72c
Update mount table and CLI with plugin version for auth (#16856) 2022-08-31 19:23:05 +01:00
Trishank Karthik Kuppusamy 303f59dce3
Allow configuring the possible salt lengths for RSA PSS signatures (#16549)
* accommodate salt lengths for RSA PSS

* address feedback

* generalise salt length to an int

* fix error reporting

* Revert "fix error reporting"

This reverts commit 8adfc15fe3303b8fdf9f094ea246945ab1364077.

* fix a faulty check

* check for min/max salt lengths

* stringly-typed HTTP param

* unit tests for sign/verify HTTP requests

also, add marshaling for both SDK and HTTP requests

* randomly sample valid salt length

* add changelog

* add documentation
2022-08-31 12:27:03 -04:00
John-Michael Faircloth b6c05fae33
feature: secrets/auth plugin multiplexing (#14946)
* enable registering backend muxed plugins in plugin catalog

* set the sysview on the pluginconfig to allow enabling secrets/auth plugins

* store backend instances in map

* store single implementations in the instances map

cleanup instance map and ensure we don't deadlock

* fix system backend unit tests

move GetMultiplexIDFromContext to pluginutil package

fix pluginutil test

fix dbplugin ut

* return error(s) if we can't get the plugin client

update comments

* refactor/move GetMultiplexIDFromContext test

* add changelog

* remove unnecessary field on pluginClient

* add unit tests to PluginCatalog for secrets/auth plugins

* fix comment

* return pluginClient from TestRunTestPlugin

* add multiplexed backend test

* honor metadatamode value in newbackend pluginconfig

* check that connection exists on cleanup

* add automtls to secrets/auth plugins

* don't remove apiclientmeta parsing

* use formatting directive for fmt.Errorf

* fix ut: remove tls provider func

* remove tlsproviderfunc from backend plugin tests

* use env var to prevent test plugin from running as a unit test

* WIP: remove lazy loading

* move non lazy loaded backend to new package

* use version wrapper for backend plugin factory

* remove backendVersionWrapper type

* implement getBackendPluginType for plugin catalog

* handle backend plugin v4 registration

* add plugin automtls env guard

* modify plugin factory to determine the backend to use

* remove old pluginsets from v5 and log pid in plugin catalog

* add reload mechanism via context

* readd v3 and v4 to pluginset

* call cleanup from reload if non-muxed

* move v5 backend code to new package

* use context reload for for ErrPluginShutdown case

* add wrapper on v5 backend

* fix run config UTs

* fix unit tests

- use v4/v5 mapping for plugin versions
- fix test build err
- add reload method on fakePluginClient
- add multiplexed cases for integration tests

* remove comment and update AutoMTLS field in test

* remove comment

* remove errwrap and unused context

* only support metadatamode false for v5 backend plugins

* update plugin catalog errors

* use const for env variables

* rename locks and remove unused

* remove unneeded nil check

* improvements based on staticcheck recommendations

* use const for single implementation string

* use const for context key

* use info default log level

* move pid to pluginClient struct

* remove v3 and v4 from multiplexed plugin set

* return from reload when non-multiplexed

* update automtls env string

* combine getBackend and getBrokeredClient

* update comments for plugin reload, Backend return val and log

* revert Backend return type

* allow non-muxed plugins to serve v5

* move v5 code to existing sdk plugin package

* do next export sdk fields now that we have removed extra plugin pkg

* set TLSProvider in ServeMultiplex for backwards compat

* use bool to flag multiplexing support on grpc backend server

* revert userpass main.go

* refactor plugin sdk

- update comments
- make use of multiplexing boolean and single implementation ID const

* update comment and use multierr

* attempt v4 if dispense fails on getPluginTypeForUnknown

* update comments on sdk plugin backend
2022-08-29 21:42:26 -05:00
Alexander Scheel e03fb14be4
Support for generating Delta CRLs (#16773)
* Allow generation of up-to-date delta CRLs

While switching to periodic rebuilds of CRLs alleviates the constant
rebuild pressure on Vault during times of high revocation, the CRL
proper becomes stale. One response to this is to switch to OCSP, but not
every system has support for this. Additionally, OCSP usually requires
connectivity and isn't used to augment a pre-distributed CRL (and is
instead used independently).

By generating delta CRLs containing only new revocations, an existing
CRL can be supplemented with newer revocations without requiring Vault
to rebuild all complete CRLs. Admins can periodically fetch the delta
CRL and add it to the existing CRL and applications should be able to
support using serials from both.

Because delta CRLs are emptied when the next complete CRL is rebuilt, it
is important that applications fetch the delta CRL and correlate it to
their complete CRL; if their complete CRL is older than the delta CRL's
extension number, applications MUST fetch the newer complete CRL to
ensure they have a correct combination.

This modifies the revocation process and adds several new configuration
options, controlling whether Delta CRLs are enabled and when we'll
rebuild it.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add tests for delta CRLs

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add changelog entry

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add documentation on delta CRLs

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Address review feedback: fix several bugs

Thanks Steve!

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Correctly invoke periodic func on active nodes

We need to ensure we read the updated config (in case of OCSP request
handling on standby nodes), but otherwise want to avoid CRL/DeltaCRL
re-building.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>
2022-08-29 11:37:09 -04:00
Tom Proctor 4edf768f17
Version-aware plugin catalog (#16688)
Adds support for using semantic version information when registering
and managing plugins. New `detailed` field in the response data for listing
plugins and new `version` field in the response data for reading a
single plugin.
2022-08-25 21:31:42 +01:00
Mike Palmiotto 6a438fd087
Vault 7133/registry status (#16846)
* plugins: Add Deprecation Status to builtinRegistry

* changelog: Deprecation Status method
2022-08-23 16:34:30 -04:00
Violet Hynes 0b3d7fdf10
VAULT-7698 Fix ignored parameter warnings for endpoint arbitrary data options (#16794)
* VAULT-7698 Fix warnings for endpoint arbitrary data options

* VAULT-7698 Add changelog
2022-08-23 08:51:23 -04:00
Steven Clark 69396b89a7
Revert "Do not mask RSA verification misuse errors as verification failures (#16695)" (#16756)
This reverts commit 34225943c5a3ff60c9be14dc8522862023af5d9b.
2022-08-22 10:15:15 -04:00
Alexander Scheel 1e6730573c
Add proof possession revocation for PKI secrets engine (#16566)
* Allow Proof of Possession based revocation

Revocation by proof of possession ensures that we have a private key
matching the (provided or stored) certificate. This allows callers to
revoke certificate they own (as proven by holding the corresponding
private key), without having an admin create innumerable ACLs around
the serial_number parameter for every issuance/user.

We base this on Go TLS stack's verification of certificate<->key
matching, but extend it where applicable to ensure curves match, the
private key is indeed valid, and has the same structure as the
corresponding public key from the certificate.

This endpoint currently is authenticated, allowing operators to disable
the endpoint if it isn't desirable to use, via ACL policies.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Clarify error message on ParseDERKey

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add changelog entry

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Leave revoke-with-key authenticated

After some discussion, given the potential for DoS (via submitting a lot
of keys/certs to validate, including invalid pairs), it seems best to
leave this as an authenticated endpoint. Presently in Vault, there's no
way to have an authenticated-but-unauthorized path (i.e., one which
bypasses ACL controls), so it is recommended (but not enforced) to make
this endpoint generally available by permissive ACL policies.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add API documentation on PoP

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add acceptance tests for Proof of Possession

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Exercise negative cases in PoP tests

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>
2022-08-16 14:01:26 -04:00
Steven Clark 29099f2ef9
Do not mask RSA verification misuse errors as verification failures (#16695)
- Found by @trishankatdatadog in PR #16549, we were masking errors
   coming out of the rsa verification calls as verfication errors and
   not returning when they were usage errors.
2022-08-12 13:53:25 -04:00
Chris Capurso a0c557f38a
VAULT-7256: Add custom_metadata to namespaces (#16640)
* add mapstructure tags to Namespace struct

* add custom metadata Parse helper

* add ns custom metadata and patch
2022-08-09 11:38:03 -04:00
Eng Zer Jun 61262ad98e
refactor: replace strings.Replace with strings.ReplaceAll (#15392)
strings.ReplaceAll(s, old, new) is a wrapper function for
strings.Replace(s, old, new, -1). But strings.ReplaceAll is more
readable and removes the hardcoded -1.

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
2022-08-03 15:22:48 -04:00
swayne275 4632a26a09
Use %q for quoted strings where appropriate (#15216)
* change '%s' to %q where single vs double quotes shouldn't matter

* replace double quotes with %q in logs and errors
2022-08-03 12:32:45 -06:00
Alexander Scheel 8acbf7f480
Add PSS support to PKI Secrets Engine (#16519)
* Add PSS signature support to Vault PKI engine

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Use issuer's RevocationSigAlg for CRL signing

We introduce a new parameter on issuers, revocation_signature_algorithm
to control the signature algorithm used during CRL signing. This is
because the SignatureAlgorithm value from the certificate itself is
incorrect for this purpose: a RSA root could sign an ECDSA intermediate
with say, SHA256WithRSA, but when the intermediate goes to sign a CRL,
it must use ECDSAWithSHA256 or equivalent instead of SHA256WithRSA. When
coupled with support for PSS-only keys, allowing the user to set the
signature algorithm value as desired seems like the best approach.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add use_pss, revocation_signature_algorithm docs

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add PSS to signature role issuance test matrix

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add changelog

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Allow roots to self-identify revocation alg

When using PSS support with a managed key, sometimes the underlying
device will not support PKCS#1v1.5 signatures. This results in CRL
building failing, unless we update the entry's signature algorithm
prior to building the CRL for the new root.

With a RSA-type key and use_pss=true, we use the signature bits value to
decide which hash function to use for PSS support.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add clearer error message on failed import

When CRL building fails during cert/key import, due to PSS failures,
give a better indication to the user that import succeeded its just CRL
building that failed. This tells them the parameter to adjust on the
issuer and warns that CRL building will fail until this is fixed.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add case insensitive SigAlgo matching

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Convert UsePSS back to regular bool

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Refactor PSS->certTemplate into helper function

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Proper string output on rev_sig_alg display

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Copy root's SignatureAlgorithm for CRL building

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>
2022-08-03 12:42:24 -04:00
Alexander Scheel cf7105929f
Allow old certs to be cross-signed (#16494)
* Allow old certs to be cross-signed

In Vault 1.11, we introduced cross-signing support, but the earlier SKID
field change in Vault 1.10 causes problems: notably, certs created on
older versions of Vault (<=1.9) or outside of Vault (with a different
SKID method) cannot be cross-signed and validated in OpenSSL.

In particular, OpenSSL appears to be unique in requiring a SKID/AKID
match for chain building. If AKID and SKID are present on an otherwise
valid client/parent cert pair and the values are different, OpenSSL will
not build a valid path over those two, whereas most other chain
validation implementations will.

Regardless, to have proper cross-signing support, we really aught to
support copying an SKID. This adds such support to the sign-intermediate
endpoint. Support for the /issue endpoint is not added, as cross-signing
leaf certs isn't generally useful and can accept random SKIDs.

Resolves: #16461

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add changelog

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Address review feedback, fix tests

Also adds a known-answer test using LE R3 CA's SKID.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Address review feedback regarding separators

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>
2022-08-03 06:34:21 -07:00
Chris Capurso 36e20779bc
VAULT-7256 - Add CustomMetadata to Namespace type (#16491)
* remove CustomMetadata type

* add custom metadata to namespace struct
2022-07-29 10:04:57 -04:00
Chris Capurso 013e1d12b1
move custom metadata validation logic to its own package (#16464)
* move custom metadata validation logic to its own package

* add comments

* add custom metadata Validate unit tests
2022-07-28 10:40:38 -04:00
John-Michael Faircloth a5349bd1ef
Revert "AutoMTLS for secrets/auth plugins (#15671)" (#16377)
This reverts commit 39bcd5c71529f5f4eb61aae68b17d06d192ea55f.
2022-07-20 10:36:23 -05:00
John-Michael Faircloth 7e170e7d87
AutoMTLS for secrets/auth plugins (#15671)
* use automtls for v5 secrets/auth plugins

* add automtls env guard

* start backend without metadata mode

* use PluginClientConfig for backend's NewPluginClient param

refactor

* - fix pluginutil test
- do not expect plugin to be unloaded in UT
- fix pluginutil tests --need new env var
- use require in UT
- fix lazy load test

* add changelog

* prioritize automtls; improve comments

* user multierror; refactor pluginSet for v4 unit test

* add test cases for v4 and v5 plugin versions

* remove unnecessary call to AutoMTLSSupported

* update comment on pluginSets

* use runconfig directly in sdk newpluginclient

* use automtls without metadatamode for v5 backend plugin registration

* use multierror for plugin runconfig calls

* remove some unnecessary code
2022-07-18 16:25:18 -05:00
Violet Hynes 0c80ee5cf5
VAULT-6614 Enable role based quotas for lease-count quotas (OSS) (#16157)
* VAULT-6613 add DetermineRoleFromLoginRequest function to Core

* Fix body handling

* Role resolution for rate limit quotas

* VAULT-6613 update precedence test

* Add changelog

* VAULT-6614 start of changes for roles in LCQs

* Expiration changes for leases

* Add role information to RequestAuth

* VAULT-6614 Test updates

* VAULT-6614 Add expiration test with roles

* VAULT-6614 fix comment

* VAULT-6614 Protobuf on OSS

* VAULT-6614 Add rlock to determine role code

* VAULT-6614 Try lock instead of rlock

* VAULT-6614 back to rlock while I think about this more

* VAULT-6614 Additional safety for nil dereference

* VAULT-6614 Use %q over %s

* VAULT-6614 Add overloading to plugin backends

* VAULT-6614 RLocks instead

* VAULT-6614 Fix return for backend factory
2022-07-05 13:02:00 -04:00
AnPucel 3215cdbd32
Dynamic parameter for mountpaths in OpenApi Spec generation(#15835)
"generic_mount_paths" query parameter for OpenApiSpec generation
2022-06-30 07:43:04 -07:00
Chris Capurso 9501d44ed5
Add endpoints to provide ability to modify logging verbosity (#16111)
* add func to set level for specific logger

* add endpoints to modify log level

* initialize base logger with IndependentLevels

* test to ensure other loggers remain unchanged

* add DELETE loggers endpoints to revert back to config

* add API docs page

* add changelog entry

* remove extraneous line

* add log level field to Core struct

* add godoc for getLogLevel

* add some loggers to c.allLoggers
2022-06-27 11:39:53 -04:00
Violet Hynes 56ed9ca8ae
Start of implementation of the plumbing for role resolution logic on auth mounts (#16049)
* VAULT-6612 Initial scaffolding for role determination

* VAULT-6612 Simplify code

* Fix fmt error that somehow happened

* VAULT-6612 Refactor resolve role response
2022-06-21 09:31:36 -04:00
shujun10086 9f0a72ef2a
Fix keyring file missing after Vault restart (#15946) 2022-06-15 10:22:42 -07:00
VAL bbcd47b10a
Update minimum required go version for sdk (#15913) 2022-06-09 12:25:24 -07:00
Alexander Scheel ea6452757f
Add parsing for NSS-wrapped Ed25519 keys (#15742)
* Add parsing for NSS-wrapped Ed25519 keys

NSS wraps Ed25519 using the PKCS#8 standard structure. The Go standard
library as of Go 1.18.x doesn't support parsing this key type with the
OID used by NSS; it requires the 1.3.101.112/RFC 8410 format, rather
than the RFC 5915-esque structure supported here.

Co-authored-by: Rachel Culpepper <84159930+rculpepper@users.noreply.github.com>
Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add integration test with NSS-created wrapped key

Co-authored-by: Rachel Culpepper <84159930+rculpepper@users.noreply.github.com>
Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add changelog

Co-authored-by: Rachel Culpepper <84159930+rculpepper@users.noreply.github.com>
Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

Co-authored-by: Rachel Culpepper <84159930+rculpepper@users.noreply.github.com>
2022-06-06 18:09:21 -04:00
Austin Gebauer 66fae8b72a
secrets/db: fix structpb conversion for external plugins using alternative cred types (#15801) 2022-06-03 16:15:09 -07:00
Kit Haines 4f532ecc4d
Support for CPS URLs in Custom Policy Identifiers. (#15751)
* Support for CPS URLs in Custom Policy Identifiers.

* go fmt

* Add Changelog

* Fix panic in test-cases.

* Update builtin/logical/pki/path_roles.go

Fix intial nil identifiers.

Co-authored-by: Steven Clark <steven.clark@hashicorp.com>

* Make valid policy OID so don't break ASN parse in test.

* Add test cases.

* go fmt.

Co-authored-by: Steven Clark <steven.clark@hashicorp.com>
2022-06-03 14:50:46 -04:00
Alexander Scheel 03efc71e62
Update to fixed parseutil v0.1.6 (#15774)
Note that this only really applies to the SSH engine, nothing else uses
this helper. Other go.mod's updated for consistency.

See also: https://github.com/hashicorp/go-secure-stdlib/pull/40

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>
2022-06-02 17:31:45 -04:00
Chris Capurso 3929d47147
Prep for 1.12 (#15612)
* set sdk version to 1.12.0

* remove 1.7.x and add 1.11.x branches in ci.hcl
2022-05-25 16:18:41 -04:00
Jim Kalafut a3b0b60a73
postgres: replace the package lib/pq with pgx (#15343)
* WIP replacing lib/pq

* change timezome param to be URI format

* add changelog

* add changelog for redshift

* update changelog

* add test for DSN style connection string

* more parseurl and quoteidentify to sdk; include copyright and license

* call dbutil.ParseURL instead, fix import ordering

Co-authored-by: Calvin Leung Huang <1883212+calvn@users.noreply.github.com>
2022-05-23 12:49:18 -07:00
Rémi Lapeyre d66333f7ac
Fix handling of username_as_alias during LDAP authentication (#15525)
* Fix handling of username_as_alias during LDAP authentication

There is a bug that was introduced in the LDAP authentication method by https://github.com/hashicorp/vault/pull/11000.
It was thought to be backward compatible but has broken a number of users. Later
a new parameter `username_as_alias` was introduced in https://github.com/hashicorp/vault/pull/14324
to make it possible for operators to restore the previous behavior.
The way it is currently working is not completely backward compatible thought
because when username_as_alias is set, a call to GetUserAliasAttributeValue() will
first be made, then this value is completely discarded in pathLogin() and replaced
by the username as expected.

This is an issue because it makes useless calls to the LDAP server and will break
backward compatibility if one of the constraints in GetUserAliasAttributeValue()
is not respected, even though the resulting value will be discarded anyway.

In order to maintain backward compatibility here we have to only call
GetUserAliasAttributeValue() if necessary.

Since this change of behavior was introduced in 1.9, this fix will need to be
backported to the 1.9, 1.10 and 1.11 branches.

* Add changelog

* Add tests

* Format code

* Update builtin/credential/ldap/backend.go

Co-authored-by: Calvin Leung Huang <1883212+calvn@users.noreply.github.com>

* Format and fix declaration

* Reword changelog

Co-authored-by: Calvin Leung Huang <1883212+calvn@users.noreply.github.com>
2022-05-20 14:17:26 -07:00
Pratyoy Mukhopadhyay 62c09bc2be
oss changes (#15487)
* oss changes

* add changelog
2022-05-18 09:16:13 -07:00
akshya96 4e9e9b7eda
Vault-6037 making filesystem permissions check opt-in (#15452)
* adding env var changes

* adding changelog

* adding strcov.ParseBool
2022-05-17 11:34:31 -07:00
Austin Gebauer d3629ab49d
secrets/database: adds ability to manage alternative credential types and configuration (#15376) 2022-05-17 09:21:26 -07:00
Alexander Scheel 60acf9ad6e
Update parseutil in API, SDK (#15465)
Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>
2022-05-17 11:44:32 -04:00
Brian Kassouf b5472aadf3
Add list of granting policies audit logs (#15457)
* Add list of granting policies audit logs

* Add changelog
2022-05-16 16:23:08 -07:00
Matt Schultz 3d1f40f850
Fix a keysutil policy lock (#15447)
* Defer an unlock call for keysutil policy imports.

* Make Transit import key type field case-insensitive for convenience.
2022-05-16 13:00:16 -05:00
Matt Schultz 611ab91e5a
Transit byok import endpoints (#15414)
* add import endpoint

* fix unlock

* add import_version

* refactor import endpoints and add tests

* add descriptions

* Update dependencies to include tink for Transit import operations. Convert Transit wrapping key endpoint to use shared wrapping key retrieval method. Disallow import of convergent keys to Transit via BYOK process.

* Include new 'hash_function' parameter on Transit import endpoints to specify OAEP random oracle hash function used to wrap ephemeral AES key.

* Add default values for Transit import endpoint fields. Prevent an OOB panic in Transit import. Proactively zero out ephemeral AES key used in Transit imports.

* Rename some Transit BYOK import variables. Ensure Transit BYOK ephemeral key is of the size specified byt the RFC.

* Add unit tests for Transit BYOK import endpoint.

* Simplify Transit BYOK import tests. Add a conditional on auto rotation to avoid errors on BYOK keys with allow_rotation=false.

* Added hash_function field to Transit import_version endpoint. Reworked Transit import unit tests. Added unit tests for Transit import_version endpoint.

* Add changelog entry for Transit BYOK.

* Transit BYOK formatting fixes.

* Omit 'convergent_encryption' field from Transit BYOK import endpoint, but reject with an error when the field is provided.

* Minor formatting fix in Transit import.

Co-authored-by: rculpepper <rculpepper@hashicorp.com>
2022-05-16 11:50:38 -05:00
Steven Clark 9607c5be97
Use backendUUID instead of mount points for managed keys (OSS) (#15441)
- Remove all references to mount point within PKI
 - Leverage the mount's backend UUID now instead of a mount point for all
   managed key lookups.
2022-05-16 12:48:54 -04:00
Alexander Scheel 48f3279c49
Return names for leaf_not_after_behavior responses (#15336)
Previously we'd return the raw enum value, which the entity accessing
the API wouldn't have any easy way of translating back into string
values. Return the string value directly instead.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>
2022-05-11 13:12:04 -04:00
Alexander Scheel 8408c19115
Root issuers lack CA Chain + Chain Building Bug Fix (#15306)
* Return the ca_chain response from root issued cert api

* Fix parent selection in cert chain building

When building chains, we'd choose the next neighbor from Go's
unordered map. However, this doesn't necessarily result in the most
optimal path: we want to prefer to visit roots over other
intermediates, as this allows us to have a more consistent chain,
putting roots before their cross-signed equivalents rather than
potentially at the end.

We additionally now ensure chains are stable.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

Co-authored-by: Steve Clark <steven.clark@hashicorp.com>
2022-05-11 13:09:18 -04:00
Alexander Scheel 4f6c6ac317
Allow Multiple Issuers in PKI Secret Engine Mounts - PKI Pod (#15277)
* Starter PKI CA Storage API (#14796)

* Simple starting PKI storage api for CA rotation
* Add key and issuer storage apis
* Add listKeys and listIssuers storage implementations
* Add simple keys and issuers configuration storage api methods

* Handle resolving key, issuer references

The API context will usually have a user-specified reference to the key.
This is either the literal string "default" to select the default key,
an identifier of the key, or a slug name for the key. Here, we wish to
resolve this reference to an actual identifier that can be understood by
storage.

Also adds the missing Name field to keys.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add method to fetch an issuer's cert bundle

This adds a method to construct a certutil.CertBundle from the specified
issuer identifier, optionally loading its corresponding key for signing.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Refactor certutil PrivateKey PEM handling

This refactors the parsing of PrivateKeys from PEM blobs into shared
methods (ParsePEMKey, ParseDERKey) that can be reused by the existing
Bundle parsing logic (ParsePEMBundle) or independently in the new
issuers/key-based PKI storage code.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add importKey, importCert to PKI storage

importKey is generally preferable to the low-level writeKey for adding
new entries. This takes only the contents of the private key (as a
string -- so a PEM bundle or a managed key handle) and checks if it
already exists in the storage.

If it does, it returns the existing key instance.

Otherwise, we create a new one. In the process, we detect any issuers
using this key and link them back to the new key entry.

The same holds for importCert over importKey, with the note that keys
are not modified when importing certificates.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add tests for importing issuers, keys

This adds tests for importing keys and issuers into the new storage
layout, ensuring that identifiers are correctly inferred and linked.

Note that directly writing entries to storage (writeKey/writeissuer)
will take KeyID links from the parent entry and should not be used for
import; only existing entries should be updated with this info.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Implement PKI storage migration.

 - Hook into the backend::initialize function, calling the migration on a primary only.
 - Migrate an existing certificate bundle to the new issuers and key layout

* Make fetchCAInfo aware of new storage layout

This allows fetchCAInfo to fetch a specified issuer, via a reference
parameter provided by the user. We pass that into the storage layer and
have it return a cert bundle for us. Finally, we need to validate that
it truly has the key desired.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Begin /issuers API endpoints

This implements the fetch operations around issuers in the PKI Secrets
Engine. We implement the following operations:

 - LIST /issuers - returns a list of known issuers' IDs and names.
 - GET /issuer/:ref - returns a JSON blob with information about this
   issuer.
 - POST /issuer/:ref - allows configuring information about issuers,
   presently just its name.
 - DELETE /issuer/:ref - allows deleting the specified issuer.
 - GET /issuer/:ref/{der,pem} - returns a raw API response with just
   the DER (or PEM) of the issuer's certificate.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add import to PKI Issuers API

This adds the two core import code paths to the API:
/issuers/import/cert and /issuers/import/bundle. The former differs from
the latter in that the latter allows the import of keys. This allows
operators to restrict importing of keys to privileged roles, while
allowing more operators permission to import additional certificates
(not used for signing, but instead for path/chain building).

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add /issuer/:ref/sign-intermediate endpoint

This endpoint allows existing issuers to be used to sign intermediate
CA certificates. In the process, we've updated the existing
/root/sign-intermediate endpoint to be equivalent to a call to
/issuer/default/sign-intermediate.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add /issuer/:ref/sign-self-issued endpoint

This endpoint allows existing issuers to be used to sign self-signed
certificates. In the process, we've updated the existing
/root/sign-self-issued endpoint to be equivalent to a call to
/issuer/default/sign-self-issued.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add /issuer/:ref/sign-verbatim endpoint

This endpoint allows existing issuers to be used to directly sign CSRs.
In the process, we've updated the existing /sign-verbatim endpoint to be
equivalent to a call to /issuer/:ref/sign-verbatim.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Allow configuration of default issuers

Using the new updateDefaultIssuerId(...) from the storage migration PR
allows for easy implementation of configuring the default issuer. We
restrict callers from setting blank defaults and setting default to
default.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Fix fetching default issuers

After setting a default issuer, one should be able to use the old /ca,
/ca_chain, and /cert/{ca,ca_chain} endpoints to fetch the default issuer
(and its chain). Update the fetchCertBySerial helper to no longer
support fetching the ca and prefer fetchCAInfo for that instead (as
we've already updated that to support fetching the new issuer location).

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add /issuer/:ref/{sign,issue}/:role

This updates the /sign and /issue endpoints, allowing them to take the
default issuer (if none is provided by a role) and adding
issuer-specific versions of them.

Note that at this point in time, the behavior isn't yet ideal (as
/sign/:role allows adding the ref=... parameter to override the default
issuer); a later change adding role-based issuer specification will fix
this incorrect behavior.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add support root issuer generation

* Add support for issuer generate intermediate end-point

* Update issuer and key arguments to consistent values

 - Update all new API endpoints to use the new agreed upon argument names.
   - issuer_ref & key_ref to refer to existing
   - issuer_name & key_name for new definitions
 - Update returned values to always user issuer_id and key_id

* Add utility methods to fetch common ref and name arguments

 - Add utility methods to fetch the issuer_name, issuer_ref, key_name and key_ref arguments from data fields.
 - Centralize the logic to clean up these inputs and apply various validations to all of them.

* Rename common PKI backend handlers

 - Use the buildPath convention for the function name instead of common...

* Move setting PKI defaults from writeCaBundle to proper import{keys,issuer} methods

 - PR feedback, move setting up the default configuration references within
   the import methods instead of within the writeCaBundle method. This should
   now cover all use cases of us setting up the defaults properly.

* Introduce constants for issuer_ref, rename isKeyDefaultSet...

* Fix legacy PKI sign-verbatim api path

 - Addresses some test failures due to an incorrect refactoring of a legacy api
   path /sign-verbatim within PKI

* Use import code to handle intermediate, config/ca

The existing bundle import code will satisfy the intermediate import;
use it instead of the old ca_bundle import logic. Additionally, update
/config/ca to use the new import code as well.

While testing, a panic was discovered:

> reflect.Value.SetMapIndex: value of type string is not assignable to type pki.keyId

This was caused by returning a map with type issuerId->keyId; instead
switch to returning string->string maps so the audit log can properly
HMAC them.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Clarify error message on missing defaults

When the default issuer and key are missing (and haven't yet been
specified), we should clarify that error message.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Update test semantics for new changes

This makes two minor changes to the existing test suite:

 1. Importing partial bundles should now succeed, where they'd
    previously error.
 2. fetchCertBySerial no longer handles CA certificates.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add support for deleting all keys, issuers

The old DELETE /root code must now delete all keys and issuers for
backwards compatibility. We strongly suggest calling individual delete
methods (DELETE /key/:key_ref or DELETE /issuer/:issuer_ref) instead,
for finer control.

In the process, we detect whether the deleted key/issuers was set as the
default. This will allow us to warn (from the single key/deletion issuer
code) whether or not the default was deleted (while allowing the
operation to succeed).

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Introduce defaultRef constant within PKI

 - Replace hardcoded "default" references with a constant to easily identify various usages.
 - Use the addIssuerRefField function instead of redefining the field in various locations.

* Rework PKI test TestBackend_Root_Idempotency

 - Validate that generate/root calls are no longer idempotent, but the bundle importing
   does not generate new keys/issuers
 - As before make sure that the delete root api resets everything
 - Address a bug within the storage that we bombed when we had multiple different
   key types within storage.

* Assign Name=current to migrated key and issuer

 - Detail I missed from the RFC was to assign the Name field as "current" for migrated key and issuer.

* Build CRL upon PKI intermediary set-signed api called

 - Add a call to buildCRL if we created an issuer within pathImportIssuers
 - Augment existing FullCAChain to verify we have a proper CRL post set-signed api call
 - Remove a code block writing out "ca" storage entry that is no longer used.

* Identify which certificate or key failed

When importing complex chains, we should identify in which certificate
or key the failure occurred.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* PKI migration writes out empty migration log entry

 - Since the elements of the struct were not exported we serialized an empty
   migration log to disk and would re-run the migration

* Add chain-building logic to PKI issuers path

With the one-entry-per-issuer approach, CA Chains become implicitly
constructed from the pool of issuers. This roughly matches the existing
expectations from /config/ca (wherein a chain could be provided) and
/intemediate/set-signed (where a chain may be provided). However, in
both of those cases, we simply accepted a chain. Here, we need to be
able to reconstruct the chain from parts on disk.

However, with potential rotation of roots, we need to be aware of
disparate chains. Simply concating together all issuers isn't
sufficient. Thus we need to be able to parse a certificate's Issuer and
Subject field and reconstruct valid (and potentially parallel)
parent<->child mappings.

This attempts to handle roots, intermediates, cross-signed
intermediates, cross-signed roots, and rotated keys (wherein one might
not have a valid signature due to changed key material with the same
subject).

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Return CA Chain when fetching issuers

This returns the CA Chain attribute of an issuer, showing its computed
chain based on other issuers in the database, when fetching a specific
issuer.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add testing for chain building

Using the issuance infrastructure, we generate new certificates (either
roots or intermediates), positing that this is roughly equivalent to
importing an external bundle (minus error handling during partial
imports). This allows us to incrementally construct complex chains,
creating reissuance cliques and cross-signing cycles.

By using ECDSA certificates, we avoid high signature verification and
key generation times.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Allow manual construction of issuer chain

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Fix handling of duplicate names

With the new issuer field (manual_chain), we can no longer err when a
name already exists: we might be updating the existing issuer (with the
same name), but changing its manual_chain field. Detect this error and
correctly handle it.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add tests for manual chain building

We break the clique, instead building these chains manually, ensuring
that the remaining chains do not change and only the modified certs
change. We then reset them (back to implicit chain building) and ensure
we get the same results as earlier.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add stricter verification of issuers PEM format

This ensures each issuer is only a single certificate entry (as
validated by count and parsing) without any trailing data.

We further ensure that each certificate PEM has leading and trailing
spaces removed with only a single trailing new line remaining.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Fix full chain building

Don't set the legacy IssuingCA field on the certificate bundle, as we
prefer the CAChain field over it.

Additionally, building the full chain could result in duplicate
certificates when the CAChain included the leaf certificate itself. When
building the full chain, ensure we don't include the bundle's
certificate twice.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add stricter tests for full chain construction

We wish to ensure that each desired certificate in the chain is only
present once.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Rename PKI types to avoid constant variable name collisions

 keyId -> keyID
 issuerId -> issuerID
 key -> keyEntry
 issuer -> issuerEntry
 keyConfig -> keyConfigEntry
 issuerConfig -> issuerConfigEntry

* Update CRL handling for multiple issuers

When building CRLs, we've gotta make sure certs issued by that issuer
land up on that issuer's CRL and not some other CRL. If no CRL is
found (matching a cert), we'll place it on the default CRL.
However, in the event of equivalent issuers (those with the same subject
AND the same key  material) -- perhaps due to reissuance -- we'll only
create a single (unified) CRL for them.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Allow fetching updated CRL locations

This updates fetchCertBySerial to support querying the default issuer's
CRL.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Remove legacy CRL storage location test case

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Update to CRLv2 Format to copy RawIssuer

When using the older Certificate.CreateCRL(...) call, Go's x509 library
copies the parsed pkix.Name version of the CRL Issuer's Subject field.
For certain constructed CAs, this fails since pkix.Name is not suitable
for round-tripping. This also builds a CRLv1 (per RFC 5280) CRL.

In updating to the newer x509.CreateRevocationList(...) call, we can
construct the CRL in the CRLv2 format and correctly copy the issuer's
name. However, this requires holding an additional field per-CRL, the
CRLNumber field, which is required in Go's implementation of CRLv2
(though OPTIONAL in the spec). We store this on the new
LocalCRLConfigEntry object, per-CRL.

Co-authored-by: Alexander Scheel <alex.scheel@hashicorp.com>
Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add comment regarding CRL non-assignment in GOTO

In previous versions of Vault, it was possible to sign an empty CRL
(when the CRL was disabled and a force-rebuild was requested). Add a
comment about this case.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Allow fetching the specified issuer's CRL

We add a new API endpoint to fetch the specified issuer's CRL directly
(rather than the default issuer's CRL at /crl and /certs/crl). We also
add a new test to validate the CRL in a multi-root scenario and ensure
it is signed with the correct keys.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add new PKI key prefix to seal wrapped storage (#15126)

* Refactor common backend initialization within backend_test

 - Leverage an existing helper method within the PKI backend tests to setup a PKI backend with storage.

* Add ability to read legacy cert bundle if the migration has not occurred on secondaries.

 - Track the migration state forbidding an issuer/key writing api call if we have not migrated
 - For operations that just need to read the CA bundle, use the same tracking variable to
   switch between reading the legacy bundle or use the new key/issuer storage.
 - Add an invalidation function that will listen for updates to our log path to refresh the state
   on secondary clusters.

* Always write migration entry to trigger secondary clusters to wake up

 - Some PR feedback and handle a case in which the primary cluster does
   not have a CA bundle within storage but somehow a secondary does.

* Update CA Chain to report entire chain

This merges the ca_chain JSON field (of the /certs/ca_chain path) with
the regular certificate field, returning the root of trust always. This
also affects the non-JSON (raw) endpoints as well.

We return the default issuer's chain here, rather than all known issuers
(as that may not form a strict chain).

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Allow explicit issuer override on roles

When a role is used to generate a certificate (such as with the sign/
and issue/ legacy paths or the legacy sign-verbatim/ paths), we prefer
that issuer to the one on the request. This allows operators to set an
issuer (other than default) for requests to be issued against,
effectively making the change no different from the users' perspective
as it is "just" a different role name.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add tests for role-based issuer selection

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Expand NotAfter limit enforcement behavior

Vault previously strictly enforced NotAfter/ttl values on certificate
requests, erring if the requested TTL extended past the NotAfter date of
the issuer. In the event of issuing an intermediate, this behavior was
ignored, instead permitting the issuance.

Users generally do not think to check their issuer's NotAfter date when
requesting a certificate; thus this behavior was generally surprising.

Per RFC 5280 however, issuers need to maintain status information
throughout the life cycle of the issued cert. If this leaf cert were to
be issued for a longer duration than the parent issuer, the CA must
still maintain revocation information past its expiration.

Thus, we add an option to the issuer to change the desired behavior:

 - err, to err out,
 - permit, to permit the longer NotAfter date, or
 - truncate, to silently truncate the expiration to the issuer's
   NotAfter date.

Since expiration of certificates in the system's trust store are not
generally validated (when validating an arbitrary leaf, e.g., during TLS
validation), permit should generally only be used in that case. However,
browsers usually validate intermediate's validity periods, and thus
truncate should likely be used (as with permit, the leaf's chain will
not validate towards the end of the issuance period).

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add tests for expanded issuance behaviors

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add warning on keyless default issuer (#15178)

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Update PKI to new Operations framework (#15180)

The backend Framework has updated Callbacks (used extensively in PKI) to
become deprecated; Operations takes their place and clarifies forwarding
of requests.

We switch to the new format everywhere, updating some bad assumptions
about forwarding along the way. Anywhere writes are handled (that should
be propagated to all nodes in all clusters), we choose to forward the
request all the way up to the performance primary cluster's primary
node. This holds for issuers/keys, roles, and configs (such as CRL
config, which is globally set for all clusters despite all clusters
having their own separate CRL).

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Kitography/vault 5474 rebase (#15150)

* These parts work (put in signature so that backend wouldn't break, but missing fields, desc, etc.)

* Import and Generate API calls w/ needed additions to SDK.

* make fmt

* Add Help/Sync Text, fix some of internal/exported/kms code.

* Fix PEM/DER Encoding issue.

* make fmt

* Standardize keyIdParam, keyNameParam, keyTypeParam

* Add error response if key to be deleted is in use.

* replaces all instances of "default" in code with defaultRef

* Updates from Callbacks to Operations Function with explicit forwarding.

* Fixes a panic with names not being updated everywhere.

* add a logged error in addition to warning on deleting default key.

* Normalize whitespace upon importing keys.

Authored-by: Alexander Scheel <alexander.m.scheel@gmail.com>

* Fix isKeyInUse functionality.

* Fixes tests associated with newline at end of key pem.

* Add alternative proposal PKI aliased paths (#15211)

* Add aliased path for root/rotate/:exported

This adds a user-friendly path name for generating a rotated root. We
automatically choose the name "next" for the newly generated root at
this path if it doesn't already exist.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add aliased path for intermediate/cross-sign

This allows cross-signatures to work.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add path for replacing the current root

This updates default to point to the value of the issuer with name
"next" rather than its current value.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Remove plural issuers/ in signing paths

These paths use a single issuer and thus shouldn't include the plural
issuers/ as a path prefix, instead using the singular issuer/ path
prefix.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Only warn if default issuer was imported

When the default issuer was not (re-)imported, we'd fail to find it,
causing an extraneous warning about missing keys, even though this
issuer indeed had a key.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add missing issuer sign/issue paths

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Clean up various warnings within the PKI package (#15230)

* Rebuild CRLs on secondary performance clusters post migration and on new/updated issuers

 - Hook into the backend invalidation function so that secondaries are notified of
   new/updated issuer or migrations occuring on the primary cluster. Upon notification
   schedule a CRL rebuild to take place upon the next process to read/update the CRL
   or within the periodic function if no request comes in.

* Schedule rebuilding PKI CRLs on active nodes only

 - Address an issue that we were scheduling the rebuilding of a CRL on standby
   nodes, which would not be able to write to storage.
 - Fix an issue with standby nodes not correctly determining that a migration previously
   occurred.

* Return legacy CRL storage path when no migration has occurred.

* Handle issuer, keys locking (#15227)

* Handle locking of issuers during writes

We need a write lock around writes to ensure serialization of
modifications. We use a single lock for both issuer and key
updates, in part because certain operations (like deletion) will
potentially affect both.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add missing b.useLegacyBundleCaStorage guards

Several locations needed to guard against early usage of the new issuers
endpoint pre-migration.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Address PKI to properly support managed keys (#15256)

* Address codebase for managed key fixes
* Add proper public key comparison for better managed key support to importKeys
* Remove redundant public key fetching within PKI importKeys

* Correctly handle rebuilding remaining chains

When deleting a specific issuer, we might impact the chains. From a
consistency perspective, we need to ensure the remaining chains are
correct and don't refer to the since-deleted issuer, so trigger a full
rebuild here.

We don't need to call this in the delete-the-world (DELETE /root) code
path, as there shouldn't be any remaining issuers or chains to build.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Remove legacy CRL bundle on world deletion

When calling DELETE /root, we should remove the legacy CRL bundle, since
we're deleting the legacy CA issuer bundle as well.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Remove deleted issuers' CRL entries

Since CRLs are no longer resolvable after deletion (due to missing
issuer ID, which will cause resolution to fail regardless of if an ID or
a name/default reference was used), we should delete these CRLs from
storage to avoid leaking them.

In the event that this issuer comes back (with key material), we can
simply rebuild the CRL at that time (from the remaining revoked storage
entries).

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add unauthed JSON fetching of CRLs, Issuers (#15253)

Default to fetching JSON CRL for consistency

This makes the bare issuer-specific CRL fetching endpoint return the
JSON-wrapped CRL by default, moving the DER CRL to a specific endpoint.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

Add JSON-specific endpoint for fetching issuers

Unlike the unqualified /issuer/:ref endpoint (which also returns JSON),
we have a separate /issuer/:ref/json endpoint to return _only_ the
PEM-encoded certificate and the chain, mirroring the existing /cert/ca
endpoint but for a specific issuer. This allows us to make the endpoint
unauthenticated, whereas the bare endpoint would remain authenticated
and usually privileged.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

Add tests for raw JSON endpoints

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add unauthenticated issuers endpoints to PKI table

This adds the unauthenticated issuers endpoints?

 - LIST /issuers,
 - Fetching _just_ the issuer certificates (in JSON/DER/PEM form), and
 - Fetching the CRL of this issuer (in JSON/DER/PEM form).

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* Add issuer usage restrictions bitset

This allows issuers to have usage restrictions, limiting whether they
can be used to issue certificates or if they can generate CRLs. This
allows certain issuers to not generate a CRL (if the global config is
with the CRL enabled) or allows the issuer to not issue new certificates
(but potentially letting the CRL generation continue).

Setting both fields to false effectively forms a soft delete capability.

Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>

* PKI Pod rotation Add Base Changelog (#15283)

* PKI Pod rotation changelog.
* Use feature release-note formatting of changelog.

Co-authored-by: Steven Clark <steven.clark@hashicorp.com>
Co-authored-by: Kit Haines <kit.haines@hashicorp.com>
Co-authored-by: kitography <khaines@mit.edu>
2022-05-11 12:42:28 -04:00
Hamid Ghaf 2ee602cfdd
removing prem/pro references as part of removing some build targets (#15278) 2022-05-06 09:09:42 -04:00
Peter Wilson 43bb764808
Do sockaddr template parsing only when needed (#15224) 2022-04-29 09:57:17 -04:00
Christopher Swenson aa6d61477e
VAULT-5827 Don't prepare SQL queries before executing them (#15166)
VAULT-5827 Don't prepare SQL queries before executing them

We don't support proper prepared statements, i.e., preparing once and
executing many times since we do our own templating. So preparing our
queries does not really accomplish anything, and can have severe
performance impacts (see
https://github.com/hashicorp/vault-plugin-database-snowflake/issues/13
for example).

This behavior seems to have been copy-pasted for many years but not for
any particular reason that we have been able to find. First use was in
https://github.com/hashicorp/vault/pull/15

So here we switch to new methods suffixed with `Direct` to indicate
that they don't `Prepare` before running `Exec`, and switch everything
here to use those. We maintain the older methods with the existing
behavior (with `Prepare`) for backwards compatibility.
2022-04-26 12:47:06 -07:00
AnPucel 2b5be0adec
[VAULT-5813] Remove duplicate sha_256 in SystemCatalogRequest OAS (#15163) 2022-04-25 13:12:08 -07:00
AnPucel f38248f5e5
[VAULT-5887] TypeInt64 support added to OpenApi Spec generation (#15104)
Adding handling for TypeInt64 to OAS types
2022-04-22 15:37:12 -07:00
Chris Capurso e69f89c279
Add build date (#14957)
* add BuildDate to version base

* populate BuildDate with ldflags

* include BuildDate in FullVersionNumber

* add BuildDate to seal-status and associated status cmd

* extend core/versions entries to include BuildDate

* include BuildDate in version-history API and CLI

* fix version history tests

* fix sys status tests

* fix TestStatusFormat

* remove extraneous LD_FLAGS from build.sh

* add BuildDate to build.bat

* fix TestSysUnseal_Reset

* attempt to add build-date to release builds

* add branch to github build workflow

* add get-build-date to build-* job needs

* fix release build command vars

* add missing quote in release build command

* Revert "add branch to github build workflow"

This reverts commit b835699ecb7c2c632757fa5fe64b3d5f60d2a886.

* add changelog entry
2022-04-19 14:28:08 -04:00
Chris Capurso d9280b0fb0
fix TypeCommaIntSlice panic caused by json.Number input (#15072)
* fix TypeCommaIntSlice panic caused by json.Number input

* add changelog entry
2022-04-18 16:43:16 -04:00
Chris Capurso 46591ec54d
sort list of unrecognized params in response warning (#15073) 2022-04-18 15:45:08 -04:00
Hamid Ghaf a12271af46
forwarding requests subjected to Login MFA to the active node (#15009)
* forwarding requests subjected to Login MFA to the active node

* CL, and making fmt happy
2022-04-13 10:11:53 -04:00
Alexander Scheel 112d622b40
Run `make fmt` (#15011)
Signed-off-by: Alexander Scheel <alex.scheel@hashicorp.com>
2022-04-12 17:11:33 -04:00
Vishal Nayak ad3bf3173c
Warnings indicating ignored and replaced parameters (#14962)
* Warnings indicating ignored and replaced parameters

* Avoid additional var creation

* Add warnings only if the response is non-nil

* Return the response even when error is non-nil

* Fix tests

* Rearrange comments

* Print warning in the log

* Fix another test

* Add CL
2022-04-11 09:57:12 -04:00