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

feat: Timestamp #207

Merged
merged 86 commits into from
Jul 8, 2024
Merged
Show file tree
Hide file tree
Changes from 77 commits
Commits
Show all changes
86 commits
Select commit Hold shift + click to select a range
582a011
tsa
Two-Hearts Nov 30, 2023
8d92e01
test
Two-Hearts Nov 30, 2023
ac03000
test
Two-Hearts Dec 1, 2023
05b0463
fix hash
Two-Hearts Dec 4, 2023
212930a
Merge branch 'notaryproject:main' into tsa
Two-Hearts Dec 13, 2023
f859d84
Merge branch 'notaryproject:main' into tsa
Two-Hearts Dec 26, 2023
f39811a
Merge branch 'notaryproject:main' into tsa
Two-Hearts Dec 28, 2023
8cfd74d
initial commit
Two-Hearts Jan 9, 2024
034e4cd
cose
Two-Hearts Jan 9, 2024
84661c3
Merge branch 'notaryproject:main' into tsa
Two-Hearts Jan 15, 2024
01e4268
initial commits
Two-Hearts Jan 15, 2024
d0a39ce
Merge branch 'notaryproject:main' into tsa
Two-Hearts Jan 19, 2024
8ad3eab
refactored to use tspclient-go
Two-Hearts Jan 23, 2024
3e76750
update tspclient-go
Two-Hearts Jan 31, 2024
5fc45dc
test
Two-Hearts Feb 1, 2024
182af1a
update
Two-Hearts Feb 1, 2024
e780d70
resolve conflicts
Two-Hearts Mar 18, 2024
8a4cd55
update
Two-Hearts Mar 22, 2024
f75c250
Merge branch 'notaryproject:main' into tsa
Two-Hearts Mar 22, 2024
65fe878
fix bug
Two-Hearts Mar 22, 2024
bad5a7f
update
Two-Hearts Mar 22, 2024
3bbfdbb
fix bug
Two-Hearts Mar 22, 2024
bf4ea64
update sign
Two-Hearts Mar 22, 2024
e653780
fix JWS timestamp
Two-Hearts Mar 22, 2024
fecb8d8
Merge branch 'notaryproject:main' into tsa
Two-Hearts Mar 27, 2024
e085696
updated tspclient-go
Two-Hearts Mar 27, 2024
2338257
updated tsa cert validation
Two-Hearts Apr 8, 2024
952d151
added tsa request nonce support
Two-Hearts Apr 8, 2024
db08071
fix typo
Two-Hearts Apr 8, 2024
7654060
fix OCSP
Two-Hearts Apr 8, 2024
4f5a246
updated tsa with ocsp
Two-Hearts Apr 8, 2024
8c59a12
fix OCSP
Two-Hearts Apr 8, 2024
cbde6f9
update timestamping
Two-Hearts Apr 8, 2024
59a472a
Merge branch 'notaryproject:main' into tsa
Two-Hearts Apr 10, 2024
29bc773
update
Two-Hearts Apr 10, 2024
44995cc
added check signing time
Two-Hearts Apr 11, 2024
7b26dab
tsa cert validation
Two-Hearts Apr 15, 2024
5f03064
fix test
Two-Hearts Apr 15, 2024
f78e16e
fix test
Two-Hearts Apr 15, 2024
679399a
fix test
Two-Hearts Apr 15, 2024
14d0551
resolved conflicts
Two-Hearts Apr 18, 2024
5f7a175
added tests
Two-Hearts Apr 19, 2024
04390e2
Merge branch 'notaryproject:main' into tsa
Two-Hearts Apr 19, 2024
80b57f0
added tests
Two-Hearts Apr 25, 2024
f67e52b
add more tests
Two-Hearts Apr 26, 2024
c5f93ec
updated tspclient-go
Two-Hearts May 8, 2024
fc1cb3d
Merge branch 'notaryproject:main' into tsa
Two-Hearts May 8, 2024
bf89fbf
updated tspclient-go
Two-Hearts May 10, 2024
3b51449
Merge branch 'notaryproject:main' into tsa
Two-Hearts Jun 4, 2024
619f7fe
updated tspclient-go
Two-Hearts Jun 4, 2024
99b5190
fix tests
Two-Hearts Jun 4, 2024
0089871
validate tsa cert chain after signing
Two-Hearts Jun 11, 2024
29d77ea
fix tests
Two-Hearts Jun 11, 2024
9e9ee89
update
Two-Hearts Jun 11, 2024
02dce64
fix test
Two-Hearts Jun 11, 2024
f309851
update
Two-Hearts Jun 14, 2024
43b2412
updated tspclient-go
Two-Hearts Jun 18, 2024
066645f
clean up
Two-Hearts Jun 20, 2024
9bbc44d
added more tests
Two-Hearts Jun 20, 2024
66dbd61
added more tests
Two-Hearts Jun 20, 2024
a57701f
fix tests
Two-Hearts Jun 20, 2024
817296a
update
Two-Hearts Jun 20, 2024
b2551ef
tsa root cert pool
Two-Hearts Jun 21, 2024
7211f7a
tsa root cert pool
Two-Hearts Jun 21, 2024
e751e91
updated timestamp
Two-Hearts Jun 21, 2024
4eb5f5f
updated root cert pool
Two-Hearts Jun 24, 2024
28b8054
updated root cert pool
Two-Hearts Jun 24, 2024
64bf87a
clean up
Two-Hearts Jun 25, 2024
a24facd
updated tspclient-go
Two-Hearts Jun 27, 2024
81332af
Merge branch 'notaryproject:main' into tsa
Two-Hearts Jun 28, 2024
d7680b1
updated tspclient-go
Two-Hearts Jun 28, 2024
4470a8e
Merge branch 'notaryproject:main' into tsa
Two-Hearts Jun 28, 2024
7ee9155
updated per code review
Two-Hearts Jun 28, 2024
44714e2
update
Two-Hearts Jun 28, 2024
906d41a
update
Two-Hearts Jun 28, 2024
de8a46c
update
Two-Hearts Jun 28, 2024
c3a9244
clean up
Two-Hearts Jul 1, 2024
42d5b83
updated per code review
Two-Hearts Jul 1, 2024
4cb711b
added tests
Two-Hearts Jul 1, 2024
89251f1
update
Two-Hearts Jul 1, 2024
66dd339
updated tspclient-go
Two-Hearts Jul 2, 2024
8c1e9cd
updated tspclient-go
Two-Hearts Jul 2, 2024
a810785
update
Two-Hearts Jul 2, 2024
0830984
clean up
Two-Hearts Jul 2, 2024
46cda71
update
Two-Hearts Jul 3, 2024
7f0c505
Merge branch 'notaryproject:main' into tsa
Two-Hearts Jul 3, 2024
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
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@ go 1.21
require (
github.com/fxamacker/cbor/v2 v2.7.0
github.com/golang-jwt/jwt/v4 v4.5.0
github.com/notaryproject/tspclient-go v0.0.0-20240627050441-dcff9b7c23fe
github.com/veraison/go-cose v1.1.0
golang.org/x/crypto v0.24.0
)

