Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Terrascan v1.0 cobra #284

Merged
merged 10 commits into from
Aug 15, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 2 additions & 70 deletions cmd/terrascan/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,76 +16,8 @@

package main

import (
"flag"
"fmt"

"github.com/accurics/terrascan/pkg/cli"
httpServer "github.com/accurics/terrascan/pkg/http-server"
"github.com/accurics/terrascan/pkg/initialize"
"github.com/accurics/terrascan/pkg/logging"
"github.com/accurics/terrascan/pkg/version"
"go.uber.org/zap"
)
import "github.com/accurics/terrascan/pkg/cli"

func main() {

// command line flags
var (
// server mode
server = flag.Bool("server", false, "run terrascan in server mode")

// IaC flags
iacType = flag.String("iac", "", "IaC provider (supported values: terraform)")
iacVersion = flag.String("iac-version", "v12", "IaC version (supported values: 'v12' for terraform)")
iacFilePath = flag.String("f", "", "IaC file path")
iacDirPath = flag.String("d", ".", "IaC directory path")
policyPath = flag.String("p", "", "Policy directory path")

// cloud flags
cloudType = flag.String("cloud", "", "cloud provider (supported values: aws, azure)")

// logging flags
logLevel = flag.String("log-level", "info", "logging level (debug, info, warn, error, panic, fatal)")
logType = flag.String("log-type", "console", "log type (json, console)")

// config file
configFile = flag.String("config", "", "config file path")

// output type
output = flag.String("output", "yaml", "output format (json, yaml)")

//version
ver = flag.Bool("version", false, "terrascan version")
)
flag.Parse()

// if no flags are passed, print usage
if flag.NFlag() < 1 {
flag.Usage()
return
}

// print version
if *ver {
fmt.Println(version.Get())
return
}

// initialize logger
logging.Init(*logType, *logLevel)

// initialize terrascan
if err := initialize.Run(); err != nil {
zap.S().Error("failed to initialize terrascan")
return
}

// if server mode set, run terrascan as a server, else run it as CLI
if *server {
httpServer.Start()
} else {
zap.S().Debug("running terrascan in cli mode")
cli.Run(*iacType, *iacVersion, *cloudType, *iacFilePath, *iacDirPath, *configFile, *policyPath, *output)
}
cli.Execute()
}
Binary file added cmd/terrascan/terrascan
Binary file not shown.
13 changes: 8 additions & 5 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,19 @@ require (
github.com/hashicorp/go-version v1.2.0
github.com/hashicorp/hcl/v2 v2.3.0
github.com/hashicorp/terraform v0.12.28
github.com/mitchellh/go-homedir v1.1.0
github.com/open-policy-agent/opa v0.22.0
github.com/pelletier/go-toml v1.8.0
github.com/pkg/errors v0.9.1
github.com/spf13/afero v1.3.2
github.com/spf13/afero v1.3.4
github.com/spf13/cobra v1.0.0
github.com/spf13/pflag v1.0.5 // indirect
github.com/zclconf/go-cty v1.2.1
go.uber.org/zap v1.9.1
go.uber.org/zap v1.10.0
golang.org/x/net v0.0.0-20200625001655-4c5254603344 // indirect
golang.org/x/tools v0.0.0-20200812231640-9176cd30088c // indirect
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1 // indirect
golang.org/x/sys v0.0.0-20200814200057-3d37ad5750ed // indirect
gopkg.in/src-d/go-git.v4 v4.13.1
gopkg.in/yaml.v2 v2.3.0
honnef.co/go/tools v0.0.1-2020.1.5 // indirect
k8s.io/apimachinery v0.18.8 // indirect
k8s.io/client-go v11.0.0+incompatible
)
149 changes: 122 additions & 27 deletions go.sum

Large diffs are not rendered by default.

