Repository: fxamacker/cbor (go)

Issue:
Using `ByteSliceMode` (unreleased new feature) can encode invalid CBOR data
`ByteSliceMode` is a new feature planned for v2.7.0 (not yet released) and was added by:
- #476

Unfortunately, using the non-default encoding setting for `ByteSliceMode` can produce invalid CBOR data in some edge cases.

This problem was discovered by fuzzing.

### Reproducer

Steps:
- Create an encoding mode with `ByteSliceMode` set to any non-default option
- Encode `cbor.Tag` with tag content of `[]byte` type
 
```Go
func main() {
	data := []byte{
		0xc2, 0x49, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
	} // 2(h'010000000000000000')

	var v1 cbor.Tag
	err := cbor.Unmarshal(data, &v1)
	if err != nil {
		fmt.Printf("failed to unmarshal %x cbor.Tag: %s\n", data, err)
		return
	}

	em, _ := cbor.EncOptions{
		ByteSlice: cbor.ByteSliceToByteStringWithExpectedConversionToBase64URL,
	}.EncMode()
	b, err := em.Marshal(v1)
	if err != nil {
		fmt.Printf("failed to marshal: %s\n", err)
		return
	}

	var v2 interface{}
	err = cbor.Unmarshal(b, &v2)
	if err != nil {
		fmt.Printf("failed to unmarshal %x to interface{}: %s\n", b, err)
	}

	// Output:
	// failed to unmarshal c2d549010000000000000000 to interface{}: cbor: tag number 2 or 3 must be followed by byte string, got tag
}
```

**Expected**: The code snippet should produce valid CBOR data `2(h'010000000000000000')`.

**Got**: The code snippet produces invalid CBOR data `2(21(h'010000000000000000'))`.

cc: @benluddy 

EDIT: s/malformed/invalid

Pull request:
Disable conflicting encode options when marshaling cbor.Tag.
Closes #545

Encode options, especially those that control the mapping from Go type to CBOR type, can result in output containing tag validity errors. For tag numbers that are built in, it's possible to "do the right thing" and override those options on a case-by-case basis. This can't and does not prevent tag validity errors for unrecognized tag numbers.

<!--
Thank you for your interest in contributing to fxamacker/cbor!
-->

### Description


<!-- For code contributions, please complete all the items below this line. -->
<!-- For documentation-only contributions, please delete everything below this line. -->

#### PR Was Proposed and Welcomed in Currently Open Issue

- [ ] This PR was proposed and welcomed by maintainer(s) in issue #___
- [x] Closes or Updates Issue #545

#### Checklist (for code PR only, ignore for docs PR)

- [x] Include unit tests that cover the new code
- [x] Pass all unit tests 
- [x] Pass all lint checks in CI (goimports, gosec, staticcheck, etc.)
- [x] Sign each commit with your real name and email.  
      Last line of each commit message should be in this format:  
      Signed-off-by: Firstname Lastname <firstname.lastname@example.com>
- [x] Certify the Developer's Certificate of Origin 1.1
      (see next section).

#### Certify the Developer's Certificate of Origin 1.1

- [x] By marking this item as completed, I certify 
      the Developer Certificate of Origin 1.1.

```
Developer Certificate of Origin
Version 1.1

Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
660 York Street, Suite 102,
San Francisco, CA 94110 USA

Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.

Developer's Certificate of Origin 1.1

By making a contribution to this project, I certify that:

(a) The contribution was created in whole or in part by me and I
    have the right to submit it under the open source license
    indicated in the file; or

(b) The contribution is based upon previous work that, to the best
    of my knowledge, is covered under an appropriate open source
    license and I have the right under that license to submit that
    work with modifications, whether created in whole or in part
    by me, under the same open source license (unless I am
    permitted to submit under a different license), as indicated
    in the file; or

(c) The contribution was provided directly to me by some other
    person who certified (a), (b) or (c) and I have not modified
    it.

(d) I understand and agree that this project and the contribution
    are public and that a record of the contribution (including all
    personal information I submit with it, including my sign-off) is
    maintained indefinitely and may be redistributed consistent with
    this project or the open source license(s) involved.
```



