Skip to content

Commit

Permalink
Merge pull request securego#216 from ccojocar/rename_gas_with_gosec
Browse files Browse the repository at this point in the history
Rename gas with gosec
  • Loading branch information
Cosmin Cojocar authored Jul 19, 2018
2 parents da26f64 + e6641c6 commit f254cec
Show file tree
Hide file tree
Showing 53 changed files with 410 additions and 416 deletions.
2 changes: 1 addition & 1 deletion .github/issue_template.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

### Steps to reproduce the behavior

### Gas version
### gosec version

### Go version (output of 'go version')

Expand Down
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ install:
- go get -u github.com/onsi/ginkgo/ginkgo
- go get -u github.com/onsi/gomega
- go get -u golang.org/x/crypto/ssh
- go get -u github.com/securego/gas/cmd/gas/...
- go get -u github.com/securego/gosec/cmd/gosec/...
- go get -v -t ./...
- export PATH=$PATH:$HOME/gopath/bin

Expand Down
2 changes: 1 addition & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
FROM golang:1.9.4-alpine3.7

ENV BIN=gas
ENV BIN=gosec

COPY build/*-linux-amd64 /go/bin/$BIN
COPY docker-entrypoint.sh /usr/local/bin
Expand Down
8 changes: 4 additions & 4 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
GIT_TAG?= $(shell git describe --always --tags)
BUILD_DATE = $(shell date +%Y-%m-%d)
BIN = gas
BUILD_CMD = go build -ldflags "-X main.Version=${VERSION} -X main.GitTag=${GIT_TAG} -X main.BuildDate=${BUILD_DATE}" -o build/$(BIN)-$(VERSION)-$${GOOS}-$${GOARCH} ./cmd/gas/ &
BIN = gosec
BUILD_CMD = go build -ldflags "-X main.Version=${VERSION} -X main.GitTag=${GIT_TAG} -X main.BuildDate=${BUILD_DATE}" -o build/$(BIN)-$(VERSION)-$${GOOS}-$${GOARCH} ./cmd/gosec/ &
FMT_CMD = $(gofmt -s -l -w $(find . -type f -name '*.go' -not -path './vendor/*') | tee /dev/stderr)
IMAGE_REPO = docker.io

Expand All @@ -13,12 +13,12 @@ test: bootstrap
test -z '$(FMT_CMD)'
go vet $(go list ./... | grep -v /vendor/)
golint -set_exit_status $(shell go list ./... | grep -v vendor)
gas ./...
gosec ./...
ginkgo -r -v
bootstrap:
dep ensure
build:
go build -o $(BIN) ./cmd/gas/
go build -o $(BIN) ./cmd/gosec/
clean:
rm -rf build vendor
rm -f release image bootstrap $(BIN)
Expand Down
49 changes: 23 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@


## GAS - Go Application Security
## gosec -Golang Security Checker

Inspects source code for security problems by scanning the Go AST.

Expand All @@ -12,26 +12,23 @@ You may obtain a copy of the License [here](http://www.apache.org/licenses/LICEN

### Project status

[![Build Status](https://travis-ci.org/securego/gas.svg?branch=master)](https://travis-ci.org/securego/gas)
[![GoDoc](https://godoc.org/github.com/securego/gas?status.svg)](https://godoc.org/github.com/securego/gas)

Gas is still in alpha and accepting feedback from early adopters. We do
not consider it production ready at this time.
[![Build Status](https://travis-ci.org/securego/gosec.svg?branch=master)](https://travis-ci.org/securego/gosec)
[![GoDoc](https://godoc.org/github.com/securego/gosec?status.svg)](https://godoc.org/github.com/securego/gosec)

### Install

`$ go get github.com/securego/gas/cmd/gas/...`
`$ go get github.com/securego/gosec/cmd/gosec/...`

### Usage

Gas can be configured to only run a subset of rules, to exclude certain file
Gosec can be configured to only run a subset of rules, to exclude certain file
paths, and produce reports in different formats. By default all rules will be
run against the supplied input files. To recursively scan from the current
directory you can supply './...' as the input argument.

#### Selecting rules

By default Gas will run all rules against the supplied file paths. It is however possible to select a subset of rules to run via the '-include=' flag,
By default gosec will run all rules against the supplied file paths. It is however possible to select a subset of rules to run via the '-include=' flag,
or to specify a set of rules to explicitly exclude using the '-exclude=' flag.

##### Available rules
Expand Down Expand Up @@ -63,22 +60,22 @@ or to specify a set of rules to explicitly exclude using the '-exclude=' flag.

```
# Run a specific set of rules
$ gas -include=G101,G203,G401 ./...
$ gosec -include=G101,G203,G401 ./...
# Run everything except for rule G303
$ gas -exclude=G303 ./...
$ gosec -exclude=G303 ./...
```

#### Excluding files:

Gas will ignore dependencies in your vendor directory any files
gosec will ignore dependencies in your vendor directory any files
that are not considered build artifacts by the compiler (so test files).

#### Annotating code

As with all automated detection tools there will be cases of false positives. In cases where Gas reports a failure that has been manually verified as being safe it is possible to annotate the code with a '#nosec' comment.
As with all automated detection tools there will be cases of false positives. In cases where gosec reports a failure that has been manually verified as being safe it is possible to annotate the code with a '#nosec' comment.

The annotation causes Gas to stop processing any further nodes within the
The annotation causes gosec to stop processing any further nodes within the
AST so can apply to a whole block or more granularly to a single expression.

```go
Expand All @@ -102,26 +99,26 @@ have been used. To run the scanner and ignore any #nosec annotations you
can do the following:

```
$ gas -nosec=true ./...
$ gosec -nosec=true ./...
```
#### Build tags

Gas is able to pass your [Go build tags](https://golang.org/pkg/go/build/) to the analyzer.
gosec is able to pass your [Go build tags](https://golang.org/pkg/go/build/) to the analyzer.
They can be provided as a comma separated list as follows:

```
$ gas -tag debug,ignore ./...
$ gosec -tag debug,ignore ./...
```

### Output formats

Gas currently supports text, json, yaml, csv and JUnit XML output formats. By default
gosec currently supports text, json, yaml, csv and JUnit XML output formats. By default
results will be reported to stdout, but can also be written to an output
file. The output format is controlled by the '-fmt' flag, and the output file is controlled by the '-out' flag as follows:

```
# Write output in json format to results.json
$ gas -fmt=json -out=results.json *.go
$ gosec -fmt=json -out=results.json *.go
```
### Development

Expand All @@ -144,7 +141,7 @@ make test

#### Release Build

Gas can be released as follows:
gosec can be released as follows:

```bash
make release VERSION=2.0.0
Expand All @@ -153,11 +150,11 @@ make release VERSION=2.0.0
The released version of the tool is available in the `build` folder. The build information should be displayed in the usage text.

```
./build/gas-2.0.0-linux-amd64 -h
./build/gosec-2.0.0-linux-amd64 -h
GAS - Go AST Scanner
gosec - Golang security checker
Gas analyzes Go source code to look for common programming mistakes that
gosec analyzes Go source code to look for common programming mistakes that
can lead to security problems.
VERSION: 2.0.0
Expand All @@ -174,10 +171,10 @@ You can execute a release and build the docker image as follows:
make image VERSION=2.0.0
```

Now you can run the gas tool in a container against your local workspace:
Now you can run the gosec tool in a container against your local workspace:

```
docker run -it -v <YOUR LOCAL WORKSPACE>:/workspace gas /workspace
docker run -it -v <YOUR LOCAL WORKSPACE>:/workspace gosec /workspace
```

#### Generate TLS rule
Expand All @@ -188,7 +185,7 @@ The configuration of TLS rule can be generated from [Mozilla's TLS ciphers recom
First you need to install the generator tool:

```
go get github.com/securego/gas/cmd/tlsconfig/...
go get github.com/securego/gosec/cmd/tlsconfig/...
```

You can invoke now the `go generate` in the root of the project:
Expand Down
98 changes: 49 additions & 49 deletions analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.

// Package gas holds the central scanning logic used by GAS
package gas
// Package gosec holds the central scanning logic used by gosec security scanner
package gosec

import (
"go/ast"
Expand Down Expand Up @@ -55,7 +55,7 @@ type Metrics struct {
NumFound int `json:"found"`
}

// Analyzer object is the main object of GAS. It has methods traverse an AST
// Analyzer object is the main object of gosec. It has methods traverse an AST
// and invoke the correct checking rules as on each node as required.
type Analyzer struct {
ignoreNosec bool
Expand All @@ -74,7 +74,7 @@ func NewAnalyzer(conf Config, logger *log.Logger) *Analyzer {
ignoreNoSec = setting == "true" || setting == "enabled"
}
if logger == nil {
logger = log.New(os.Stderr, "[gas]", log.LstdFlags)
logger = log.New(os.Stderr, "[gosec]", log.LstdFlags)
}
return &Analyzer{
ignoreNosec: ignoreNoSec,
Expand All @@ -89,15 +89,15 @@ func NewAnalyzer(conf Config, logger *log.Logger) *Analyzer {

// LoadRules instantiates all the rules to be used when analyzing source
// packages
func (gas *Analyzer) LoadRules(ruleDefinitions map[string]RuleBuilder) {
func (gosec *Analyzer) LoadRules(ruleDefinitions map[string]RuleBuilder) {
for id, def := range ruleDefinitions {
r, nodes := def(id, gas.config)
gas.ruleset.Register(r, nodes...)
r, nodes := def(id, gosec.config)
gosec.ruleset.Register(r, nodes...)
}
}

// Process kicks off the analysis process for a given package
func (gas *Analyzer) Process(buildTags []string, packagePaths ...string) error {
func (gosec *Analyzer) Process(buildTags []string, packagePaths ...string) error {
ctx := build.Default
ctx.BuildTags = append(ctx.BuildTags, buildTags...)
packageConfig := loader.Config{
Expand All @@ -111,10 +111,10 @@ func (gas *Analyzer) Process(buildTags []string, packagePaths ...string) error {
return err
}
if _, err := os.Stat(abspath); os.IsNotExist(err) {
gas.logger.Printf("Skipping: %s. Path doesn't exist.", abspath)
gosec.logger.Printf("Skipping: %s. Path doesn't exist.", abspath)
continue
}
gas.logger.Println("Searching directory:", abspath)
gosec.logger.Println("Searching directory:", abspath)

basePackage, err := build.Default.ImportDir(packagePath, build.ImportComment)
if err != nil {
Expand All @@ -135,31 +135,31 @@ func (gas *Analyzer) Process(buildTags []string, packagePaths ...string) error {
}

for _, pkg := range builtPackage.Created {
gas.logger.Println("Checking package:", pkg.String())
gosec.logger.Println("Checking package:", pkg.String())
for _, file := range pkg.Files {
gas.logger.Println("Checking file:", builtPackage.Fset.File(file.Pos()).Name())
gas.context.FileSet = builtPackage.Fset
gas.context.Config = gas.config
gas.context.Comments = ast.NewCommentMap(gas.context.FileSet, file, file.Comments)
gas.context.Root = file
gas.context.Info = &pkg.Info
gas.context.Pkg = pkg.Pkg
gas.context.Imports = NewImportTracker()
gas.context.Imports.TrackPackages(gas.context.Pkg.Imports()...)
ast.Walk(gas, file)
gas.stats.NumFiles++
gas.stats.NumLines += builtPackage.Fset.File(file.Pos()).LineCount()
gosec.logger.Println("Checking file:", builtPackage.Fset.File(file.Pos()).Name())
gosec.context.FileSet = builtPackage.Fset
gosec.context.Config = gosec.config
gosec.context.Comments = ast.NewCommentMap(gosec.context.FileSet, file, file.Comments)
gosec.context.Root = file
gosec.context.Info = &pkg.Info
gosec.context.Pkg = pkg.Pkg
gosec.context.Imports = NewImportTracker()
gosec.context.Imports.TrackPackages(gosec.context.Pkg.Imports()...)
ast.Walk(gosec, file)
gosec.stats.NumFiles++
gosec.stats.NumLines += builtPackage.Fset.File(file.Pos()).LineCount()
}
}
return nil
}

// ignore a node (and sub-tree) if it is tagged with a "#nosec" comment
func (gas *Analyzer) ignore(n ast.Node) ([]string, bool) {
if groups, ok := gas.context.Comments[n]; ok && !gas.ignoreNosec {
func (gosec *Analyzer) ignore(n ast.Node) ([]string, bool) {
if groups, ok := gosec.context.Comments[n]; ok && !gosec.ignoreNosec {
for _, group := range groups {
if strings.Contains(group.Text(), "#nosec") {
gas.stats.NumNosec++
gosec.stats.NumNosec++

// Pull out the specific rules that are listed to be ignored.
re := regexp.MustCompile("(G\\d{3})")
Expand All @@ -182,27 +182,27 @@ func (gas *Analyzer) ignore(n ast.Node) ([]string, bool) {
return nil, false
}

// Visit runs the GAS visitor logic over an AST created by parsing go code.
// Visit runs the gosec visitor logic over an AST created by parsing go code.
// Rule methods added with AddRule will be invoked as necessary.
func (gas *Analyzer) Visit(n ast.Node) ast.Visitor {
func (gosec *Analyzer) Visit(n ast.Node) ast.Visitor {
// If we've reached the end of this branch, pop off the ignores stack.
if n == nil {
if len(gas.context.Ignores) > 0 {
gas.context.Ignores = gas.context.Ignores[1:]
if len(gosec.context.Ignores) > 0 {
gosec.context.Ignores = gosec.context.Ignores[1:]
}
return gas
return gosec
}

// Get any new rule exclusions.
ignoredRules, ignoreAll := gas.ignore(n)
ignoredRules, ignoreAll := gosec.ignore(n)
if ignoreAll {
return nil
}

// Now create the union of exclusions.
ignores := make(map[string]bool, 0)
if len(gas.context.Ignores) > 0 {
for k, v := range gas.context.Ignores[0] {
if len(gosec.context.Ignores) > 0 {
for k, v := range gosec.context.Ignores[0] {
ignores[k] = v
}
}
Expand All @@ -212,37 +212,37 @@ func (gas *Analyzer) Visit(n ast.Node) ast.Visitor {
}

// Push the new set onto the stack.
gas.context.Ignores = append([]map[string]bool{ignores}, gas.context.Ignores...)
gosec.context.Ignores = append([]map[string]bool{ignores}, gosec.context.Ignores...)

// Track aliased and initialization imports
gas.context.Imports.TrackImport(n)
gosec.context.Imports.TrackImport(n)

for _, rule := range gas.ruleset.RegisteredFor(n) {
for _, rule := range gosec.ruleset.RegisteredFor(n) {
if _, ok := ignores[rule.ID()]; ok {
continue
}
issue, err := rule.Match(n, gas.context)
issue, err := rule.Match(n, gosec.context)
if err != nil {
file, line := GetLocation(n, gas.context)
file, line := GetLocation(n, gosec.context)
file = path.Base(file)
gas.logger.Printf("Rule error: %v => %s (%s:%d)\n", reflect.TypeOf(rule), err, file, line)
gosec.logger.Printf("Rule error: %v => %s (%s:%d)\n", reflect.TypeOf(rule), err, file, line)
}
if issue != nil {
gas.issues = append(gas.issues, issue)
gas.stats.NumFound++
gosec.issues = append(gosec.issues, issue)
gosec.stats.NumFound++
}
}
return gas
return gosec
}

// Report returns the current issues discovered and the metrics about the scan
func (gas *Analyzer) Report() ([]*Issue, *Metrics) {
return gas.issues, gas.stats
func (gosec *Analyzer) Report() ([]*Issue, *Metrics) {
return gosec.issues, gosec.stats
}

// Reset clears state such as context, issues and metrics from the configured analyzer
func (gas *Analyzer) Reset() {
gas.context = &Context{}
gas.issues = make([]*Issue, 0, 16)
gas.stats = &Metrics{}
func (gosec *Analyzer) Reset() {
gosec.context = &Context{}
gosec.issues = make([]*Issue, 0, 16)
gosec.stats = &Metrics{}
}
Loading

0 comments on commit f254cec

Please sign in to comment.