gunk-dev/the-valley

piv.go

source8c40ee5f164cmain's published tip history
6.4 KiB
1package approval
2
3import (
4 "bufio"
5 "crypto/ed25519"
6 "crypto/x509"
7 "encoding/asn1"
8 "encoding/hex"
9 "errors"
10 "fmt"
11 "io"
12 "os/exec"
13 "strings"
14)
15
16// PIVSession signs with a YubiKey's PIV slot through valley-piv-signer
17// (approval/piv/valley-piv-signer.c), a helper on libykpiv that holds the
18// YubiKey exclusively for the whole session and resets it when the session
19// ends. The PIN is asked for once, on the terminal, by the helper; it never
20// passes through this process. Each signature takes a touch when the key's
21// touch policy says so.
22//
23// After any refusal the session is over: it sends nothing more, so a PIN
24// the device refused is never sent again.
25type PIVSession struct {
26 cmd *exec.Cmd
27 in io.WriteCloser
28 out *bufio.Reader
29 pub ed25519.PublicKey
30 serial string
31 pin byte // the key's attested PIN policy
32 touch byte // and touch policy
33 prompt io.Writer
34 done error
35 waited bool
36 status error // how the helper exited, once waited for
37}
38
39// PIVError is a refusal valley-piv-signer reports.
40type PIVError struct {
41 Kind string // device, pin, pin-format, cancelled, touch or request
42 Detail string
43}
44
45func (e *PIVError) Error() string {
46 switch e.Kind {
47 case "pin":
48 return fmt.Sprintf("the YubiKey refused the PIN, and allows %s more tries; it is not sent again", e.Detail)
49 case "pin-format":
50 return "a PIN is 6 to 8 characters; what was entered was not sent to the YubiKey"
51 case "cancelled":
52 return "no PIN was entered"
53 case "touch":
54 return "the YubiKey did not sign: it was not touched in time"
55 case "device":
56 return "the YubiKey cannot sign: " + e.Detail
57 }
58 return "the PIV signer refused the request: " + e.Detail
59}
60
61// The attestation extension holding a key's PIN and touch policy, and the
62// values Yubico gives them (identity/attestation.go).
63var policyOID = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 41482, 3, 8}
64
65const (
66 pinNever = 1
67 pinAlways = 3
68 touchNever = 1
69 maxPIVReply = 16 << 10
70)
71
72// OpenPIV starts the helper at program on one slot ("9c" when empty) of
73// the YubiKey on the first reader whose name holds reader (any, when
74// empty), and reads the key the slot attests to. Touch requests are
75// written to prompt.
76func OpenPIV(program, slot, reader string, prompt io.Writer) (*PIVSession, error) {
77 args := []string{}
78 if slot != "" {
79 args = append(args, "--slot", slot)
80 }
81 if reader != "" {
82 args = append(args, "--reader", reader)
83 }
84 cmd := exec.Command(program, args...)
85 in, err := cmd.StdinPipe()
86 if err != nil {
87 return nil, err
88 }
89 out, err := cmd.StdoutPipe()
90 if err != nil {
91 return nil, err
92 }
93 if err := cmd.Start(); err != nil {
94 return nil, fmt.Errorf("the PIV signer did not start: %w", err)
95 }
96 p := &PIVSession{cmd: cmd, in: in, out: bufio.NewReaderSize(out, 4096), prompt: prompt}
97 word, rest, err := p.reply()
98 if err == nil && word != "key" {
99 err = fmt.Errorf("the PIV signer opened with %q, not its key", word)
100 }
101 if err == nil {
102 err = p.readKey(rest)
103 }
104 if err != nil {
105 p.Close()
106 return nil, err
107 }
108 return p, nil
109}
110
111func (p *PIVSession) readKey(rest string) error {
112 serial, encoded, _ := strings.Cut(rest, " ")
113 der, err := hex.DecodeString(encoded)
114 if err != nil {
115 return errors.New("the PIV signer's attestation certificate is not hex")
116 }
117 cert, err := x509.ParseCertificate(der)
118 if err != nil {
119 return fmt.Errorf("the slot's attestation certificate does not parse: %w", err)
120 }
121 pub, ok := cert.PublicKey.(ed25519.PublicKey)
122 if !ok {
123 return errors.New("the slot holds no ed25519 key; an approval is an ed25519 signature")
124 }
125 for _, ext := range cert.Extensions {
126 if ext.Id.Equal(policyOID) && len(ext.Value) == 2 {
127 p.pin, p.touch = ext.Value[0], ext.Value[1]
128 }
129 }
130 p.pub, p.serial = pub, serial
131 return nil
132}
133
134// Public is the key the slot attests to.
135func (p *PIVSession) Public() ed25519.PublicKey { return p.pub }
136
137// Sign asks the device to sign text. Text over MaxStatement is refused
138// here, before the device is asked.
139func (p *PIVSession) Sign(text []byte) ([]byte, error) {
140 if p.done != nil {
141 return nil, p.done
142 }
143 if len(text) == 0 || len(text) > MaxStatement {
144 return nil, fmt.Errorf("the text is %d bytes; the PIV signer signs 1 to %d", len(text), MaxStatement)
145 }
146 mode := map[byte]string{pinNever: "none", pinAlways: "each"}[p.pin]
147 if mode == "" {
148 mode = "session"
149 }
150 if _, err := fmt.Fprintf(p.in, "sign %d %s\n%s", len(text), mode, text); err != nil {
151 return nil, p.end(fmt.Errorf("the PIV signer stopped reading: %w", err))
152 }
153 word, rest, err := p.reply()
154 if err != nil {
155 return nil, p.end(err)
156 }
157 if word == "touch" {
158 if p.touch != touchNever {
159 fmt.Fprintf(p.prompt, "touch the YubiKey (serial %s) to sign\n", p.serial)
160 }
161 if word, rest, err = p.reply(); err != nil {
162 return nil, p.end(err)
163 }
164 }
165 if word != "signature" {
166 return nil, p.end(fmt.Errorf("the PIV signer replied %q, not a signature", word))
167 }
168 sig, err := hex.DecodeString(rest)
169 if err != nil || len(sig) != ed25519.SignatureSize {
170 return nil, p.end(errors.New("the PIV signer's signature is not 64 bytes of hex"))
171 }
172 return sig, nil
173}
174
175// reply reads one line from the helper. A refusal is returned as a
176// *PIVError.
177func (p *PIVSession) reply() (word, rest string, err error) {
178 var line []byte
179 for {
180 chunk, isPrefix, err := p.out.ReadLine()
181 if err != nil {
182 return "", "", fmt.Errorf("the PIV signer ended without replying: %w", p.exit(err))
183 }
184 line = append(line, chunk...)
185 if len(line) > maxPIVReply {
186 return "", "", errors.New("the PIV signer's reply is too long")
187 }
188 if !isPrefix {
189 break
190 }
191 }
192 word, rest, _ = strings.Cut(string(line), " ")
193 if word == "error" {
194 kind, detail, _ := strings.Cut(rest, " ")
195 return "", "", &PIVError{Kind: kind, Detail: detail}
196 }
197 return word, rest, nil
198}
199
200// exit waits for a helper whose output ended, and says how it ended.
201func (p *PIVSession) exit(err error) error {
202 if werr := p.wait(); werr != nil {
203 return werr
204 }
205 return err
206}
207
208func (p *PIVSession) wait() error {
209 if !p.waited {
210 p.waited, p.status = true, p.cmd.Wait()
211 }
212 return p.status
213}
214
215func (p *PIVSession) end(err error) error {
216 p.done = err
217 p.Close()
218 return err
219}
220
221// Close ends the session: the helper reads the end of its input,
222// disconnects from the device, and exits.
223func (p *PIVSession) Close() error {
224 p.in.Close()
225 io.Copy(io.Discard, io.LimitReader(p.out, maxPIVReply))
226 return p.wait()
227}
228
229// PIVSerial is the serial number of the YubiKey the session signs on.
230func (p *PIVSession) PIVSerial() string { return p.serial }