Patch:
diff --git a/encode.go b/encode.go
index b45147f..ebef78f 100644
--- a/encode.go
+++ b/encode.go
@@ -1648,8 +1648,21 @@ func encodeTag(e *bytes.Buffer, em *encMode, v reflect.Value) error {
 	// Marshal tag number
 	encodeHead(e, byte(cborTypeTag), t.Number)
 
+	vem := *em // shallow copy
+
+	// For built-in tags, disable settings that may introduce tag validity errors when
+	// marshaling certain Content values.
+	switch t.Number {
+	case tagNumRFC3339Time:
+		vem.stringType = StringToTextString
+		vem.stringMajorType = cborTypeTextString
+	case tagNumUnsignedBignum, tagNumNegativeBignum:
+		vem.byteSlice = ByteSliceToByteString
+		vem.byteSliceEncodingTag = 0
+	}
+
 	// Marshal tag content
-	return encode(e, em, reflect.ValueOf(t.Content))
+	return encode(e, &vem, reflect.ValueOf(t.Content))
 }
 
 // encodeHead writes CBOR head of specified type t and returns number of bytes written.
diff --git a/tag.go b/tag.go
index 4c9c99f..5c4d2b7 100644
--- a/tag.go
+++ b/tag.go
@@ -7,7 +7,9 @@ import (
 	"sync"
 )
 
-// Tag represents CBOR tag data, including tag number and unmarshaled tag content.
+// Tag represents CBOR tag data, including tag number and unmarshaled tag content. Marshaling and
+// unmarshaling of tag content is subject to any encode and decode options that would apply to
+// enclosed data item if it were to appear outside of a tag.
 type Tag struct {
 	Number  uint64
 	Content interface{}


Test patch:
diff --git a/tag_test.go b/tag_test.go
index fd9246d..f5917c4 100644
--- a/tag_test.go
+++ b/tag_test.go
@@ -1490,3 +1490,49 @@ func TestMarshalRawTagContainingMalformedCBORData(t *testing.T) {
 		})
 	}
 }
+
+// TestEncodeBuiltinTag tests that marshaling a value of type Tag "does the right thing" when
+// marshaling the enclosed data item of a built-in tag number.
+func TestEncodeBuiltinTag(t *testing.T) {
+	for _, tc := range []struct {
+		name string
+		tag  Tag
+		opts EncOptions
+		want []byte
+	}{
+		{
+			name: "unsigned bignum content not enclosed in expected encoding tag",
+			tag:  Tag{Number: tagNumUnsignedBignum, Content: []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
+			opts: EncOptions{ByteSlice: ByteSliceExpectedEncodingBase16},
+			want: []byte{0xc2, 0x49, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		},
+		{
+			name: "negative bignum content not enclosed in expected encoding tag",
+			tag:  Tag{Number: tagNumNegativeBignum, Content: []byte{0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}},
+			opts: EncOptions{ByteSlice: ByteSliceExpectedEncodingBase16},
+			want: []byte{0xc3, 0x49, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00},
+		},
+		{
+			name: "rfc 3339 content is not encoded as byte string",
+			tag:  Tag{Number: tagNumRFC3339Time, Content: "2013-03-21T20:04:00Z"},
+			opts: EncOptions{String: StringToByteString},
+			want: hexDecode("c074323031332d30332d32315432303a30343a30305a"),
+		},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			em, err := tc.opts.EncMode()
+			if err != nil {
+				t.Fatal(err)
+			}
+
+			got, err := em.Marshal(tc.tag)
+			if err != nil {
+				t.Fatal(err)
+			}
+
+			if !bytes.Equal(got, tc.want) {
+				t.Errorf("unexpected difference\ngot: 0x%x\nwant: 0x%x", got, tc.want)
+			}
+		})
+	}
+}