Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move verify logic to pkg #120

Merged
merged 2 commits into from
Nov 8, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
70 changes: 6 additions & 64 deletions cmd/timestamp-cli/app/verify.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,19 +16,14 @@
package app

import (
"bytes"
"crypto/x509"
"errors"
"fmt"
"hash"
"io"
"os"
"path/filepath"

"github.com/digitorus/pkcs7"
"github.com/digitorus/timestamp"
"github.com/sigstore/timestamp-authority/cmd/timestamp-cli/app/format"
"github.com/sigstore/timestamp-authority/pkg/log"
"github.com/sigstore/timestamp-authority/pkg/verification"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
Expand Down Expand Up @@ -72,80 +67,27 @@ func runVerify() (interface{}, error) {
return nil, fmt.Errorf("Error reading request from file: %w", err)
}

ts, err := timestamp.ParseResponse(tsrBytes)
if err != nil {
pe := timestamp.ParseError("")
if errors.As(err, &pe) {
return nil, fmt.Errorf("Given timestamp response is not valid: %w", err)
}
return nil, fmt.Errorf("Error parsing response into Timestamp: %w", err)
}

// verify the timestamp response against the certificate chain PEM file
err = verifyTSRWithPEM(ts)
if err != nil {
return nil, err
}

// verify the timestamp response signature against the local arficat hash
err = verifyArtifactWithTSR(ts)
if err != nil {
return nil, err
}

return &verifyCmdOutput{TimestampPath: tsrPath}, nil
}

func verifyTSRWithPEM(ts *timestamp.Timestamp) error {
p7Message, err := pkcs7.Parse(ts.RawToken)
if err != nil {
return fmt.Errorf("Error parsing hashed message: %w", err)
}

certChainPEM := viper.GetString("cert-chain")
pemBytes, err := os.ReadFile(filepath.Clean(certChainPEM))
if err != nil {
return fmt.Errorf("Error reading request from file: %w", err)
return nil, fmt.Errorf("Error reading request from file: %w", err)
hectorj2f marked this conversation as resolved.
Show resolved Hide resolved
}

certPool := x509.NewCertPool()
ok := certPool.AppendCertsFromPEM(pemBytes)
if !ok {
return fmt.Errorf("Error while appending certs from PEM")
}

err = p7Message.VerifyWithChain(certPool)
if err != nil {
return fmt.Errorf("Error while verifying with chain: %w", err)
return nil, fmt.Errorf("error parsing response into Timestamp while appending certs from PEM")
}

log.CliLogger.Info("Verified with chain")

return nil
}

func verifyArtifactWithTSR(ts *timestamp.Timestamp) error {
artifactPath := viper.GetString("artifact")
artifact, err := os.Open(filepath.Clean(artifactPath))
if err != nil {
return err
}

return verifyHashedMessages(ts.HashAlgorithm.New(), ts.HashedMessage, artifact)
}

func verifyHashedMessages(hashAlg hash.Hash, hashedMessage []byte, artifactReader io.Reader) error {
h := hashAlg
if _, err := io.Copy(h, artifactReader); err != nil {
return fmt.Errorf("failed to create hash %w", err)
return nil, err
}
localHashedMsg := h.Sum(nil)

if !bytes.Equal(localHashedMsg, hashedMessage) {
return fmt.Errorf("Hashed messages don't match")
}
err = verification.VerifyTimestampResponse(tsrBytes, artifact, certPool)

return nil
return &verifyCmdOutput{TimestampPath: tsrPath}, err
}

