Tuesday, 29 September 2020

Vault seal/unseal

 

When a Vault server is started, it starts in sealed state. In this state, vault doesn’t know how to decrypt the data. If you are in sealed state, almost no operation is possible. To work with vault you need to unseal it first.

 

What is Unsealing?

It is a process of obtaining a plain text master key which is used to read the ‘Encryption Key’ to decrypt the data and allow access to vault.

 

Why this unsealing required?

Data in vault is encrypted before storing. In order to decrypt this data vault needs an ‘Encryption Key’. This ‘Encryption Key’ is also stored with the data (possibly in a keyring file), but encrypted with other encryption key known as ‘Master key’.

 

So to read the data in vault, we need a ‘Master key’ which is used to decrypt the ‘Encryption Key’ and this decrypted ‘Encryption key’ is used to decrypt actual data. Unsealing is a process of getting Master Key.

 

Shamir Secret Sharing Algorithm

Vault uses Sahmir Secret Sharing Algorithm to split the unsealed keys to shares. Some minimum number of these shares are used to form a unsealed key. This unsealed key is used to decrypt the master key.

 

In Shamir Secret Sharing Algorithm used to secure a secret in distributed way. In this algorithm a secret is divided into multiple parts called shares. Each unique shares is divided across multiple participants. These shares are used to reconstruct the original secret.

 

How to unlock a secret?

To unlock a secret, you need minimum number of shares. This minimum number is called the threshold.

 

How the algorithm works?

Divide the secret ‘S’ into ‘n’ pieces {S1, S2…Sn} such that

a.   We can compute the secret ‘S’ with the knowledge of any k or more pieces or shares .

b.   We can’t compute the secret ‘S’ with the knowledge of k-1 or fewer pieces.

 

This algorithm works based on the principle ‘to build a polynomial with the degree (K – 1) such that the constant term is the secret code and the remaining numbers are random and this constant term can be found by using any K points out of N points generated from this polynomial by using Legrange’s Basis Polynomial’.

 

Process looks like below.

a. Create key-shares using certain key-threshold

$vault operator init -key-shares=5 -key-threshold=2
Unseal Key 1: SjtWQ+s+30GmiXfGqz/CWTmVs5or3yCVF8wcYMhJJj/E
Unseal Key 2: zH2n8A4H+3MyG5hD0WQsAHyv4wSJyju2nl2cbx7L2DSw
Unseal Key 3: dHEuNdy6jX6x+OrLMKNO50AilCdHgZCw1o5En9EzoYSx
Unseal Key 4: TuK5YEUmYjpxzHSLsUMPoqnErOCSUBd0ZcCKFtNYv1xm
Unseal Key 5: ex2DgsSYZhtGQiVvmAYReYerdgejpBSG6J8GrjxKPcO4

Initial Root Token: s.E3BRk50CvwMf7nWA0of9qsQB

b. Unseal Vault by providing minimum 'key-threshold' key shares (Unseal keys) generated in step 1. In this process, valut generate unsealed key using the key shares. Once unsealed key generated, it use this to get Master Key. Once Master key generated, it is used to get 'Encryption Key.'

$vault operator unseal ex2DgsSYZhtGQiVvmAYReYerdgejpBSG6J8GrjxKPcO4
Key                Value
---                -----
Seal Type          shamir
Initialized        true
Sealed             true
Total Shares       5
Threshold          2
Unseal Progress    1/2
Unseal Nonce       04a05ef6-1d8c-971b-dbad-684ab3efdf78
Version            1.4.2
HA Enabled         false

$vault operator unseal zH2n8A4H+3MyG5hD0WQsAHyv4wSJyju2nl2cbx7L2DSw
Key             Value
---             -----
Seal Type       shamir
Initialized     true
Sealed          false
Total Shares    5
Threshold       2
Version         1.4.2
Cluster Name    vault-cluster-5d1876f0
Cluster ID      86774adb-7768-ac51-d7e2-a7ec1cfde4c4
HA Enabled      false


How long a vault is in unsealed state?

Once a vault is unsealed, it remains in unsealed state until one of the below things occur.

a.   Vault is resealed via the API

