Skip to content

Commit

Permalink
preliminary Go modules support (#274)
Browse files Browse the repository at this point in the history
* preliminary Go modules support (#2)

#### Summary 

The heart of the change is very small -- we stop overwriting the user's value for the `GO111MODULE` env var in two places. This means we end up respecting whatever the user has set for `GO111MODULE`, and relying on `cmd/go` to interpret the meaning of an unset `GO111MODULE` (which defaults to `auto` for Go 1.11-1.13, and likely will default to `on` at some point during Go 1.14 development).

In addition, there are some comments added, as well as an explicit check for `GOFLAGS=-mod=vendor`, which is not supported.

The tests exercises 'replace' directives, v2+ modules, GO111MODULE set to on|off|auto, running inside GOPATH, running outside GOPATH, the mechanisms by which go-fuzz/go-fuzz-dep is found, as well as vendoring (which is not supported, but it tests that a sensible error is emitted). 

#### Additional Details

Historically, go-fuzz has set up a clean GOPATH environment in a temp directory, instrumented the code for fuzzing coverage, and built the instrumented code in the temp directory.

The current approach is to keep doing that (and not set up a full-blown modules-based environment for building), but use modules to find the code to instrument.

v2+ modules are potentially problematic due to Semantic Import Versioning (with the major version in the import path). However, it turns out to not be too bad to handle it. For a v2+ module created following the 'major branch' approach, the /vN is materialized into a physical directory. For example, the github.com/russross/blackfriday/v2 module ends up in the /tmp/blah/gopath/src/github.com/russross/blackfriday/v2 directory. This should be a valid layout, and people use this layout today (including when manually switching to a 'major subdirectory' approach for a v2+ module, which involves creating a /v2 or /vN directory so that pre-modules toolchains follow a /v2 or /vN import path and find an on-disk layout that they expect without any knowledge of modules).

The approach does not copy go.mod files at all. (Before starting, I was thinking I would need to copy go.mod files to trigger "minimal module awareness", which is a transitional mechanism within cmd/go, but after some experimentation / thinking, I concluded it was not needed based on materializing the /v2).

For tests, I am using the script-driven test facility that the core Go team created for testing cmd/go, which is well tuned to testing the various permutations of modules, including it lets you relatively easily set up go.mod files and source files, run commands and check results. (Some more details of the capability here: https://github.com/golang/go/blob/master/src/cmd/go/testdata/script/README).

* modules support: adjust wording based on first-pass review, and update vendor test (#3)

* travis: attempt to install cmd/testscript

* testing: initial check of 'go-fuzz-build -h' output to see if any testscripts work

* testing: change name of first test script

* travis: check if the 'testscript' cmd seems to function at all.

* testing: use the exec command to invoke 'go-fuzz-build -h'

* testing: create initially failing test case for v2 modules

* travis: run testscript for v2 modules

* testing: remember to use 'exec' to invoke go-fuzz-build

* testing: adjust comments in v2 module testscript

* go-fuzz-build: preliminary module support

* testing: flip  from an expected failure to an expected pass for a module test

* go-fuzz-build: update comments for preliminary modules support

* go-fuzz: preliminary modules support for go-fuzz itself

* travis: go-fuzz-defs sanity check

* travis: additional temp sanity check

* travis: add more comments, some additional sanity checks in case we need to debug in future

* travis: s/go-fuzz-deps/go-fuzz-dep/

* testing: validate behavior of v2 modules

* testing: renamed fuzz_help.txt

* testing: update travis to use the renamed testscripts

* travis: conditionally set GO111MODULE=auto, and test Go 1.13 rather than 1.11

* testing: validate modules outside GOPATH

* testing: validate modules inside GOPATH

* testing: invoke timeout properly

* testing: preliminary test for vendored modules (not yet supported)

* testing: validate how go-fuzz-dep and go-fuzz-defs are found

* travis: run the latest testscripts for modules testing

* testing: fix typo in mod_outside_gopath.txt file name

* travis: fix typo in file name

* go-fuzz-build: detect -mod=vendor

* testing: validate we get a proper error for -mod=vendor

* readme: describe preliminary modules support

* readme: correct typo in modules support

* readme: adjust modules support section

* readme: tweak wording based on PR review

* go-fuzz: tweak comment wording by removing "preliminary modules support"

* go-fuzz-build: tweak comment wording by removing "preliminary modules support"

* mod_vendor.txt: avoid triggering Go 1.14 auto detection of a vendor directory

* readme: update wording based on review

* readme: remove a blank line to re-trigger travis
  • Loading branch information
thepudds authored and josharian committed Oct 22, 2019
1 parent a951146 commit 8cb2038
Show file tree
Hide file tree
Showing 10 changed files with 593 additions and 21 deletions.
42 changes: 32 additions & 10 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,32 +8,37 @@
language: go

# Test Go 1.11 and 1.12 across linux, osx, windows.
# Test Go tip on linux, osx (and explicitly set GO111MODULE=on given Travis sets GO111MODULE=auto).
# Test Go tip on linux, osx (and explicitly set GO111MODULE=auto for tip, given default might change).
matrix:
include:
- os: linux
go: tip
env: SET_GO111MODULE=1
- os: linux
go: "1.12.x"
go: tip
- os: linux
go: "1.11.x"
go: "1.13.x"
- os: linux
go: "1.12.x"
- os: osx
go: tip
env: SET_GO111MODULE=1
- os: osx
go: "1.12.x"
go: tip
- os: osx
go: "1.13.x"
- os: osx
go: "1.11.x"
- os: windows
go: "1.12.x"
- os: windows
go: "1.11.x"
go: "1.13.x"
- os: windows
go: "1.12.x"

# Install coreutils for the 'timeout(1)' utility on windows and osx.
before_install:
- if [[ "$TRAVIS_OS_NAME" == "windows" ]]; then choco install gnuwin32-coreutils.install; fi
- if [[ "$TRAVIS_OS_NAME" == "osx" ]]; then ln -s /usr/local/bin/gtimeout /usr/local/bin/timeout ; fi
- go get -u github.com/rogpeppe/go-internal/cmd/testscript

# Set the import path (including to help with forks).
go_import_path: github.com/dvyukov/go-fuzz
Expand All @@ -44,6 +49,21 @@ script:
- "echo 'verify the timeout utility works, including that it exits with status 124 on timeout.'"
- "(timeout 2 sleep 10; ret=$?; echo timeout ret=$ret; if [[ $ret -eq 124 ]]; then exit 0; fi; exit $ret)"

# Sanity check that the 'testscript' cmd seems to function at all.
# If all the testscripts fail, this is a good one to troubleshoot first.
- cd $GOPATH/src/github.com/dvyukov/go-fuzz
- testscript -v testscripts/fuzz_help.txt

# Run our tests for fuzzing modules.
# If multiple modules testcripts fail, probably makes sense to start by troubleshooting
# the earliest failing testscript.
# TODO: probably makes more sense to move this further down, but place here for now for faster iterations.
- testscript -v testscripts/mod_go_fuzz_dep.txt
- testscript -v testscripts/mod_outside_gopath.txt
- testscript -v testscripts/mod_inside_gopath.txt
- testscript -v testscripts/mod_v2.txt
- testscript -v testscripts/mod_vendor.txt

# Prepare to test the png example from dvyukov/go-fuzz-corpus.
- go get -v -d github.com/dvyukov/go-fuzz-corpus/png
- cd $GOPATH/src/github.com/dvyukov/go-fuzz-corpus/
Expand All @@ -53,9 +73,11 @@ script:
# Reduce chances of future surprises due to any caching.
- rm -rf fuzz.zip ./freshworkdir

# Explicitly set GO111MODULE=on if requested (given Travis sets GO111MODULE=auto).
# This is currently intended to test tip / 1.13, which default to GO111MODULE=on.
- if [[ ! -z "$SET_GO111MODULE" ]]; then export GO111MODULE=on; fi
# Explicitly set GO111MODULE=auto if requested.
# Travis and/or tip might change the default value of GO111MODULE at some point.
# As of 2019-08-31, travis sets GO111MODULE=auto, and tip defaults to 'auto' if
# GO111MODULE is unset.
- if [[ ! -z "$SET_GO111MODULE" ]]; then export GO111MODULE=auto; fi
- echo "GO111MODULE=$GO111MODULE"

# Instrument using go-fuzz-build on the png example Fuzz function.
Expand Down
18 changes: 15 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ Fuzzing is mainly applicable to packages that parse complex inputs (both text
and binary), and is especially useful for hardening of systems that parse inputs
from potentially malicious users (e.g. anything accepted over a network).

**Note:** go-fuzz has recently added preliminary support for fuzzing [Go Modules](github.com/golang/go/wiki/Modules). See the [section below](https://github.com/dvyukov/go-fuzz/blob/master/README.md#modules-support) for more details.
If you encounter a problem with modules, please file an issue with details. A workaround might be to disable modules via `export GO111MODULE=off`.

## Usage

First, you need to write a test function of the form:
Expand Down Expand Up @@ -102,9 +105,6 @@ $ go-fuzz-build
```
This will produce png-fuzz.zip archive.

Note that go-fuzz [does not support modules yet](https://github.com/dvyukov/go-fuzz/issues/195).
`go-fuzz-build` disables modules by setting environment variable `GO111MODULE=off` during the build.

Now we are ready to go:
```
$ go-fuzz
Expand Down Expand Up @@ -136,6 +136,18 @@ value should be less than ~5000, otherwise fuzzer can miss new interesting input
due to hash collisions. And finally ```uptime``` is uptime of the process. This same
information is also served via http (see the ```-http``` flag).

## Modules support

go-fuzz has preliminary support for fuzzing [Go Modules](github.com/golang/go/wiki/Modules).
go-fuzz respects the standard `GO111MODULE` environment variable, which can be set to `on`, `off`, or `auto`.

go-fuzz-build will add a `require` for `github.com/dvyukov/go-fuzz` to your go.mod. If desired, you may remove this once the build is complete.

Vendoring with modules is not yet supported. A `vendor` directory will be ignored, and go-fuzz will report an error if `GOFLAGS=-mod=vendor` is set.

Note that while modules are used to prepare the build, the final instrumented build is still done in GOPATH mode.
For most modules, this should not matter.

## libFuzzer support

go-fuzz-build can also generate an archive file
Expand Down
40 changes: 33 additions & 7 deletions go-fuzz-build/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,15 +61,32 @@ func makeTags() string {
func basePackagesConfig() *packages.Config {
cfg := new(packages.Config)

goFuzzModule, isGoFuzzModuleSet := os.LookupEnv("GOFUZZ111MODULE")
if isGoFuzzModuleSet {
cfg.Env = append(os.Environ(), "GO111MODULE=" + goFuzzModule)
} else {
cfg.Env = append(os.Environ(), "GO111MODULE=off")
}
// Note that we do not set GO111MODULE here in order to respect any GO111MODULE
// setting by the user as we are finding dependencies. Note, however, that
// we are still setting up a GOPATH to build, so we later will force
// GO111MODULE to be off when building so that we are in GOPATH mode.
// If the user has not set GO111MODULE, the meaning here is
// left up to cmd/go (defaulting to 'auto' in Go 1.11-1.13,
// but likely defaulting to 'on' at some point during Go 1.14
// development cycle).
// Also note that we are leaving the overall cfg structure
// in place to support future experimentation, etc.
cfg.Env = os.Environ()
return cfg
}

// checkModVendor reports if the GOFLAGS env variable
// contains -mod=vendor, which enables vendoring for modules.
func checkModVendor() bool {
val := os.Getenv("GOFLAGS")
for _, s := range strings.Split(val, " ") {
if s == "-mod=vendor" {
return true
}
}
return false
}

// main copies the package with all dependent packages into a temp dir,
// instruments Go source files there, and builds setting GOROOT to the temp dir.
func main() {
Expand All @@ -90,6 +107,12 @@ func main() {
if *flagLibFuzzer && *flagRace {
c.failf("-race and -libfuzzer are incompatible")
}
if checkModVendor() {
// We don't support -mod=vendor with modules.
// Part of the issue is go-fuzz-dep and go-fuzz-defs
// won't be in the user's vendor directory.
c.failf("GOFLAGS with -mod=vendor is not supported")
}

c.startProfiling() // start pprof as requested
c.loadPkg(pkg) // load and typecheck pkg
Expand Down Expand Up @@ -504,10 +527,13 @@ func (c *Context) buildInstrumentedBinary(blocks *[]CoverBlock, sonar *[]CoverBl
}
args = append(args, "-o", outf, mainPkg)
cmd := exec.Command("go", args...)

// We are constructing a GOPATH environment, so while building
// we force GOPATH mode here via GO111MODULE=off.
cmd.Env = append(os.Environ(),
"GOROOT="+filepath.Join(c.workdir, "goroot"),
"GOPATH="+filepath.Join(c.workdir, "gopath"),
"GO111MODULE=off", // temporary measure until we have proper module support
"GO111MODULE=off",
)
if out, err := cmd.CombinedOutput(); err != nil {
c.failf("failed to execute go build: %v\n%v", err, string(out))
Expand Down
5 changes: 4 additions & 1 deletion go-fuzz/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,10 @@ func main() {
// Try the default. Best effort only.
var bin string
cfg := new(packages.Config)
cfg.Env = append(os.Environ(), "GO111MODULE=off")
// Note that we do not set GO111MODULE here in order to respect any GO111MODULE
// setting by the user as we are finding dependencies. See modules support
// comments in go-fuzz-build/main.go for more details.
cfg.Env = os.Environ()
pkgs, err := packages.Load(cfg, ".")
if err == nil && len(pkgs) == 1 {
bin = pkgs[0].Name + "-fuzz.zip"
Expand Down
8 changes: 8 additions & 0 deletions testscripts/fuzz_help.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
# Start by seeing if anything works at all.
# This is intended to excercise travis and the testscript cmd invoking go-fuzz.
# If this fails, likely everything else will fail too, but if so might be easier to
# start by troubleshooting this.

# Ask go-fuzz-build to emit its help message, which should be a failing status code.
! exec go-fuzz-build -h
stderr 'Usage of.*go-fuzz-build'
56 changes: 56 additions & 0 deletions testscripts/mod_go_fuzz_dep.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
# These steps validate that go-fuzz/go-fuzz-dep and go-fuzz/go-fuzz-defs are found,
# along with validating how they are currently found, and where they end up being located.

# Enter a simple module with a fuzz function.
# Note that we are outside of GOPATH, so the presence of the 'go.mod' here will
# enable module-module for cmd/go (which is true in Go 1.11-1.13, and likely will be true in 1.14 as well).
cd testmod

# Sanity check the module seems well formed.
exec go list -m all
stdout '^example.com/testmod$'
exec go build

# Sanity check go-fuzz is not in our go.mod, nor reported by 'go list -m all'.
! grep 'github.com/dvyukov/go-fuzz' go.mod
exec go list -m all
! stdout 'github.com/dvyukov/go-fuzz'

# Ask go-fuzz-build to build, including specifying the fuzz function for mod.
exec go-fuzz-build -func=FuzzMod
exists testmod-fuzz.zip

# Sanity check github.com/dvyukov/go-fuzz was added by go-fuzz-build
# to our go.mod and is now visible via 'go list -m all'.
# This is not necessarily a requirement for all time,
# but this is the way the current modules approach for go-fuzz works.
# This is important to make sure the go-fuzz-dep source code is
# findable by go-fuzz-build (when it invokes 'go list').
grep -count=1 '^require github.com/dvyukov/go-fuzz v[^ ]+ // indirect$' go.mod
exec go list -m all
stdout '^example.com/testmod$'
stdout '^github.com/dvyukov/go-fuzz v[^ ]+$'

# Also output directories for go-fuzz-defs and go-fuzz-dep
# in case we need to debug this at some point in the future,
# or in case cmd/go or go-fuzz change in the future
# in some way that moves these out of $GOPATH/pkg/testmod or
# otherwise alters where these are located.
# The exact location might not be critical, but we should be aware of what it is,
# so capture the location here in this test so we know if it changes later.
exec go list -f {{.Dir}} github.com/dvyukov/go-fuzz/go-fuzz-defs
stdout 'gopath.pkg.mod.github.com.dvyukov.go-fuzz@v[^ ]+.go-fuzz-defs$'
exec go list -f {{.Dir}} github.com/dvyukov/go-fuzz/go-fuzz-dep
stdout 'gopath.pkg.mod.github.com.dvyukov.go-fuzz@v[^ ]+.go-fuzz-dep$'

# Define a simple module 'mod' that has a fuzz function.

-- testmod/go.mod --
module example.com/testmod

-- testmod/fuzz.go --
package testmod

func FuzzMod(data []byte) int {
return 0
}
99 changes: 99 additions & 0 deletions testscripts/mod_inside_gopath.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
# These steps validate we can fuzz inside of GOPATH
# with GO111MODULE on and off.

# Here, we purposefully do not test with GO111MODULE auto and unset,
# because the meaning of auto within GOPATH has changed with
# Go 1.13, and the meaning of unset will likely change in Go 1.14
# (and some chance auto could change meaning again in Go 1.14).
# However, the Go 1.13 and 1.14 changes ultimately translate
# to what external conditions enable or disable module mode
# for cmd/go. Testing here with GO111MODULE on and off allows
# us to explicitly test with cmd/go's module mode enabled and disabled in GOPATH,
# which is our current goal here. (These are not cmd/go tests after all).

# The foo module being fuzzed depends on a 'replace'
# in its go.mod to find one of its dependencies, and that dependency bar
# is located *outside* of GOPATH, which is a way to check that
# module-mode is required to compile successfully.
# (Other go-fuzz tests validate that non-module targets work in GOPATH with
# cmd/go's module mode disabled; that has been the status quo).

# Enter a simple module with a fuzz function.
# This is inside GOPATH.
cd gopath/src/example.com/foo

# Copy a pristine go.mod file.
cp go.mod_PRISTINE go.mod

# First, we test with GO111MODULE=on, which will likely be the default in Go 1.14.
env GO111MODULE=on

# Sanity check the module seems well formed.
exec go list -m all
stdout '^example.com/foo$'
exec go build

# Ask go-fuzz-build to build, including specifying the fuzz function for mod.
exec go-fuzz-build -func=FuzzMod
exists foo-fuzz.zip

# Validate we can start fuzzing.
# Note that 'timeout(1)' will error here, so we preface the invocation with '!'.
# For travis on Windows, we install 'timeout(1)' as part of our travis setup steps.
# To test this locally on Windows, you might need to change 'timeout' to '\cygwin64\bin\timeout' or similar.
! exec timeout 5 go-fuzz -procs=1 -func=FuzzMod
stderr 'workers: \d+, corpus: '

# Clean up.
cp go.mod_PRISTINE go.mod
rm foo-fuzz.zip

# Second, we test with GO111MODULE=off.
# The meaning of this is unlikely to change in Go 1.14,
# altough in some (distant?) future, GO111MODULE=off might
# no longer be supported.
env GO111MODULE=off

# Confirm 'go list -m' and 'go build' fail.
! exec go list -m all
! exec go build

# Confirm go-fuzz-build fails.
! exec go-fuzz-build -func=FuzzMod
! exists foo-fuzz.zip

# Clean up (mainly in case we later add another test below).
cp go.mod_PRISTINE go.mod
rm foo-fuzz.zip

# Define two modules.
# example.com/foo has a fuzz function, and depends on example.com/bar.
# foo is inside GOPATH, and bar is outside of GOPATH.

-- gopath/src/example.com/foo/go.mod_PRISTINE --
module example.com/foo

require example.com/bar v0.0.0

replace example.com/bar => ../../../../bar

-- gopath/src/example.com/foo/fuzz.go --
package foo

import "example.com/bar"

func FuzzMod(data []byte) int {
bar.Bar()
return 0
}

-- bar/go.mod --
module example.com/bar

-- bar/bar.go --
package bar

func Bar() string {
return "hello from bar"
}

Loading

0 comments on commit 8cb2038

Please sign in to comment.