Skip to content

Commit

Permalink
fix(crypto): check message length
Browse files Browse the repository at this point in the history
  • Loading branch information
tdakkota committed Feb 17, 2021
1 parent 1b1b02f commit a4bdb76
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
8 changes: 7 additions & 1 deletion internal/crypto/cipher_decrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,13 @@ func (c Cipher) Decrypt(k AuthKey, encrypted *EncryptedMessage) (*EncryptedMessa
const maxPadding = 1024
n := int(msg.MessageDataLen)
paddingLen := len(msg.MessageDataWithPadding) - n
if paddingLen > maxPadding {

switch {
case n < 0:
return nil, xerrors.Errorf("message length is invalid: %d less than zero", n)
case n%4 != 0:
return nil, xerrors.Errorf("message length is invalid: %d is not divisible by 4", n)
case paddingLen > maxPadding:
return nil, xerrors.Errorf("padding %d of message is too big", paddingLen)
}
}
Expand Down
43 changes: 43 additions & 0 deletions internal/crypto/cipher_decrypt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,13 @@ package crypto

import (
"bytes"
"io"
"testing"

"github.com/stretchr/testify/require"

"github.com/gotd/td/bin"
"github.com/gotd/td/internal/testutil"
)

type Zero struct{}
Expand Down Expand Up @@ -46,3 +50,42 @@ func TestDecrypt(t *testing.T) {
t.Error("mismatch")
}
}

func TestCipher_Decrypt(t *testing.T) {
var key AuthKey
if _, err := io.ReadFull(testutil.Rand([]byte{10}), key.Value[:]); err != nil {
t.Fatal(err)
}

c := NewClientCipher(Zero{})
s := NewServerCipher(Zero{})
tests := []struct {
name string
data []byte
dataLen int
expectErr bool
}{
{"NegativeLength", []byte{1, 2, 3, 4}, -1, true},
{"NoPadBy4", []byte{1, 2, 3}, 3, true},
{"Good", bytes.Repeat([]byte{1, 2, 3, 4}, 4), 16, false},
}

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
a := require.New(t)
b := bin.Buffer{}
data := EncryptedMessageData{
MessageDataLen: int32(test.dataLen),
MessageDataWithPadding: test.data,
}
a.NoError(s.Encrypt(key, data, &b))

_, err := c.DecryptFromBuffer(key, &b)
if test.expectErr {
a.Error(err)
return
}
a.NoError(err)
})
}
}

0 comments on commit a4bdb76

Please sign in to comment.