forked from Versent/unicreds
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ds.go
348 lines (269 loc) · 7.03 KB
/
ds.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
package unicreds
import (
"encoding/base64"
"errors"
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbiface"
)
const (
// Table the name of the dynamodb table
Table = "credential-store"
// KmsKey default KMS key alias name
KmsKey = "alias/credstash"
tableCreateTimeout = 30 * time.Second
)
var (
dynamoSvc dynamodbiface.DynamoDBAPI
// ErrSecretNotFound returned when unable to find the specified secret in dynamodb
ErrSecretNotFound = errors.New("Secret Not Found")
// ErrHmacValidationFailed returned when the hmac signature validation fails
ErrHmacValidationFailed = errors.New("Secret HMAC validation failed")
// ErrTimeout timeout occured waiting for dynamodb table to create
ErrTimeout = errors.New("Timed out waiting for dynamodb table to become active")
)
func init() {
dynamoSvc = dynamodb.New(session.New(), aws.NewConfig())
}
// SetDynamoDBConfig override the default aws configuration
func SetDynamoDBConfig(config *aws.Config) {
dynamoSvc = dynamodb.New(session.New(), config)
}
// Credential managed credential information
type Credential struct {
Name string `ds:"name"`
Version string `ds:"version"`
Key string `ds:"key"`
Contents string `ds:"contents"`
Hmac string `ds:"hmac"`
}
// DecryptedCredential managed credential information
type DecryptedCredential struct {
*Credential
Secret string
}
// Setup create the table which stores credentials
func Setup() (err error) {
res, err := dynamoSvc.CreateTable(&dynamodb.CreateTableInput{
AttributeDefinitions: []*dynamodb.AttributeDefinition{
{
AttributeName: aws.String("name"),
AttributeType: aws.String("S"),
},
{
AttributeName: aws.String("version"),
AttributeType: aws.String("S"),
},
},
KeySchema: []*dynamodb.KeySchemaElement{
{
AttributeName: aws.String("name"),
KeyType: aws.String(dynamodb.KeyTypeHash),
},
{
AttributeName: aws.String("version"),
KeyType: aws.String(dynamodb.KeyTypeRange),
},
},
ProvisionedThroughput: &dynamodb.ProvisionedThroughput{
ReadCapacityUnits: aws.Int64(1),
WriteCapacityUnits: aws.Int64(1),
},
TableName: aws.String(Table),
})
if err != nil {
return
}
fmt.Printf("res = %+v\n", res)
err = waitForTable()
return
}
// GetSecret retrieve the secret from dynamodb using the name
func GetSecret(name string) (*DecryptedCredential, error) {
res, err := dynamoSvc.Query(&dynamodb.QueryInput{
TableName: aws.String(Table),
ExpressionAttributeNames: map[string]*string{
"#N": aws.String("name"),
},
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":name": &dynamodb.AttributeValue{
S: aws.String(name),
},
},
KeyConditionExpression: aws.String("#N = :name"),
Limit: aws.Int64(1),
ConsistentRead: aws.Bool(true),
ScanIndexForward: aws.Bool(false), // descending order
})
if err != nil {
return nil, err
}
cred := new(Credential)
if len(res.Items) == 0 {
return nil, ErrSecretNotFound
}
err = Decode(res.Items[0], cred)
if err != nil {
return nil, err
}
return decryptCredential(cred)
}
// ListSecrets return a list of secrets
func ListSecrets() ([]*DecryptedCredential, error) {
res, err := dynamoSvc.Scan(&dynamodb.ScanInput{
TableName: aws.String(Table),
AttributesToGet: []*string{
aws.String("name"),
aws.String("version"),
aws.String("key"),
aws.String("contents"),
aws.String("hmac"),
},
ConsistentRead: aws.Bool(true),
})
if err != nil {
return nil, err
}
var results []*DecryptedCredential
for _, item := range res.Items {
cred := new(Credential)
err = Decode(item, cred)
if err != nil {
return nil, err
}
dcred, err := decryptCredential(cred)
if err != nil {
return nil, err
}
results = append(results, dcred)
}
return results, nil
}
// PutSecret retrieve the secret from dynamodb
func PutSecret(name, secret, version string) error {
if version == "" {
version = "1"
}
dk, err := GenerateDataKey(KmsKey, 64)
dataKey := dk.Plaintext[:32]
hmacKey := dk.Plaintext[32:]
wrappedKey := dk.CiphertextBlob
ctext, err := Encrypt(dataKey, []byte(secret))
b64hmac := ComputeHmac256(ctext, hmacKey)
b64ctext := base64.StdEncoding.EncodeToString(ctext)
cred := &Credential{
Name: name,
Version: version,
Key: base64.StdEncoding.EncodeToString(wrappedKey),
Contents: b64ctext,
Hmac: b64hmac,
}
data, err := Encode(cred)
if err != nil {
return err
}
_, err = dynamoSvc.PutItem(&dynamodb.PutItemInput{
TableName: aws.String(Table),
Item: data,
})
return err
}
// DeleteSecret delete a secret
func DeleteSecret(name string) error {
res, err := dynamoSvc.Query(&dynamodb.QueryInput{
TableName: aws.String(Table),
ExpressionAttributeNames: map[string]*string{
"#N": aws.String("name"),
},
ExpressionAttributeValues: map[string]*dynamodb.AttributeValue{
":name": &dynamodb.AttributeValue{
S: aws.String(name),
},
},
KeyConditionExpression: aws.String("#N = :name"),
ConsistentRead: aws.Bool(true),
ScanIndexForward: aws.Bool(false), // descending order
})
if err != nil {
return err
}
for _, item := range res.Items {
cred := new(Credential)
err = Decode(item, cred)
if err != nil {
return err
}
fmt.Printf("deleting name=%s version=%s\n", cred.Name, cred.Version)
_, err = dynamoSvc.DeleteItem(&dynamodb.DeleteItemInput{
TableName: aws.String(Table),
Key: map[string]*dynamodb.AttributeValue{
"name": &dynamodb.AttributeValue{
S: aws.String(cred.Name),
},
"version": &dynamodb.AttributeValue{
S: aws.String(cred.Version),
},
},
})
if err != nil {
return err
}
}
return nil
}
func decryptCredential(cred *Credential) (*DecryptedCredential, error) {
wrappedKey, err := base64.StdEncoding.DecodeString(cred.Key)
if err != nil {
return nil, err
}
dk, err := DecryptDataKey(wrappedKey)
if err != nil {
return nil, err
}
dataKey := dk.Plaintext[:32]
hmacKey := dk.Plaintext[32:]
contents, err := base64.StdEncoding.DecodeString(cred.Contents)
if err != nil {
return nil, err
}
hexhmac := ComputeHmac256(contents, hmacKey)
if hexhmac != cred.Hmac {
return nil, ErrHmacValidationFailed
}
secret, err := Decrypt(dataKey, contents)
if err != nil {
return nil, err
}
plainText := string(secret)
return &DecryptedCredential{Credential: cred, Secret: plainText}, nil
}
func waitForTable() error {
timeout := make(chan bool, 1)
go func() {
time.Sleep(tableCreateTimeout)
timeout <- true
}()
ticker := time.NewTicker(1 * time.Second)
defer ticker.Stop()
for {
select {
case <-ticker.C:
// a read from ch has occurred
res, err := dynamoSvc.DescribeTable(&dynamodb.DescribeTableInput{
TableName: aws.String(Table),
})
if err != nil {
return err
}
if *res.Table.TableStatus == "ACTIVE" {
return nil
}
case <-timeout:
// polling for table status has taken more than the timeout
return ErrTimeout
}
}
}