-
Notifications
You must be signed in to change notification settings - Fork 59
/
kmsgcp.go
230 lines (185 loc) · 4.6 KB
/
kmsgcp.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
package vault
import (
"context"
"crypto/rand"
"encoding/base64"
"fmt"
"io"
"sync"
"encoding/json"
"golang.org/x/crypto/argon2"
"golang.org/x/crypto/nacl/secretbox"
"golang.org/x/oauth2/google"
"google.golang.org/api/cloudkms/v1"
)
///
/// Boxer implementation.
///
type KMSGCPBoxer struct {
keyPath string
}
func NewKMSGCPBoxer(keyPath string) *KMSGCPBoxer {
return &KMSGCPBoxer{
keyPath: keyPath,
}
}
func (b *KMSGCPBoxer) Seal(in []byte) (string, error) {
mgr, err := NewKMSGCPManager(b.keyPath)
if err != nil {
return "", fmt.Errorf("new kms gcp manager, %s", err)
}
encrypted, err := mgr.Encrypt(in)
if err != nil {
return "", fmt.Errorf("kms encryption, %s", err)
}
return base64.RawStdEncoding.EncodeToString(encrypted), nil
}
func (b *KMSGCPBoxer) Open(in string) ([]byte, error) {
mgr, err := NewKMSGCPManager(b.keyPath)
if err != nil {
return []byte{}, fmt.Errorf("new kms gcp manager, %s", err)
}
data, err := base64.RawStdEncoding.DecodeString(in)
if err != nil {
return []byte{}, fmt.Errorf("base 64 decode, %s", err)
}
out, err := mgr.Decrypt(data)
if err != nil {
return []byte{}, fmt.Errorf("base 64 decode, %s", err)
}
return out, nil
}
func (b *KMSGCPBoxer) WrapType() string {
return "kms-gcp"
}
const (
saltLength = 16
nonceLength = 24
keyLength = 32
shamirSecretLength = 32
)
func deriveKey(passphrase string, salt []byte) [keyLength]byte {
secretKeyBytes := argon2.IDKey([]byte(passphrase), salt, 4, 64*1024, 4, 32)
var secretKey [keyLength]byte
copy(secretKey[:], secretKeyBytes)
return secretKey
}
///
/// Manager implementation
///
func NewKMSGCPManager(keyPath string) (*KMSGCPManager, error) {
ctx := context.Background()
client, err := google.DefaultClient(ctx, cloudkms.CloudPlatformScope)
if err != nil {
return nil, err
}
kmsService, err := cloudkms.New(client)
if err != nil {
return nil, err
}
manager := &KMSGCPManager{
service: kmsService,
keyPath: keyPath,
}
return manager, nil
}
type KMSGCPManager struct {
dekCache map[string][32]byte
dekCacheLock sync.Mutex
localDEK [32]byte
localWrappedDEK string
service *cloudkms.Service
keyPath string
}
func (k *KMSGCPManager) setupEncryption() error {
if k.dekCache != nil {
return nil
}
_, err := rand.Read(k.localDEK[:])
if err != nil {
return err
}
req := &cloudkms.EncryptRequest{
Plaintext: base64.StdEncoding.EncodeToString(k.localDEK[:]),
}
resp, err := k.service.Projects.Locations.KeyRings.CryptoKeys.Encrypt(k.keyPath, req).Do()
if err != nil {
return err
}
k.localWrappedDEK = resp.Ciphertext
k.dekCache = map[string][32]byte{resp.Ciphertext: k.localDEK}
return nil
}
func (k *KMSGCPManager) fetchPlainDEK(wrappedDEK string) (out [32]byte, err error) {
k.dekCacheLock.Lock()
defer k.dekCacheLock.Unlock()
if cachedKey, found := k.dekCache[wrappedDEK]; found {
return cachedKey, nil
}
req := &cloudkms.DecryptRequest{
Ciphertext: wrappedDEK,
}
resp, err := k.service.Projects.Locations.KeyRings.CryptoKeys.Decrypt(k.keyPath, req).Do()
if err != nil {
return
}
plainKey, err := base64.StdEncoding.DecodeString(resp.Plaintext)
if err != nil {
return
}
copy(out[:], plainKey)
if k.dekCache == nil {
k.dekCache = map[string][32]byte{}
}
if k.localWrappedDEK == "" {
k.localWrappedDEK = wrappedDEK
}
k.dekCache[wrappedDEK] = out
return
}
type BlobV1 struct {
Version int `bson:"version"`
WrappedDEK string `bson:"wrapped_dek"`
Nonce [24]byte `bson:"nonce"`
EncryptedData []byte `bson:"data"`
}
func (k *KMSGCPManager) Encrypt(in []byte) ([]byte, error) {
if err := k.setupEncryption(); err != nil {
return nil, err
}
var nonce [24]byte
if _, err := io.ReadFull(rand.Reader, nonce[:]); err != nil {
return nil, err
}
var sealedMsg []byte
sealedMsg = secretbox.Seal(sealedMsg, in, &nonce, &k.localDEK)
blob := &BlobV1{
Version: 1,
WrappedDEK: k.localWrappedDEK,
Nonce: nonce,
EncryptedData: sealedMsg,
}
cereal, err := json.Marshal(blob)
if err != nil {
return nil, err
}
return cereal, nil
}
func (k *KMSGCPManager) Decrypt(in []byte) ([]byte, error) {
var blob BlobV1
err := json.Unmarshal(in, &blob)
if err != nil {
return nil, err
}
// No need to check `blob.Version` == 1, we did it already with
// the `magicFound` comparison.
plainDEK, err := k.fetchPlainDEK(blob.WrappedDEK)
if err != nil {
return nil, err
}
plainData, ok := secretbox.Open(nil, blob.EncryptedData, &blob.Nonce, &plainDEK)
if !ok {
return nil, fmt.Errorf("failed decrypting data, that's all we know")
}
return plainData, nil
}