from the trunkDatabase secrets mechanismprovides a centralized workflow for managing credentials for multiple database systems. This gives each service instance a unique set of database credentials, instead of sharing one. By binding these credentials directly to each service instance and are only valid for the lifetime of the service, any unusual access patterns can be attributed to a specific service instance and your credentials revoked immediately.
This reduces manual tasks for the database administrator and makes database access more efficient and secure.
oSecret as a Service: Dynamic SecretsTutorial demonstrates the main workflow.
Because the store manages database credentials on behalf of the database administrator, it must also be provisioned with a set of highly privileged credentials that allow it to grant and revoke access to the database system. So it's very common to give Vault itsThoseCredentials.
However, these credentials are typically very persistent and never change once they are set up in Vault. This may violate theGovernance, risk and compliance(GRC) around the data stored in the database.
Solution
use the vault/database/rotate-root/:name
API endpoint to rotate stored root credentials for database connection.
best exercise Use this feature to change root credentials immediately after the initial configuration of each database.
This lab was tested on macOS with an x86_64-based processor. If you're running macOS on an Applesilicon-based processor, use an x86_64-based Linux virtual machine from your preferred cloud provider.
To perform the tasks described in this tutorial, you need the following:
- health workeroOSSVault environment
- stevedoreto run a PostgreSQL container
- jqFurnished
- psqlo
libpq
Furnished - Rocainstalled and configured with an authentication token (HCP Vault only)
political requirements
supervision For this tutorial you can use yourThose
Tokens to work with Vault. However, it is recommended to only use root tokens for sufficient initial setup or in emergencies. As a best practice, use tokens with the appropriate policies based on your role in the organization.
To perform all the tasks shown in this tutorial, your policy must include the following permissions:
# Assemble secret mechanismsFar"sys/mounts/*" { capabilities = [ "create","ler","Update","extinguish","List" ]}# Configure the database secrets mechanism and create rolesFar"database/*" { capabilities = [ "create","ler","Update","extinguish","List" ]}
If you are not familiar with the guidelines, please fill them outguidelinestutorial.
laboratory facility
Inicie PostgreSQL
The tutorial requires a Postgres database. Docker provides a Postgres server image that meets this requirement.
open onenew deviceand pull an image from the postgres server
stevedore
.ps docker pull postgres:neueste
Create a Postgres database with a root username
Those
with the passwordroot password
.ps running docker\--name learn-postgres\--envPOSTGRES_USER=Those\--envPOSTGRES_PASSWORD=root password\-- distance\--Mail5432:5432\postgraduate
The PostgreSQL server is ready.
start vault
In onenew deviceStart a Vault development server with
Those
as root token.ps server vault -dev -dev-root-token-id root
Vault development server runs by default
127.0.0.1:8200
. The server is initialized and not sealed.unsafe operation
Do not run a Vault development server in production. This approach starts a vault server with an in-memory database and runs insecurely.
In onenew deviceExport an environment variable to the
safe
CLI to go to the Vault server.ps Export VAULT_ADDR=http://127.0.0.1:8200
Export an environment variable to the
safe
CLI to authenticate with Vault Server.ps Export VAULT_TOKEN=Those
Vault Server is ready.
supervision
You can use Vault for these tasksThoseSymbol. However, it is recommended to only use root tokens for sufficient initial setup or in emergencies. As a best practice, use an authentication method or token that meets the requirementspolitical requirements.
Set an environment variable to the address of PostreSQL.
(Video) Quick Tutorial - Users and Permissions in SQL Serverps Export POSTGRES_URL=127,0.0.1:5432
You can continue with the laboratory.
supervision If you do not have access to an HCP Vault cluster, visit theCreate a Vault Cluster on HCPtutorial.
start itPortal HCPand log in.
Cliquesafein the left navigation area.
NObreast clusterscontrol panel, clickVault-Cluster.
SobURLs de Clusters, cliquePublicURL cluster.
In a terminal, put the
VAULT_ADDR
Environment variable for the copied address.ps Export VAULT_ADDR=<public_cluster_URL>
To return togeneral descriptionpage and clickgenerate tokens.
A new token will be generated in a few moments.
copy theadmin token.
Go back to the terminal and set the
VAULT_TOKEN
environmental variable.ps Export VAULT_TOKEN=<sheet>
put that
VAULT_NAMESPACE
environment variable forAdministrator
.ps Export VAULT_NAMESPACE=Administrator
o
Administrator
The namespace is the top-level namespace automatically created by HCPVault. By default, all CLI operations use the namespace defined in this environment variable.type
Zustand des Tresors
to verify your connectivity to the Vault Cluster.ps Zustand des Tresorskey value--- -----Shamir Restoration Stamp Typetrue initializedfalse sealingTotal Recovery Actions 1threshold 1Version 1.9.2+entraft storage type...cut...
The HCP Vault server is ready.
In order for HCP Vault to interact with resources running on your local computer, a tunnel must be established.
emanother terminal, start ngrok and connect to PostgreSQL.
ps ngrok tcp127,0.0.1:5432
Example output:
ngrok (Ctrl+C to exit)Online session statusAccount username (Plan: Free)Update available (Version 3.0.5, Ctrl-U to update)Version 3.0.3United States (US) RegionLatency 32.791235msWeb interface http://127.0.0.1:4040Redirect tcp://d12b-34-567-89-10.ngrok.io:12345 -> 127.0.0.1:5432conexiones ttl opn rt1 rt5 p50 p900 0 0,00 0,00 0,00 0,00
Copy the forwarding address from ngrok.
Return to the terminal where you defined the
VAULT_ADDR
environment variable and set an environment variable at the address ngrok. not includedtcp://
.ps Export POSTGRES_URL=<current-address-of-ngrok>
You can continue with the laboratory.
Enable the database secrets mechanism.
ps vault secretsMake it possibledatabase
SUPERVISION:This example enables the database secrets mechanism./database
I walk in the vault.
Enable the database secrets mechanism using/sys/mounts
Point.
ps curling--Header"X-Bóveda-Token:$VAULT_TOKEN" \- Request POST\--Data'{"type":"database"}' \ $VAULT_ADDR/v1/sys/mounts/database
SUPERVISION:This example implements the database secrets engine/database
, passing the secret engine type ("database
") in the request payload.
Enable the database secrets mechanism using/sys/mounts
Point.
ps curling--Header"X-Bóveda-Token:$VAULT_TOKEN" \--Header"X-Vault Namespace:$VAULT_NAMESPACE" \- Request POST\--Data'{"type":"database"}' \ $VAULT_ADDR/v1/sys/mounts/database
SUPERVISION:This example implements the database secrets engine/database
, passing the secret engine type ("database
") in the request payload.
Open a web browser and log in to the Vault user interface.
navigate tomysteriesand clickactivate new engine.
Activate on the Secrets Engine pagebelowsection, selectdatabasesand clickNext.
Leave all fields as they are and clickactivate engine.
supervision
This tutorial assumes that you have enabled the database secrets mechanism in
database
. If yours is activated on a different path, make sure you're using the correct path by following this tutorial.
Step 2: Configuring the PostgreSQL secrets mechanism
Configure the secret mechanism of the database.
ps safewriteDatabase/config/postgresql\ plugin_name=postgresql-datenbank-plugin\ connection url="postgresql://{{username}}:{{password}}@$POSTGRES_URL/postgres?sslmode=deshabilitar" \ allowed_roles="*" \ Username="Those" \ password="root password"
Please note that theconnection url
The value includes the usage model credentials andUsername
mipassword
Parameters are also passed to initiate the connection.
Create an API request payload that contains the database secrets engine configuration.
ps Teepayload.json<<weekend{"plugin_name": "postgresql-datenbank-plugin","connection_url": "postgresql://{{username}}:{{password}}@$POSTGRES_URL/postgres?sslmode=deshabilitar","allowed_roles": "read only","Username": "root""password": "root password"}weekend
Call toDatabase/config/postgresql
Endpoint to configure the database secrets mechanism.
ps curling--Header"X-Bóveda-Token:$VAULT_TOKEN" \- Request POST\--datos @payload.json\ $VAULT_ADDR/v1/base de datos/config/postgresql
Please note that theconnection url
The value uses template credentials andUsername
mipassword
Parameters are also passed to initiate the connection.
Create an API request payload that contains the database secrets engine configuration.
ps Teepayload.json<<weekend{"plugin_name": "postgresql-datenbank-plugin","connection_url": "postgresql://{{username}}:{{password}}@$POSTGRES_URL/postgres?sslmode=deshabilitar","allowed_roles": "read only","Username": "root""password": "root password"}weekend
Call toDatabase/config/postgresql
Endpoint to configure the database secrets mechanism.
ps curling--Header"X-Bóveda-Token:$VAULT_TOKEN" \--Header"X-Vault Namespace:$VAULT_NAMESPACE" \- Request POST\--datos @payload.json\ $VAULT_ADDR/v1/base de datos/config/postgresql
Please note that theconnection url
The value uses template credentials andUsername
mipassword
Parameters are also passed to initiate the connection.
The database confidentiality mechanism is enabled, but no connection is yet available from the store to the database. Establish the Vault connection to the PostgreSQL server by clickingcreate connection.
Fordatabase add-on, choosePostgreSQLName.
(Video) Hashicorp Vault - Tokens, Types, Root, Accessors, Service vs batch tokens, Orphan Tokens & TTL - #5Forconnection name, tap
posgresql
.Enter the followingconnection urlfield replacement
<host:puerto>
with the value ofPOSTGRES_URL
environmental variablepostgresql://{{username}}:{{password}}@<host:port>/postgres?sslmode=disable
.deactivateThe connection is verified.
ForUsername, tap
Those
.Forpassword, tap
root password
.Cliquecreate database.
When prompted to change root credentials, clickturn and activate.
Vault provides an API endpoint to easily change the initial credentials of the master database.
ps safewrite-force database/rotate-root/postgresql
ps curling--Header"X-Bóveda-Token:$VAULT_TOKEN" \- Request POST\ $VAULT_ADDR/v1/database/rotate-root/postgresql
ps curling--Header"X-Bóveda-Token:$VAULT_TOKEN" \--Header"X-Vault Namespace:$VAULT_NAMESPACE" \- Request POST\ $VAULT_ADDR/v1/database/rotate-root/postgresql
You chose to rotate the root credentials when you set up the database connection, but you can manually rotate the root credentials at any time.
navigate tomysteries→database→links.
Click the ellipsis on the line representing the database connection name to display a menu.
CliqueRotate root credentials.
To verify that the root credentials have been rotated, try logging into PostgreSQL.
ps psql -h servidor local -p5432-U Root-PostgresRoot user password:
Enter the initial password (eg.root password
) oNOit works as long as the password has been rotated through the vault.
you can call themdatabase/rotate-root/:name
Endpoint periodically to protect root credentials.
supervision Once root credentials have been rotated, only Vault will know the new root password. This applies to any root database credentials provided to Vault. Therefore, you must create a separate super user for Vaultusage that is not used for any other purpose.
Step 4: Check the settings
You can create a role and verify that the database secrets engine dynamically generates credentials as expected.
If you are not familiar with the secret mechanism of the database, please read theSecrets as a Service: Dynamic SecretsTutorial for more detailed instructions.
Create a file namedreadonly.sql
contains the SQL statement to create a new function.
ps Teereadonly.sql<<weekendCREATE ROLE '{{name}}' WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';GRANT SELECTION ON ALL TABLES IN SCHEMA public TO "{{name}}";weekend
Create a function called "readonly" with a TTL of 1 hour.
ps safewriteDatabase/Roles/Read Onlydatabase name=posgresql\ creation statements=@readonly.sql\ default_ttl=1hmax_ttl=24 hours
Get a new set of credentials from the database.
ps safefurtherdatabase/creds/read-onlykey value--- -----banco de datos de lease_id/creds/readonly/999c43f0-f79e-ba90-24a8-4de5af33a2e9Duration_Lease 1hrenewable wahr_leasePassword A1a-u7wxtrpx09xp40yqBenutzername v-root-only read-x6q809467q98yp4yx4z4-1525378026e
Create an API request payload that contains the parameters to create a new function.
ps Teepayload.json<<weekend{"db_name": "postgresql","creation_statements": "PAPEL CRIAR\"{{Name}}\"WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';GRANT SELECT ON ALL TABLES IN public SCHEMA FOR\"{{Name}}\";","default_ttl": "1 hora","max_ttl": "24 horas"}weekend
Create a new function calledI just read
.
ps curling--Header"X-Bóveda-Token:$VAULT_TOKEN" \- Request POST\--datos @payload.json\ $VAULT_ADDR/v1/database/roles/read-only
Generate a new set of credentials.
ps curling--Header"X-Bóveda-Token:$VAULT_TOKEN" \ $VAULT_ADDR/v1/database/creds/read-only|jq
Example output:
{"request_id": "527970fd-f5e8-4de5-d4ed-1b7970eaef0b","lease_id": "banco de dados/creds/readonly/ac79265e-668c-242f-4f67-1dae33da094c","renewable": true,"rental_duration": 3600,"Data": {"Password": "A1a-0tr8u15y0us2u08v","Benutzername": "v-root-read-only-x7v65y1xuprzxv9vpt80-1525378873"},"wrap_info": nulo,"warnings": null,'authentication': null}
Create an API request payload that contains the parameters to create a new function.
ps Teepayload.json<<weekend{"db_name": "postgresql","creation_statements": "PAPEL CRIAR\"{{Name}}\"WITH LOGIN PASSWORD '{{password}}' VALID UNTIL '{{expiration}}';GRANT SELECT ON ALL TABLES IN public SCHEMA FOR\"{{Name}}\";","default_ttl": "1 hora","max_ttl": "24 horas"}weekend
Create a new function calledI just read
.
ps curling--Header"X-Bóveda-Token:$VAULT_TOKEN" \--Header"X-Vault Namespace:$VAULT_NAMESPACE" \- Request POST\--datos @payload.json\ $VAULT_ADDR/v1/database/roles/read-only
Generate a new set of credentials.
ps curling--Header"X-Bóveda-Token:$VAULT_TOKEN" \--Header"X-Vault Namespace:$VAULT_NAMESPACE" \--request GET\ $VAULT_ADDR/v1/database/creds/read-only|jq
Example output:
{"request_id": "527970fd-f5e8-4de5-d4ed-1b7970eaef0b","lease_id": "banco de dados/creds/readonly/ac79265e-668c-242f-4f67-1dae33da094c","renewable": true,"rental_duration": 3600,"Data": {"Password": "A1a-0tr8u15y0us2u08v","Benutzername": "v-root-read-only-x7v65y1xuprzxv9vpt80-1525378873"},"wrap_info": nulo,"warnings": null,'authentication': null}
navigate tomysteries→database→functions.
Cliquecreate role.
Forrole name, tap
I just read
.ForDatabase name, chooseposgresql.
Forart paper, choosedynamic.
ForUsername, tap
Those
.Forcreation statements, enter the following SQL statements:
CREATEPAPER"{{Name}}" KOMPASSWORD'{{Password}}'EXPIRATION DATE'{{Process}}';GRANT CHOOSE ONE IN TABLE EM THE PLAN public FOR "{{Name}}";
Cliquecreate role.
Select on the read-only features pageget credentials.
On the Credentials page, click the clipboard icon to copy the token value to the system clipboard.
Use the copied token value to validate the connection in the next step.
Make sure you can connect to the database using the credentials generated by Vault.
Example
ps psql -h servidor local -p5432 \-U v-root-readonly-x7v65y1xuprzxv9vpt80-1525378873 postgresPassword for user v-root-readonly-x7v65y1xuprzxv9vpt80-1525378873:postgres=> \yourole name | Attributes | member of-------------------------------------------------- +- ------------------------------------------------ -----------------+----------postgres | Superuser, create role, create database, replication, omit RLS | {}v-root-read-only-x6q809467q98yp4yx4z4-1525378026 | Password valid until 2018-05-03 21:07:11+00 | {}postgres=> \q
This confirms that Vault successfully connected to your PostgreSQL server and created a new user based on the permission defined byreadonly.sql
.
Vault-generated user credentials have a limited TTL depending on your configuration (default_ttl
). You can also revoke them if necessary.
- Secret as a Service: Dynamic Secrets
- Database Secrets Engine (API)
- API-HTTP Add-on for PostgreSQL