Class: Inspec::BaseCLI

Inherits:
Thor
  • Object
show all
Defined in:
lib/inspec/plugin/v2/plugin_types/cli.rb,
lib/inspec/base_cli.rb

Overview

The InSpec load order has this file being loaded before ‘inspec/base_cli` can finish being loaded. So, we must define Inspec::BaseCLI here first to avoid a NameError below.

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.inspec_cli_commandObject

Returns the value of attribute inspec_cli_command.



31
32
33
# File 'lib/inspec/base_cli.rb', line 31

def inspec_cli_command
  @inspec_cli_command
end

Class Method Details

.audit_log_optionsObject



236
237
238
239
# File 'lib/inspec/base_cli.rb', line 236

def self.audit_log_options
  option :audit_log_location, type: :string,
  desc: "Audit log location to send diagnostic log messages to. (default: '~/.inspec/logs/inspec-audit.log')"
end

.check_license!Object

EULA acceptance



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/inspec/base_cli.rb', line 64

def self.check_license!
  allowed_commands = ["-h", "--help", "help", "-v", "--version", "version"]

  require "license_acceptance/acceptor"
  begin
    if (allowed_commands & ARGV.map(&:downcase)).empty? && # Did they use a non-exempt command?
        !ARGV.empty? # Did they supply at least one command?
      license_acceptor_output = LicenseAcceptance::Acceptor.check_and_persist(
        Inspec::Dist::EXEC_NAME,
        Inspec::VERSION,
        logger: Inspec::Log
      )
      license_acceptor_output
    end
  rescue LicenseAcceptance::LicenseNotAcceptedError
    Inspec::Log.error "#{Inspec::Dist::PRODUCT_NAME} cannot execute without accepting the license"
    Inspec::UI.new.exit(:license_not_accepted)
  end
end

.exec_optionsObject



183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/inspec/base_cli.rb', line 183

def self.exec_options
  target_options
  profile_options
  supermarket_options
  option :controls, type: :array,
    desc: "A list of control names to run, or a list of /regexes/ to match against control names. Ignore all other tests."
  option :tags, type: :array,
    desc: "A list of tags names that are part of controls to filter and run controls, or a list of /regexes/ to match against tags names of controls. Ignore all other tests."
  option :reporter, type: :array,
    banner: "one two:/output/file/path",
    desc: "Enable one or more output reporters: cli, documentation, html, progress, progress-bar, json, json-min, json-rspec, junit, yaml"
  option :reporter_message_truncation, type: :string,
    desc: "Number of characters to truncate failure messages and code_desc in report data to (default: no truncation)"
  option :reporter_backtrace_inclusion, type: :boolean,
    desc: "Include a code backtrace in report data (default: true)"
  option :input, type: :array, banner: "name1=value1 name2=value2",
    desc: "Specify one or more inputs directly on the command line, as --input NAME=VALUE. Accepts single-quoted YAML and JSON structures."
  option :input_file, type: :array,
    desc: "Load one or more input files, a YAML file with values for the profile to use."
  option :waiver_file, type: :array,
    desc: "Load one or more waiver files."
  option :attrs, type: :array,
    desc: "Legacy name for --input-file - deprecated."
  option :create_lockfile, type: :boolean,
    desc: "Write out a lockfile based on this execution (unless one already exists)"
  option :backend_cache, type: :boolean,
    desc: "Allow caching for backend command output. (default: true)."
  option :show_progress, type: :boolean,
    desc: "Show progress while executing tests."
  option :distinct_exit, type: :boolean, default: true,
    desc: "Exit with code 101 if any tests fail, and 100 if any are skipped (default).  If disabled, exit 0 on skips and 1 for failures."
  option :silence_deprecations, type: :array,
    banner: "[all]|[GROUP GROUP...]",
    desc: "Suppress deprecation warnings. See install_dir/etc/deprecations.json for a list of GROUPs or use 'all'."
  option :diff, type: :boolean, default: true,
    desc: "Use --no-diff to suppress 'diff' output of failed textual test results."
  option :sort_results_by, type: :string, default: "file", banner: "--sort-results-by=none|control|file|random",
    desc: "After normal execution order, results are sorted by control ID, or by file (default), or randomly. None uses legacy unsorted mode."
  option :filter_empty_profiles, type: :boolean, default: false,
    desc: "Filter empty profiles (profiles without controls) from the report."
  option :filter_waived_controls, type: :boolean,
    desc: "Do not execute waived controls in InSpec at all. Must use with --waiver-file. Ignores the `run` setting of the waiver file."
  option :retain_waiver_data, type: :boolean,
    desc: "EXPERIMENTAL: Only works in conjunction with --filter-waived-controls, retains waiver data about controls that were skipped"
  option :command_timeout, type: :numeric,
    desc: "Maximum seconds to allow commands to run during execution.",
    long_desc: "Maximum seconds to allow commands to run during execution. A timed out command is considered an error."
  option :reporter_include_source, type: :boolean, default: false,
    desc: "Include full source code of controls in the CLI report"
  option :enhanced_outcomes, type: :boolean,
    desc: "Show enhanced outcomes in output"
end

.exit_on_failure?Boolean

Returns:

  • (Boolean)


85
86
87
# File 'lib/inspec/base_cli.rb', line 85

def self.exit_on_failure?
  true
end

.fetch_and_persist_licenseObject



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/inspec/base_cli.rb', line 43

def self.fetch_and_persist_license
  allowed_commands = ["-h", "--help", "help", "-v", "--version", "version", "license"]
  begin
    if (allowed_commands & ARGV.map(&:downcase)).empty? && !ARGV.empty?
      license_keys = ChefLicensing.fetch_and_persist

      # Only if EULA acceptance or license key args are present. And licenses are successfully persisted, do clean exit.
      if ARGV.select { |arg| !(arg.include? "--chef-license") }.empty? && !license_keys.blank?
        Inspec::UI.new.exit
      end
    end
  rescue ChefLicensing::LicenseKeyFetcher::LicenseKeyNotFetchedError
    Inspec::Log.error "#{Inspec::Dist::PRODUCT_NAME} cannot execute without valid licenses."
    Inspec::UI.new.exit(:license_not_set)
  rescue ChefLicensing::Error => e
    Inspec::Log.error e.message
    Inspec::UI.new.exit(:usage_error)
  end
end

.format_platform_info(params: {}, indent: 0, color: 39, enable_color: true) ⇒ Object



271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'lib/inspec/base_cli.rb', line 271

def self.format_platform_info(params: {}, indent: 0, color: 39, enable_color: true)
  str = ""
  params.each do |item, info|
    data = info

    # Format Array for better output if applicable
    data = data.join(", ") if data.is_a?(Array)

    # Do not output fields of data is missing ('unknown' is fine)
    next if data.nil?

    data = "\e[1m\e[#{color}m#{data}\e[0m" if enable_color
    str << format("#{" " * indent}%-10s %s\n", item.to_s.capitalize + ":", data)
  end
  str
end

.help(*args) ⇒ Object



241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
# File 'lib/inspec/base_cli.rb', line 241

def self.help(*args)
  super(*args)
  if Inspec::Dist::EXEC_NAME == "inspec"
    puts <<~CHEF_LICENSE_HELP
      Chef Compliance has three tiers of licensing:

      * Free-Tier
        Users are limited to audit maximum of 10 targets
        Entitled for personal or non-commercial use

      * Trial
        Entitled for unlimited number of targets
        Entitled for 30 days only
        Entitled for commercial use

      * Commercial
        Entitled for purchased number of targets
        Entitled for period of subscription purchased
        Entitled for commercial use

      inspec license add: This command helps users to generate or add an additional license (not applicable to local licensing service)

      For more information please visit:
      www.chef.io/licensing/faqs
    CHEF_LICENSE_HELP
  end
  puts "\nAbout #{Inspec::Dist::PRODUCT_NAME}:"
  puts "  Patents: chef.io/patents\n\n"
end

.profile_optionsObject



167
168
169
170
171
172
173
174
175
176
# File 'lib/inspec/base_cli.rb', line 167

def self.profile_options
  option :profiles_path, type: :string,
    desc: "Folder which contains referenced profiles."
  option :vendor_cache, type: :string,
    desc: "Use the given path for caching dependencies, (default: ~/.inspec/cache)."
  option :auto_install_gems, type: :boolean, default: false,
    desc: "Auto installs gem dependencies of the profile or resource pack."
  option :allow_unsigned_profiles, type: :boolean, default: false,
    desc: "Allow unsigned profiles to be used in InSpec command."
end

.start(given_args = ARGV, config = {}) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/inspec/base_cli.rb', line 34

def self.start(given_args = ARGV, config = {})
  if Inspec::Dist::EXEC_NAME == "inspec"
    check_license! if config[:enforce_license] || config[:enforce_license].nil?
    fetch_and_persist_license
  end

  super(given_args, config)
end

.supermarket_optionsObject



178
179
180
181
# File 'lib/inspec/base_cli.rb', line 178

def self.supermarket_options
  option :supermarket_url, type: :string,
    desc: "Specify the URL of a private Chef Supermarket."
end

.target_optionsObject

rubocop:disable Metrics/MethodLength



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
# File 'lib/inspec/base_cli.rb', line 89

def self.target_options # rubocop:disable Metrics/MethodLength
  option :target, aliases: :t, type: :string,
    desc: "Simple targeting option using URIs, e.g. ssh://user:pass@host:port"
  option :backend, aliases: :b, type: :string,
    desc: "Choose a backend: local, ssh, winrm, docker."
  option :host, type: :string,
    desc: "Specify a remote host which is tested."
  option :port, aliases: :p, type: :numeric,
    desc: "Specify the login port for a remote scan."
  option :user, type: :string,
    desc: "The login user for a remote scan."
  option :password, type: :string, lazy_default: -1,
    desc: "Login password for a remote scan, if required."
  option :enable_password, type: :string, lazy_default: -1,
    desc: "Password for enable mode on Cisco IOS devices."
  option :key_files, aliases: :i, type: :array,
    desc: "Login key or certificate file for a remote scan."
  option :path, type: :string,
    desc: "Login path to use when connecting to the target (WinRM)."
  option :sudo, type: :boolean,
    desc: "Run scans with sudo. Only activates on Unix and non-root user."
  option :sudo_password, type: :string, lazy_default: -1,
    desc: "Specify a sudo password, if it is required."
  option :sudo_options, type: :string,
    desc: "Additional sudo options for a remote scan."
  option :sudo_command, type: :string,
    desc: "Alternate command for sudo."
  option :shell, type: :boolean,
    desc: "Run scans in a subshell. Only activates on Unix."
  option :shell_options, type: :string,
    desc: "Additional shell options."
  option :shell_command, type: :string,
    desc: "Specify a particular shell to use."
  option :ssl, type: :boolean,
    desc: "Use SSL for transport layer encryption (WinRM)."
  option :ssl_peer_fingerprint, type: :string,
    desc: "Specify SSL peer fingerprint in place of certificates for SSL authentication (WinRM)."
  option :self_signed, type: :boolean,
    desc: "Allow remote scans with self-signed certificates (WinRM)."
  option :ca_trust_file, type: :string,
    desc: "Specify CA certificate required for SSL authentication (WinRM)."
  option :client_cert, type: :string,
    desc: "Specify client certificate for SSL authentication"
  option :client_key, type: :string,
    desc: "Specify client key required with client cert for SSL authentication"
  option :client_key_pass, type: :string, lazy_default: -1,
    desc: "Specify client cert password, if required for SSL authentication"
  option :winrm_transport, type: :string, default: "negotiate",
    desc: "Specify which transport to use, defaults to negotiate (WinRM)."
  option :winrm_disable_sspi, type: :boolean,
    desc: "Whether to use disable sspi authentication, defaults to false (WinRM)."
  option :winrm_basic_auth_only, type: :boolean,
    desc: "Whether to use basic authentication, defaults to false (WinRM)."
  option :config, type: :string,
    desc: "Read configuration from JSON file (`-` reads from stdin)."
  option :json_config, type: :string, hide: true
  option :proxy_command, type: :string,
    desc: "Specifies the command to use to connect to the server."
  option :bastion_host, type: :string,
    desc: "Specifies the bastion host if applicable."
  option :bastion_user, type: :string,
    desc: "Specifies the bastion user if applicable."
  option :bastion_port, type: :string,
    desc: "Specifies the bastion port if applicable."
  option :insecure, type: :boolean, default: false,
    desc: "Disable SSL verification on select targets."
  option :target_id, type: :string,
    desc: "Provide an ID which will be included on reports - deprecated"
  option :winrm_shell_type, type: :string, default: "powershell",
    desc: "Specify which shell type to use (powershell, elevated, or cmd), which defaults to powershell (WinRM)."
  option :docker_url, type: :string,
    desc: "Provides path to Docker API endpoint (Docker). Defaults to unix:///var/run/docker.sock on Unix systems and tcp://localhost:2375 on Windows."
  option :ssh_config_file, type: :array,
    desc: "A list of paths to the ssh config file, e.g ~/.ssh/config or /etc/ssh/ssh_config."
  option :podman_url, type: :string,
    desc: "Provides the path to the Podman API endpoint. Defaults to unix:///run/user/$UID/podman/podman.sock for rootless container, unix:///run/podman/podman.sock for rootful container (for this you need to execute inspec as root user)."
end