b.   The server is restarted.

c.    Vault's storage layer encounters an unrecoverable error.



 

 

Previous                                                    Next                                                    Home

Shamir Secret Sharing Algorithm

In Shamir Secret Sharing Algorithm used to secure a secret in distributed way. In this algorithm a secret is divided into multiple parts called shares. Each unique shares is divided across multiple participants. These shares are used to reconstruct the original secret.

 

How to unlock a secret?

To unlock a secret, you need minimum number of shares. This minimum number is called the threshold.

 

How the algorithm works?

Divide the secret ‘S’ into ‘n’ pieces {S1, S2…Sn} such that

a.   We can compute the secret ‘S’ with the knowledge of any k or more pieces or shares .

b.   We can’t compute the secret ‘S’ with the knowledge of k-1 or fewer pieces.

 

This algorithm works based on the principle ‘to build a polynomial with the degree (K – 1) such that the constant term is the secret code and the remaining numbers are random and this constant term can be found by using any K points out of N points generated from this polynomial by using Legrange’s Basis Polynomial’.

 

 

Previous                                                    Next                                                    Home

HashiCorp Vault: Run in dev mode

You can start vault in dev mode by executing below command.

vault server -dev

 

You can use dev server to experiment with Vault.

 

Is every feature of Vault is available in dev mode?

Yes

 

Dev server is unsealed

When you start dev server it automatically initialized and unsealed. It is ready for use, you no need to unseal explicitly.

 

Dev server store the data in-memory

It store the data in-memory.

 

Find below steps to perform CRUD operations against vault dev server.

 

Step 1:Start vault dev server by executing below command.

vault server -dev

$vault server -dev
==> Vault server configuration:

             Api Address: http://127.0.0.1:8200
                     Cgo: disabled
         Cluster Address: https://127.0.0.1:8201
              Listener 1: tcp (addr: "127.0.0.1:8200", cluster address: "127.0.0.1:8201", max_request_duration: "1m30s", max_request_size: "33554432", tls: "disabled")
               Log Level: info
                   Mlock: supported: false, enabled: false
           Recovery Mode: false
                 Storage: inmem
                 Version: Vault v1.4.2
             Version Sha: 18f1c494be8b06788c2fdda1a4296eb3c4b174ce+CHANGES

WARNING! dev mode is enabled! In this mode, Vault runs entirely in-memory
and starts unsealed with a single unseal key. The root token is already
authenticated to the CLI, so you can immediately begin using Vault.

You may need to set the following environment variable:

    $ export VAULT_ADDR='http://127.0.0.1:8200'

The unseal key and root token are displayed below in case you want to
seal/unseal the Vault or re-authenticate.

Unseal Key: 7Ikm5CEkuxiUAITXgWJb81Hfo7wdymr3gM1igvOEiLo=
Root Token: s.l5QIWgO9MhRc8dqQpuqFEQ5V

Development mode should NOT be used in production installations!

==> Vault server started! Log data will stream in below:

