import "github.com/securego/gosec"
Package gosec holds the central scanning logic used by gosec security scanner
analyzer.go call_list.go config.go errors.go helpers.go import_tracker.go issue.go resolve.go rule.go
const ( // Globals are applicable to all rules and used for general // configuration settings for gosec. Globals = "global" )
const LoadMode = packages.NeedName | packages.NeedFiles | packages.NeedCompiledGoFiles | packages.NeedImports | packages.NeedTypes | packages.NeedTypesSizes | packages.NeedTypesInfo | packages.NeedSyntax
LoadMode controls the amount of details to return when loading the packages
var IssueToCWE = map[string]Cwe{ "G101": GetCwe("798"), "G102": GetCwe("200"), "G103": GetCwe("242"), "G104": GetCwe("703"), "G106": GetCwe("322"), "G107": GetCwe("88"), "G201": GetCwe("89"), "G202": GetCwe("89"), "G203": GetCwe("79"), "G204": GetCwe("78"), "G301": GetCwe("276"), "G302": GetCwe("276"), "G303": GetCwe("377"), "G304": GetCwe("22"), "G305": GetCwe("22"), "G401": GetCwe("326"), "G402": GetCwe("295"), "G403": GetCwe("310"), "G404": GetCwe("338"), "G501": GetCwe("327"), "G502": GetCwe("327"), "G503": GetCwe("327"), "G504": GetCwe("327"), "G505": GetCwe("327"), }
IssueToCWE maps gosec rules to CWEs
func ConcatString(n *ast.BinaryExpr) (string, bool)
ConcatString recursively concatenates strings from a binary expression
ExcludedDirsRegExp builds the regexps for a list of excluded dirs provided as strings
FindVarIdentities returns array of all variable identities in a given binary expression
GetCallInfo returns the package or type and name associated with a call expression.
GetCallObject returns the object and call expression and associated object for a given AST node. nil, nil will be returned if the object cannot be resolved.
GetCallStringArgsValues returns the values of strings arguments if they can be resolved
GetChar will read and return a char value from an ast.BasicLit
GetFloat will read and return a float value from an ast.BasicLit
GetIdentStringValues return the string values of an Ident if they can be resolved
GetImportPath resolves the full import path of an identifier based on the imports in the current context.
GetImportedName returns the name used for the package within the code. It will resolve aliases and ignores initialization only imports.
GetInt will read and return an integer value from an ast.BasicLit
GetLocation returns the filename and line number of an ast.Node
GetPkgAbsPath returns the Go package absolute path derived from the given path
GetPkgRelativePath returns the Go relative relative path derived form the given path
GetString will read and return a string value from an ast.BasicLit
Getenv returns the values of the environment variable, otherwise returns the default if variable is not set
Gopath returns all GOPATHs
MatchCallByPackage ensures that the specified package is imported, adjusts the name for any aliases and ignores cases that are initialization only imports.
Usage:
node, matched := MatchCallByPackage(n, ctx, "math/rand", "Read")
MatchCompLit will match an ast.CompositeLit based on the supplied type
PackagePaths returns a slice with all packages path at given root directory
RootPath returns the absolute root path of a scan
TryResolve will attempt, given a subtree starting at some AST node, to resolve all values contained within to a known constant. It is used to check for any unknown values in compound expressions.
type Analyzer struct {
// contains filtered or unexported fields
}
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.
NewAnalyzer builds a new analyzer.
AppendError appends an error to the file errors
Check runs analysis on the given package
Config returns the current configuration
func (gosec *Analyzer) LoadRules(ruleDefinitions map[string]RuleBuilder)
LoadRules instantiates all the rules to be used when analyzing source packages
ParseErrors parses the errors from given package
Process kicks off the analysis process for a given package
Report returns the current issues discovered and the metrics about the scan
Reset clears state such as context, issues and metrics from the configured analyzer
SetConfig upates the analyzer configuration
Visit runs the gosec visitor logic over an AST created by parsing go code. Rule methods added with AddRule will be invoked as necessary.
CallList is used to check for usage of specific packages and functions.
NewCallList creates a new empty CallList
Add a selector and call to the call list
AddAll will add several calls to the call list at once
Contains returns true if the package and function are / members of this call list.
ContainsCallExpr resolves the call expression name and type / or package and determines if it exists within the CallList
Config is used to provide configuration and customization to each of the rules.
NewConfig initializes a new configuration instance. The configuration data then needs to be loaded via c.ReadFrom(strings.NewReader("config data")) or from a *os.File.
Get returns the configuration section for the supplied key
func (c Config) GetGlobal(option GlobalOption) (string, error)
GetGlobal returns value associated with global configuration option
func (c Config) IsGlobalEnabled(option GlobalOption) (bool, error)
IsGlobalEnabled checks if a global option is enabled
ReadFrom implements the io.ReaderFrom interface. This should be used with io.Reader to load configuration from file or from string etc.
Set section in the configuration to specified value
func (c Config) SetGlobal(option GlobalOption, value string)
SetGlobal associates a value with a global configuration option
WriteTo implements the io.WriteTo interface. This should be used to save or print out the configuration information.
type Context struct { FileSet *token.FileSet Comments ast.CommentMap Info *types.Info Pkg *types.Package PkgFiles []*ast.File Root *ast.File Config Config Imports *ImportTracker Ignores []map[string]bool }
The Context is populated with data parsed from the source code as it is scanned. It is passed through to all rule functions as they are called. Rules may use this data in conjunction withe the encountered AST node.
Cwe id and url
GetCwe creates a cwe object for a given RuleID
Error is used when there are golang errors while parsing the AST
NewError creates Error object
GlobalOption defines the name of the global options
const ( // Nosec global option for #nosec directive Nosec GlobalOption = "nosec" // Audit global option which indicates that gosec runs in audit mode Audit GlobalOption = "audit" // NoSecAlternative global option alternative for #nosec directive NoSecAlternative GlobalOption = "#nosec" )
type ImportTracker struct { Imported map[string]string Aliased map[string]string InitOnly map[string]bool }
ImportTracker is used to normalize the packages that have been imported by a source file. It is able to differentiate between plain imports, aliased imports and init only imports.
func NewImportTracker() *ImportTracker
NewImportTracker creates an empty Import tracker instance
func (t *ImportTracker) TrackFile(file *ast.File)
TrackFile track all the imports used by the supplied file
func (t *ImportTracker) TrackImport(n ast.Node)
TrackImport tracks imports and handles the 'unsafe' import
func (t *ImportTracker) TrackPackages(pkgs ...*types.Package)
TrackPackages tracks all the imports used by the supplied packages
type Issue struct { Severity Score `json:"severity"` // issue severity (how problematic it is) Confidence Score `json:"confidence"` // issue confidence (how sure we are we found it) Cwe Cwe `json:"cwe"` // Cwe associated with RuleID RuleID string `json:"rule_id"` // Human readable explanation What string `json:"details"` // Human readable explanation File string `json:"file"` // File name we found it in Code string `json:"code"` // Impacted code line Line string `json:"line"` // Line number in file }
Issue is returned by a gosec rule if it discovers an issue with the scanned code.
func NewIssue(ctx *Context, node ast.Node, ruleID, desc string, severity Score, confidence Score) *Issue
NewIssue creates a new Issue
MetaData is embedded in all gosec rules. The Severity, Confidence and What message will be passed through to reported issues.
type Metrics struct { NumFiles int `json:"files"` NumLines int `json:"lines"` NumNosec int `json:"nosec"` NumFound int `json:"found"` }
Metrics used when reporting information about a scanning run.
The Rule interface used by all rules supported by gosec.
RuleBuilder is used to register a rule definition with the analyzer
A RuleSet maps lists of rules to the type of AST node they should be run on. The analyzer will only invoke rules contained in the list associated with the type of AST node it is currently visiting.
NewRuleSet constructs a new RuleSet
Register adds a trigger for the supplied rule for the the specified ast nodes.
RegisteredFor will return all rules that are registered for a specified ast node.
Score type used by severity and confidence values
const ( // Low severity or confidence Low Score = iota // Medium severity or confidence Medium // High severity or confidence High )
MarshalJSON is used convert a Score object into a JSON representation
String converts a Score into a string
Path | Synopsis |
---|---|
cmd/gosec | |
cmd/gosecutil | |
cmd/tlsconfig | |
output | |
rules | |
testutils |
Package gosec imports 22 packages (graph) and is imported by 15 packages. Updated 2019-11-19. Refresh now. Tools for package owners.