This repository has been archived by the owner on Mar 28, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 68
/
hTsxVault.go
356 lines (284 loc) · 10.7 KB
/
hTsxVault.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
349
350
351
352
353
354
355
356
package system
import (
"crypto/sha512"
"fmt"
"net/http"
"strings"
"time"
"encoding/base64"
"encoding/hex"
"encoding/json"
"github.com/go-chi/chi"
hashicorpVault "github.com/hashicorp/vault/api"
"github.com/seknox/trasa/server/api/orgs"
"github.com/seknox/trasa/server/api/providers/vault"
"github.com/seknox/trasa/server/api/providers/vault/tsxvault"
"github.com/seknox/trasa/server/consts"
"github.com/seknox/trasa/server/global"
"github.com/seknox/trasa/server/models"
"github.com/seknox/trasa/server/utils"
logger "github.com/sirupsen/logrus"
)
// StoreKey stores keys in database.
// Keys should be encrypted and tag value must be generated.
// Before storing key, check if the key is valid and working.
func StoreKey(w http.ResponseWriter, r *http.Request) {
uc := r.Context().Value("user").(models.UserContext)
var req models.KeysHolderReq
if err := utils.ParseAndValidateRequest(r, &req); err != nil {
logger.Error(err)
utils.TrasaResponse(w, 200, "failed", "invalid request.", "StoreKey", "")
return
}
var store models.KeysHolder
store.OrgID = uc.User.OrgID
store.KeyID = utils.GetRandomString(5)
store.KeyTag = fmt.Sprintf("%s-xxxx-xxxx...", req.KeyVal[0:4])
store.AddedBy = uc.User.ID
store.AddedAt = time.Now().Unix()
store.KeyVal = []byte(req.KeyVal)
store.KeyName = req.KeyName
_, err := EncryptAndStoreKeyOrToken(store)
if err != nil {
logger.Error(err)
utils.TrasaResponse(w, 200, "failed", err.Error(), "StoreKey", nil)
return
}
utils.TrasaResponse(w, 200, "success", "keys stored", "StoreKey", req.KeyTag)
}
// Getkey retrieves key or token from database. should fetch and return key tag rather than key value.
func Getkey(w http.ResponseWriter, r *http.Request) {
uc := r.Context().Value("user").(models.UserContext)
vendorID := chi.URLParam(r, "vendorID")
key, err := tsxvault.Store.GetKeyOrTokenWithTag(uc.User.OrgID, vendorID)
if err != nil {
logger.Error(err, vendorID)
utils.TrasaResponse(w, 200, "failed", "failed to get token.", "Getkey-GetKeyOrTokenWithTag", nil)
return
}
var resp models.KeysHolderReq
resp.KeyName = key.KeyName
resp.KeyID = key.KeyID
resp.KeyVal = key.KeyTag
resp.KeyTag = key.KeyTag
resp.AddedAt = key.AddedAt
resp.AddedBy = key.AddedBy
utils.TrasaResponse(w, 200, "success", "key fetched", "Getkey", resp)
}
//EncryptAndStoreKeyOrToken is helper function which encrypts key or token and store it in database.
func EncryptAndStoreKeyOrToken(req models.KeysHolder) ([]byte, error) {
ct, err := tsxvault.Store.AesEncrypt([]byte(req.KeyVal))
req.KeyVal = ct
if err != nil {
//logger.Error(err)
return nil, err
}
err = tsxvault.Store.StoreKeyOrTokens(req)
if err != nil {
logger.Error(err)
return nil, fmt.Errorf("failed to store token")
}
return req.KeyVal, nil
}
type VaultInit struct {
SecretShares int `json:"secretShares"`
SecretThreshold int `json:"secretThreshold"`
}
type VaultInitResp struct {
UnsealKeys []string `json:"unsealKeys"`
DecryptKeys []string `json:"decryptKeys"`
EncRootToken string `json:"encRootToken"`
Tsxvault bool `json:"tsxvault"`
}
// TsxvaultInit initializes TRASA built in secure storage. master key for encryption is
// Shamir'ed into 5 keys with minimum 3 keys threshold and responded back to administrator.
func TsxvaultInit(w http.ResponseWriter, r *http.Request) {
uc := r.Context().Value("user").(models.UserContext)
var req VaultInit
if err := utils.ParseAndValidateRequest(r, &req); err != nil {
logger.Error(err)
utils.TrasaResponse(w, 200, "failed", "invalid request", "Vault not initialised", nil)
return
}
// Initing tsxvault process: (1) Create encryption key. (2) Create master key and encrypt encryption key with it.
// (3) shard master key and give it to user. (4) store encrypted encryption key in database.
encKeyShards, err := initTsxvault(uc.User.OrgID)
if err != nil {
logger.Error(err)
utils.TrasaResponse(w, 200, "failed", "failed to init vault", "failed to retrieve key", nil)
return
}
var store models.GlobalSettings
store.SettingID = utils.GetUUID()
store.OrgID = uc.Org.ID
store.Status = true
store.SettingType = consts.GLOBAL_TSXVAULT
var vaultFeature models.VaultFeature
vaultFeature.CredStorage = "tsxvault"
vaultFeature.CertStorage = "tsxvault"
jsonV, _ := json.Marshal(vaultFeature)
store.SettingValue = string(jsonV)
store.UpdatedBy = uc.User.ID
store.UpdatedOn = time.Now().Unix()
err = Store.UpdateGlobalSetting(store)
if err != nil {
logger.Error(err)
utils.TrasaResponse(w, 200, "failed", "failed to init vault", "Vault not initialised", nil)
return
}
var resp VaultInitResp
resp.UnsealKeys = encKeyShards
resp.Tsxvault = true
utils.TrasaResponse(w, 200, "success", "next-key", "Vault initialised", resp)
}
// initTsxvault generates aws encryption key. shards it with sharder and returns sharded key.
func initTsxvault(orgID string) ([]string, error) {
encKey, err := tsxvault.Store.GenAndStoreKey(orgID)
if err != nil {
return nil, err
}
shardedKeys := utils.ShamirSharder(encKey[:], 5, 3)
return shardedKeys, nil
}
// ReInit purpose is to delete exisiting vault configs and instances from database.
// Clients should immediately send another request to vault init when this handler returns success response.
func ReInit(w http.ResponseWriter, r *http.Request) {
uc := r.Context().Value("user").(models.UserContext)
// (1) remove all managed users for this organization.
err := orgs.Store.RemoveAllManagedAccounts(uc.User.OrgID)
if err != nil {
logger.Error(err)
utils.TrasaResponse(w, 200, "failed", "failed to remove manged users but vault storage is removed.", "Vault not reinitialised", nil)
return
}
err = tsxvault.Store.TsxvdeactivateAllKeys(uc.User.OrgID, time.Now().Unix())
if err != nil {
logger.Error(err)
utils.TrasaResponse(w, 200, "failed", "failed to remove manged users but vault storage is removed.", "Vault not reinitialised", nil)
return
}
// delete all rows from Service_keyvaultv1
err = tsxvault.Store.TsxvDeleteAllSecret(uc.User.OrgID)
if err != nil {
logger.Error(err)
utils.TrasaResponse(w, 200, "failed", "failed to remove manged users but vault storage is removed.", "Vault not reinitialised", nil)
return
}
utils.TrasaResponse(w, 200, "success", "submit-init", "Vault reinitialised", nil)
}
type VaultStatus struct {
InitStatus models.GlobalSettings `json:"initStatus"`
SealStatus *hashicorpVault.SealStatusResponse `json:"sealStatus"`
TokenStatus hashicorpVault.SealStatusResponse `json:"tokenStatus"`
// TsxVault is TRASA's built in tsxvault. if false, caller should assume hashicorp vault is used instead.
Tsxvault bool `json:"tsxvault"`
Setting string `json:"setting"`
}
// Status returns vault's current status.
func Status(w http.ResponseWriter, r *http.Request) {
uc := r.Context().Value("user").(models.UserContext)
vaultInitStatus, err := Store.GetGlobalSetting(uc.Org.ID, consts.GLOBAL_TSXVAULT)
if err != nil {
logger.Error(err)
utils.TrasaResponse(w, 200, "failed", "successfully retrieved org details", "GetOrgDetail", nil)
return
}
var resp VaultStatus
resp.InitStatus = vaultInitStatus
resp.Tsxvault = global.GetConfig().Vault.Tsxvault
resp.Setting = vaultInitStatus.SettingValue
_, status := tsxvault.Store.GetTsxVaultKey()
if status == false {
resp.TokenStatus = hashicorpVault.SealStatusResponse{Sealed: true}
utils.TrasaResponse(w, 200, "failed", "This key is not retrieved", "Vault not decrypted", resp)
return
}
resp.TokenStatus = hashicorpVault.SealStatusResponse{Sealed: false}
utils.TrasaResponse(w, 200, "success", "successfully retrieved org details", "GetOrgDetail", resp)
}
// HoldDecryptShard hods state of encryption key retreival during shamir deduce function
var HoldDecryptShard [][]byte
type unseal struct {
Key string `json:"key"`
}
// DecryptKey retrieves token from vaultDecrypt function and
// store it in vaultEncryption Token. This is only available option for tsxtsxvault.
// TODO @sshahcodes compose this handler to smaller functions
func DecryptKey(w http.ResponseWriter, r *http.Request) {
uc := r.Context().Value("user").(models.UserContext)
var req unseal
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
logger.Error(err)
utils.TrasaResponse(w, 200, "failed", "invalid request", "Vault not decrypted", nil)
return
}
trimmed := strings.TrimSpace(req.Key)
key, err := base64.StdEncoding.DecodeString(trimmed)
if err != nil {
logger.Error(err)
utils.TrasaResponse(w, 200, "failed", "decode error", "Vault not decrypted", nil)
return
}
var resp hashicorpVault.SealStatusResponse
HoldDecryptShard = append(HoldDecryptShard, key)
if len(HoldDecryptShard) < 3 {
resp.Sealed = true
resp.Progress = len(HoldDecryptShard)
utils.TrasaResponse(w, 200, "success", "next-key", "Vault decrypted", resp)
return
}
// try to deduce the key. if deducing is success, also test if the key works. else return failed.
deducedVal, err := utils.ShamirDeducer(HoldDecryptShard)
if err != nil {
logger.Error("ShamirDeducer ", err)
HoldDecryptShard = nil
utils.TrasaResponse(w, 200, "failed", "unable to deduce key. Retry again from 1st key", "Vault decrypted", resp)
return
}
hash := sha512.New()
var buf []byte
buf = append(buf, deducedVal[:]...)
hashed := hash.Sum([]byte(buf))
// check if token is valid.
// this is verified by fetching value from TsxvGetEncKeyHash. if this fails or returned key is expired,
// we return failed response. other wise will store it in TsxVaultKey.
getKey, err := tsxvault.Store.TsxvGetEncKeyHash(uc.User.OrgID, hex.EncodeToString(hashed))
if err != nil {
logger.Error(err)
HoldDecryptShard = nil
utils.TrasaResponse(w, 200, "failed", "This key is not registered", "Vault not decrypted", nil)
return
}
if getKey.Status == false {
logger.Error("failed status")
HoldDecryptShard = nil
utils.TrasaResponse(w, 200, "failed", "This key is expired", "Vault not decrypted", nil)
return
}
if hex.EncodeToString(hashed) != getKey.KeyHash {
logger.Error("hash mismatch")
HoldDecryptShard = nil
utils.TrasaResponse(w, 200, "failed", "This key is not valid", "Vault not decrypted", nil)
return
}
// reaching here means we can set encryption key and state
nkey := new([32]byte)
copy(nkey[:], deducedVal)
// set in global tsxvKey vault
tsxvault.Store.SetTsxVaultKey(nkey, true)
HoldDecryptShard = HoldDecryptShard[:0]
resp.Sealed = false
resp.Progress = len(HoldDecryptShard)
// retreive trasaCPxy api key here
// get key ct from database.
apikey, err := vault.Store.GetKeyOrTokenWithKeyval(uc.User.OrgID, consts.GLOBAL_CLOUDPROXY_APIKEY)
if err != nil {
logger.Error(err)
}
pt, err := utils.AESDecrypt(nkey[:], apikey.KeyVal)
if err != nil {
logger.Error(err)
}
tsxvault.Store.SetTsxCPxyKey(string(pt))
utils.TrasaResponse(w, 200, "success", "token retrieved", "Vault decrypted", resp)
}