Class: Fluent::Plugin::WindowsEventLog2Input

Inherits:
Input
  • Object
show all
Defined in:
lib/fluent/plugin/in_windows_eventlog2.rb

Defined Under Namespace

Classes: ReconnectError

Constant Summary collapse

DEFAULT_STORAGE_TYPE =
'local'
KEY_MAP =
{"ProviderName"      => ["ProviderName",          :string],
"ProviderGUID"      => ["ProviderGUID",          :string],
"EventID"           => ["EventID",               :string],
"Qualifiers"        => ["Qualifiers",            :string],
"Level"             => ["Level",                 :string],
"Task"              => ["Task",                  :string],
"Opcode"            => ["Opcode",                :string],
"Keywords"          => ["Keywords",              :string],
"TimeCreated"       => ["TimeCreated",           :string],
"EventRecordID"     => ["EventRecordID",         :string],
"ActivityID"        => ["ActivityID",            :string],
"RelatedActivityID" => ["RelatedActivityID",     :string],
"ProcessID"         => ["ProcessID",             :string],
"ThreadID"          => ["ThreadID",              :string],
"Channel"           => ["Channel",               :string],
"Computer"          => ["Computer",              :string],
"UserID"            => ["UserID",                :string],
"Version"           => ["Version",               :string],
"Description"       => ["Description",           :string],
"EventData"         => ["EventData",             :array]}
GROUP_DELIMITER =
"\r\n\r\n".freeze
RECORD_DELIMITER =
"\r\n\t".freeze
FIELD_DELIMITER =
"\t\t".freeze
NONE_FIELD_DELIMITER =
"\t".freeze

Instance Method Summary collapse

Instance Method Details

#bookmark_validator(bookmarkXml, channel) ⇒ Object



257
258
259
260
261
262
263
264
265
266
267
268
269
270
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 257

def bookmark_validator(bookmarkXml, channel)
  return false if bookmarkXml.empty?

  evtxml = WinevtBookmarkDocument.new
  parser = Nokogiri::XML::SAX::Parser.new(evtxml)
  parser.parse(bookmarkXml)
  result = evtxml.result
  if !result.empty? && (result[:channel].downcase == channel.downcase) && result[:is_current]
    true
  else
    log.warn "This stored bookmark is incomplete for using. Referring `read_existing_events` parameter to subscribe: #{bookmarkXml}, channel: #{channel}"
    false
  end
end

#clear_subscritpionsObject



205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 205

def clear_subscritpions
  @subscriptions.keys.each do |ch|
    subscription = @subscriptions.delete(ch)
    if subscription
      if subscription.cancel
        log.debug "channel (#{ch}) subscription is cancelled."
        subscription.close
        log.debug "channel (#{ch}) subscription handles are closed forcibly."
      end
    end
  end
  @timers.keys.each do |ch|
    timer = @timers.delete(ch)
    if timer
      event_loop_detach(timer)
      log.debug "channel (#{ch}) subscription watcher is detached."
    end
  end
end

#configure(conf) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 77

def configure(conf)
  super
  @session = nil
  @chs = []
  @subscriptions = {}
  @all_chs = Winevt::EventLog::Channel.new
  @all_chs.force_enumerate = false
  @timers = {}

  if @read_all_channels
    @all_chs.each do |ch|
      uch = ch.strip.downcase
      @chs.push([uch, @read_existing_events])
    end
  end

  @read_existing_events = @read_from_head || @read_existing_events
  if @channels.empty? && @subscribe_configs.empty? && !@read_all_channels
    @chs.push(['application', @read_existing_events, nil])
  else
    @channels.map {|ch| ch.strip.downcase }.uniq.each do |uch|
      @chs.push([uch, @read_existing_events, nil])
    end
    @subscribe_configs.each do |subscribe|
      if subscribe.remote_server
        @session = Winevt::EventLog::Session.new(subscribe.remote_server,
                                                 subscribe.remote_domain,
                                                 subscribe.remote_username,
                                                 subscribe.remote_password)

        log.debug("connect to remote box (server: #{subscribe.remote_server}) domain: #{subscribe.remote_domain} username: #{subscribe.remote_username})")
      end
      subscribe.channels.map {|ch| ch.strip.downcase }.uniq.each do |uch|
        @chs.push([uch, subscribe.read_existing_events, @session])
      end
    end
  end
  @chs.uniq!
  @keynames = @keys.map {|k| k.strip }.uniq
  if @keynames.empty?
    @keynames = KEY_MAP.keys
  end

  @tag = tag
  @bookmarks_storage = storage_create(usage: "bookmarks")
  @winevt_xml = false
  @parser = nil
  if @render_as_xml
    @parser = parser_create
    @winevt_xml = @parser.respond_to?(:winevt_xml?) && @parser.winevt_xml?
    class << self
      alias_method :on_notify, :on_notify_xml
    end
  else
    class << self
      alias_method :on_notify, :on_notify_hash
    end
  end

  if @render_as_xml && @preserve_qualifiers_on_hash
    raise Fluent::ConfigError, "preserve_qualifiers_on_hash must be used with Hash object rendering(render_as_xml as false)."
  end
  if !@render_as_xml && !@preserve_qualifiers_on_hash
    @keynames.delete('Qualifiers')
  elsif @parser.respond_to?(:preserve_qualifiers?) && !@parser.preserve_qualifiers?
    @keynames.delete('Qualifiers')
  end
  @keynames.delete('EventData') if @parse_description

  locale = Winevt::EventLog::Locale.new
  if @description_locale && unsupported_locale?(locale, @description_locale)
    raise Fluent::ConfigError, "'#{@description_locale}' is not supported. Supported locales are: #{locale.each.map{|code, _desc| code}.join(" ")}"
  end
