inspec-core 5.21.29 → 5.22.3

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7f6f86730baadd988c363a823e5e46ba68c318e48b27bbaaba614ce7c33bb71c
4
- data.tar.gz: f02ca42e9d4e525b82e9cfa61a04b122dc3b09c1e3c96f2ec4440c3fb3053f25
3
+ metadata.gz: 257ccbe0a55a1779ee75f8d6e9e8e0ff612990c123e5cdb10d8cf1e19dbade54
4
+ data.tar.gz: 820f9a0ec86451f48f65f229befe175cf937648ddb5669df1c8a7c27ebfb234b
5
5
  SHA512:
6
- metadata.gz: 597fed943b00ed280a749f05c97d01e29b4d5a85034835e9f242990588b35b740bf56a886b65202777d68b79b5cbd1faf1a48a69c1a4f1f8a00a83ecdece3527
7
- data.tar.gz: 13aa012d46677b3cd31614dcc118c62b1aa1656f3007d6b105f7822a3c25a45b1b1284eef9fb9e761cf5a03cd8209ffe8518d54ed355c189a2f141788a000694
6
+ metadata.gz: 8150cdd9aca6ac14ae762dd4b6d09867dab6651f0a0705a28f7256a94683a1fd59b7841bfc69e1a362c253d6c2a847d2e9a03b901dd20118ecc1566b4496a8a9
7
+ data.tar.gz: a3469cb7fa6786e1d9416e9493fed402ccfb6c8e6ac0a2d40a0029ab63c09b09671cf6729736899ed1a039ca75e36a6a57428deba9a8c5d6dbf0975711a06d13
data/Gemfile CHANGED
@@ -34,7 +34,6 @@ group :test do
34
34
  gem "pry-byebug"
35
35
  gem "pry", "~> 0.10"
36
36
  gem "rake", ">= 10"
37
- gem "ruby-progressbar", "~> 1.8"
38
37
  gem "simplecov", "~> 0.21"
39
38
  gem "simplecov_json_formatter"
40
39
  gem "webmock", "~> 3.0"
@@ -100,11 +100,11 @@ module Inspec
100
100
  option :ssl, type: :boolean,
101
101
  desc: "Use SSL for transport layer encryption (WinRM)."
102
102
  option :ssl_peer_fingerprint, type: :string,
103
- desc: "Specify peer fingerprint for SSL authentication, used in lieu of certificates"
103
+ desc: "Specify SSL peer fingerprint in place of certificates for SSL authentication (WinRM)."
104
104
  option :self_signed, type: :boolean,
105
105
  desc: "Allow remote scans with self-signed certificates (WinRM)."
106
106
  option :ca_trust_file, type: :string,
107
- desc: "Specify CA trust file for SSL authentication"
107
+ desc: "Specify CA certificate required for SSL authentication (WinRM)."
108
108
  option :client_cert, type: :string,
109
109
  desc: "Specify client certificate for SSL authentication"
110
110
  option :client_key, type: :string,
@@ -121,32 +121,32 @@ module Inspec
121
121
  desc: "Read configuration from JSON file (`-` reads from stdin)."
122
122
  option :json_config, type: :string, hide: true
123
123
  option :proxy_command, type: :string,
124
- desc: "Specifies the command to use to connect to the server"
124
+ desc: "Specifies the command to use to connect to the server."
125
125
  option :bastion_host, type: :string,
126
- desc: "Specifies the bastion host if applicable"
126
+ desc: "Specifies the bastion host if applicable."
127
127
  option :bastion_user, type: :string,
128
- desc: "Specifies the bastion user if applicable"
128
+ desc: "Specifies the bastion user if applicable."
129
129
  option :bastion_port, type: :string,
130
- desc: "Specifies the bastion port if applicable"
130
+ desc: "Specifies the bastion port if applicable."
131
131
  option :insecure, type: :boolean, default: false,
132
- desc: "Disable SSL verification on select targets"
132
+ desc: "Disable SSL verification on select targets."
133
133
  option :target_id, type: :string,
134
- desc: "Provide a ID which will be included on reports - deprecated"
134
+ desc: "Provide an ID which will be included on reports - deprecated"
135
135
  option :winrm_shell_type, type: :string, default: "powershell",
136
- desc: "Specify a shell type for winrm (eg. 'elevated' or 'powershell')"
136
+ desc: "Specify which shell type to use (powershell, elevated, or cmd), which defaults to powershell (WinRM)."
137
137
  option :docker_url, type: :string,
138
- desc: "Provides path to Docker API endpoint (Docker)"
138
+ desc: "Provides path to Docker API endpoint (Docker). Defaults to unix:///var/run/docker.sock on Unix systems and tcp://localhost:2375 on Windows."
139
139
  option :ssh_config_file, type: :array,
