Skip to content

patch for destination field #24

@ghost

Description

I do not consider this patch copyrightable.

commit f15289ad055d9d575653651019253e3097641bd6
Author: Cameron Nemo <[email protected]>
Date:   Thu Jul 30 14:14:51 2020 -0700

    feat: assign network to destination field
    
    It can be desirable to know which specific network was matched,
    so I added an option to set a destination field based on that info.

diff --git a/lib/logstash/filters/cidr.rb b/lib/logstash/filters/cidr.rb
index 3bb19b0..7ee2a63 100644
--- a/lib/logstash/filters/cidr.rb
+++ b/lib/logstash/filters/cidr.rb
@@ -56,6 +56,9 @@ class LogStash::Filters::CIDR < LogStash::Filters::Base
   # pointed by network_path.
   config :separator, :validate => :string, :default => "\n"
 
+  # The destination field where the matching IP network is written.
+  config :destination, :validate => :string
+
   public
   def register
     rw_lock = java.util.concurrent.locks.ReentrantReadWriteLock.new
@@ -169,6 +172,9 @@ class LogStash::Filters::CIDR < LogStash::Filters::Base
     address.product(network).each do |a, n|
       @logger.debug("Checking IP inclusion", :address => a, :network => n)
       if n.include?(a)
+        if @destination
+          event.set(@destination, n.to_s + '/' + n.prefix.to_s)
+        end
         filter_matched(event)
         return
       end
diff --git a/spec/filters/cidr_spec.rb b/spec/filters/cidr_spec.rb
index 04511b8..b4b7835 100644
--- a/spec/filters/cidr_spec.rb
+++ b/spec/filters/cidr_spec.rb
@@ -188,4 +188,24 @@ describe LogStash::Filters::CIDR do
       expect { subject.register }.to raise_error(LogStash::ConfigurationError)
     end
   end
+
+  describe "destination" do
+    let(:config) { Hash.new }
+    config <<-CONFIG
+      filter {
+        cidr {
+          address     => "%{clientip}"
+          network     => ["192.168.1.0/24"]
+          destination => "clientnet"
+        }
+      }
+    CONFIG
+
+    sample("clientip" => "192.168.1.1") do
+      expect(subject.get("clientnet")).to eq("192.168.1.0/24")
+    end
+    sample("clientip" => "192.168.2.1") do
+      expect(subject.get("clientnet").nil?).to eq(true)
+    end
+  end
 end

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions