Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Validate PKCS7 padding correctly #1108

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions btcec/ciphering.go
Original file line number Diff line number Diff line change
Expand Up @@ -208,9 +208,14 @@ func addPKCSPadding(src []byte) []byte {
func removePKCSPadding(src []byte) ([]byte, error) {
length := len(src)
padLength := int(src[length-1])
if padLength > aes.BlockSize || length < aes.BlockSize {
//The padding length must be between 1 and aes block size (16), else invalid:
if padLength > aes.BlockSize || length < aes.BlockSize || padLength == 0 {
return nil, errInvalidPadding
}
//The padding must contain the padding length byte, repeated (RFC2315 10.3.2)
expectedPadding := bytes.Repeat(src[length-1:], padLength)
if !bytes.Equal(src[length-padLength:length], expectedPadding) {
return nil, errInvalidPadding
}

return src[:length-padLength], nil
}
21 changes: 19 additions & 2 deletions btcec/ciphering_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -162,8 +162,25 @@ func TestCipheringErrors(t *testing.T) {
tests2 := []struct {
in []byte // input data
}{
{bytes.Repeat([]byte{0x11}, 17)},
{bytes.Repeat([]byte{0x07}, 15)},
{bytes.Repeat([]byte{0x11}, 17)}, //too long
{bytes.Repeat([]byte{0x07}, 15)}, //too short
{append(bytes.Repeat([]byte{0x07}, 15),
bytes.Repeat([]byte{0x04}, 1)...)}, //invalid padding
{append(bytes.Repeat([]byte{0x07}, 9),
[]byte{0x01, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07}...)}, //invalid padding
{append(bytes.Repeat([]byte{0x07}, 9),
[]byte{0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0xfe, 0x10,
0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10}...)}, //invalid padding
{append(bytes.Repeat([]byte{0x07}, 9),
[]byte{0x01, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07}...)}, //invalid padding
{append(bytes.Repeat([]byte{0x07}, 9),
[]byte{0x01, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07}...)}, //invalid padding
{append(bytes.Repeat([]byte{0x07}, 15),
bytes.Repeat([]byte{0x11}, 1)...)}, //invalid padding length
{append(bytes.Repeat([]byte{0x07}, 15),
bytes.Repeat([]byte{0x00}, 1)...)}, //invalid padding length
{append(bytes.Repeat([]byte{0x07}, 15),
bytes.Repeat([]byte{0xff}, 1)...)}, //invalid padding length
}
for i, test := range tests2 {
_, err = removePKCSPadding(test.in)
Expand Down