140
- desc: "A list of paths to the ssh config file, e.g ~/.ssh/config or /etc/ssh/ssh_config"
140
+ desc: "A list of paths to the ssh config file, e.g ~/.ssh/config or /etc/ssh/ssh_config."
141
141
  option :podman_url, type: :string,
142
- desc: "Provides path to Podman API endpoint"
142
+ 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)."
143
143
  end
144
144
 
145
145
  def self.profile_options
146
146
  option :profiles_path, type: :string,
147
147
  desc: "Folder which contains referenced profiles."
148
148
  option :vendor_cache, type: :string,
149
- desc: "Use the given path for caching dependencies. (default: ~/.inspec/cache)"
149
+ desc: "Use the given path for caching dependencies, (default: ~/.inspec/cache)."
150
150
  option :auto_install_gems, type: :boolean, default: false,
151
151
  desc: "Auto installs gem dependencies of the profile or resource pack."
152
152
  end
@@ -174,7 +174,7 @@ module Inspec
174
174
  option :input, type: :array, banner: "name1=value1 name2=value2",
175
175
  desc: "Specify one or more inputs directly on the command line, as --input NAME=VALUE. Accepts single-quoted YAML and JSON structures."
176
176
  option :input_file, type: :array,
177
- desc: "Load one or more input files, a YAML file with values for the profile to use"
177
+ desc: "Load one or more input files, a YAML file with values for the profile to use."
178
178
  option :waiver_file, type: :array,
179
179
  desc: "Load one or more waiver files."
180
180
  option :attrs, type: :array,
@@ -182,14 +182,14 @@ module Inspec
182
182
  option :create_lockfile, type: :boolean,
183
183
  desc: "Write out a lockfile based on this execution (unless one already exists)"
184
184
  option :backend_cache, type: :boolean,
185
- desc: "Allow caching for backend command output. (default: true)"
185
+ desc: "Allow caching for backend command output. (default: true)."
186
186
  option :show_progress, type: :boolean,
187
187
  desc: "Show progress while executing tests."
188
188
  option :distinct_exit, type: :boolean, default: true,
189
189
  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."
190
190
  option :silence_deprecations, type: :array,
191
191
  banner: "[all]|[GROUP GROUP...]",
192
- desc: "Suppress deprecation warnings. See install_dir/etc/deprecations.json for list of GROUPs or use 'all'."
192
+ desc: "Suppress deprecation warnings. See install_dir/etc/deprecations.json for a list of GROUPs or use 'all'."
193
193
  option :diff, type: :boolean, default: true,
194
194
  desc: "Use --no-diff to suppress 'diff' output of failed textual test results."
195
195
  option :sort_results_by, type: :string, default: "file", banner: "--sort-results-by=none|control|file|random",
@@ -197,7 +197,7 @@ module Inspec
197
197
  option :filter_empty_profiles, type: :boolean, default: false,
198
198
  desc: "Filter empty profiles (profiles without controls) from the report."
199
199
  option :filter_waived_controls, type: :boolean,
200
- desc: "Do not execute waived controls in InSpec at all. Must use with --waiver-file. Ignores `run` setting of waiver file."
200
+ desc: "Do not execute waived controls in InSpec at all. Must use with --waiver-file. Ignores the `run` setting of the waiver file."
201
201
  option :retain_waiver_data, type: :boolean,
202
202
  desc: "EXPERIMENTAL: Only works in conjunction with --filter-waived-controls, retains waiver data about controls that were skipped"
203
203
  option :command_timeout, type: :numeric,
data/lib/inspec/cli.rb CHANGED
@@ -61,9 +61,9 @@ class Inspec::InspecCLI < Inspec::BaseCLI
61
61
  require "license_acceptance/cli_flags/thor"
62
62
  include LicenseAcceptance::CLIFlags::Thor
63
63
 
64
- desc "json PATH", "read all tests in PATH and generate a JSON summary"
64
+ desc "json PATH", "read all tests in the PATH and generate a JSON summary."
65
65
  option :output, aliases: :o, type: :string,
66
- desc: "Save the created profile to a path"
66
+ desc: "Save the created profile to a path."
67
67
  option :controls, type: :array,
68
68
  desc: "A list of controls to include. Ignore all other tests."
69
69
  option :tags, type: :array,
@@ -81,7 +81,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
81
81
  option :format, type: :string,
82
82
  desc: "The output format to use: json, raw, yaml. If valid format is not provided then it will use the default for the given 'what'."
83
83
  option :output, aliases: :o, type: :string,
84
- desc: "Save the created output to a path"
84
+ desc: "Save the created output to a path."
85
85
  option :controls, type: :array,
86
86
  desc: "For --what=profile, a list of controls to include. Ignore all other tests."
87
87
  option :tags, type: :array,
