Debian Codegraph @

keycache/keycache.go

raw symbols SCIP
1 // Package keycache provides the ability to hold active keys in memory
2 // for the Red October server.
3 //
4 // Copyright (c) 2013 CloudFlare, Inc.
5
6 package keycache
7
8 import (
9 "crypto/aes"
10 "crypto/ecdsa"
11 "crypto/rand"
12 "crypto/rsa"
13 "crypto/sha1"
14 "crypto/x509"
15 "errors"
16 "fmt"
17 "log"
18 "strings"
19 "time"
20
21 "github.com/cloudflare/redoctober/ecdh"
22 "github.com/cloudflare/redoctober/passvault"
23 )
24
25 // DelegateIndex is used to index the map of currently delegated keys.
26 // This is necessary to provide a way for a delegator to provide multiple
27 // delegations. It is also used to avoid the complexity of string parsing
28 // and enforcement of username and slot character requirements.
29 type DelegateIndex struct {
30 Name string
31 Slot string
32 }
33
34 // Usage holds the permissions of a delegated permission
35 type Usage struct {
36 Uses int // Number of uses delegated
37 Labels []string // File labels allowed to decrypt
38 Users []string // Set of users allows to decrypt
39 Expiry time.Time // Expiration of usage
40 }
41
42 // ActiveUser holds the information about an actively delegated key.
43 type ActiveUser struct {
44 Usage
45 AltNames map[string]string
46 Admin bool
47 Type string
48 Key []byte
49
50 rsaKey rsa.PrivateKey
51 eccKey *ecdsa.PrivateKey
52 }
53
54 // Cache represents the current list of delegated keys in memory
55 type Cache struct {
56 UserKeys map[DelegateIndex]ActiveUser
57 }
58
59 // matchesLabel returns true if this usage applies the user and label
60 // an empty array of Users indicates that all users are valid
61 func (usage Usage) matchesLabel(labels []string) bool {
62 // if asset has no labels always match
63 if len(labels) == 0 {
64 return true
65 }
66
67 for _, validLabel := range usage.Labels {
68 for _, label := range labels {
69 if label == validLabel {
70 return true
71 }
72 }
73 }
74 return false
75 }
76
77 // matches returns true if this usage applies the user and label
78 // an empty array of Users indicates that all users are valid
79 func (usage Usage) matches(user string, labels []string) bool {
80 if !usage.matchesLabel(labels) {
81 return false
82 }
83 // if usage lists no users, always match
84 if len(usage.Users) == 0 {
85 return true
86 }
87 for _, validUser := range usage.Users {
88 if user == validUser {
89 return true
90 }
91 }
92 return false
93 }
94
95 // NewCache initalizes a new cache.
96 func NewCache() Cache {
97 return Cache{make(map[DelegateIndex]ActiveUser)}
98 }
99
100 // NewFrom takes the output of GetSummary and returns a new keycache.
101 func NewFrom(summary map[string]ActiveUser) *Cache {
102 cache := &Cache{make(map[DelegateIndex]ActiveUser)}
103 for di, user := range summary {
104 diSplit := strings.SplitN(di, "-", 2)
105 index := DelegateIndex{
106 Name: diSplit[0],
107 }
108
109 if len(diSplit) == 2 {
110 index.Slot = diSplit[1]
111 }
112 cache.UserKeys[index] = user
113 }
114
115 return cache
116 }
117
118 // setUser takes an ActiveUser and adds it to the cache.
119 func (cache *Cache) setUser(in ActiveUser, name, slot string) {
120 cache.UserKeys[DelegateIndex{Name: name, Slot: slot}] = in
121 }
122
123 // Valid returns true if matching active user is present.
124 func (cache *Cache) Valid(name, user string, labels []string) (present bool) {
125 for d, key := range cache.UserKeys {
126 if d.Name != name {
127 continue
128 }
129 if key.Usage.matches(user, labels) {
130 return true
131 }
132 }
133
134 return false
135 }
136
137 // MatchUser returns the matching active user if present
138 // and a boolean to indicate its presence.
139 func (cache *Cache) MatchUser(name, user string, labels []string) (ActiveUser, string, bool) {
140 var key ActiveUser
141 for d, key := range cache.UserKeys {
142 if d.Name != name {
143 continue
144 }
145 if key.Usage.matches(user, labels) {
146 return key, d.Slot, true
147 }
148 }
149
150 return key, "", false
151 }
152
153 // useKey decrements the counter on an active key
154 // for decryption or symmetric encryption
155 func (cache *Cache) useKey(name, user, slot string, labels []string) {
156 if val, slot, present := cache.MatchUser(name, user, labels); present {
157 val.Usage.Uses -= 1
158 if val.Usage.Uses <= 0 {
159 delete(cache.UserKeys, DelegateIndex{name, slot})
160 } else {
161 cache.setUser(val, name, slot)
162 }
163 }
164 }
165
166 // GetSummary returns the list of active user keys.
167 func (cache *Cache) GetSummary() map[string]ActiveUser {
168 summaryData := make(map[string]ActiveUser)
169 for d, activeUser := range cache.UserKeys {
170 summaryInfo := d.Name
171 if d.Slot != "" {
172 summaryInfo = fmt.Sprintf("%s-%s", d.Name, d.Slot)
173 }
174 summaryData[summaryInfo] = activeUser
175 }
176 return summaryData
177 }
178
179 // FlushCache removes all delegated keys. It returns true if the cache
180 // wasn't empty (i.e. there were active users removed), and false if
181 // the cache was empty.
182 func (cache *Cache) Flush() bool {
183 if len(cache.UserKeys) == 0 {
184 return false
185 }
186
187 for d := range cache.UserKeys {
188 delete(cache.UserKeys, d)
189 }
190
191 return true
192 }
193
194 // Refresh purges all expired keys. It returns the number of
195 // delegations that were removed.
196 func (cache *Cache) Refresh() int {
197 var removed int
198
199 for d, active := range cache.UserKeys {
200 if active.Usage.Expiry.Before(time.Now()) {
201 log.Println("Record expired", d.Name, d.Slot, active.Usage.Users, active.Usage.Labels, active.Usage.Expiry)
202 removed++
203 delete(cache.UserKeys, d)
204 }
205 }
206
207 return removed
208 }
209
210 // AddKeyFromRecord decrypts a key for a given record and adds it to the cache.
211 func (cache *Cache) AddKeyFromRecord(record passvault.PasswordRecord, name, password string, users, labels []string, uses int, slot, durationString string) (err error) {
212 var current ActiveUser
213
214 cache.Refresh()
215
216 // compute exipiration
217 duration, err := time.ParseDuration(durationString)
218 if err != nil {
219 return
220 }
221 current.Usage.Uses = uses
222 current.Usage.Expiry = time.Now().Add(duration)
223 current.Usage.Users = users
224 current.Usage.Labels = labels
225
226 // get decryption keys
227 switch record.Type {
228 case passvault.RSARecord:
229 current.rsaKey, err = record.GetKeyRSA(password)
230 if err != nil {
231 return
232 }
233 current.Key = x509.MarshalPKCS1PrivateKey(&current.rsaKey)
234 case passvault.ECCRecord:
235 current.eccKey, err = record.GetKeyECC(password)
236 if err != nil {
237 return
238 }
239 current.Key, err = x509.MarshalECPrivateKey(current.eccKey)
240 default:
241 err = errors.New("Unknown record type")
242 }
243
244 if err != nil {
245 return
246 }
247
248 // set types
249 current.Type = record.Type
250 current.Admin = record.Admin
251
252 // add current to map (overwriting previous for this name)
253 cache.setUser(current, name, slot)
254
255 return
256 }
257
258 // DecryptKey decrypts a 16 byte key using the key corresponding to the name parameter
259 // For RSA and EC keys, the cached RSA/EC key is used to decrypt
260 // the pubEncryptedKey which is then used to decrypt the input
261 // buffer.
262 func (cache *Cache) DecryptKey(in []byte, name, user string, labels []string, pubEncryptedKey []byte) (out []byte, err error) {
263 cache.Refresh()
264
265 decryptKey, slot, ok := cache.MatchUser(name, user, labels)
266 if !ok {
267 return nil, errors.New("Key not delegated")
268 }
269
270 var aesKey []byte
271
272 // pick the aesKey to use for decryption
273 switch decryptKey.Type {
274 case passvault.RSARecord:
275 // extract the aes key from the pubEncryptedKey
276 aesKey, err = rsa.DecryptOAEP(sha1.New(), rand.Reader, &decryptKey.rsaKey, pubEncryptedKey, nil)
277 if err != nil {
278 return out, err
279 }
280 case passvault.ECCRecord:
281 // extract the aes key from the pubEncryptedKey
282 aesKey, err = ecdh.Decrypt(decryptKey.eccKey, pubEncryptedKey)
283
284 if err != nil {
285 return out, err
286 }
287 default:
288 return nil, errors.New("unknown type")
289 }
290
291 // decrypt
292 aesSession, err := aes.NewCipher(aesKey)
293 if err != nil {
294 return out, err
295 }
296 out = make([]byte, 16)
297 aesSession.Decrypt(out, in)
298
299 cache.useKey(name, user, slot, labels)
300
301 return
302 }
303
304 // DecryptShares decrypts an array of 16 byte shares using the key corresponding
305 // to the name parameter.
306 func (cache *Cache) DecryptShares(in [][]byte, name, user string, labels []string, pubEncryptedKey []byte) (out [][]byte, err error) {
307 cache.Refresh()
308
309 decryptKey, slot, ok := cache.MatchUser(name, user, labels)
310 if !ok {
311 return nil, errors.New("Key not delegated")
312 }
313
314 var aesKey []byte
315
316 // pick the aesKey to use for decryption
317 switch decryptKey.Type {
318 case passvault.RSARecord:
319 // extract the aes key from the pubEncryptedKey
320 aesKey, err = rsa.DecryptOAEP(sha1.New(), rand.Reader, &decryptKey.rsaKey, pubEncryptedKey, nil)
321 if err != nil {
322 return
323 }
324 case passvault.ECCRecord:
325 // extract the aes key from the pubEncryptedKey
326 aesKey, err = ecdh.Decrypt(decryptKey.eccKey, pubEncryptedKey)
327
328 if err != nil {
329 return
330 }
331 default:
332 return nil, errors.New("unknown type")
333 }
334
335 // decrypt
336 aesSession, err := aes.NewCipher(aesKey)
337 if err != nil {
338 return
339 }
340
341 for _, encShare := range in {
342 tmp := make([]byte, 16)
343 aesSession.Decrypt(tmp, encShare)
344
345 out = append(out, tmp)
346 }
347
348 cache.useKey(name, user, slot, labels)
349
350 return
351 }
352
353 // DelegateStatus will return a list of admins who have delegated to a particular user, for a particular label.
354 // This is useful information to have when determining the status of an order and conveying order progress.
355 func (cache *Cache) DelegateStatus(name string, labels, admins []string) (adminsDelegated []string, hasDelegated int) {
356 // Iterate over the admins of the ciphertext to look for users
357 // who have already delegated the label to the delegatee.
358 for _, admin := range admins {
359 for di, use := range cache.UserKeys {
360 if di.Name != admin {
361 continue
362 }
363 nameFound := false
364 for _, user := range use.Users {
365 if user == name {
366 nameFound = true
367 }
368 }
369 for _, ol := range use.Labels {
370 for _, il := range labels {
371 if ol == il {
372 if nameFound {
373 adminsDelegated = append(adminsDelegated, admin)
374 hasDelegated++
375 }
376 }
377 }
378 }
379 }
380 }
381 return
382 }
383
384 // Restore unmarshals the private key stored in the delegator to the
385 // appropriate private structure.
386 func (cache *Cache) Restore() (err error) {
387 for index, uk := range cache.UserKeys {
388 if len(uk.Key) == 0 {
389 return errors.New("keycache: no private key in active user")
390 }
391
392 rsaPriv, err := x509.ParsePKCS1PrivateKey(uk.Key)
393 if err == nil {
394 uk.rsaKey = *rsaPriv
395 cache.UserKeys[index] = uk
396 continue
397 }
398
399 ecPriv, err := x509.ParseECPrivateKey(uk.Key)
400 if err == nil {
401 uk.eccKey = ecPriv
402 cache.UserKeys[index] = uk
403 continue
404 }
405
406 return err
407 }
408
409 return nil
410 }