end

#escape_channel(ch) ⇒ Object



272
273
274
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 272

def escape_channel(ch)
  ch.gsub(/[^a-zA-Z0-9\s]/, '_')
end

#initalizeObject



71
72
73
74
75
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 71

def initalize
  super
  @chs = []
  @keynames = []
end

#on_notify(ch, subscribe) ⇒ Object



276
277
278
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 276

def on_notify(ch, subscribe)
  # for safety.

end

#on_notify_hash(ch, subscribe) ⇒ Object



322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 322

def on_notify_hash(ch, subscribe)
  es = Fluent::MultiEventStream.new
  begin
    subscribe.each do |record, message, string_inserts|
      record["Description"] = message
      record["EventData"] = string_inserts
      h = {}
      @keynames.each do |k|
        type = KEY_MAP[k][1]
        value = record[KEY_MAP[k][0]]
        h[k]=case type
             when :string
               value.to_s
             when :array
               value.map {|v| v.to_s}
             else
               raise "Unknown value type: #{type}"
             end
      end
      parse_desc(h) if @parse_description
      es.add(Fluent::Engine.now, h)
    end
    router.emit_stream(@tag, es)
    @bookmarks_storage.put(ch, subscribe.bookmark)
    log.trace "Collecting Windows EventLog from #{ch} channel. Collected size: #{es.size}"
  rescue Winevt::EventLog::Query::Error => e
    log.warn "Invalid Hash data on #{ch}.", error: e
    log.warn_backtrace
  end
end

#on_notify_xml(ch, subscribe) ⇒ Object



280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 280

def on_notify_xml(ch, subscribe)
  es = Fluent::MultiEventStream.new
  begin
    subscribe.each do |xml, message, string_inserts|
      @parser.parse(xml) do |time, record|
        # record.has_key?("EventData") for none parser checking.

        if @winevt_xml
          record["Description"] = message
          record["EventData"] = string_inserts

          h = {}
          @keynames.each do |k|
            type = KEY_MAP[k][1]
            value = record[KEY_MAP[k][0]]
            h[k]=case type
                 when :string
                   value.to_s
                 when :array
                   value.map {|v| v.to_s}
                 else
                   raise "Unknown value type: #{type}"
                 end
          end
          parse_desc(h) if @parse_description
          es.add(Fluent::Engine.now, h)
        else
          record["Description"] = message
          record["EventData"] = string_inserts
          # for none parser

          es.add(Fluent::Engine.now, record)
        end
      end
    end
    router.emit_stream(@tag, es)
    @bookmarks_storage.put(ch, subscribe.bookmark)
    log.trace "Collecting Windows EventLog from #{ch} channel. Collected size: #{es.size}"
  rescue Winevt::EventLog::Query::Error => e
    log.warn "Invalid XML data on #{ch}.", error: e
    log.warn_backtrace
  end
end

#parse_desc(record) ⇒ Object



360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 360

