Vault와 Consul Template으로 Consul 가십 암호화 생성·관리하기

Vault와 Consul Template으로 Consul 가십 암호화 생성·관리하기 (Generate and manage gossip encryption for Consul with Vault and Consul Template)

이 문서는 HashiCorp Vault와 Consul Template을 사용해 Consul 데이터센터의 가십(gossip) 암호화 키를 만들고 관리하는 과정을 자동화하는 방법을 알려드릴게요. 암호화 키를 안전하게 저장하고 주기적으로 회전(rotate)시키는 실무 구성을 배울 수 있어요.

출처: 문서

본문

이 페이지는 HashiCorp Vault와 Consul Template을 사용하여 Consul 데이터센터의 가십 암호화 키를 생성하고 관리하는 과정을 자동화하는 방법을 설명합니다.

개요 (Overview)

Consul 데이터센터를 프로덕션 용도로 구성하려면 데이터센터의 모든 에이전트에 대해 가십 암호화를 활성화하는 것이 필요한 단계 중 하나입니다. 이 과정은 가십 암호화 관리 [/consul/docs/secure/encryption/gossip/enable] 문서에 자세히 설명되어 있습니다.

가십 통신이 대칭 키로 보호되면, 권장 모범 사례는 요구 사항에 맞는 정의된 간격에 따라 가십 키를 회전하는 정책을 정의하는 것입니다. 이 과정을 수동으로 수행하는 방법은 Consul에서 가십 암호화 키 회전 [/consul/docs/secure/encryption/gossip/rotate/vm] 문서에서 확인할 수 있습니다.

이 가이드에서는 Consul을 HashiCorp의 Vault 및 Consul Template과 통합하여 암호화 키를 안전하게 저장하고 회전합니다. 이 과정은 다음 단계를 포함합니다:

  • 가십 암호화 키를 생성합니다.
  • Vault 인스턴스에 연결합니다.
  • Vault에 키 값 저장소를 초기화합니다.
  • Vault에서 암호화 키를 저장하고 검색합니다.
  • Consul Template이 키를 검색한 다음 스크립트를 사용하여 회전하도록 구성합니다.
  • Consul Template을 시작합니다.

이 가이드는 암호화 키 회전을 자동화하는 예제 사용자 정의 스크립트를 제공합니다. 이 스크립트를 시작점으로 사용하여 자신만의 회전 자동화를 만들 수 있습니다.

