forked from keycard-tech/keycard-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
424 lines (362 loc) · 9.55 KB
/
main.go
File metadata and controls
424 lines (362 loc) · 9.55 KB
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
package main
import (
"bufio"
"context"
"encoding/hex"
"errors"
"fmt"
"log/slog"
"os"
"strconv"
"strings"
"github.com/ebfe/scard"
"github.com/ethereum/go-ethereum/crypto"
"github.com/ethereum/go-ethereum/log"
"github.com/urfave/cli/v3"
)
var version string
type commandFunc func(*scard.Card) error
var logger log.Logger
func initLogger(logLevel string) {
if logLevel == "" {
logLevel = "info"
}
var level slog.Level
switch strings.ToLower(logLevel) {
case "debug":
level = log.LevelDebug
case "info":
level = log.LevelInfo
case "warn":
level = log.LevelWarn
case "error":
level = log.LevelError
default:
// Set up a basic logger first to ensure we can log the error
handler := log.NewTerminalHandlerWithLevel(os.Stderr, log.LevelError, true)
log.SetDefault(log.NewLogger(handler))
logger = log.New("package", "keycard-cli")
log.Error("invalid log level", "level", logLevel)
return
}
handler := log.NewTerminalHandlerWithLevel(os.Stderr, level, true)
log.SetDefault(log.NewLogger(handler))
logger = log.New("package", "keycard-cli")
}
func main() {
app := &cli.Command{
Name: "keycard",
Usage: "Keycard CLI tool",
Version: version,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "log-level",
Aliases: []string{"l"},
Value: "info",
Usage: `Log level, one of: "error", "warn", "info" and "debug"`,
},
},
Before: func(ctx context.Context, cmd *cli.Command) (context.Context, error) {
initLogger(cmd.String("log-level"))
return ctx, nil
},
Commands: []*cli.Command{
{
Name: "version",
Usage: "Show version information",
Action: cliCommandVersion,
},
{
Name: "install",
Usage: "Install applets to the card",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "applet-file",
Aliases: []string{"a"},
Usage: "applet cap file path",
Required: true,
},
&cli.BoolFlag{
Name: "keycard-applet",
Usage: "install keycard applet",
Value: true,
},
&cli.BoolFlag{
Name: "cash-applet",
Usage: "install cash applet",
Value: true,
},
&cli.BoolFlag{
Name: "ndef-applet",
Usage: "install NDEF applet",
Value: true,
},
&cli.BoolFlag{
Name: "force",
Aliases: []string{"f"},
Usage: "force applet installation if already installed",
},
&cli.StringFlag{
Name: "ndef",
Usage: "Specify a URL to use in the NDEF record. Use the {{.cashAddress}} variable to get the cash address: http://example.com/{{.cashAddress}}.",
},
},
Action: cliCommandInstall,
},
{
Name: "info",
Usage: "Show card information",
Action: cliCommandInfo,
},
{
Name: "delete",
Usage: "Delete applets from the card",
Action: cliCommandDelete,
},
{
Name: "init",
Usage: "Initialize the card",
Action: cliCommandInit,
},
{
Name: "shell",
Usage: "Start interactive shell",
Action: cliCommandShell,
},
},
}
if err := app.Run(context.Background(), os.Args); err != nil {
log.Error("application error", "error", err)
}
}
func fail(msg string, ctx ...interface{}) {
logger.Error(msg, ctx...)
os.Exit(1)
}
func waitForCard(ctx *scard.Context, readers []string) (int, error) {
rs := make([]scard.ReaderState, len(readers))
for i := range rs {
rs[i].Reader = readers[i]
rs[i].CurrentState = scard.StateUnaware
}
for {
for i := range rs {
if rs[i].EventState&scard.StatePresent != 0 {
return i, nil
}
rs[i].CurrentState = rs[i].EventState
}
err := ctx.GetStatusChange(rs, -1)
if err != nil {
return -1, err
}
}
}
func connectToCard() (*scard.Card, func(), error) {
ctx, err := scard.EstablishContext()
if err != nil {
return nil, nil, fmt.Errorf("error establishing card context: %w", err)
}
readers, err := ctx.ListReaders()
if err != nil {
ctx.Release()
return nil, nil, fmt.Errorf("error getting readers: %w", err)
}
logger.Info("waiting for a card")
if len(readers) == 0 {
ctx.Release()
return nil, nil, errors.New("no smartcard reader found")
}
index, err := waitForCard(ctx, readers)
if err != nil {
ctx.Release()
return nil, nil, fmt.Errorf("error waiting for card: %w", err)
}
logger.Info("card found", "index", index)
reader := readers[index]
logger.Debug("using reader", "name", reader)
logger.Debug("connecting to card", "reader", reader)
card, err := ctx.Connect(reader, scard.ShareShared, scard.ProtocolAny)
if err != nil {
ctx.Release()
return nil, nil, fmt.Errorf("error connecting to card: %w", err)
}
status, err := card.Status()
if err != nil {
card.Disconnect(scard.ResetCard)
ctx.Release()
return nil, nil, fmt.Errorf("error getting card status: %w", err)
}
switch status.ActiveProtocol {
case scard.ProtocolT0:
logger.Debug("card protocol", "T", "0")
case scard.ProtocolT1:
logger.Debug("card protocol", "T", "1")
default:
logger.Debug("card protocol", "T", "unknown")
}
cleanup := func() {
if err := card.Disconnect(scard.ResetCard); err != nil {
logger.Error("error disconnecting card", "error", err)
}
if err := ctx.Release(); err != nil {
logger.Error("error releasing context", "error", err)
}
}
return card, cleanup, nil
}
func cliCommandVersion(ctx context.Context, cmd *cli.Command) error {
return commandVersion(nil)
}
func cliCommandInstall(ctx context.Context, cmd *cli.Command) error {
card, cleanup, err := connectToCard()
if err != nil {
return err
}
defer cleanup()
capFile := cmd.String("applet-file")
if capFile == "" {
return errors.New("you must specify a cap file path with the -a flag")
}
f, err := os.Open(capFile)
if err != nil {
return fmt.Errorf("error opening cap file: %w", err)
}
defer f.Close()
i := NewInstaller(card)
return i.Install(f, cmd.Bool("force"), cmd.Bool("keycard-applet"), cmd.Bool("cash-applet"), cmd.Bool("ndef-applet"), cmd.String("ndef"))
}
func cliCommandInfo(ctx context.Context, cmd *cli.Command) error {
card, cleanup, err := connectToCard()
if err != nil {
return err
}
defer cleanup()
return commandInfo(card)
}
func cliCommandDelete(ctx context.Context, cmd *cli.Command) error {
card, cleanup, err := connectToCard()
if err != nil {
return err
}
defer cleanup()
return commandDelete(card)
}
func cliCommandInit(ctx context.Context, cmd *cli.Command) error {
card, cleanup, err := connectToCard()
if err != nil {
return err
}
defer cleanup()
return commandInit(card)
}
func cliCommandShell(ctx context.Context, cmd *cli.Command) error {
card, cleanup, err := connectToCard()
if err != nil {
return err
}
defer cleanup()
return commandShell(card)
}
func ask(description string) string {
r := bufio.NewReader(os.Stdin)
fmt.Printf("%s: ", description)
text, err := r.ReadString('\n')
if err != nil {
log.Error("error reading input", "error", err)
}
return strings.TrimSpace(text)
}
func askHex(description string) []byte {
s := ask(description)
if s[:2] == "0x" {
s = s[2:]
}
data, err := hex.DecodeString(s)
if err != nil {
log.Error("error decoding hex", "error", err)
}
return data
}
func askInt(description string) int {
s := ask(description)
i, err := strconv.ParseInt(s, 10, 8)
if err != nil {
log.Error("error parsing integer", "error", err)
}
return int(i)
}
func commandVersion(card *scard.Card) error {
fmt.Printf("version %+v\n", version)
return nil
}
func commandInfo(card *scard.Card) error {
i := NewInitializer(card)
info, cashInfo, err := i.Info()
if err != nil {
return err
}
var keyInitialized bool
if len(info.KeyUID) > 0 {
keyInitialized = true
}
fmt.Printf("Keycard Applet:\n")
fmt.Printf(" Installed: %+v\n", info.Installed)
fmt.Printf(" Initialized: %+v\n", info.Initialized)
fmt.Printf(" Key Initialized: %+v\n", keyInitialized)
fmt.Printf(" InstanceUID: 0x%x\n", info.InstanceUID)
fmt.Printf(" SecureChannelPublicKey: 0x%x\n", info.SecureChannelPublicKey)
fmt.Printf(" Version: 0x%x\n", info.Version)
fmt.Printf(" AvailableSlots: 0x%x\n", info.AvailableSlots)
fmt.Printf(" KeyUID: 0x%x\n", info.KeyUID)
fmt.Printf(" Capabilities:\n")
fmt.Printf(" Secure channel:%v\n", info.HasSecureChannelCapability())
fmt.Printf(" Key management:%v\n", info.HasKeyManagementCapability())
fmt.Printf(" Credentials Management:%v\n", info.HasCredentialsManagementCapability())
fmt.Printf(" NDEF:%v\n", info.HasNDEFCapability())
fmt.Printf("Cash Applet:\n")
if len(cashInfo.PublicKey) == 0 {
fmt.Printf(" Installed: %+v\n", false)
return nil
}
ecdsaPubKey, err := crypto.UnmarshalPubkey(cashInfo.PublicKey)
if err != nil {
return err
}
cashAddress := crypto.PubkeyToAddress(*ecdsaPubKey)
fmt.Printf(" Installed: %+v\n", cashInfo.Installed)
fmt.Printf(" PublicKey: 0x%x\n", cashInfo.PublicKey)
fmt.Printf(" Address: 0x%x\n", cashAddress)
fmt.Printf(" Public Data: 0x%x\n", cashInfo.PublicData)
fmt.Printf(" Version: 0x%x\n", cashInfo.Version)
return nil
}
func commandDelete(card *scard.Card) error {
i := NewInstaller(card)
err := i.Delete()
if err != nil {
return err
}
fmt.Printf("applet deleted\n")
return nil
}
func commandInit(card *scard.Card) error {
i := NewInitializer(card)
secrets, err := i.Init()
if err != nil {
return err
}
fmt.Printf("PIN %s\n", secrets.Pin())
fmt.Printf("PUK %s\n", secrets.Puk())
fmt.Printf("Pairing password: %s\n", secrets.PairingPass())
return nil
}
func commandShell(card *scard.Card) error {
fi, _ := os.Stdin.Stat()
if (fi.Mode() & os.ModeCharDevice) == 0 {
s := NewShell(card)
return s.Run()
} else {
return errors.New("non interactive shell. you must pipe commands")
}
}