Skip to content

Commit d55c284

Browse files
committed
more validation checks
1 parent c1bd101 commit d55c284

2 files changed

Lines changed: 41 additions & 0 deletions

File tree

component.go

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package multiaddr
22

33
import (
4+
"bytes"
45
"encoding/binary"
56
"encoding/json"
67
"fmt"
@@ -217,6 +218,43 @@ func newComponent(protocol Protocol, bvalue []byte) (Component, error) {
217218
// It ensures that we will be able to call all methods on Component without
218219
// error.
219220
func validateComponent(c Component) (Component, error) {
221+
if c.valueStartIdx > len(c.bytes) {
222+
return Component{}, fmt.Errorf("component valueStartIdx is greater than the length of the component's bytes")
223+
}
224+
225+
if len(c.protocol.VCode) == 0 {
226+
return Component{}, fmt.Errorf("Component is missing its protocol's VCode field")
227+
}
228+
if len(c.bytes) < len(c.protocol.VCode) {
229+
return Component{}, fmt.Errorf("component size mismatch: %d != %d", len(c.bytes), len(c.protocol.VCode))
230+
}
231+
if !bytes.Equal([]byte(c.bytes[:len(c.protocol.VCode)]), c.protocol.VCode) {
232+
return Component{}, fmt.Errorf("component's VCode field is invalid: %v != %v", []byte(c.bytes[:len(c.protocol.VCode)]), c.protocol.VCode)
233+
}
234+
if c.protocol.Size < 0 {
235+
size, n, err := ReadVarintCode([]byte(c.bytes[len(c.protocol.VCode):]))
236+
if err != nil {
237+
return Component{}, err
238+
}
239+
if size != len(c.bytes[c.valueStartIdx:]) {
240+
return Component{}, fmt.Errorf("component value size mismatch: %d != %d", size, len(c.bytes[c.valueStartIdx:]))
241+
}
242+
243+
if len(c.protocol.VCode)+n+size != len(c.bytes) {
244+
return Component{}, fmt.Errorf("component size mismatch: %d != %d", len(c.protocol.VCode)+n+size, len(c.bytes))
245+
}
246+
} else {
247+
// Fixed size value
248+
size := c.protocol.Size / 8
249+
if size != len(c.bytes[c.valueStartIdx:]) {
250+
return Component{}, fmt.Errorf("component value size mismatch: %d != %d", size, len(c.bytes[c.valueStartIdx:]))
251+
}
252+
253+
if len(c.protocol.VCode)+size != len(c.bytes) {
254+
return Component{}, fmt.Errorf("component size mismatch: %d != %d", len(c.protocol.VCode)+size, len(c.bytes))
255+
}
256+
}
257+
220258
_, err := c.valueAndErr()
221259
if err != nil {
222260
return Component{}, err

protocol.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,9 @@ func AddProtocol(p Protocol) error {
6565
if p.Path && p.Size >= 0 {
6666
return fmt.Errorf("path protocols must have variable-length sizes")
6767
}
68+
if len(p.VCode) == 0 {
69+
return fmt.Errorf("protocol code %d is missing its VCode field", p.Code)
70+
}
6871

6972
Protocols = append(Protocols, p)
7073
protocolsByName[p.Name] = p

0 commit comments

Comments
 (0)