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