forked from FiloSottile/yubikey-agent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
408 lines (367 loc) · 10.1 KB
/
main.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
// Copyright 2020 Google LLC
//
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file or at
// https://developers.google.com/open-source/licenses/bsd
package main
import (
"bytes"
"context"
"crypto/ecdsa"
"crypto/rand"
"crypto/rsa"
"errors"
"flag"
"fmt"
"io"
"io/ioutil"
"log"
"net"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strings"
"strconv"
"sync"
"syscall"
"time"
"github.com/sgrb/piv-go/piv"
"golang.org/x/crypto/ssh"
"golang.org/x/crypto/ssh/agent"
"golang.org/x/crypto/ssh/terminal"
)
func main() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage of yubikey-agent:\n")
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintf(os.Stderr, "\tyubikey-agent -setup\n")
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintf(os.Stderr, "\t\tGenerate a new SSH key on the attached YubiKey.\n")
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintf(os.Stderr, "\tyubikey-agent -l PATH [-p pinfile] [-s slot,slot,...]\n")
fmt.Fprintf(os.Stderr, "\n")
fmt.Fprintf(os.Stderr, "\t\tRun the agent, listening on the UNIX socket at PATH.\n")
fmt.Fprintf(os.Stderr, "\n")
}
socketPath := flag.String("l", "", "agent: path of the UNIX socket to listen on")
resetFlag := flag.Bool("really-delete-all-piv-keys", false, "setup: reset the PIV applet")
setupFlag := flag.Bool("setup", false, "setup: configure a new YubiKey")
pinPath := flag.String("p", "", "file with pin")
slots := flag.String("s", "", "slots to use")
flag.Parse()
if flag.NArg() > 0 {
flag.Usage()
os.Exit(1)
}
if *setupFlag {
log.SetFlags(0)
yk := connectForSetup()
if *resetFlag {
runReset(yk)
}
runSetup(yk)
} else {
var pin string = ""
if *pinPath != "" {
bpin, err := ioutil.ReadFile(*pinPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to read pin from file: %v", err)
os.Exit(1)
}
pin = strings.TrimSpace(string(bpin))
}
if *socketPath == "" {
flag.Usage()
os.Exit(1)
}
var slotsNums []uint32
if len(*slots) > 0 {
items := strings.Split(*slots, ",")
for _, i := range items {
s, err := strconv.ParseInt(i, 16, 32)
if (err != nil) {
fmt.Fprintf(os.Stderr, "Bad slot %v: %v", i, err)
os.Exit(1)
}
slotsNums = append(slotsNums, uint32(s))
}
}
runAgent(*socketPath, slotsNums, pin)
}
}
func runAgent(socketPath string, slotsNum []uint32, pin string) {
if terminal.IsTerminal(int(os.Stdin.Fd())) {
log.Println("Warning: yubikey-agent is meant to run as a background daemon.")
log.Println("Running multiple instances is likely to lead to conflicts.")
log.Println("Consider using the launchd or systemd services.")
}
var slots []piv.Slot
if len(slotsNum) > 0 {
for _, i := range slotsNum {
slots = append(slots, makeSlot(i))
}
} else {
slots = defaultSlots
}
a := &Agent{PIN: pin, slots: slots}
c := make(chan os.Signal)
signal.Notify(c, syscall.SIGHUP)
go func() {
for range c {
a.Close()
}
}()
os.Remove(socketPath)
if err := os.MkdirAll(filepath.Dir(socketPath), 0777); err != nil {
log.Fatalln("Failed to create UNIX socket folder:", err)
}
l, err := net.Listen("unix", socketPath)
if err != nil {
log.Fatalln("Failed to listen on UNIX socket:", err)
}
for {
c, err := l.Accept()
if err != nil {
type temporary interface {
Temporary() bool
}
if err, ok := err.(temporary); ok && err.Temporary() {
log.Println("Temporary Accept error, sleeping 1s:", err)
time.Sleep(1 * time.Second)
continue
}
log.Fatalln("Failed to accept connections:", err)
}
go a.serveConn(c)
}
}
var defaultSlots = []piv.Slot{
piv.SlotAuthentication,
piv.SlotCardAuthentication,
piv.SlotKeyManagement,
piv.SlotSignature,
}
func makeSlot(num uint32) piv.Slot {
return piv.Slot{num, 0x5FC10D + (num - 0x82)}
}
type Agent struct {
mu sync.Mutex
yk *piv.YubiKey
serial uint32
PIN string
slots []piv.Slot
// touchNotification is armed by Sign to show a notification if waiting for
// more than a few seconds for the touch operation. It is paused and reset
// by getPIN so it won't fire while waiting for the PIN.
touchNotification *time.Timer
}
var _ agent.ExtendedAgent = &Agent{}
func (a *Agent) serveConn(c net.Conn) {
defer a.Close()
if err := agent.ServeAgent(a, c); err != io.EOF {
log.Println("Agent client connection ended with error:", err)
}
}
func healthy(yk *piv.YubiKey) bool {
// We can't use Serial because it locks the session on older firmwares, and
// can't use Retries because it fails when the session is unlocked.
_, err := yk.AttestationCertificate()
return err == nil
}
func (a *Agent) ensureYK() error {
if a.yk == nil || !healthy(a.yk) {
if a.yk != nil {
log.Println("Reconnecting to the YubiKey...")
a.yk.Close()
} else {
log.Println("Connecting to the YubiKey...")
}
yk, err := a.connectToYK()
if err != nil {
return err
}
a.yk = yk
}
return nil
}
func (a *Agent) connectToYK() (*piv.YubiKey, error) {
cards, err := piv.Cards()
if err != nil {
return nil, err
}
if len(cards) == 0 {
return nil, errors.New("no YubiKey detected")
}
// TODO: support multiple YubiKeys.
var client piv.Client
client.Shared = true
yk, err := client.Open(cards[0])
if err != nil {
return nil, err
}
// Cache the serial number locally because requesting it on older firmwares
// requires switching application, which drops the PIN cache.
a.serial, _ = yk.Serial()
return yk, nil
}
func (a *Agent) Close() error {
a.mu.Lock()
defer a.mu.Unlock()
if a.yk != nil {
err := a.yk.Close()
a.yk = nil
return err
}
return nil
}
func (a *Agent) getPIN() (string, error) {
if a.touchNotification != nil && a.touchNotification.Stop() {
defer a.touchNotification.Reset(5 * time.Second)
}
r, _ := a.yk.Retries()
return getPIN(a.serial, r)
}
func (a *Agent) List() ([]*agent.Key, error) {
a.mu.Lock()
defer a.mu.Unlock()
if err := a.ensureYK(); err != nil {
return nil, fmt.Errorf("could not reach YubiKey: %w", err)
}
var keys []*agent.Key
for _, slot := range a.slots {
var pk ssh.PublicKey
var err error
pk, err = getPublicKey(a.yk, slot)
if err != nil {
continue
}
k := &agent.Key{
Format: pk.Type(),
Blob: pk.Marshal(),
Comment: fmt.Sprintf("YubiKey #%d PIV Slot %x", a.serial, slot.Key),
}
keys = append(keys, k)
}
return keys, nil
}
func getPublicKey(yk *piv.YubiKey, slot piv.Slot) (ssh.PublicKey, error) {
cert, err := yk.Certificate(slot)
if err != nil {
return nil, fmt.Errorf("could not get public key from slot %x: %w", slot.Key, err)
}
switch cert.PublicKey.(type) {
case *ecdsa.PublicKey:
case *rsa.PublicKey:
default:
return nil, fmt.Errorf("unexpected public key type: %T", cert.PublicKey)
}
pk, err := ssh.NewPublicKey(cert.PublicKey)
if err != nil {
return nil, fmt.Errorf("failed to process public key: %w", err)
}
return pk, nil
}
func (a *Agent) Signers() ([]ssh.Signer, error) {
a.mu.Lock()
defer a.mu.Unlock()
if err := a.ensureYK(); err != nil {
return nil, fmt.Errorf("could not reach YubiKey: %w", err)
}
return a.signers()
}
func (a *Agent) signers() ([]ssh.Signer, error) {
var signers []ssh.Signer
for _, slot := range a.slots {
pk, err := getPublicKey(a.yk, slot)
if err != nil {
continue
}
priv, err := a.yk.PrivateKey(
slot,
pk.(ssh.CryptoPublicKey).CryptoPublicKey(),
piv.KeyAuth{PIN: a.PIN, PINPrompt: a.getPIN},
)
if err != nil {
return nil, fmt.Errorf("failed to prepare private key: %w", err)
}
s, err := ssh.NewSignerFromKey(priv)
if err != nil {
return nil, fmt.Errorf("failed to prepare signer: %w", err)
}
signers = append(signers, s)
}
return signers, nil
}
func (a *Agent) Sign(key ssh.PublicKey, data []byte) (*ssh.Signature, error) {
return a.SignWithFlags(key, data, 0)
}
func (a *Agent) SignWithFlags(key ssh.PublicKey, data []byte, flags agent.SignatureFlags) (*ssh.Signature, error) {
a.mu.Lock()
defer a.mu.Unlock()
if err := a.ensureYK(); err != nil {
return nil, fmt.Errorf("could not reach YubiKey: %w", err)
}
signers, err := a.signers()
if err != nil {
return nil, err
}
for _, s := range signers {
if !bytes.Equal(s.PublicKey().Marshal(), key.Marshal()) {
continue
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
a.touchNotification = time.NewTimer(5 * time.Second)
go func() {
select {
case <-a.touchNotification.C:
case <-ctx.Done():
a.touchNotification.Stop()
return
}
showNotification("Waiting for YubiKey touch...")
}()
alg := key.Type()
switch {
case alg == ssh.KeyAlgoRSA && flags&agent.SignatureFlagRsaSha256 != 0:
alg = ssh.SigAlgoRSASHA2256
case alg == ssh.KeyAlgoRSA && flags&agent.SignatureFlagRsaSha512 != 0:
alg = ssh.SigAlgoRSASHA2512
}
// TODO: maybe retry if the PIN is not correct?
return s.(ssh.AlgorithmSigner).SignWithAlgorithm(rand.Reader, data, alg)
}
return nil, fmt.Errorf("no private keys match the requested public key")
}
func showNotification(message string) {
switch runtime.GOOS {
case "darwin":
message = strings.ReplaceAll(message, `\`, `\\`)
message = strings.ReplaceAll(message, `"`, `\"`)
appleScript := `display notification "%s" with title "yubikey-agent"`
exec.Command("osascript", "-e", fmt.Sprintf(appleScript, message)).Run()
case "linux":
exec.Command("notify-send", "-i", "dialog-password", "yubikey-agent", message).Run()
}
}
func (a *Agent) Extension(extensionType string, contents []byte) ([]byte, error) {
return nil, agent.ErrExtensionUnsupported
}
var ErrOperationUnsupported = errors.New("operation unsupported")
func (a *Agent) Add(key agent.AddedKey) error {
return ErrOperationUnsupported
}
func (a *Agent) Remove(key ssh.PublicKey) error {
return ErrOperationUnsupported
}
func (a *Agent) RemoveAll() error {
return a.Close()
}
func (a *Agent) Lock(passphrase []byte) error {
return ErrOperationUnsupported
}
func (a *Agent) Unlock(passphrase []byte) error {
return ErrOperationUnsupported
}