func init() {
Expand Down
4 changes: 2 additions & 2 deletions pkg/tests/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ func TestVerify_InvalidTSR(t *testing.T) {

// It should return a message that the PEM is not valid
out := runCliErr(t, "--timestamp_server", restapiURL, "verify", "--timestamp", invalidTSR, "--artifact", artifactPath, "--cert-chain", pemPath)
outputContains(t, out, "Error parsing response into Timestamp")
outputContains(t, out, "error parsing response into Timestamp while appending certs from PEM")
}

func TestVerify_InvalidPEM(t *testing.T) {
Expand All @@ -127,7 +127,7 @@ func TestVerify_InvalidPEM(t *testing.T) {

// It should return a message that the PEM is not valid
out := runCliErr(t, "--timestamp_server", restapiURL, "verify", "--timestamp", tsrPath, "--artifact", artifactPath, "--cert-chain", invalidPEMPath)
outputContains(t, out, "Error while appending certs from PEM")
outputContains(t, out, "error parsing response into Timestamp while appending certs from PEM")
}

func runCliErr(t *testing.T, arg ...string) string {
Expand Down
77 changes: 77 additions & 0 deletions pkg/verification/verify.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
//
// Copyright 2022 The Sigstore Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package verification

import (
"bytes"
"crypto/x509"
"errors"
"fmt"
"hash"
"io"

"github.com/digitorus/pkcs7"
"github.com/digitorus/timestamp"
)

// VerifyTimestampResponse the timestamp response using a timestamp certificate chain.
func VerifyTimestampResponse(tsrBytes []byte, artifact io.Reader, certPool *x509.CertPool) error {
ts, err := timestamp.ParseResponse(tsrBytes)
if err != nil {
pe := timestamp.ParseError("")
if errors.As(err, &pe) {
return fmt.Errorf("timestamp response is not valid: %w", err)
}
return fmt.Errorf("error parsing response into Timestamp: %w", err)
}

// verify the timestamp response signature using the provided certificate pool
err = verifyTSRWithChain(ts, certPool)
if err != nil {
return err
}

// verify the hash in the timestamp response matches the artifact hash
return verifyHashedMessages(ts.HashAlgorithm.New(), ts.HashedMessage, artifact)
}

func verifyTSRWithChain(ts *timestamp.Timestamp, certPool *x509.CertPool) error {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit (to @malancas for the other issue): We'll want to rename this function to make it clear that this takes a trust root store (a single cert pool) rather than a chain

p7Message, err := pkcs7.Parse(ts.RawToken)
if err != nil {
return fmt.Errorf("error parsing hashed message: %w", err)
}

err = p7Message.VerifyWithChain(certPool)
if err != nil {
return fmt.Errorf("error while verifying with chain: %w", err)
}

return nil
}

func verifyHashedMessages(hashAlg hash.Hash, hashedMessage []byte, artifactReader io.Reader) error {
h := hashAlg
if _, err := io.Copy(h, artifactReader); err != nil {
return fmt.Errorf("failed to create hash %w", err)
}
localHashedMsg := h.Sum(nil)

if !bytes.Equal(localHashedMsg, hashedMessage) {
return fmt.Errorf("hashed messages don't match")
}

return nil
}
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@
// See the License for the specific language governing permissions and
// limitations under the License.

package app
package verification

import (
"bytes"
"crypto"
"crypto/x509"
"io"
"net/http/httptest"
"strings"
Expand All @@ -43,7 +44,9 @@ func TestVerifyArtifactHashedMessages(t *testing.T) {
}

type test struct {
message string
message string
forceError bool
expectedErrorMessage string
}

tests := []test{
Expand All @@ -62,6 +65,10 @@ func TestVerifyArtifactHashedMessages(t *testing.T) {
{
message: "MIIEbjADAgEAMIIEZQYJKoZIhvcNAQcCoIIEVjCCBFICAQExDTALBglghkgBZQMEAgEwgdQGCyqGSIb3DQEJEAEEoIHEBIHBMIG+AgEBBgkrBgEEAYO/MAIwMTANBglghkgBZQMEAgEFAAQgN94hMnpq0onyUi7r1zJHNiLT1/spX8MU2GBN9AdMe6wCFQDS6RL1iVlmlkwJzmpS2EH0cuX8sxgTMjAyMjExMDMxNzQyNDIrMDEwMDADAgEBAhRKnQszZjzcgJkpE8LCbmbF0s1jPaA0pDIwMDEOMAwGA1UEChMFbG9jYWwxHjAcBgNVBAMTFVRlc3QgVFNBIFRpbWVzdGFtcGluZ6CCAckwggHFMIIBaqADAgECAhRHCu9dHKS97mFo1cH5neJubRibujAKBggqhkjOPQQDAjAoMQ4wDAYDVQQKEwVsb2NhbDEWMBQGA1UEAxMNVGVzdCBUU0EgUm9vdDAeFw0yMjExMDMxMTUzMThaFw0zMTExMDMxMTU2MThaMDAxDjAMBgNVBAoTBWxvY2FsMR4wHAYDVQQDExVUZXN0IFRTQSBUaW1lc3RhbXBpbmcwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAATo3W6NQrpx5D8z5IvgD2DlAgoJMF4KPY9Pj4UfFhfOq029ryszXp3460Z7N+x86bDvyjVrHaeiPnl1HO9Q52zso2owaDAOBgNVHQ8BAf8EBAMCB4AwHQYDVR0OBBYEFHSIhDdTGIsodML/iUOhx7hgo/K7MB8GA1UdIwQYMBaAFBoZYijuouZCvKDtBd0eCyaU2HWoMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMIMAoGCCqGSM49BAMCA0kAMEYCIQCmPVr5kwYe4Jg9PGO6apgfzSrKAtESgNHpAbE3iIvJhQIhAJIGNxshJcC8LXHRrVWM77no3d3GguSvR01OAPZwE2pqMYIBmDCCAZQCAQEwQDAoMQ4wDAYDVQQKEwVsb2NhbDEWMBQGA1UEAxMNVGVzdCBUU0EgUm9vdAIURwrvXRykve5haNXB+Z3ibm0Ym7owCwYJYIZIAWUDBAIBoIHqMBoGCSqGSIb3DQEJAzENBgsqhkiG9w0BCRABBDAcBgkqhkiG9w0BCQUxDxcNMjIxMTAzMTY0MjQyWjAvBgkqhkiG9w0BCQQxIgQgrKbkOizzGoAudPhAnW5Qny788Kcd++VQwPrCMhg4MTEwfQYLKoZIhvcNAQkQAi8xbjBsMGowaAQgXqxJD0nAgg6en9P1bRrU7+6tzxOMn3YThreg7uR6T7EwRDAspCowKDEOMAwGA1UEChMFbG9jYWwxFjAUBgNVBAMTDVRlc3QgVFNBIFJvb3QCFEcK710cpL3uYWjVwfmd4m5tGJu6MAoGCCqGSM49BAMCBEcwRQIgQkc2BxMjnUMzqBDYzUiw10LoCIZ9Zmp1E0Hl6E+9mzwCIQDp2lD826Du5Ss4pNG/TksDknTUJfKvrLc2ex+x+W3VHg==",
},
{
expectedErrorMessage: "hashed messages don't match",
forceError: true,
},
}

for _, tc := range tests {
Expand All @@ -73,8 +80,13 @@ func TestVerifyArtifactHashedMessages(t *testing.T) {
t.Fatalf("unexpected error creating request: %v", err)
}

chain, err := c.Timestamp.GetTimestampCertChain(nil)
if err != nil {
t.Fatalf("unexpected error getting timestamp chain: %v", err)
}

params := tsatimestamp.NewGetTimestampResponseParams()
params.SetTimeout(10 * time.Second)
params.SetTimeout(5 * time.Second)
params.Request = io.NopCloser(bytes.NewReader(tsq))

var respBytes bytes.Buffer
Expand All @@ -83,14 +95,26 @@ func TestVerifyArtifactHashedMessages(t *testing.T) {
t.Fatalf("unexpected error getting timestamp response: %v", err)
}

tsr, err := timestamp.ParseResponse(respBytes.Bytes())
if err != nil {
t.Fatalf("unexpected error parsing response: %v", err)
certPool := x509.NewCertPool()
ok := certPool.AppendCertsFromPEM([]byte(chain.Payload))
if !ok {
t.Fatalf("error parsing response into Timestamp while appending certs from PEM")
}

if err := verifyHashedMessages(tsr.HashAlgorithm.New(), tsr.HashedMessage, strings.NewReader(tc.message)); err != nil {
if err := VerifyTimestampResponse(respBytes.Bytes(), strings.NewReader(tc.message), certPool); err != nil {
t.Errorf("verifyHashedMessages failed comparing hashes: %v", err)
}

if tc.forceError {
// Force hashed message error mismatch
msg := tc.message + "XXX"
err := VerifyTimestampResponse(respBytes.Bytes(), strings.NewReader(msg), certPool)
if err == nil {
t.Error("expected error message when verifying the timestamp response")
}
if err != nil && err.Error() != tc.expectedErrorMessage {
t.Errorf("expected error message when verifying the timestamp response: %s got %s", tc.expectedErrorMessage, err.Error())
}
}
}
}