require github.com/x448/float16 v0.8.4 // indirect

replace github.com/notaryproject/tspclient-go => github.com/Two-Hearts/tspclient-go v0.0.0-20240628085816-98b1c64c4172
Two-Hearts marked this conversation as resolved.
Show resolved Hide resolved
2 changes: 2 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
github.com/Two-Hearts/tspclient-go v0.0.0-20240628085816-98b1c64c4172 h1:ME+WMRNcucfmJ9Le8eCtdV1gR3Xc8ve6Ab/cPnN/z48=
github.com/Two-Hearts/tspclient-go v0.0.0-20240628085816-98b1c64c4172/go.mod h1:LGyA/6Kwd2FlM0uk8Vc5il3j0CddbWSHBj/4kxQDbjs=
github.com/fxamacker/cbor/v2 v2.7.0 h1:iM5WgngdRBanHcxugY4JySA0nk1wZorNOpTgCMedv5E=
github.com/fxamacker/cbor/v2 v2.7.0/go.mod h1:pxXPTn3joSm21Gbwsv0w9OSA2y1HFR9qXEeXQVeNoDQ=
github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg=
Expand Down
31 changes: 31 additions & 0 deletions internal/oid/oid.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// Copyright The Notary Project 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 oid

import "encoding/asn1"

