Build and deploy KMS Agent across environments to retrieve secrets
This topic describes how to build the KMS Agent executable and deploy KMS Agent.
KMS Agent integration steps
To ensure standardized deployment and secure calls of KMS Agent, follow the workflow below.
Step 1: Build the KMS Agent executable
We recommend that you build the executable in a build environment and upload it to the deployment environment.
Install Go. For more information, see Install Go.
Download the source code and dependencies.
Visit Git to download and install Git.
Run the following commands to download the source code and dependencies.
git clone https://github.com/aliyun/alibabacloud-kms-agent go mod download
In the project root directory, run the
go build .command to compile the executable. The default file name is alibabacloud-kms-agent, and the file is saved in the project root directory by default.If the build environment and deployment environment are the same, run the
go build .command. If they differ, use the following commands for cross-platform compilation to generate a 64-bit executable.Build environment
Deployment target: macOS
Deployment target: Linux
Deployment target: Windows
macOS
go build .CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build .CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build .Linux
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build .go build .CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build .Windows
SET CGO_ENABLED=0 SET GOOS=darwin SET GOARCH=amd64 go build .SET CGO_ENABLED=0 SET GOOS=linux SET GOARCH=amd64 go build .go build .In the project root directory, check whether the alibabacloud-kms-agent executable file exists.
Step 2: Create access credentials
For deployments on Alibaba Cloud ECS, we recommend an ECS instance RAM role. For Kubernetes Sidecar containers, we recommend RRSA, For other environments, it is recommended to use AccessKey.
AccessKey
This example uses the AccessKey of a RAM user.
An Alibaba Cloud account has Administrator permissions for all resources and the permissions cannot be modified. Leaking the AccessKey endangers resource security. Therefore, we strongly recommend that you do not create an AccessKey for the root account. Create a RAM user dedicated to API access, create an AccessKey for the RAM user, and complete least-privilege authorization. For more information, see Create an AccessKey.
Log on to the RAM console. On the Users page, click the name of the target RAM user.
On the Secret Management tab, in the AccessKey section, click Create AccessKey.
Grant the RAM user permission to obtain KMS credentials.
When KMS Agent caches credentials, it needs to obtain credential values from KMS. Therefore, KMS Agent must have permission to obtain credential values. Because credential values are encrypted, KMS Agent also must have permission to decrypt the key.
Method 1: Configure an identity-based policy.
For more information, see Create a custom policy and Manage RAM user permissions.
Method 2: Configure a resource-based policy.
KMS supports resource-based policies, which set access permissions on individual keys and secrets to control which Alibaba Cloud accounts, RAM users, and RAM roles can manage or use KMS keys and secrets. For more information, see Key policies and Secret policies.
ECS instance RAM role
An ECS instance RAM role allows you to obtain a temporary access credential (STS token) from within an ECS instance to call KMS API operations, without needing to configure an AccessKey pair.
For more information, see Instance RAM roles.
Log on to the RAM console and create a RAM role for a trusted Alibaba Cloud service.
Trusted Entity Type: Select Elastic Compute Service.
Trusted entity: Select Elastic Compute Service (ECS).
Grant the RAM role permission to obtain KMS credentials.
When KMS Agent caches credentials, it needs to obtain credential values from KMS. Therefore, KMS Agent must have permission to obtain credential values. Because credential values are encrypted, KMS Agent also must have permission to decrypt the key.
Method 1: Configure an identity-based policy.
For more information, see Create a custom policy and Manage permissions for a RAM role.
Method 2: Configure a resource-based policy.
KMS supports resource-based policies, which set access permissions on individual keys and secrets to control which Alibaba Cloud accounts, RAM users, and RAM roles can manage or use KMS keys and secrets. For more information, see Key policies and Secret policies.
Log on to the ECS console and attach the RAM role to an ECS instance.
RRSA
Container Service for Kubernetes (ACK) supports RAM Roles for Service Accounts (RRSA) to implement pod-level OpenAPI permission isolation within a cluster, thereby achieving fine-grained isolation of cloud resource access permissions and reducing security risks. For how to configure RRSA, see Use RRSA for pod-level access control.
For how to authorize the RAM role assumed by KMS Agent, refer to the following information.
When KMS Agent caches credentials, it needs to obtain credential values from KMS. Therefore, KMS Agent must have permission to obtain credential values. Because credential values are encrypted, KMS Agent also must have permission to decrypt the key.
Method 1: Configure an identity-based policy.
For more information, see Create a custom policy and Manage permissions for a RAM role.
Method 2: Configure a resource-based policy.
KMS supports resource-based policies, which set access permissions on individual keys and secrets to control which Alibaba Cloud accounts, RAM users, and RAM roles can manage or use KMS keys and secrets. For more information, see Key policies and Secret policies.
Step 3: Deploy KMS Agent
Local deployment
Deploy KMS Agent locally by using the executable and configuration file. This method is suitable for small environments or test scenarios. This example uses the AccessKey of a RAM user.
Set environment variables to configure the authentication information required for running KMS Agent.
export ALIBABA_CLOUD_ACCESS_KEY_ID=*** export ALIBABA_CLOUD_ACCESS_KEY_SECRET=*** export KMS_TOKEN='file:///var/run/kmstoken'ALIBABA_CLOUD_ACCESS_KEY_ID: the AccessKey ID of the RAM user.
ALIBABA_CLOUD_ACCESS_KEY_SECRET: the AccessKey Secret of the RAM user.
KMS_TOKEN: the path of the SSRF Token file generated when the agent starts.
Generate an SSRF token and save it to the specified file.
# Generate an SSRF token and save it to the file /var/run/kmstoken ./alibabacloud-kms-agent token /var/run/kmstokenConfigure the running parameters in the KMS Agent configuration file (
config.toml).[Server] HttpPort = 2025 [Kms] Region = "cn-hangzhou" [Cache] CacheType = "InMemory" CacheSize = 1000 TtlSeconds = 300 [Log] LogLevel = "Debug" LogPath = "./logs/" MaxSize = 100 MaxBackups = 2Start the KMS Agent service.
./alibabacloud-kms-agent agent ./config.toml
Deploy KMS Agent on an Alibaba Cloud ECS Linux instance
Deploy KMS Agent on a Linux server and use systemd to start and manage the agent. This ensures that KMS Agent automatically runs when the system starts and provides process monitoring, log management, and other features. This topic uses deployment on an Alibaba Cloud ECS instance with an ECS instance RAM role as an example.
Set environment variables to configure the authentication information required for running KMS Agent.
export ALIBABA_CLOUD_ECS_METADATA=*** export KMS_TOKEN='file:///var/run/kmstoken'ALIBABA_CLOUD_ECS_METADATA: the name of the ECS instance RAM role.
KMS_TOKEN: the path of the SSRF Token file generated when the agent starts.
Install and start the agent.
Go to the installation directory.
cd alibabacloud-kms-agent/deploy/linuxUpload the following files to the installation directory.
alibabacloud-kms-agent: the KMS Agent executable generated in Step 1.
config.toml: the KMS Agent configuration file. Example:
alibabacloud-kms-agent.service: the systemd service file used to manage KMS Agent.
Run the
install.shcommand as the root user.sudo bash -x ./install.shWhen you run the
install.shscript, an SSRF Token file is automatically generated. The file is used for authentication between business applications and KMS Agent to prevent unauthorized server-side request forgery (SSRF) attacks.The agent process is managed by the systemd service (
alibabacloud-kms-agent.service) to provide standardized service management features such as auto-start on boot and process monitoring.
In
alibabacloud-kms-agent.service, modify theUserfield so that the user that runs the agent is the same as the user of the application that accesses the agent.Otherwise, the application does not have permission to read the SSRF token and cannot access KMS Agent.
Sidecar container deployment
Use docker-compose to orchestrate the agent sidecar container and the application container. This example uses the AccessKey of a RAM user.
Create container Dockerfile files.
Create two Dockerfile files, which are used to build the agent sidecar container and the business application container. For file content, see Dockerfile.agent and Dockerfile.app.
Create a container orchestration file. For file content, see docker-compose.yaml.
The authentication information required for running KMS Agent is configured as environment variables in the file, as follows.
environment: - ALIBABA_CLOUD_ACCESS_KEY_ID=<ak> - ALIBABA_CLOUD_ACCESS_KEY_SECRET=<sk> - KMS_TOKEN='file:///var/run/kmstoken'ALIBABA_CLOUD_ACCESS_KEY_ID: the AccessKey ID of the RAM user.
ALIBABA_CLOUD_ACCESS_KEY_SECRET: the AccessKey Secret of the RAM user.
KMS_TOKEN: the path of the SSRF Token file generated when the agent starts.
Configure the running parameters of KMS Agent in
config.toml.[Server] HttpPort = 2025 [Kms] Region = "cn-hangzhou" [Cache] CacheType = "InMemory" CacheSize = 1000 TtlSeconds = 300 [Log] LogLevel = "Debug" LogPath = "./logs/" MaxSize = 100 MaxBackups = 2Build and start the containers.
Place the
alibabacloud-kms-agentexecutable,config.tomlconfiguration file,Dockerfile.agent, andDockerfile.appfiles in the same directory as thedocker-compose.ymlcontainer orchestration file.deploy/docker-compose/ ├── alibabacloud-kms-agent ├── config.toml ├── Dockerfile.agent ├── Dockerfile.app └── docker-compose.ymlRun the following command.
docker-compose up --build
Log on to the business application container and access the agent from within the container.
Deploy KMS Agent on Alibaba Cloud ACK
Deploy KMS Agent as a sidecar container together with the application container to Alibaba Cloud ACK. This example uses RRSA.
Configure the running parameters of KMS Agent in config.toml.
[Server] HttpPort = 2025 [Kms] Region = "cn-hangzhou" [Cache] CacheType = "InMemory" CacheSize = 1000 TtlSeconds = 300 [Log] LogLevel = "Debug" LogPath = "./logs/" MaxSize = 100 MaxBackups = 2Build the agent sidecar container image.
Enter the
deploy/ack/agentfolder, create a Dockerfile, and build the agent container image. For file content, see agent_Dockerfile.cd alibabacloud-kms-agent/deploy/ack/agent # In this example, the image is uploaded to an Alibaba Cloud image registry. docker build -t registry.cn-hangzhou.aliyuncs.com/<namespace>/<repository> . docker push registry.cn-hangzhou.aliyuncs.com/<namespace>/<repository>:kmsagent-1.0Build the application container image.
Enter the
deploy/ack/appfolder, create a Dockerfile, and build the application container image. For file content, see app_Dockerfile.cd alibabacloud-kms-agent/deploy/ack/app docker build -t registry.cn-hangzhou.aliyuncs.com/<namespace>/<repository> . docker push registry.cn-hangzhou.aliyuncs.com/<namespace>/<repository>:app-1.0Write a Kubernetes YAML resource file to deploy the application and agent containers to Alibaba Cloud ACK. For file content, see deployment-demo.yaml.
The authentication information required for running KMS Agent is configured as environment variables in the file, as follows.
env: - name: KMS_TOKEN value: 'file:///var/run/kmstoken' - name: ALIBABA_CLOUD_ROLE_ARN value: acs:ram::<account>:role/<rolename> - name: ALIBABA_CLOUD_OIDC_PROVIDER_ARN value: acs:ram::<account>:oidc-provider/<ack cluster id> - name: ALIBABA_CLOUD_OIDC_TOKEN_FILE value: /var/run/secrets/ack.alibabacloud.com/rrsa-tokens/tokenKMS_TOKEN: the path of the SSRF Token file generated when the agent starts.
ALIBABA_CLOUD_ROLE_ARN: the ARN of the RAM role.
ALIBABA_CLOUD_OIDC_PROVIDER_ARN: the ARN of the OIDC identity provider, which is the ACK cluster ARN.
ALIBABA_CLOUD_OIDC_TOKEN_FILE: the path of the file that contains the OIDC token.
Run the container application.
Place the files in the project directory according to the following hierarchy.
deploy/ack/ ├── alibabacloud-kms-agent ├── config.toml ├── Dockerfile.agent ├── Dockerfile.app └── deployment-demo.yamlRun your container application. For more information, see Create a stateless Deployment.
Step 4: Retrieve secrets
By default, KMS Agent retrieves the ACSCurrent version of a secret. To retrieve another version, you can set versionStage or versionId.
KMS Agent listens only on 127.0.0.1. Only applications or processes on the same machine can communicate with the agent. External network devices cannot connect. Only localhost or 127.0.0.1 is supported. You cannot change the access address to the local IP of the application. The following examples use localhost.
Use curl
When you use the sample code, replace <SecretId> with your actual secret name.
# Read the token from the token file
curl -v -H "X-KMS-Token:$(</var/run/kmstoken)" 'http://localhost:2025/secretsmanager/get?secretId=<SecretId>'
# Pass the token value directly
curl -v -H "X-KMS-Token:<token>" 'http://localhost:2025/secretsmanager/get?secretId=<SecretId>'You can specify versionStage or versionId to retrieve a specific credential value. The following example shows how to retrieve a credential value with a specific versionId. Replace 0a7513ee719da740807b15b77500**** with your actual credential version.
# Read the token from the token file
curl -v -H "X-KMS-Token:$(</var/run/kmstoken)" 'http://localhost:2025/secretsmanager/get?secretId=<SecretId>&versionId=0a7513ee719da740807b15b77500****'
# Pass the token value directly
curl -v -H "X-KMS-Token:<token>" 'http://localhost:2025/secretsmanager/get?secretId=<SecretId>&versionId=0a7513ee719da740807b15b77500****'Go code sample
When you use the sample code, replace agent-test with your actual secret name.
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
func main() {
// To retrieve a specific version, append &versionId=<version-id> to the URL.
url := fmt.Sprintf("http://localhost:2025/secretsmanager/get?secretId=%s", "agent-test")
token, err := ioutil.ReadFile("/var/run/kmstoken")
if err != nil {
fmt.Printf("error reading token file: %v\n", err)
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
fmt.Printf("error creating request: %v\n", err)
}
req.Header.Add("X-KMS-Token", string(token))
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Printf("error sending request: %v\n", err)
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
fmt.Printf("status code %d - %s\n", resp.StatusCode, string(body))
}