티스토리 뷰

Security/Cloud Native

How to use Vault

Jacob_baek 2020. 10. 23. 15:19

Vault에 대한 설명은 아래 링크를 참고

installation

centos 8 혹은 RHEL 8 기반은 다음과 같은 명령을 통해 설치가 가능하다.

[root@monitor ~]# dnf config-manager --add-repo https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
Adding repo from: https://rpm.releases.hashicorp.com/RHEL/hashicorp.repo
[root@monitor ~]# dnf install vault
Hashicorp Stable - x86_64                       157 kB/s | 232 kB     00:01    
Dependencies resolved.
================================================================================
 Package         Architecture     Version             Repository           Size
================================================================================
Installing:
 vault           x86_64           1.5.4-1             hashicorp            40 M

Transaction Summary
================================================================================
Install  1 Package

How to use

Production mode로 사용하는 방식

  1. server 준비

    [root@monitor vault.d]# cat /etc/vault.d/vault.hcl
    storage "raft" {
          path    = "/opt/vault/data"
          node_id = "vault-server"
    }
    
    listener "tcp" {
          address     = "0.0.0.0:8200"
          tls_disable = 1
    }
    
    api_addr = "http://127.0.0.1:8200"
    cluster_addr = "https://127.0.0.1:8201"
    ui = true
    [root@monitor vault.d]# cat /usr/lib/systemd/system/vault.service
    [Unit]
    Description="HashiCorp Vault - A tool for managing secrets"
    Documentation=https://www.vaultproject.io/docs/
    Requires=network-online.target
    After=network-online.target
    ConditionFileNotEmpty=/etc/vault.d/vault.hcl
    StartLimitIntervalSec=60
    StartLimitBurst=3
    
    [Service]
    User=vault
    Group=vault
    ProtectSystem=full
    ProtectHome=read-only
    PrivateTmp=yes
    PrivateDevices=yes
    SecureBits=keep-caps
    AmbientCapabilities=CAP_IPC_LOCK
    CapabilityBoundingSet=CAP_SYSLOG CAP_IPC_LOCK
    NoNewPrivileges=yes
    ExecStart=/usr/bin/vault server -config=/etc/vault.d/vault.hcl
    ExecReload=/bin/kill --signal HUP $MAINPID
    KillMode=process
    KillSignal=SIGINT
    Restart=on-failure
    RestartSec=5
    TimeoutStopSec=30
    StartLimitInterval=60
    StartLimitBurst=3
    LimitNOFILE=65536
    LimitMEMLOCK=infinity
    
    [Install]
    WantedBy=multi-user.target

    또한 아래와 같은 환경변수 추가가 필요하다.

    [root@vault-server vault.d]# cat ~/.bashrc 
    # .bashrc
    
    # User specific aliases and functions
    
    alias rm='rm -i'
    alias cp='cp -i'
    alias mv='mv -i'
    
    # Source global definitions
    if [ -f /etc/bashrc ]; then
        . /etc/bashrc
    fi
    
    export VAULT_ADDR='http://127.0.0.1:8200' # <====== 추가 필요
  2. server 시작

    [root@vault-server ~]# systemctl daemon-reload
    [root@vault-server ~]# systemctl start vault
  3. vault 상태(not initialized)에서 초기화 작업 수행

    [root@vault-server vault]# vault status
    2020-10-17T11:41:35.840Z [INFO]  core: seal configuration missing, not initialized
    Key                Value
    ---                -----
    Seal Type          shamir
    Initialized        false      # <======= 아직 초기화 되지 않은 상태
    Sealed             true
    Total Shares       0
    Threshold          0
    Unseal Progress    0/0
    Unseal Nonce       n/a
    Version            n/a
    HA Enabled         true

    초기화 작업 수행

    [root@monitor vault.d]# vault operator init
    Unseal Key 1: BWEkwRnB8rwhgdTddNXHeIU81XeuNPaOp9A4oSUKK4pG
    Unseal Key 2: 1rGz9s5ppeqFeuFQ4Xo3oVP8pHduA7uoHMCcvnkk75qs
    Unseal Key 3: 1VjJEN+e0YtY0s7or0q4ydJR9lc4NqSB5WmJ2UAz8j/C
    Unseal Key 4: uIc1Pn0qe+aK4dtVhdDaNU3mrP3TSWbdv7kty5Z30Zae
    Unseal Key 5: 1vh4KTa5F6CXFdNqiF0yAyMFdjRrNbZhYZNJg6pkIrTP
    
    Initial Root Token: s.HkueChqdr2GeyDyR2lvXRC5y
    
    Vault initialized with 5 key shares and a key threshold of 3. Please securely
    distribute the key shares printed above. When the Vault is re-sealed,
    restarted, or stopped, you must supply at least 3 of these keys to unseal it
    before it can start servicing requests.
    
    Vault does not store the generated master key. Without at least 3 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.
  4. vault 상태 재확인(sealed) 및 unseal 수행

    [root@monitor vault]# vault status
    Key                Value
    ---                -----
    Seal Type          shamir
    Initialized        true
    Sealed             true
    Total Shares       5
    Threshold          3
    Unseal Progress    0/3
    Unseal Nonce       n/a
    Version            1.5.4
    HA Enabled         true

    unsealed

    [root@monitor vault.d]# vault operator unseal 1rGz9s5ppeqFeuFQ4Xo3oVP8pHduA7uoHMCcvnkk75qs
    Key                Value
    ---                -----
    Seal Type          shamir
    Initialized        true
    Sealed             true
    Total Shares       5
    Threshold          3
    Unseal Progress    1/3
    Unseal Nonce       2d3d5566-4c07-cf0e-8fc2-cc96fec2fb04
    Version            1.5.4
    HA Enabled         true
    [root@monitor vault.d]# vault operator unseal 1VjJEN+e0YtY0s7or0q4ydJR9lc4NqSB5WmJ2UAz8j/C
    Key                Value
    ---                -----
    Seal Type          shamir
    Initialized        true
    Sealed             true
    Total Shares       5
    Threshold          3
    Unseal Progress    2/3
    Unseal Nonce       2d3d5566-4c07-cf0e-8fc2-cc96fec2fb04
    Version            1.5.4
    HA Enabled         true
    [root@monitor vault.d]# vault operator unseal uIc1Pn0qe+aK4dtVhdDaNU3mrP3TSWbdv7kty5Z30Zae
    Key                     Value
    ---                     -----
    Seal Type               shamir
    Initialized             true
    Sealed                  false
    Total Shares            5
    Threshold               3
    Version                 1.5.4
    Cluster Name            vault-cluster-dd2a107d
    Cluster ID              f7b59b16-2c53-d35a-dbc3-fc2f5acf1fe4
    HA Enabled              true
    HA Cluster              n/a
    HA Mode                 standby
    Active Node Address     <none>
    Raft Committed Index    24
    Raft Applied Index      24
  5. vault 상태 재확인(unsealed)

    [root@monitor vault]# vault status
    Key                     Value
    ---                     -----
    Seal Type               shamir
    Initialized             true
    Sealed                  false
    Total Shares            5
    Threshold               3
    Version                 1.5.4
    Cluster Name            vault-cluster-05fb7ad8
    Cluster ID              2f9f5429-34a3-7794-97dd-bf6fc9e08135
    HA Enabled              true
    HA Cluster              n/a
    HA Mode                 standby
    Active Node Address     <none>
    Raft Committed Index    24
    Raft Applied Index      24

    참고로 여기서 vault를 재시작하는 경우 Sealed vaule가 다시 true로 변경된다.

  6. login
    vault secrets list를 확인해보고자 했으나 아직 active 상태가 아니라하며 500 error를 뱉어낸다.

    [root@monitor vault.d]# vault secrets list
    Error listing secrets engines: Error making API request.
    
    URL: GET http://127.0.0.1:8200/v1/sys/mounts
    Code: 500. Errors:
    
    * local node not active but active cluster node not found

    vault login 후 다시 수행해보자.

    [root@monitor vault.d]# vault login s.HkueChqdr2GeyDyR2lvXRC5y
    Success! You are now authenticated. The token information displayed below
    is already stored in the token helper. You do NOT need to run "vault login"
    again. Future Vault requests will automatically use this token.
    
    Key                  Value
    ---                  -----
    token                s.HkueChqdr2GeyDyR2lvXRC5y
    token_accessor       NyZKKPvDFtfg9Yj2IoLf1VxR
    token_duration       ∞
    token_renewable      false
    token_policies       ["root"]
    identity_policies    []
    policies             ["root"]

    아래와 같이 vault secret 항목이 출력된다.

    [root@monitor vault.d]# vault secrets list
    Path          Type         Accessor              Description
    ----          ----         --------              -----------
    cubbyhole/    cubbyhole    cubbyhole_0d16ec72    per-token private secret storage
    identity/     identity     identity_627ee9ca     identity store
    sys/          system       system_ba5dbfbb       system endpoints used for control, policy and debugging
  7. secret engine enable

    [root@monitor vault.d]# vault secrets enable -version=2 kv
    Success! Enabled the kv secrets engine at: kv/
    [root@monitor vault.d]# vault secrets list
    Path          Type         Accessor              Description
    ----          ----         --------              -----------
    cubbyhole/    cubbyhole    cubbyhole_0d16ec72    per-token private secret storage
    identity/     identity     identity_627ee9ca     identity store
    kv/           kv           kv_ac9d76db           n/a
    sys/          system       system_ba5dbfbb       system endpoints used for control, policy and debugging

