/
rekey.go
90 lines (76 loc) · 2.27 KB
/
rekey.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
package vault
import (
"fmt"
"os"
"os/signal"
"syscall"
"github.com/cloudfoundry-community/vaultkv"
"github.com/jhunt/go-ansi"
"github.com/menta2l/secret-helper/prompt"
"golang.org/x/crypto/ssh/terminal"
)
var termState *terminal.State
func (v *Vault) cancelRekey() {
if termState != nil {
terminal.Restore(int(os.Stdin.Fd()), termState)
}
err := v.client.Client.RekeyCancel()
if err != nil {
ansi.Fprintf(os.Stderr, "Failed to cancel rekey process: %s\n", err.Error())
return
}
ansi.Fprintf(os.Stderr, "@y{Vault rekey canceled successfully}\n")
}
func (v *Vault) ReKey(unsealKeyCount, numToUnseal int, pgpKeys []string) ([]string, error) {
err := v.client.Client.RekeyCancel()
if err != nil {
return nil, fmt.Errorf("An error occurred when trying to cancel potentially preexisting rekey: %s", err)
}
backup := len(pgpKeys) > 0
rekey, err := v.client.Client.NewRekey(vaultkv.RekeyConfig{
Shares: unsealKeyCount,
Threshold: numToUnseal,
PGPKeys: pgpKeys,
Backup: backup,
})
if err != nil {
return nil, fmt.Errorf("An error occurred when starting a new rekey operation: %s", err)
}
// we successfully started a rekey, we should now cancel on failure, unless we finish rekeying
var shouldCancelRekey = true
defer func() {
if shouldCancelRekey {
v.cancelRekey()
}
}()
sighandler := make(chan os.Signal, 4)
signal.Ignore(os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
signal.Notify(sighandler, os.Interrupt, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT)
go func() {
for _ = range sighandler {
v.cancelRekey()
os.Exit(1)
}
}()
if terminal.IsTerminal(int(os.Stdin.Fd())) {
termState, err = terminal.GetState(int(os.Stdin.Fd()))
if err != nil {
return nil, err
}
}
givenKeys := make([]string, rekey.Remaining())
for i := 0; i < len(givenKeys); i++ {
givenKeys[i] = prompt.Secure("Unseal Key %d: ", i+1)
}
rekeyDone, err := rekey.Submit(givenKeys...)
if err != nil {
return nil, fmt.Errorf("Key submission failed: %s", err)
}
if !rekeyDone {
return nil, fmt.Errorf("The rekey did not finish (is somebody else trying to rekey at the same time?)")
}
// vault should be rekeyed by here, as our progress met the requirement
shouldCancelRekey = false
signal.Stop(sighandler)
return rekey.Keys(), nil
}