2020-06-01T19:27:15.762+0530 [INFO]  proxy environment: http_proxy= https_proxy= no_proxy=
2020-06-01T19:27:15.765+0530 [WARN]  no `api_addr` value specified in config or in VAULT_API_ADDR; falling back to detection if possible, but this value should be manually set
2020-06-01T19:27:15.768+0530 [ERROR] core: no seal config found, can't determine if legacy or new-style shamir
2020-06-01T19:27:15.768+0530 [ERROR] core: no seal config found, can't determine if legacy or new-style shamir
2020-06-01T19:27:15.768+0530 [INFO]  core: security barrier not initialized
2020-06-01T19:27:15.768+0530 [INFO]  core: security barrier initialized: stored=1 shares=1 threshold=1
2020-06-01T19:27:15.769+0530 [INFO]  core: post-unseal setup starting
2020-06-01T19:27:15.780+0530 [INFO]  core: loaded wrapping token key
2020-06-01T19:27:15.780+0530 [INFO]  core: successfully setup plugin catalog: plugin-directory=
2020-06-01T19:27:15.780+0530 [INFO]  core: no mounts; adding default mount table
2020-06-01T19:27:15.781+0530 [INFO]  core: successfully mounted backend: type=cubbyhole path=cubbyhole/
2020-06-01T19:27:15.781+0530 [INFO]  core: successfully mounted backend: type=system path=sys/
2020-06-01T19:27:15.781+0530 [INFO]  core: successfully mounted backend: type=identity path=identity/
2020-06-01T19:27:15.787+0530 [INFO]  core: successfully enabled credential backend: type=token path=token/
2020-06-01T19:27:15.787+0530 [INFO]  core: restoring leases
2020-06-01T19:27:15.787+0530 [INFO]  rollback: starting rollback manager
2020-06-01T19:27:15.788+0530 [INFO]  expiration: lease restore complete
2020-06-01T19:27:15.788+0530 [INFO]  identity: entities restored
2020-06-01T19:27:15.788+0530 [INFO]  identity: groups restored
2020-06-01T19:27:15.788+0530 [INFO]  core: post-unseal setup complete
2020-06-01T19:27:15.790+0530 [INFO]  core: root token generated
2020-06-01T19:27:15.790+0530 [INFO]  core: pre-seal teardown starting
2020-06-01T19:27:15.790+0530 [INFO]  rollback: stopping rollback manager
2020-06-01T19:27:15.790+0530 [INFO]  core: pre-seal teardown complete
2020-06-01T19:27:15.790+0530 [ERROR] core: no seal config found, can't determine if legacy or new-style shamir
2020-06-01T19:27:15.790+0530 [INFO]  core.cluster-listener.tcp: starting listener: listener_address=127.0.0.1:8201
2020-06-01T19:27:15.790+0530 [INFO]  core.cluster-listener: serving cluster requests: cluster_listen_address=127.0.0.1:8201
2020-06-01T19:27:15.790+0530 [INFO]  core: post-unseal setup starting
2020-06-01T19:27:15.791+0530 [INFO]  core: loaded wrapping token key
2020-06-01T19:27:15.791+0530 [INFO]  core: successfully setup plugin catalog: plugin-directory=
2020-06-01T19:27:15.792+0530 [INFO]  core: successfully mounted backend: type=system path=sys/
2020-06-01T19:27:15.792+0530 [INFO]  core: successfully mounted backend: type=identity path=identity/
2020-06-01T19:27:15.792+0530 [INFO]  core: successfully mounted backend: type=cubbyhole path=cubbyhole/
2020-06-01T19:27:15.792+0530 [INFO]  core: successfully enabled credential backend: type=token path=token/
2020-06-01T19:27:15.792+0530 [INFO]  core: restoring leases
2020-06-01T19:27:15.792+0530 [INFO]  rollback: starting rollback manager
2020-06-01T19:27:15.793+0530 [INFO]  expiration: lease restore complete
2020-06-01T19:27:15.793+0530 [INFO]  identity: entities restored
2020-06-01T19:27:15.793+0530 [INFO]  identity: groups restored
2020-06-01T19:27:15.793+0530 [INFO]  core: post-unseal setup complete
2020-06-01T19:27:15.793+0530 [INFO]  core: vault is unsealed
2020-06-01T19:27:15.798+0530 [INFO]  core: successful mount: namespace= path=secret/ type=kv
2020-06-01T19:27:15.799+0530 [INFO]  secrets.kv.kv_acf5e2da: collecting keys to upgrade
2020-06-01T19:27:15.799+0530 [INFO]  secrets.kv.kv_acf5e2da: done collecting keys: num_keys=1
2020-06-01T19:27:15.799+0530 [INFO]  secrets.kv.kv_acf5e2da: upgrading keys finished

Step 2: Points to be noted in step 1 output.

 

Dev server is started at port 8200

http://127.0.0.1:8200

 

Vault run in-memory.

Vault is already unsealed with a single unseal key ‘7Ikm5CEkuxiUAITXgWJb81Hfo7wdymr3gM1igvOEiLo=’.

Root token ‘s.l5QIWgO9MhRc8dqQpuqFEQ5V’

 

To communicate with dev server, we need to set following environment variable in the terminal.

 

export VAULT_ADDR='http://127.0.0.1:8200'

 