@@ -145,9 +145,11 @@ class Inspec::InspecCLI < Inspec::BaseCLI
145
145
  pretty_handle_exception(e)
146
146
  end
147
147
 
148
- desc "check PATH", "verify all tests at the specified PATH"
148
+ desc "check PATH", "Verify the metadata in the `inspec.yml` file,\
149
+ verify that control blocks have the correct fields (title, description, impact),\
150
+ and define that all controls have visible tests and the controls are not using deprecated InSpec DSL code"
149
151
  option :format, type: :string,
150
- desc: "The output format to use doc (default), json. If valid format is not provided then it will use the default."
152
+ desc: "The output format to use. Valid values: `json` and `doc`. Default value: `doc`."
151
153
  option :with_cookstyle, type: :boolean,
152
154
  desc: "Enable or disable cookstyle checks.", default: false
153
155
  profile_options
@@ -228,10 +230,10 @@ class Inspec::InspecCLI < Inspec::BaseCLI
228
230
  vendor_deps(path, o)
229
231
  end
230
232
 
231
- desc "archive PATH", "archive a profile to tar.gz (default) or zip"
233
+ desc "archive PATH", "Archive a profile to a tar file (default) or zip file."
232
234
  profile_options
233
235
  option :output, aliases: :o, type: :string,
234
- desc: "Save the archive to a path"
236
+ desc: "Save the archive to a path."
235
237
  option :zip, type: :boolean, default: false,
236
238
  desc: "Generates a zip archive."
237
239
  option :tar, type: :boolean, default: false,
@@ -275,14 +277,10 @@ class Inspec::InspecCLI < Inspec::BaseCLI
275
277
  pretty_handle_exception(e)
276
278
  end
277
279
 
278
- desc "exec LOCATIONS", "Run all tests at LOCATIONS."
280
+ desc "exec LOCATIONS", "Run all test files at the specified locations."
279
281
  long_desc <<~EOT
280
- Run all test files at the specified LOCATIONS.
281
-
282
- Loads the given profile(s) and fetches their dependencies if needed. Then
283
- connects to the target and executes any controls contained in the profiles.
284
- One or more reporters are used to generate output.
285
-
282
+ The subcommand loads the given profiles, fetches their dependencies if needed, then connects to the target and executes any controls in the profiles.
283
+ One or more reporters are used to generate the output.
286
284
  ```
287
285
  Exit codes:
288
286
  0 Normal exit, all tests passed
@@ -296,7 +294,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
296
294
 
297
295
  Below are some examples of using `exec` with different test LOCATIONS:
298
296
 
299
- Automate:
297
+ Chef Automate:
300
298
  ```
301
299
  #{Inspec::Dist::EXEC_NAME} automate login
302
300
  #{Inspec::Dist::EXEC_NAME} exec compliance://username/linux-baseline
@@ -306,7 +304,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
306
304
  #{Inspec::Dist::EXEC_NAME} compliance login
307
305
  ```
308
306
 
309
- Supermarket:
307
+ Chef Supermarket:
310
308
  ```
311
309
  #{Inspec::Dist::EXEC_NAME} exec supermarket://username/linux-baseline
312
310
  ```
@@ -343,12 +341,12 @@ class Inspec::InspecCLI < Inspec::BaseCLI
343
341
  #{Inspec::Dist::EXEC_NAME} exec https://github.com/dev-sec/linux-baseline.git
344
342
  ```
345
343
 
346
- Web hosted fileshare (also supports .zip):
344
+ Web hosted file (also supports .zip):
347
345
  ```
348
346
  #{Inspec::Dist::EXEC_NAME} exec https://webserver/linux-baseline.tar.gz
349
347
  ```
350
348
 
351
- Web hosted fileshare with basic authentication (supports .zip):
349
+ Web hosted file with basic authentication (supports .zip):
352
350
  ```
353
351
  #{Inspec::Dist::EXEC_NAME} exec https://username:password@webserver/linux-baseline.tar.gz
354
352
  ```
@@ -371,7 +369,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
371
369
  pretty_handle_exception(e)
372
370
  end
373
371
 
374
- desc "detect", "detect the target OS"
372
+ desc "detect", "detects the target OS."
375
373
  target_options
376
374
  option :format, type: :string
377
375
  def detect
@@ -396,7 +394,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
396
394
  pretty_handle_exception(e)
397
395
  end
398
396
 
399
- desc "shell", "open an interactive debugging shell"
397
+ desc "shell", "open an interactive debugging shell."
400
398
  target_options
401
399
  option :command, aliases: :c,
402
400
  desc: "A single command string to run instead of launching the shell"
@@ -455,7 +453,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
455
453
  pretty_handle_exception(e)
456
454
  end
457
455
 