// KeyUsage (id-ce-keyUsage) is defined in RFC 5280
//
// Reference: https://www.rfc-editor.org/rfc/rfc5280.html#section-4.2.1.3
var KeyUsage = asn1.ObjectIdentifier{2, 5, 29, 15}

// ExtKeyUsage (id-ce-extKeyUsage) is defined in RFC 5280
//
// Reference: https://www.rfc-editor.org/rfc/rfc5280.html#section-4.2.1.12
var ExtKeyUsage = asn1.ObjectIdentifier{2, 5, 29, 37}

// Timestamping (id-kp-timeStamping) is defined in RFC 3161 2.3
//
// Reference: https://datatracker.ietf.org/doc/html/rfc3161#section-2.3
var Timestamping = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added internal/timestamp/testdata/granted.tsq
Binary file not shown.
Binary file added internal/timestamp/testdata/tsaRootCert.crt
Binary file not shown.
60 changes: 60 additions & 0 deletions internal/timestamp/timestamp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Copyright The Notary Project 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 timestamp provides functionalities of timestamp countersignature
package timestamp

import (
"context"
"crypto/x509"
"time"

nx509 "github.com/notaryproject/notation-core-go/x509"
"github.com/notaryproject/tspclient-go"
)

// Timestamp generates a timestamp request and sends to TSA. It then validates
// the TSA certificate chain against Notary Project certificate and signature
// algorithm requirements.
// On success, it returns the full bytes of the timestamp token received from
// TSA.
//
// Reference: https://github.com/notaryproject/specifications/blob/v1.0.0/specs/signature-specification.md#leaf-certificates
func Timestamp(ctx context.Context, tsaURL string, signingTime *time.Time, tsaRootCAs *x509.CertPool, opts tspclient.RequestOptions) ([]byte, error) {
tsaRequest, err := tspclient.NewRequest(opts)
if err != nil {
return nil, err
}
httpTimestamper, err := tspclient.NewHTTPTimestamper(nil, tsaURL)
Two-Hearts marked this conversation as resolved.
Show resolved Hide resolved
if err != nil {
return nil, err
}
resp, err := httpTimestamper.Timestamp(ctx, tsaRequest)
if err != nil {
return nil, err
}
token, err := resp.SignedToken()
if err != nil {
return nil, err

Check warning on line 48 in internal/timestamp/timestamp.go

View check run for this annotation

Codecov / codecov/patch

internal/timestamp/timestamp.go#L48

Added line #L48 was not covered by tests
}
tsaCertChain, err := token.Verify(ctx, x509.VerifyOptions{
Roots: tsaRootCAs,
})
if err != nil {
return nil, err
}
if err := nx509.ValidateTimestampingCertChain(tsaCertChain, signingTime); err != nil {
return nil, err
}
return resp.TimestampToken.FullBytes, nil
}
223 changes: 223 additions & 0 deletions internal/timestamp/timestamp_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,223 @@
// Copyright The Notary Project 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 timestamp

import (
"context"
"crypto"
"crypto/x509"
"encoding/asn1"
"encoding/hex"
"io"
"net/http"
"net/http/httptest"
"os"
"strings"
"testing"
"time"

nx509 "github.com/notaryproject/notation-core-go/x509"
"github.com/notaryproject/tspclient-go"
"github.com/notaryproject/tspclient-go/pki"
)

const rfc3161TSAurl = "http://rfc3161timestamp.globalsign.com/advanced"

