Skip to content

Commit

Permalink
piv: support RSA PSS and add test for TLS 1.3 as a server and client
Browse files Browse the repository at this point in the history
  • Loading branch information
ericchiang committed Mar 16, 2023
1 parent 8f83ce3 commit 851fa59
Show file tree
Hide file tree
Showing 7 changed files with 418 additions and 40 deletions.
8 changes: 2 additions & 6 deletions .github/workflows/test.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ jobs:
build:
strategy:
matrix:
go-version: [1.18.x, 1.19.x]
go-version: [1.19.x, 1.20.x]
name: Linux
runs-on: ubuntu-latest
steps:
Expand All @@ -22,16 +22,14 @@ jobs:
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Install staticcheck
run: go install honnef.co/go/tools/cmd/[email protected]
- name: Install libpcsc
run: sudo apt-get install -y libpcsclite-dev pcscd pcsc-tools
- name: Test
run: "make test"
build-windows:
strategy:
matrix:
go-version: [1.18.x, 1.19.x]
go-version: [1.19.x, 1.20.x]
name: Windows
runs-on: windows-latest
steps:
Expand All @@ -42,8 +40,6 @@ jobs:
id: go
- name: Check out code into the Go module directory
uses: actions/checkout@v2
- name: Install staticcheck
run: go install honnef.co/go/tools/cmd/[email protected]
- name: Test
run: "make build"
env:
Expand Down
8 changes: 2 additions & 6 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
.PHONY: test
test: lint
test:
go test -v ./...

.PHONY: lint
lint:
staticcheck ./...

.PHONY: build
build: lint
build:
go build ./...
69 changes: 41 additions & 28 deletions piv/key.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import (
"math/big"
"strconv"
"strings"

rsafork "github.com/go-piv/piv-go/third_party/rsa"
)