Development mode should not be used in production installations.

 

Step 3: Open other terminal and set VAULT_ADDR by executing below command.

 

export VAULT_ADDR='http://127.0.0.1:8200'

 

 

Step 4: Enable kv secret engine at path secret/kv.

$vault secrets enable -path=my-secrets/ kv
Success! Enabled the kv secrets engine at: my-secrets/

Step 5: Write some key-values at path my-secrets/my-app

 

vault kv put my-secrets/my-app username=krishna123 password=password123

$vault kv put my-secrets/my-app username=krishna123 password=password123
Success! Data written to: my-secrets/my-app

Step 6: Get the secrets.

vault kv get my-secrets/my-app

 

$vault kv get my-secrets/my-app
====== Data ======
Key         Value
---         -----
password    password123
username    krishna123

Step 7: Delete the secrets.

vault kv delete my-secrets/my-app

$vault kv delete my-secrets/my-app
Success! Data deleted (if it existed) at: my-secrets/my-app
$
$vault kv get my-secrets/my-app
No value found at my-secrets/my-app




Previous                                                    Next                                                    Home

Java: HashiCorp Vault: Hello World Application

 Step 1: Create new maven project ‘hashiCorp’. 

Step 2: Update pom.xml with maven dependencies.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sample.app</groupId>
    <artifactId>hashicorp</artifactId>
    <version>1</version>

    <dependencies>
        <dependency>
            <groupId>com.bettercloud</groupId>
            <artifactId>vault-java-driver</artifactId>
            <version>5.1.0</version>
        </dependency>
    </dependencies>
</project>

 

Step 3: Create new package ‘com.sample.app’ and define App.java like below.

App.java
package com.sample.app;

import java.util.HashMap;
import java.util.Map;

import com.bettercloud.vault.Vault;
import com.bettercloud.vault.VaultConfig;
import com.bettercloud.vault.VaultException;
import com.bettercloud.vault.response.LogicalResponse;

public class App {
    private static final String VAULT_SERVER_PATH = "http://127.0.0.1:9999";
    private static final String TOKEN = "s.E3BRk50CvwMf7nWA0of9qsQB";

    public static void main(String args[]) throws VaultException {
        final VaultConfig vaultConfig = new VaultConfig().address(VAULT_SERVER_PATH).token(TOKEN).build();
        final Vault vault = new Vault(vaultConfig);

        final Map<String, Object> secrets = new HashMap<>();
        secrets.put("user_name", "krishna");
        secrets.put("password", "password123");

        // Write operation
        final LogicalResponse writeResponse = vault.logical().write("secret/my-app", secrets);

        // Read Data
        final String userName = vault.logical().read("secret/my-app").getData().get("user_name");
        final String password = vault.logical().read("secret/my-app").getData().get("password");

        System.out.println("user name : " + userName);
        System.out.println("password: " + password);

    }
}

 

Output

user name : krishna
password: password123

 

Note

Update VAULT_SERVER_PATH and TOKEN accordingly.

 

 

 

  

Previous                                                    Next                                                    Home

Saturday, 26 September 2020

HashiCorp Vault: Start a Vault Server

 Step 1: Define a configuration file ‘vault.conf’

 

vault.conf

storage "inmem" {
}

listener "tcp" {
  address = "0.0.0.0:9999"
  tls_disable = 1
}

disable_mlock = true

Step 2: Start a vault server by executing below command.

 

vault server -config vault.conf

$vault server -config vault.conf
==> Vault server configuration:

                     Cgo: disabled
              Listener 1: tcp (addr: "0.0.0.0:9999", cluster address: "0.0.0.0:10000", max_request_duration: "1m30s", max_request_size: "33554432", tls: "disabled")
               Log Level: info
                   Mlock: supported: false, enabled: false
           Recovery Mode: false
                 Storage: inmem
                 Version: Vault v1.4.2
             Version Sha: 18f1c494be8b06788c2fdda1a4296eb3c4b174ce+CHANGES

==> Vault server started! Log data will stream in below:

2020-06-01T18:03:39.121+0530 [INFO]  proxy environment: http_proxy= https_proxy= no_proxy=
2020-06-01T18:03:39.122+0530 [WARN]  no `api_addr` value specified in config or in VAULT_API_ADDR; falling back to detection if possible, but this value should be manually set


Step 3: Open other terminal and set VAULT_ADDR variable by executing below command.

export VAULT_ADDR=http://127.0.0.1:9999

 

Initialize and unseal vault

 

Initialize Vault

It is a process of initial key generation. Vault create two thing in initialization process.

 

a.   The master key and key splits

b.   A root token

 

Execute below command in terminal.

vault operator init -key-shares=5 -key-threshold=2

 

As per the above command, to unseal vault, minimum two shared keys should be provided.

$vault operator init -key-shares=5 -key-threshold=2
Unseal Key 1: SjtWQ+s+30GmiXfGqz/CWTmVs5or3yCVF8wcYMhJJj/E
Unseal Key 2: zH2n8A4H+3MyG5hD0WQsAHyv4wSJyju2nl2cbx7L2DSw
Unseal Key 3: dHEuNdy6jX6x+OrLMKNO50AilCdHgZCw1o5En9EzoYSx
Unseal Key 4: TuK5YEUmYjpxzHSLsUMPoqnErOCSUBd0ZcCKFtNYv1xm
Unseal Key 5: ex2DgsSYZhtGQiVvmAYReYerdgejpBSG6J8GrjxKPcO4

Initial Root Token: s.E3BRk50CvwMf7nWA0of9qsQB

Vault initialized with 5 key shares and a key threshold of 2. Please securely
distribute the key shares printed above. When the Vault is re-sealed,
restarted, or stopped, you must supply at least 2 of these keys to unseal it
before it can start servicing requests.

Vault does not store the generated master key. Without at least 2 key to
reconstruct the master key, Vault will remain permanently sealed!

It is possible to generate new unseal keys, provided you have a quorum of
existing unseal keys shares. See "vault operator rekey" for more information.

 

As you see the output, Vault is initialized with 5 key shared and key threshold of 2. When the Vault is re-sealed, restarted, or stopped, you must supply at least 2 of these keys to unseal it before it can start servicing requests.

 

Unsealing the Vault

In Unsealing process, we supply keys to Vault so Vault can decrypt the encrypted data and start serving clients.

 

Execute below command twice with different shared keys generated in initialization process.

 

vault operator unseal {Unseal key}. We need to execute unseal command with two different unseal keys.

$vault operator unseal ex2DgsSYZhtGQiVvmAYReYerdgejpBSG6J8GrjxKPcO4
Key                Value
---                -----
Seal Type          shamir
Initialized        true
Sealed             true
Total Shares       5
Threshold          2
Unseal Progress    1/2
Unseal Nonce       04a05ef6-1d8c-971b-dbad-684ab3efdf78
Version            1.4.2
HA Enabled         false

$vault operator unseal zH2n8A4H+3MyG5hD0WQsAHyv4wSJyju2nl2cbx7L2DSw
Key             Value
---             -----
Seal Type       shamir
Initialized     true
Sealed          false
Total Shares    5
Threshold       2
Version         1.4.2
Cluster Name    vault-cluster-5d1876f0
Cluster ID      86774adb-7768-ac51-d7e2-a7ec1cfde4c4
HA Enabled      false

 

Store secrets into vault

Once Vault unsealed, you can store the secrets into vault. Secrets written to vault are encrypted and stored to backed configured storage.

 

To perform any CRUD with Vault, we need to provide vault token that is generated as part of initialization process.

 

export VAULT_TOKEN=s.E3BRk50CvwMf7nWA0of9qsQB

 

Enable kv secret engine at path secret/kv.

$vault secrets enable -path=secret/ kv
Success! Enabled the kv secrets engine at: secret/

 

Now you can add secrets to the path secret/..

$vault kv put secret/my-app username=krishna123 password=password123
Success! Data written to: secret/my-app

 

Read the secrets

$vault kv get secret/my-app
====== Data ======
Key         Value
---         -----
password    password123
username    krishna123

 

Delete Secrets