50 changes: 50 additions & 0 deletions pkg/cli/init.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
/*
Copyright (C) 2020 Accurics, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cli

import (
"github.com/accurics/terrascan/pkg/initialize"
"github.com/accurics/terrascan/pkg/logging"
"github.com/spf13/cobra"
"go.uber.org/zap"
)

var initCmd = &cobra.Command{
Use: "init",
Short: "Initialize Terrascan",
Long: `Terrascan

Initializes Terrascan and clones policies from the Terrascan GitHub repository.
`,
Run: initial,
}

func initial(cmd *cobra.Command, args []string) {

// initialize logger
logging.Init(LogType, LogLevel)

// initialize terrascan
if err := initialize.Run(); err != nil {
zap.S().Error("failed to initialize terrascan")
return
}
}

func init() {
RegisterCommand(rootCmd, initCmd)
}
64 changes: 64 additions & 0 deletions pkg/cli/register.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/*
Copyright (C) 2020 Accurics, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cli

import (
"fmt"
"os"

"github.com/spf13/cobra"
)

// RegisterCommand Registers a new command under the base command
func RegisterCommand(baseCommand *cobra.Command, command *cobra.Command) {
baseCommand.AddCommand(command)
}

func subCommands() (commandNames []string) {
for _, command := range rootCmd.Commands() {
commandNames = append(commandNames, append(command.Aliases, command.Name())...)
}
return
}

// setDefaultCommand sets `scan` as default command if no other command is specified
func setDefaultCommandIfNonePresent() {
if len(os.Args) > 1 {
potentialCommand := os.Args[1]
for _, command := range subCommands() {
if command == potentialCommand {
return
}
}
os.Args = append([]string{os.Args[0], "scan"}, os.Args[1:]...)
}

}

// Execute the entrypoint called by main
func Execute() {
rootCmd.PersistentFlags().StringVarP(&LogLevel, "log-level", "l", "info", "log level (debug, info, warn, error, panic, fatal)")
rootCmd.PersistentFlags().StringVarP(&LogType, "log-type", "x", "console", "log output type (console, json)")
rootCmd.PersistentFlags().StringVarP(&OutputType, "output-type", "o", "yaml", "output type (json, yaml, xml)")
rootCmd.PersistentFlags().StringVarP(&ConfigFile, "config-path", "c", "", "config file path")

setDefaultCommandIfNonePresent()
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
45 changes: 45 additions & 0 deletions pkg/cli/root.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
/*
Copyright (C) 2020 Accurics, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cli

import (
"github.com/accurics/terrascan/pkg/version"
"github.com/spf13/cobra"
)

var (
// LogLevel Logging level (debug, info, warn, error, panic, fatal)
LogLevel string
// LogType Logging output type (console, json)
LogType string
// OutputType Violation output type (text, json, yaml, xml)
OutputType string
// ConfigFile Config file path
ConfigFile string
)

var rootCmd = &cobra.Command{
Use: "terrascan",
Short: "Terrascan is an IaC (Infrastructure-as-Code) file scanner",
Long: `Terrascan

An advanced IaC (Infrastructure-as-Code) file scanner written in Go.
Secure your cloud deployments at design time.
For more information, please visit https://www.accurics.com
`,
Version: version.Get(),
}
66 changes: 66 additions & 0 deletions pkg/cli/scan.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
Copyright (C) 2020 Accurics, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cli

import (
"github.com/spf13/cobra"
"go.uber.org/zap"
)

var (
// PolicyPath Policy path directory
PolicyPath string
// PolicyType Cloud type (aws, azure, gcp)
PolicyType string
// IacType IaC type (terraform)
IacType string
// IacVersion IaC version (for terraform:v12)
IacVersion string
// IacFilePath Path to a single IaC file
IacFilePath string
// IacDirPath Path to a directory containing one or more IaC files
IacDirPath string
)

var scanCmd = &cobra.Command{
Use: "scan",
Short: "Scan IaC (Infrastructure-as-Code) files for vulnerabilities.",
Long: `Terrascan

Scan IaC (Infrastructure-as-Code) files for vulnerabilities.
`,
PreRun: func(cmd *cobra.Command, args []string) {
initial(cmd, args)
},
Run: scan,
}

func scan(cmd *cobra.Command, args []string) {
zap.S().Debug("running terrascan in cli mode")
Run(IacType, IacVersion, PolicyType, IacFilePath, IacDirPath, ConfigFile, PolicyPath, OutputType)
}

func init() {
scanCmd.Flags().StringVarP(&PolicyType, "policy-type", "t", "", "<required> policy type (aws, azure, gcp)")
scanCmd.Flags().StringVarP(&IacType, "iac-type", "i", "terraform", "iac type (terraform)")
scanCmd.Flags().StringVarP(&IacVersion, "iac-version", "", "v12", "iac version (v12)")
scanCmd.Flags().StringVarP(&IacFilePath, "iac-file", "f", "", "path to a single IaC file")
scanCmd.Flags().StringVarP(&IacDirPath, "iac-dir", "d", ".", "path to a directory containing one or more IaC files")
scanCmd.Flags().StringVarP(&PolicyPath, "policy-path", "", "", "policy path directory")
scanCmd.MarkFlagRequired("policy-type")
RegisterCommand(rootCmd, scanCmd)
}
43 changes: 43 additions & 0 deletions pkg/cli/server.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
Copyright (C) 2020 Accurics, Inc.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cli

import (
httpserver "github.com/accurics/terrascan/pkg/http-server"
"github.com/spf13/cobra"
)

var serverCmd = &cobra.Command{
Use: "server",
Short: "Run Terrascan as an API server",
Long: `Terrascan

Run Terrascan as an API server that inspects incoming IaC (Infrastructure-as-Code) files and returns the scan results.
`,
PreRun: func(cmd *cobra.Command, args []string) {
initial(cmd, args)
},
Run: server,
}

func server(cmd *cobra.Command, args []string) {
httpserver.Start()
}

func init() {
RegisterCommand(rootCmd, serverCmd)
}
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
{
"name": "cloudfrontNoHTTPSTraffic",
"file": "cloudfrontNoHTTPSTraffic.rego",
"templateArgs": {
"template_args": {
"prefix": ""
},
"severity": "HIGH",
"description": "Use encrypted connection between CloudFront and origin server",
"referenceId": "AWS.CloudFront.EncryptionandKeyManagement.High.0407",
"reference_id": "AWS.CloudFront.EncryptionandKeyManagement.High.0407",
"category": "Encryption and Key Management",
"version": 2
}
Loading