458
- desc "env", "Output shell-appropriate completion configuration"
456
+ desc "env", "Outputs shell-appropriate completion configuration."
459
457
  def env(shell = nil)
460
458
  p = Inspec::EnvPrinter.new(self.class, shell)
461
459
  p.print_and_exit!
@@ -481,7 +479,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
481
479
  puts Inspec::Telemetry::RunContextProbe.guess_run_context
482
480
  end
483
481
 
484
- desc "version", "prints the version of this tool"
482
+ desc "version", "prints the version of this tool."
485
483
  option :format, type: :string
486
484
  def version
487
485
  if config["format"] == "json"
@@ -495,7 +493,7 @@ class Inspec::InspecCLI < Inspec::BaseCLI
495
493
 
496
494
  desc "clear_cache", "clears the InSpec cache. Useful for debugging."
497
495
  option :vendor_cache, type: :string,
498
- desc: "Use the given path for caching dependencies. (default: ~/.inspec/cache)"
496
+ desc: "Use the given path for caching dependencies, (default: `~/.inspec/cache`)."
499
497
  def clear_cache
500
498
  o = config
501
499
  configure_logger(o)
@@ -26,7 +26,7 @@ module Inspec
26
26
  dep_list = {}
27
27
  dependencies.each do |d|
28
28
  # if depedent profile does not have a source version then only name is used in dependency hash
29
- key_name = (d.source_version ? "#{d.name}-#{d.source_version}" : "#{d.name}") rescue "#{d.name}"
29
+ key_name = (d.source_version.blank? ? "#{d.name}" : "#{d.name}-#{d.source_version}") rescue "#{d.name}"
30
30
  dep_list[key_name] = d
31
31
  end
32
32
  new(cwd, cache, dep_list, backend)
@@ -42,7 +42,7 @@ module Inspec
42
42
  dep_list = {}
43
43
  dep_tree.each do |d|
44
44
  # if depedent profile does not have a source version then only name is used in dependency hash
45
- key_name = (d.source_version ? "#{d.name}-#{d.source_version}" : "#{d.name}") rescue d.name
45
+ key_name = (d.source_version.blank? ? "#{d.name}" : "#{d.name}-#{d.source_version}") rescue "#{d.name}"
46
46
  dep_list[key_name] = d
47
47
  dep_list.merge!(flatten_dep_tree(d.dependencies))
48
48
  end
data/lib/inspec/dsl.rb CHANGED
@@ -91,14 +91,12 @@ module Inspec::DSL
91
91
  if profile_version
92
92
  new_profile_id = "#{profile_id}-#{profile_version}"
93
93
  else
