forked from restic/restic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
key.go
303 lines (246 loc) · 7.01 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
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
package repository
import (
"context"
"encoding/json"
"fmt"
"os"
"os/user"
"time"
"github.com/wutong-paas/restic/pkg/errors"
"github.com/wutong-paas/restic/pkg/restic"
"github.com/wutong-paas/restic/pkg/backend"
"github.com/wutong-paas/restic/pkg/crypto"
"github.com/wutong-paas/restic/pkg/debug"
)
var (
// ErrNoKeyFound is returned when no key for the repository could be decrypted.
ErrNoKeyFound = errors.New("wrong password or no key found")
// ErrMaxKeysReached is returned when the maximum number of keys was checked and no key could be found.
ErrMaxKeysReached = errors.New("maximum number of keys reached")
)
// Key represents an encrypted master key for a repository.
type Key struct {
Created time.Time `json:"created"`
Username string `json:"username"`
Hostname string `json:"hostname"`
KDF string `json:"kdf"`
N int `json:"N"`
R int `json:"r"`
P int `json:"p"`
Salt []byte `json:"salt"`
Data []byte `json:"data"`
user *crypto.Key
master *crypto.Key
id restic.ID
}
// Params tracks the parameters used for the KDF. If not set, it will be
// calibrated on the first run of AddKey().
var Params *crypto.Params
var (
// KDFTimeout specifies the maximum runtime for the KDF.
KDFTimeout = 500 * time.Millisecond
// KDFMemory limits the memory the KDF is allowed to use.
KDFMemory = 60
)
// createMasterKey creates a new master key in the given backend and encrypts
// it with the password.
func createMasterKey(ctx context.Context, s *Repository, password string) (*Key, error) {
return AddKey(ctx, s, password, "", "", nil)
}
// OpenKey tries do decrypt the key specified by name with the given password.
func OpenKey(ctx context.Context, s *Repository, id restic.ID, password string) (*Key, error) {
k, err := LoadKey(ctx, s, id)
if err != nil {
debug.Log("LoadKey(%v) returned error %v", id.String(), err)
return nil, err
}
// check KDF
if k.KDF != "scrypt" {
return nil, errors.New("only supported KDF is scrypt()")
}
// derive user key
params := crypto.Params{
N: k.N,
R: k.R,
P: k.P,
}
k.user, err = crypto.KDF(params, k.Salt, password)
if err != nil {
return nil, errors.Wrap(err, "crypto.KDF")
}
// decrypt master keys
nonce, ciphertext := k.Data[:k.user.NonceSize()], k.Data[k.user.NonceSize():]
buf, err := k.user.Open(nil, nonce, ciphertext, nil)
if err != nil {
return nil, err
}
// restore json
k.master = &crypto.Key{}
err = json.Unmarshal(buf, k.master)
if err != nil {
debug.Log("Unmarshal() returned error %v", err)
return nil, errors.Wrap(err, "Unmarshal")
}
k.id = id
if !k.Valid() {
return nil, errors.New("Invalid key for repository")
}
return k, nil
}
// SearchKey tries to decrypt at most maxKeys keys in the backend with the
// given password. If none could be found, ErrNoKeyFound is returned. When
// maxKeys is reached, ErrMaxKeysReached is returned. When setting maxKeys to
// zero, all keys in the repo are checked.
func SearchKey(ctx context.Context, s *Repository, password string, maxKeys int, keyHint string) (k *Key, err error) {
checked := 0
if len(keyHint) > 0 {
id, err := restic.Find(ctx, s.Backend(), restic.KeyFile, keyHint)
if err == nil {
key, err := OpenKey(ctx, s, id, password)
if err == nil {
debug.Log("successfully opened hinted key %v", id)
return key, nil
}
debug.Log("could not open hinted key %v", id)
} else {
debug.Log("Could not find hinted key %v", keyHint)
}
}
listCtx, cancel := context.WithCancel(ctx)
defer cancel()
// try at most maxKeys keys in repo
err = s.List(listCtx, restic.KeyFile, func(id restic.ID, size int64) error {
checked++
if maxKeys > 0 && checked > maxKeys {
return ErrMaxKeysReached
}
debug.Log("trying key %q", id.String())
key, err := OpenKey(ctx, s, id, password)
if err != nil {
debug.Log("key %v returned error %v", id.String(), err)
// ErrUnauthenticated means the password is wrong, try the next key
if errors.Is(err, crypto.ErrUnauthenticated) {
return nil
}
return err
}
debug.Log("successfully opened key %v", id.String())
k = key
cancel()
return nil
})
if err == context.Canceled {
err = nil
}
if err != nil {
return nil, err
}
if k == nil {
return nil, ErrNoKeyFound
}
return k, nil
}
// LoadKey loads a key from the backend.
func LoadKey(ctx context.Context, s *Repository, id restic.ID) (k *Key, err error) {
h := restic.Handle{Type: restic.KeyFile, Name: id.String()}
data, err := backend.LoadAll(ctx, nil, s.be, h)
if err != nil {
return nil, err
}
k = &Key{}
err = json.Unmarshal(data, k)
if err != nil {
return nil, errors.Wrap(err, "Unmarshal")
}
return k, nil
}
// AddKey adds a new key to an already existing repository.
func AddKey(ctx context.Context, s *Repository, password, username, hostname string, template *crypto.Key) (*Key, error) {
// make sure we have valid KDF parameters
if Params == nil {
p, err := crypto.Calibrate(KDFTimeout, KDFMemory)
if err != nil {
return nil, errors.Wrap(err, "Calibrate")
}
Params = &p
debug.Log("calibrated KDF parameters are %v", p)
}
// fill meta data about key
newkey := &Key{
Created: time.Now(),
Username: username,
Hostname: hostname,
KDF: "scrypt",
N: Params.N,
R: Params.R,
P: Params.P,
}
if newkey.Hostname == "" {
newkey.Hostname, _ = os.Hostname()
}
if newkey.Username == "" {
usr, err := user.Current()
if err == nil {
newkey.Username = usr.Username
}
}
// generate random salt
var err error
newkey.Salt, err = crypto.NewSalt()
if err != nil {
panic("unable to read enough random bytes for salt: " + err.Error())
}
// call KDF to derive user key
newkey.user, err = crypto.KDF(*Params, newkey.Salt, password)
if err != nil {
return nil, err
}
if template == nil {
// generate new random master keys
newkey.master = crypto.NewRandomKey()
} else {
// copy master keys from old key
newkey.master = template
}
// encrypt master keys (as json) with user key
buf, err := json.Marshal(newkey.master)
if err != nil {
return nil, errors.Wrap(err, "Marshal")
}
nonce := crypto.NewRandomNonce()
ciphertext := make([]byte, 0, crypto.CiphertextLength(len(buf)))
ciphertext = append(ciphertext, nonce...)
ciphertext = newkey.user.Seal(ciphertext, nonce, buf, nil)
newkey.Data = ciphertext
// dump as json
buf, err = json.Marshal(newkey)
if err != nil {
return nil, errors.Wrap(err, "Marshal")
}
id := restic.Hash(buf)
// store in repository and return
h := restic.Handle{
Type: restic.KeyFile,
Name: id.String(),
}
err = s.be.Save(ctx, h, restic.NewByteReader(buf, s.be.Hasher()))
if err != nil {
return nil, err
}
newkey.id = id
return newkey, nil
}
func (k *Key) String() string {
if k == nil {
return "<Key nil>"
}
return fmt.Sprintf("<Key of %s@%s, created on %s>", k.Username, k.Hostname, k.Created)
}
// ID returns an identifier for the key.
func (k Key) ID() restic.ID {
return k.id
}
// Valid tests whether the mac and encryption keys are valid (i.e. not zero)
func (k *Key) Valid() bool {
return k.user.Valid() && k.master.Valid()
}