func TestTimestamp(t *testing.T) {
ctx := context.Background()
testResp, err := os.ReadFile("testdata/granted.tsq")
if err != nil {
t.Fatal("failed to read test response:", err)
}
rootCerts, err := nx509.ReadCertificateFile("testdata/tsaRootCert.crt")
if err != nil || len(rootCerts) == 0 {
t.Fatal("failed to read root CA certificate:", err)
}
rootCert := rootCerts[0]
rootCAs := x509.NewCertPool()
rootCAs.AddCert(rootCert)

// --------------- Success case ----------------------------------
opts := tspclient.RequestOptions{
Content: []byte("notation"),
HashAlgorithm: crypto.SHA256,
HashAlgorithmParameters: asn1.NullRawValue,
}
_, err = Timestamp(ctx, rfc3161TSAurl, nil, rootCAs, opts)
if err != nil {
t.Fatal(err)
}

// ------------- Failure cases ------------------------
opts = tspclient.RequestOptions{
Content: []byte("notation"),
HashAlgorithm: crypto.SHA1,
}
expectedErr := "malformed timestamping request: unsupported hashing algorithm: SHA-1"
_, err = Timestamp(ctx, "", nil, rootCAs, opts)
assertErrorEqual(expectedErr, err, t)

opts = tspclient.RequestOptions{
Content: []byte("notation"),
HashAlgorithm: crypto.SHA256,
HashAlgorithmParameters: asn1.NullRawValue,
}
bs, err := hex.DecodeString("7f")
if err != nil {
t.Fatal(err)
}
expectedErr = "parse \"http://\\x7f\": net/url: invalid control character in URL"
_, err = Timestamp(ctx, "http://"+string(bs), nil, rootCAs, opts)
assertErrorEqual(expectedErr, err, t)

mockInvalidTSA := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
const wantContentType = tspclient.MediaTypeTimestampQuery
if got := r.Header.Get("Content-Type"); got != wantContentType {
t.Fatalf("TimestampRequest.ContentType = %v, want %v", err, wantContentType)
}
if _, err := io.ReadAll(r.Body); err != nil {
t.Fatalf("TimestampRequest.Body read error = %v", err)
}

// write reply
w.Header().Set("Content-Type", tspclient.MediaTypeTimestampReply)
w.WriteHeader(http.StatusInternalServerError)
if _, err := w.Write(testResp); err != nil {
t.Error("failed to write response:", err)
}
}))
defer mockInvalidTSA.Close()
expectedErr = "https response bad status: 500 Internal Server Error"
_, err = Timestamp(ctx, mockInvalidTSA.URL, nil, rootCAs, opts)
if err == nil || !strings.Contains(err.Error(), expectedErr) {
t.Fatalf("expected error message to contain %s, but got %v", expectedErr, err)
}

opts = tspclient.RequestOptions{
Content: []byte("notation"),
HashAlgorithm: crypto.SHA256,
HashAlgorithmParameters: asn1.NullRawValue,
NoNonce: true,
}
mockInvalidTSA = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
const wantContentType = tspclient.MediaTypeTimestampQuery
if got := r.Header.Get("Content-Type"); got != wantContentType {
t.Fatalf("TimestampRequest.ContentType = %v, want %v", err, wantContentType)
}
if _, err := io.ReadAll(r.Body); err != nil {
t.Fatalf("TimestampRequest.Body read error = %v", err)
}

// write reply
token, err := os.ReadFile("testdata/TimeStampTokenWithoutCertificate.p7s")
if err != nil {
t.Fatal(err)
}
resp := &tspclient.Response{
Status: pki.StatusInfo{
Status: pki.StatusGranted,
},
TimestampToken: asn1.RawValue{
FullBytes: token,
},
}
respBytes, err := resp.MarshalBinary()
if err != nil {
t.Fatal(err)
}
w.Header().Set("Content-Type", tspclient.MediaTypeTimestampReply)
if _, err := w.Write(respBytes); err != nil {
t.Error("failed to write response:", err)
}
}))
defer mockInvalidTSA.Close()
expectedErr = "invalid timestamping response: certReq is True in request, but did not find any TSA signing certificate in the response"
_, err = Timestamp(ctx, mockInvalidTSA.URL, nil, rootCAs, opts)
assertErrorEqual(expectedErr, err, t)

opts = tspclient.RequestOptions{
Content: []byte("notation"),
HashAlgorithm: crypto.SHA256,
HashAlgorithmParameters: asn1.NullRawValue,
NoNonce: true,
}
mockInvalidTSA = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
const wantContentType = tspclient.MediaTypeTimestampQuery
if got := r.Header.Get("Content-Type"); got != wantContentType {
t.Fatalf("TimestampRequest.ContentType = %v, want %v", err, wantContentType)
}
if _, err := io.ReadAll(r.Body); err != nil {
t.Fatalf("TimestampRequest.Body read error = %v", err)
}

