Comments WIP
diff --git a/bs3/bs3test/bs3test.go b/bs3/bs3test/bs3test.go index fdfdcbe..af90533 100644 --- a/bs3/bs3test/bs3test.go +++ b/bs3/bs3test/bs3test.go
@@ -5,14 +5,16 @@ import ( "bytes" "context" + "crypto/sha256" + "encoding/hex" "errors" - "fmt" "io" "net/http" "sync" awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/aws/aws-sdk-go-v2/service/s3/types" smithyhttp "github.com/aws/smithy-go/transport/http" ) @@ -20,15 +22,16 @@ type StoredObject struct { Data []byte ContentEncoding *string + ETag string } // FakeS3 implements the PutObject/GetObject/Bucket subset of the S3 API // with an in-memory map. // -// PutObject fails for an existing key only when IfNoneMatch is set. +// PutObject honors IfNoneMatch and IfMatch, failing with 412 Precondition +// Failed like S3 does, and GetObject returns types.NoSuchKey for a missing key. type FakeS3 struct { - mu sync.Mutex - + mu sync.Mutex Objects map[string]StoredObject } @@ -36,37 +39,47 @@ return &FakeS3{Objects: make(map[string]StoredObject)} } +func preconditionFailed() error { + return &awshttp.ResponseError{ + ResponseError: &smithyhttp.ResponseError{ + Response: &smithyhttp.Response{Response: &http.Response{StatusCode: http.StatusPreconditionFailed}}, + Err: errors.New("PreconditionFailed"), + }, + } +} + func (f *FakeS3) PutObject(ctx context.Context, params *s3.PutObjectInput, optFns ...func(*s3.Options)) (*s3.PutObjectOutput, error) { f.mu.Lock() defer f.mu.Unlock() - _, ok := f.Objects[*params.Key] + existing, ok := f.Objects[*params.Key] if ok && params.IfNoneMatch != nil { - return nil, &awshttp.ResponseError{ - ResponseError: &smithyhttp.ResponseError{ - Response: &smithyhttp.Response{Response: &http.Response{StatusCode: http.StatusPreconditionFailed}}, - Err: errors.New("PreconditionFailed"), - }, - } + return nil, preconditionFailed() + } + if params.IfMatch != nil && (!ok || existing.ETag != *params.IfMatch) { + return nil, preconditionFailed() } body, err := io.ReadAll(params.Body) if err != nil { return nil, err } - f.Objects[*params.Key] = StoredObject{Data: body, ContentEncoding: params.ContentEncoding} - return nil, nil + sum := sha256.Sum256(body) + etag := "\"" + hex.EncodeToString(sum[:]) + "\"" + f.Objects[*params.Key] = StoredObject{Data: body, ContentEncoding: params.ContentEncoding, ETag: etag} + return &s3.PutObjectOutput{ETag: &etag}, nil } func (f *FakeS3) GetObject(ctx context.Context, params *s3.GetObjectInput, optFns ...func(*s3.Options)) (*s3.GetObjectOutput, error) { f.mu.Lock() defer f.mu.Unlock() o, ok := f.Objects[*params.Key] - if ok { - return &s3.GetObjectOutput{ - Body: io.NopCloser(bytes.NewReader(o.Data)), - ContentEncoding: o.ContentEncoding, - }, nil + if !ok { + return nil, &types.NoSuchKey{} } - return nil, fmt.Errorf("not found") + return &s3.GetObjectOutput{ + Body: io.NopCloser(bytes.NewReader(o.Data)), + ContentEncoding: o.ContentEncoding, + ETag: &o.ETag, + }, nil } func (f *FakeS3) Bucket() string {
diff --git a/mtca/mtca.go b/mtca/mtca.go index fd8361e..3399f9e 100644 --- a/mtca/mtca.go +++ b/mtca/mtca.go
@@ -15,10 +15,14 @@ "encoding/hex" "errors" "fmt" + "net/http" + "path" "sync" "time" + awshttp "github.com/aws/aws-sdk-go-v2/aws/transport/http" "github.com/aws/aws-sdk-go-v2/service/s3" + "github.com/aws/aws-sdk-go-v2/service/s3/types" "github.com/jmhodges/clock" "github.com/letsencrypt/borp" @@ -37,6 +41,7 @@ var ErrIssuanceLogAlreadyInitialized = errors.New("issuance log already initialized") var ErrCheckpointNotReady = errors.New("not ready - no mirror signature") +var ErrCheckpointChanged = errors.New("checkpoint in tile storage changed since it was last written") var _ mtcapb.MTCAServer = &mtca{} @@ -119,6 +124,9 @@ mirrorVerifier *cosignature.Verifier servedCheckpointID int64 + // servedCheckpointETag is the ETag of the checkpoint object in tile storage + // as this MTCA last wrote or read it, nil until it has done either. + servedCheckpointETag *string pool *pool @@ -718,34 +726,89 @@ return fmt.Errorf("checkpoint %d root hash is %d bytes, want %d", latest.ID, len(latest.RootHash), tlog.HashSize) } - // Verify the MTCA cosignature and produce its signature line. + // Produce the signature line for the MTCA's cosignature. tree := tlog.Tree{N: latest.TreeSize, Hash: tlog.Hash(latest.RootHash)} - caCosignatureLine, err := m.verifier.SignatureLine(m.logID.Origin(), tree, latest.MTCASignature) + caCosignatureLine, err := cosignature.SignatureLine(m.verifier.Name(), m.verifier.KeyHash(), latest.MTCASignature) if err != nil { return fmt.Errorf("checkpoint %d MTCA signature: %s", latest.ID, err) } - // Verify the mirror cosignature and produce its signature line. + // Produce the signature line for the mirror's cosignature. if latest.MirrorID != m.mirrorID { return fmt.Errorf("checkpoint %d cosigned by mirror %q, want %q", latest.ID, latest.MirrorID, m.mirrorID) } - mirrorCosignatureLine, err := m.mirrorVerifier.SignatureLine(m.logID.Origin(), tree, latest.MirrorSignature) + mirrorCosignatureLine, err := cosignature.SignatureLine(m.mirrorVerifier.Name(), m.mirrorVerifier.KeyHash(), latest.MirrorSignature) if err != nil { return fmt.Errorf("checkpoint %d mirror cosignature: %s", latest.ID, err) } - // Produce a note containing both cosgnatures. + // Produce a signed note containing both cosignatures. cp := checkpoint.Checkpoint{Origin: m.logID.Origin(), Tree: tree} - note, err := cp.SignedNoteForServing(caCosignatureLine, mirrorCosignatureLine) + signedNote, err := cp.SignedNoteForServing(caCosignatureLine, mirrorCosignatureLine) if err != nil { return err } - // Finally, write it to the checkpoint path for serving. - err = tiles.WriteCheckpoint(ctx, m.s3c, m.logID.TilePrefix(), note) + // Verify the signed note containing both cosignatures. + _, _, err = checkpoint.Open(signedNote, m.verifier, m.mirrorVerifier) + if err != nil { + return fmt.Errorf("checkpoint %d: %s", latest.ID, err) + } + + // Finally, write the signed note to the checkpoint path in tile storage. + etag, err := m.writeCheckpoint(ctx, signedNote, m.servedCheckpointETag) if err != nil { return fmt.Errorf("serving checkpoint %d: %s", latest.ID, err) } m.servedCheckpointID = latest.ID + m.servedCheckpointETag = etag return nil } + +// writeCheckpoint stores signedNote at the log's "checkpoint" key per +// c2sp.org/tlog-tiles, replacing the checkpoint whose ETag is prevETag, and +// returns the new checkpoint's ETag. A nil prevETag means the current ETag is +// unknown, so it is read first, and the note is written only if no checkpoint +// exists when none is found. It returns ErrCheckpointChanged if the checkpoint +// was replaced by another writer in the meantime. The note must be written +// only after the tiles its tree covers are published. +func (m *mtca) writeCheckpoint(ctx context.Context, signedNote []byte, prevETag *string) (*string, error) { + bucket := m.s3c.Bucket() + key := path.Join(m.logID.TilePrefix(), "checkpoint") + if prevETag == nil { + current, err := m.s3c.GetObject(ctx, &s3.GetObjectInput{Bucket: &bucket, Key: &key}) + if err == nil { + current.Body.Close() + prevETag = current.ETag + } else { + _, notFound := errors.AsType[*types.NoSuchKey](err) + if !notFound { + return nil, fmt.Errorf("reading s3://%s/%s: %w", bucket, key, err) + } + } + } + + contentType := "text/plain; charset=utf-8" + cacheControl := "no-store" + input := &s3.PutObjectInput{ + Bucket: &bucket, + Key: &key, + ContentType: &contentType, + CacheControl: &cacheControl, + Body: bytes.NewReader(signedNote), + IfMatch: prevETag, + } + if prevETag == nil { + star := "*" + input.IfNoneMatch = &star + } + out, err := m.s3c.PutObject(ctx, input) + if err != nil { + respErr, ok := errors.AsType[*awshttp.ResponseError](err) + if ok && respErr.HTTPStatusCode() == http.StatusPreconditionFailed { + return nil, fmt.Errorf("writing s3://%s/%s: %w", bucket, key, ErrCheckpointChanged) + } + return nil, fmt.Errorf("writing s3://%s/%s: %w", bucket, key, err) + } + return out.ETag, nil +}
diff --git a/mtca/mtca_test.go b/mtca/mtca_test.go index 6c4ecd5..47ab01e 100644 --- a/mtca/mtca_test.go +++ b/mtca/mtca_test.go
@@ -263,6 +263,54 @@ return ch } +// TestWriteCheckpoint checks that writeCheckpoint replaces only the checkpoint +// it was told about, reads the current ETag when given none, and refuses to +// replace a checkpoint another writer stored. +func TestWriteCheckpoint(t *testing.T) { + m, fs3, cleanup, err := setup() + if err != nil { + t.Fatalf("setup: %s", err) + } + defer cleanup() + key := m.logID.TilePrefix() + "/checkpoint" + + first, err := m.writeCheckpoint(t.Context(), []byte("first note\n"), nil) + if err != nil { + t.Fatalf("writing the first checkpoint: %s", err) + } + if string(fs3.Objects[key].Data) != "first note\n" { + t.Errorf("stored checkpoint = %q, want %q", fs3.Objects[key].Data, "first note\n") + } + + second, err := m.writeCheckpoint(t.Context(), []byte("second note\n"), first) + if err != nil { + t.Fatalf("replacing the checkpoint: %s", err) + } + if string(fs3.Objects[key].Data) != "second note\n" { + t.Errorf("stored checkpoint = %q, want %q", fs3.Objects[key].Data, "second note\n") + } + + third, err := m.writeCheckpoint(t.Context(), []byte("third note\n"), nil) + if err != nil { + t.Fatalf("replacing the checkpoint with an unknown ETag: %s", err) + } + if string(fs3.Objects[key].Data) != "third note\n" { + t.Errorf("stored checkpoint = %q, want %q", fs3.Objects[key].Data, "third note\n") + } + if *third == *second { + t.Error("ETag did not change with the checkpoint's contents") + } + + fs3.Objects[key] = bs3test.StoredObject{Data: []byte("foreign note\n"), ETag: "\"foreign\""} + _, err = m.writeCheckpoint(t.Context(), []byte("fourth note\n"), third) + if !errors.Is(err, ErrCheckpointChanged) { + t.Errorf("writeCheckpoint over another writer's checkpoint = %s, want ErrCheckpointChanged", err) + } + if string(fs3.Objects[key].Data) != "foreign note\n" { + t.Errorf("stored checkpoint = %q, want the other writer's %q", fs3.Objects[key].Data, "foreign note\n") + } +} + // errorS3 wraps a bs3test.FakeS3, failing every PutObject with `err` while // it is non-nil and passing through to the wrapped fake otherwise. type errorS3 struct {
diff --git a/mtpublisher/mirror.go b/mtpublisher/mirror.go index ee316c8..f8a02d6 100644 --- a/mtpublisher/mirror.go +++ b/mtpublisher/mirror.go
@@ -272,7 +272,7 @@ if err != nil { return nil, fmt.Errorf("marshaling the checkpoint: %w", err) } - timestampedMirrorCosignature, err := cosignature.TimestampedSignature(noteText, subtreeCosignatureLines, m.verifier) + timestampedMirrorCosignature, err := m.verifier.FilterByVerify(noteText, subtreeCosignatureLines) if err != nil { return nil, fmt.Errorf("cosignature failed verification: %w", err) }
diff --git a/mtpublisher/mtpublisher.go b/mtpublisher/mtpublisher.go index 388d26fd..e1ae239 100644 --- a/mtpublisher/mtpublisher.go +++ b/mtpublisher/mtpublisher.go
@@ -116,16 +116,21 @@ if len(latest.MTCASignature) == 0 { return fmt.Errorf("checkpoint %d (%s size %d) has no MTCA signature", latest.ID, latest.MTCLogID, latest.TreeSize) } - caCosignatureLine, err := p.caVerifier.SignatureLine(cp.Origin, tree, latest.MTCASignature) + caCosignatureLine, err := cosignature.SignatureLine(p.caVerifier.Name(), p.caVerifier.KeyHash(), latest.MTCASignature) if err != nil { return fmt.Errorf("checkpoint %d MTCA signature: %w", latest.ID, err) } - // Reconstruct the signed note for submission to the mirror. + // Reconstruct the signed note for submission to the mirror, and verify + // the MTCA signature before submitting it. signedNoteForMirror, err := cp.SignedNoteForMirror(caCosignatureLine) if err != nil { return fmt.Errorf("assembling checkpoint %d signed note: %w", latest.ID, err) } + _, _, err = checkpoint.Open(signedNoteForMirror, p.caVerifier) + if err != nil { + return fmt.Errorf("checkpoint %d MTCA signature: %w", latest.ID, err) + } // Submit the signed checkpoint to the mirror for cosigning. mirrorRawCosig, err := p.mirror.Cosign(ctx, cp, signedNoteForMirror)
diff --git a/mtpublisher/mtpublisher_test.go b/mtpublisher/mtpublisher_test.go index dd2c41b..f75ee60 100644 --- a/mtpublisher/mtpublisher_test.go +++ b/mtpublisher/mtpublisher_test.go
@@ -393,7 +393,7 @@ if err != nil { t.Fatalf("NewVerifier: %s", err) } - caLine, err := caVerifier.SignatureLine(cp.Origin, newer, rawCA) + caLine, err := cosignature.SignatureLine(caVerifier.Name(), caVerifier.KeyHash(), rawCA) if err != nil { t.Fatalf("SignatureLine: %s", err) } @@ -426,7 +426,7 @@ if err != nil { t.Fatalf("NewVerifier: %s", err) } - cosigLine, err := mirrorVerifier.SignatureLine(cp.Origin, newer, rawCosig) + cosigLine, err := cosignature.SignatureLine(mirrorVerifier.Name(), mirrorVerifier.KeyHash(), rawCosig) if err != nil { t.Fatalf("SignatureLine: %s", err) }
diff --git a/mtpublisher/mtpublishertest/mtpublishertest_test.go b/mtpublisher/mtpublishertest/mtpublishertest_test.go index 9894ed7..b083ec8 100644 --- a/mtpublisher/mtpublishertest/mtpublishertest_test.go +++ b/mtpublisher/mtpublishertest/mtpublishertest_test.go
@@ -55,9 +55,17 @@ if err != nil { t.Fatalf("NewVerifier: %s", err) } - _, err = verifier.SignatureLine(cp.Origin, cp.Tree, raw) + line, err := cosignature.SignatureLine(verifier.Name(), verifier.KeyHash(), raw) if err != nil { - t.Errorf("SignatureLine rejected the mirror's cosignature: %s", err) + t.Fatalf("SignatureLine: %s", err) + } + text, err := cp.Marshal() + if err != nil { + t.Fatalf("Marshal: %s", err) + } + _, err = verifier.FilterByVerify(text, line) + if err != nil { + t.Errorf("the mirror's cosignature does not verify: %s", err) } }
diff --git a/trees/checkpoint/checkpoint.go b/trees/checkpoint/checkpoint.go index 3d108f9..848327a 100644 --- a/trees/checkpoint/checkpoint.go +++ b/trees/checkpoint/checkpoint.go
@@ -190,18 +190,29 @@ } // Open opens a signed checkpoint note and parses its text. An error is returned -// if signedNote is not a well-formed note, if any of the verifiers rejects a -// signature (note.InvalidSignatureError), if none of the verifiers has signed -// the note (note.UnverifiedNoteError), or if the note's text is not a -// well-formed checkpoint. Signatures from unknown keys are ignored. +// if signedNote is not a well-formed note, if its signature lines are not +// exactly one verified signature per verifier and nothing else +// (note.InvalidSignatureError for a rejected one), or if the note's text is not +// a well-formed checkpoint. // // - https://c2sp.org/tlog-checkpoint // - https://c2sp.org/signed-note -func Open(signedNote []byte, verifiers note.Verifiers) (*Checkpoint, *note.Note, error) { - n, err := note.Open(signedNote, verifiers) +func Open(signedNote []byte, verifiers ...note.Verifier) (*Checkpoint, *note.Note, error) { + n, err := note.Open(signedNote, note.VerifierList(verifiers...)) if err != nil { return nil, nil, err } + // n.Sigs holds one verified signature per signing key in verifiers, so its + // length is the number of verifiers whose key signed the note. + if len(n.Sigs) != len(verifiers) { + return nil, nil, fmt.Errorf("%d of %d verifiers signed the note", len(n.Sigs), len(verifiers)) + } + // note.Open ignores signatures from unknown keys and repeated signatures + // from known ones, so the lines themselves are counted as well. + signatureLines := bytes.Count(signedNote[len(n.Text)+1:], []byte("\n")) + if signatureLines != len(verifiers) { + return nil, nil, fmt.Errorf("note has %d signature lines, want %d", signatureLines, len(verifiers)) + } c, err := Unmarshal([]byte(n.Text)) if err != nil { return nil, nil, err
diff --git a/trees/checkpoint/checkpoint_test.go b/trees/checkpoint/checkpoint_test.go index 32c0bf6..d31e774 100644 --- a/trees/checkpoint/checkpoint_test.go +++ b/trees/checkpoint/checkpoint_test.go
@@ -233,7 +233,7 @@ } t.Run("Valid", func(t *testing.T) { - cp, n, err := Open(signed, note.VerifierList(verifier)) + cp, n, err := Open(signed, verifier) if err != nil { t.Fatalf("Open: %s", err) } @@ -248,6 +248,48 @@ } }) + t.Run("Missing a verifier", func(t *testing.T) { + _, otherVkey, err := note.GenerateKey(rand.Reader, "example.com/other") + if err != nil { + t.Fatalf("GenerateKey: %s", err) + } + otherV, err := note.NewVerifier(otherVkey) + if err != nil { + t.Fatalf("NewVerifier: %s", err) + } + _, _, err = Open(signed, verifier, otherV) + if err == nil { + t.Error("Open with a verifier that did not sign = nil error, want error") + } + }) + + t.Run("Extra signature from an unknown key", func(t *testing.T) { + otherSkey, _, err := note.GenerateKey(rand.Reader, "example.com/other") + if err != nil { + t.Fatalf("GenerateKey: %s", err) + } + otherSigner, err := note.NewSigner(otherSkey) + if err != nil { + t.Fatalf("NewSigner: %s", err) + } + twiceSigned, err := note.Sign(¬e.Note{Text: exampleCheckpoint}, signer, otherSigner) + if err != nil { + t.Fatalf("note.Sign: %s", err) + } + _, _, err = Open(twiceSigned, verifier) + if err == nil { + t.Error("Open with an extra signature from an unknown key = nil error, want error") + } + }) + + t.Run("Repeated signature", func(t *testing.T) { + repeated := append(slices.Clone(signed), signed[len(exampleCheckpoint)+1:]...) + _, _, err := Open(repeated, verifier) + if err == nil { + t.Error("Open with a repeated signature = nil error, want error") + } + }) + t.Run("Wrong key", func(t *testing.T) { _, otherVkey, err := note.GenerateKey(rand.Reader, "example.com/behind-the-sofa") if err != nil { @@ -257,7 +299,7 @@ if err != nil { t.Fatalf("NewVerifier: %s", err) } - _, _, err = Open(signed, note.VerifierList(otherV)) + _, _, err = Open(signed, otherV) if err == nil { t.Error("Open with wrong key = nil error, want error") } @@ -283,7 +325,7 @@ if err != nil { t.Fatalf("NewVerifier: %s", err) } - _, _, err = Open(signed, note.VerifierList(verifier)) + _, _, err = Open(signed, verifier) if err == nil { t.Error("Open of a verified non-checkpoint note = nil error, want error") }
diff --git a/trees/cosignature/cosignature.go b/trees/cosignature/cosignature.go index f352988..5c91c05 100644 --- a/trees/cosignature/cosignature.go +++ b/trees/cosignature/cosignature.go
@@ -72,15 +72,6 @@ return cosignedMessage.Marshal() } -// signatureLineFor assembles the signature line "— <name> base64(keyID || -// timestamped_signature)\n". -func signatureLineFor(name string, keyID uint32, timestampedSignature []byte) string { - idSignature := make([]byte, keyIDSize+len(timestampedSignature)) - binary.BigEndian.PutUint32(idSignature[:keyIDSize], keyID) - copy(idSignature[keyIDSize:], timestampedSignature) - return noteSignatureLinePrefix + name + " " + base64.StdEncoding.EncodeToString(idSignature) + "\n" -} - // checkRelativeOID returns an error if id is not a dotted decimal OID like // "32473.2", nil otherwise. func checkRelativeOID(id string) error { @@ -176,7 +167,7 @@ // - https://c2sp.org/tlog-cosignature // - https://c2sp.org/mtc-tlog type Verifier struct { - name string + keyName string keyID uint32 publicKey *mldsa.PublicKey } @@ -195,7 +186,7 @@ return nil, errors.New("public key must be ML-DSA-44") } return &Verifier{ - name: oidPrefix + cosignerID, + keyName: oidPrefix + cosignerID, keyID: keyIDFor(oidPrefix+cosignerID, publicKey), publicKey: publicKey, }, nil @@ -203,7 +194,7 @@ // Name satisfies note.Verifier. func (v *Verifier) Name() string { - return v.name + return v.keyName } // KeyHash satisfies note.Verifier. @@ -225,7 +216,7 @@ if timestamp > math.MaxInt64 { return fmt.Errorf("timestamp %d exceeds 2^63-1", timestamp) } - cosignedMessage, err := marshalCheckpointMessage(v.name, timestamp, origin, tree.N, tree.Hash) + cosignedMessage, err := marshalCheckpointMessage(v.keyName, timestamp, origin, tree.N, tree.Hash) if err != nil { return err } @@ -241,28 +232,26 @@ // and root hash from noteText, so extension lines do not affect the result. // Verify is the note.Verifier entry point. For an already parsed checkpoint, // use VerifyCheckpoint. -func (v *Verifier) Verify(noteText, signature []byte) bool { +func (v *Verifier) Verify(noteText, timestampedSignature []byte) bool { parsed, err := checkpoint.Unmarshal(noteText) if err != nil { return false } - return v.VerifyCheckpoint(parsed.Origin, parsed.Tree, signature) == nil + return v.VerifyCheckpoint(parsed.Origin, parsed.Tree, timestampedSignature) == nil } -// TimestampedSignature verifies signatureLine against noteText with verifier -// and returns the timestamped_signature by verifier's cosigner. An error is -// returned if noteText and signatureLine do not form a well-formed note or if -// verifier rejects the signature. Signatures from unknown keys are ignored. -func TimestampedSignature(noteText, signatureLine []byte, verifier *Verifier) ([]byte, error) { - n, err := note.Open(fmt.Appendf(nil, "%s\n%s", noteText, signatureLine), note.VerifierList(verifier)) +// FilterByVerify returns the timestamped_signature by this verifier's cosigner +// from the signatureLines over noteText, ignoring lines by other keys. It +// errors if the two do not form a well-formed note, if no line is by that +// cosigner, or if its signature does not verify. +func (v *Verifier) FilterByVerify(noteText, signatureLines []byte) ([]byte, error) { + n, err := note.Open(fmt.Appendf(nil, "%s\n%s", noteText, signatureLines), note.VerifierList(v)) if err != nil { return nil, fmt.Errorf("opening the cosigned note: %s", err) } - // verifier is the only verifier in the list, so every signature in n.Sigs - // is by the verifier's cosigner, verified and length-checked. idSignature, err := base64.StdEncoding.DecodeString(n.Sigs[0].Base64) if err != nil { - return nil, fmt.Errorf("decoding the signature by %s: %s", verifier.name, err) + return nil, fmt.Errorf("decoding the signature by %s: %s", v.keyName, err) } return idSignature[keyIDSize:], nil } @@ -283,18 +272,15 @@ return timestampedSignature[timestampSize:], nil } -// SignatureLine verifies rawSignature over the checkpoint described by origin -// and tree, and reassembles the cosigner's note signature line, restoring the -// zero timestamp RawSignature stripped. -func (v *Verifier) SignatureLine(origin string, tree tlog.Tree, rawSignature []byte) ([]byte, error) { +// SignatureLine reassembles the note signature line of the cosigner with the +// given keyName, keyID, and rawSignature. Callers are responsible for ensuring +// the signature line is valid for any note text they append it to. +func SignatureLine(keyName string, keyID uint32, rawSignature []byte) ([]byte, error) { if len(rawSignature) != mldsa.MLDSA44SignatureSize { return nil, fmt.Errorf("raw signature is %d bytes, want %d", len(rawSignature), mldsa.MLDSA44SignatureSize) } - timestamped := make([]byte, timestampedSignatureSize) - copy(timestamped[timestampSize:], rawSignature) - err := v.VerifyCheckpoint(origin, tree, timestamped) - if err != nil { - return nil, err - } - return []byte(signatureLineFor(v.name, v.keyID, timestamped)), nil + idSignature := make([]byte, keyIDSize+timestampedSignatureSize) + binary.BigEndian.PutUint32(idSignature[:keyIDSize], keyID) + copy(idSignature[keyIDSize+timestampSize:], rawSignature) + return []byte(noteSignatureLinePrefix + keyName + " " + base64.StdEncoding.EncodeToString(idSignature) + "\n"), nil }
diff --git a/trees/cosignature/cosignature_test.go b/trees/cosignature/cosignature_test.go index 3f01e01..0254026 100644 --- a/trees/cosignature/cosignature_test.go +++ b/trees/cosignature/cosignature_test.go
@@ -18,7 +18,6 @@ "github.com/letsencrypt/boulder/privatekey" "github.com/letsencrypt/boulder/trees/checkpoint" - "golang.org/x/mod/sumdb/note" "golang.org/x/mod/sumdb/tlog" ) @@ -258,21 +257,27 @@ t.Error("VerifyCheckpoint accepted a cosignature over a different origin") } - line := signatureLineFor(ca.name, ca.keyID, signature) - if !strings.HasPrefix(line, noteSignatureLinePrefix+ca.name+" ") { + line, err := SignatureLine(ca.name, ca.keyID, signature[timestampSize:]) + if err != nil { + t.Fatalf("SignatureLine: %s", err) + } + if !strings.HasPrefix(string(line), noteSignatureLinePrefix+ca.name+" ") { t.Errorf("line %q has unexpected prefix", line) } - extracted, err := TimestampedSignature([]byte(text), []byte(line), v) + extracted, err := v.FilterByVerify([]byte(text), line) if err != nil { t.Fatalf("TimestampedSignature on a reassembled note: %s", err) } if !v.Verify([]byte(text), extracted) { t.Error("Verify rejected an extracted cosignature") } - rebuilt := signatureLineFor(ca.name, ca.keyID, extracted) - if rebuilt != line { - t.Errorf("signatureLineFor = %q, want %q", rebuilt, line) + rebuilt, err := SignatureLine(ca.name, ca.keyID, extracted[timestampSize:]) + if err != nil { + t.Fatalf("SignatureLine: %s", err) + } + if !bytes.Equal(rebuilt, line) { + t.Errorf("SignatureLine = %q, want %q", rebuilt, line) } } @@ -422,13 +427,16 @@ if err != nil { t.Fatalf("CosignCheckpoint: %s", err) } - line := signatureLineFor(ca.name, ca.keyID, cosigned) + line, err := SignatureLine(ca.name, ca.keyID, cosigned[timestampSize:]) + if err != nil { + t.Fatalf("SignatureLine: %s", err) + } v, err := NewVerifier("32473.2", testPubKey(t)) if err != nil { t.Fatalf("NewVerifier: %s", err) } - timestampedSignature, err := TimestampedSignature([]byte(text), []byte(line), v) + timestampedSignature, err := v.FilterByVerify([]byte(text), line) if err != nil { t.Fatalf("TimestampedSignature for the cosigner that signed the note: %s", err) } @@ -440,7 +448,7 @@ if err != nil { t.Fatalf("NewVerifier: %s", err) } - _, err = TimestampedSignature([]byte(text), []byte(line), other) + _, err = other.FilterByVerify([]byte(text), line) if err == nil { t.Error("TimestampedSignature for a cosigner that did not sign the note = nil error, want error") } @@ -455,16 +463,18 @@ idSignature := make([]byte, keyIDSize+64) binary.BigEndian.PutUint32(idSignature[:keyIDSize], v.KeyHash()) line := noteSignatureLinePrefix + v.Name() + " " + base64.StdEncoding.EncodeToString(idSignature) + "\n" - _, err := TimestampedSignature([]byte(exampleCheckpoint), []byte(line), v) + _, err := v.FilterByVerify([]byte(exampleCheckpoint), []byte(line)) if err == nil { t.Error("TimestampedSignature with a 64-byte signature body = nil error, want error") } } -// TestOpenIgnoresUnknownSignatures covers signed-note's "verifiers MUST ignore -// signatures from unknown keys" with a note cosigned for one log by two MTC -// cosigners and opened by one verifier, the shape of every real exchange. -func TestOpenIgnoresUnknownSignatures(t *testing.T) { +// TestFilterByVerifyIgnoresUnknownSignatures covers signed-note's "verifiers +// MUST ignore signatures from unknown keys" with a note cosigned for one log by +// two MTC cosigners and filtered by one verifier, the shape of every mirror +// exchange. checkpoint.Open, which only opens notes we assembled, rejects the +// same note. +func TestFilterByVerifyIgnoresUnknownSignatures(t *testing.T) { known, err := NewCosigner("32473.2", "oid/1.3.6.1.4.1.32473.2.0.42", testSigner(t)) if err != nil { t.Fatalf("NewCosigner: %s", err) @@ -492,37 +502,42 @@ if err != nil { t.Fatalf("CosignCheckpoint: %s", err) } - knownLine := signatureLineFor(known.name, known.keyID, knownSignature) + knownLine, err := SignatureLine(known.name, known.keyID, knownSignature[timestampSize:]) + if err != nil { + t.Fatalf("SignatureLine: %s", err) + } unknownSignature, err := unknown.CosignCheckpoint(parsed.Tree) if err != nil { t.Fatalf("CosignCheckpoint: %s", err) } - unknownLine := signatureLineFor(unknown.name, unknown.keyID, unknownSignature) - signed := []byte(text + "\n" + knownLine + unknownLine) + unknownLine, err := SignatureLine(unknown.name, unknown.keyID, unknownSignature[timestampSize:]) + if err != nil { + t.Fatalf("SignatureLine: %s", err) + } + lines := append(knownLine, unknownLine...) v, err := NewVerifier("32473.2", testPubKey(t)) if err != nil { t.Fatalf("NewVerifier: %s", err) } - cp, n, err := checkpoint.Open(signed, note.VerifierList(v)) + filtered, err := v.FilterByVerify([]byte(text), lines) if err != nil { - t.Fatalf("checkpoint.Open: %s", err) + t.Fatalf("FilterByVerify: %s", err) } - if cp.Origin != known.origin { - t.Errorf("Origin = %q, want %q", cp.Origin, known.origin) + if !bytes.Equal(filtered, knownSignature) { + t.Errorf("FilterByVerify = %x, want the known cosigner's signature %x", filtered, knownSignature) } - if len(n.Sigs) != 1 || n.Sigs[0].Name != known.name { - t.Fatalf("Sigs = %+v, want only the known cosigner's", n.Sigs) - } - if len(n.UnverifiedSigs) != 1 || n.UnverifiedSigs[0].Name != unknown.name { - t.Errorf("UnverifiedSigs = %+v, want the unknown cosigner's", n.UnverifiedSigs) + + _, _, err = checkpoint.Open([]byte(text+"\n"+string(lines)), v) + if err == nil { + t.Error("checkpoint.Open with a signature from an unknown key = nil error, want error") } } // TestSignatureLineRoundTrip checks that a raw signature extracted with -// RawSignature reassembles into a verified signature line, and that -// reassembly rejects short signatures and checkpoints the signature does not -// cover. +// RawSignature reassembles into a signature line that verifies against the +// checkpoint it covers and not against another, and that reassembly rejects +// short signatures. func TestSignatureLineRoundTrip(t *testing.T) { ca, err := NewCosigner("32473.2", "oid/1.3.6.1.4.1.32473.2.0.42", testSigner(t)) if err != nil { @@ -546,11 +561,11 @@ if err != nil { t.Fatalf("NewVerifier: %s", err) } - line, err := v.SignatureLine(ca.Origin(), parsed.Tree, raw) + line, err := SignatureLine(v.Name(), v.KeyHash(), raw) if err != nil { t.Fatalf("SignatureLine: %s", err) } - roundTripped, err := TimestampedSignature([]byte(text), line, v) + roundTripped, err := v.FilterByVerify([]byte(text), line) if err != nil { t.Fatalf("TimestampedSignature rejected the reassembled line: %s", err) } @@ -558,14 +573,14 @@ t.Errorf("round-tripped signature = %x, want %x", roundTripped, timestamped) } - _, err = v.SignatureLine(ca.Origin(), parsed.Tree, raw[1:]) + _, err = SignatureLine(v.Name(), v.KeyHash(), raw[1:]) if err == nil { t.Error("SignatureLine with a short signature = nil error, want error") } - tampered := tlog.Tree{N: parsed.Tree.N + 1, Hash: parsed.Tree.Hash} - _, err = v.SignatureLine(ca.Origin(), tampered, raw) + tampered := ca.origin + "\n20852164\n" + exampleHashB64 + "\n" + _, err = v.FilterByVerify([]byte(tampered), line) if err == nil { - t.Error("SignatureLine over a different tree = nil error, want error") + t.Error("TimestampedSignature accepted the reassembled line over a different tree") } }
diff --git a/trees/tiles/tiles.go b/trees/tiles/tiles.go index bfec680..c29abd3 100644 --- a/trees/tiles/tiles.go +++ b/trees/tiles/tiles.go
@@ -715,24 +715,3 @@ } return body[entriesBegin : len(body)-len(rest)], nil } - -// WriteCheckpoint stores the log's signed checkpoint note at the "checkpoint" -// key under prefix per c2sp.org/tlog-tiles, overwriting the previous one. The -// note must be written only after the tiles its tree covers are published. -func WriteCheckpoint(ctx context.Context, s3c simpleS3, prefix string, signedNote []byte) error { - key := path.Join(prefix, "checkpoint") - contentType := "text/plain; charset=utf-8" - cacheControl := "no-store" - bucket := s3c.Bucket() - _, err := s3c.PutObject(ctx, &s3.PutObjectInput{ - Bucket: &bucket, - Key: &key, - ContentType: &contentType, - CacheControl: &cacheControl, - Body: bytes.NewReader(signedNote), - }) - if err != nil { - return fmt.Errorf("writing s3://%s/%s: %w", bucket, key, err) - } - return nil -}
diff --git a/trees/tiles/tiles_test.go b/trees/tiles/tiles_test.go index 5dc9b9d1..fbe1098 100644 --- a/trees/tiles/tiles_test.go +++ b/trees/tiles/tiles_test.go
@@ -587,36 +587,6 @@ } } -// readCheckpoint fetches the "checkpoint" key under prefix, checking what -// WriteCheckpoint stored. Nothing outside tests reads it back through this -// package. -func readCheckpoint(t *testing.T, s3c *bs3test.FakeS3, prefix string) []byte { - t.Helper() - obj, ok := s3c.Objects[prefix+"/checkpoint"] - if !ok { - t.Fatalf("no checkpoint stored under %q", prefix) - } - return obj.Data -} - -// TestWriteReadCheckpoint checks the checkpoint note round trip and that a -// newer note overwrites the previous one. -func TestWriteReadCheckpoint(t *testing.T) { - fs3 := bs3test.New() - err := WriteCheckpoint(t.Context(), fs3, testPrefix, []byte("first note\n")) - if err != nil { - t.Fatalf("WriteCheckpoint: %s", err) - } - err = WriteCheckpoint(t.Context(), fs3, testPrefix, []byte("second note\n")) - if err != nil { - t.Fatalf("WriteCheckpoint overwriting: %s", err) - } - got := readCheckpoint(t, fs3, testPrefix) - if string(got) != "second note\n" { - t.Errorf("stored checkpoint = %q, want %q", got, "second note\n") - } -} - // TestEntriesForPackage checks reading entry intervals back from stored // bundles in wire form, from both full and partial bundles, and that invalid // and bundle-spanning intervals are rejected.