diff --git a/note/note_cosigv1.go b/note/note_cosigv1.go index 4201731..e42768d 100644 --- a/note/note_cosigv1.go +++ b/note/note_cosigv1.go @@ -375,8 +375,7 @@ func CosignatureTimestamp(s note.Signature) (uint64, error) { if err != nil { return 0, errMalformedSig } - const minSigSize = 64 // min(ed25519.SignatureSize, mldsa.MLDSA44SignatureSize) - if len(r) < keyHashSize+timestampSize+minSigSize { + if l := len(r); l != keyHashSize+timestampSize+ed25519.SignatureSize && l != keyHashSize+timestampSize+mldsa.MLDSA44SignatureSize { return 0, errVerifierAlg } r = r[keyHashSize:] // Skip the hash @@ -466,6 +465,10 @@ func formatEd25519CosignatureV1(t uint64, msg []byte) ([]byte, error) { // // See https://c2sp.org/tlog-cosignature for more details. + // SPEC: MUST NOT exceed 2^63-1 + if t > math.MaxInt64 { + return nil, errInvalidTimestamp + } if bytes.IndexByte(msg, '\r') >= 0 { return nil, errors.New("cosigned note contains carriage return") } diff --git a/note/note_cosigv1_test.go b/note/note_cosigv1_test.go index ce17383..abd66e7 100644 --- a/note/note_cosigv1_test.go +++ b/note/note_cosigv1_test.go @@ -11,6 +11,8 @@ import ( "crypto/rand" "crypto/sha256" "encoding/base64" + "encoding/binary" + "math" "strings" "testing" "time" @@ -145,14 +147,56 @@ func TestVerifierInvalidSig(t *testing.T) { if err != nil { t.Fatal(err) } + v := s.Verifier() - msg := "test\n123\nf+7CoKgXKE/tNys9TTXcr/ad6U/K3xvznmzew9y6SP0=\n" - if _, err := note.Sign(¬e.Note{Text: msg}, s); err != nil { + msg := []byte("test\n123\nf+7CoKgXKE/tNys9TTXcr/ad6U/K3xvznmzew9y6SP0=\n") + validSig, err := s.Sign(msg) + if err != nil { t.Fatal(err) } - if _, err := note.Open([]byte("nobbled"), note.VerifierList(s.Verifier())); err == nil { - t.Fatal("Verifier validated incorrect signature") + overMaxTsSig := append([]byte(nil), validSig...) + binary.BigEndian.PutUint64(overMaxTsSig, math.MaxInt64+1) + + corruptSig := append([]byte(nil), validSig...) + corruptSig[len(corruptSig)-1] ^= 1 + + for _, test := range []struct { + name string + msg []byte + sig []byte + }{ + { + name: "short signature", + msg: msg, + sig: validSig[:len(validSig)-1], + }, + { + name: "long signature", + msg: msg, + sig: append(append([]byte(nil), validSig...), 0), + }, + { + name: "corrupted signature bytes", + msg: msg, + sig: corruptSig, + }, + { + name: "timestamp exceeds 2^63-1", + msg: msg, + sig: overMaxTsSig, + }, + { + name: "malformed note body (too few lines)", + msg: []byte("nobbled"), + sig: validSig, + }, + } { + t.Run(test.name, func(t *testing.T) { + if v.Verify(test.msg, test.sig) { + t.Errorf("Verify() = true, want false") + } + }) } } @@ -244,6 +288,10 @@ func TestCoSigV1Timestamp(t *testing.T) { name: "gibberish", sig: note.Signature{Base64: "5%/$!\n 2"}, wantErr: true, + }, { + name: "non-cosignature length (80 bytes)", + sig: note.Signature{Base64: base64.StdEncoding.EncodeToString(make([]byte, 80))}, + wantErr: true, }, } { t.Run(test.name, func(t *testing.T) { @@ -279,6 +327,10 @@ func TestCosignatureTimestamp(t *testing.T) { name: "gibberish", sig: note.Signature{Base64: "5%/$!\n 2"}, wantErr: true, + }, { + name: "non-cosignature length (80 bytes)", + sig: note.Signature{Base64: base64.StdEncoding.EncodeToString(make([]byte, 80))}, + wantErr: true, }, } { t.Run(test.name, func(t *testing.T) { diff --git a/note/note_rfc6962.go b/note/note_rfc6962.go index 956ddbe..7d45588 100644 --- a/note/note_rfc6962.go +++ b/note/note_rfc6962.go @@ -25,10 +25,12 @@ import ( "encoding/json" "errors" "fmt" + "math" "strconv" "strings" "time" + "golang.org/x/crypto/cryptobyte" "golang.org/x/mod/sumdb/note" ) @@ -36,7 +38,8 @@ import ( // logURL is the root URL of the log. // pubK is the public key of the log. func RFC6962VerifierString(logURL string, pubK crypto.PublicKey) (string, error) { - if !isValidName(logURL) { + name := rfc6962LogName(logURL) + if !isValidName(name) { return "", errors.New("invalid name") } pubSer, err := x509.MarshalPKIXPublicKey(pubK) @@ -44,7 +47,6 @@ func RFC6962VerifierString(logURL string, pubK crypto.PublicKey) (string, error) return "", err } logID := sha256.Sum256(pubSer) - name := rfc6962LogName(logURL) hash := rfc6962Keyhash(name, logID) return fmt.Sprintf("%s+%08x+%s", name, hash, base64.StdEncoding.EncodeToString(append([]byte{algRFC6962STH}, pubSer...))), nil } @@ -131,12 +133,19 @@ func RFC6962STHTimestamp(s note.Signature) (time.Time, error) { if err != nil { return time.UnixMilli(0), errMalformedSig } - if len(r) <= keyHashSize+timestampSize { + var t uint64 + b := cryptobyte.String(r) + // Skip the 4-byte key hash, read the 8-byte millisecond timestamp, and ensure + // the 4-byte TLS DigitallySigned header (hashAlg, sigAlg, uint16 sigLen) plus + // at least 1 signature byte follow. + if !b.Skip(keyHashSize) || !b.ReadUint64(&t) || + !b.Skip(1+1+2) || b.Empty() { return time.UnixMilli(0), errVerifierAlg } - r = r[keyHashSize:] // Skip the hash - // Next 8 bytes are the timestamp as Unix millis-since-epoch: - return time.Unix(0, int64(binary.BigEndian.Uint64(r)*1000)), nil + if t > math.MaxInt64 { + return time.UnixMilli(0), errInvalidTimestamp + } + return time.UnixMilli(int64(t)), nil } func rfc6962Keyhash(name string, logID [32]byte) uint32 { @@ -184,24 +193,15 @@ func (v *rfc6962Verifer) Verify(msg, sig []byte) bool { func verifyRFC6962(key crypto.PublicKey) func([]byte, string, []byte) bool { return func(msg []byte, origin string, sig []byte) bool { - if len(sig) < timestampSize { - return false - } - t := binary.BigEndian.Uint64(sig) - // slice off timestamp bytes - sig = sig[timestampSize:] - - hAlg := sig[0] - sAlg := sig[1] - // slice off the hAlg and sAlg bytes read above - sig = sig[2:] - - // Figure out sig bytes length - sigLen := binary.BigEndian.Uint16(sig) - sig = sig[2:] // Slice off length bytes - - // All that remains should be the signature bytes themselves, and nothing more. - if len(sig) != int(sigLen) { + // Per https://c2sp.org/static-ct-api, sig is an RFC6962NoteSignature: + // uint64 timestamp followed by a TLS 1.2 DigitallySigned struct (RFC 5246 ยง4.7). + var t uint64 + var hAlg, sAlg uint8 + var rawSig cryptobyte.String + s := cryptobyte.String(sig) + if !s.ReadUint64(&t) || t > math.MaxInt64 || + !s.ReadUint8(&hAlg) || !s.ReadUint8(&sAlg) || + !s.ReadUint16LengthPrefixed(&rawSig) || !s.Empty() { return false } @@ -224,7 +224,7 @@ func verifyRFC6962(key crypto.PublicKey) func([]byte, string, []byte) bool { if sAlg != 0x03 { return false } - return ecdsa.VerifyASN1(k, dgst[:], sig) + return ecdsa.VerifyASN1(k, dgst[:], rawSig) default: return false } diff --git a/note/note_rfc6962_test.go b/note/note_rfc6962_test.go index efe90db..aec2909 100644 --- a/note/note_rfc6962_test.go +++ b/note/note_rfc6962_test.go @@ -17,7 +17,10 @@ package note import ( "crypto/x509" "encoding/base64" + "encoding/binary" "encoding/json" + "fmt" + "math" "strconv" "strings" "testing" @@ -65,6 +68,11 @@ func TestRFC6962VerifierString(t *testing.T) { url: "ct.googleapis.com/logs/us1/argon2024+cheese", pubK: mustB64(t, "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEHblsqctplMVc5ramA7vSuNxUQxcomQwGAVAdnWTAWUYr3MgDHQW0LagJ95lB7QT75Ve6JgT2EVLOFGU7L3YrwA=="), wantErr: true, + }, { + name: "empty name after stripping scheme", + url: "https://", + pubK: mustB64(t, "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEHblsqctplMVc5ramA7vSuNxUQxcomQwGAVAdnWTAWUYr3MgDHQW0LagJ95lB7QT75Ve6JgT2EVLOFGU7L3YrwA=="), + wantErr: true, }, } { t.Run(test.name, func(t *testing.T) { @@ -84,6 +92,15 @@ func TestRFC6962VerifierString(t *testing.T) { } func TestVerify(t *testing.T) { + const ( + romeVKey = "rome.ct.filippo.io/2024h1+78f4abae+BTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABAFzPC3fap+uINc1RQ4eRbYMUt84+bKkA8GDLN8KwVdzAgYhYSv4kS8XSheGLAHCWhIJTJbuC3sL88bNMTtrsBM=" + romeBody = "rome.ct.filippo.io/2024h1\n115474666\n2q1K6aiIJR+F7TyhiWOghoWOjY0/3dVBLsBbAvB4xCw=\n" + ) + romeSynthCP := func(sigPayload []byte) []byte { + rawSig := append([]byte{0x78, 0xf4, 0xab, 0xae}, sigPayload...) + return []byte(fmt.Sprintf("%s\n\u2014 rome.ct.filippo.io/2024h1 %s\n", romeBody, base64.StdEncoding.EncodeToString(rawSig))) + } + for _, test := range []struct { name string cp []byte @@ -94,21 +111,61 @@ func TestVerify(t *testing.T) { // "2q1K6aiIJR+F7TyhiWOghoWOjY0/3dVBLsBbAvB4xCw=" with non-zero padding bits ('w=' -> 'x='). name: "non-canonical base64 root hash", cp: []byte(strings.Replace(romeCP, "4xCw=", "4xCx=", 1)), - verifier: "rome.ct.filippo.io/2024h1+78f4abae+BTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABAFzPC3fap+uINc1RQ4eRbYMUt84+bKkA8GDLN8KwVdzAgYhYSv4kS8XSheGLAHCWhIJTJbuC3sL88bNMTtrsBM=", + verifier: romeVKey, wantErr: true, }, { name: "works - rome", cp: []byte(romeCP), - verifier: "rome.ct.filippo.io/2024h1+78f4abae+BTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABAFzPC3fap+uINc1RQ4eRbYMUt84+bKkA8GDLN8KwVdzAgYhYSv4kS8XSheGLAHCWhIJTJbuC3sL88bNMTtrsBM=", + verifier: romeVKey, }, { name: "invalid signature", cp: []byte("B0rked" + romeCP), - verifier: "rome.ct.filippo.io/2024h1+78f4abae+BTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABAFzPC3fap+uINc1RQ4eRbYMUt84+bKkA8GDLN8KwVdzAgYhYSv4kS8XSheGLAHCWhIJTJbuC3sL88bNMTtrsBM=", + verifier: romeVKey, wantErr: true, }, { name: "leading zero in size", cp: []byte(strings.Replace(romeCP, "\n115474666\n", "\n0115474666\n", 1)), - verifier: "rome.ct.filippo.io/2024h1+78f4abae+BTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABAFzPC3fap+uINc1RQ4eRbYMUt84+bKkA8GDLN8KwVdzAgYhYSv4kS8XSheGLAHCWhIJTJbuC3sL88bNMTtrsBM=", + verifier: romeVKey, + wantErr: true, + }, { + name: "short sig: 0 bytes after key hash", + cp: romeSynthCP(make([]byte, 0)), + verifier: romeVKey, + wantErr: true, + }, { + name: "short sig: 7 bytes (shorter than timestamp)", + cp: romeSynthCP(make([]byte, 7)), + verifier: romeVKey, + wantErr: true, + }, { + name: "short sig: 8 bytes (timestamp only, 0 TLS header bytes)", + cp: romeSynthCP(make([]byte, 8)), + verifier: romeVKey, + wantErr: true, + }, { + name: "short sig: 9 bytes (timestamp + 1 TLS header byte)", + cp: romeSynthCP(make([]byte, 9)), + verifier: romeVKey, + wantErr: true, + }, { + name: "short sig: 10 bytes (timestamp + 2 TLS header bytes)", + cp: romeSynthCP(make([]byte, 10)), + verifier: romeVKey, + wantErr: true, + }, { + name: "short sig: 11 bytes (timestamp + 3 TLS header bytes)", + cp: romeSynthCP(make([]byte, 11)), + verifier: romeVKey, + wantErr: true, + }, { + name: "short sig: 12 bytes (timestamp + 4 zero TLS header bytes)", + cp: romeSynthCP(make([]byte, 12)), + verifier: romeVKey, + wantErr: true, + }, { + name: "short sig: 13 bytes (mismatched TLS sig length)", + cp: romeSynthCP(make([]byte, 13)), + verifier: romeVKey, wantErr: true, }, } { @@ -128,6 +185,7 @@ func TestVerify(t *testing.T) { } func TestRFC6962STHToCheckpoint(t *testing.T) { + const argonVKey = "ct.googleapis.com/logs/us1/argon2024+7deb49d0+BTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABB25bKnLaZTFXOa2pgO70rjcVEMXKJkMBgFQHZ1kwFlGK9zIAx0FtC2oCfeZQe0E++VXuiYE9hFSzhRlOy92K8A=" for _, test := range []struct { name string sth []byte @@ -137,16 +195,26 @@ func TestRFC6962STHToCheckpoint(t *testing.T) { { name: "works", sth: []byte(`{"tree_size":1267285836,"timestamp":1711642477482,"sha256_root_hash":"SHySaYoaGIV5oCMANTytRfUjfzXb7wvO9xQiGkDJlfQ=","tree_head_signature":"BAMARzBFAiAQWbsL/MbJdeR4jk8xYKWDBDGHyDcntBim9Jr1BvwPnAIhAMedQo0YuBo+ajNd9xyVOMvhOdVAeJYgOhBLQn8rca94"}`), - verifier: "ct.googleapis.com/logs/us1/argon2024+7deb49d0+BTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABB25bKnLaZTFXOa2pgO70rjcVEMXKJkMBgFQHZ1kwFlGK9zIAx0FtC2oCfeZQe0E++VXuiYE9hFSzhRlOy92K8A=", + verifier: argonVKey, }, { name: "invalid JSON", sth: []byte(`Bananas are cool : {"tree_size":1267285836,"timestamp":1711642477482,"sha256_root_hash":"SHySaYoaGIV5oCMANTytRfUjfzXb7wvO9xQiGkDJlfQ=","tree_head_signature":"BAMARzBFAiAQWbsL/MbJdeR4jk8xYKWDBDGHyDcntBim9Jr1BvwPnAIhAMedQo0YuBo+ajNd9xyVOMvhOdVAeJYgOhBLQn8rca94"}`), - verifier: "ct.googleapis.com/logs/us1/argon2024+7deb49d0+BTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABB25bKnLaZTFXOa2pgO70rjcVEMXKJkMBgFQHZ1kwFlGK9zIAx0FtC2oCfeZQe0E++VXuiYE9hFSzhRlOy92K8A=", + verifier: argonVKey, wantErr: true, }, { name: "invalid STH", sth: []byte(`{"tree_size":1267285836,"timestamp":1711642477482,"sha256_root_hash":"SHySaYoaGIV5oCMANTytRfUjfzXb7wvO9xQiGkDJlfQ=","tree_head_signature":"BananaSignature"}`), - verifier: "ct.googleapis.com/logs/us1/argon2024+7deb49d0+BTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABB25bKnLaZTFXOa2pgO70rjcVEMXKJkMBgFQHZ1kwFlGK9zIAx0FtC2oCfeZQe0E++VXuiYE9hFSzhRlOy92K8A=", + verifier: argonVKey, + wantErr: true, + }, { + name: "empty tree_head_signature (0 bytes)", + sth: []byte(`{"tree_size":1267285836,"timestamp":1711642477482,"sha256_root_hash":"SHySaYoaGIV5oCMANTytRfUjfzXb7wvO9xQiGkDJlfQ=","tree_head_signature":""}`), + verifier: argonVKey, + wantErr: true, + }, { + name: "truncated tree_head_signature (3 bytes, shorter than TLS DigitallySigned header)", + sth: []byte(`{"tree_size":1267285836,"timestamp":1711642477482,"sha256_root_hash":"SHySaYoaGIV5oCMANTytRfUjfzXb7wvO9xQiGkDJlfQ=","tree_head_signature":"AQID"}`), + verifier: argonVKey, wantErr: true, }, } { @@ -188,7 +256,7 @@ func TestRFC6962STHToCheckpoint(t *testing.T) { if err != nil { t.Fatalf("RFC6962STHTimestamp: %v", err) } - if got, want := ts, time.Unix(0, int64(sth.Timestamp*1000)); got != want { + if got, want := ts, time.UnixMilli(int64(sth.Timestamp)); !got.Equal(want) { t.Fatalf("Got %v, want %v", got, want) } @@ -270,3 +338,50 @@ func TestRFC6962_KeyHashValidation(t *testing.T) { } } } + +func TestRFC6962STHTimestamp(t *testing.T) { + overMaxTsSig := make([]byte, 20) + binary.BigEndian.PutUint64(overMaxTsSig[keyHashSize:], math.MaxInt64+1) + + for _, test := range []struct { + name string + sig note.Signature + wantTime time.Time + wantErr bool + }{ + { + name: "works", + sig: note.Signature{Base64: "ePSrrgAAAY5+gVlSBAMARzBFAiEAv8bOMzo3Ed/GbU9fzzJvaStX6i8xTsmEF+NqvpGhIO0CIEn1X+zzVEerdix64GEn97XCXObA2G5JQ8UDDqCKdG5m"}, + wantTime: time.UnixMilli(1711519390034), + }, { + name: "gibberish base64", + sig: note.Signature{Base64: "5%/$!\n 2"}, + wantErr: true, + }, { + name: "too short: 12 bytes (key hash + timestamp only)", + sig: note.Signature{Base64: base64.StdEncoding.EncodeToString(make([]byte, 12))}, + wantErr: true, + }, { + name: "too short: 16 bytes (key hash + timestamp + 4-byte TLS header, 0 sig bytes)", + sig: note.Signature{Base64: base64.StdEncoding.EncodeToString(make([]byte, 16))}, + wantErr: true, + }, { + name: "timestamp exceeds math.MaxInt64", + sig: note.Signature{Base64: base64.StdEncoding.EncodeToString(overMaxTsSig)}, + wantErr: true, + }, + } { + t.Run(test.name, func(t *testing.T) { + got, err := RFC6962STHTimestamp(test.sig) + if gotErr := err != nil; gotErr != test.wantErr { + t.Fatalf("RFC6962STHTimestamp(%q) err = %v, wantErr %v", test.sig.Base64, err, test.wantErr) + } + if test.wantErr { + return + } + if !got.Equal(test.wantTime) { + t.Errorf("RFC6962STHTimestamp() = %v, want %v", got, test.wantTime) + } + }) + } +} diff --git a/note/note_verifier.go b/note/note_verifier.go index 1d1863c..766ffd2 100644 --- a/note/note_verifier.go +++ b/note/note_verifier.go @@ -101,6 +101,9 @@ func NewECDSAVerifier(key string) (note.Verifier, error) { if got, want := len(parts), 3; got != want { return nil, fmt.Errorf("key has %d parts, expected %d: %q", got, want, key) } + if !isValidName(parts[0]) { + return nil, fmt.Errorf("key has invalid name %q", parts[0]) + } keyBytes, err := base64.StdEncoding.Strict().DecodeString(parts[2]) if err != nil { return nil, fmt.Errorf("key has invalid base64 %q: %v", parts[2], err) diff --git a/note/note_verifier_test.go b/note/note_verifier_test.go index 5495713..82ea3ed 100644 --- a/note/note_verifier_test.go +++ b/note/note_verifier_test.go @@ -151,6 +151,14 @@ func TestNewECDSAVerifier(t *testing.T) { name: "short keyhash", pubK: "rekor.sigstore.dev" + "+" + sigStoreKeyHash[1:] + "+" + sigStoreKeyMaterial, wantErr: true, + }, { + name: "empty name", + pubK: "+" + sigStoreKeyHash + "+" + sigStoreKeyMaterial, + wantErr: true, + }, { + name: "whitespace in name", + pubK: "rekor sigstore" + "+" + sigStoreKeyHash + "+" + sigStoreKeyMaterial, + wantErr: true, }, } { t.Run(test.name, func(t *testing.T) {