def parse_desc(record)
  desc = record.delete("Description".freeze)
  return if desc.nil?

  elems = desc.split(GROUP_DELIMITER)
  record['DescriptionTitle'] = elems.shift
  previous_key = nil
  elems.each { |elem|
    parent_key = nil
    elem.split(RECORD_DELIMITER).each { |r|
      key, value = if r.index(FIELD_DELIMITER)
                     r.split(FIELD_DELIMITER)
                   else
                     r.split(NONE_FIELD_DELIMITER)
                   end
      key = "" if key.nil?
      key.chop!  # remove ':' from key

      if value.nil?
        parent_key = to_key(key)
      else
        # parsed value sometimes contain unexpected "\t". So remove it.

        value.strip!
        # merge empty key values into the previous non-empty key record.

        if key.empty?
          record[previous_key] = [record[previous_key], value].flatten.reject {|e| e.nil?}
        elsif parent_key.nil?
          record[to_key(key)] = value
        else
          k = "#{parent_key}.#{to_key(key)}"
          record[k] = value
        end
      end
      # XXX: This is for empty privileges record key.

      # We should investigate whether an another case exists or not.

      previous_key = to_key(key) unless key.empty?
    }
  }
end

#refresh_subscriptionsObject



193
194
195
196
197
198
199
200
201
202
203
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 193

def refresh_subscriptions
  clear_subscritpions

  @chs.each do |ch, read_existing_events, session|
    retry_on_error(ch) do
      ch, subscribe = subscription(ch, read_existing_events, session)
      @subscriptions[ch] = subscribe
    end
  end
  subscribe_channels(@subscriptions)
end

#retry_on_error(channel, times: 15) ⇒ Object



177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 177

def retry_on_error(channel, times: 15)
  try = 0
  begin
    log.debug "Retry to subscribe for #{channel}...." if try > 1
    try += 1
    yield
    log.info "Retry to subscribe for #{channel} succeeded." if try > 1
    try = 0
  rescue Winevt::EventLog::Subscribe::RemoteHandlerError => e
    raise ReconnectError, "Retrying limit is exceeded." if try > times
    log.warn "#{e.message}. Remaining retry count(s): #{times - try}"
    sleep 2**try
    retry
  end
end

#shutdownObject



165
166
167
168
169
170
171
172
173
174
175
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 165

def shutdown
  super

  @subscriptions.keys.each do |ch|
    subscription = @subscriptions.delete(ch)
    if subscription
      subscription.cancel
      log.debug "channel (#{ch}) subscription is canceled."
    end
  end
end

#startObject



156
157
158
159
160
161
162
163
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 156

def start
  super

  refresh_subscriptions
  if @refresh_subscription_interval
    timer_execute(:in_windows_eventlog_refresh_subscription_timer, @refresh_subscription_interval, &method(:refresh_subscriptions))
  end
end

#subscribe_channels(subscriptions) ⇒ Object



247
248
249
250
251
252
253
254
255
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 247

def subscribe_channels(subscriptions)
  subscriptions.each do |ch, subscribe|
    log.trace "Subscribing Windows EventLog at #{ch} channel"
    @timers[ch] = timer_execute("in_windows_eventlog_#{escape_channel(ch)}".to_sym, @read_interval) do
      on_notify(ch, subscribe)
    end
    log.debug "channel (#{ch}) subscription is subscribed."
  end
end

#subscription(ch, read_existing_events, remote_session) ⇒ Object



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 225

def subscription(ch, read_existing_events, remote_session)
  bookmarkXml = @bookmarks_storage.get(ch) || ""
  bookmark = nil
  if bookmark_validator(bookmarkXml, ch)
    bookmark = Winevt::EventLog::Bookmark.new(bookmarkXml)
  end
  subscribe = Winevt::EventLog::Subscribe.new
  subscribe.read_existing_events = read_existing_events
  begin
    subscribe.subscribe(ch, event_query, bookmark, remote_session)
    if !@render_as_xml && @preserve_qualifiers_on_hash
      subscribe.preserve_qualifiers = @preserve_qualifiers_on_hash
    end
  rescue Winevt::EventLog::Query::Error => e
    raise Fluent::ConfigError, "Invalid Bookmark XML is loaded. #{e}"
  end
  subscribe.render_as_xml = @render_as_xml
  subscribe.rate_limit = @rate_limit
  subscribe.locale = @description_locale if @description_locale
  [ch, subscribe]
end

#to_key(key) ⇒ Object



399
400
401
402
403
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 399

def to_key(key)
  key.downcase!
  key.gsub!(' '.freeze, '_'.freeze)
  key
end

#unsupported_locale?(locale, description_locale) ⇒ Boolean

Returns:

  • (Boolean)


152
153
154
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 152

def unsupported_locale?(locale, description_locale)
  locale.each.select {|c, _d| c.downcase == description_locale.downcase}.empty?
end