94
- # This scary regex is used to match version following semantic Versioning (SemVer). Thanks to https://ihateregex.io/expr/semver/
95
- regex_for_semver = /(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?/
96
- dependencies.list.keys.each do |key|
94
+ dependencies.list.each do |key, value|
97
95
  # 1. Fetching VERSION from a profile dependency name which is in a format NAME-VERSION.
98
96
  # 2. Matching original profile dependency name with profile name used with include or require control DSL.
99
- fetching_semver = key.match(regex_for_semver).to_s
100
- unless fetching_semver.nil? || fetching_semver.empty?
101
- profile_id_key = key.split("-#{fetching_semver}")[0]
97
+ source_version = value.source_version
98
+ unless source_version.blank?
99
+ profile_id_key = key.split("-#{source_version}")[0]
102
100
  new_profile_id = key if profile_id_key == profile_id
103
101
  end
104
102
  end
@@ -383,24 +383,25 @@ module Inspec
383
383
  @runner_context
384
384
  end
385
385
 
386
- def collect_gem_dependencies(profile_context)
386
+ # This collects the gem dependencies data from parent and its dependent profiles
387
+ def collect_gem_dependencies
387
388
  gem_dependencies = []
388
- all_profiles = []
389
- profile_context.dependencies.list.values.each do |requirement|
390
- all_profiles << requirement.profile
391
- end
392
- all_profiles << self
393
- all_profiles.each do |profile|
389
+ # This collects the dependent profiles gem dependencies if any
390
+ locked_dependencies.dep_list.each do |_name, dep|
391
+ profile = dep.profile
394
392
  gem_dependencies << profile.metadata.gem_dependencies unless profile.metadata.gem_dependencies.empty?
395
393
  end
394
+ # Appends the parent profile gem dependencies which are available through metadata
395
+ gem_dependencies << metadata.gem_dependencies unless metadata.gem_dependencies.empty?
396
396
  gem_dependencies.flatten.uniq
397
397
  end
398
398
 
399
399
  # Loads the required gems specified in the Profile's metadata file from default inspec gems path i.e. ~/.inspec/gems
400
400
  # else installs and loads them.
401
401
  def load_gem_dependencies
402
- gem_dependencies = collect_gem_dependencies(load_libraries)
402
+ gem_dependencies = collect_gem_dependencies
403
403
  gem_dependencies.each do |gem_data|
404
+
404
405
  dependency_loader = DependencyLoader.new
405
406
  if dependency_loader.gem_version_installed?(gem_data[:name], gem_data[:version]) ||
406
407
  dependency_loader.gem_installed?(gem_data[:name])
@@ -304,11 +304,11 @@ module Inspec::Resources
304
304
  # Insecure not supported simply https://stackoverflow.com/questions/11696944/powershell-v3-invoke-webrequest-https-error
305
305
  cmd << "-MaximumRedirection #{max_redirects}" unless max_redirects.nil?
306
306
  request_headers["Authorization"] = """ '\"Basic ' + [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes(\"#{username}:#{password}\")) +'\"' """ unless username.nil? || password.nil?
307
- request_header_string = nil
307
+ request_header_array = []
308
308
  request_headers.each do |k, v|
309
- request_header_string << " #{k} = #{v}"
309
+ request_header_array << " '#{k}' = '#{v}'"
310
310
  end
311
- cmd << "-Headers @{#{request_header_string.join(";")}}" unless request_header_string.nil?
311
+ cmd << "-Headers @{#{request_header_array.join(";")}}" unless request_header_array.empty?
312
312
  if params.nil?
313
313
  cmd << "'#{url}'"
314
314
  else
@@ -84,6 +84,11 @@ module Inspec::Resources
84
84
  options[:ssl_cert] = @ssl_cert unless @ssl_cert.nil?
85
85
  options[:ssl_ca_cert] = @ssl_ca_cert unless @ssl_ca_cert.nil?
86
86
 
87
+ # Setting the logger level to INFO as mongo gem version 2.13.2 is using DEBUG as the log level Ref: https://github.com/mongodb/mongo-ruby-driver/blob/v2.13.2/lib/mongo/logger.rb#L79
88
+ # Latest version of the mongo gem don't have this issue as it set to INFO level Ref: https://github.com/mongodb/mongo-ruby-driver/blob/master/lib/mongo/logger.rb#L82
89
+ # We pinned the version to 2.13.2 as the latest version of the mongo gem has broken symlink https://jira.mongodb.org/browse/RUBY-2546 which causes omnibus build failure.
90
+ # Once we get the latest version working we can remove logger level set here.
91
+ Mongo::Logger.logger.level = Logger::INFO
87
92
  @client = Mongo::Client.new([ "#{host}:#{port}" ], options)
88
93
 
89
94
  rescue => e
@@ -0,0 +1,251 @@
1
+ require "inspec/resources/command"
2
+ require "json" unless defined?(JSON)
3
+
4
+ # @see https://wiki.nftables.org/
5
+ # @see https://www.netfilter.org/projects/nftables/manpage.html
6
+
7
+ # rubocop:disable Style/ClassVars
8
+
9
+ module Inspec::Resources
10
+ class NfTables < Inspec.resource(1)
11
+ name "nftables"
12
+ supports platform: "linux"
13
+ desc "Use the nftables InSpec audit resource to test rules and sets that are defined in nftables, which maintains tables of IP packet filtering rules. There may be more than one table. Each table contains one (or more) chains. A chain is a list of rules that match packets. When the rule matches, the rule defines what target to assign to the packet."
14
+ example <<~EXAMPLE
15
+ describe nftables(family:'inet', table:'filter', chain: 'INPUT') do
16
+ its('type') { should eq 'filter' }
17
+ its('hook') { should eq 'input' }
18
+ its('prio') { should eq 0 } # filter
19
+ its('policy') { should eq 'drop' }
20
+ it { should have_rule('tcp dport { 22, 80, 443 } accept') }
21
+ end
22
+ describe nftables(family: 'inet', table: 'filter', set: 'OPEN_PORTS') do
23
+ its('type') { should eq 'ipv4_addr . inet_proto . inet_service' }
24
+ its('flags') { should include 'interval' }
25
+ it { should have_element('1.1.1.1 . tcp . 25-27') }
26
+ end
27
+ EXAMPLE
28
+
29
+ @@bin = nil
30
+ @@nft_params = {}
31
+ @@nft_params["json"] = ""
32
+ @@nft_params["stateless"] = ""
33
+ @@nft_params["num"] = ""
34
+
35
+ def initialize(params = {})
36
+ @family = params[:family] || nil
37
+ @table = params[:table] || nil
38
+ @chain = params[:chain] || nil
39
+ @set = params[:set] || nil
40
+ @ignore_comments = params[:ignore_comments] || false
41
+ unless @@bin
42
+ @@bin = find_nftables_or_error
43
+ end
44
+
45
+ # Some old versions of `nft` do not support JSON output or stateless modifier
46
+ res = inspec.command("#{@@bin} --version").stdout
47
+ version = Gem::Version.new(/^nftables v(\S+) .*/.match(res)[1])
48
+ case
49
+ when version < Gem::Version.new("0.8.0")
50
+ @@nft_params["num"] = "-nn"
51
+ when version < Gem::Version.new("0.9.0")
52
+ @@nft_params["stateless"] = "-s"
53
+ @@nft_params["num"] = "-nn"
54
+ when version < Gem::Version.new("0.9.3")
55
+ @@nft_params["json"] = "-j"
56
+ @@nft_params["stateless"] = "-s"
57
+ @@nft_params["num"] = "-nn"
58
+ when version >= Gem::Version.new("0.9.3")
59
+ @@nft_params["json"] = "-j"
60
+ @@nft_params["stateless"] = "-s"
61
+ @@nft_params["num"] = "-y"
62
+ ## --terse
63
+ end
64
+
65
+ # family and table attributes are mandatory
66
+ fail_resource "nftables family and table are mandatory." if @family.nil? || @family.empty? || @table.nil? || @table.empty?
67
+ # chain name or set name has to be specified and are mutually exclusive
68
+ fail_resource "You must specify either a chain or a set name." if (@chain.nil? || @chain.empty?) && (@set.nil? || @set.empty?)
69
+ fail_resource "You must specify either a chain or a set name, not both." if !(@chain.nil? || @chain.empty?) && !(@set.nil? || @set.empty?)
70
+
71
+ # we're done if we are on linux
72
+ return if inspec.os.linux?
73
+
74
+ # ensures, all calls are aborted for non-supported os
75
+ @nftables_cache = {}
76
+ skip_resource "The `nftables` resource is not supported on your OS yet."
77
+ end
78
+
79
+ # Let's have a generic method to retrieve attributes for chains and sets
80
+ def _get_attr(name)
81
+ # Some attributes are valid for chains only, for sets only or for both
82
+ valid = {
83
+ "chains" => %w{hook policy prio type},
84
+ "sets" => %w{flags size type},
85
+ }
86
+
87
+ target_obj = @set.nil? ? "chains" : "sets"
88
+
89
+ if valid[target_obj].include?(name)
90
+ attrs = @set.nil? ? retrieve_chain_attrs : retrieve_set_attrs
91
+ else
92
+ raise Inspec::Exceptions::ResourceSkipped, "`#{name}` attribute is not valid for #{target_obj}"
93
+ end
94
+ # flags attribute is an array, if not retrieved ensure we return an empty array
95
+ # otherwise return an empty string
96
+ default = name == "flags" ? [] : ""
97
+ val = attrs.key?(name) ? attrs[name] : default
98
+ # When set type is has multiple data types it's retrieved as an array, make humans life easier
99
+ # by returning a string representation
100
+ if name == "type" && target_obj == "sets" && val.is_a?(Array)
101
+ return val.join(" . ")
102
+ end
103
+
104
+ val
105
+ end
106
+
107
+ # Create a method for each attribute
108
+ %i{flags hook policy prio size type}.each do |attr_method|
109
+ define_method attr_method do
110
+ _get_attr(attr_method.to_s)
111
+ end
112
+ end
113
+
114
+ def has_rule?(rule = nil, _family = nil, _table = nil, _chain = nil)
115
+ # checks if the rule is part of the chain
116
+ # for now, we expect an exact match
117
+ retrieve_chain_rules.any? { |line| line.casecmp(rule) == 0 }
118
+ end
119
+
120
+ def has_element?(element = nil, _family = nil, _table = nil, _chain = nil)
121
+ # checks if the element is part of the set
122
+ # for now, we expect an exact match
123
+ retrieve_set_elements.any? { |line| line.casecmp(element) == 0 }
124
+ end
125
+
126
+ def retrieve_set_elements
127
+ idx = "set_#{@family}_#{@table}_#{@set}"
128
+ return @nftables_cache[idx] if defined?(@nftables_cache) && @nftables_cache.key?(idx)
129
+
130
+ @nftables_cache = {} unless defined?(@nftables_cache)
131
+
132
+ elem_cmd = "list set #{@family} #{@table} #{@set}"
133
+ nftables_cmd = format("%s %s %s", @@bin, @@nft_params["stateless"], elem_cmd).strip
134
+
135
+ cmd = inspec.command(nftables_cmd)
136
+ return [] if cmd.exit_status.to_i != 0
137
+
138
+ @nftables_cache[idx] = cmd.stdout.gsub("\t", "").split("\n").reject { |line| line =~ /^(table|set|type|size|flags|typeof|auto-merge)/ || line =~ /^}$/ }.map { |line| line.sub("elements = {", "").sub("}", "").split(",") }.flatten.map(&:strip)
139
+ end
140
+
141
+ def retrieve_chain_rules
142
+ idx = "rule_#{@family}_#{@table}_#{@chain}"
143
+ return @nftables_cache[idx] if defined?(@nftables_cache) && @nftables_cache.key?(idx)
144
+
145
+ @nftables_cache = {} unless defined?(@nftables_cache)
146
+
147
+ # construct nftables command to read all rules of the given chain
148
+ chain_cmd = "list chain #{@family} #{@table} #{@chain}"
149
+ nftables_cmd = format("%s %s %s %s", @@bin, @@nft_params["stateless"], @@nft_params["num"], chain_cmd).strip
150
+
151
+ cmd = inspec.command(nftables_cmd)
152
+ return [] if cmd.exit_status.to_i != 0
153
+
154
+ rules = cmd.stdout.gsub("\t", "").split("\n").reject { |line| line =~ /^(table|chain)/ || line =~ /^}$/ }
155
+
156
+ if @ignore_comments
157
+ # split rules, returns array or rules without any comment
158
+ @nftables_cache[idx] = remove_comments_from_rules(rules)
159
+ else
160
+ # split rules, returns array or rules
161
+ @nftables_cache[idx] = rules.map(&:strip)
162
+ end
163
+ end
164
+
165
+ def retrieve_chain_attrs
166
+ idx = "chain_attrs_#{@family}_#{@table}_#{@chain}"
167
+ return @nftables_cache[idx] if defined?(@nftables_cache) && @nftables_cache.key?(idx)
168
+
169
+ @nftables_cache = {} unless defined?(@nftables_cache)
170
+
171
+ chain_cmd = "list chain #{@family} #{@table} #{@chain}"
172
+ nftables_cmd = format("%s %s %s %s", @@bin, @@nft_params["stateless"], @@nft_params["json"], chain_cmd).strip
173
+
174
+ cmd = inspec.command(nftables_cmd)
175
+ return {} if cmd.exit_status.to_i != 0
176
+
177
+ if @@nft_params["json"].empty?
178
+ res = cmd.stdout.gsub("\t", "").split("\n").select { |line| line =~ /^type/ }[0]
179
+ parsed = /type (\S+) hook (\S+) priority (\S+); policy (\S+);/.match(res)
180
+ @nftables_cache[idx] = { "type" => parsed[1], "hook" => parsed[2], "prio" => parsed[3].to_i, "policy" => parsed[4] }
181
+ else
182
+ @nftables_cache[idx] = JSON.parse(cmd.stdout)["nftables"].select { |line| line.key?("chain") }[0]["chain"]
183
+ end
184
+ end
185
+
186
+ def retrieve_set_attrs
187
+ idx = "set_attrs_#{@family}_#{@table}_#{@chain}"
188
+ return @nftables_cache[idx] if defined?(@nftables_cache) && @nftables_cache.key?(idx)
189
+
190
+ @nftables_cache = {} unless defined?(@nftables_cache)
191
+
192
+ chain_cmd = "list set #{@family} #{@table} #{@set}"
193
+ nftables_cmd = format("%s %s %s %s", @@bin, @@nft_params["stateless"], @@nft_params["json"], chain_cmd).strip
194
+
195
+ cmd = inspec.command(nftables_cmd)
196
+ return {} if cmd.exit_status.to_i != 0
197
+
198
+ if @@nft_params["json"].empty?
199
+ type = ""
200
+ size = 0
201
+ flags = []
202
+ res = cmd.stdout.gsub("\t", "").split("\n").select { |line| line =~ /^(type|size|flags)/ }
203
+ res.each do |line|
204
+ parsed = /^type (.*)/.match(line)
205
+ if parsed
206
+ type = parsed[1]
207
+ end
208
+ parsed = /^flags (.*)/.match(line)
209
+ if parsed
210
+ flags = parsed[1].split(",")
211
+ end
212
+ parsed = /^size (.*)/.match(line)
213
+ if parsed
214
+ size = parsed[1].to_i
215
+ end
216
+ end
217
+ @nftables_cache[idx] = { "type" => type, "size" => size, "flags" => flags }
218
+ else
219
+ @nftables_cache[idx] = JSON.parse(cmd.stdout)["nftables"].select { |line| line.key?("set") }[0]["set"]
220
+ end
221
+ end
222
+
223
+ def resource_id
224
+ to_s || "nftables"
225
+ end
226
+
227
+ def to_s
228
+ format("nftables (%s %s %s %s)", @family && "family: #{@family}", @table && "table: #{@table}", @chain && "chain: #{@chain}", @set && "set: #{@set}").strip
229
+ end
230
+
231
+ private
232
+
233
+ def remove_comments_from_rules(rules)
234
+ rules.each do |rule|
235
+ next if rule.nil?
236
+
237
+ rule.gsub!(/ comment "([^"]*)"/, "")
238
+ rule.strip
239
+ end
240
+ rules
241
+ end
242
+
243
+ def find_nftables_or_error
244
+ %w{/usr/sbin/nft /sbin/nft nft}.each do |cmd|
245
+ return cmd if inspec.command(cmd).exist?
246
+ end
247
+
248
+ raise Inspec::Exceptions::ResourceFailed, "Could not find `nft`"
249
+ end
250
+ end
251
+ end
@@ -81,7 +81,8 @@ module Inspec::Resources
81
81
  # Socket path and empty host in the connection string establishes socket connection
