2019-12-19 13:53:31 -08:00
|
|
|
// Copyright 2019 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
// Package wirefuzz includes a fuzzer for the wire marshaler and unmarshaler.
|
|
|
|
package wirefuzz
|
|
|
|
|
|
|
|
import (
|
2019-12-16 09:37:59 -08:00
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"google.golang.org/protobuf/internal/impl"
|
2019-12-19 13:53:31 -08:00
|
|
|
"google.golang.org/protobuf/proto"
|
2019-12-16 09:37:59 -08:00
|
|
|
piface "google.golang.org/protobuf/runtime/protoiface"
|
2019-12-19 13:53:31 -08:00
|
|
|
|
|
|
|
fuzzpb "google.golang.org/protobuf/internal/testprotos/fuzz"
|
|
|
|
)
|
|
|
|
|
|
|
|
// Fuzz is a fuzzer for proto.Marshal and proto.Unmarshal.
|
|
|
|
func Fuzz(data []byte) (score int) {
|
|
|
|
m1 := &fuzzpb.Fuzz{}
|
2020-02-14 14:49:35 -08:00
|
|
|
vout, valid := impl.Validate(m1.ProtoReflect().Type(), piface.UnmarshalInput{
|
|
|
|
Buf: data,
|
2019-12-16 09:37:59 -08:00
|
|
|
})
|
2020-02-14 14:49:35 -08:00
|
|
|
vinit := vout.Flags&piface.UnmarshalInitialized != 0
|
2019-12-19 13:53:31 -08:00
|
|
|
if err := (proto.UnmarshalOptions{
|
|
|
|
AllowPartial: true,
|
|
|
|
}).Unmarshal(data, m1); err != nil {
|
2019-12-16 09:37:59 -08:00
|
|
|
switch valid {
|
|
|
|
case impl.ValidationUnknown:
|
|
|
|
case impl.ValidationInvalid:
|
|
|
|
default:
|
|
|
|
panic("unmarshal error with validation status: " + valid.String())
|
|
|
|
}
|
2019-12-19 13:53:31 -08:00
|
|
|
return 0
|
|
|
|
}
|
2020-02-03 16:17:31 -08:00
|
|
|
switch valid {
|
|
|
|
case impl.ValidationUnknown:
|
|
|
|
case impl.ValidationValid:
|
|
|
|
default:
|
|
|
|
panic("unmarshal ok with validation status: " + valid.String())
|
|
|
|
}
|
2020-02-20 10:05:37 -08:00
|
|
|
if proto.CheckInitialized(m1) != nil && vinit {
|
2020-02-03 16:17:31 -08:00
|
|
|
panic("validation reports partial message is initialized")
|
2019-12-16 09:37:59 -08:00
|
|
|
}
|
2019-12-19 13:53:31 -08:00
|
|
|
data1, err := proto.MarshalOptions{
|
|
|
|
AllowPartial: true,
|
|
|
|
}.Marshal(m1)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
if proto.Size(m1) != len(data1) {
|
2019-12-16 09:37:59 -08:00
|
|
|
panic(fmt.Errorf("size does not match output %v", m1))
|
2019-12-19 13:53:31 -08:00
|
|
|
}
|
|
|
|
m2 := &fuzzpb.Fuzz{}
|
|
|
|
if err := (proto.UnmarshalOptions{
|
|
|
|
AllowPartial: true,
|
|
|
|
}).Unmarshal(data1, m2); err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
if !proto.Equal(m1, m2) {
|
|
|
|
panic("not equal")
|
|
|
|
}
|
|
|
|
return 1
|
|
|
|
}
|