-
Notifications
You must be signed in to change notification settings - Fork 1
/
hsm.go
279 lines (237 loc) · 7.36 KB
/
hsm.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
package cli
import (
"fmt"
"os"
"strings"
"time"
"github.com/effective-security/x/fileutil"
"github.com/effective-security/x/guid"
"github.com/effective-security/xpki/cryptoprov"
"github.com/effective-security/xpki/csr"
"github.com/effective-security/xpki/x/print"
"github.com/pkg/errors"
)
// HsmCmd is the parent for HSM command
type HsmCmd struct {
List HsmLsKeyCmd `cmd:"" help:"list keys"`
Info HsmKeyInfoCmd `cmd:"" help:"print key information"`
Generate HsmGenKeyCmd `cmd:"" help:"generate key"`
Remove HsmRmKeyCmd `cmd:"" help:"delete key"`
}
// HsmLsKeyCmd prints Keys
type HsmLsKeyCmd struct {
Token string `help:"specifies slot token (optional)"`
Serial string `help:"specifies slot serial (optional)"`
Prefix string `help:"specifies key label prefix (optional)"`
}
const skipSerial = "--@--"
// Run the command
func (a *HsmLsKeyCmd) Run(ctx *Cli) error {
_, defprov := ctx.CryptoProv()
keyProv, ok := defprov.(cryptoprov.KeyManager)
if !ok {
return errors.Errorf("unsupported command for this crypto provider")
}
isDefaultSlot := a.Serial == "" && a.Token == ""
filterSerial := a.Serial
if filterSerial == "" {
filterSerial = skipSerial
}
filterLabel := a.Token
if filterLabel == "" {
filterLabel = skipSerial
}
out := ctx.Writer()
tokens, err := keyProv.EnumTokens(isDefaultSlot)
if err != nil {
return errors.WithMessagef(err, "failed to list tokens")
}
printIfNotEmpty := func(label, val string) {
if val != "" {
fmt.Fprintf(out, "%s: %s\n", label, val)
}
}
for _, token := range tokens {
if isDefaultSlot || token.Serial == filterSerial || token.Label == filterLabel {
fmt.Fprintf(out, "Slot: %d\n", token.SlotID)
printIfNotEmpty(" Manufacturer", token.Manufacturer)
printIfNotEmpty(" Model", token.Model)
printIfNotEmpty(" Description", token.Description)
printIfNotEmpty(" Token serial", token.Serial)
printIfNotEmpty(" Token label", token.Label)
keys, err := keyProv.EnumKeys(token.SlotID, a.Prefix)
if err != nil {
return errors.WithMessagef(err, "failed to list keys on slot %d", token.SlotID)
}
if a.Prefix != "" && len(keys) == 0 {
fmt.Fprintf(out, "no keys found with prefix: %s\n", a.Prefix)
}
for i, key := range keys {
fmt.Fprintf(out, "[%d]\n", i)
fmt.Fprintf(out, " Id: %s\n", key.ID)
printIfNotEmpty(" Label", key.Label)
printIfNotEmpty(" Type", key.Type)
printIfNotEmpty(" Class", key.Class)
printIfNotEmpty(" Version", key.CurrentVersionID)
if key.CreationTime != nil {
fmt.Fprintf(out, " Created: %s\n", key.CreationTime.Format(time.RFC3339))
}
for k, v := range key.Meta {
fmt.Fprintf(out, " %s: %s\n", k, v)
}
}
}
}
return nil
}
// HsmKeyInfoCmd prints the key info
type HsmKeyInfoCmd struct {
ID string `kong:"arg" required:"" help:"key ID"`
Token string `help:"slot token (optional)"`
Serial string `help:"slot serial (optional)"`
Public bool `help:"print Public Key"`
}
// Run the command
func (a *HsmKeyInfoCmd) Run(ctx *Cli) error {
_, defprov := ctx.CryptoProv()
keyProv, ok := defprov.(cryptoprov.KeyManager)
if !ok {
return errors.Errorf("unsupported command for this crypto provider")
}
filterSerial := a.Serial
isDefaultSlot := filterSerial == ""
if isDefaultSlot {
filterSerial = "--@--"
}
out := ctx.Writer()
tokens, err := keyProv.EnumTokens(isDefaultSlot)
if err != nil {
return errors.WithMessagef(err, "failed to list tokens")
}
printIfNotEmpty := func(label, val string) {
if val != "" {
fmt.Fprintf(out, " %s: %s\n", label, val)
}
}
for _, token := range tokens {
if isDefaultSlot || token.Serial == filterSerial {
fmt.Fprintf(out, "Slot: %d\n", token.SlotID)
fmt.Fprintf(out, " Description: %s\n", token.Description)
fmt.Fprintf(out, " Token serial: %s\n", token.Serial)
key, err := keyProv.KeyInfo(token.SlotID, a.ID, a.Public)
if err != nil {
return errors.WithMessagef(err, "failed to get key on slot %d", token.SlotID)
}
fmt.Fprintf(out, " Id: %s\n", key.ID)
printIfNotEmpty(" Label", key.Label)
printIfNotEmpty(" Type", key.Type)
printIfNotEmpty(" Class", key.Class)
printIfNotEmpty(" Version", key.CurrentVersionID)
if key.CreationTime != nil {
fmt.Fprintf(out, " Created: %s\n", key.CreationTime.Format(time.RFC3339))
}
for k, v := range key.Meta {
fmt.Fprintf(out, " %s: %s\n", k, v)
}
if key.PublicKey != "" {
fmt.Fprintf(out, " Public key: \n%s\n", key.PublicKey)
}
}
}
return nil
}
// HsmGenKeyCmd generates key
type HsmGenKeyCmd struct {
Algo string `required:"" help:"algorithm: RSA|ECDSA"`
Size int `required:"" help:"key size in bits"`
Purpose string `required:"" help:"purpose of the key: SIGN|ENCRYPT"`
Label string `required:"" help:"name for generated key"`
Output string `help:"location to write the key, if not set, the output will be printed to STDOUT only"`
Force bool `help:"force to override key file if exists"`
}
// Run the command
func (a *HsmGenKeyCmd) Run(ctx *Cli) error {
if !a.Force && fileutil.FileExists(a.Output) == nil {
return errors.Errorf("%q file exists, specify --force flag to override", a.Output)
}
_, crypto := ctx.CryptoProv()
prov := csr.NewProvider(crypto)
var purpose csr.KeyPurpose
switch strings.ToLower(a.Purpose) {
case "s", "sign", "signing":
purpose = csr.SigningKey
case "e", "encrypt", "encryption":
purpose = csr.EncryptionKey
default:
return errors.Errorf("unsupported purpose: %q", a.Purpose)
}
req := prov.NewKeyRequest(prefixKeyLabel(a.Label), a.Algo, a.Size, purpose)
prv, err := req.Generate()
if err != nil {
return err
}
keyID, _, err := crypto.IdentifyKey(prv)
if err != nil {
return err
}
uri, key, err := crypto.ExportKey(keyID)
if err != nil {
return err
}
if key == nil {
key = []byte(uri)
}
if a.Output == "" {
print.CertAndKey(ctx.Writer(), key, nil, nil)
} else {
err = os.WriteFile(a.Output, key, 0600)
if err != nil {
return errors.WithStack(err)
}
}
return nil
}
// HsmRmKeyCmd deletes key
type HsmRmKeyCmd struct {
ID string `kong:"arg" required:"" help:"specifies key ID"`
Token string `help:"specifies slot token (optional)"`
Serial string `help:"specifies slot serial (optional)"`
}
// Run the command
func (a *HsmRmKeyCmd) Run(ctx *Cli) error {
_, defprov := ctx.CryptoProv()
keyProv, ok := defprov.(cryptoprov.KeyManager)
if !ok {
return errors.Errorf("unsupported command for this crypto provider")
}
filterSerial := a.Serial
isDefaultSlot := a.Serial == ""
if isDefaultSlot {
filterSerial = "--@--"
}
tokens, err := keyProv.EnumTokens(isDefaultSlot)
if err != nil {
return errors.WithMessagef(err, "failed to list tokens")
}
for _, token := range tokens {
if isDefaultSlot || token.Serial == filterSerial {
err := keyProv.DestroyKeyPairOnSlot(token.SlotID, a.ID)
if err != nil {
return errors.WithMessagef(err, "unable to destroy key %q on slot %d", a.ID, token.SlotID)
}
fmt.Fprintf(ctx.Writer(), "destroyed key: %s\n", a.ID)
return nil
}
}
return nil
}
// prefixKeyLabel adds a date prefix to label for a key
func prefixKeyLabel(label string) string {
if strings.HasSuffix(label, "*") {
g := guid.MustCreate()
t := time.Now().UTC()
label = strings.TrimSuffix(label, "*") +
fmt.Sprintf("_%04d%02d%02d%02d%02d%02d_%x", t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), g[:4])
}
return label
}