82
82
  # Socket connection only enabled for non-windows platforms
83
83
  # Windows does not support unix domain sockets
84
- "psql -d postgresql://#{@user}:#{@pass}@/#{dbs}?host=#{@socket_path} -A -t -w -c #{escaped_query(query)}"
84
+ option_port = @port.nil? ? "" : "-p #{@port}" # add explicit port if specified
85
+ "psql -d postgresql://#{@user}:#{@pass}@/#{dbs}?host=#{@socket_path} #{option_port} -A -t -w -c #{escaped_query(query)}"
85
86
  else
86
87
  # Host in connection string establishes tcp/ip connection
87
88
  if inspec.os.windows?
@@ -73,6 +73,7 @@ require "inspec/resources/mssql_sys_conf"
73
73
  require "inspec/resources/mysql"
74
74
  require "inspec/resources/mysql_conf"
75
75
  require "inspec/resources/mysql_session"
76
+ require "inspec/resources/nftables"
76
77
  require "inspec/resources/nginx"
77
78
  require "inspec/resources/nginx_conf"
78
79
  require "inspec/resources/npm"
@@ -57,11 +57,18 @@ class SimpleConfig
57
57
  m = opts[:assignment_regex].match(line)
58
58
  return nil if m.nil?
59
59
 
60
+ values = parse_values(m, opts[:key_values])
61
+
60
62
  if opts[:multiple_values]
