Skip to content

Commit

Permalink
fix and check bounds reading packets (#40)
Browse files Browse the repository at this point in the history
  • Loading branch information
imsodin authored Apr 12, 2021
1 parent 3a7a6d9 commit 4e5e57c
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
14 changes: 10 additions & 4 deletions stun/packet.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import (
"crypto/rand"
"encoding/binary"
"errors"
"math"
)

type packet struct {
Expand All @@ -41,21 +42,26 @@ func newPacket() (*packet, error) {
}

func newPacketFromBytes(packetBytes []byte) (*packet, error) {
if len(packetBytes) < 24 {
if len(packetBytes) < 20 {
return nil, errors.New("Received data length too short.")
}
if len(packetBytes) > math.MaxUint16+20 {
return nil, errors.New("Received data length too long.")
}
pkt := new(packet)
pkt.types = binary.BigEndian.Uint16(packetBytes[0:2])
pkt.length = binary.BigEndian.Uint16(packetBytes[2:4])
pkt.transID = packetBytes[4:20]
pkt.attributes = make([]attribute, 0, 10)
for pos := uint16(20); pos < uint16(len(packetBytes)); {
packetBytes = packetBytes[20:]
for pos := uint16(0); pos+4 < uint16(len(packetBytes)); {
types := binary.BigEndian.Uint16(packetBytes[pos : pos+2])
length := binary.BigEndian.Uint16(packetBytes[pos+2 : pos+4])
if pos+4+length > uint16(len(packetBytes)) {
end := pos + 4 + length
if end < pos+4 || end > uint16(len(packetBytes)) {
return nil, errors.New("Received data format mismatch.")
}
value := packetBytes[pos+4 : pos+4+length]
value := packetBytes[pos+4 : end]
attribute := newAttribute(types, value)
pkt.addAttribute(*attribute)
pos += align(length) + 4
Expand Down
6 changes: 3 additions & 3 deletions stun/packet_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ import (
)

func TestNewPacketFromBytes(t *testing.T) {
b := make([]byte, 23)
b := make([]byte, 19)
_, err := newPacketFromBytes(b)
if err == nil {
t.Errorf("newPacketFromBytes error")
}
b = make([]byte, 24)
b = make([]byte, 20)
_, err = newPacketFromBytes(b)
if err != nil {
t.Errorf("newPacketFromBytes error")
Expand Down Expand Up @@ -53,7 +53,7 @@ func TestPacketAll(t *testing.T) {
if pkt.types != 0 {
t.Errorf("newPacketFromBytes error")
}
if pkt.length < 24 {
if pkt.length < 20 {
t.Errorf("newPacketFromBytes error")
}
}

0 comments on commit 4e5e57c

Please sign in to comment.