Module: Mihari::Commands::Search

Includes:
Mixins::Database, Mixins::ErrorNotification, Mixins::Rule
Included in:
Mihari::CLI::Main
Defined in:
lib/mihari/commands/search.rb

Class Method Summary collapse

Methods included from Mixins::ErrorNotification

#with_error_notification

Methods included from Mixins::Rule

#initialize_rule_yaml, #load_erb_yaml, #load_rule, #load_yaml_from_db, #load_yaml_from_file, #rule_template, #validate_rule!

Methods included from Mixins::Database

#with_db_connection

Class Method Details

.included(thor) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/mihari/commands/search.rb', line 10

def self.included(thor)
  thor.class_eval do
    desc "search [RULE]", "Search by a rule"
    method_option :yes, type: :boolean, aliases: "-y", desc: "yes to overwrite the rule in the database"
    def search_by_rule(path_or_id)
      rule = load_rule(path_or_id)

      # validate
      begin
        validate_rule! rule
      rescue RuleValidationError => e
        raise e
      end

      # check update
      id = rule.id
      yes = options["yes"] || false
      unless yes
        with_db_connection do
          rule_ = Mihari::Rule.find(id)
          next if rule.yaml == rule_.yaml
          return unless yes?("This operation will overwrite the rule in the database (Rule ID: #{id}). Are you sure you want to update the rule? (yes/no)")
        rescue ActiveRecord::RecordNotFound
          next
        end
      end

      analyzer = rule.to_analyzer

      with_error_notification do
        alert = analyzer.run

        if alert
          data = Mihari::Entities::Alert.represent(alert)
          puts JSON.pretty_generate(data.as_json)
        else
          Mihari.logger.info "There is no new artifact"
        end

        # record a rule
        with_db_connection do
          model = rule.to_model
          model.save
        rescue ActiveRecord::RecordNotUnique
          nil
        end
      end
    end
  end
end