$vault kv delete secret/my-app
Success! Data deleted (if it existed) at: secret/my-app
$
$vault kv get secret/my-app
No value found at secret/my-app

 

 

 

Previous                                                    Next                                                    Home

Friday, 25 September 2020

Install HashiCorp Vault in Mac

Open terminal and execute below command.

brew install vault

 

Once the service is installed, execute the command ‘vault’.

$vault
Usage: vault <command> [args]

Common commands:
    read        Read data and retrieves secrets
    write       Write data, configuration, and secrets
    delete      Delete secrets and configuration
    list        List data or secrets
    login       Authenticate locally
    agent       Start a Vault agent
    server      Start a Vault server
    status      Print seal and HA status
    unwrap      Unwrap a wrapped secret

Other commands:
    audit          Interact with audit devices
    auth           Interact with auth methods
    debug          Runs the debug command
    kv             Interact with Vault's Key-Value storage
    lease          Interact with leases
    namespace      Interact with namespaces
    operator       Perform operator-specific tasks
    path-help      Retrieve API help for paths
    plugin         Interact with Vault plugins and catalog
    policy         Interact with policies
    print          Prints runtime configurations
    secrets        Interact with secrets engines
    ssh            Initiate an SSH session
    token          Interact with tokens
$

 

 

 

Previous                                                    Next                                                    Home

Core Components of Vault

 

Storage Backends

Storage Backends represents the location where Vaults store the information.

 

Syntax

storage [NAME] {

  [PARAMETERS...]

}

 

Example

storage "file" {

  path = "/mnt/vault/data"

}

 

Right now Vault supports following storage backends.

a.   Azure

b.   Cassandra

c.    CockroachDB

d.   Consul

e.   CouchDB

f.     DynamoDB

g.   Etcd

h.   Filesystem

i.     FoundationDB

j.     Google Cloud Spanner

k.    Google Cloud Storage

l.     In-Memory

m. Manta

n.   MSSQL

o.   MySQL

p.   OCI Object Storage

q.   PostgreSQL

r.     Raft

s.    S3

t.     Swift

u.   Zookeeper

 

Secrets Engines

These are the components which store, generate or encrypt data. Depending on your requirement, you can enable one or more secrets engines.

 

Following are the different secrets engines supported by Vault.

a.   Active Directory

b.   AliCloud

c.    AWS

d.   Azure

e.   Consul

f.     Cubbyhole

g.   Databases

h.   Google Cloud

i.     Google Cloud KMS

j.     KMIP ENTERPRISE

k.    Key/Value

l.     Identity

m. MongoDB Atlas

n.   Nomad

o.   OpenLDAP

p.   PKI (Certificates)

q.   RabbitMQ

r.     SSH

s.    TOTP

t.     Transform ENTERPRISE

u.   Transit

v.    Venafi (Certificates)

 

Authentication Methods

Auth methods are the components in Vault that perform authentication and are responsible for assigning identity and a set of policies to a user.

 

Depending on your use case, you can enable multiple authentication methods.

 

Following different authentication methods supported by Vault.

 

a.   AppRole

b.   AliCloud

c.    AWS

d.   Azure

e.   Cloud Foundry

f.     GitHub

g.   Google Cloud

h.   JWT/OIDC

i.     Kerberos

j.     Kubernetes

k.    LDAP

l.     Oracle Cloud Infrastructure

m. Okta

n.   RADIUS

o.   TLS Certificates

p.   Tokens

q.   Username & Password

 

Audit Devices

This component responsible to log all the requests and responses to Vault. Multiple audit devices can be enabled and Vault will send the audit logs to both.

 

Each line in Audit log is a JSON Object. Responses are hashed with a salt using HMAC-SHA256. The purpose of the hash is, so that secrets aren't in plaintext within your audit logs.

 

Following Audit devices supported by Vault.

a.   File

b.   Syslog

c.    Socket

 

Vault Paths

Paths are used with the API or read, write, delete commands in order to interact with Vault. Path informs Vault, which Vault component a request should route.

 

Permissions or Policies are granted based on path.

 

Example

vault secrets enable -path=secret/ kv

 

Above statement enable kv secret engine at path secret/kv.

Previous                                                    Next                                                    Home