-
Notifications
You must be signed in to change notification settings - Fork 128
/
keyRing.go
241 lines (207 loc) · 5.83 KB
/
keyRing.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
/*
* Copyright 2020, Cossack Labs Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package filesystem
import (
"errors"
"github.com/cossacklabs/acra/keystore/v2/keystore/api"
"github.com/cossacklabs/acra/keystore/v2/keystore/asn1"
log "github.com/sirupsen/logrus"
)
// KeyRing is a KeyRing provided by KeyStore.
// It provides a snapshot of data which might be outdated.
type KeyRing struct {
store *KeyStore
log *log.Entry
// Location of this key ring in KeyStore.
path string
// Data stored in the key ring and views into it.
data *asn1.KeyRing
// Transaction log of pending modifications to the key ring.
txLog []keyRingTX
}
//
// Construction
//
var errInvalidCurrentIndex = errors.New("invalid Current index in key ring")
func newKeyRing(store *KeyStore, path string) *KeyRing {
ring := &KeyRing{
store: store,
log: store.log,
path: path,
data: &asn1.KeyRing{
// TODO: shouldn't this be only the last component?..
Purpose: asn1.LikelyUTF8String(path),
Keys: make([]asn1.Key, 0),
Current: asn1.NoKey,
},
}
return ring
}
func (r *KeyRing) toASN1() asn1.KeyRing {
return *r.data
}
func (r *KeyRing) loadASN1(ring *asn1.KeyRing) error {
r.data = ring
return nil
}
//
// KeyRing & MutableKeyRing interface
//
// CurrentKey returns current key of this key ring, if available.
func (r *KeyRing) CurrentKey() (int, error) {
seqnum := r.data.Current
if seqnum == asn1.NoKey {
return seqnum, api.ErrNoCurrentKey
}
return seqnum, nil
}
// AllKeys returns all keys of this key ring, from newest to oldest.
func (r *KeyRing) AllKeys() ([]int, error) {
// Return a copy so that the caller cannot modify *our* cache. Also,
// return keys in reverse order, from newest to oldest. This makes
// AcraStruct decryption attempts more likely to succeed earlier.
keyCount := len(r.data.Keys)
keySeqnums := make([]int, keyCount)
for i := range r.data.Keys {
keySeqnums[keyCount-i-1] = r.data.Keys[i].Seqnum
}
return keySeqnums, nil
}
// AddKey appends a key to the key ring based on its description.
// Newly added key is returned if you wish to inspect or modify its state.
// Current key is not changed when a new key is added.
func (r *KeyRing) AddKey(key api.KeyDescription) (int, error) {
newKey, err := r.newKey(key)
if err != nil {
r.log.WithError(err).Debug("failed to make new key")
return asn1.NoKey, err
}
err = r.addKey(newKey)
if err != nil {
r.log.WithError(err).Debug("failed to add new key")
return asn1.NoKey, err
}
r.log.Trace("new key added to key ring")
return newKey.Seqnum, nil
}
//
// Key data encryption
//
func (r *KeyRing) keyRingContext(context []byte) []byte {
c := make([]byte, 0, len("key ring ")+len(r.path)+len(": ")+len(context))
c = append(c, "key ring "...)
c = append(c, r.path...)
c = append(c, ": "...)
c = append(c, context...)
return c
}
func (r *KeyRing) encrypt(data, context []byte) ([]byte, error) {
return r.store.encrypt(data, r.keyRingContext(context))
}
func (r *KeyRing) decrypt(data, context []byte) ([]byte, error) {
return r.store.decrypt(data, r.keyRingContext(context))
}
//
// Transaction handling
//
func (r *KeyRing) pendingUpdates() bool {
return len(r.txLog) > 0
}
func (r *KeyRing) applyPendingTX() error {
for lastTX, tx := range r.txLog {
err := tx.Apply(r)
if err != nil {
r.log.WithError(err).Debug("failed to apply update")
// Apply damage control. We cannot handle double faults so our best option
// is to complain in logs and then keep calm and carry on, betting on luck.
// Rollback should not fail, actually, but panicking is too destructive now.
// TODO: is it possible to just snapshot the original state instead?
for i := lastTX - 1; i >= 0; i-- {
err := r.txLog[i].Rollback(r)
if err != nil {
r.log.WithError(err).Warn("failed to roll back update")
}
}
return err
}
}
return nil
}
func (r *KeyRing) commitTX() {
r.txLog = nil
}
func (r *KeyRing) setCurrent(newSeqnum int) error {
oldSeqnum := r.data.Current
r.pushTX(&txSetKeyCurrent{oldSeqnum, newSeqnum})
err := r.store.syncKeyRing(r)
if err != nil {
r.popTX()
}
return err
}
func (r *KeyRing) changeKeyState(keySeqnum int, oldState, newState api.KeyState) error {
r.pushTX(&txChangeKeyState{keySeqnum, oldState, newState})
err := r.store.syncKeyRing(r)
if err != nil {
r.popTX()
}
return err
}
func (r *KeyRing) addKey(newKey *asn1.Key) error {
r.pushTX(&txAddKey{newKey})
err := r.store.syncKeyRing(r)
if err != nil {
r.popTX()
}
return err
}
func (r *KeyRing) destroyKey(keySeqnum int, currentState api.KeyState) error {
r.pushTX(&txDestroyKeyData{keySeqnum: keySeqnum})
r.pushTX(&txChangeKeyState{keySeqnum, currentState, api.KeyDestroyed})
err := r.store.syncKeyRing(r)
if err != nil {
r.popTX()
r.popTX()
}
return err
}
//
// Internal utilities
//
func (r *KeyRing) keyDataBySeqnum(seqnum int) *asn1.Key {
key, _ := r.data.KeyWithSeqnum(seqnum)
return key
}
// Don't start with zero to not match zero-initialized defaults.
const firstSeqnum = 1
func (r *KeyRing) nextSeqnum() int {
if len(r.data.Keys) == 0 {
return firstSeqnum
}
return r.data.Keys[len(r.data.Keys)-1].Seqnum + 1
}
func (r *KeyRing) pushTX(tx keyRingTX) {
r.txLog = append(r.txLog, tx)
}
func (r *KeyRing) popTX() keyRingTX {
if len(r.txLog) == 0 {
return nil
}
last := len(r.txLog) - 1
tx := r.txLog[last]
r.txLog = r.txLog[:last]
return tx
}