Database Root Privilege Rotation | safe | HashiCorp developer (2023)

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/:nameAPI endpoint to rotate stored root credentials for database connection.

Database Root Privilege Rotation | safe | HashiCorp developer (1)

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
  • psqlolibpqFurnished
  • Rocainstalled and configured with an authentication token (HCP Vault only)

political requirements

supervision

For this tutorial you can use yourThoseTokens 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.

  1. open onenew deviceand pull an image from the postgres serverstevedore.

    ps docker pull postgres:neueste
  2. Create a Postgres database with a root usernameThosewith 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

  1. In onenew deviceStart a Vault development server withThoseas root token.

    ps server vault -dev -dev-root-token-id root

    Vault development server runs by default127.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.

  2. In onenew deviceExport an environment variable to thesafeCLI to go to the Vault server.

    ps Export VAULT_ADDR=http://127.0.0.1:8200
  3. Export an environment variable to thesafeCLI 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.

  4. Set an environment variable to the address of PostreSQL.

    (Video) Quick Tutorial - Users and Permissions in SQL Server

    ps 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.

  1. start itPortal HCPand log in.

  2. Cliquesafein the left navigation area.

  3. NObreast clusterscontrol panel, clickVault-Cluster.

  4. SobURLs de Clusters, cliquePublicURL cluster.Database Root Privilege Rotation | safe | HashiCorp developer (2)

  5. In a terminal, put theVAULT_ADDREnvironment variable for the copied address.

    ps Export VAULT_ADDR=<public_cluster_URL>
  6. To return togeneral descriptionpage and clickgenerate tokens.Database Root Privilege Rotation | safe | HashiCorp developer (3)

    A new token will be generated in a few moments.

  7. copy theadmin token.Database Root Privilege Rotation | safe | HashiCorp developer (4)

  8. Go back to the terminal and set theVAULT_TOKENenvironmental variable.

    ps Export VAULT_TOKEN=<sheet>
  9. put thatVAULT_NAMESPACEenvironment variable forAdministrator.

    ps Export VAULT_NAMESPACE=Administrator

    oAdministratorThe namespace is the top-level namespace automatically created by HCPVault. By default, all CLI operations use the namespace defined in this environment variable.

  10. typeZustand des Tresorsto 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.

  11. 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
  12. Copy the forwarding address from ngrok.

  13. Return to the terminal where you defined theVAULT_ADDRenvironment 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./databaseI walk in the vault.

Enable the database secrets mechanism using/sys/mountsPoint.

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/mountsPoint.

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.

(Video) Generating a Root Token on HashiCorp Vault using
  1. Open a web browser and log in to the Vault user interface.

  2. navigate tomysteriesand clickactivate new engine.

    Database Root Privilege Rotation | safe | HashiCorp developer (5)

  3. Activate on the Secrets Engine pagebelowsection, selectdatabasesand clickNext.

    Database Root Privilege Rotation | safe | HashiCorp developer (6)

  4. Leave all fields as they are and clickactivate engine.

    Database Root Privilege Rotation | safe | HashiCorp developer (7)

    supervision

    This tutorial assumes that you have enabled the database secrets mechanism indatabase. 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 urlThe value includes the usage model credentials andUsernamemipasswordParameters 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/postgresqlEndpoint 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 urlThe value uses template credentials andUsernamemipasswordParameters 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/postgresqlEndpoint 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 urlThe value uses template credentials andUsernamemipasswordParameters are also passed to initiate the connection.

  1. 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.

    Database Root Privilege Rotation | safe | HashiCorp developer (8)

  2. Fordatabase add-on, choosePostgreSQLName.

    (Video) Hashicorp Vault - Tokens, Types, Root, Accessors, Service vs batch tokens, Orphan Tokens & TTL - #5

  3. Forconnection name, tapposgresql.

  4. Enter the followingconnection urlfield replacement<host:puerto>with the value ofPOSTGRES_URLenvironmental variablepostgresql://{{username}}:{{password}}@<host:port>/postgres?sslmode=disable.

  5. deactivateThe connection is verified.

  6. ForUsername, tapThose.

  7. Forpassword, taproot password.

    Database Root Privilege Rotation | safe | HashiCorp developer (9)

  8. Cliquecreate database.

  9. When prompted to change root credentials, clickturn and activate.

    Database Root Privilege Rotation | safe | HashiCorp developer (10)

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.

  1. navigate tomysteriesdatabaselinks.

  2. Click the ellipsis on the line representing the database connection name to display a menu.

  3. CliqueRotate root credentials.

    Database Root Privilege Rotation | safe | HashiCorp developer (11)

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/:nameEndpoint 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.sqlcontains 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
(Video) Painless Password Rotation with HashiCorp Vault

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}
  1. navigate tomysteriesdatabasefunctions.

  2. Cliquecreate role.

  3. Forrole name, tapI just read.

  4. ForDatabase name, chooseposgresql.

  5. Forart paper, choosedynamic.

  6. ForUsername, tapThose.

  7. 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}}";

    Database Root Privilege Rotation | safe | HashiCorp developer (12)

  8. Cliquecreate role.

  9. Select on the read-only features pageget credentials.

    Database Root Privilege Rotation | safe | HashiCorp developer (13)

  10. On the Credentials page, click the clipboard icon to copy the token value to the system clipboard.

    Database Root Privilege Rotation | safe | HashiCorp developer (14)

  11. 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.

(Video) How Hackers Login To Any Websites Without Password?!

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

Videos

1. How to create root user and password MongoDB on Ubuntu, Linux | Enable Access Control of MongoDB
(OSTechHelp)
2. HashiCorp Vault Tutorial for Beginners | FULL COURSE in 1 Hour | HashiCorp Vault Fundamentals
(TeKanAid)
3. SQL Injection For Beginners
(Loi Liang Yang)
4. How Hackers Could Brute-Force SSH Credentials to Gain Access to Servers
(Null Byte)
5. how hackers hack any website in 9 minutes 6 seconds?!
(Loi Liang Yang)
6. How to Hide Your API Keys
(PortEXE)
Top Articles
Latest Posts
Article information

Author: Rueben Jacobs

Last Updated: 01/13/2023

Views: 6162

Rating: 4.7 / 5 (77 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Rueben Jacobs

Birthday: 1999-03-14

Address: 951 Caterina Walk, Schambergerside, CA 67667-0896

Phone: +6881806848632

Job: Internal Education Planner

Hobby: Candle making, Cabaret, Poi, Gambling, Rock climbing, Wood carving, Computer programming

Introduction: My name is Rueben Jacobs, I am a cooperative, beautiful, kind, comfortable, glamorous, open, magnificent person who loves writing and wants to share my knowledge and understanding with you.