사전 요구 사항 (Prerequisites)

  • Consul: 이 가이드를 완료하려면 가십 암호화가 활성화된 Consul 데이터센터가 필요합니다. 가십 암호화가 활성화된 Consul 데이터센터를 배포하는 방법은 VMs에 Consul 배포 [/consul/tutorials/get-started-vms/virtual-machine-gs-deploy]를 참조하세요.
  • Vault: 이 가이드는 네트워크에 실행 중인 Vault 클러스터가 있다고 가정합니다. 로컬 Vault dev 서버 [/vault/tutorials/get-started/setup#set-up-the-lab] 또는 기존 Vault 배포를 사용할 수 있습니다.
  • Consul Template: Consul 에이전트와 상호 작용하려면 노드에 consul-template 바이너리 [/consul/docs/automate/consul-template/install]를 설치해야 합니다. 가십 키를 회전하려면 한 노드에만 바이너리를 설치하면 됩니다. 변경 사항은 Consul 데이터센터 전체에 자동으로 전파됩니다.

아래 다이어그램은 기능을 시연하는 데 필요한 최소 아키텍처를 보여줍니다.

암호화 키 생성 (Generate a encryption key)

Consul의 consul keygen 명령을 사용하여 암호화 키를 생성할 수 있습니다.

$ consul keygen | tee encryption.key

T6kFttAkS3oSCS/nvlK8ONmfESmtKhCpRA2pc20RBcA=

Vault 구성 (Configure Vault)

Vault는 임의의 비밀을 저장하는 데 사용할 수 있는 kv secrets engine을 제공합니다. 이 엔진을 사용하여 암호화 키를 저장합니다.

secrets engine을 초기화하기 전에 로컬 Vault 인스턴스에 연결할 수 있도록 VAULT_ADDR 및 VAULT_TOKEN 환경 변수를 설정해야 합니다.

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

VAULT_ADDR 환경 변수는 연결하려는 대상 Vault 서버 주소로 설정해야 합니다.

$ export VAULT_TOKEN="root"

VAULT_TOKEN 환경 변수는 클라이언트 토큰(예: root)을 저장해야 합니다.

Vault secrets engine 초기화 (Initialize the Vault secrets engine)

키/값 v2 secrets engine(kv-v2)을 활성화합니다.

$ vault secrets enable kv-v2

Success! Enabled the kv-v2 secrets engine at: kv-v2/

secrets engine이 활성화되면 다음 명령을 사용하여 제대로 작동하는지 확인합니다.

$ vault secrets list

Path          Type         Accessor              Description
----          ----         --------              -----------
...
kv-v2/        kv           kv_5e0867f7           n/a
secret/       kv           kv_b5027aee           key/value secret storage
...

Vault에 암호화 키 저장 (Store the encryption key in Vault)

secrets engine이 올바르게 초기화되면 여기에 가십 암호화 키를 저장할 수 있습니다.

$ vault kv put kv-v2/consul/config/encryption key=$(cat encryption.key) ttl=1h

Success! Data written to: kv-v2/consul/config/encryption

Tip (팁)

Vault의 KV secrets engine은 만료를 위한 TTL을 강제하지 않습니다. 대신 lease_duration 값은 소비자에게 새 값을 얼마나 자주 확인해야 하는지에 대한 힌트로 사용할 수 있습니다. ttl 값을 변경하거나 사용하지 않을 수도 있지만, Consul Template과 통합하려면 Consul Template이 키의 새 버전을 언제 확인해야 하는지 알 수 있도록 TTL을 정의해야 합니다.

암호화 키 TTL 튜닝

이 튜토리얼에서는 암호화 키의 TTL이 1시간으로 설정되어 있어 키가 만료되기 전에 1시간 동안만 유효함을 의미합니다. 테스트 환경에서는 더 짧은 TTL을 사용하여 TTL이 만료된 후 키가 올바르게 폐기되는지 확인할 수 있습니다.

Vault에서 가십 암호화 키 검색 (Retrieve the gossip encryption key from Vault)

키가 Vault에 저장되면 Vault에 접근 권한이 있는 모든 머신에서 키를 검색할 수 있습니다.

Consul 서버 노드에서 -field 파라미터와 함께 vault kv get 명령을 사용하여 키 값만 검색합니다.

$ vault kv get -field=key kv-v2/consul/config/encryption | tee encryption.key

T6kFttAkS3oSCS/nvlK8ONmfESmtKhCpRA2pc20RBcA=

Vault에서 암호화 키를 검색하면 새 Consul 데이터센터를 구성하거나 가십 암호화가 활성화된 기존 데이터센터의 키를 회전하는 데 사용할 수 있습니다.

키 회전 과정은 가능하면 자동화해야 하며, 다음 단락에서는 Consul Template을 사용하여 이 과정을 자동화하는 방법을 보여줍니다.

Consul Template으로 가십 암호화 키 회전 (Rotate the gossip encryption key with Consul Template)

Consul 데이터센터에서 Consul Template을 사용하여 Vault의 KV secrets engine과 통합하고 Consul의 가십 암호화 키를 동적으로 회전할 수 있습니다.

템플릿 파일 만들기 (Create a template file)

Consul Template이 Vault에서 키를 검색하도록 Go 템플릿을 만듭니다.

이 예시에서는 이러한 템플릿을 /opt/consul/templates 아래에 배치합니다.

$ mkdir -p /opt/consul/templates

/opt/consul/templates 아래에 gossip.key.tpl이라는 파일을 다음 내용으로 만듭니다.

gossip.key.tpl

{{ with secret "kv-v2/data/consul/config/encryption" }}
{{ .Data.data.key}}
{{ end }}

템플릿은 kv-v2/data/consul/config/encryption 경로를 사용하여 Vault와 상호 작용하며 해당 경로에 있는 비밀의 key 값만 검색합니다.

Consul Template 구성 작성 (Create the Consul Template configuration)

만든 템플릿을 사용하는 Consul Template용 구성 파일을 작성합니다. 이 구성은 템플릿을 실행하고 결과 파일을 로컬 머신에 렌더링합니다.

/opt/consul/templates 아래에 consul_template.hcl이라는 파일을 다음 내용으로 만듭니다.

consul_template.hcl

# This denotes the start of the configuration section for Vault. All values
# contained in this section pertain to Vault.
vault {
  # This is the address of the Vault leader. The protocol (http(s)) portion
  # of the address is required.
  address      = "http://localhost:8200"

  # This value can also be specified via the environment variable VAULT_TOKEN.
  token        = "root"

  unwrap_token = false

  renew_token  = false
}

# This block defines the configuration for a template. Unlike other blocks,
# this block may be specified multiple times to configure multiple templates.
template {
  # This is the source file on disk to use as the input template. This is often
  # called the "consul-template template".
  source      = "/opt/consul/templates/gossip.key.tpl"

  # This is the destination path on disk where the source template will render.
  # If the parent directories do not exist, consul-template will attempt to
  # create them, unless create_dest_dirs is false.
  destination = "/opt/consul/gossip/gossip.key"

  # This is the permission to render the file. If this option is left
  # unspecified, consul-template will attempt to match the permissions of the
  # file that already exists at the destination path. If no file exists at that
  # path, the permissions are 0644.
  perms       = 0700

  # This is the optional command to run when the template is rendered. The
  # command will only run if the resulting template changes.
  command     = "/opt/rotate_key.sh"
}

회전 스크립트 작성 (Write a rotation script)

구성 파일의 마지막 줄은 Vault에서 새 키가 검색될 때마다 실행될 /opt/rotate_key.sh에 있는 스크립트를 참조합니다.

다음 예시를 사용하여 자신만의 회전 스크립트를 만들 수 있습니다.

/opt/rotate_key.sh

#!/usr/bin/env bash

# Setup Consul address info
export CONSUL_HTTP_ADDR="http://localhost:8500"

# The new key will be in a file generated by consul-template
# the script retrieves the key from the file
NEW_KEY=`cat /opt/consul/gossip/gossip.key | sed -e '/^$/d'`

# Install the key
consul keyring -install ${NEW_KEY}

# Set as primary
consul keyring -use ${NEW_KEY}

# Retrieve all keys used by Consul
KEYS=`curl -s ${CONSUL_HTTP_ADDR}/v1/operator/keyring`

ALL_KEYS=`echo ${KEYS} | jq -r '.[].Keys| to_entries[].key' | sort | uniq`

for i in `echo ${ALL_KEYS}`; do
  if [ $i != ${NEW_KEY} ] ; then
    consul keyring -remove $i
  fi
done

Consul Template 시작 (Start Consul Template)

-config 파라미터를 사용하여 구성 파일을 제공하며 Consul Template을 시작합니다.

$ consul-template -config "consul_template.hcl"

이 명령은 Consul Template을 장기 실행 데몬으로 시작하고 Vault의 변경 사항을 계속 수신합니다.

Consul 암호화 키 회전 (Rotate the Consul encryption key)

프로세스를 시작한 후 Vault에서 키 값을 업데이트할 때마다 Consul Template이 새 키가 Consul에도 설치되도록 합니다.

이제 vault kv put 명령을 사용하여 암호화 키를 변경할 수 있습니다.

$ vault kv put kv-v2/consul/config/encryption key=$(consul keygen) ttl=1s

스크립트는 새 키가 포함된 gossip.key 파일을 가져와 Consul 가십 암호화 키를 회전하는 데 사용합니다.

다음 줄을 출력해야 합니다.

==> Installing new gossip encryption key...
==> Changing primary gossip encryption key...
==> Removing gossip encryption key...

consul keyring 명령을 사용하여 Consul에서 키가 실제로 변경되었는지 테스트할 수 있습니다:

$ consul keyring -list

==> Gathering installed encryption keys...
WAN:
 ROfcQ/QLUgvBpIsWCCY9MtNqIyV7r3SS5eJmNZ6vUEA= [1/1]
dc1 (LAN):
 ROfcQ/QLUgvBpIsWCCY9MtNqIyV7r3SS5eJmNZ6vUEA= [1/1]

더 알아보기 (Learn more)