crypto: add input data length check in (*PublicKey).DecodeBytes

DecodeBinary works with streams, so it can't do that, but DecodeBytes can and
should. Also fix unmarshalled binary buffer that this check exposed.
This commit is contained in:
Roman Khimov 2020-05-21 14:28:16 +03:00
parent 0ce3a12e87
commit 60bca03577
2 changed files with 13 additions and 1 deletions

View file

@ -158,6 +158,12 @@ func decodeCompressedY(x *big.Int, ylsb uint) (*big.Int, error) {
// DecodeBytes decodes a PublicKey from the given slice of bytes.
func (p *PublicKey) DecodeBytes(data []byte) error {
l := len(data)
if !((l == 1 && data[0] == 0) ||
(l == 33 && (data[0] == 0x02 || data[0] == 0x03)) ||
(l == 65 && data[0] == 0x04)) {
return errors.New("invalid key size/prefix")
}
b := io.NewBinReaderFromBuf(data)
p.DecodeBinary(b)
return b.Err
@ -288,7 +294,7 @@ func (p *PublicKey) UnmarshalJSON(data []byte) error {
return errors.New("wrong format")
}
bytes := make([]byte, l-2)
bytes := make([]byte, hex.DecodedLen(l-2))
_, err := hex.Decode(bytes, data[1:l-1])
if err != nil {
return err

View file

@ -91,6 +91,12 @@ func TestDecodeBytes(t *testing.T) {
require.Equal(t, pubKey, decodedPubKey)
}
func TestDecodeBytesBadInfinity(t *testing.T) {
decodedPubKey := &PublicKey{}
err := decodedPubKey.DecodeBytes([]byte{0, 0, 0})
require.Error(t, err)
}
func TestSort(t *testing.T) {
pubs1 := make(PublicKeys, 10)
for i := range pubs1 {