-
Notifications
You must be signed in to change notification settings - Fork 1
/
key.go
227 lines (203 loc) · 5.59 KB
/
key.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
package main
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/aws/external"
"github.com/aws/aws-sdk-go-v2/service/kms"
"github.com/aws/aws-sdk-go-v2/service/s3/s3manager"
"github.com/hashicorp/go-uuid"
"github.com/jcmturner/awsarn"
"io/ioutil"
"os"
"strconv"
"strings"
"time"
)
const (
passPhraseByteSize = 1024
)
type key struct {
EncryptionContext encryptionContext `json:"EncryptionContext"`
CMKARN string `json:"CMKARN"`
DataKey dataKey `json:"DataKey"`
}
type encryptionContext struct {
FQDN string `json:"FQDN"`
Production bool `json:"Production"`
UUID string `json:"UUID"`
}
type dataKey struct {
Plain string `json:"Plain,omitempty"`
Encrypted string `json:"Encrypted"`
Created time.Time `json:"Created"`
}
func newEncryptionContext(fqdn, uuid string, production bool) encryptionContext {
return encryptionContext{
FQDN: fqdn,
Production: production,
UUID: uuid,
}
}
func (e encryptionContext) toMap() map[string]string {
return map[string]string{
"fqdn": e.FQDN,
"production": strconv.FormatBool(e.Production),
"uuid": e.UUID,
}
}
func newDataKey(cmkARNStr, fqdn string, production bool) (key, error) {
cmkARN, err := awsarn.Parse(cmkARNStr, nil)
if err != nil {
return key{}, fmt.Errorf("invalid CMK ARN: %v", err)
}
cfg, err := external.LoadDefaultAWSConfig()
if err != nil {
return key{}, fmt.Errorf("unable to load AWS SDK config: %v", err)
}
cfg.Region = cmkARN.Region
kmsSrv := kms.New(cfg)
devUUID, err := uuid.GenerateUUID()
if err != nil {
return key{}, err
}
ec := newEncryptionContext(fqdn, devUUID, production)
bs := int64(passPhraseByteSize)
input := kms.GenerateDataKeyInput{
EncryptionContext: ec.toMap(),
KeyId: &cmkARNStr,
NumberOfBytes: &bs,
}
request := kmsSrv.GenerateDataKeyRequest(&input)
output, err := request.Send()
if err != nil {
return key{}, err
}
k := key{
EncryptionContext: ec,
CMKARN: cmkARNStr,
DataKey: dataKey{
Plain: base64.StdEncoding.EncodeToString(output.Plaintext),
Encrypted: base64.StdEncoding.EncodeToString(output.CiphertextBlob),
Created: time.Now().UTC(),
},
}
return k, nil
}
func (k key) archive(bucket string) error {
//Blank the plaintext form of the key before storing
k.DataKey.Plain = ""
// The config the S3 Uploader will use
cfg, err := external.LoadDefaultAWSConfig()
// Create an uploader with the config and default options
uploader := s3manager.NewUploader(cfg)
// Marshal the key to json
keyBytes, err := json.MarshalIndent(k, "", " ")
if err != nil {
return fmt.Errorf("failed to marshal key: %v", err)
}
// Upload the file to S3.
_, err = uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(bucket),
Key: aws.String(fmt.Sprintf("%s/%s.json", k.EncryptionContext.FQDN, k.EncryptionContext.UUID)),
Body: bytes.NewBuffer(keyBytes),
})
if err != nil {
return fmt.Errorf("failed to upload file, %v", err)
}
return nil
}
func (k key) store(path string) error {
k.DataKey.Plain = ""
err := os.MkdirAll(path+k.EncryptionContext.FQDN, 0600)
if err != nil {
return fmt.Errorf("could not create local key store directory: " + err.Error())
}
kjson, err := json.MarshalIndent(k, "", " ")
if err != nil {
return fmt.Errorf("could not marshal key to JSON: " + err.Error())
}
kf, err := os.OpenFile(path+k.EncryptionContext.FQDN+"/"+k.EncryptionContext.UUID+".json", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0666)
if err != nil {
return fmt.Errorf("could not open key file: " + err.Error())
}
defer kf.Close()
_, err = kf.Write(kjson)
if err != nil {
return fmt.Errorf("could not write to local key store: %v", err)
}
return nil
}
func (k *key) decrypt() error {
cmkARN, err := awsarn.Parse(k.CMKARN, nil)
if err != nil {
return fmt.Errorf("invalid CMK ARN: %v", err)
}
cfg, err := external.LoadDefaultAWSConfig()
if err != nil {
return fmt.Errorf("unable to load AWS SDK config: %v", err)
}
cfg.Region = cmkARN.Region
kmsSrv := kms.New(cfg)
b, err := base64.StdEncoding.DecodeString(k.DataKey.Encrypted)
if err != nil {
return fmt.Errorf("cannot base64 decode encrypted key: %v", err)
}
input := kms.DecryptInput{
CiphertextBlob: b,
EncryptionContext: k.EncryptionContext.toMap(),
}
request := kmsSrv.DecryptRequest(&input)
output, err := request.Send()
if err != nil {
return err
}
k.DataKey.Plain = base64.StdEncoding.EncodeToString(output.Plaintext)
return nil
}
func (k *key) Load(path string) error {
b, err := ioutil.ReadFile(path)
if err != nil {
return fmt.Errorf("error reading device's key from local store (%s): %v", path, err)
}
err = json.Unmarshal(b, k)
if err != nil {
return fmt.Errorf("error parsing device's key from local store (%s): %v", path, err)
}
return nil
}
func keys() ([]key, error) {
var ks []key
// Get host's FQDN
fqdn, err := os.Hostname()
if err != nil {
return ks, fmt.Errorf("could not get host's FQDN: " + err.Error())
}
sp := dirRoot + keyStore + fqdn + "/"
kl, err := ioutil.ReadDir(sp)
if err != nil {
return ks, fmt.Errorf("could not read local key store (%s): %v", sp, err)
}
for _, kp := range kl {
if kp.IsDir() {
continue
}
if !strings.HasSuffix(kp.Name(), ".json") {
continue
}
_, err := uuid.ParseUUID(strings.SplitN(kp.Name(), ".json", 2)[0])
if err != nil {
continue
}
var k key
err = k.Load(sp + kp.Name())
if err != nil {
fmt.Fprintf(os.Stderr, "error loading key %s: %v", sp+kp.Name(), err)
continue
}
ks = append(ks, k)
}
return ks, nil
}