Repository: fxamacker/cbor
Pull request #527 (2024-04-26 19:25:21)

Add option to reject decoding bignum tags and encoding big.Int.
<!--
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. -->

This allows encode and decode modes to be configured for applications whose CBOR-based protocols do not allow the bignum tags (https://www.rfc-editor.org/rfc/rfc8949.html#section-5-3).

#### 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 #528

#### 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/decode.go b/decode.go
index 91aa5d1..ae4f365 100644
--- a/decode.go
+++ b/decode.go
@@ -630,6 +630,25 @@ func (bseem ByteSliceExpectedEncodingMode) valid() bool {
 	return bseem >= 0 && bseem < maxByteSliceExpectedEncodingMode
 }
 
+// BignumTagMode specifies whether or not the "bignum" tags 2 and 3 (RFC 8949 Section 3.4.3) can be
+// decoded.
+type BignumTagMode int
+
+const (
+	// BignumTagAllowed allows bignum tags to be decoded.
+	BignumTagAllowed BignumTagMode = iota
+
+	// BignumTagForbidden produces an UnacceptableDataItemError during Unmarshal if a bignum tag
+	// is encountered in the input.
+	BignumTagForbidden
+
+	maxBignumTag
+)
+
+func (btm BignumTagMode) valid() bool {
+	return btm >= 0 && btm < maxBignumTag
+}
+
 // BinaryUnmarshalerMode specifies how to decode into types that implement
 // encoding.BinaryUnmarshaler.
 type BinaryUnmarshalerMode int
@@ -771,6 +790,12 @@ type DecOptions struct {
 	// "expected later encoding" tag (RFC 8949 Section 3.4.5.2) into a Go byte slice.
 	ByteSliceExpectedEncoding ByteSliceExpectedEncodingMode
 
+	// BignumTag specifies whether or not the "bignum" tags 2 and 3 (RFC 8949 Section 3.4.3) can
+	// be decoded. Unlike BigIntDec, this option applies to all bignum tags encountered in a
+	// CBOR input, independent of the type of the destination value of a particular Unmarshal
+	// operation.
+	BignumTag BignumTagMode
+
 	// BinaryUnmarshaler specifies how to decode into types that implement
 	// encoding.BinaryUnmarshaler.
 	BinaryUnmarshaler BinaryUnmarshalerMode
@@ -977,6 +1002,10 @@ func (opts DecOptions) decMode() (*decMode, error) {
 		return nil, errors.New("cbor: invalid ByteSliceExpectedEncoding " + strconv.Itoa(int(opts.ByteSliceExpectedEncoding)))
 	}
 
+	if !opts.BignumTag.valid() {
+		return nil, errors.New("cbor: invalid BignumTag " + strconv.Itoa(int(opts.BignumTag)))
+	}
+
 	if !opts.BinaryUnmarshaler.valid() {
 		return nil, errors.New("cbor: invalid BinaryUnmarshaler " + strconv.Itoa(int(opts.BinaryUnmarshaler)))
 	}
@@ -1006,6 +1035,7 @@ func (opts DecOptions) decMode() (*decMode, error) {
 		infDec:                    opts.Inf,
 		byteStringToTime:          opts.ByteStringToTime,
 		byteSliceExpectedEncoding: opts.ByteSliceExpectedEncoding,
+		bignumTag:                 opts.BignumTag,
 		binaryUnmarshaler:         opts.BinaryUnmarshaler,
 	}
 
@@ -1084,6 +1114,7 @@ type decMode struct {
 	infDec                    InfMode
 	byteStringToTime          ByteStringToTimeMode
 	byteSliceExpectedEncoding ByteSliceExpectedEncodingMode
+	bignumTag                 BignumTagMode
 	binaryUnmarshaler         BinaryUnmarshalerMode
 }
 
@@ -1123,6 +1154,7 @@ func (dm *decMode) DecOptions() DecOptions {
 		Inf:                       dm.infDec,
 		ByteStringToTime:          dm.byteStringToTime,
 		ByteSliceExpectedEncoding: dm.byteSliceExpectedEncoding,
+		BignumTag:                 dm.bignumTag,
 		BinaryUnmarshaler:         dm.binaryUnmarshaler,
 	}
 }
diff --git a/encode.go b/encode.go
index 40f79da..f068a9c 100644
--- a/encode.go
+++ b/encode.go
@@ -318,6 +318,9 @@ const (
 	// converting it to another CBOR type.
 	BigIntConvertNone
 
+	// BigIntConvertReject returns an UnsupportedTypeError instead of marshaling a big.Int.
+	BigIntConvertReject
+
 	maxBigIntConvert
 )
 
@@ -1505,6 +1508,10 @@ func encodeTime(e *bytes.Buffer, em *encMode, v reflect.Value) error {
 }
 
 func encodeBigInt(e *bytes.Buffer, em *encMode, v reflect.Value) error {
+	if em.bigIntConvert == BigIntConvertReject {
+		return &UnsupportedTypeError{Type: typeBigInt}
+	}
+
 	vbi := v.Interface().(big.Int)
 	sign := vbi.Sign()
 	bi := new(big.Int).SetBytes(vbi.Bytes()) // bi is absolute value of v
diff --git a/valid.go b/valid.go
index 15ae19f..2fa5497 100644
--- a/valid.go
+++ b/valid.go
@@ -99,7 +99,7 @@ func (d *decoder) wellformed(allowExtraData bool, checkBuiltinTags bool) error {
 }
 
 // wellformedInternal checks data's well-formedness and returns max depth and error.
-func (d *decoder) wellformedInternal(depth int, checkBuiltinTags bool) (int, error) {
+func (d *decoder) wellformedInternal(depth int, checkBuiltinTags bool) (int, error) { // nolint:gocyclo
 	t, ai, val, err := d.wellformedHead()
 	if err != nil {
 		return 0, err
@@ -188,6 +188,12 @@ func (d *decoder) wellformedInternal(depth int, checkBuiltinTags bool) (int, err
 					return 0, err
 				}
 			}
+			if d.dm.bignumTag == BignumTagForbidden && (tagNum == 2 || tagNum == 3) {
+				return 0, &UnacceptableDataItemError{
+					CBORType: cborTypeTag.String(),
+					Message:  "bignum",
+				}
+			}
 			if cborType(d.data[d.off]&0xe0) != cborTypeTag {
 				break
 			}


Test patch:
diff --git a/decode_test.go b/decode_test.go
index 2e7fc77..7e05f30 100644
--- a/decode_test.go
+++ b/decode_test.go
@@ -4923,6 +4923,7 @@ func TestDecOptions(t *testing.T) {
 		Inf:                       InfDecodeForbidden,
 		ByteStringToTime:          ByteStringToTimeAllowed,
 		ByteSliceExpectedEncoding: ByteSliceToByteStringWithExpectedConversionToBase64,
+		BignumTag:                 BignumTagForbidden,
 		BinaryUnmarshaler:         BinaryUnmarshalerNone,
 	}
 	ov := reflect.ValueOf(opts1)
@@ -10007,3 +10008,95 @@ func TestBinaryUnmarshalerMode(t *testing.T) {
 		})
 	}
 }
+
+func TestDecModeInvalidBignumTag(t *testing.T) {
+	for _, tc := range []struct {
+		name         string
+		opts         DecOptions
+		wantErrorMsg string
+	}{
+		{
+			name:         "below range of valid modes",
+			opts:         DecOptions{BignumTag: -1},
+			wantErrorMsg: "cbor: invalid BignumTag -1",
+		},
+		{
+			name:         "above range of valid modes",
+			opts:         DecOptions{BignumTag: 101},
+			wantErrorMsg: "cbor: invalid BignumTag 101",
+		},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			_, err := tc.opts.DecMode()
+			if err == nil {
+				t.Errorf("Expected non nil error from DecMode()")
+			} else if err.Error() != tc.wantErrorMsg {
+				t.Errorf("Expected error: %q, want: %q \n", tc.wantErrorMsg, err.Error())
+			}
+		})
+	}
+}
+
+func TestBignumTagMode(t *testing.T) {
+	for _, tc := range []struct {
+		name           string
+		opt            DecOptions
+		input          []byte
+		wantErrMessage string // if "" then expect nil error
+	}{
+		{
+			name:  "default options decode unsigned bignum without error",
+			opt:   DecOptions{},
+			input: hexDecode("c240"), // 2(0) i.e. unsigned bignum 0
+		},
+		{
+			name:  "default options decode negative bignum without error",
+			opt:   DecOptions{},
+			input: hexDecode("c340"), // 3(0) i.e. negative bignum -1
+		},
+		{
+			name:           "BignumTagForbidden returns UnacceptableDataItemError on unsigned bignum",
+			opt:            DecOptions{BignumTag: BignumTagForbidden},
+			input:          hexDecode("c240"), // 2(0) i.e. unsigned bignum 0
+			wantErrMessage: "cbor: data item of cbor type tag is not accepted by protocol: bignum",
+		},
+		{
+			name:           "BignumTagForbidden returns UnacceptableDataItemError on negative bignum",
+			opt:            DecOptions{BignumTag: BignumTagForbidden},
+			input:          hexDecode("c340"), // 3(0) i.e. negative bignum -1
+			wantErrMessage: "cbor: data item of cbor type tag is not accepted by protocol: bignum",
+		},
+	} {
+		t.Run(tc.name, func(t *testing.T) {
+			dm, err := tc.opt.DecMode()
+			if err != nil {
+				t.Fatal(err)
+			}
+
+			for _, dstType := range []reflect.Type{
+				typeInt64,
+				typeFloat64,
+				typeByteArray,
+				typeByteSlice,
+				typeBigInt,
+				typeIntf,
+			} {
+				t.Run(dstType.String(), func(t *testing.T) {
+					dstv := reflect.New(dstType)
+					err = dm.Unmarshal(tc.input, dstv.Interface())
+					if err != nil {
+						if tc.wantErrMessage == "" {
+							t.Errorf("want nil error, got: %v", err)
+						} else if gotErrMessage := err.Error(); gotErrMessage != tc.wantErrMessage {
+							t.Errorf("want error: %q, got error: %q", tc.wantErrMessage, gotErrMessage)
+						}
+					} else {
+						if tc.wantErrMessage != "" {
+							t.Errorf("got nil error, want: %s", tc.wantErrMessage)
+						}
+					}
+				})
+			}
+		})
+	}
+}
diff --git a/encode_test.go b/encode_test.go
index 835c534..7a6cd65 100644
--- a/encode_test.go
+++ b/encode_test.go
@@ -4676,6 +4676,23 @@ func TestMarshalByteSliceMode(t *testing.T) {
 	}
 }
 
+func TestBigIntConvertReject(t *testing.T) {
+	em, err := EncOptions{BigIntConvert: BigIntConvertReject}.EncMode()
+	if err != nil {
+		t.Fatal(err)
+	}
+
+	want := &UnsupportedTypeError{Type: typeBigInt}
+
+	if _, err := em.Marshal(big.Int{}); !reflect.DeepEqual(want, err) {
+		t.Errorf("want: %v, got: %v", want, err)
+	}
+
+	if _, err := em.Marshal(&big.Int{}); !reflect.DeepEqual(want, err) {
+		t.Errorf("want: %v, got: %v", want, err)
+	}
+}
+
 func TestEncModeInvalidBinaryMarshalerMode(t *testing.T) {
 	for _, tc := range []struct {
 		name         string