// errMismatchingAlgorithms is returned when a cryptographic operation
Expand Down Expand Up @@ -1072,7 +1074,7 @@ func (k *keyRSA) Public() crypto.PublicKey {

func (k *keyRSA) Sign(rand io.Reader, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
return k.auth.do(k.yk, k.pp, func(tx *scTx) ([]byte, error) {
return ykSignRSA(tx, k.slot, k.pub, digest, opts)
return ykSignRSA(tx, rand, k.slot, k.pub, digest, opts)
})
}

Expand Down Expand Up @@ -1285,43 +1287,54 @@ func ykDecryptRSA(tx *scTx, slot Slot, pub *rsa.PublicKey, data []byte) ([]byte,
// PKCS#1 v15 is largely informed by the standard library
// https://github.com/golang/go/blob/go1.13.5/src/crypto/rsa/pkcs1v15.go

func ykSignRSA(tx *scTx, slot Slot, pub *rsa.PublicKey, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
if _, ok := opts.(*rsa.PSSOptions); ok {
return nil, fmt.Errorf("rsassa-pss signatures not supported")
func ykSignRSA(tx *scTx, rand io.Reader, slot Slot, pub *rsa.PublicKey, digest []byte, opts crypto.SignerOpts) ([]byte, error) {
hash := opts.HashFunc()
if hash.Size() != len(digest) {
return nil, fmt.Errorf("input must be a hashed message")
}

alg, err := rsaAlg(pub)
if err != nil {
return nil, err
}
hash := opts.HashFunc()
if hash.Size() != len(digest) {
return nil, fmt.Errorf("input must be a hashed message")
}
prefix, ok := hashPrefixes[hash]
if !ok {
return nil, fmt.Errorf("unsupported hash algorithm: crypto.Hash(%d)", hash)
}

// https://tools.ietf.org/pdf/rfc2313.pdf#page=9
d := make([]byte, len(prefix)+len(digest))
copy(d[:len(prefix)], prefix)
copy(d[len(prefix):], digest)
var data []byte
if o, ok := opts.(*rsa.PSSOptions); ok {
salt, err := rsafork.NewSalt(rand, pub, hash, o)
if err != nil {
return nil, err
}
em, err := rsafork.EMSAPSSEncode(digest, pub, salt, hash.New())
if err != nil {
return nil, err
}
data = em
} else {
prefix, ok := hashPrefixes[hash]
if !ok {
return nil, fmt.Errorf("unsupported hash algorithm: crypto.Hash(%d)", hash)
}

// https://tools.ietf.org/pdf/rfc2313.pdf#page=9
d := make([]byte, len(prefix)+len(digest))
copy(d[:len(prefix)], prefix)
copy(d[len(prefix):], digest)

paddingLen := pub.Size() - 3 - len(d)
if paddingLen < 0 {
return nil, fmt.Errorf("message too large")
}
paddingLen := pub.Size() - 3 - len(d)
if paddingLen < 0 {
return nil, fmt.Errorf("message too large")
}

padding := make([]byte, paddingLen)
for i := range padding {
padding[i] = 0xff
}
padding := make([]byte, paddingLen)
for i := range padding {
padding[i] = 0xff
}

// https://tools.ietf.org/pdf/rfc2313.pdf#page=9
data := append([]byte{0x00, 0x01}, padding...)
data = append(data, 0x00)
data = append(data, d...)
// https://tools.ietf.org/pdf/rfc2313.pdf#page=9
data = append([]byte{0x00, 0x01}, padding...)
data = append(data, 0x00)
data = append(data, d...)
}

// https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=117
cmd := apdu{
Expand Down
176 changes: 176 additions & 0 deletions piv/key_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,14 @@ import (
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/tls"
"crypto/x509"
"crypto/x509/pkix"
"encoding/asn1"
"encoding/pem"
"errors"
"fmt"
"io"
"math/big"
"testing"
"time"
Expand Down Expand Up @@ -333,6 +336,179 @@ func TestYubiKeySignRSA(t *testing.T) {
}
}

func TestYubiKeySignRSAPSS(t *testing.T) {
tests := []struct {
name string
alg Algorithm
long bool
}{
{"rsa1024", AlgorithmRSA1024, false},
{"rsa2048", AlgorithmRSA2048, true},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if test.long && testing.Short() {
t.Skip("skipping test in short mode")
}
yk, close := newTestYubiKey(t)
defer close()
slot := SlotAuthentication
key := Key{
Algorithm: test.alg,
TouchPolicy: TouchPolicyNever,
PINPolicy: PINPolicyNever,
}
pubKey, err := yk.GenerateKey(DefaultManagementKey, slot, key)
if err != nil {
t.Fatalf("generating key: %v", err)
}
pub, ok := pubKey.(*rsa.PublicKey)
if !ok {
t.Fatalf("public key is not an rsa key")
}
data := sha256.Sum256([]byte("hello"))
priv, err := yk.PrivateKey(slot, pub, KeyAuth{})
if err != nil {
t.Fatalf("getting private key: %v", err)
}
s, ok := priv.(crypto.Signer)
if !ok {
t.Fatalf("private key didn't implement crypto.Signer")
}

opt := &rsa.PSSOptions{Hash: crypto.SHA256}
out, err := s.Sign(rand.Reader, data[:], opt)
if err != nil {
t.Fatalf("signing failed: %v", err)
}
if err := rsa.VerifyPSS(pub, crypto.SHA256, data[:], out, opt); err != nil {
t.Errorf("failed to verify signature: %v", err)
}
})
}
}

func TestTLS13(t *testing.T) {
yk, close := newTestYubiKey(t)
defer close()
slot := SlotAuthentication
key := Key{
Algorithm: AlgorithmRSA1024,
TouchPolicy: TouchPolicyNever,
PINPolicy: PINPolicyNever,
}
pub, err := yk.GenerateKey(DefaultManagementKey, slot, key)
if err != nil {
t.Fatalf("generating key: %v", err)
}
priv, err := yk.PrivateKey(slot, pub, KeyAuth{})
if err != nil {
t.Fatalf("getting private key: %v", err)
}

tmpl := &x509.Certificate{
Subject: pkix.Name{CommonName: "test"},
SerialNumber: big.NewInt(100),
NotBefore: time.Now(),
NotAfter: time.Now().Add(time.Hour),
DNSNames: []string{"example.com"},
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{
x509.ExtKeyUsageClientAuth,
x509.ExtKeyUsageServerAuth,
},
}

rawCert, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, pub, priv)
if err != nil {
t.Fatalf("creating certificate: %v", err)
}
x509Cert, err := x509.ParseCertificate(rawCert)
if err != nil {
t.Fatalf("parsing cert: %v", err)
}
cert := tls.Certificate{
Certificate: [][]byte{rawCert},
PrivateKey: priv,
SupportedSignatureAlgorithms: []tls.SignatureScheme{
tls.PSSWithSHA256,
},
}
pool := x509.NewCertPool()
pool.AddCert(x509Cert)

cliConf := &tls.Config{
Certificates: []tls.Certificate{cert},
RootCAs: pool,
ServerName: "example.com",
MinVersion: tls.VersionTLS13,
MaxVersion: tls.VersionTLS13,
}
srvConf := &tls.Config{
Certificates: []tls.Certificate{cert},
ClientCAs: pool,
ClientAuth: tls.RequireAndVerifyClientCert,
MinVersion: tls.VersionTLS13,
MaxVersion: tls.VersionTLS13,
}

srv, err := tls.Listen("tcp", "0.0.0.0:0", srvConf)
if err != nil {
t.Fatalf("creating tls listener: %v", err)
}
defer srv.Close()

errCh := make(chan error, 2)

want := []byte("hello, world")

go func() {
conn, err := srv.Accept()
if err != nil {
errCh <- fmt.Errorf("accepting conn: %v", err)
return
}
defer conn.Close()

got := make([]byte, len(want))
if _, err := io.ReadFull(conn, got); err != nil {
errCh <- fmt.Errorf("read data: %v", err)
return
}
if !bytes.Equal(want, got) {
errCh <- fmt.Errorf("unexpected value read: %s", got)
return
}
errCh <- nil
}()

go func() {
conn, err := tls.Dial("tcp", srv.Addr().String(), cliConf)
if err != nil {
errCh <- fmt.Errorf("dial: %v", err)
return
}
defer conn.Close()

if v := conn.ConnectionState().Version; v != tls.VersionTLS13 {
errCh <- fmt.Errorf("client got verison 0x%x, want=0x%x", v, tls.VersionTLS13)
return
}

if _, err := conn.Write(want); err != nil {
errCh <- fmt.Errorf("write: %v", err)
return
}
errCh <- nil
}()

for i := 0; i < 2; i++ {
if err := <-errCh; err != nil {
t.Fatalf("%v", err)
}
}
}

func TestYubiKeyDecryptRSA(t *testing.T) {
tests := []struct {
name string
Expand Down
27 changes: 27 additions & 0 deletions third_party/rsa/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
Copyright (c) 2009 The Go Authors. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of Google Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2 changes: 2 additions & 0 deletions third_party/rsa/README
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
This directory contains a fork of internal crypto/rsa logic to allow computation
of PSS padding.
Loading

0 comments on commit 851fa59

Please sign in to comment.