Skip to content

Commit

Permalink
fix: verify num-val could fit a whole byte, not half of it
Browse files Browse the repository at this point in the history
  • Loading branch information
pandatix committed Sep 5, 2024
1 parent 48627fb commit 6ae4a72
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
10 changes: 6 additions & 4 deletions grammar.go
Original file line number Diff line number Diff line change
Expand Up @@ -814,22 +814,24 @@ func semvalAlternation(alt Alternation) error {
val = strings.TrimLeft(val, "0")
switch elem.Base {
case "B", "b":
if len(val) > 7 { // 7 = ceil(log(base, 2^|us-ascii|)), base=2
// 8 bits to fill a byte, reject more
if len(val) > 8 {
return &ErrTooLargeNumeral{
Base: elem.Base,
Value: val,
}
}
case "D", "d":
// 3 = ceil(log(base, 2^|us-ascii|)), base=10
if len(val) > 3 || (len(val) == 3 && (val[0] > '1' || (val[0] == '1' && (val[1] > '2' || (val[1] == '2' && val[2] > '7'))))) {
// 3 = ceil(log(base, 2^8)), base=10, maximal value of 255 (included)
if len(val) > 3 || (len(val) == 3 && (val[0] > '2' || (val[0] == '2' && (val[1] > '5' || (val[1] == '5' && val[2] > '5'))))) {
return &ErrTooLargeNumeral{
Base: elem.Base,
Value: val,
}
}
case "X", "x":
if len(val) > 2 || (len(val) == 2 && val[0] > '7') { // 2 = ceil(log(base, 2^|us-ascii|)), base=16
// 2 hex to fill a byte, reject more
if len(val) > 2 {
return &ErrTooLargeNumeral{
Base: elem.Base,
Value: val,
Expand Down
30 changes: 30 additions & 0 deletions grammar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,36 @@ var testsParseAbnf = map[string]struct {
Validate: false,
ExpectErr: false,
},
"binary-maximal": {
Input: []byte("a = %b00000000-11111111\r\n"),
Validate: true,
ExpectErr: false,
},
"binary-out": {
Input: []byte("a = %b0000000000000-111111110"),
Validate: true,
ExpectErr: true,
},
"decimal-maximal": {
Input: []byte("a = %d000-255\r\n"),
Validate: true,
ExpectErr: false,
},
"decimal-out": {
Input: []byte("a = %d000000-256"),
Validate: true,
ExpectErr: true,
},
"hexadecimal-maximal": {
Input: []byte("a = %x00-0FF\r\n"),
Validate: true,
ExpectErr: false,
},
"hexadecimal-out": {
Input: []byte("a = %x000-FF0"),
Validate: true,
ExpectErr: true,
},
}

func Test_U_ParseABNF(t *testing.T) {
Expand Down

0 comments on commit 6ae4a72

Please sign in to comment.