gopkg.in/alecthomas/gometalinter.v3@v3.0.0/_linters/src/github.com/securego/gosec/rules/subproc.go (about)

     1  // (c) Copyright 2016 Hewlett Packard Enterprise Development LP
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package rules
    16  
    17  import (
    18  	"go/ast"
    19  	"go/types"
    20  
    21  	"github.com/securego/gosec"
    22  )
    23  
    24  type subprocess struct {
    25  	gosec.MetaData
    26  	gosec.CallList
    27  }
    28  
    29  func (r *subprocess) ID() string {
    30  	return r.MetaData.ID
    31  }
    32  
    33  // TODO(gm) The only real potential for command injection with a Go project
    34  // is something like this:
    35  //
    36  // syscall.Exec("/bin/sh", []string{"-c", tainted})
    37  //
    38  // E.g. Input is correctly escaped but the execution context being used
    39  // is unsafe. For example:
    40  //
    41  // syscall.Exec("echo", "foobar" + tainted)
    42  func (r *subprocess) Match(n ast.Node, c *gosec.Context) (*gosec.Issue, error) {
    43  	if node := r.ContainsCallExpr(n, c); node != nil {
    44  		for _, arg := range node.Args {
    45  			if ident, ok := arg.(*ast.Ident); ok {
    46  				obj := c.Info.ObjectOf(ident)
    47  				if _, ok := obj.(*types.Var); ok && !gosec.TryResolve(ident, c) {
    48  					return gosec.NewIssue(c, n, r.ID(), "Subprocess launched with variable", gosec.Medium, gosec.High), nil
    49  				}
    50  			}
    51  		}
    52  		return gosec.NewIssue(c, n, r.ID(), "Subprocess launching should be audited", gosec.Low, gosec.High), nil
    53  	}
    54  	return nil, nil
    55  }
    56  
    57  // NewSubproc detects cases where we are forking out to an external process
    58  func NewSubproc(id string, conf gosec.Config) (gosec.Rule, []ast.Node) {
    59  	rule := &subprocess{gosec.MetaData{ID: id}, gosec.NewCallList()}
    60  	rule.Add("os/exec", "Command")
    61  	rule.Add("os/exec", "CommandContext")
    62  	rule.Add("syscall", "Exec")
    63  	return rule, []ast.Node{(*ast.CallExpr)(nil)}
    64  }