From a4aa26fa484d688b36a7983ec43d725c93a54949 Mon Sep 17 00:00:00 2001 From: Steven Pritchard Date: Fri, 13 Dec 2024 17:32:33 -0600 Subject: [PATCH] Clean up for rubocop --- .github/workflows/pr_tests.yml | 11 +- .rubocop.yml | 699 ++++++++++++++++++ Gemfile | 11 +- lib/facter/auditd_sample_ruleset_location.rb | 5 +- lib/facter/auditd_sample_rulesets.rb | 8 +- lib/facter/auditd_version.rb | 6 +- .../functions/auditd/get_array_index.rb | 7 +- .../00_simp_profile_install_spec.rb | 30 +- .../compliance/01_simp_profile_inspec_spec.rb | 27 +- .../20_stig_profile_install_spec.rb | 30 +- .../compliance/21_stig_profile_inspec_spec.rb | 27 +- .../compliance/22_stig_profile_oscap_spec.rb | 15 +- .../acceptance/suites/default/00_base_spec.rb | 100 +-- .../default/10_alt_audit_profiles_spec.rb | 82 +- .../default/20_built_in_audit_profile_spec.rb | 85 +-- .../suites/default/90_disable_audit_spec.rb | 35 +- .../default/99_disable_audit_kernel_spec.rb | 46 +- ...uditd_sample_ruleset_location_fact_spec.rb | 5 +- spec/acceptance/suites/default/lib/util.rb | 184 +++-- spec/classes/config/audisp/syslog_spec.rb | 89 ++- .../config/audit_profiles/built_in_spec.rb | 255 ++++--- .../config/audit_profiles/custom_spec.rb | 92 ++- .../config/audit_profiles/simp_spec.rb | 145 ++-- .../config/audit_profiles/stig_spec.rb | 53 +- spec/classes/config/audit_profiles_spec.rb | 66 +- spec/classes/config/grub_spec.rb | 28 +- spec/classes/config_spec.rb | 255 +++---- spec/classes/init_spec.rb | 67 +- spec/defines/rule_spec.rb | 110 +-- spec/functions/auditd/get_array_index_spec.rb | 13 +- spec/spec_helper.rb | 15 +- spec/spec_helper_acceptance.rb | 39 +- .../compliance_engine_enforce_spec.rb | 97 ++- 33 files changed, 1722 insertions(+), 1015 deletions(-) create mode 100644 .rubocop.yml diff --git a/.github/workflows/pr_tests.yml b/.github/workflows/pr_tests.yml index 21ca28c1..bcc5fb01 100644 --- a/.github/workflows/pr_tests.yml +++ b/.github/workflows/pr_tests.yml @@ -35,7 +35,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - name: "Install Ruby ${{matrix.puppet.ruby_version}}" + - name: "Install Ruby 2.7" uses: ruby/setup-ruby@v1 # ruby/setup-ruby@ec106b438a1ff6ff109590de34ddc62c540232e0 with: ruby-version: 2.7 @@ -47,7 +47,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - name: "Install Ruby ${{matrix.puppet.ruby_version}}" + - name: "Install Ruby 2.7" uses: ruby/setup-ruby@v1 with: ruby-version: 2.7 @@ -56,13 +56,12 @@ jobs: - run: "bundle exec rake metadata_lint" ruby-style: - if: false # TODO Modules will need: rubocop in Gemfile, .rubocop.yml - name: 'Ruby Style (experimental)' + name: 'Ruby Style' runs-on: ubuntu-latest continue-on-error: true steps: - uses: actions/checkout@v3 - - name: "Install Ruby ${{matrix.puppet.ruby_version}}" + - name: "Install Ruby 2.7" uses: ruby/setup-ruby@v1 with: ruby-version: 2.7 @@ -89,7 +88,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - name: 'Install Ruby ${{matrix.puppet.ruby_version}}' + - name: 'Install Ruby 2.7' uses: ruby/setup-ruby@v1 with: ruby-version: 2.7 diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 00000000..65c8c0ab --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,699 @@ +--- +require: + - rubocop-performance + - rubocop-rake + - rubocop-rspec +AllCops: + NewCops: enable + DisplayCopNames: true + TargetRubyVersion: "2.7" + Include: + - "**/*.rb" + Exclude: + - bin/* + - ".vendor/**/*" + - pkg/**/* + - spec/fixtures/**/* + - vendor/**/* + - "**/Puppetfile" + - "**/Vagrantfile" + - "**/Guardfile" +Layout/LineLength: + Description: People have wide screens, use them. + Max: 200 +RSpec/BeforeAfterAll: + Description: + Beware of using after(:all) as it may cause state to leak between tests. + A necessary evil in acceptance testing. + Exclude: + - spec/acceptance/**/*.rb +RSpec/HookArgument: + Description: Prefer explicit :each argument, matching existing module's style + EnforcedStyle: each +RSpec/DescribeSymbol: + Exclude: + - spec/unit/facter/**/*.rb +Style/BlockDelimiters: + Description: + Prefer braces for chaining. Mostly an aesthetical choice. Better to + be consistent then. + EnforcedStyle: braces_for_chaining +Style/ClassAndModuleChildren: + Description: Compact style reduces the required amount of indentation. + EnforcedStyle: compact +Style/EmptyElse: + Description: Enforce against empty else clauses, but allow `nil` for clarity. + EnforcedStyle: empty +Style/FormatString: + Description: Following the main puppet project's style, prefer the % format format. + EnforcedStyle: percent +Style/FormatStringToken: + Description: + Following the main puppet project's style, prefer the simpler template + tokens over annotated ones. + EnforcedStyle: template +Style/Lambda: + Description: Prefer the keyword for easier discoverability. + EnforcedStyle: literal +Style/RegexpLiteral: + Description: Community preference. See https://github.com/voxpupuli/modulesync_config/issues/168 + EnforcedStyle: percent_r +Style/TernaryParentheses: + Description: + Checks for use of parentheses around ternary conditions. Enforce parentheses + on complex expressions for better readability, but seriously consider breaking + it up. + EnforcedStyle: require_parentheses_when_complex +Style/TrailingCommaInArguments: + Description: + Prefer always trailing comma on multiline argument lists. This makes + diffs, and re-ordering nicer. + EnforcedStyleForMultiline: comma +Style/TrailingCommaInArrayLiteral: + Description: + Prefer always trailing comma on multiline literals. This makes diffs, + and re-ordering nicer. + EnforcedStyleForMultiline: comma +Style/SymbolArray: + Description: Using percent style obscures symbolic intent of array's contents. + EnforcedStyle: brackets +RSpec/MessageSpies: + EnforcedStyle: receive +Style/Documentation: + Exclude: + - lib/puppet/parser/functions/**/* + - spec/**/* +Style/WordArray: + EnforcedStyle: brackets +Performance/AncestorsInclude: + Enabled: true +Performance/BigDecimalWithNumericArgument: + Enabled: true +Performance/BlockGivenWithExplicitBlock: + Enabled: true +Performance/CaseWhenSplat: + Enabled: true +Performance/ConstantRegexp: + Enabled: true +Performance/MethodObjectAsBlock: + Enabled: true +Performance/RedundantSortBlock: + Enabled: true +Performance/RedundantStringChars: + Enabled: true +Performance/ReverseFirst: + Enabled: true +Performance/SortReverse: + Enabled: true +Performance/Squeeze: + Enabled: true +Performance/StringInclude: + Enabled: true +Performance/Sum: + Enabled: true +Style/CollectionMethods: + Enabled: true +Style/MethodCalledOnDoEndBlock: + Enabled: true +Style/StringMethods: + Enabled: true +Bundler/GemFilename: + Enabled: false +Bundler/InsecureProtocolSource: + Enabled: false +Gemspec/DuplicatedAssignment: + Enabled: false +Gemspec/OrderedDependencies: + Enabled: false +Gemspec/RequiredRubyVersion: + Enabled: false +Gemspec/RubyVersionGlobalsUsage: + Enabled: false +Layout/ArgumentAlignment: + Enabled: false +Layout/BeginEndAlignment: + Enabled: false +Layout/ClosingHeredocIndentation: + Enabled: false +Layout/EmptyComment: + Enabled: false +Layout/EmptyLineAfterGuardClause: + Enabled: false +Layout/EmptyLinesAroundArguments: + Enabled: false +Layout/EmptyLinesAroundAttributeAccessor: + Enabled: false +Layout/EndOfLine: + Enabled: false +Layout/FirstArgumentIndentation: + Enabled: false +Layout/HashAlignment: + Enabled: false +Layout/HeredocIndentation: + Enabled: false +Layout/LeadingEmptyLines: + Enabled: false +Layout/SpaceAroundMethodCallOperator: + Enabled: false +Layout/SpaceInsideArrayLiteralBrackets: + Enabled: false +Layout/SpaceInsideReferenceBrackets: + Enabled: false +Lint/BigDecimalNew: + Enabled: false +Lint/BooleanSymbol: + Enabled: false +Lint/ConstantDefinitionInBlock: + Enabled: false +Lint/DeprecatedOpenSSLConstant: + Enabled: false +Lint/DisjunctiveAssignmentInConstructor: + Enabled: false +Lint/DuplicateElsifCondition: + Enabled: false +Lint/DuplicateRequire: + Enabled: false +Lint/DuplicateRescueException: + Enabled: false +Lint/EmptyConditionalBody: + Enabled: false +Lint/EmptyFile: + Enabled: false +Lint/ErbNewArguments: + Enabled: false +Lint/FloatComparison: + Enabled: false +Lint/HashCompareByIdentity: + Enabled: false +Lint/IdentityComparison: + Enabled: false +Lint/InterpolationCheck: + Enabled: false +Lint/MissingCopEnableDirective: + Enabled: false +Lint/MixedRegexpCaptureTypes: + Enabled: false +Lint/NestedPercentLiteral: + Enabled: false +Lint/NonDeterministicRequireOrder: + Enabled: false +Lint/OrderedMagicComments: + Enabled: false +Lint/OutOfRangeRegexpRef: + Enabled: false +Lint/RaiseException: + Enabled: false +Lint/RedundantCopEnableDirective: + Enabled: false +Lint/RedundantRequireStatement: + Enabled: false +Lint/RedundantSafeNavigation: + Enabled: false +Lint/RedundantWithIndex: + Enabled: false +Lint/RedundantWithObject: + Enabled: false +Lint/RegexpAsCondition: + Enabled: false +Lint/ReturnInVoidContext: + Enabled: false +Lint/SafeNavigationConsistency: + Enabled: false +Lint/SafeNavigationWithEmpty: + Enabled: false +Lint/SelfAssignment: + Enabled: false +Lint/SendWithMixinArgument: + Enabled: false +Lint/ShadowedArgument: + Enabled: false +Lint/StructNewOverride: + Enabled: false +Lint/ToJSON: + Enabled: false +Lint/TopLevelReturnWithArgument: + Enabled: false +Lint/TrailingCommaInAttributeDeclaration: + Enabled: false +Lint/UnreachableLoop: + Enabled: false +Lint/UriEscapeUnescape: + Enabled: false +Lint/UriRegexp: + Enabled: false +Lint/UselessMethodDefinition: + Enabled: false +Lint/UselessTimes: + Enabled: false +Metrics/AbcSize: + Enabled: false +Metrics/BlockLength: + Enabled: false +Metrics/BlockNesting: + Enabled: false +Metrics/ClassLength: + Enabled: false +Metrics/CyclomaticComplexity: + Enabled: false +Metrics/MethodLength: + Enabled: false +Metrics/ModuleLength: + Enabled: false +Metrics/ParameterLists: + Enabled: false +Metrics/PerceivedComplexity: + Enabled: false +Migration/DepartmentName: + Enabled: false +Naming/AccessorMethodName: + Enabled: false +Naming/BlockParameterName: + Enabled: false +Naming/HeredocDelimiterCase: + Enabled: false +Naming/HeredocDelimiterNaming: + Enabled: false +Naming/MemoizedInstanceVariableName: + Enabled: false +Naming/MethodParameterName: + Enabled: false +Naming/RescuedExceptionsVariableName: + Enabled: false +Naming/VariableNumber: + Enabled: false +Performance/BindCall: + Enabled: false +Performance/DeletePrefix: + Enabled: false +Performance/DeleteSuffix: + Enabled: false +Performance/InefficientHashSearch: + Enabled: false +Performance/UnfreezeString: + Enabled: false +Performance/UriDefaultParser: + Enabled: false +RSpec/Be: + Enabled: false +RSpec/Dialect: + Enabled: false +RSpec/ContainExactly: + Enabled: false +RSpec/ContextMethod: + Enabled: false +RSpec/ContextWording: + Enabled: false +RSpec/DescribeClass: + Enabled: false +RSpec/EmptyHook: + Enabled: false +RSpec/EmptyLineAfterExample: + Enabled: false +RSpec/EmptyLineAfterExampleGroup: + Enabled: false +RSpec/EmptyLineAfterHook: + Enabled: false +RSpec/ExampleLength: + Enabled: false +RSpec/ExampleWithoutDescription: + Enabled: false +RSpec/ExpectChange: + Enabled: false +RSpec/ExpectInHook: + Enabled: false +RSpec/HooksBeforeExamples: + Enabled: false +RSpec/ImplicitBlockExpectation: + Enabled: false +RSpec/ImplicitSubject: + Enabled: false +RSpec/LeakyConstantDeclaration: + Enabled: false +RSpec/LetBeforeExamples: + Enabled: false +RSpec/MatchArray: + Enabled: false +RSpec/MissingExampleGroupArgument: + Enabled: false +RSpec/MultipleExpectations: + Enabled: false +RSpec/MultipleMemoizedHelpers: + Enabled: false +RSpec/MultipleSubjects: + Enabled: false +RSpec/NestedGroups: + Enabled: false +RSpec/PredicateMatcher: + Enabled: false +RSpec/ReceiveCounts: + Enabled: false +RSpec/ReceiveNever: + Enabled: false +RSpec/RepeatedExampleGroupBody: + Enabled: false +RSpec/RepeatedExampleGroupDescription: + Enabled: false +RSpec/RepeatedIncludeExample: + Enabled: false +RSpec/ReturnFromStub: + Enabled: false +RSpec/SharedExamples: + Enabled: false +RSpec/StubbedMock: + Enabled: false +RSpec/UnspecifiedException: + Enabled: false +RSpec/VariableDefinition: + Enabled: false +RSpec/VoidExpect: + Enabled: false +RSpec/Yield: + Enabled: false +Security/Open: + Enabled: false +Style/AccessModifierDeclarations: + Enabled: false +Style/AccessorGrouping: + Enabled: false +Style/BisectedAttrAccessor: + Enabled: false +Style/CaseLikeIf: + Enabled: false +Style/ClassEqualityComparison: + Enabled: false +Style/ColonMethodDefinition: + Enabled: false +Style/CombinableLoops: + Enabled: false +Style/CommentedKeyword: + Enabled: false +Style/Dir: + Enabled: false +Style/DoubleCopDisableDirective: + Enabled: false +Style/EmptyBlockParameter: + Enabled: false +Style/EmptyLambdaParameter: + Enabled: false +Style/Encoding: + Enabled: false +Style/EvalWithLocation: + Enabled: false +Style/ExpandPathArguments: + Enabled: false +Style/ExplicitBlockArgument: + Enabled: false +Style/ExponentialNotation: + Enabled: false +Style/FloatDivision: + Enabled: false +Style/FrozenStringLiteralComment: + Enabled: false +Style/GlobalStdStream: + Enabled: false +Style/HashAsLastArrayItem: + Enabled: false +Style/HashLikeCase: + Enabled: false +Style/HashTransformKeys: + Enabled: false +Style/HashTransformValues: + Enabled: false +Style/IfUnlessModifier: + Enabled: false +Style/KeywordParametersOrder: + Enabled: false +Style/MinMax: + Enabled: false +Style/MixinUsage: + Enabled: false +Style/MultilineWhenThen: + Enabled: false +Style/NegatedUnless: + Enabled: false +Style/NumericPredicate: + Enabled: false +Style/OptionalBooleanParameter: + Enabled: false +Style/OrAssignment: + Enabled: false +Style/RandomWithOffset: + Enabled: false +Style/RedundantAssignment: + Enabled: false +Style/RedundantCondition: + Enabled: false +Style/RedundantConditional: + Enabled: false +Style/RedundantFetchBlock: + Enabled: false +Style/RedundantFileExtensionInRequire: + Enabled: false +Style/RedundantRegexpCharacterClass: + Enabled: false +Style/RedundantRegexpEscape: + Enabled: false +Style/RedundantSelfAssignment: + Enabled: false +Style/RedundantSort: + Enabled: false +Style/RescueStandardError: + Enabled: false +Style/SingleArgumentDig: + Enabled: false +Style/SlicingWithRange: + Enabled: false +Style/SoleNestedConditional: + Enabled: false +Style/StderrPuts: + Enabled: false +Style/StringConcatenation: + Enabled: false +Style/Strip: + Enabled: false +Style/SymbolProc: + Enabled: false +Style/TrailingBodyOnClass: + Enabled: false +Style/TrailingBodyOnMethodDefinition: + Enabled: false +Style/TrailingBodyOnModule: + Enabled: false +Style/TrailingCommaInHashLiteral: + Enabled: false +Style/TrailingMethodEndStatement: + Enabled: false +Style/UnpackFirst: + Enabled: false +Gemspec/DeprecatedAttributeAssignment: + Enabled: false +Gemspec/DevelopmentDependencies: + Enabled: false +Gemspec/RequireMFA: + Enabled: false +Layout/LineContinuationLeadingSpace: + Enabled: false +Layout/LineContinuationSpacing: + Enabled: false +Layout/LineEndStringConcatenationIndentation: + Enabled: false +Layout/SpaceBeforeBrackets: + Enabled: false +Lint/AmbiguousAssignment: + Enabled: false +Lint/AmbiguousOperatorPrecedence: + Enabled: false +Lint/AmbiguousRange: + Enabled: false +Lint/ConstantOverwrittenInRescue: + Enabled: false +Lint/DeprecatedConstants: + Enabled: false +Lint/DuplicateBranch: + Enabled: false +Lint/DuplicateMagicComment: + Enabled: false +Lint/DuplicateMatchPattern: + Enabled: false +Lint/DuplicateRegexpCharacterClassElement: + Enabled: false +Lint/EmptyBlock: + Enabled: false +Lint/EmptyClass: + Enabled: false +Lint/EmptyInPattern: + Enabled: false +Lint/IncompatibleIoSelectWithFiberScheduler: + Enabled: false +Lint/LambdaWithoutLiteralBlock: + Enabled: false +Lint/NoReturnInBeginEndBlocks: + Enabled: false +Lint/NonAtomicFileOperation: + Enabled: false +Lint/NumberedParameterAssignment: + Enabled: false +Lint/OrAssignmentToConstant: + Enabled: false +Lint/RedundantDirGlobSort: + Enabled: false +Lint/RefinementImportMethods: + Enabled: false +Lint/RequireRangeParentheses: + Enabled: false +Lint/RequireRelativeSelfPath: + Enabled: false +Lint/SymbolConversion: + Enabled: false +Lint/ToEnumArguments: + Enabled: false +Lint/TripleQuotes: + Enabled: false +Lint/UnexpectedBlockArity: + Enabled: false +Lint/UnmodifiedReduceAccumulator: + Enabled: false +Lint/UselessRescue: + Enabled: false +Lint/UselessRuby2Keywords: + Enabled: false +Metrics/CollectionLiteralLength: + Enabled: false +Naming/BlockForwarding: + Enabled: false +Performance/CollectionLiteralInLoop: + Enabled: false +Performance/ConcurrentMonotonicTime: + Enabled: false +Performance/MapCompact: + Enabled: false +Performance/RedundantEqualityComparisonBlock: + Enabled: false +Performance/RedundantSplitRegexpArgument: + Enabled: false +Performance/StringIdentifierArgument: + Enabled: false +RSpec/BeEq: + Enabled: false +RSpec/BeNil: + Enabled: false +RSpec/ChangeByZero: + Enabled: false +RSpec/ClassCheck: + Enabled: false +RSpec/DuplicatedMetadata: + Enabled: false +RSpec/ExcessiveDocstringSpacing: + Enabled: false +RSpec/IdenticalEqualityAssertion: + Enabled: false +RSpec/NoExpectationExample: + Enabled: false +RSpec/PendingWithoutReason: + Enabled: false +RSpec/RedundantAround: + Enabled: false +RSpec/SkipBlockInsideExample: + Enabled: false +RSpec/SortMetadata: + Enabled: false +RSpec/SubjectDeclaration: + Enabled: false +RSpec/VerifiedDoubleReference: + Enabled: false +Security/CompoundHash: + Enabled: false +Security/IoMethods: + Enabled: false +Style/ArgumentsForwarding: + Enabled: false +Style/ArrayIntersect: + Enabled: false +Style/CollectionCompact: + Enabled: false +Style/ComparableClamp: + Enabled: false +Style/ConcatArrayLiterals: + Enabled: false +Style/DataInheritance: + Enabled: false +Style/DirEmpty: + Enabled: false +Style/DocumentDynamicEvalDefinition: + Enabled: false +Style/EmptyHeredoc: + Enabled: false +Style/EndlessMethod: + Enabled: false +Style/EnvHome: + Enabled: false +Style/FetchEnvVar: + Enabled: false +Style/FileEmpty: + Enabled: false +Style/FileRead: + Enabled: false +Style/FileWrite: + Enabled: false +Style/HashConversion: + Enabled: false +Style/HashExcept: + Enabled: false +Style/IfWithBooleanLiteralBranches: + Enabled: false +Style/InPatternThen: + Enabled: false +Style/MagicCommentFormat: + Enabled: false +Style/MapCompactWithConditionalBlock: + Enabled: false +Style/MapToHash: + Enabled: false +Style/MapToSet: + Enabled: false +Style/MinMaxComparison: + Enabled: false +Style/MultilineInPatternThen: + Enabled: false +Style/NegatedIfElseCondition: + Enabled: false +Style/NestedFileDirname: + Enabled: false +Style/NilLambda: + Enabled: false +Style/NumberedParameters: + Enabled: false +Style/NumberedParametersLimit: + Enabled: false +Style/ObjectThen: + Enabled: false +Style/OpenStructUse: + Enabled: false +Style/OperatorMethodCall: + Enabled: false +Style/QuotedSymbols: + Enabled: false +Style/RedundantArgument: + Enabled: false +Style/RedundantConstantBase: + Enabled: false +Style/RedundantDoubleSplatHashBraces: + Enabled: false +Style/RedundantEach: + Enabled: false +Style/RedundantHeredocDelimiterQuotes: + Enabled: false +Style/RedundantInitialize: + Enabled: false +Style/RedundantLineContinuation: + Enabled: false +Style/RedundantSelfAssignmentBranch: + Enabled: false +Style/RedundantStringEscape: + Enabled: false +Style/SelectByRegexp: + Enabled: false +Style/StringChars: + Enabled: false +Style/SwapValues: + Enabled: false diff --git a/Gemfile b/Gemfile index e74c3dad..7c330d61 100644 --- a/Gemfile +++ b/Gemfile @@ -10,16 +10,23 @@ ENV['PDK_DISABLE_ANALYTICS'] ||= 'true' gem_sources.each { |gem_source| source gem_source } +group :syntax do + gem 'metadata-json-lint' + gem 'puppet-lint-trailing_comma-check', require: false + gem 'rubocop', '~> 1.68.0' + gem 'rubocop-performance', '~> 1.23.0' + gem 'rubocop-rake', '~> 0.6.0' + gem 'rubocop-rspec', '~> 3.2.0' +end + group :test do puppet_version = ENV.fetch('PUPPET_VERSION', ['>= 7', '< 9']) major_puppet_version = Array(puppet_version).first.scan(%r{(\d+)(?:\.|\Z)}).flatten.first.to_i gem 'hiera-puppet-helper' - gem 'metadata-json-lint' gem 'pathspec', '~> 0.2' if Gem::Requirement.create('< 2.6').satisfied_by?(Gem::Version.new(RUBY_VERSION.dup)) gem('pdk', ENV.fetch('PDK_VERSION', ['>= 2.0', '< 4.0']), require: false) if major_puppet_version > 5 gem 'puppet', puppet_version gem 'puppetlabs_spec_helper' - gem 'puppet-lint-trailing_comma-check', require: false gem 'puppet-strings' gem 'rake' gem 'rspec' diff --git a/lib/facter/auditd_sample_ruleset_location.rb b/lib/facter/auditd_sample_ruleset_location.rb index b72a2b72..0d520f1a 100644 --- a/lib/facter/auditd_sample_ruleset_location.rb +++ b/lib/facter/auditd_sample_ruleset_location.rb @@ -5,16 +5,15 @@ # Current output is a string containing the location of the audit sample rules # Facter.add('auditd_sample_ruleset_location') do - confine :kernel => 'Linux' + confine kernel: 'Linux' confine do File.directory?('/usr/share/audit/sample-rules') || !Dir.glob('/usr/share/doc/audit*/rules').empty? end setcode do - retval = '/usr/share/audit/sample-rules' if File.directory?('/usr/share/audit/sample-rules') - retval = Dir.glob('/usr/share/doc/audit*/rules').first if !Dir.glob('/usr/share/doc/audit*/rules').empty? + retval = Dir.glob('/usr/share/doc/audit*/rules').first unless Dir.glob('/usr/share/doc/audit*/rules').empty? retval end diff --git a/lib/facter/auditd_sample_rulesets.rb b/lib/facter/auditd_sample_rulesets.rb index de85033f..defe57a8 100644 --- a/lib/facter/auditd_sample_rulesets.rb +++ b/lib/facter/auditd_sample_rulesets.rb @@ -1,6 +1,6 @@ # _Description_ # -# Set a fact with all of the sample ruleset names if they exist on +# Set a fact with all of the sample ruleset names if they exist on # the system for being able to utilize included rulesets # # Current output is hash containing: @@ -10,7 +10,7 @@ # } # Facter.add('auditd_sample_rulesets') do - confine :kernel => 'Linux' + confine kernel: 'Linux' confine do !Facter.value(:auditd_sample_ruleset_location).nil? @@ -19,10 +19,10 @@ setcode do retval = {} - Dir["#{Facter.value(:auditd_sample_ruleset_location)}/*.rules"].map { |x| + Dir["#{Facter.value(:auditd_sample_ruleset_location)}/*.rules"].map do |x| order, name = File.basename(x, '.rules').split('-', 2) retval[name] = { 'order' => order } - } + end retval end diff --git a/lib/facter/auditd_version.rb b/lib/facter/auditd_version.rb index 6e1b968b..d0e904f0 100644 --- a/lib/facter/auditd_version.rb +++ b/lib/facter/auditd_version.rb @@ -4,7 +4,7 @@ # This is useful for applying the correct configuration file options. # Facter.add('auditd_version') do - confine :kernel => 'Linux' + confine kernel: 'Linux' setcode do auditd_facts = Facter.value('simplib__auditd') @@ -13,10 +13,10 @@ end Facter.add('auditd_major_version') do - confine :kernel => 'Linux' + confine kernel: 'Linux' setcode do auditd_version = Facter.value('auditd_version') - auditd_version.split('.').first if auditd_version + auditd_version&.split('.')&.first end end diff --git a/lib/puppet/functions/auditd/get_array_index.rb b/lib/puppet/functions/auditd/get_array_index.rb index b44d3c20..a2fd0aea 100644 --- a/lib/puppet/functions/auditd/get_array_index.rb +++ b/lib/puppet/functions/auditd/get_array_index.rb @@ -3,10 +3,9 @@ # Terminates catalog compilation if the element is not found within # the array. Puppet::Functions.create_function(:'auditd::get_array_index') do - # @param element The element # @param array The array - # @param min_digits The minimum number of digits the index should be. + # @param min_digits The minimum number of digits the index should be. # It will be '0'-padded to meet this number. # @return [String] Index of `element` in `array` represented as # a string @@ -21,9 +20,9 @@ def get_array_index(element, array, min_digits = 2) index_num = array.index(element) if index_num.nil? - fail("auditd::get_array_index: #{element} is not found in #{array}") + raise("auditd::get_array_index: #{element} is not found in #{array}") end - sprintf('%01$*2$d', index_num, min_digits) + '%01$*2$d' % [index_num, min_digits] end end diff --git a/spec/acceptance/suites/compliance/00_simp_profile_install_spec.rb b/spec/acceptance/suites/compliance/00_simp_profile_install_spec.rb index 47ffe841..a42b3e08 100644 --- a/spec/acceptance/suites/compliance/00_simp_profile_install_spec.rb +++ b/spec/acceptance/suites/compliance/00_simp_profile_install_spec.rb @@ -3,14 +3,14 @@ test_name 'auditd STIG enforcement of simp profile' describe 'auditd STIG enforcement of simp profile' do - - let(:manifest) { + let(:manifest) do <<-EOS include 'auditd' EOS - } + end - let(:hieradata) { <<-EOF + let(:hieradata) do + <<-EOF --- simp_options::pki: true simp_options::pki::source: '/etc/pki/simp-testing/pki' @@ -18,11 +18,11 @@ compliance_markup::enforcement: - disa_stig EOF - } + end hosts.each do |host| - - let(:hiera_yaml) { <<-EOM + let(:hiera_yaml) do + <<-EOM --- version: 5 hierarchy: @@ -34,29 +34,29 @@ data_hash: yaml_data datadir: "#{hiera_datadir(host)}" EOM - } + end context 'when enforcing the STIG' do - it 'should work with no errors' do + it 'works with no errors' do create_remote_file(host, host.puppet['hiera_config'], hiera_yaml) write_hieradata_to(host, hieradata) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should reboot to fully apply' do + it 'reboots to fully apply' do host.reboot end # Some versions of auditd leave a backup rules file in place when they # recompile. This is caught by our 'purge' setting in the directory # management and will cause subsequent activity. - it 'will apply to cleanup' do - apply_manifest_on(host, manifest, :catch_failures => true) + it 'applies to cleanup' do + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be idempotent' do - apply_manifest_on(host, manifest, :catch_changes => true) + it 'is idempotent' do + apply_manifest_on(host, manifest, catch_changes: true) end end end diff --git a/spec/acceptance/suites/compliance/01_simp_profile_inspec_spec.rb b/spec/acceptance/suites/compliance/01_simp_profile_inspec_spec.rb index 18cb5df1..0bdd0aea 100644 --- a/spec/acceptance/suites/compliance/01_simp_profile_inspec_spec.rb +++ b/spec/acceptance/suites/compliance/01_simp_profile_inspec_spec.rb @@ -4,7 +4,6 @@ test_name 'Check Inspec for simp profile' describe 'run inspec against the appropriate fixtures for simp audit profile' do - profiles_to_validate = ['disa_stig'] hosts.each do |host| @@ -14,31 +13,27 @@ profile_path = File.join( fixtures_path, 'inspec_profiles', - "#{fact_on(host, 'os.name')}-#{fact_on(host, 'os.release.major')}-#{profile}" + "#{fact_on(host, 'os.name')}-#{fact_on(host, 'os.release.major')}-#{profile}", ) - unless File.exist?(profile_path) - it 'should run inspec' do - skip("No matching profile available at #{profile_path}") - end - else + if File.exist?(profile_path) before(:all) do @inspec = Simp::BeakerHelpers::Inspec.new(host, profile) - @inspec_report = {:data => nil} + @inspec_report = { data: nil } end - it 'should run inspec' do + it 'runs inspec' do @inspec.run end - it 'should have an inspec report' do + it 'has an inspec report' do @inspec_report[:data] = @inspec.process_inspec_results info = [ 'Results:', " * Passed: #{@inspec_report[:data][:passed]}", " * Failed: #{@inspec_report[:data][:failed]}", - " * Skipped: #{@inspec_report[:data][:skipped]}" + " * Skipped: #{@inspec_report[:data][:skipped]}", ] puts info.join("\n") @@ -46,11 +41,11 @@ @inspec.write_report(@inspec_report[:data]) end - it 'should have run some tests' do + it 'has run some tests' do expect(@inspec_report[:data][:failed] + @inspec_report[:data][:passed]).to be > 0 end - it 'should not have any failing tests' do + it 'does not have any failing tests' do # 2 tests erroneously fail # - 'All privileged function executions must be audited': # - inspec_profiles/profiles/disa_stig-el7-baseline/controls/V-72095.rb @@ -64,7 +59,11 @@ puts @inspec_report[:data][:report] end - expect( @inspec_report[:data][:failed] ).to eq(0) + expect(@inspec_report[:data][:failed]).to eq(0) + end + else + it 'runs inspec' do + skip("No matching profile available at #{profile_path}") end end end diff --git a/spec/acceptance/suites/compliance/20_stig_profile_install_spec.rb b/spec/acceptance/suites/compliance/20_stig_profile_install_spec.rb index 28742d0a..85de0d45 100644 --- a/spec/acceptance/suites/compliance/20_stig_profile_install_spec.rb +++ b/spec/acceptance/suites/compliance/20_stig_profile_install_spec.rb @@ -3,14 +3,14 @@ test_name 'auditd STIG enforcement of stig profile' describe 'auditd STIG enforcement of stig profile' do - - let(:manifest) { + let(:manifest) do <<-EOS include 'auditd' EOS - } + end - let(:hieradata) { <<-EOF + let(:hieradata) do + <<-EOF --- simp_options::pki: true simp_options::pki::source: '/etc/pki/simp-testing/pki' @@ -26,11 +26,11 @@ auditd::config::audit_profiles::stig::suid_sgid_cmds: - '/usr/bin/screen' EOF - } + end hosts.each do |host| - - let(:hiera_yaml) { <<-EOM + let(:hiera_yaml) do + <<-EOM --- version: 5 hierarchy: @@ -42,31 +42,31 @@ data_hash: yaml_data datadir: "#{hiera_datadir(host)}" EOM - } + end context 'when enforcing the STIG' do - it 'should work with no errors' do + it 'works with no errors' do create_remote_file(host, host.puppet['hiera_config'], hiera_yaml) # Be sure to use write_hieradata_to() and not set_hieradata_on() # or you will lose the hiera config from hiera_yaml write_hieradata_to(host, hieradata) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should reboot to fully apply' do + it 'reboots to fully apply' do host.reboot end # Some versions of auditd leave a backup rules file in place when they # recompile. This is caught by our 'purge' setting in the directory # management and will cause subsequent activity. - it 'will apply to cleanup' do - apply_manifest_on(host, manifest, :catch_failures => true) + it 'applies to cleanup' do + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be idempotent' do - apply_manifest_on(host, manifest, :catch_changes => true) + it 'is idempotent' do + apply_manifest_on(host, manifest, catch_changes: true) end end end diff --git a/spec/acceptance/suites/compliance/21_stig_profile_inspec_spec.rb b/spec/acceptance/suites/compliance/21_stig_profile_inspec_spec.rb index 7f8fd781..45fdac6a 100644 --- a/spec/acceptance/suites/compliance/21_stig_profile_inspec_spec.rb +++ b/spec/acceptance/suites/compliance/21_stig_profile_inspec_spec.rb @@ -4,7 +4,6 @@ test_name 'Check Inspec for stig profile' describe 'run inspec against the appropriate fixtures for stig audit profile' do - profiles_to_validate = ['disa_stig'] hosts.each do |host| @@ -14,38 +13,34 @@ profile_path = File.join( fixtures_path, 'inspec_profiles', - "#{fact_on(host, 'os.name')}-#{fact_on(host, 'os.release.major')}-#{profile}" + "#{fact_on(host, 'os.name')}-#{fact_on(host, 'os.release.major')}-#{profile}", ) - unless File.exist?(profile_path) - it 'should run inspec' do - skip("No matching profile available at #{profile_path}") - end - else + if File.exist?(profile_path) before(:all) do @inspec = Simp::BeakerHelpers::Inspec.new(host, profile) # If we don't do this, the variable gets reset - @inspec_report = { :data => nil } + @inspec_report = { data: nil } end - it 'should run inspec' do + it 'runs inspec' do @inspec.run end - it 'should have an inspec report' do + it 'has an inspec report' do @inspec_report[:data] = @inspec.process_inspec_results - expect(@inspec_report[:data]).to_not be_nil + expect(@inspec_report[:data]).not_to be_nil @inspec.write_report(@inspec_report[:data]) end - it 'should have run some tests' do + it 'has run some tests' do expect(@inspec_report[:data][:failed] + @inspec_report[:data][:passed]).to be > 0 end - it 'should not have any failing tests' do + it 'does not have any failing tests' do # 1 test erroneously fails # - 'The system must send rsyslog output to a log aggregation server': # - inspec_profiles/profiles/disa_stig-el7-baseline/controls/V-72209.rb @@ -55,7 +50,11 @@ puts @inspec_report[:data][:report] end - expect(@inspec_report[:data][:score] ).to eq(100) + expect(@inspec_report[:data][:score]).to eq(100) + end + else + it 'runs inspec' do + skip("No matching profile available at #{profile_path}") end end end diff --git a/spec/acceptance/suites/compliance/22_stig_profile_oscap_spec.rb b/spec/acceptance/suites/compliance/22_stig_profile_oscap_spec.rb index c1e045ea..6291acc2 100644 --- a/spec/acceptance/suites/compliance/22_stig_profile_oscap_spec.rb +++ b/spec/acceptance/suites/compliance/22_stig_profile_oscap_spec.rb @@ -3,23 +3,22 @@ test_name 'Check SCAP for stig profile' describe 'run the SSG against the appropriate fixtures for stig audit profile' do - hosts.each do |host| context "on #{host}" do before(:all) do @ssg = Simp::BeakerHelpers::SSG.new(host) # If we don't do this, the variable gets reset - @ssg_report = { :data => nil } + @ssg_report = { data: nil } end - it 'should run the SSG' do + it 'runs the SSG' do profile = 'xccdf_org.ssgproject.content_profile_stig' @ssg.evaluate(profile) end - it 'should have an SSG report' do + it 'has an SSG report' do # Filter on records containing '_rule_audit' # This isn't perfect, but it should be partially OK filter = '_rule_audit' @@ -43,21 +42,21 @@ # Dragged in by EL8 but we're not applying an OSPP profile 'audit_rules_for_ospp', # We do this using lname and the 'user' setting - 'auditd_name_format' + 'auditd_name_format', ] @ssg_report[:data] = @ssg.process_ssg_results(filter, exclusions) - expect(@ssg_report[:data]).to_not be_nil + expect(@ssg_report[:data]).not_to be_nil @ssg.write_report(@ssg_report[:data]) end - it 'should have run some tests' do + it 'has run some tests' do expect(@ssg_report[:data][:failed].count + @ssg_report[:data][:passed].count).to be > 0 end - it 'should not have any failing tests' do + it 'does not have any failing tests' do if @ssg_report[:data][:failed].count > 0 puts @ssg_report[:data][:report] end diff --git a/spec/acceptance/suites/default/00_base_spec.rb b/spec/acceptance/suites/default/00_base_spec.rb index 80e43a2b..2dfe9a78 100644 --- a/spec/acceptance/suites/default/00_base_spec.rb +++ b/spec/acceptance/suites/default/00_base_spec.rb @@ -5,95 +5,95 @@ describe 'auditd class with simp audit profile' do require_relative('lib/util') - let(:hieradata) { + let(:hieradata) do { 'simp_options::syslog' => true, - 'pki::cacerts_sources' => ['file:///etc/pki/simp-testing/pki/cacerts'] , - 'pki::private_key_source' => "file:///etc/pki/simp-testing/pki/private/%{facts.networking.fqdn}.pem", - 'pki::public_key_source' => "file:///etc/pki/simp-testing/pki/public/%{facts.networking.fqdn}.pub", + 'pki::cacerts_sources' => ['file:///etc/pki/simp-testing/pki/cacerts'], + 'pki::private_key_source' => 'file:///etc/pki/simp-testing/pki/private/%{facts.networking.fqdn}.pem', + 'pki::public_key_source' => 'file:///etc/pki/simp-testing/pki/public/%{facts.networking.fqdn}.pub', 'rsyslog::config::main_msg_queue_size' => 4321, } - } + end - let(:enable_audit_messages) { + let(:enable_audit_messages) do { 'auditd::syslog' => true, 'auditd::config::audisp::syslog::enable' => true, 'auditd::config::audisp::syslog::drop_audit_logs' => false, 'auditd::config::audisp::syslog::priority' => 'LOG_NOTICE' }.merge(hieradata) - } + end - let(:disable_audit_messages) { + let(:disable_audit_messages) do { 'auditd::config::audisp::syslog::enable' => false, 'auditd::config::audisp::syslog::syslog_priority' => 'LOG_NOTICE', 'auditd::syslog' => true }.merge(hieradata) - } + end - let(:manifest) { + let(:manifest) do <<-EOS class { 'auditd': } EOS - } + end hosts.each do |host| context "on #{host}" do context 'default parameters' do - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, hieradata) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should require reboot on subsequent run' do - result = apply_manifest_on(host, manifest, :catch_failures => true) + it 'requires reboot on subsequent run' do + result = apply_manifest_on(host, manifest, catch_failures: true) expect(result.output).to include('audit => modified') # Reboot to enable auditing in the kernel host.reboot end - it 'should be idempotent' do - apply_manifest_on(host, manifest, :catch_changes => true) + it 'is idempotent' do + apply_manifest_on(host, manifest, catch_changes: true) end - it 'should have kernel-level audit enabled on reboot' do + it 'has kernel-level audit enabled on reboot' do on(host, 'grep "audit=1" /proc/cmdline') end - it 'should have the audit package installed' do + it 'has the audit package installed' do result = YAML.safe_load(on(host, 'puppet resource package audit --to_yaml').stdout) expect(result['package']['audit']['ensure']).not_to eq('absent') end - it 'should activate the auditd service' do + it 'activates the auditd service' do result = YAML.safe_load(on(host, 'puppet resource service auditd --to_yaml').stdout) expect(result['service']['auditd']['ensure']).to eq('running') expect(result['service']['auditd']['enable']).to eq('true') end - it 'should load valid rules' do + it 'loads valid rules' do results = AuditdTestUtil::AuditdRules.new(host) - expect(results.rules).to_not be_empty + expect(results.rules).not_to be_empty expect(results.warnings).to eq([]) expect(results.errors).to eq([]) end - it 'should not send audit logs to syslog' do + it 'does not send audit logs to syslog' do # log rotate so any audit messages present before the apply turned off # audit record logging are no longer in /var/log/secure on(host, 'logrotate --force /etc/logrotate.d/syslog; service rsyslog restart; sleep 2') # cause an auditable event - on(host,'useradd thing1') + on(host, 'useradd thing1') on(host, %q(grep -qe 'acct="thing1".*exe="/usr/sbin/useradd"' /var/log/audit/audit.log)) - on(host, %q(grep -qe 'audispd.*msg=audit' /var/log/secure), :acceptable_exit_codes => [1,2]) + on(host, "grep -qe 'audispd.*msg=audit' /var/log/secure", acceptable_exit_codes: [1, 2]) end - it 'should fix incorrect permissions' do + it 'fixes incorrect permissions' do on(host, 'chmod 666 /var/log/audit/audit.log') - apply_manifest_on(host, manifest, :catch_failures => true) - result = on(host, "/bin/find /var/log/audit/audit.log -perm 0600") + apply_manifest_on(host, manifest, catch_failures: true) + result = on(host, '/bin/find /var/log/audit/audit.log -perm 0600') expect(result.output).to include('/var/log/audit/audit.log') end end @@ -101,26 +101,26 @@ class { 'auditd': } context 'allowing audit syslog messages' do result = on(host, 'rpm -q --qf "%{VERSION}\n" audit') audit_version = result.stdout - audit_major_version = audit_version.split(".")[0].to_i + audit_major_version = audit_version.split('.')[0].to_i - if audit_major_version < 3 - dispatcher = 'audispd' - else - dispatcher = 'audisp-syslog' - end + dispatcher = if audit_major_version < 3 + 'audispd' + else + 'audisp-syslog' + end - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, enable_audit_messages) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be running the audit dispatcher' do + it 'is running the audit dispatcher' do on(host, "pgrep #{dispatcher}") end - it 'should have audit.rules has been generated with SIMP rules' do + it 'has audit.rules has been generated with SIMP rules' do # spot check that audit.rules has been generated with SIMP rules - on(host, %q(grep -qe '^-c$' /etc/audit/audit.rules)) + on(host, "grep -qe '^-c$' /etc/audit/audit.rules") on(host, %q(grep -qe '\-a never,exit \-F auid=-1' /etc/audit/audit.rules)) on(host, %q(grep -qe '\-a always,exit \-F perm=a \-F exit=-EACCES \-k access' /etc/audit/audit.rules)) on(host, %q(grep -qe '\-w /var/log/audit -p wa \-k audit-logs' /etc/audit/audit.rules)) @@ -129,42 +129,42 @@ class { 'auditd': } # - Implicit '-S all' is included in '-a' rules without a '-S' option # - '-a' arguments are reordered to have action,list instead of list,action. # - '-k keyname' arguments are expanded to '-F key=keyname' for '-a' rules - result = on(host, "auditctl -l") + result = on(host, 'auditctl -l') expect(result.output).to include('-a never,exit -S all -F auid=-1') expect(result.output).to include('-a always,exit -S all -F perm=a -F exit=-EACCES -F key=access') # On El6 it adds / to the end of directories but not on later versions. - expect(result.output).to match(/-w \/var\/log\/audit[\/]* \-p wa \-k audit\-logs/) + expect(result.output).to match(%r{-w /var/log/audit[/]* \-p wa \-k audit\-logs}) end - it 'should send audit logs to syslog' do + it 'sends audit logs to syslog' do on(host, 'logrotate --force /etc/logrotate.d/syslog') # cause an auditable event and verify it is logged # log rotate so any audit messages present before the apply turned off # audit record logging are no longer in /var/log/secure - on(host,'useradd thing2') + on(host, 'useradd thing2') on(host, %q(grep -qe 'acct="thing2".*exe="/usr/sbin/useradd"' /var/log/audit/audit.log)) on(host, %q(grep -qe 'audispd.*type=SYSCALL msg=audit.*comm="useradd.*key="audit_account_changes"' /var/log/secure)) end - it 'should restart the dispatcher if killed' do + it 'restarts the dispatcher if killed' do on(host, "pkill #{dispatcher}") - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) on(host, "pgrep #{dispatcher}") end end context 'disable audit syslog messages' do - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, disable_audit_messages) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should not be logging messages to syslog' do + it 'is not logging messages to syslog' do # log rotate so any audit messages present before the apply turned off # audit record logging are no longer in /var/log/secure on(host, 'logrotate --force /etc/logrotate.d/syslog') - on(host,'useradd notathing') - on(host, %q(grep -qe 'audispd.*acct="notathing"' /var/log/secure), :acceptable_exit_codes => [1,2]) + on(host, 'useradd notathing') + on(host, %q(grep -qe 'audispd.*acct="notathing"' /var/log/secure), acceptable_exit_codes: [1, 2]) on(host, %q(grep -qe 'acct="notathing".*exe="/usr/sbin/useradd"' /var/log/audit/audit.log)) end end diff --git a/spec/acceptance/suites/default/10_alt_audit_profiles_spec.rb b/spec/acceptance/suites/default/10_alt_audit_profiles_spec.rb index 52d11603..4a90b925 100644 --- a/spec/acceptance/suites/default/10_alt_audit_profiles_spec.rb +++ b/spec/acceptance/suites/default/10_alt_audit_profiles_spec.rb @@ -9,146 +9,142 @@ describe 'auditd class with alternative audit profiles' do require_relative('lib/util') - let(:hieradata) { + let(:hieradata) do { - 'pki::cacerts_sources' => ['file:///etc/pki/simp-testing/pki/cacerts'] , - 'pki::private_key_source' => "file:///etc/pki/simp-testing/pki/private/%{facts.networking.fqdn}.pem", - 'pki::public_key_source' => "file:///etc/pki/simp-testing/pki/public/%{facts.networking.fqdn}.pub", + 'pki::cacerts_sources' => ['file:///etc/pki/simp-testing/pki/cacerts'], + 'pki::private_key_source' => 'file:///etc/pki/simp-testing/pki/private/%{facts.networking.fqdn}.pem', + 'pki::public_key_source' => 'file:///etc/pki/simp-testing/pki/public/%{facts.networking.fqdn}.pub', } - } + end - let(:simp_profile_aggressive) { + let(:simp_profile_aggressive) do { 'auditd::root_audit_level' => 'aggressive', }.merge(hieradata) - } + end - let(:simp_profile_insane_enable_optional) { + let(:simp_profile_insane_enable_optional) do { 'auditd::root_audit_level' => 'insane', 'auditd::config::audit_profiles::simp::audit_chmod' => true, - 'auditd::config::audit_profiles::simp::audit_rename_remove'=> true, + 'auditd::config::audit_profiles::simp::audit_rename_remove' => true, 'auditd::config::audit_profiles::simp::audit_umask' => true, 'auditd::config::audit_profiles::simp::audit_selinux_cmds' => true, 'auditd::config::audit_profiles::simp::audit_yum_cmd' => true, 'auditd::config::audit_profiles::simp::audit_rpm_cmd' => true, }.merge(hieradata) - } + end - let(:stig_profile) { + let(:stig_profile) do { 'auditd::default_audit_profiles' => [ 'stig' ] }.merge(hieradata) - } + end - let(:simp_plus_stig_profiles) { + let(:simp_plus_stig_profiles) do { 'auditd::default_audit_profiles' => [ 'simp', 'stig' ] }.merge(hieradata) - } + end - let(:manifest) { + let(:manifest) do <<-EOS class { 'auditd': } EOS - } + end hosts.each do |host| context "on #{host}" do - context 'with simp profile, aggressive su-root auditing ' do - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, simp_profile_aggressive) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be running the auditd service' do + it 'is running the auditd service' do result = YAML.safe_load(on(host, 'puppet resource service auditd --to_yaml').stdout) expect(result['service']['auditd']['ensure']).to eq('running') end - it 'should load valid rules' do + it 'loads valid rules' do # make sure the rules have been regenerated # (search for rule only contained in new rule set) retry_on(host, 'grep execve /etc/audit/audit.rules | grep renameat', - { :max_retries => 30, :verbose => true }) + { max_retries: 30, verbose: true }) results = AuditdTestUtil::AuditdRules.new(host) - expect(results.rules).to_not be_empty + expect(results.rules).not_to be_empty expect(results.warnings).to eq([]) expect(results.errors).to eq([]) end end context 'with simp profile, insane su-root auditing, all optional auditing enabled' do - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, simp_profile_insane_enable_optional) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be running the auditd service' do + it 'is running the auditd service' do result = YAML.safe_load(on(host, 'puppet resource service auditd --to_yaml').stdout) expect(result['service']['auditd']['ensure']).to eq('running') end - - it 'should load valid rules' do + it 'loads valid rules' do # make sure the rules have been regenerated # (search for tag only contained in new rule set) retry_on(host, 'grep package_changes /etc/audit/audit.rules', - { :max_retries => 30, :verbose => true }) - + { max_retries: 30, verbose: true }) results = AuditdTestUtil::AuditdRules.new(host) - expect(results.rules).to_not be_empty + expect(results.rules).not_to be_empty expect(results.warnings).to eq([]) expect(results.errors).to eq([]) end end context 'with stig audit profile with default parameters' do - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, stig_profile) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be running the auditd service' do + it 'is running the auditd service' do result = YAML.safe_load(on(host, 'puppet resource service auditd --to_yaml').stdout) expect(result['service']['auditd']['ensure']).to eq('running') end - it 'should load valid rules' do + it 'loads valid rules' do # make sure the rules have been regenerated # (search for tag only contained in new rule set) retry_on(host, 'cat /etc/audit/audit.rules | grep identity', - { :max_retries => 30, :verbose => true }) - + { max_retries: 30, verbose: true }) results = AuditdTestUtil::AuditdRules.new(host) - expect(results.rules).to_not be_empty + expect(results.rules).not_to be_empty expect(results.warnings).to eq([]) expect(results.errors).to eq([]) end end context 'with simp + stig audit profiles, both with default parameters' do - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, simp_plus_stig_profiles) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should load valid rules' do + it 'loads valid rules' do # make sure the rules have been regenerated # (search for tag only contained in new rule set) retry_on(host, 'cat /etc/audit/audit.rules | grep su-root-activity', - { :max_retries => 30, :verbose => true }) + { max_retries: 30, verbose: true }) results = AuditdTestUtil::AuditdRules.new(host) - expect(results.rules).to_not be_empty + expect(results.rules).not_to be_empty expect(results.warnings).to eq([]) expect(results.errors).to eq([]) end diff --git a/spec/acceptance/suites/default/20_built_in_audit_profile_spec.rb b/spec/acceptance/suites/default/20_built_in_audit_profile_spec.rb index afa18288..30432bd2 100644 --- a/spec/acceptance/suites/default/20_built_in_audit_profile_spec.rb +++ b/spec/acceptance/suites/default/20_built_in_audit_profile_spec.rb @@ -9,15 +9,15 @@ describe 'auditd class with sample rulesets' do require_relative('lib/util') - let(:hieradata) { + let(:hieradata) do { - 'pki::cacerts_sources' => ['file:///etc/pki/simp-testing/pki/cacerts'] , - 'pki::private_key_source' => "file:///etc/pki/simp-testing/pki/private/%{facts.networking.fqdn}.pem", - 'pki::public_key_source' => "file:///etc/pki/simp-testing/pki/public/%{facts.networking.fqdn}.pub", + 'pki::cacerts_sources' => ['file:///etc/pki/simp-testing/pki/cacerts'], + 'pki::private_key_source' => 'file:///etc/pki/simp-testing/pki/private/%{facts.networking.fqdn}.pem', + 'pki::public_key_source' => 'file:///etc/pki/simp-testing/pki/public/%{facts.networking.fqdn}.pub', } - } + end - let(:enable_stig_sample_rulesets) { + let(:enable_stig_sample_rulesets) do { 'auditd::default_audit_profiles' => [ 'built_in', @@ -28,9 +28,9 @@ 'finalize', ], }.merge(hieradata) - } + end - let(:multiple_profiles) { + let(:multiple_profiles) do { 'auditd::default_audit_profiles' => [ 'built_in', @@ -42,9 +42,9 @@ 'finalize', ], } - } + end - let(:enable_ospp_rulesets) { + let(:enable_ospp_rulesets) do { 'auditd::default_audit_profiles' => [ 'built_in', @@ -67,130 +67,125 @@ 'ospp-v42', ], } - } + end - let(:enable_privileged_ruleset) { + let(:enable_privileged_ruleset) do { 'auditd::default_audit_profiles' => [ 'built_in', ], 'auditd::config::audit_profiles::built_in::rulesets' => [ - 'privileged' + 'privileged', ], }.merge(hieradata) - } + end - let(:manifest) { + let(:manifest) do <<-EOS class { 'auditd': } EOS - } + end hosts_with_role(hosts, 'el8').each do |host| # Ensure audit is at latest, since this will not test anything if not upgrade_package(host, 'audit') context "on #{host}" do - context 'with stig profile from sample rulesets' do - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, enable_stig_sample_rulesets) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be running the auditd service' do + it 'is running the auditd service' do result = YAML.safe_load(on(host, 'puppet resource service auditd --to_yaml').stdout) expect(result['service']['auditd']['ensure']).to eq('running') end - it 'should load valid rules' do + it 'loads valid rules' do # make sure the rules have been regenerated # (search for rule only contained in new rule set) retry_on(host, 'grep renameat /etc/audit/audit.rules | grep delete', - { :max_retries => 30, :verbose => true }) + { max_retries: 30, verbose: true }) results = AuditdTestUtil::AuditdRules.new(host) - expect(results.rules).to_not be_empty + expect(results.rules).not_to be_empty expect(results.warnings).to eq([]) expect(results.errors).to eq([]) end end context 'with ospp enabled from sample rulesets' do - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, enable_ospp_rulesets) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be running the auditd service' do + it 'is running the auditd service' do result = YAML.safe_load(on(host, 'puppet resource service auditd --to_yaml').stdout) expect(result['service']['auditd']['ensure']).to eq('running') end - - it 'should load valid rules' do + it 'loads valid rules' do # make sure the rules have been regenerated # (search for tag only contained in new rule set) retry_on(host, 'grep selinux /etc/audit/audit.rules | grep MAC-policy', - { :max_retries => 30, :verbose => true }) - + { max_retries: 30, verbose: true }) results = AuditdTestUtil::AuditdRules.new(host) - expect(results.rules).to_not be_empty + expect(results.rules).not_to be_empty expect(results.warnings).to eq([]) expect(results.errors).to eq([]) end end context 'with privileged sample ruleset' do - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, enable_privileged_ruleset) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be running the auditd service' do + it 'is running the auditd service' do result = YAML.safe_load(on(host, 'puppet resource service auditd --to_yaml').stdout) expect(result['service']['auditd']['ensure']).to eq('running') end - - it 'should load valid rules' do + it 'loads valid rules' do # make sure the rules have been regenerated # (search for tag only contained in new rule set) retry_on(host, 'grep umount /etc/audit/audit.rules | grep privileged', - { :max_retries => 30, :verbose => true }) - + { max_retries: 30, verbose: true }) results = AuditdTestUtil::AuditdRules.new(host) - expect(results.rules).to_not be_empty + expect(results.rules).not_to be_empty expect(results.warnings).to eq([]) expect(results.errors).to eq([]) end end context 'with built_in and simp profiles' do - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, multiple_profiles) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be running the auditd service' do + it 'is running the auditd service' do result = YAML.safe_load(on(host, 'puppet resource service auditd --to_yaml').stdout) expect(result['service']['auditd']['ensure']).to eq('running') end - it 'should load valid rules' do + it 'loads valid rules' do # make sure the rules have been regenerated # (search for rule only contained in new rule set) retry_on(host, 'grep renameat /etc/audit/audit.rules | grep delete', - { :max_retries => 30, :verbose => true }) + { max_retries: 30, verbose: true }) results = AuditdTestUtil::AuditdRules.new(host) - expect(results.rules).to_not be_empty + expect(results.rules).not_to be_empty expect(results.warnings).to eq([]) expect(results.errors).to eq([]) end diff --git a/spec/acceptance/suites/default/90_disable_audit_spec.rb b/spec/acceptance/suites/default/90_disable_audit_spec.rb index 1fe231aa..e22dbd65 100644 --- a/spec/acceptance/suites/default/90_disable_audit_spec.rb +++ b/spec/acceptance/suites/default/90_disable_audit_spec.rb @@ -4,18 +4,18 @@ test_name 'disabling auditing via auditd class' describe 'auditd class with simp auditd profile' do - let(:enable_hieradata) { - YAML.load <<~HIERA + let(:enable_hieradata) do + YAML.safe_load <<~HIERA --- pki::cacerts_sources: - 'file:///etc/pki/simp-testing/pki/cacerts' pki::private_key_source: 'file:///etc/pki/simp-testing/pki/private/%{facts.networking.fqdn}.pem' pki::public_key_source: 'file:///etc/pki/simp-testing/pki/public/%{facts.networking.fqdn}.pub' HIERA - } + end - let(:disable_hieradata) { - YAML.load <<~HIERA + let(:disable_hieradata) do + YAML.safe_load <<~HIERA --- pki::cacerts_sources: - 'file:///etc/pki/simp-testing/pki/cacerts' @@ -23,50 +23,49 @@ pki::public_key_source: 'file:///etc/pki/simp-testing/pki/public/%{facts.networking.fqdn}.pub' auditd::enable: false HIERA - } + end - let(:manifest) { + let(:manifest) do <<-EOS class { 'auditd': } EOS - } + end hosts.each do |host| context "on #{host}" do context 'ensure that auditing is enabled' do - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, enable_hieradata) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) host.reboot end end context 'disabling auditd' do - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, disable_hieradata) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should kill the auditd service' do + it 'kills the auditd service' do result = YAML.safe_load(on(host, 'puppet resource service auditd --to_yaml').stdout) expect(result['service']['auditd']['ensure']).to eq('stopped') expect(result['service']['auditd']['enable']).to eq('false') end - it 'should require reboot on subsequent run' do - result = apply_manifest_on(host, manifest, :catch_failures => true) + it 'requires reboot on subsequent run' do + result = apply_manifest_on(host, manifest, catch_failures: true) expect(result.output).to include('audit => modified') # Reboot to disable auditing in the kernel host.reboot end - it 'should have kernel-level audit disabled on reboot' do + it 'has kernel-level audit disabled on reboot' do retry_on(host, 'grep "audit=0" /proc/cmdline', - { :max_retries => 30, :verbose => true } - ) + { max_retries: 30, verbose: true }) end end end diff --git a/spec/acceptance/suites/default/99_disable_audit_kernel_spec.rb b/spec/acceptance/suites/default/99_disable_audit_kernel_spec.rb index fcc70501..8b760804 100644 --- a/spec/acceptance/suites/default/99_disable_audit_kernel_spec.rb +++ b/spec/acceptance/suites/default/99_disable_audit_kernel_spec.rb @@ -1,73 +1,71 @@ require 'spec_helper_acceptance' - # This set of tests should be last, so that we don't have to # reboot the servers to get manifests to apply fully. # test_name 'disabling kernel auditing via auditd class' describe 'auditd class with simp auditd profile' do - let(:enable_hieradata) { + let(:enable_hieradata) do { - 'pki::cacerts_sources' => ['file:///etc/pki/simp-testing/pki/cacerts'] , - 'pki::private_key_source' => "file:///etc/pki/simp-testing/pki/private/%{facts.networking.fqdn}.pem", - 'pki::public_key_source' => "file:///etc/pki/simp-testing/pki/public/%{facts.networking.fqdn}.pub", + 'pki::cacerts_sources' => ['file:///etc/pki/simp-testing/pki/cacerts'], + 'pki::private_key_source' => 'file:///etc/pki/simp-testing/pki/private/%{facts.networking.fqdn}.pem', + 'pki::public_key_source' => 'file:///etc/pki/simp-testing/pki/public/%{facts.networking.fqdn}.pub', } - } + end - let(:disable_hieradata) { + let(:disable_hieradata) do { - 'pki::cacerts_sources' => ['file:///etc/pki/simp-testing/pki/cacerts'] , - 'pki::private_key_source' => "file:///etc/pki/simp-testing/pki/private/%{facts.networking.fqdn}.pem", - 'pki::public_key_source' => "file:///etc/pki/simp-testing/pki/public/%{facts.networking.fqdn}.pub", + 'pki::cacerts_sources' => ['file:///etc/pki/simp-testing/pki/cacerts'], + 'pki::private_key_source' => 'file:///etc/pki/simp-testing/pki/private/%{facts.networking.fqdn}.pem', + 'pki::public_key_source' => 'file:///etc/pki/simp-testing/pki/public/%{facts.networking.fqdn}.pub', 'auditd::at_boot' => false } - } + end - let(:manifest) { + let(:manifest) do <<-EOS class { 'auditd': } EOS - } + end hosts.each do |host| context "on #{host}" do context 'ensure that auditing is enabled' do - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, enable_hieradata) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) host.reboot end end context 'disabling auditd at the kernel level' do - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, disable_hieradata) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - # Note: In SIMP, svckill will take care of actually disabling auditd if + # NOTE: In SIMP, svckill will take care of actually disabling auditd if # it is no longer managed. Here, we're not including svckill by default. - it 'should not kill the auditd service' do + it 'does not kill the auditd service' do result = YAML.safe_load(on(host, 'puppet resource service auditd --to_yaml').stdout) expect(result['service']['auditd']['ensure']).to eq('running') expect(result['service']['auditd']['enable']).to eq('true') end - it 'should require reboot on subsequent run' do - result = apply_manifest_on(host, manifest, :catch_failures => true) + it 'requires reboot on subsequent run' do + result = apply_manifest_on(host, manifest, catch_failures: true) expect(result.output).to include('audit => modified') # Reboot to disable auditing in the kernel host.reboot end - it 'should have kernel-level audit disabled on reboot' do + it 'has kernel-level audit disabled on reboot' do retry_on(host, 'grep "audit=0" /proc/cmdline', - { :max_retries => 30, :verbose => true } - ) + { max_retries: 30, verbose: true }) end end end diff --git a/spec/acceptance/suites/default/auditd_sample_ruleset_location_fact_spec.rb b/spec/acceptance/suites/default/auditd_sample_ruleset_location_fact_spec.rb index df58a4d7..72ce7edd 100644 --- a/spec/acceptance/suites/default/auditd_sample_ruleset_location_fact_spec.rb +++ b/spec/acceptance/suites/default/auditd_sample_ruleset_location_fact_spec.rb @@ -3,12 +3,11 @@ test_name 'auditd_sample_ruleset_location fact' describe 'auditd_sample_ruleset_location fact' do - hosts.each do |host| it 'Auditd sample ruleset location should be gathered' do fact_info = pfact_on(host, 'auditd_sample_ruleset_location') - expect(fact_info).to match(/\/usr\/share\/(doc\/)*audit(-*\d*.\d*.\d*)*\/(sample-)*rules/) + expect(fact_info).to match(%r{/usr/share/(doc/)*audit(-*\d*.\d*.\d*)*/(sample-)*rules}) end end -end \ No newline at end of file +end diff --git a/spec/acceptance/suites/default/lib/util.rb b/spec/acceptance/suites/default/lib/util.rb index 3671f310..8885a66b 100644 --- a/spec/acceptance/suites/default/lib/util.rb +++ b/spec/acceptance/suites/default/lib/util.rb @@ -1,113 +1,109 @@ -module AuditdTestUtil - # An object that holds the assessment of a given nodes ruleset - class AuditdRules - RULE_IGNORE_LIST = [ - # Ignore anything with a 'path' entry since those may not exist on the - # target system. - %r{path=}, - # Ignore all file watches since the files may not exist - %r{^-w}, - # Ignore any uid or gid watches where the user is not root or 0 since the - # user may not exist - %r{(uid|gid)=(?!rot|0)} - ] - - # @return [Array[String]] - # The rules found on the system after filtering - attr_reader :rules - - # @return [Array[String]] - # The rules found on the system before filtering - attr_reader :system_rules - - # @return [Array[String]] - # Warnings found in the system rules - attr_reader :warnings - - # @return [Array[String]] - # Errors found in the system rules - attr_reader :errors - - # @param host [Beaker::Host] - # The host to operate on - # - # @param ignore [Array[Regexp]] - # Regular expressions that denote invalid rules - def initialize(host, ignore = RULE_IGNORE_LIST) - @rules = [] - @warnings = [] - @errors = [] - @system_rules = on(host,'cat /etc/audit/audit.rules').stdout.lines.map(&:strip) - - if @system_rules.grep(/no rules/i).empty? - require 'securerandom' - - @rules = @system_rules.dup - @rules.delete_if do |rule| - ignore.any? do |regexp| - regexp.match?(rule) - end - end +# An object that holds the assessment of a given nodes ruleset +class AuditdTestUtil::AuditdRules + RULE_IGNORE_LIST = [ + # Ignore anything with a 'path' entry since those may not exist on the + # target system. + %r{path=}, + # Ignore all file watches since the files may not exist + %r{^-w}, + # Ignore any uid or gid watches where the user is not root or 0 since the + # user may not exist + %r{(uid|gid)=(?!rot|0)}, + ].freeze + + # @return [Array[String]] + # The rules found on the system after filtering + attr_reader :rules + + # @return [Array[String]] + # The rules found on the system before filtering + attr_reader :system_rules + + # @return [Array[String]] + # Warnings found in the system rules + attr_reader :warnings + + # @return [Array[String]] + # Errors found in the system rules + attr_reader :errors + + # @param host [Beaker::Host] + # The host to operate on + # + # @param ignore [Array[Regexp]] + # Regular expressions that denote invalid rules + def initialize(host, ignore = RULE_IGNORE_LIST) + @rules = [] + @warnings = [] + @errors = [] + @system_rules = on(host, 'cat /etc/audit/audit.rules').stdout.lines.map(&:strip) + + return unless @system_rules.grep(%r{no rules}i).empty? + require 'securerandom' + + @rules = @system_rules.dup + @rules.delete_if do |rule| + ignore.any? do |regexp| + regexp.match?(rule) + end + end - tempname = '/tmp/auditd-' + SecureRandom.uuid+ '.rules' + tempname = '/tmp/auditd-' + SecureRandom.uuid + '.rules' - create_remote_file(host, tempname, ['-c', @rules].flatten.join("\n")) - on(host, "chmod 600 #{tempname}") + create_remote_file(host, tempname, ['-c', @rules].flatten.join("\n")) + on(host, "chmod 600 #{tempname}") - auditctl_output = on(host, - "auditctl -R #{tempname}", - :accept_all_exit_codes => true - ).output.lines.map(&:strip) + auditctl_output = on(host, + "auditctl -R #{tempname}", + accept_all_exit_codes: true).output.lines.map(&:strip) + error_found = false + auditctl_output.each_with_index do |line, i| + if error_found error_found = false - auditctl_output.each_with_index do |line, i| - if error_found - error_found = false - next - end + next + end - next_line = auditctl_output[i+1] + next_line = auditctl_output[i + 1] - if line =~ /^error/i - # The error line number is in the next line down - if next_line =~ /(line \d+)/ - @errors << line + ': ' + $1 + if %r{^error}i.match?(line) + # The error line number is in the next line down + if next_line =~ %r{(line \d+)} + @errors << line + ': ' + ::Regexp.last_match(1) - error_found = true - end + error_found = true + end - next - end + next + end - if line =~ /^warning/i - @warnings << line - end - end + if %r{^warning}i.match?(line) + @warnings << line end end + end - # Convert the errors and warnings to a well-formatted string - # - # @return [String] - def to_s - output = ['Rule Warnings:'] + # Convert the errors and warnings to a well-formatted string + # + # @return [String] + def to_s + output = ['Rule Warnings:'] - if @warnings.empty? - output << ' * None' - else - output << %{ * #{@warnings.join("\n *")}} - end + output << if @warnings.empty? + ' * None' + else + %( * #{@warnings.join("\n *")}) + end - output << [''] - output << ['Rule Errors:'] + output << [''] + output << ['Rule Errors:'] - if @errors.empty? - output << ' * None' - else - output << %{ * #{@errors.join("\n *")}} - end + output << if @errors.empty? + ' * None' + else + %( * #{@errors.join("\n *")}) + end - output.join("\n") - end + output.join("\n") end end diff --git a/spec/classes/config/audisp/syslog_spec.rb b/spec/classes/config/audisp/syslog_spec.rb index 5ee611da..4a1d7536 100644 --- a/spec/classes/config/audisp/syslog_spec.rb +++ b/spec/classes/config/audisp/syslog_spec.rb @@ -8,22 +8,22 @@ 'include "auditd"' end - #Test if auditd version is not defined that it finds defaults. - #This will be the case first time it is run if auditd is not installed - #already. + # Test if auditd version is not defined that it finds defaults. + # This will be the case first time it is run if auditd is not installed + # already. context 'if auditd version is unknown' do - let(:facts) { os_facts.reject { |k,v| k == :auditd_major_version }} + let(:facts) { os_facts.reject { |k, _v| k == :auditd_major_version } } + it { is_expected.to compile.with_all_deps } end - context 'for all versions of auditd' do - [{ :auditd_version => "3.0", :auditd_major_version => "3"}, { :auditd_version => "2.8.4", :auditd_major_version => "2"}].each do | more_facts | - let(:facts) {os_facts.merge(more_facts)} + [{ auditd_version: '3.0', auditd_major_version: '3' }, { auditd_version: '2.8.4', auditd_major_version: '2' }].each do |more_facts| + let(:facts) { os_facts.merge(more_facts) } context 'without any parameters' do - let(:params) {{ }} - let(:expected_content2){ -< false, - :rsyslog => true, - :facility => 'LOG_LOCAL6', - :priority => 'LOG_NOTICE' - }} - let(:expected_content2) { -< 'warn' - }} - it { is_expected.to_not compile.with_all_deps } + # appropriate priority for /usr/bin/logger, but not audisp + let(:params) do + { + priority: 'warn' + } + end + + it { is_expected.not_to compile.with_all_deps } end context 'when syslog facility is invalid' do # appropriate facility for /usr/bin/logger, but not audisp - let(:params) {{ - :facility => 'local6' - }} - it { is_expected.to_not compile.with_all_deps } + let(:params) do + { + facility: 'local6' + } + end + + it { is_expected.not_to compile.with_all_deps } end end end diff --git a/spec/classes/config/audit_profiles/built_in_spec.rb b/spec/classes/config/audit_profiles/built_in_spec.rb index 8d473ec8..5145fed0 100644 --- a/spec/classes/config/audit_profiles/built_in_spec.rb +++ b/spec/classes/config/audit_profiles/built_in_spec.rb @@ -8,207 +8,202 @@ describe 'auditd' do on_supported_os.each do |os, os_facts| context "on #{os}" do - let(:facts) { + let(:facts) do _facts = Marshal.load(Marshal.dump(os_facts)) - if _facts[:os][:release][:major] < '8' - _facts[:auditd_major_version] = '2' - _facts[:auditd_sample_ruleset_location] = '/usr/share/doc/audit-2.8.5/rules' - _facts[:auditd_sample_rulesets] = { - 'base-config' => { 'order' => 10, }, - 'no-audit' => { 'order' => 10, }, - 'loginuid' => { 'order' => 11, }, - 'stig' => { 'order' => 30, }, - 'privileged' => { 'order' => 31, }, - 'networking' => { 'order' => 71, }, - 'finalize' => { 'order' => 99, }, - } - else - _facts[:auditd_major_version] = '3' - _facts[:auditd_sample_ruleset_location] = '/usr/share/audit/sample-rules' - _facts[:auditd_sample_rulesets] = { - 'base-config' => { 'order' => 10, }, - 'no-audit' => { 'order' => 10, }, - 'loginuid' => { 'order' => 11, }, - 'stig' => { 'order' => 30, }, - 'privileged' => { 'order' => 31, }, - 'networking' => { 'order' => 71, }, - 'finalize' => { 'order' => 99, }, - } - end + if _facts[:os][:release][:major] < '8' + _facts[:auditd_major_version] = '2' + _facts[:auditd_sample_ruleset_location] = '/usr/share/doc/audit-2.8.5/rules' + else + _facts[:auditd_major_version] = '3' + _facts[:auditd_sample_ruleset_location] = '/usr/share/audit/sample-rules' + end + _facts[:auditd_sample_rulesets] = { + 'base-config' => { 'order' => 10, }, + 'no-audit' => { 'order' => 10, }, + 'loginuid' => { 'order' => 11, }, + 'stig' => { 'order' => 30, }, + 'privileged' => { 'order' => 31, }, + 'networking' => { 'order' => 71, }, + 'finalize' => { 'order' => 99, }, + } _facts - } + end context 'with default parameters' do it { is_expected.to compile.with_all_deps } end context 'with non-privileged sample rulesets and one invalid sample' do - let(:params) {{ - :default_audit_profiles => [ - 'built_in' - ] - }} + let(:params) do + { + default_audit_profiles: [ + 'built_in', + ] + } + end let(:hieradata) { 'built_in_audit_profile/random_sample_rulesets' } it { # We should not have the items included in audit_profiles since we are # only defining `built_in` - is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content(%r(^-i$)) - is_expected.to_not contain_file('/etc/audit/rules.d/05_default_drop.rules') - is_expected.to_not contain_file('/etc/audit/rules.d/99_tail.rules') + is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content(%r{^-i$}) + is_expected.not_to contain_file('/etc/audit/rules.d/05_default_drop.rules') + is_expected.not_to contain_file('/etc/audit/rules.d/99_tail.rules') + is_expected.to compile.with_all_deps if facts[:auditd_major_version] == '3' - is_expected.to compile.with_all_deps is_expected.to contain_file('/etc/audit/rules.d/10-base-config.rules').with({ - :ensure => 'file', - :source => 'file:///usr/share/audit/sample-rules/10-base-config.rules', - }).that_notifies('Class[auditd::service]') + ensure: 'file', + source: 'file:///usr/share/audit/sample-rules/10-base-config.rules', + }).that_notifies('Class[auditd::service]') is_expected.to contain_file('/etc/audit/rules.d/10-no-audit.rules').with({ - :ensure => 'file', - :source => 'file:///usr/share/audit/sample-rules/10-no-audit.rules', - }).that_notifies('Class[auditd::service]') + ensure: 'file', + source: 'file:///usr/share/audit/sample-rules/10-no-audit.rules', + }).that_notifies('Class[auditd::service]') is_expected.to contain_file('/etc/audit/rules.d/99-finalize.rules').with({ - :ensure => 'file', - :source => 'file:///usr/share/audit/sample-rules/99-finalize.rules', - }).that_notifies('Class[auditd::service]') + ensure: 'file', + source: 'file:///usr/share/audit/sample-rules/99-finalize.rules', + }).that_notifies('Class[auditd::service]') is_expected.to contain_notify('bad_sample_set not found') else - is_expected.to compile.with_all_deps is_expected.to contain_file('/etc/audit/rules.d/10-base-config.rules').with({ - :ensure => 'file', - :source => 'file:///usr/share/doc/audit-2.8.5/rules/10-base-config.rules', - }).that_notifies('Class[auditd::service]') + ensure: 'file', + source: 'file:///usr/share/doc/audit-2.8.5/rules/10-base-config.rules', + }).that_notifies('Class[auditd::service]') is_expected.to contain_file('/etc/audit/rules.d/10-no-audit.rules').with({ - :ensure => 'file', - :source => 'file:///usr/share/doc/audit-2.8.5/rules/10-no-audit.rules', - }).that_notifies('Class[auditd::service]') + ensure: 'file', + source: 'file:///usr/share/doc/audit-2.8.5/rules/10-no-audit.rules', + }).that_notifies('Class[auditd::service]') is_expected.to contain_file('/etc/audit/rules.d/99-finalize.rules').with({ - :ensure => 'file', - :source => 'file:///usr/share/doc/audit-2.8.5/rules/99-finalize.rules', - }).that_notifies('Class[auditd::service]') + ensure: 'file', + source: 'file:///usr/share/doc/audit-2.8.5/rules/99-finalize.rules', + }).that_notifies('Class[auditd::service]') end } end context 'with privileged sample ruleset' do - let(:params) {{ - :default_audit_profiles => [ - 'built_in' - ], - }} + let(:params) do + { + default_audit_profiles: [ + 'built_in', + ], + } + end let(:hieradata) { 'built_in_audit_profile/privileged_ruleset' } it { # We should not have the items included in audit_profiles since we are # only defining `built_in` - is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content(%r(^-i$)) - is_expected.to_not contain_file('/etc/audit/rules.d/05_default_drop.rules') - is_expected.to_not contain_file('/etc/audit/rules.d/99_tail.rules') + is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content(%r{^-i$}) + is_expected.not_to contain_file('/etc/audit/rules.d/05_default_drop.rules') + is_expected.not_to contain_file('/etc/audit/rules.d/99_tail.rules') + is_expected.to compile.with_all_deps if facts[:auditd_major_version] == '3' - is_expected.to compile.with_all_deps is_expected.to contain_exec('generate_privileged_script').with({ - :command => "sha512sum /usr/share/audit/sample-rules/31-privileged.rules > /usr/share/audit/sample-rules/.31-privileged.rules.sha512 && sed -e 's|^#||' -e 's|>[[:space:]][[:alnum:]]*.rules|> /usr/share/audit/sample-rules/31-privileged.rules.evaluated|' /usr/share/audit/sample-rules/31-privileged.rules > /usr/local/sbin/generate_privileged_audit_sample_rules.sh", - :path => ['/usr/bin', '/usr/sbin', '/bin', '/sbin'], - :unless => [ + command: "sha512sum /usr/share/audit/sample-rules/31-privileged.rules > /usr/share/audit/sample-rules/.31-privileged.rules.sha512 && sed -e 's|^#||' -e 's|>[[:space:]][[:alnum:]]*.rules|> /usr/share/audit/sample-rules/31-privileged.rules.evaluated|' /usr/share/audit/sample-rules/31-privileged.rules > /usr/local/sbin/generate_privileged_audit_sample_rules.sh", + path: ['/usr/bin', '/usr/sbin', '/bin', '/sbin'], + unless: [ 'test -f /usr/share/audit/sample-rules/.31-privileged.rules.sha512', - 'sha512sum -c --status /usr/share/audit/sample-rules/.31-privileged.rules.sha512' + 'sha512sum -c --status /usr/share/audit/sample-rules/.31-privileged.rules.sha512', ], - }).that_notifies('Exec[build_privileged_ruleset]') + }).that_notifies('Exec[build_privileged_ruleset]') is_expected.to contain_exec('build_privileged_ruleset').with({ - :command => '/bin/bash "/usr/local/sbin/generate_privileged_audit_sample_rules.sh"', - :refreshonly => true, - }) + command: '/bin/bash "/usr/local/sbin/generate_privileged_audit_sample_rules.sh"', + refreshonly: true, + }) is_expected.to contain_file('/etc/audit/rules.d/31-privileged.rules').with({ - :ensure => 'file', - :source => 'file:///usr/share/audit/sample-rules/31-privileged.rules.evaluated', - }).that_notifies('Class[auditd::service]').that_requires('Exec[build_privileged_ruleset]') + ensure: 'file', + source: 'file:///usr/share/audit/sample-rules/31-privileged.rules.evaluated', + }).that_notifies('Class[auditd::service]').that_requires('Exec[build_privileged_ruleset]') else - is_expected.to compile.with_all_deps is_expected.to contain_exec('generate_privileged_script').with({ - :command => "sha512sum /usr/share/doc/audit-2.8.5/rules/31-privileged.rules > /usr/share/doc/audit-2.8.5/rules/.31-privileged.rules.sha512 && sed -e 's|^#||' -e 's|>[[:space:]][[:alnum:]]*.rules|> /usr/share/doc/audit-2.8.5/rules/31-privileged.rules.evaluated|' /usr/share/doc/audit-2.8.5/rules/31-privileged.rules > /usr/local/sbin/generate_privileged_audit_sample_rules.sh", - :path => ['/usr/bin', '/usr/sbin', '/bin', '/sbin'], - :unless => [ + command: "sha512sum /usr/share/doc/audit-2.8.5/rules/31-privileged.rules > /usr/share/doc/audit-2.8.5/rules/.31-privileged.rules.sha512 && sed -e 's|^#||' -e 's|>[[:space:]][[:alnum:]]*.rules|> /usr/share/doc/audit-2.8.5/rules/31-privileged.rules.evaluated|' /usr/share/doc/audit-2.8.5/rules/31-privileged.rules > /usr/local/sbin/generate_privileged_audit_sample_rules.sh", + path: ['/usr/bin', '/usr/sbin', '/bin', '/sbin'], + unless: [ 'test -f /usr/share/doc/audit-2.8.5/rules/.31-privileged.rules.sha512', - 'sha512sum -c --status /usr/share/doc/audit-2.8.5/rules/.31-privileged.rules.sha512' + 'sha512sum -c --status /usr/share/doc/audit-2.8.5/rules/.31-privileged.rules.sha512', ], - }).that_notifies('Exec[build_privileged_ruleset]') + }).that_notifies('Exec[build_privileged_ruleset]') is_expected.to contain_exec('build_privileged_ruleset').with({ - :command => '/bin/bash "/usr/local/sbin/generate_privileged_audit_sample_rules.sh"', - :refreshonly => true, - }) + command: '/bin/bash "/usr/local/sbin/generate_privileged_audit_sample_rules.sh"', + refreshonly: true, + }) is_expected.to contain_file('/etc/audit/rules.d/31-privileged.rules').with({ - :ensure => 'file', - :source => 'file:///usr/share/doc/audit-2.8.5/rules/31-privileged.rules.evaluated', - }).that_notifies('Class[auditd::service]').that_requires('Exec[build_privileged_ruleset]') + ensure: 'file', + source: 'file:///usr/share/doc/audit-2.8.5/rules/31-privileged.rules.evaluated', + }).that_notifies('Class[auditd::service]').that_requires('Exec[build_privileged_ruleset]') end } end context 'with additional simp profile and some built_ins' do - let(:params) {{ - :default_audit_profiles => [ - 'built_in', - 'simp', - ] - }} + let(:params) do + { + default_audit_profiles: [ + 'built_in', + 'simp', + ] + } + end let(:hieradata) { 'built_in_audit_profile/random_sample_rulesets' } # auditd::config::audit_profiles validation it { is_expected.to compile.with_all_deps } - it { is_expected.to contain_auditd__rule('audit_auditd_config').with_content( %r(-w /var/log/audit -p wa -k audit-logs)) } + it { is_expected.to contain_auditd__rule('audit_auditd_config').with_content(%r{-w /var/log/audit -p wa -k audit-logs}) } it 'configures auditd to ignore rule failures' do - is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content(%r(^-i$)) - is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content(%r(^-c$)) + is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content(%r{^-i$}) + is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content(%r{^-c$}) end it 'configures buffer size' do is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content( - %r(^-b\s+16384$) + %r{^-b\s+16384$}, ) end it 'configures failure mode' do is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content( - %r(^-f\s+1$) + %r{^-f\s+1$}, ) end it 'configures rate limiting' do is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content( - %r(^-r\s+0$) + %r{^-r\s+0$}, ) end it 'adds a drop rule to ignore anonymous and daemon events' do is_expected.to contain_file('/etc/audit/rules.d/05_default_drop.rules').with_content( - %r(^-a\s+never,exit\s+-F\s+auid=-1$) + %r{^-a\s+never,exit\s+-F\s+auid=-1$}, ) end it 'adds a rule to drop crond events' do is_expected.to contain_file('/etc/audit/rules.d/05_default_drop.rules').with_content( - %r(^-a\s+never,user\s+-F\s+subj_type=crond_t$) + %r{^-a\s+never,user\s+-F\s+subj_type=crond_t$}, ) end it 'adds a rule to drop events from system services' do is_expected.to contain_file('/etc/audit/rules.d/05_default_drop.rules').with_content( - %r(^-a\s+never,exit\s+-F\s+auid!=0\s+-F\s+auid<#{facts[:uid_min]}$) + %r{^-a\s+never,exit\s+-F\s+auid!=0\s+-F\s+auid<#{facts[:uid_min]}$}, ) end @@ -219,38 +214,37 @@ it { if facts[:auditd_major_version] == '3' is_expected.to contain_file('/etc/audit/rules.d/10-base-config.rules').with({ - :ensure => 'file', - :source => 'file:///usr/share/audit/sample-rules/10-base-config.rules', - }).that_notifies('Class[auditd::service]') + ensure: 'file', + source: 'file:///usr/share/audit/sample-rules/10-base-config.rules', + }).that_notifies('Class[auditd::service]') is_expected.to contain_file('/etc/audit/rules.d/10-no-audit.rules').with({ - :ensure => 'file', - :source => 'file:///usr/share/audit/sample-rules/10-no-audit.rules', - }).that_notifies('Class[auditd::service]') + ensure: 'file', + source: 'file:///usr/share/audit/sample-rules/10-no-audit.rules', + }).that_notifies('Class[auditd::service]') is_expected.to contain_file('/etc/audit/rules.d/99-finalize.rules').with({ - :ensure => 'file', - :source => 'file:///usr/share/audit/sample-rules/99-finalize.rules', - }).that_notifies('Class[auditd::service]') + ensure: 'file', + source: 'file:///usr/share/audit/sample-rules/99-finalize.rules', + }).that_notifies('Class[auditd::service]') - is_expected.to contain_notify('bad_sample_set not found') else is_expected.to contain_file('/etc/audit/rules.d/10-base-config.rules').with({ - :ensure => 'file', - :source => 'file:///usr/share/doc/audit-2.8.5/rules/10-base-config.rules', - }).that_notifies('Class[auditd::service]') + ensure: 'file', + source: 'file:///usr/share/doc/audit-2.8.5/rules/10-base-config.rules', + }).that_notifies('Class[auditd::service]') is_expected.to contain_file('/etc/audit/rules.d/10-no-audit.rules').with({ - :ensure => 'file', - :source => 'file:///usr/share/doc/audit-2.8.5/rules/10-no-audit.rules', - }).that_notifies('Class[auditd::service]') + ensure: 'file', + source: 'file:///usr/share/doc/audit-2.8.5/rules/10-no-audit.rules', + }).that_notifies('Class[auditd::service]') is_expected.to contain_file('/etc/audit/rules.d/99-finalize.rules').with({ - :ensure => 'file', - :source => 'file:///usr/share/doc/audit-2.8.5/rules/99-finalize.rules', - }).that_notifies('Class[auditd::service]') - is_expected.to contain_notify('bad_sample_set not found') + ensure: 'file', + source: 'file:///usr/share/doc/audit-2.8.5/rules/99-finalize.rules', + }).that_notifies('Class[auditd::service]') end + is_expected.to contain_notify('bad_sample_set not found') } # auditd::config::audit_profiles::simp validation @@ -262,8 +256,8 @@ it 'specifies a key specified for each rule' do base_rules = catalogue.resource('File[/etc/audit/rules.d/50_01_simp_base.rules]')[:content].split("\n") - rules_with_tags = base_rules.select{|x| x =~ / -k / } - rules_with_tags.delete_if{|x| x =~ / -k \S+/} + rules_with_tags = base_rules.select { |x| x.include?(' -k ') } + rules_with_tags.delete_if { |x| x =~ %r{ -k \S+} } expect(rules_with_tags).to be_empty end @@ -271,36 +265,35 @@ it 'disables chmod auditing by default' do # chmod is disabled by default (SIMP-2250) is_expected.not_to contain_file('/etc/audit/rules.d/50_01_simp_base.rules').with_content( - %r(^-a always,exit -F arch=b\d\d -S chmod,fchmod,fchmodat -k chmod$) + %r{^-a always,exit -F arch=b\d\d -S chmod,fchmod,fchmodat -k chmod$}, ) end it 'disables rename/remove auditing by default' do is_expected.not_to contain_file('/etc/audit/rules.d/50_01_simp_base.rules').with_content( - %r(^-a always,exit -F arch=b\d\d -S rename,renameat,rmdir,unlink,unlinkat -F perm=x -k delete) + %r{^-a always,exit -F arch=b\d\d -S rename,renameat,rmdir,unlink,unlinkat -F perm=x -k delete}, ) end it 'disables umask auditing by default' do is_expected.not_to contain_file('/etc/audit/rules.d/50_01_simp_base.rules').with_content( - %r(^-a always,exit -F arch=b\d\d -S umask -k umask) + %r{^-a always,exit -F arch=b\d\d -S umask -k umask}, ) end it 'disables package command auditing is disabled by default' do is_expected.not_to contain_file('/etc/audit/rules.d/50_01_simp_base.rules').with_content( - %r{^-w /(usr/)?bin/(rpm|yum) -p x} + %r{^-w /(usr/)?bin/(rpm|yum) -p x}, ) - end it 'disables selinux commands auditing by default' do is_expected.not_to contain_file('/etc/audit/rules.d/50_01_simp_base.rules').with_content( - %r{^-a always,exit -F path=/usr/bin/(chcon|semanage|setsebool) -F perm=x -k privileged-priv_change} + %r{^-a always,exit -F path=/usr/bin/(chcon|semanage|setsebool) -F perm=x -k privileged-priv_change}, ) is_expected.not_to contain_file('/etc/audit/rules.d/50_01_simp_base.rules').with_content( - %r(^-a always,exit -F path=/(usr/)?sbin/setfiles -F perm=x -k privileged-priv_change) + %r{^-a always,exit -F path=/(usr/)?sbin/setfiles -F perm=x -k privileged-priv_change}, ) end end diff --git a/spec/classes/config/audit_profiles/custom_spec.rb b/spec/classes/config/audit_profiles/custom_spec.rb index 851d8844..0cfe3c79 100644 --- a/spec/classes/config/audit_profiles/custom_spec.rb +++ b/spec/classes/config/audit_profiles/custom_spec.rb @@ -3,9 +3,9 @@ describe 'auditd::config::audit_profiles::custom' do on_supported_os.each do |os, os_facts| context "on #{os}" do - let(:facts){ os_facts } + let(:facts) { os_facts } - let(:common_pre_condition) { + let(:common_pre_condition) do <<-EOM function assert_private() { } @@ -15,17 +15,19 @@ class auditd::config ( ){} include auditd::config EOM - } + end let(:pre_condition) { common_pre_condition } context 'with rules specified' do - let(:params) {{ - :rules => [ - 'First Rule', - 'Second Rule' - ] - }} + let(:params) do + { + rules: [ + 'First Rule', + 'Second Rule', + ] + } + end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_file('/etc/audit/rules.d/50_00_custom_base.rules').with_content(params[:rules].join("\n") + "\n") } @@ -33,65 +35,73 @@ class auditd::config ( context 'when using templates' do context 'with EPP template specified' do - let(:params) {{ - :template => 'foo/bar.epp' - }} + let(:params) do + { + template: 'foo/bar.epp' + } + end - let(:pre_condition) { + let(:pre_condition) do <<-EOM #{common_pre_condition} function epp($arg) >> String { 'EPP!' } EOM - } + end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_file('/etc/audit/rules.d/50_00_custom_base.rules').with_content("EPP!\n") } end context 'with ERB template specified' do - let(:params) {{ - :template => 'foo/bar.erb' - }} + let(:params) do + { + template: 'foo/bar.erb' + } + end - let(:pre_condition) { + let(:pre_condition) do <<-EOM #{common_pre_condition} function template($arg) >> String { 'ERB!' } EOM - } + end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_file('/etc/audit/rules.d/50_00_custom_base.rules').with_content("ERB!\n") } end context 'with an invalid template name specified' do - let(:params) {{ - :template => 'foo/bar.bad' - }} + let(:params) do + { + template: 'foo/bar.bad' + } + end - it { expect{is_expected.to compile.with_all_deps}.to raise_error(/must end with/) } + it { expect { is_expected.to compile.with_all_deps }.to raise_error(%r{must end with}) } end end context 'with invalid options' do - it 'should require $rules or $template' do - expect{is_expected.to compile.with_all_deps}.to raise_error(/must specify either/) + it 'requires $rules or $template' do + expect { is_expected.to compile.with_all_deps }.to raise_error(%r{must specify either}) end context 'with both $rules and $template' do - let(:params) {{ - :rules => ['RULEZ'], - :template => 'foo/bar.epp' - }} - - it { expect{is_expected.to compile.with_all_deps}.to raise_error(/may not specify/) } + let(:params) do + { + rules: ['RULEZ'], + template: 'foo/bar.epp' + } + end + + it { expect { is_expected.to compile.with_all_deps }.to raise_error(%r{may not specify}) } end end context 'with other profiles specified' do - let(:pre_condition) { + let(:pre_condition) do <<-EOM function assert_private() { } @@ -101,14 +111,16 @@ class auditd::config ( ){} include auditd::config EOM - } - - let(:params) {{ - :rules => [ - 'First Rule', - 'Second Rule' - ] - }} + end + + let(:params) do + { + rules: [ + 'First Rule', + 'Second Rule', + ] + } + end it { is_expected.to compile.with_all_deps } it { is_expected.to contain_file('/etc/audit/rules.d/50_01_custom_base.rules').with_content(params[:rules].join("\n") + "\n") } diff --git a/spec/classes/config/audit_profiles/simp_spec.rb b/spec/classes/config/audit_profiles/simp_spec.rb index 3535e30f..961d4589 100644 --- a/spec/classes/config/audit_profiles/simp_spec.rb +++ b/spec/classes/config/audit_profiles/simp_spec.rb @@ -8,15 +8,13 @@ describe 'auditd' do on_supported_os.each do |os, os_facts| context "on #{os}" do - - let(:facts){ + let(:facts) do os_facts - } + end it { is_expected.to compile.with_all_deps } context 'with default parameters' do - it { expected = File.read('spec/classes/config/audit_profiles/expected/simp_el7_basic_rules.txt') is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content(expected) @@ -25,8 +23,8 @@ it 'specifies a key specified for each rule' do base_rules = catalogue.resource('File[/etc/audit/rules.d/50_00_simp_base.rules]')[:content].split("\n") - rules_with_tags = base_rules.select{|x| x =~ / -k / } - rules_with_tags.delete_if{|x| x =~ / -k \S+/} + rules_with_tags = base_rules.select { |x| x.include?(' -k ') } + rules_with_tags.delete_if { |x| x =~ %r{ -k \S+} } expect(rules_with_tags).to be_empty end @@ -34,36 +32,35 @@ it 'disables chmod auditing by default' do # chmod is disabled by default (SIMP-2250) is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r(^-a always,exit -F arch=b\d\d -S chmod,fchmod,fchmodat -k chmod$) + %r{^-a always,exit -F arch=b\d\d -S chmod,fchmod,fchmodat -k chmod$}, ) end it 'disables rename/remove auditing by default' do is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r(^-a always,exit -F arch=b\d\d -S rename,renameat,rmdir,unlink,unlinkat -F perm=x -k delete) + %r{^-a always,exit -F arch=b\d\d -S rename,renameat,rmdir,unlink,unlinkat -F perm=x -k delete}, ) end it 'disables umask auditing by default' do is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r(^-a always,exit -F arch=b\d\d -S umask -k umask) + %r{^-a always,exit -F arch=b\d\d -S umask -k umask}, ) end it 'disables package command auditing is disabled by default' do is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r{^-w /(usr/)?bin/(rpm|yum) -p x} + %r{^-w /(usr/)?bin/(rpm|yum) -p x}, ) - end it 'disables selinux commands auditing by default' do is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r{^-a always,exit -F path=/usr/bin/(chcon|semanage|setsebool) -F perm=x -k privileged-priv_change} + %r{^-a always,exit -F path=/usr/bin/(chcon|semanage|setsebool) -F perm=x -k privileged-priv_change}, ) is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r(^-a always,exit -F path=/(usr/)?sbin/setfiles -F perm=x -k privileged-priv_change) + %r{^-a always,exit -F path=/(usr/)?sbin/setfiles -F perm=x -k privileged-priv_change}, ) end @@ -72,17 +69,17 @@ it 'disables auditing of grub' do is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r{^-w /boot/grub/grub.conf} + %r{^-w /boot/grub/grub.conf}, ) is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r{^-w /etc/grub.d} + %r{^-w /etc/grub.d}, ) end end end context 'with root audit level set to aggressive' do - let(:params) {{ :root_audit_level => 'aggressive' }} + let(:params) { { root_audit_level: 'aggressive' } } it { expected = File.read('spec/classes/config/audit_profiles/expected/simp_el7_aggressive_rules.txt') @@ -91,7 +88,7 @@ end context 'with root audit level set to insane' do - let(:params) {{ :root_audit_level => 'insane' }} + let(:params) { { root_audit_level: 'insane' } } it { expected = File.read('spec/classes/config/audit_profiles/expected/simp_el7_insane_rules.txt') @@ -125,14 +122,13 @@ 'privileged-postfix' => 'disable__audit_postfix_cmds', 'privileged-ssh' => 'disable__audit_ssh_keysign_cmd', 'privileged-cron' => 'disable__audit_crontab_cmd', - 'privileged-pam' => 'disable__audit_pam_timestamp_check_cmd', - }.each do |key, hiera_file| + 'privileged-pam' => 'disable__audit_pam_timestamp_check_cmd', }.each do |key, hiera_file| context "with #{key} auditing disabled" do let(:hieradata) { "simp_audit_profile/#{hiera_file}" } it { is_expected.not_to contain_file('/etc/audit/rules.d/50_00_base.rules').with_content( - %r{^.* -k #{key}$} + %r{^.* -k #{key}$}, ) } end @@ -140,36 +136,38 @@ context 'with privilege-related command auditing disabled' do let(:hieradata) { 'simp_audit_profile/disable__audit_priv_cmds' } + [ %r{^-a always,exit -F path=/(usr/)?bin/su -F perm=x -k privileged-priv_change$}, %r{^-a always,exit -F path=/usr/bin/sudo -F perm=x -k privileged-priv_change$}, %r{^-a always,exit -F path=/usr/bin/newgrp -F perm=x -k privileged-priv_change$}, %r{^-a always,exit -F path=/usr/bin/chsh -F perm=x -k privileged-priv_change$}, - %r{^-a always,exit -F path=/(usr/)?bin/sudoedit -F perm=x -k privileged-priv_change$} + %r{^-a always,exit -F path=/(usr/)?bin/sudoedit -F perm=x -k privileged-priv_change$}, ].each do |command_regex| it { - is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules'). - with_content(command_regex) + is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules') + .with_content(command_regex) } end end context 'with sudoers config auditing disabled' do let(:hieradata) { 'simp_audit_profile/disable__audit_cfg_sudoers' } + [ %r{^-w /etc/sudoers -p wa -k CFG_sys$}, %r{^-w /etc/sudoers.d/ -p wa -k CFG_sys$}, ].each do |command_regex| it { - is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules'). - with_content(command_regex) + is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules') + .with_content(command_regex) } end - end context 'with other system config auditing disabled' do let(:hieradata) { 'simp_audit_profile/disable__audit_cfg_sys' } + [ %r{^-w /etc/default -p wa -k CFG_sys$}, %r{^-w /etc/exports -p wa -k CFG_sys$}, @@ -203,8 +201,8 @@ %r{^-w /var/spool/at -p wa -k CFG_sys$}, ].each do |command_regex| it { - is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules'). - with_content(command_regex) + is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules') + .with_content(command_regex) } end end @@ -214,7 +212,7 @@ it { is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules'). with_content( - %r{^-a always,exit -F arch=b\d\d -S ptrace -k paranoid$} + %r{^-a always,exit -F arch=b\d\d -S ptrace -k paranoid$}, ) } end @@ -224,7 +222,7 @@ it { is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r{^-a always,exit -F arch=b\d\d -S personality -k paranoid$} + %r{^-a always,exit -F arch=b\d\d -S personality -k paranoid$}, ) } end @@ -234,7 +232,7 @@ it { is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r(^-a always,exit -F arch=b\d\d -S chmod,fchmod,fchmodat -k chmod$) + %r{^-a always,exit -F arch=b\d\d -S chmod,fchmod,fchmodat -k chmod$}, ) } end @@ -244,13 +242,13 @@ it { is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r(^-a always,exit -F arch=b64 -S rename,renameat,rmdir,unlink,unlinkat -F perm=x -k delete) + %r{^-a always,exit -F arch=b64 -S rename,renameat,rmdir,unlink,unlinkat -F perm=x -k delete}, ) } it { is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r(^-a always,exit -F arch=b32 -S rename,renameat,rmdir,unlink,unlinkat -F perm=x -k delete) + %r{^-a always,exit -F arch=b32 -S rename,renameat,rmdir,unlink,unlinkat -F perm=x -k delete}, ) } end @@ -260,7 +258,7 @@ it { is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r(^-a always,exit -F arch=b\d\d -S umask -k umask) + %r{^-a always,exit -F arch=b\d\d -S umask -k umask}, ) } end @@ -270,25 +268,25 @@ it { is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r(^-a always,exit -F path=/usr/bin/chcon -F perm=x -k privileged-priv_change) + %r{^-a always,exit -F path=/usr/bin/chcon -F perm=x -k privileged-priv_change}, ) } it { is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r(^-a always,exit -F path=/usr/sbin/semanage -F perm=x -k privileged-priv_change) + %r{^-a always,exit -F path=/usr/sbin/semanage -F perm=x -k privileged-priv_change}, ) } it { is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r(^-a always,exit -F path=/usr/sbin/setsebool -F perm=x -k privileged-priv_change) + %r{^-a always,exit -F path=/usr/sbin/setsebool -F perm=x -k privileged-priv_change}, ) } it { is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r(^-a always,exit -F path=/(usr/)?sbin/setfiles -F perm=x -k privileged-priv_change) + %r{^-a always,exit -F path=/(usr/)?sbin/setfiles -F perm=x -k privileged-priv_change}, ) } end @@ -298,7 +296,7 @@ it { is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r(^-w /(usr/)?bin/yum -p x) + %r{^-w /(usr/)?bin/yum -p x}, ) } end @@ -308,31 +306,32 @@ it { is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r(^-w /(usr/)?bin/rpm -p x) + %r{^-w /(usr/)?bin/rpm -p x}, ) } end - context 'with all auditing options enabled and custom tags' do let(:hieradata) { 'simp_audit_profile/enable_all_custom_tags' } - let(:params) {{ :root_audit_level => 'insane' }} + let(:params) { { root_audit_level: 'insane' } } it 'uses custom tags as rule keys' do - expected = File.read('spec/classes/config/audit_profiles/expected/simp_el7_all_rules_custom_tags.txt') + File.read('spec/classes/config/audit_profiles/expected/simp_el7_all_rules_custom_tags.txt') end end context 'with multiple audit profiles' do - let(:params) {{ :default_audit_profiles => ['simp', 'stig'] }} + let(:params) { { default_audit_profiles: ['simp', 'stig'] } } it { - expected = File.read('spec/classes/config/audit_profiles/expected/simp_el7_basic_rules.txt') - is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content(expected) + expected = File.read('spec/classes/config/audit_profiles/expected/simp_el7_basic_rules.txt') + is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content(expected) } - it { is_expected.to contain_file('/etc/audit/rules.d/50_01_stig_base.rules').with_content( - /#### auditd::config::audit_profiles::stig Audit Rules ####/) + it { + is_expected.to contain_file('/etc/audit/rules.d/50_01_stig_base.rules').with_content( + %r{#### auditd::config::audit_profiles::stig Audit Rules ####}, + ) } end @@ -341,44 +340,44 @@ # EL 7.3 context '2.6.5' do - let(:facts) { + let(:facts) do new_facts = Marshal.load(Marshal.dump(os_facts)) new_facts[:auditd_version] = '2.6.5' new_facts - } + end context 'default options' do it do - expect(auditd_conf[:content]).to match(/log_format = raw/) - expect(auditd_conf[:content]).to match(/write_logs = yes/) + expect(auditd_conf[:content]).to match(%r{log_format = raw}) + expect(auditd_conf[:content]).to match(%r{write_logs = yes}) end end context 'write_logs = false' do - let(:params) {{ :write_logs => false }} + let(:params) { { write_logs: false } } it do - expect(auditd_conf[:content]).to match(/log_format = raw/) - expect(auditd_conf[:content]).to match(/write_logs = no/) + expect(auditd_conf[:content]).to match(%r{log_format = raw}) + expect(auditd_conf[:content]).to match(%r{write_logs = no}) end end context 'log_format = NOLOG' do - let(:params) {{ :log_format => 'NOLOG' }} + let(:params) { { log_format: 'NOLOG' } } it do - expect(auditd_conf[:content]).to match(/log_format = raw/) - expect(auditd_conf[:content]).to match(/write_logs = no/) + expect(auditd_conf[:content]).to match(%r{log_format = raw}) + expect(auditd_conf[:content]).to match(%r{write_logs = no}) end end context 'log_format = ENRICHED' do - let(:params) {{ :log_format => 'ENRICHED' }} + let(:params) { { log_format: 'ENRICHED' } } it do - expect(auditd_conf[:content]).to match(/log_format = ENRICHED/) - expect(auditd_conf[:content]).to match(/write_logs = yes/) + expect(auditd_conf[:content]).to match(%r{log_format = ENRICHED}) + expect(auditd_conf[:content]).to match(%r{write_logs = yes}) end end end @@ -396,8 +395,8 @@ if Puppet[:strict] == :error is_expected.to compile.and_raise_error(%r{'auditd::config::audit_profiles::simp::audit_sudoers' is deprecated\.}) else - is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules'). - with_content(command_regex) + is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules') + .with_content(command_regex) end end end @@ -414,8 +413,8 @@ if Puppet[:strict] == :error is_expected.to compile.and_raise_error(%r{'auditd::config::audit_profiles::simp::audit_sudoers_tag' is deprecated\.}) else - is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules'). - with_content(command_regex) + is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules') + .with_content(command_regex) end end end @@ -428,8 +427,8 @@ if Puppet[:strict] == :error is_expected.to compile.and_raise_error(%r{'auditd::config::audit_profiles::simp::audit_sudoers_tag' is deprecated\.}) else - is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules'). - with_content(command_regex) + is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules') + .with_content(command_regex) end end end @@ -443,7 +442,7 @@ is_expected.to compile.and_raise_error(%r{'auditd::config::audit_profiles::simp::audit_grub' is deprecated\.}) else is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r{^.* -k CFG_grub$} + %r{^.* -k CFG_grub$}, ) end end @@ -457,7 +456,7 @@ is_expected.to compile.and_raise_error(%r{'auditd::config::audit_profiles::simp::audit_grub_tag' is deprecated\.}) else is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r{^.*grub.(d|conf).* -k old_grub_tag$} + %r{^.*grub.(d|conf).* -k old_grub_tag$}, ) end end @@ -467,7 +466,7 @@ is_expected.to compile.and_raise_error(%r{'auditd::config::audit_profiles::simp::audit_grub_tag' is deprecated\.}) else is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r{^.* -k CFG_grub$} + %r{^.* -k CFG_grub$}, ) end end @@ -481,7 +480,7 @@ is_expected.to compile.and_raise_error(%r{'auditd::config::audit_profiles::simp::audit_yum' is deprecated\.}) else is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r{^.* -k yum_config$} + %r{^.* -k yum_config$}, ) end end @@ -495,7 +494,7 @@ is_expected.to compile.and_raise_error(%r{'auditd::config::audit_profiles::simp::audit_yum_tag' is deprecated\.}) else is_expected.to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r{^.*/etc/yum.* -k old_yum_tag$} + %r{^.*/etc/yum.* -k old_yum_tag$}, ) end end @@ -505,7 +504,7 @@ is_expected.to compile.and_raise_error(%r{'auditd::config::audit_profiles::simp::audit_yum_tag' is deprecated\.}) else is_expected.not_to contain_file('/etc/audit/rules.d/50_00_simp_base.rules').with_content( - %r{^.* -k yum_config$} + %r{^.* -k yum_config$}, ) end end diff --git a/spec/classes/config/audit_profiles/stig_spec.rb b/spec/classes/config/audit_profiles/stig_spec.rb index 55282964..053f1f3a 100644 --- a/spec/classes/config/audit_profiles/stig_spec.rb +++ b/spec/classes/config/audit_profiles/stig_spec.rb @@ -8,13 +8,12 @@ describe 'auditd' do on_supported_os.each do |os, os_facts| context "on #{os}" do - - let(:facts){ os_facts } + let(:facts) { os_facts } it { is_expected.to compile.with_all_deps } context 'with auditd::config::audit_profile::stig default parameters' do - let(:params) {{ :default_audit_profiles => ['stig'] }} + let(:params) { { default_audit_profiles: ['stig'] } } it { expected = File.read('spec/classes/config/audit_profiles/expected/stig_el7_base_rules.txt') @@ -35,87 +34,87 @@ 'privileged-postfix' => 'stig_audit_profile/disable__audit_postfix_cmds', 'privileged-ssh' => 'stig_audit_profile/disable__audit_ssh_keysign_cmd', 'privileged-cron' => 'stig_audit_profile/disable__audit_crontab_cmd', - 'privileged-pam' => 'stig_audit_profile/disable__audit_pam_timestamp_check_cmd', - }.each do |key, hiera_file| + 'privileged-pam' => 'stig_audit_profile/disable__audit_pam_timestamp_check_cmd', }.each do |key, hiera_file| context "with #{key} auditing disabled" do - let(:params) {{ :default_audit_profiles => ['stig'] }} + let(:params) { { default_audit_profiles: ['stig'] } } let(:hieradata) { hiera_file } it { is_expected.not_to contain_file('/etc/audit/rules.d/50_00_stig_base.rules').with_content( - %r{^.* -F key=#{key}$} + %r{^.* -F key=#{key}$}, ) } end end context 'with chown auditing disabled' do - let(:params) {{ :default_audit_profiles => ['stig'] }} + let(:params) { { default_audit_profiles: ['stig'] } } let(:hieradata) { 'stig_audit_profile/disable__audit_chown' } it { is_expected.not_to contain_file('/etc/audit/rules.d/50_00_stig_base.rules').with_content( - %r(^-a always,exit -F arch=b\d\d -S \w*chown\w* -F auid>=\d+ -F auid!=unset -F key=perm_mod$) + %r{^-a always,exit -F arch=b\d\d -S \w*chown\w* -F auid>=\d+ -F auid!=unset -F key=perm_mod$}, ) } end context 'with chmod auditing disabled' do - let(:params) {{ :default_audit_profiles => ['stig'] }} + let(:params) { { default_audit_profiles: ['stig'] } } let(:hieradata) { 'stig_audit_profile/disable__audit_chmod' } it { is_expected.not_to contain_file('/etc/audit/rules.d/50_00_stig_base.rules').with_content( - %r(^-a always,exit -F arch=b\d\d -S \w*chmod\w* -F auid>=\d+ -F auid!=unset -F key=perm_mod$) + %r{^-a always,exit -F arch=b\d\d -S \w*chmod\w* -F auid>=\d+ -F auid!=unset -F key=perm_mod$}, ) } end context 'with attr auditing disabled' do - let(:params) {{ :default_audit_profiles => ['stig'] }} + let(:params) { { default_audit_profiles: ['stig'] } } let(:hieradata) { 'stig_audit_profile/disable__audit_attr' } it { is_expected.not_to contain_file('/etc/audit/rules.d/50_00_stig_base.rules').with_content( - %r(^-a always,exit -F arch=b\d\d -S \w*attr -F auid>=\d+ -F auid!=unset -F key=perm_mod$) + %r{^-a always,exit -F arch=b\d\d -S \w*attr -F auid>=\d+ -F auid!=unset -F key=perm_mod$}, ) } end context 'with selinux command auditing disabled' do - let(:params) {{ :default_audit_profiles => ['stig'] }} + let(:params) { { default_audit_profiles: ['stig'] } } let(:hieradata) { 'stig_audit_profile/disable__audit_selinux_cmds' } it { is_expected.not_to contain_file('/etc/audit/rules.d/50_00_stig_base.rules').with_content( - %r{^-a always,exit -F path=/usr/bin/(chcon|semanage|setsebool) -F perm=x -F auid>=\d+ -F auid!=unset -F key=privileged-priv_change} + %r{^-a always,exit -F path=/usr/bin/(chcon|semanage|setsebool) -F perm=x -F auid>=\d+ -F auid!=unset -F key=privileged-priv_change}, ) is_expected.not_to contain_file('/etc/audit/rules.d/50_00_stig_base.rules').with_content( - %r(^-a always,exit -F path=/(usr/)?sbin/setfiles -F perm=x -F auid>=\d+ -F auid!=unset -F key=privileged-priv_change) + %r{^-a always,exit -F path=/(usr/)?sbin/setfiles -F perm=x -F auid>=\d+ -F auid!=unset -F key=privileged-priv_change}, ) } end context 'with privilege-related command auditing disabled' do - let(:params) {{ :default_audit_profiles => ['stig'] }} + let(:params) { { default_audit_profiles: ['stig'] } } let(:hieradata) { 'stig_audit_profile/disable__audit_priv_cmds' } + [ %r{^-a always,exit -F path=/(usr/)?bin/su -F perm=x -F auid>=\d+ -F auid!=unset -F key=privileged-priv_change$}, %r{^-a always,exit -F path=/usr/bin/sudo -F perm=x -F auid>=\d+ -F auid!=unset -F key=privileged-priv_change$}, %r{^-a always,exit -F path=/usr/bin/newgrp -F perm=x -F auid>=\d+ -F auid!=unset -F key=privileged-priv_change$}, %r{^-a always,exit -F path=/usr/bin/chsh -F perm=x -F auid>=\d+ -F auid!=unset -F key=privileged-priv_change$}, - %r{^-a always,exit -F path=/(usr/)?bin/sudoedit -F perm=x -F auid>=\d+ -F auid!=unset -F key=privileged-priv_change$} + %r{^-a always,exit -F path=/(usr/)?bin/sudoedit -F perm=x -F auid>=\d+ -F auid!=unset -F key=privileged-priv_change$}, ].each do |command_regex| it { - is_expected.not_to contain_file('/etc/audit/rules.d/50_00_stig_base.rules'). - with_content(command_regex) + is_expected.not_to contain_file('/etc/audit/rules.d/50_00_stig_base.rules') + .with_content(command_regex) } end end context 'with all custom tags' do - let(:params) {{ :default_audit_profiles => ['stig'] }} + let(:params) { { default_audit_profiles: ['stig'] } } let(:hieradata) { 'stig_audit_profile/all_custom_tags' } it 'uses custom tags as rule keys' do @@ -125,15 +124,17 @@ end context 'with multiple audit profiles' do - let(:params) {{ :default_audit_profiles => ['stig', 'simp'] }} + let(:params) { { default_audit_profiles: ['stig', 'simp'] } } it { - expected = File.read('spec/classes/config/audit_profiles/expected/stig_el7_base_rules.txt') - is_expected.to contain_file('/etc/audit/rules.d/50_00_stig_base.rules').with_content(expected) + expected = File.read('spec/classes/config/audit_profiles/expected/stig_el7_base_rules.txt') + is_expected.to contain_file('/etc/audit/rules.d/50_00_stig_base.rules').with_content(expected) } - it { is_expected.to contain_file('/etc/audit/rules.d/50_01_simp_base.rules').with_content( - /#### auditd::config::audit_profiles::simp Audit Rules ####/) + it { + is_expected.to contain_file('/etc/audit/rules.d/50_01_simp_base.rules').with_content( + %r{#### auditd::config::audit_profiles::simp Audit Rules ####}, + ) } end end diff --git a/spec/classes/config/audit_profiles_spec.rb b/spec/classes/config/audit_profiles_spec.rb index 8bdc65c0..32399179 100644 --- a/spec/classes/config/audit_profiles_spec.rb +++ b/spec/classes/config/audit_profiles_spec.rb @@ -7,116 +7,117 @@ describe 'auditd' do on_supported_os.each do |os, os_facts| context "on #{os}" do - let(:facts){ + let(:facts) do _facts = Marshal.load(Marshal.dump(os_facts)) unless _facts[:auditd_major_version] - if _facts[:os][:release][:major] < '8' - _facts[:auditd_major_version] = '2' - else - _facts[:auditd_major_version] = '3' - end + _facts[:auditd_major_version] = if _facts[:os][:release][:major] < '8' + '2' + else + '3' + end end _facts - } + end context 'with default parameters' do it { is_expected.to compile.with_all_deps } - it { is_expected.to contain_auditd__rule('audit_auditd_config').with_content( %r(-w /var/log/audit -p wa -k audit-logs)) } + it { is_expected.to contain_auditd__rule('audit_auditd_config').with_content(%r{-w /var/log/audit -p wa -k audit-logs}) } it 'configures auditd to ignore rule failures' do - is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content(%r(^-i$)) - is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content(%r(^-c$)) + is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content(%r{^-i$}) + is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content(%r{^-c$}) end it 'configures buffer size' do is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content( - %r(^-b\s+16384$) + %r{^-b\s+16384$}, ) end it 'configures failure mode' do is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content( - %r(^-f\s+1$) + %r{^-f\s+1$}, ) end it 'configures rate limiting' do is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content( - %r(^-r\s+0$) + %r{^-r\s+0$}, ) end it 'adds a drop rule to ignore anonymous and daemon events' do is_expected.to contain_file('/etc/audit/rules.d/05_default_drop.rules').with_content( - %r(^-a\s+never,exit\s+-F\s+auid=-1$) + %r{^-a\s+never,exit\s+-F\s+auid=-1$}, ) end it 'adds a rule to drop crond events' do is_expected.to contain_file('/etc/audit/rules.d/05_default_drop.rules').with_content( - %r(^-a\s+never,user\s+-F\s+subj_type=crond_t$) + %r{^-a\s+never,user\s+-F\s+subj_type=crond_t$}, ) end it 'adds a rule to drop events from system services' do is_expected.to contain_file('/etc/audit/rules.d/05_default_drop.rules').with_content( - %r(^-a\s+never,exit\s+-F\s+auid!=0\s+-F\s+auid<#{facts[:uid_min]}$) + %r{^-a\s+never,exit\s+-F\s+auid!=0\s+-F\s+auid<#{facts[:uid_min]}$}, ) end it { is_expected.to contain_class('auditd::config::audit_profiles::simp') } - end context 'targeting specific SELinux types' do - let(:params){{ - :target_selinux_types => ['unconfined_t', 'bob_t'] - }} + let(:params) do + { + target_selinux_types: ['unconfined_t', 'bob_t'] + } + end it 'adds a rule to drop types not in the match list' do is_expected.to contain_file('/etc/audit/rules.d/05_default_drop.rules').with_content( - %r(^-a\s+never,user\s+-F\s+subj_type!=unconfined_t$) + %r{^-a\s+never,user\s+-F\s+subj_type!=unconfined_t$}, ) is_expected.to contain_file('/etc/audit/rules.d/05_default_drop.rules').with_content( - %r(^-a\s+never,user\s+-F\s+subj_type!=bob_t$) + %r{^-a\s+never,user\s+-F\s+subj_type!=bob_t$}, ) end end context 'setting the root audit level to aggressive' do - let(:params) {{ :root_audit_level => 'aggressive' }} + let(:params) { { root_audit_level: 'aggressive' } } it { is_expected.to compile.with_all_deps } it 'increases the buffer size (above basic setting)' do is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content( - %r(^-b\s+32788$) + %r{^-b\s+32788$}, ) end end context 'setting the root audit level to insane' do - let(:params) {{ :root_audit_level => 'insane' }} + let(:params) { { root_audit_level: 'insane' } } it { is_expected.to compile.with_all_deps } it 'increases the buffer size (above aggressive setting)' do is_expected.to contain_file('/etc/audit/rules.d/00_head.rules').with_content( - %r(^-b\s+65576$) + %r{^-b\s+65576$}, ) end end context "setting default_audit_profiles to ['stig']" do - let(:params) {{ :default_audit_profiles => ['stig'] }} + let(:params) { { default_audit_profiles: ['stig'] } } it { is_expected.to compile.with_all_deps } - it { is_expected.to_not contain_class('auditd::config::audit_profiles::simp') } + it { is_expected.not_to contain_class('auditd::config::audit_profiles::simp') } it { is_expected.to contain_class('auditd::config::audit_profiles::stig') } end context "setting default_audit_profiles to ['simp', 'stig']" do - let(:params) {{ :default_audit_profiles => ['simp', 'stig'] }} + let(:params) { { default_audit_profiles: ['simp', 'stig'] } } it { is_expected.to compile.with_all_deps } it { is_expected.to contain_class('auditd::config::audit_profiles::simp') } @@ -124,13 +125,12 @@ end context 'setting default_audit_profiles to []' do - let(:params) {{ :default_audit_profiles => [] }} + let(:params) { { default_audit_profiles: [] } } it { is_expected.to compile.with_all_deps } - it { is_expected.to_not contain_class('auditd::config::audit_profiles::simp') } - it { is_expected.to_not contain_class('auditd::config::audit_profiles::stig') } + it { is_expected.not_to contain_class('auditd::config::audit_profiles::simp') } + it { is_expected.not_to contain_class('auditd::config::audit_profiles::stig') } end - end end end diff --git a/spec/classes/config/grub_spec.rb b/spec/classes/config/grub_spec.rb index 36b10951..ccee4aae 100644 --- a/spec/classes/config/grub_spec.rb +++ b/spec/classes/config/grub_spec.rb @@ -5,27 +5,28 @@ on_supported_os.each do |os, facts| context "on #{os}" do let(:facts) do - if ['RedHat','CentOS'].include?(facts[:os][:name]) && facts[:os][:release][:major].to_s < '7' + if ['RedHat', 'CentOS'].include?(facts[:os][:name]) && facts[:os][:release][:major].to_s < '7' facts[:apache_version] = '2.2' facts[:grub_version] = '0.9' else facts[:apache_version] = '2.4' facts[:grub_version] = '2.0~beta' end - if ! facts[:auditd_major_version] - if facts[:os][:release][:major] < '8' - facts[:auditd_major_version] = '2' - else - facts[:auditd_major_version] = '3' - end + unless facts[:auditd_major_version] + facts[:auditd_major_version] = if facts[:os][:release][:major] < '8' + '2' + else + '3' + end end facts end it { is_expected.to compile.with_all_deps } - context "without any parameters" do - let(:params) {{ }} + context 'without any parameters' do + let(:params) { {} } + it { is_expected.to contain_kernel_parameter('audit').with_value('1') } it { is_expected.to contain_reboot_notify('audit').that_subscribes_to('Kernel_parameter[audit]') @@ -33,9 +34,12 @@ end context 'when disabled' do - let(:params) {{ - :enable => false - }} + let(:params) do + { + enable: false + } + end + it { is_expected.to contain_kernel_parameter('audit').with_value('0') } it { is_expected.to contain_reboot_notify('audit').that_subscribes_to('Kernel_parameter[audit]') diff --git a/spec/classes/config_spec.rb b/spec/classes/config_spec.rb index 9bac20ad..c678f73f 100644 --- a/spec/classes/config_spec.rb +++ b/spec/classes/config_spec.rb @@ -9,147 +9,147 @@ context 'supported operating systems' do on_supported_os.each do |os, os_facts| context "on #{os}" do - let (:facts) {os_facts} + let(:facts) { os_facts } context 'with default parameters' do - let (:params) {{ }} + let(:params) { {} } it { is_expected.to compile.with_all_deps } it { is_expected.to contain_file('/etc/audit/rules.d').with({ - :ensure => 'directory', - :owner => 'root', - :group => 'root', - :mode => '0600', - :recurse => true, - :purge => true - }) + ensure: 'directory', + owner: 'root', + group: 'root', + mode: '0600', + recurse: true, + purge: true + }) } it { is_expected.to contain_file('/etc/audit/audit.rules').with({ - :owner => 'root', - :group => 'root', - :mode => 'o-rwx' - }) + owner: 'root', + group: 'root', + mode: 'o-rwx' + }) } it { is_expected.to contain_file('/etc/audit/audit.rules.prev').with({ - :owner => 'root', - :group => 'root', - :mode => 'o-rwx' - }) + owner: 'root', + group: 'root', + mode: 'o-rwx' + }) } it { is_expected.to contain_file('/etc/audit').with({ - :ensure => 'directory', - :owner => 'root', - :group => 'root', - :mode => '0600', - :recurse => true, - :purge => true - }) + ensure: 'directory', + owner: 'root', + group: 'root', + mode: '0600', + recurse: true, + purge: true + }) } - it { is_expected.to_not contain_augeas('auditd/USE_AUGENRULES') } - it { is_expected.to_not contain_class('auditd::config::logging').that_notifies('Class[auditd::service]') } + it { is_expected.not_to contain_augeas('auditd/USE_AUGENRULES') } + it { is_expected.not_to contain_class('auditd::config::logging').that_notifies('Class[auditd::service]') } it { is_expected.to contain_file('/var/log/audit').with({ - :ensure => 'directory', - :owner => 'root', - :group => 'root', - :mode => 'u+rX,g-rwx,o-rwx', - :recurse => true - }) + ensure: 'directory', + owner: 'root', + group: 'root', + mode: 'u+rX,g-rwx,o-rwx', + recurse: true + }) } it { is_expected.to contain_class('auditd::config::audit_profiles') } it { is_expected.to contain_class('auditd::config::audit_profiles::simp') } - it { is_expected.to_not contain_class('auditd::config::audisp') } - it { is_expected.to_not contain_class('auditd::config::audisp::syslog') } - end # Default params + it { is_expected.not_to contain_class('auditd::config::audisp') } + it { is_expected.not_to contain_class('auditd::config::audisp::syslog') } + end # Default params context 'with purge behaviour false' do - let(:params) {{ :purge_auditd_rules => false }} + let(:params) { { purge_auditd_rules: false } } it { is_expected.to compile.with_all_deps } it { is_expected.to contain_file('/etc/audit/rules.d').with({ - :ensure => 'directory', - :owner => 'root', - :group => 'root', - :mode => '0600', - :recurse => true, - :purge => false - }) + ensure: 'directory', + owner: 'root', + group: 'root', + mode: '0600', + recurse: true, + purge: false + }) } end context 'with empty default_audit_profiles' do - let(:params) {{ :default_audit_profiles => [] }} + let(:params) { { default_audit_profiles: [] } } it { is_expected.to compile.with_all_deps } - it { is_expected.to_not contain_class('auditd::config::audit_profiles') } + it { is_expected.not_to contain_class('auditd::config::audit_profiles') } end context 'with different log_group' do - let(:params) {{ log_group: 'rspec' }} + let(:params) { { log_group: 'rspec' } } it { is_expected.to compile.with_all_deps } it { is_expected.to contain_file('/etc/audit').with({ - :ensure => 'directory', - :owner => 'root', - :group => 'rspec', - :mode => '0640', - :recurse => true, - :purge => true - }) + ensure: 'directory', + owner: 'root', + group: 'rspec', + mode: '0640', + recurse: true, + purge: true + }) } it { is_expected.to contain_file('/etc/audit/rules.d').with({ - :ensure => 'directory', - :owner => 'root', - :group => 'rspec', - :mode => '0640', - :recurse => true, - :purge => true - }) + ensure: 'directory', + owner: 'root', + group: 'rspec', + mode: '0640', + recurse: true, + purge: true + }) } it { is_expected.to contain_file('/etc/audit/audit.rules').with({ - :owner => 'root', - :group => 'rspec', - :mode => 'o-rwx' - }) + owner: 'root', + group: 'rspec', + mode: 'o-rwx' + }) } it { is_expected.to contain_file('/etc/audit/audit.rules.prev').with({ - :owner => 'root', - :group => 'rspec', - :mode => 'o-rwx' - }) + owner: 'root', + group: 'rspec', + mode: 'o-rwx' + }) } it { is_expected.to contain_file('/etc/audit/auditd.conf').with({ - :owner => 'root', - :group => 'rspec', - :mode => '0640' - }) + owner: 'root', + group: 'rspec', + mode: '0640' + }) } it { is_expected.to contain_file('/var/log/audit').with({ - :ensure => 'directory', - :owner => 'root', - :group => 'rspec', - :mode => 'u+rX,g+rX,g-w,o-rwx', - :recurse => true - }) + ensure: 'directory', + owner: 'root', + group: 'rspec', + mode: 'u+rX,g+rX,g-w,o-rwx', + recurse: true + }) } end context 'with deprecated parameters' do context 'with default_audit_profile = true' do - let(:params) {{ default_audit_profile: true }} + let(:params) { { default_audit_profile: true } } it do if Puppet[:strict] == :error @@ -162,7 +162,7 @@ end context 'with default_audit_profile = false' do - let(:params) {{ default_audit_profile: false }} + let(:params) { { default_audit_profile: false } } it do if Puppet[:strict] == :error @@ -176,7 +176,7 @@ end context "with default_audit_profile = 'simp'" do - let(:params) {{ default_audit_profile: 'simp' }} + let(:params) { { default_audit_profile: 'simp' } } it do if Puppet[:strict] == :error @@ -190,7 +190,7 @@ end context "with default_audit_profiles = 'built_in'" do - let(:params) {{ :default_audit_profiles => ['built_in'] }} + let(:params) { { default_audit_profiles: ['built_in'] } } it { is_expected.to contain_class('auditd::config::audit_profiles') } it { is_expected.to contain_class('auditd::config::audit_profiles::built_in') } @@ -201,19 +201,19 @@ # default for rhel 8 but version 2 is the default for el6 and el7. # Neither fact is available if auditing in the kernel is not enabled. [ - { :auditd_version => '3.0', :auditd_major_version => '3' }, - { :auditd_version => '2.4.5', :auditd_major_version => '2' }, - { :auditd_version => nil, :auditd_major_version => nil } - ].each do | more_facts | + { auditd_version: '3.0', auditd_major_version: '3' }, + { auditd_version: '2.4.5', auditd_major_version: '2' }, + { auditd_version: nil, auditd_major_version: nil }, + ].each do |more_facts| context "with auditd version #{more_facts[:auditd_major_version].inspect}" do - - let(:facts) { + let(:facts) do _facts = Marshal.load(Marshal.dump(os_facts)) _facts[:auditd_version] = more_facts[:auditd_version] _facts[:auditd_major_version] = more_facts[:auditd_major_version] _facts - } - let(:expected_content){ <<-EOM.gsub(/^\s+/,'') + end + let(:expected_content) do + <<-EOM.gsub(%r{^\s+}, '') # This file is managed by Puppet (module 'auditd') log_file = /var/log/audit/audit.log log_format = raw @@ -233,17 +233,20 @@ disk_full_action = rotate disk_error_action = syslog EOM - } - let(:extra_content){<<-EOM.gsub(/^\s+/,'') + end + let(:extra_content) do + <<-EOM.gsub(%r{^\s+}, '') write_logs = yes EOM - } - let(:v2_content){<<-EOM.gsub(/^\s+/,'') + end + let(:v2_content) do + <<-EOM.gsub(%r{^\s+}, '') disp_qos = lossy dispatcher = /sbin/audispd EOM - } - let(:v3_content){<<-EOM.gsub(/^\s+/,'') + end + let(:v3_content) do + <<-EOM.gsub(%r{^\s+}, '') # Auditd Version 3.0 or later specific options local_events = yes verify_email = yes @@ -252,72 +255,70 @@ max_restarts = 10 plugin_dir = /etc/audit/plugins.d EOM - } - let(:end_content){<<-EOM.gsub(/^\s+/,'') + end + let(:end_content) do + <<-EOM.gsub(%r{^\s+}, '') # This entry must be after verify_email if verify_email is to work # Note: verify_email is only an auditd version 3 option action_mail_acct = root EOM - } + end context 'with default parameters' do - let(:params) {{ }} + let(:params) { {} } it { - if (facts[:auditd_major_version].nil? && (facts[:os][:release][:major] < '8')) || - (facts[:auditd_major_version] == '2') - - if facts[:auditd_version] && (facts[:auditd_version] < '2.5.2') - # If version 2.5.2 does not have option write_logs - complete_content = expected_content + v2_content + end_content - else - complete_content = expected_content + extra_content + v2_content + end_content - end - else - complete_content = expected_content + extra_content + v3_content + end_content - end + complete_content = if (facts[:auditd_major_version].nil? && (facts[:os][:release][:major] < '8')) || + (facts[:auditd_major_version] == '2') + + if facts[:auditd_version] && (facts[:auditd_version] < '2.5.2') + # If version 2.5.2 does not have option write_logs + expected_content + v2_content + end_content + else + expected_content + extra_content + v2_content + end_content + end + else + expected_content + extra_content + v3_content + end_content + end is_expected.to contain_file('/etc/audit/auditd.conf').with({ - :owner => 'root', - :group => 'root', - :mode => '0600', - :content => complete_content + "\n" - }) + owner: 'root', + group: 'root', + mode: '0600', + content: complete_content + "\n" + }) if (facts[:auditd_major_version].nil? && (facts[:os][:release][:major] >= '8')) || (facts[:auditd_major_version] == '3') - is_expected.to contain_file('/etc/audit/auditd.conf').with_content(%r(^local_events = .*$)) + is_expected.to contain_file('/etc/audit/auditd.conf').with_content(%r{^local_events = .*$}) else - is_expected.to contain_file('/etc/audit/auditd.conf').with_content(%r(^disp_qos = .*$)) + is_expected.to contain_file('/etc/audit/auditd.conf').with_content(%r{^disp_qos = .*$}) end } - end context 'with syslog enabled' do - let(:params) {{ :syslog => true }} + let(:params) { { syslog: true } } it { is_expected.to contain_class('auditd::config::logging').that_notifies('Class[auditd::service]') } # Test private class config::logging it { if facts[:auditd_version].nil? || facts[:auditd_major_version] >= '3' - is_expected.to_not contain_class('auditd::config::audisp') + is_expected.not_to contain_class('auditd::config::audisp') else is_expected.to contain_class('auditd::config::audisp') end } it { if facts[:auditd_version].nil? - is_expected.to_not contain_class('auditd::config::audisp::syslog') + is_expected.not_to contain_class('auditd::config::audisp::syslog') else is_expected.to contain_class('auditd::config::audisp::syslog') end } end - - end # End auditd version context - end # End auditd version loop - + end # End auditd version context + end # End auditd version loop end # End OS Context end # End OS loop end diff --git a/spec/classes/init_spec.rb b/spec/classes/init_spec.rb index 5299e8b6..d07e4ca1 100644 --- a/spec/classes/init_spec.rb +++ b/spec/classes/init_spec.rb @@ -17,12 +17,12 @@ os_facts.merge( { # Oldest version shipping with EL7 - :auditd_version => '2.4.1', - :simplib__auditd => { + auditd_version: '2.4.1', + simplib__auditd: { 'enabled' => true, 'kernel_enforcing' => true } - } + }, ) end @@ -31,20 +31,21 @@ end context 'auditd with default parameters' do - let(:params) {{ }} + let(:params) { {} } + it_behaves_like 'a structured module' it { is_expected.to contain_service('auditd').with({ - :ensure => true, - :enable => true, - :start => "/sbin/service auditd start", - :stop => "/sbin/service auditd stop", - :restart => "/sbin/service auditd restart" - }) + ensure: true, + enable: true, + start: '/sbin/service auditd start', + stop: '/sbin/service auditd stop', + restart: '/sbin/service auditd restart' + }) } it { is_expected.to contain_class('auditd::install').that_comes_before('Class[auditd::config::grub]') } it { is_expected.to contain_class('auditd::config::grub').with_enable(true) } - it { is_expected.to_not contain_class('auditd::config::logging') } + it { is_expected.not_to contain_class('auditd::config::logging') } context 'on a host without grub' do let(:facts) { super().merge(grub_version: nil) } @@ -56,32 +57,34 @@ end context 'auditd with space_left < admin_space_left' do - let(:params) {{ - :space_left => 20, - :admin_space_left => 25 - }} + let(:params) do + { + space_left: 20, + admin_space_left: 25 + } + end - it { is_expected.to compile.and_raise_error(/Auditd requires \$space_left to be greater than \$admin_space_left, otherwise it will not start/) } + it { is_expected.to compile.and_raise_error(%r{Auditd requires \$space_left to be greater than \$admin_space_left, otherwise it will not start}) } end context 'with space_left as a percentage' do let(:params) do { - :space_left => '20%' + space_left: '20%' } end - it { is_expected.to compile.and_raise_error(/cannot contain "%"/) } + it { is_expected.to compile.and_raise_error(%r{cannot contain "%"}) } end context 'with space_left as a percentage' do let(:params) do { - :admin_space_left => '20%' + admin_space_left: '20%' } end - it { is_expected.to compile.and_raise_error(/cannot contain "%"/) } + it { is_expected.to compile.and_raise_error(%r{cannot contain "%"}) } end context 'auditd 2.8.5' do @@ -92,7 +95,7 @@ context 'with space_left as a percentage' do let(:params) do { - :space_left => '20%' + space_left: '20%' } end @@ -102,7 +105,7 @@ context 'with admin_space_left as a percentage' do let(:params) do { - :admin_space_left => '20%' + admin_space_left: '20%' } end @@ -135,13 +138,15 @@ end context 'auditd with auditing disabled' do - let(:params) {{ - :enable => false - }} + let(:params) do + { + enable: false + } + end it { is_expected.to contain_class('auditd::config::grub').with_enable(false) } - it { is_expected.to_not contain_class('auditd::install') } - it { is_expected.to_not contain_class('auditd::config') } + it { is_expected.not_to contain_class('auditd::install') } + it { is_expected.not_to contain_class('auditd::config') } it { is_expected.to contain_class('auditd::service') } end end @@ -150,15 +155,15 @@ context 'unsupported operating system' do describe 'auditd without any parameters on Solaris/Nexenta' do - let(:facts) { + let(:facts) do { - :os => { + os: { 'name' => 'Solaris' } } - } + end - it { expect { is_expected.to contain_package('auditd') }.to raise_error(Puppet::Error) } + it { expect { is_expected.to contain_package('auditd') }.to raise_error(Puppet::Error) } end end end diff --git a/spec/defines/rule_spec.rb b/spec/defines/rule_spec.rb index 947a4d2d..f5e58682 100644 --- a/spec/defines/rule_spec.rb +++ b/spec/defines/rule_spec.rb @@ -5,110 +5,122 @@ on_supported_os.each do |os, os_facts| context "on #{os}" do let(:title) { 'test' } - let(:params) {{ :content => 'rspec_audit_message' }} - let(:facts){ + let(:params) { { content: 'rspec_audit_message' } } + let(:facts) do _facts = Marshal.load(Marshal.dump(os_facts)) unless _facts[:auditd_major_version] - if _facts[:os][:release][:major] < '8' - _facts[:auditd_major_version] = '2' - else - _facts[:auditd_major_version] = '3' - end + _facts[:auditd_major_version] = if _facts[:os][:release][:major] < '8' + '2' + else + '3' + end end _facts - } + end it { is_expected.to compile.with_all_deps } - context "without any parameters" do + context 'without any parameters' do it { is_expected.to contain_class('auditd') - is_expected.to contain_file("/etc/audit/rules.d/75.#{title}.rules").with_content(%r(#{params[:content]})) + is_expected.to contain_file("/etc/audit/rules.d/75.#{title}.rules").with_content(%r{#{params[:content]}}) } end context 'when :content is an Array' do - let(:params) {{ - :content => [ - '-a always,exit -F dir=${confdir} -F uid!=puppet -p wa -k Puppet_Config', - '-a always,exit -F dir=${logdir} -F uid!=puppet -p wa -k Puppet_Log', - '-a always,exit -F dir=${rundir} -F uid!=puppet -p wa -k Puppet_Run', - '-a always,exit -F dir=${ssldir} -F uid!=puppet -p wa -k Puppet_SSL' - ] - }} + let(:params) do + { + content: [ + '-a always,exit -F dir=${confdir} -F uid!=puppet -p wa -k Puppet_Config', + '-a always,exit -F dir=${logdir} -F uid!=puppet -p wa -k Puppet_Log', + '-a always,exit -F dir=${rundir} -F uid!=puppet -p wa -k Puppet_Run', + '-a always,exit -F dir=${ssldir} -F uid!=puppet -p wa -k Puppet_SSL', + ] + } + end it { - is_expected.to compile.with_all_deps - is_expected.to create_file("/etc/audit/rules.d/75.#{title}.rules").with_content(%r(^-a always,exit -F dir=)) - is_expected.to create_file("/etc/audit/rules.d/75.#{title}.rules").without_content(%r(^[^-])) + is_expected.to compile.with_all_deps + is_expected.to create_file("/etc/audit/rules.d/75.#{title}.rules").with_content(%r{^-a always,exit -F dir=}) + is_expected.to create_file("/etc/audit/rules.d/75.#{title}.rules").without_content(%r{^[^-]}) } end context 'with :content containing extra whitespace' do # :content string mocks a common pattern of declaring readable auditd rules. - let(:params) {{ - :content => ' + let(:params) do + { + content: ' -a always,exit -F dir=${confdir} -F uid!=puppet -p wa -k Puppet_Config -a always,exit -F dir=${logdir} -F uid!=puppet -p wa -k Puppet_Log -a always,exit -F dir=${rundir} -F uid!=puppet -p wa -k Puppet_Run -a always,exit -F dir=${ssldir} -F uid!=puppet -p wa -k Puppet_SSL ' - }} + } + end it { - is_expected.to compile.with_all_deps - is_expected.to create_file("/etc/audit/rules.d/75.#{title}.rules").with_content(%r(^-a always,exit -F dir=)) - is_expected.to create_file("/etc/audit/rules.d/75.#{title}.rules").without_content(%r(^[^-])) + is_expected.to compile.with_all_deps + is_expected.to create_file("/etc/audit/rules.d/75.#{title}.rules").with_content(%r{^-a always,exit -F dir=}) + is_expected.to create_file("/etc/audit/rules.d/75.#{title}.rules").without_content(%r{^[^-]}) } end context 'with :order specified' do - let(:params) {{ - :order => '10', - :content => '-a always,exit -F dir=${confdir} -F uid!=puppet -p wa -k Puppet_Config' - }} + let(:params) do + { + order: '10', + content: '-a always,exit -F dir=${confdir} -F uid!=puppet -p wa -k Puppet_Config' + } + end it { - is_expected.to compile.with_all_deps - is_expected.to create_file("/etc/audit/rules.d/#{params[:order]}.#{title}.rules").with_content(%r(#{Regexp.escape(params[:content])})) + is_expected.to compile.with_all_deps + is_expected.to create_file("/etc/audit/rules.d/#{params[:order]}.#{title}.rules").with_content(%r{#{Regexp.escape(params[:content])}}) } end context 'when set to :first' do - let(:params) {{ - :first => true, - :content => 'audit stuff' - }} + let(:params) do + { + first: true, + content: 'audit stuff' + } + end it { is_expected.to compile.with_all_deps - is_expected.to contain_file("/etc/audit/rules.d/10.#{title}.rules").with_content(%r(#{params[:content]})) + is_expected.to contain_file("/etc/audit/rules.d/10.#{title}.rules").with_content(%r{#{params[:content]}}) } end context 'when set to :absolute :first' do - let(:params) {{ - :first => true, - :absolute => true, - :content => 'audit stuff' - }} + let(:params) do + { + first: true, + absolute: true, + content: 'audit stuff' + } + end it { is_expected.to compile.with_all_deps - is_expected.to contain_file("/etc/audit/rules.d/01.#{title}.rules").with_content(%r(#{params[:content]})) + is_expected.to contain_file("/etc/audit/rules.d/01.#{title}.rules").with_content(%r{#{params[:content]}}) } end context 'when set to :prepend' do - let(:params) {{ - :prepend => true, - :content => 'audit stuff' - }} + let(:params) do + { + prepend: true, + content: 'audit stuff' + } + end it { is_expected.to compile.with_all_deps - is_expected.to contain_file("/etc/audit/rules.d/00.#{title}.rules").with_content(%r(#{params[:content]})) + is_expected.to contain_file("/etc/audit/rules.d/00.#{title}.rules").with_content(%r{#{params[:content]}}) } end end diff --git a/spec/functions/auditd/get_array_index_spec.rb b/spec/functions/auditd/get_array_index_spec.rb index f3dc6ed0..0fefb2b7 100644 --- a/spec/functions/auditd/get_array_index_spec.rb +++ b/spec/functions/auditd/get_array_index_spec.rb @@ -2,11 +2,9 @@ describe 'auditd::get_array_index' do let(:test_array) { ['elemA', 'elemB', 'elemC'] } - let(:long_test_array) { - array = [] - (0..99).each { |num| array << "elem#{num}" } - array - } + let(:long_test_array) do + (0..99).map { |num| "elem#{num}" } + end it 'returns the index 0-padded to 2 digits, when num_digits is not specified' do is_expected.to run.with_params('elemA', test_array).and_return('00') @@ -27,8 +25,7 @@ it 'fails when the element is not in the array' do expect { is_expected.to run.with_params('elemX', test_array) }.to raise_error( - /auditd::get_array_index: elemX is not found in/) + %r{auditd::get_array_index: elemX is not found in}, + ) end - end - diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index 1b21aa4d..5799a78a 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + # # ------------------------------------------------------------------------------ # NOTICE: **This file is maintained with puppetsync** @@ -90,7 +91,7 @@ def set_hieradata(hieradata) # If nothing else... c.default_facts = { production: { - #:fqdn => 'production.rspec.test.localdomain', + # :fqdn => 'production.rspec.test.localdomain', path: '/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin', concat_basedir: '/tmp' } @@ -151,9 +152,9 @@ def set_hieradata(hieradata) # sanitize hieradata if defined?(hieradata) - set_hieradata(hieradata.gsub(':', '_')) + set_hieradata(hieradata.tr(':', '_')) elsif defined?(class_name) - set_hieradata(class_name.gsub(':', '_')) + set_hieradata(class_name.tr(':', '_')) end end @@ -165,9 +166,7 @@ def set_hieradata(hieradata) end Dir.glob("#{RSpec.configuration.module_path}/*").each do |dir| - begin - Pathname.new(dir).realpath - rescue StandardError - raise "ERROR: The module '#{dir}' is not installed. Tests cannot continue." - end + Pathname.new(dir).realpath +rescue StandardError + raise "ERROR: The module '#{dir}' is not installed. Tests cannot continue." end diff --git a/spec/spec_helper_acceptance.rb b/spec/spec_helper_acceptance.rb index 9631ed6b..cfd86962 100644 --- a/spec/spec_helper_acceptance.rb +++ b/spec/spec_helper_acceptance.rb @@ -15,7 +15,6 @@ end end - RSpec.configure do |c| # ensure that environment OS is ready on each host fix_errata_on hosts @@ -29,29 +28,25 @@ # Configure all nodes in nodeset c.before :suite do + # Install modules and dependencies from spec/fixtures/modules + copy_fixture_modules_to(hosts) begin - # Install modules and dependencies from spec/fixtures/modules - copy_fixture_modules_to( hosts ) - begin - server = only_host_with_role(hosts, 'server') - rescue ArgumentError =>e - server = only_host_with_role(hosts, 'default') - end - - # Generate and install PKI certificates on each SUT - Dir.mktmpdir do |cert_dir| - run_fake_pki_ca_on(server, hosts, cert_dir ) - hosts.each{ |sut| copy_pki_to( sut, cert_dir, '/etc/pki/simp-testing' )} - end + server = only_host_with_role(hosts, 'server') + rescue ArgumentError => e + server = only_host_with_role(hosts, 'default') + end - # add PKI keys - copy_keydist_to(server) - rescue StandardError, ScriptError => e - if ENV['PRY'] - require 'pry'; binding.pry - else - raise e - end + # Generate and install PKI certificates on each SUT + Dir.mktmpdir do |cert_dir| + run_fake_pki_ca_on(server, hosts, cert_dir) + hosts.each { |sut| copy_pki_to(sut, cert_dir, '/etc/pki/simp-testing') } end + + # add PKI keys + copy_keydist_to(server) + rescue StandardError, ScriptError => e + raise e unless ENV['PRY'] + require 'pry' + binding.pry end end diff --git a/spec/unit/compliance_engine/compliance_engine_enforce_spec.rb b/spec/unit/compliance_engine/compliance_engine_enforce_spec.rb index 5a47bb02..0de7b520 100644 --- a/spec/unit/compliance_engine/compliance_engine_enforce_spec.rb +++ b/spec/unit/compliance_engine/compliance_engine_enforce_spec.rb @@ -7,14 +7,13 @@ # This is the class that needs to be added to the catalog last to make the # reporting work. describe 'compliance_markup', type: :class do - let(:params) do - { :report_types => ['full'] } + { report_types: ['full'] } end compliance_profiles = [ 'disa_stig', - 'nist_800_53:rev4' + 'nist_800_53:rev4', ] # A list of classes that we expect to be included for compliance @@ -22,61 +21,61 @@ # This needs to be well defined since we can also manipulate defined type # defaults expected_classes = [ - 'auditd' + 'auditd', ] allowed_failures = { 'documented_missing_parameters' => [ - ] + expected_classes.map{|c| Regexp.new("^(?!#{c}(::.*)?)")}, + ] + expected_classes.map { |c| Regexp.new("^(?!#{c}(::.*)?)") }, 'documented_missing_resources' => [ - ] + expected_classes.map{|c| Regexp.new("^(?!#{c}(::.*)?)")} + ] + expected_classes.map { |c| Regexp.new("^(?!#{c}(::.*)?)") } } on_supported_os.each do |os, os_facts| context "on #{os}" do compliance_profiles.each do |target_profile| context "with compliance profile '#{target_profile}'" do - let(:facts){ + let(:facts) do unless os_facts[:auditd_major_version] - if os_facts[:os][:release][:major] < '8' - os_facts[:auditd_major_version] = '2' - else - os_facts[:auditd_major_version] = '3' - end + os_facts[:auditd_major_version] = if os_facts[:os][:release][:major] < '8' + '2' + else + '3' + end end os_facts.merge({ - :target_compliance_profile => target_profile - }) - } - - let(:pre_condition) {%( - #{expected_classes.map{|c| %{include #{c}}}.join("\n")} - )} - - let(:hieradata){ 'compliance-engine' } - - it { is_expected.to compile } - - let(:compliance_report) { - @compliance_report ||= JSON.load( - catalogue.resource("File[#{facts[:puppet_vardir]}/compliance_report.json]")[:content] + target_compliance_profile: target_profile + }) + end + let(:compliance_report) do + @compliance_report ||= JSON.parse( + catalogue.resource("File[#{facts[:puppet_vardir]}/compliance_report.json]")[:content], ) @compliance_report - } - - let(:compliance_profile_data) { + end + let(:compliance_profile_data) do @compliance_profile_data ||= compliance_report['compliance_profiles'][target_profile] @compliance_profile_data - } + end + + let(:pre_condition) do + %( + #{expected_classes.map { |c| %(include #{c}) }.join("\n")} + ) + end + + let(:hieradata) { 'compliance-engine' } + + it { is_expected.to compile } - it 'should have a compliance profile report' do - expect(compliance_profile_data).to_not be_nil + it 'has a compliance profile report' do + expect(compliance_profile_data).not_to be_nil end - it 'should have a 100% compliant report' do + it 'has a 100% compliant report' do expect(compliance_profile_data['summary']['percent_compliant']).to eq(100) end @@ -96,29 +95,29 @@ # classes included, this report may be useless and is disabled by # default. # - 'documented_missing_resources' + 'documented_missing_resources', ] report_validators.each do |report_section| - it "should have no issues with the '#{report_section}' report" do + it "has no issues with the '#{report_section}' report" do if compliance_profile_data[report_section] # This just gets us a good print out of what went wrong - compliance_profile_data[report_section].delete_if{ |item| - rm = false - - Array(allowed_failures[report_section]).each do |allowed| - if allowed.is_a?(Regexp) - if allowed.match?(item) - rm = true - break - end - else - rm = (allowed == item) + compliance_profile_data[report_section].delete_if do |item| + rm = false + + Array(allowed_failures[report_section]).each do |allowed| + if allowed.is_a?(Regexp) + if allowed.match?(item) + rm = true + break end + else + rm = (allowed == item) end + end - rm - } + rm + end expect(compliance_profile_data[report_section]).to eq([]) end