-
-
Notifications
You must be signed in to change notification settings - Fork 3.1k
/
Copy pathkeystore.go
575 lines (500 loc) · 14.4 KB
/
keystore.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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
package commands
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"text/tabwriter"
cmds "github.com/ipfs/go-ipfs-cmds"
config "github.com/ipfs/go-ipfs-config"
keystore "github.com/ipfs/go-ipfs-keystore"
oldcmds "github.com/ipfs/go-ipfs/commands"
cmdenv "github.com/ipfs/go-ipfs/core/commands/cmdenv"
"github.com/ipfs/go-ipfs/core/commands/e"
ke "github.com/ipfs/go-ipfs/core/commands/keyencode"
fsrepo "github.com/ipfs/go-ipfs/repo/fsrepo"
migrations "github.com/ipfs/go-ipfs/repo/fsrepo/migrations"
options "github.com/ipfs/interface-go-ipfs-core/options"
"github.com/libp2p/go-libp2p-core/crypto"
peer "github.com/libp2p/go-libp2p-core/peer"
)
var KeyCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Create and list IPNS name keypairs",
ShortDescription: `
'ipfs key gen' generates a new keypair for usage with IPNS and 'ipfs name
publish'.
> ipfs key gen --type=rsa --size=2048 mykey
> ipfs name publish --key=mykey QmSomeHash
'ipfs key list' lists the available keys.
> ipfs key list
self
mykey
`,
},
Subcommands: map[string]*cmds.Command{
"gen": keyGenCmd,
"export": keyExportCmd,
"import": keyImportCmd,
"list": keyListCmd,
"rename": keyRenameCmd,
"rm": keyRmCmd,
"rotate": keyRotateCmd,
},
}
type KeyOutput struct {
Name string
Id string
}
type KeyOutputList struct {
Keys []KeyOutput
}
// KeyRenameOutput define the output type of keyRenameCmd
type KeyRenameOutput struct {
Was string
Now string
Id string
Overwrite bool
}
const (
keyStoreAlgorithmDefault = options.Ed25519Key
keyStoreTypeOptionName = "type"
keyStoreSizeOptionName = "size"
oldKeyOptionName = "oldkey"
)
var keyGenCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Create a new keypair",
},
Options: []cmds.Option{
cmds.StringOption(keyStoreTypeOptionName, "t", "type of the key to create: rsa, ed25519").WithDefault(keyStoreAlgorithmDefault),
cmds.IntOption(keyStoreSizeOptionName, "s", "size of the key to generate"),
ke.OptionIPNSBase,
},
Arguments: []cmds.Argument{
cmds.StringArg("name", true, false, "name of key to create"),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
api, err := cmdenv.GetApi(env, req)
if err != nil {
return err
}
typ, f := req.Options[keyStoreTypeOptionName].(string)
if !f {
return fmt.Errorf("please specify a key type with --type")
}
name := req.Arguments[0]
if name == "self" {
return fmt.Errorf("cannot create key with name 'self'")
}
opts := []options.KeyGenerateOption{options.Key.Type(typ)}
size, sizefound := req.Options[keyStoreSizeOptionName].(int)
if sizefound {
opts = append(opts, options.Key.Size(size))
}
keyEnc, err := ke.KeyEncoderFromString(req.Options[ke.OptionIPNSBase.Name()].(string))
if err != nil {
return err
}
key, err := api.Key().Generate(req.Context, name, opts...)
if err != nil {
return err
}
return cmds.EmitOnce(res, &KeyOutput{
Name: name,
Id: keyEnc.FormatID(key.ID()),
})
},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, ko *KeyOutput) error {
_, err := w.Write([]byte(ko.Id + "\n"))
return err
}),
},
Type: KeyOutput{},
}
var keyExportCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Export a keypair",
ShortDescription: `
Exports a named libp2p key to disk.
By default, the output will be stored at './<key-name>.key', but an alternate
path can be specified with '--output=<path>' or '-o=<path>'.
`,
},
Arguments: []cmds.Argument{
cmds.StringArg("name", true, false, "name of key to export").EnableStdin(),
},
Options: []cmds.Option{
cmds.StringOption(outputOptionName, "o", "The path where the output should be stored."),
},
NoRemote: true,
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
name := req.Arguments[0]
if name == "self" {
return fmt.Errorf("cannot export key with name 'self'")
}
cfgRoot, err := cmdenv.GetConfigRoot(env)
if err != nil {
return err
}
// Check repo version, and error out if not matching
ver, err := migrations.RepoVersion(cfgRoot)
if err != nil {
return err
}
if ver != fsrepo.RepoVersion {
return fmt.Errorf("key export expects repo version (%d) but found (%d)", fsrepo.RepoVersion, ver)
}
// Export is read-only: safe to read it without acquiring repo lock
// (this makes export work when ipfs daemon is already running)
ksp := filepath.Join(cfgRoot, "keystore")
ks, err := keystore.NewFSKeystore(ksp)
if err != nil {
return err
}
sk, err := ks.Get(name)
if err != nil {
return fmt.Errorf("key with name '%s' doesn't exist", name)
}
encoded, err := crypto.MarshalPrivateKey(sk)
if err != nil {
return err
}
return res.Emit(bytes.NewReader(encoded))
},
PostRun: cmds.PostRunMap{
cmds.CLI: func(res cmds.Response, re cmds.ResponseEmitter) error {
req := res.Request()
v, err := res.Next()
if err != nil {
return err
}
outReader, ok := v.(io.Reader)
if !ok {
return e.New(e.TypeErr(outReader, v))
}
outPath, _ := req.Options[outputOptionName].(string)
if outPath == "" {
trimmed := strings.TrimRight(fmt.Sprintf("%s.key", req.Arguments[0]), "/")
_, outPath = filepath.Split(trimmed)
outPath = filepath.Clean(outPath)
}
// create file
file, err := os.Create(outPath)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(file, outReader)
if err != nil {
return err
}
return nil
},
},
}
var keyImportCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Import a key and prints imported key id",
},
Options: []cmds.Option{
ke.OptionIPNSBase,
},
Arguments: []cmds.Argument{
cmds.StringArg("name", true, false, "name to associate with key in keychain"),
cmds.FileArg("key", true, false, "key provided by generate or export"),
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
name := req.Arguments[0]
if name == "self" {
return fmt.Errorf("cannot import key with name 'self'")
}
keyEnc, err := ke.KeyEncoderFromString(req.Options[ke.OptionIPNSBase.Name()].(string))
if err != nil {
return err
}
file, err := cmdenv.GetFileArg(req.Files.Entries())
if err != nil {
return err
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
return err
}
sk, err := crypto.UnmarshalPrivateKey(data)
if err != nil {
return err
}
cfgRoot, err := cmdenv.GetConfigRoot(env)
if err != nil {
return err
}
r, err := fsrepo.Open(cfgRoot)
if err != nil {
return err
}
defer r.Close()
_, err = r.Keystore().Get(name)
if err == nil {
return fmt.Errorf("key with name '%s' already exists", name)
}
err = r.Keystore().Put(name, sk)
if err != nil {
return err
}
pid, err := peer.IDFromPrivateKey(sk)
if err != nil {
return err
}
return cmds.EmitOnce(res, &KeyOutput{
Name: name,
Id: keyEnc.FormatID(pid),
})
},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, ko *KeyOutput) error {
_, err := w.Write([]byte(ko.Id + "\n"))
return err
}),
},
Type: KeyOutput{},
}
var keyListCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "List all local keypairs.",
},
Options: []cmds.Option{
cmds.BoolOption("l", "Show extra information about keys."),
ke.OptionIPNSBase,
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
keyEnc, err := ke.KeyEncoderFromString(req.Options[ke.OptionIPNSBase.Name()].(string))
if err != nil {
return err
}
api, err := cmdenv.GetApi(env, req)
if err != nil {
return err
}
keys, err := api.Key().List(req.Context)
if err != nil {
return err
}
list := make([]KeyOutput, 0, len(keys))
for _, key := range keys {
list = append(list, KeyOutput{
Name: key.Name(),
Id: keyEnc.FormatID(key.ID()),
})
}
return cmds.EmitOnce(res, &KeyOutputList{list})
},
Encoders: cmds.EncoderMap{
cmds.Text: keyOutputListEncoders(),
},
Type: KeyOutputList{},
}
const (
keyStoreForceOptionName = "force"
)
var keyRenameCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Rename a keypair.",
},
Arguments: []cmds.Argument{
cmds.StringArg("name", true, false, "name of key to rename"),
cmds.StringArg("newName", true, false, "new name of the key"),
},
Options: []cmds.Option{
cmds.BoolOption(keyStoreForceOptionName, "f", "Allow to overwrite an existing key."),
ke.OptionIPNSBase,
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
api, err := cmdenv.GetApi(env, req)
if err != nil {
return err
}
keyEnc, err := ke.KeyEncoderFromString(req.Options[ke.OptionIPNSBase.Name()].(string))
if err != nil {
return err
}
name := req.Arguments[0]
newName := req.Arguments[1]
force, _ := req.Options[keyStoreForceOptionName].(bool)
key, overwritten, err := api.Key().Rename(req.Context, name, newName, options.Key.Force(force))
if err != nil {
return err
}
return cmds.EmitOnce(res, &KeyRenameOutput{
Was: name,
Now: newName,
Id: keyEnc.FormatID(key.ID()),
Overwrite: overwritten,
})
},
Encoders: cmds.EncoderMap{
cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, kro *KeyRenameOutput) error {
if kro.Overwrite {
fmt.Fprintf(w, "Key %s renamed to %s with overwriting\n", kro.Id, cmdenv.EscNonPrint(kro.Now))
} else {
fmt.Fprintf(w, "Key %s renamed to %s\n", kro.Id, cmdenv.EscNonPrint(kro.Now))
}
return nil
}),
},
Type: KeyRenameOutput{},
}
var keyRmCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Remove a keypair.",
},
Arguments: []cmds.Argument{
cmds.StringArg("name", true, true, "names of keys to remove").EnableStdin(),
},
Options: []cmds.Option{
cmds.BoolOption("l", "Show extra information about keys."),
ke.OptionIPNSBase,
},
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
api, err := cmdenv.GetApi(env, req)
if err != nil {
return err
}
keyEnc, err := ke.KeyEncoderFromString(req.Options[ke.OptionIPNSBase.Name()].(string))
if err != nil {
return err
}
names := req.Arguments
list := make([]KeyOutput, 0, len(names))
for _, name := range names {
key, err := api.Key().Remove(req.Context, name)
if err != nil {
return err
}
list = append(list, KeyOutput{
Name: name,
Id: keyEnc.FormatID(key.ID()),
})
}
return cmds.EmitOnce(res, &KeyOutputList{list})
},
Encoders: cmds.EncoderMap{
cmds.Text: keyOutputListEncoders(),
},
Type: KeyOutputList{},
}
var keyRotateCmd = &cmds.Command{
Helptext: cmds.HelpText{
Tagline: "Rotates the IPFS identity.",
ShortDescription: `
Generates a new ipfs identity and saves it to the ipfs config file.
Your existing identity key will be backed up in the Keystore.
The daemon must not be running when calling this command.
ipfs uses a repository in the local file system. By default, the repo is
located at ~/.ipfs. To change the repo location, set the $IPFS_PATH
environment variable:
export IPFS_PATH=/path/to/ipfsrepo
`,
},
Arguments: []cmds.Argument{},
Options: []cmds.Option{
cmds.StringOption(oldKeyOptionName, "o", "Keystore name to use for backing up your existing identity"),
cmds.StringOption(keyStoreTypeOptionName, "t", "type of the key to create: rsa, ed25519").WithDefault(keyStoreAlgorithmDefault),
cmds.IntOption(keyStoreSizeOptionName, "s", "size of the key to generate"),
},
NoRemote: true,
PreRun: DaemonNotRunning,
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
cctx := env.(*oldcmds.Context)
nBitsForKeypair, nBitsGiven := req.Options[keyStoreSizeOptionName].(int)
algorithm, _ := req.Options[keyStoreTypeOptionName].(string)
oldKey, ok := req.Options[oldKeyOptionName].(string)
if !ok {
return fmt.Errorf("keystore name for backing up old key must be provided")
}
if oldKey == "self" {
return fmt.Errorf("keystore name for back up cannot be named 'self'")
}
return doRotate(os.Stdout, cctx.ConfigRoot, oldKey, algorithm, nBitsForKeypair, nBitsGiven)
},
}
func doRotate(out io.Writer, repoRoot string, oldKey string, algorithm string, nBitsForKeypair int, nBitsGiven bool) error {
// Open repo
repo, err := fsrepo.Open(repoRoot)
if err != nil {
return fmt.Errorf("opening repo (%v)", err)
}
defer repo.Close()
// Read config file from repo
cfg, err := repo.Config()
if err != nil {
return fmt.Errorf("reading config from repo (%v)", err)
}
// Generate new identity
var identity config.Identity
if nBitsGiven {
identity, err = config.CreateIdentity(out, []options.KeyGenerateOption{
options.Key.Size(nBitsForKeypair),
options.Key.Type(algorithm),
})
} else {
identity, err = config.CreateIdentity(out, []options.KeyGenerateOption{
options.Key.Type(algorithm),
})
}
if err != nil {
return fmt.Errorf("creating identity (%v)", err)
}
// Save old identity to keystore
oldPrivKey, err := cfg.Identity.DecodePrivateKey("")
if err != nil {
return fmt.Errorf("decoding old private key (%v)", err)
}
keystore := repo.Keystore()
if err := keystore.Put(oldKey, oldPrivKey); err != nil {
return fmt.Errorf("saving old key in keystore (%v)", err)
}
// Update identity
cfg.Identity = identity
// Write config file to repo
if err = repo.SetConfig(cfg); err != nil {
return fmt.Errorf("saving new key to config (%v)", err)
}
return nil
}
func keyOutputListEncoders() cmds.EncoderFunc {
return cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, list *KeyOutputList) error {
withID, _ := req.Options["l"].(bool)
tw := tabwriter.NewWriter(w, 1, 2, 1, ' ', 0)
for _, s := range list.Keys {
if withID {
fmt.Fprintf(tw, "%s\t%s\t\n", s.Id, cmdenv.EscNonPrint(s.Name))
} else {
fmt.Fprintf(tw, "%s\n", cmdenv.EscNonPrint(s.Name))
}
}
tw.Flush()
return nil
})
}
// DaemonNotRunning checks to see if the ipfs repo is locked, indicating that
// the daemon is running, and returns and error if the daemon is running.
func DaemonNotRunning(req *cmds.Request, env cmds.Environment) error {
cctx := env.(*oldcmds.Context)
daemonLocked, err := fsrepo.LockedByOtherProcess(cctx.ConfigRoot)
if err != nil {
return err
}
log.Info("checking if daemon is running...")
if daemonLocked {
log.Debug("ipfs daemon is running")
e := "ipfs daemon is running. please stop it to run this command"
return cmds.ClientError(e)
}
return nil
}