61
63
  @vals[m[1]] ||= []
62
- @vals[m[1]].push(parse_values(m, opts[:key_values]))
64
+ if opts[:multiple_value_regex] # can be used only if multiple values is set as true
65
+ value_to_array = values.split(opts[:multiple_value_regex])
66
+ @vals[m[1]].concat(value_to_array)
67
+ else
68
+ @vals[m[1]].push(values)
69
+ end
63
70
  else
64
- @vals[m[1]] = parse_values(m, opts[:key_values])
71
+ @vals[m[1]] = values
65
72
  end
66
73
  end
67
74
 
@@ -116,6 +123,7 @@ class SimpleConfig
116
123
  key_values: 1, # default for key=value, may require for 'key val1 val2 val3'
117
124
  standalone_comments: false,
118
125
  multiple_values: false,
126
+ multiple_value_regex: nil,
119
127
  }
120
128
  end
121
129
  end
@@ -1,3 +1,3 @@
1
1
  module Inspec
2
- VERSION = "5.21.29".freeze
2
+ VERSION = "5.22.3".freeze
3
3
  end
@@ -148,7 +148,7 @@ RSpec::Matchers.define :be_resolvable do
148
148
  end
149
149
  end
150
150
 
151
- # matcher for iptables and ip6tables
151
+ # matcher for iptables, ip6tables and nftables
152
152
  RSpec::Matchers.define :have_rule do |rule|
