-
Notifications
You must be signed in to change notification settings - Fork 880
/
keysource.go
236 lines (206 loc) · 8.13 KB
/
keysource.go
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
/*
Package azkv contains an implementation of the github.com/getsops/sops/v3/keys.MasterKey
interface that encrypts and decrypts the data key using Azure Key Vault with the
Azure Key Vault Keys client module for Go.
*/
package azkv // import "github.com/getsops/sops/v3/azkv"
import (
"context"
"encoding/base64"
"fmt"
"regexp"
"strings"
"time"
"github.com/Azure/azure-sdk-for-go/sdk/azcore"
"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/security/keyvault/azkeys"
"github.com/sirupsen/logrus"
"github.com/getsops/sops/v3/logging"
)
const (
// KeyTypeIdentifier is the string used to identify an Azure Key Vault MasterKey.
KeyTypeIdentifier = "azure_kv"
)
var (
// log is the global logger for any Azure Key Vault MasterKey.
log *logrus.Logger
// azkvTTL is the duration after which a MasterKey requires rotation.
azkvTTL = time.Hour * 24 * 30 * 6
)
func init() {
log = logging.NewLogger("AZKV")
}
// MasterKey is an Azure Key Vault Key used to Encrypt and Decrypt SOPS'
// data key.
type MasterKey struct {
// VaultURL of the Azure Key Vault. For example:
// "https://myvault.vault.azure.net/".
VaultURL string
// Name of the Azure Key Vault key in the VaultURL.
Name string
// Version of the Azure Key Vault key. Can be empty.
Version string
// EncryptedKey contains the SOPS data key encrypted with the Azure Key
// Vault key.
EncryptedKey string
// CreationDate of the MasterKey, used to determine if the EncryptedKey
// needs rotation.
CreationDate time.Time
// tokenCredential contains the azcore.TokenCredential used by the Azure
// client. It can be injected by a (local) keyservice.KeyServiceServer
// using TokenCredential.ApplyToMasterKey.
// If nil, azidentity.NewDefaultAzureCredential is used.
tokenCredential azcore.TokenCredential
}
// NewMasterKey creates a new MasterKey from a URL, key name and version,
// setting the creation date to the current date.
func NewMasterKey(vaultURL string, keyName string, keyVersion string) *MasterKey {
return &MasterKey{
VaultURL: vaultURL,
Name: keyName,
Version: keyVersion,
CreationDate: time.Now().UTC(),
}
}
// NewMasterKeyFromURL takes an Azure Key Vault key URL, and returns a new
// MasterKey. The URL format is {vaultUrl}/keys/{keyName}/{keyVersion}.
func NewMasterKeyFromURL(url string) (*MasterKey, error) {
url = strings.TrimSpace(url)
re := regexp.MustCompile("^(https://[^/]+)/keys/([^/]+)/([^/]+)$")
parts := re.FindStringSubmatch(url)
if parts == nil || len(parts) < 3 {
return nil, fmt.Errorf("could not parse %q into a valid Azure Key Vault MasterKey", url)
}
return NewMasterKey(parts[1], parts[2], parts[3]), nil
}
// MasterKeysFromURLs takes a comma separated list of Azure Key Vault URLs,
// and returns a slice of new MasterKeys.
func MasterKeysFromURLs(urls string) ([]*MasterKey, error) {
var keys []*MasterKey
if urls == "" {
return keys, nil
}
for _, s := range strings.Split(urls, ",") {
k, err := NewMasterKeyFromURL(s)
if err != nil {
return nil, err
}
keys = append(keys, k)
}
return keys, nil
}
// TokenCredential is an azcore.TokenCredential used for authenticating towards Azure Key
// Vault.
type TokenCredential struct {
token azcore.TokenCredential
}
// NewTokenCredential creates a new TokenCredential with the provided azcore.TokenCredential.
func NewTokenCredential(token azcore.TokenCredential) *TokenCredential {
return &TokenCredential{token: token}
}
// ApplyToMasterKey configures the TokenCredential on the provided key.
func (t TokenCredential) ApplyToMasterKey(key *MasterKey) {
key.tokenCredential = t.token
}
// Encrypt takes a SOPS data key, encrypts it with Azure Key Vault, and stores
// the result in the EncryptedKey field.
func (key *MasterKey) Encrypt(dataKey []byte) error {
token, err := key.getTokenCredential()
if err != nil {
log.WithFields(logrus.Fields{"key": key.Name, "version": key.Version}).Info("Encryption failed")
return fmt.Errorf("failed to get Azure token credential to encrypt data: %w", err)
}
c, err := azkeys.NewClient(key.VaultURL, token, nil)
if err != nil {
log.WithFields(logrus.Fields{"key": key.Name, "version": key.Version}).Info("Encryption failed")
return fmt.Errorf("failed to construct Azure Key Vault client to encrypt data: %w", err)
}
resp, err := c.Encrypt(context.Background(), key.Name, key.Version, azkeys.KeyOperationParameters{
Algorithm: to.Ptr(azkeys.EncryptionAlgorithmRSAOAEP256),
Value: dataKey,
}, nil)
if err != nil {
log.WithFields(logrus.Fields{"key": key.Name, "version": key.Version}).Info("Encryption failed")
return fmt.Errorf("failed to encrypt sops data key with Azure Key Vault key '%s': %w", key.ToString(), err)
}
encodedEncryptedKey := base64.RawURLEncoding.EncodeToString(resp.KeyOperationResult.Result)
key.SetEncryptedDataKey([]byte(encodedEncryptedKey))
log.WithFields(logrus.Fields{"key": key.Name, "version": key.Version}).Info("Encryption succeeded")
return nil
}
// EncryptedDataKey returns the encrypted data key this master key holds.
func (key *MasterKey) EncryptedDataKey() []byte {
return []byte(key.EncryptedKey)
}
// SetEncryptedDataKey sets the encrypted data key for this master key.
func (key *MasterKey) SetEncryptedDataKey(enc []byte) {
key.EncryptedKey = string(enc)
}
// EncryptIfNeeded encrypts the provided SOPS data key, if it has not been
// encrypted yet.
func (key *MasterKey) EncryptIfNeeded(dataKey []byte) error {
if key.EncryptedKey == "" {
return key.Encrypt(dataKey)
}
return nil
}
// Decrypt decrypts the EncryptedKey field with Azure Key Vault and returns
// the result.
func (key *MasterKey) Decrypt() ([]byte, error) {
token, err := key.getTokenCredential()
if err != nil {
log.WithFields(logrus.Fields{"key": key.Name, "version": key.Version}).Info("Decryption failed")
return nil, fmt.Errorf("failed to get Azure token credential to decrypt: %w", err)
}
rawEncryptedKey, err := base64.RawURLEncoding.DecodeString(key.EncryptedKey)
if err != nil {
log.WithFields(logrus.Fields{"key": key.Name, "version": key.Version}).Info("Decryption failed")
return nil, fmt.Errorf("failed to base64 decode Azure Key Vault encrypted key: %w", err)
}
c, err := azkeys.NewClient(key.VaultURL, token, nil)
if err != nil {
log.WithFields(logrus.Fields{"key": key.Name, "version": key.Version}).Info("Decryption failed")
return nil, fmt.Errorf("failed to construct Azure Key Vault client to decrypt data: %w", err)
}
resp, err := c.Decrypt(context.Background(), key.Name, key.Version, azkeys.KeyOperationParameters{
Algorithm: to.Ptr(azkeys.EncryptionAlgorithmRSAOAEP256),
Value: rawEncryptedKey,
}, nil)
if err != nil {
log.WithFields(logrus.Fields{"key": key.Name, "version": key.Version}).Info("Decryption failed")
return nil, fmt.Errorf("failed to decrypt sops data key with Azure Key Vault key '%s': %w", key.ToString(), err)
}
log.WithFields(logrus.Fields{"key": key.Name, "version": key.Version}).Info("Decryption succeeded")
return resp.KeyOperationResult.Result, nil
}
// NeedsRotation returns whether the data key needs to be rotated or not.
func (key *MasterKey) NeedsRotation() bool {
return time.Since(key.CreationDate) > (azkvTTL)
}
// ToString converts the key to a string representation.
func (key *MasterKey) ToString() string {
return fmt.Sprintf("%s/keys/%s/%s", key.VaultURL, key.Name, key.Version)
}
// ToMap converts the MasterKey to a map for serialization purposes.
func (key MasterKey) ToMap() map[string]interface{} {
out := make(map[string]interface{})
out["vaultUrl"] = key.VaultURL
out["key"] = key.Name
out["version"] = key.Version
out["created_at"] = key.CreationDate.UTC().Format(time.RFC3339)
out["enc"] = key.EncryptedKey
return out
}
// TypeToIdentifier returns the string identifier for the MasterKey type.
func (key *MasterKey) TypeToIdentifier() string {
return KeyTypeIdentifier
}
// getTokenCredential returns the tokenCredential of the MasterKey, or
// azidentity.NewDefaultAzureCredential.
func (key *MasterKey) getTokenCredential() (azcore.TokenCredential, error) {
if key.tokenCredential == nil {
return azidentity.NewDefaultAzureCredential(nil)
}
return key.tokenCredential, nil
}