Debian Codegraph @

integration/hcvault/hcvault_aead.go

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // Copyright 2019 Google Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package hcvault
16
17 import (
18 "encoding/base64"
19 "errors"
20 "fmt"
21 "strings"
22
23 "github.com/hashicorp/vault/api"
24 "github.com/tink-crypto/tink-go/v2/tink"
25 )
26
27 // vaultAEAD represents a HashiCorp Vault service to a particular URI.
28 type vaultAEAD struct {
29 encKeyPath string
30 decKeyPath string
31 client *api.Logical
32 associatedDataName string
33 }
34
35 var _ tink.AEAD = (*vaultAEAD)(nil)
36
37 const (
38 encryptSegment = "encrypt"
39 decryptSegment = "decrypt"
40 defaultAssociatedDataName = "associated_data"
41 legacyAssociatedDataName = "context"
42 )
43
44 type aeadParams struct {
45 associatedDataName string
46 }
47
48 // AEADOption is an interface for defining options that are passed to [NewAEAD].
49 type AEADOption interface{ set(*aeadParams) error }
50
51 type option func(*aeadParams) error
52
53 func (o option) set(a *aeadParams) error { return o(a) }
54
55 // WithLegacyContextParamater lets the remote AEAD populate the "context" parameter
56 // in encrypt and decrypt requests instead of the "associated_data".
57 //
58 // Using this option makes the AEAD compatible with the instance returned by GetAEAD
59 // from the KMSClient returned by NewClient. For new keys, this option should not be used.
60 //
61 // ## Warning
62 //
63 // Vault only uses the "context" parameter for keys which have derivation enabled
64 // (with "derived=true") and ignores it otherwise. For such keys, the "context"
65 // parameter is required to be non-empty.
66 //
67 // Therefore:
68 //
69 // - for keys with "derived=false", you should only use empty associated data.
70 //
71 // - for keys with "derived=true", you should only use non-empty associated data.
72 //
73 // With Tink's "KMS envelope AEAD", always use a key with "derived=false".
74 //
75 // For reference, see https://developer.hashicorp.com/vault/api-docs/secret/transit.
76 func WithLegacyContextParamater() AEADOption {
77 return option(func(a *aeadParams) error {
78 a.associatedDataName = legacyAssociatedDataName
79 return nil
80 })
81 }
82
83 // NewAEAD returns a new remote AEAD primitive for a HashiCorp Vault service.
84 func NewAEAD(keyPath string, client *api.Logical, opts ...AEADOption) (tink.AEAD, error) {
85 params := &aeadParams{
86 associatedDataName: defaultAssociatedDataName,
87 }
88 // Process options, if any.
89 for _, opt := range opts {
90 if err := opt.set(params); err != nil {
91 return nil, fmt.Errorf("failed setting option: %v", err)
92 }
93 }
94 encKeyPath, decKeyPath, err := getEndpointPaths(keyPath)
95 if err != nil {
96 return nil, err
97 }
98 a := &vaultAEAD{
99 encKeyPath: encKeyPath,
100 decKeyPath: decKeyPath,
101 client: client,
102 associatedDataName: params.associatedDataName,
103 }
104 return a, nil
105 }
106
107 func extractCiphertext(secret *api.Secret) ([]byte, error) {
108 if secret == nil {
109 return nil, errors.New("secret is nil")
110 }
111 c, ok := secret.Data["ciphertext"]
112 if !ok {
113 return nil, errors.New("no ciphertext")
114 }
115 ciphertext, ok := c.(string)
116 if !ok {
117 return nil, errors.New("invalid ciphertext")
118 }
119 if len(ciphertext) == 0 {
120 return nil, errors.New("empty ciphertext")
121 }
122 return []byte(ciphertext), nil
123 }
124
125 // Encrypt encrypts the plaintext data using a key stored in HashiCorp Vault.
126 func (a *vaultAEAD) Encrypt(plaintext, associatedData []byte) ([]byte, error) {
127 // Create an encryption request map according to Vault REST API:
128 // https://www.vaultproject.io/api/secret/transit/index.html#encrypt-data.
129 req := map[string]any{
130 "plaintext": base64.StdEncoding.EncodeToString(plaintext),
131 a.associatedDataName: base64.StdEncoding.EncodeToString(associatedData),
132 }
133 secret, err := a.client.Write(a.encKeyPath, req)
134 if err != nil {
135 return nil, err
136 }
137 return extractCiphertext(secret)
138 }
139
140 func extractPlaintext(secret *api.Secret) ([]byte, error) {
141 // Note that when a valid ciphertext of the empty string is decrypted,
142 // secret.Data["plaintext"] may not be set. So we allow that.
143 if secret == nil {
144 return []byte{}, nil
145 }
146 p, ok := secret.Data["plaintext"]
147 if !ok {
148 return []byte{}, nil
149 }
150 plaintext64, ok := p.(string)
151 if !ok {
152 return nil, errors.New("invalid plaintext")
153 }
154 plaintext, err := base64.StdEncoding.DecodeString(plaintext64)
155 if err != nil {
156 return nil, err
157 }
158 return plaintext, nil
159 }
160
161 // Decrypt decrypts the ciphertext using a key stored in HashiCorp Vault.
162 func (a *vaultAEAD) Decrypt(ciphertext, associatedData []byte) ([]byte, error) {
163 // Create a decryption request map according to Vault REST API:
164 // https://www.vaultproject.io/api/secret/transit/index.html#decrypt-data.
165 req := map[string]any{
166 "ciphertext": string(ciphertext),
167 a.associatedDataName: base64.StdEncoding.EncodeToString(associatedData),
168 }
169 secret, err := a.client.Write(a.decKeyPath, req)
170 if err != nil {
171 return nil, err
172 }
173 return extractPlaintext(secret)
174 }
175
176 // getEndpointPaths transforms keyPath into the Vault transit encrypt and decrypt
177 // paths. The keyPath is expected to have the form "/{mount-path}/keys/{keyName}", which will
178 // be transformed to
179 // "{mount-path}/encrypt/{keyName}" and "{mount-path}/decrypt/{keyName}".
180 func getEndpointPaths(keyPath string) (encryptPath, decryptPath string, err error) {
181 parts := strings.Split(keyPath, "/")
182 length := len(parts)
183 if length < 4 || parts[0] != "" || parts[length-2] != "keys" {
184 return "", "", errors.New("malformed keyPath")
185 }
186
187 parts[length-2] = encryptSegment
188 encryptPath = strings.Join(parts[1:], "/")
189 parts[length-2] = decryptSegment
190 decryptPath = strings.Join(parts[1:], "/")
191 return encryptPath, decryptPath, nil
192 }