153
153
  match do |tables|
154
154
  tables.has_rule?(rule)
@@ -163,6 +163,13 @@ RSpec::Matchers.define :have_rule do |rule|
163
163
  end
164
164
  end
165
165
 
166
+ # matcher for nftables sets
167
+ RSpec::Matchers.define :have_element do |elem|
168
+ match do |sets|
169
+ sets.has_element?(elem)
170
+ end
171
+ end
172
+
166
173
  # `be_in` matcher
167
174
  # You can use it in the following cases:
168
175
  # - check if an item or array is included in a given array
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: inspec-core
3
3
  version: !ruby/object:Gem::Version
4
- version: 5.21.29
4
+ version: 5.22.3
5
5
  platform: ruby
6
6
  authors:
7
7
  - Chef InSpec Team
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2023-01-24 00:00:00.000000000 Z
11
+ date: 2023-05-16 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: chef-telemetry
@@ -584,6 +584,7 @@ files:
584
584
  - lib/inspec/resources/mysql.rb
585
585
  - lib/inspec/resources/mysql_conf.rb
586
586
  - lib/inspec/resources/mysql_session.rb
587
+ - lib/inspec/resources/nftables.rb
587
588
  - lib/inspec/resources/nginx.rb
588
589
  - lib/inspec/resources/nginx_conf.rb
589
590
  - lib/inspec/resources/noop.rb