만약 export VAULT_ADDR='http://127.0.0.1:8200' 명령을 함께 수행하지 않을 경우 아래와 같이 https로 요청되어 연결이 이루어지지 않는다.

[root@monitor vault-test]# vault status  
Error checking seal status: Get "[https://127.0.0.1:8200/v1/sys/seal-status"](https://127.0.0.1:8200/v1/sys/seal-status"): http: server gave HTTP response to HTTPS client

ssh 사용

ssh-signer의 경우 TrustedUserCAKeys 설정을 통해 인증 과정을 수행한다.
이를 다르게 해석해보면 사용자의 인증서가 서명된 CA의 public key를 신뢰할수 있도록 설정해

관련된 내용을 자세히 설명한 블로그를 소개하니 한번 읽고 오는것을 추천한다.

아래 두가지 방식으로 signing을 진행할수 있고 verification을 수행할 수 있다.

Vault Server

plugin을 enable 한다.

[root@vault-server ~]# vault secrets enable -path=ssh-client-signer ssh
Success! Enabled the ssh secrets engine at: ssh-client-signer/

이후 인증서를 생성한다.

[root@vault-server ~]# vault write ssh-client-signer/config/ca generate_signing_key=true
Key           Value
---           -----
public_key    ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQC1oefdzwZ3mVfcUXSVcpncJR67BMiGAB7pmBnnaD5VBrX82Y2auBH9hkaJSz9eNBGg0VbAt8HEQ+4J/dcvR5y4ybaxiyAHzMRbIexvDDIIg1VrQ5qOqTelovZ9ib8kWYzQFjK8/6hKnny1zW4YPzMTFCGz443M0ibMh4+C5jgNhNfoSUzUJZC/TMXusV1dS5LO2L5ZzZho/++pmtf55rHIR631kte0tWGpFDmTdvZdqgBWxisqG7/w0LJUaU78bb4x5rBBzBILd4WEW0f/Z37YvbK9GupfLKxMaoWf9oac8fXdUXoAxsTv69YSsjCHN1EpE5E/Yr4Au4GuZDc3hNmDQZp9PHRfEYSSxZyzOHefZfHbcfHGk6CRZGzBGLdJVsokUebQfKXWxljCycQU7LZLXLCT7GvQ5r9p/qqUECYeXL35OIne9YdsqPr5T0eSCFNUX65s0/tv9205yWReI92cTqtm1cGdzLJos1QePeVjfUAVJqmR8n8tLkg1sODDEMVTDzp5Qn1KPChKEEs5riS6/s9tSb542dqV0TTlXsz31KAlETtzsh5xrfkhkLR+FkT5OZC+oe/ir1aodtfrvBxTL1fVJCQC6WuGDBctr0oDs3F+400IYhVAH9nj7GjI3c7dcXFUmRYbQgCsnu1+e1meWN3joxPjeZrOwzcDXUmQhQ==

role을 생성하자. (향후 client에서 해당 role을 기반으로 public key를 signing 한다.)

[root@vault-server ~]# cat testrole.json 
{
  "allow_user_certificates": true,
  "allowed_users": "*",
  "allowed_extensions": "permit-pty,permit-port-forwarding",
  "default_extensions": [
    {
      "permit-pty": ""
    }
  ],
  "key_type": "ca",
  "default_user": "centos",
  "ttl": "30m0s"
}
[root@vault-server ~]# vault write ssh-client-signer/roles/ssh-srv-role @testrole.json 
Success! Data written to: ssh-client-signer/roles/ssh-srv-role

다음과 같이 role 정보를 확인할 수 있다.

[root@vault-server ~]# vault read ssh-client-signer/roles/ssh-srv-role
Key                         Value
---                         -----
algorithm_signer            n/a
allow_bare_domains          false
allow_host_certificates     false
allow_subdomains            false
allow_user_certificates     true
allow_user_key_ids          false
allowed_critical_options    n/a
allowed_domains             n/a
allowed_extensions          permit-pty,permit-port-forwarding
allowed_user_key_lengths    map[]
allowed_users               *
allowed_users_template      false
default_critical_options    map[]
default_extensions          map[permit-pty:]
default_user                centos
key_bits                    0
key_id_format               n/a
key_type                    ca
max_ttl                     0s
ttl                         30m

Target Server

아래와 같이 생성된 인증서를 해당 서버에 파일로 남겨둔다.

[root@vault-server ~]# curl -o /etc/ssh/trusted-user-ca-keys.pem http://127.0.0.1:8200/v1/ssh-client-signer/public_key
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   725  100   725    0     0   236k      0 --:--:-- --:--:-- --:--:--  236k

# 혹은 아래와 같은 방식을 사용
[root@vault-server ~]# vault read -field=public_key ssh-client-signer/config/ca > /etc/ssh/trusted-user-ca-keys.pem

# 혹은 위 생성시 발생된 key 를 text 그대로 copy&paste

해당 인증서를 참조할수 있도록 TrustedUserCAKeys를 추가한다.

[root@vault-server ~]# cat /etc/ssh/sshd_config  | grep Trust
TrustedUserCAKeys /etc/ssh/trusted-user-ca-keys.pem

이후 다시 sshd daemon을 재시작하여 반영한다.

[root@vault-server ~]# systemctl restart sshd

Client 에서 작업

아래와 같이 vault 명령을 통한 API call이 이루어지도록 환경변수를 등록한다.

[root@vault-client ~]# export | grep VAULT
declare -x VAULT_ADDR="http://192.168.201.81:8200"
declare -x VAULT_TOKEN="s.HkueChqdr2GeyDyR2lvXRC5y"

실제 ssh 접속에 사용할 sshkey를 생성하자.(사전에 존재한다면 해당 과정은 skip)

[root@vault-client ~]# ssh-keygen -t rsa -C "client@vault"
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:0s7UGkUyYupWpDEDcT8Wn/pW7/mL7x80STTBq/EnPQM client@vault
The key's randomart image is:
+---[RSA 3072]----+
|  oo= = o .   .+.|
|   . X + =    ...|
|    o = o .    ..|
|   . o + o   E...|
|    o o S o   == |
|   .   * + . .o++|
|        *   .  o+|
|       .   . o  .|
|            ++=o.|
+----[SHA256]-----+

생성된 public key를 vault 명령을 통해 signing 과정을 수행한다.

[root@vault-client ~]# vault write ssh-client-signer/sign/ssh-srv-role public_key=@$HOME/.ssh/id_rsa.pub
Key              Value
---              -----
serial_number    119dfe95bc174a0a
signed_key       ssh-rsa-cert-v01@openssh.com AAAAHHNzaC1yc2EtY2VydC12MDFAb3BlbnNzaC5jb20AAAAg/UM4tCfgHxX35O/9n/0rs5UNL+ay9P9kzDT9B67cTw0AAAADAQABAAABgQC/3Hvb6snGEJsW0TzG1j7NoFPEGk+ZkT/yNfTWPdbLc/1DaNXfhvp26qrasX/8fR5Un7JkY4Z7Bkv6HyX96cHUs/m1m4CHza7LN6hhbo8KJlpnqDNdl+dS5BeomXWG66G/8BHTSYje4DCnGmIqVtpZiaKRCbOBt9M/60DHFPilzqBoVrmASqzPFbjoqjWSpmz87zX7GtjIDLJdYt6A1ukswirnQAYiHfbROCTmxXvhX3UYq+BVYfywAE/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c7Ieca35IZC0fhZE+TmQvqHv4q9WqHbX67wcUy9X1SQkAulrhgwXLa9KA7NxfuNNCGIVQB/Z4+xoyN3O3XFxVJkWG0IArJ7tfntZnljd46MT43mazsM3A11JkIUAAAIPAAAAB3NzaC1yc2EAAAIAF2dfEhNj0Lu+MpfSQQyXbTYJhwv5CLjXE12RiaFF27DsIqha3PYeumsbqU/gUhq7U5+/tnlD4OW4Xi8Lx9vEWOmarLNauHyyvPlmQcxjwzmUou1g2qCdEBRZpCHWJKaX2b513Jb7J1m+cqPd+NGyDIp+OsWcVksmm5nJAT8Qf9I2oqPUS7zW4jM9A7TwXbVfsEh3Z2p7xHySdWagWBakOqlVetaYYV4nTZf5VdzFvuYkJcRVPTMeRDxpuqGp530lGH03lfnl1th1TO9FyCK/CzphZ1Qeqmr6LDxQnvzC59TMUOiYVz7NfTf9nDUR/mPgOrWrjgqGw+BFU340aEMPShWLluDZF9eKJTImg/1vJxj6N4c3XzP4ZLUY64/UK607r+RHjUPNlHNOMzD1RMH6PCJGAzz4J8/WP7bb9me50OcE0WDO9KVDXMURmmwAovu0CLFknPYbz32ttPzU+d1rKXTJFAtvmEN4T9+l3Dvo0MKtABT5eawaWKpEURRPiBIzx42/Ff1qUODT0ZMkco03dIU5f9ZCcjHJgcWNanF/GxmEDJJjSBPVS4oaOS0sCnRvid9gVSF/3XG5hOYGovt9i7JVRuLPReaiRjwgta1PGUXW3yi0o7CfoExqJ3bwSGiy87VmqOpFwnAarpC1SldCsj2KO310VbedQxWOSp1C7wI=

# 아래 명령만 수행해도 된다.
[root@vault-client ~]# vault write -field=signed_key ssh-client-signer/sign/ssh-srv-role public_key=@$HOME/.ssh/id_rsa.pub > ~/.ssh/signed.pub

아래와 같이 접속을 수행하면 접속이 이루어짐을 확인할 수 있다.

[root@vault-client ~]# ssh -i ~/.ssh/signed.pub -i ~/.ssh/id_rsa centos@192.168.201.81

관련하여 ansible-playbook으로 vault-server/target-server/client 별 role을 생성해두었으니 이를 참고하면 좀더 쉽게 사용이 가능할것으로 보인다.

참고사이트

'Security > Cloud Native' 카테고리의 다른 글

Gatekeeper mutatation  (0) 2023.05.04
Rego test and http.send  (0) 2023.05.03
trivy db search  (0) 2023.04.02
Hashicorp Boundary  (0) 2020.10.28
How to use Hashicorp boundary  (0) 2020.10.24
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/10   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함