// write reply
w.Header().Set("Content-Type", tspclient.MediaTypeTimestampReply)
if _, err := w.Write(testResp); err != nil {
t.Error("failed to write response:", err)
}
}))
defer mockInvalidTSA.Close()
signingTime := time.Date(2100, 1, 1, 0, 0, 0, 0, time.UTC)
expectedErr = "certificate with subject \"CN=Globalsign TSA for Advanced - G4,O=GlobalSign nv-sa,C=BE\" was invalid at signing time of 2100-01-01 00:00:00 +0000 UTC. Certificate is valid from [2021-05-27 09:55:23 +0000 UTC] to [2032-06-28 09:55:22 +0000 UTC]"
_, err = Timestamp(ctx, mockInvalidTSA.URL, &signingTime, rootCAs, opts)
assertErrorEqual(expectedErr, err, t)

opts = tspclient.RequestOptions{
Content: []byte("notation"),
HashAlgorithm: crypto.SHA256,
HashAlgorithmParameters: asn1.NullRawValue,
NoNonce: true,
}
mockInvalidTSA = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
const wantContentType = tspclient.MediaTypeTimestampQuery
if got := r.Header.Get("Content-Type"); got != wantContentType {
t.Fatalf("TimestampRequest.ContentType = %v, want %v", err, wantContentType)
}
if _, err := io.ReadAll(r.Body); err != nil {
t.Fatalf("TimestampRequest.Body read error = %v", err)
}

// write reply
token, err := os.ReadFile("testdata/TimeStampTokenWithInvalidSignature.p7s")
if err != nil {
t.Fatal(err)
}
resp := &tspclient.Response{
Status: pki.StatusInfo{
Status: pki.StatusGranted,
},
TimestampToken: asn1.RawValue{
FullBytes: token,
},
}
respBytes, err := resp.MarshalBinary()
if err != nil {
t.Fatal(err)
}
w.Header().Set("Content-Type", tspclient.MediaTypeTimestampReply)
if _, err := w.Write(respBytes); err != nil {
t.Error("failed to write response:", err)
}
}))
defer mockInvalidTSA.Close()
expectedErr = "failed to verify signed token: cms verification failure: crypto/rsa: verification error"
_, err = Timestamp(ctx, mockInvalidTSA.URL, nil, rootCAs, opts)
assertErrorEqual(expectedErr, err, t)
}

func assertErrorEqual(expected string, err error, t *testing.T) {
if err == nil || expected != err.Error() {
t.Fatalf("Expected error \"%v\" but was \"%v\"", expected, err)
}
}
30 changes: 25 additions & 5 deletions revocation/ocsp/ocsp.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,11 +36,24 @@ import (
"golang.org/x/crypto/ocsp"
)

// Purpose is an enum for purpose of the certificate chain whose OCSP status
// is checked
type Purpose int

const (
// PurposeCodeSigning means the certificate chain is a code signing chain
PurposeCodeSigning Purpose = iota

// PurposeTimestamping means the certificate chain is a timestamping chain
PurposeTimestamping
)

// Options specifies values that are needed to check OCSP revocation
type Options struct {
CertChain []*x509.Certificate
SigningTime time.Time
HTTPClient *http.Client
CertChain []*x509.Certificate
CertChainPurpose Purpose
Two-Hearts marked this conversation as resolved.
Show resolved Hide resolved
SigningTime time.Time
HTTPClient *http.Client
}

const (
Expand All @@ -64,8 +77,15 @@ func CheckStatus(opts Options) ([]*result.CertRevocationResult, error) {
// Since this is using authentic signing time, signing time may be zero.
// Thus, it is better to pass nil here than fail for a cert's NotBefore
// being after zero time
if err := coreX509.ValidateCodeSigningCertChain(opts.CertChain, nil); err != nil {
return nil, result.InvalidChainError{Err: err}
switch opts.CertChainPurpose {
Two-Hearts marked this conversation as resolved.
Show resolved Hide resolved
case PurposeCodeSigning:
if err := coreX509.ValidateCodeSigningCertChain(opts.CertChain, nil); err != nil {
return nil, result.InvalidChainError{Err: err}
}
case PurposeTimestamping:
if err := coreX509.ValidateTimestampingCertChain(opts.CertChain, nil); err != nil {
return nil, result.InvalidChainError{Err: err}
}
}

certResults := make([]*result.CertRevocationResult, len(opts.CertChain))
Expand Down
Loading
Loading