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],
"User"              => ["User",                  :string],
"Version"           => ["Version",               :string],
"Description"       => ["Description",           :string],
"EventData"         => ["EventData",             :array]}
RESERVED_RECORD_KEYS =
(KEY_MAP.keys + ["DescriptionTitle"]).freeze
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_valid?(bookmarkXml, channel) ⇒ Boolean

Returns:

  • (Boolean)


295
296
297
298
299
300
301
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 295

def bookmark_valid?(bookmarkXml, channel)
  if @@bookmark_parser_avaiable
    bookmark_valid_strictly?(bookmarkXml, channel)
  else
    bookmarklist_is_not_empty?(bookmarkXml, channel)
  end
end

#bookmark_valid_strictly?(bookmarkXml, channel) ⇒ Boolean

Returns:

  • (Boolean)


303
304
305
306
307
308
309
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 303

def bookmark_valid_strictly?(bookmarkXml, channel)
  evtxml = WinevtBookmarkDocument.new
  parser = Nokogiri::XML::SAX::Parser.new(evtxml)
  parser.parse(bookmarkXml)
  result = evtxml.result
  !result.empty? && (result[:channel].downcase == channel.downcase) && result[:is_current]
end

#bookmarklist_is_not_empty?(bookmarkXml, channel) ⇒ Boolean

Returns:

  • (Boolean)


311
312
313
314
315
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 311

def bookmarklist_is_not_empty?(bookmarkXml, channel)
  # Empty example: "<BookmarkList>\r\n</BookmarkList>"
  # Not empty example: "<BookmarkList>\r\n  <Bookmark Channel='Setup' RecordId='777' IsCurrent='true'/>\r\n</BookmarkList>"
  bookmarkXml.include?("Channel")
end

#clear_subscritpionsObject



235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 235

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



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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 89

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_config = @parser_configs.first
    if parser_config["@type"] == "windows_eventlog2_dummy"
      @parser = parser_create(usage: "parse_xml", type: "winevt_xml", conf: conf.elements("parse").first)
    else
      @parser = parser_create
    end
    @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
  if @render_as_xml && !@preserve_sid_on_hash
    raise Fluent::ConfigError, "preserve_sid_on_hash is effective with Hash object rendering(render_as_xml as false)."
  end
  if @render_as_xml
    @keynames.delete('User')
  end
  if !@render_as_xml && !@preserve_sid_on_hash
    @keynames.delete('UserID')
  end

  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



317
318
319
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 317

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

#initalizeObject



83
84
85
86
87
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 83

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

#on_notify(ch, subscribe) ⇒ Object



321
322
323
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 321

def on_notify(ch, subscribe)
  # for safety.
end

#on_notify_hash(ch, subscribe) ⇒ Object



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
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 367

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



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
352
353
354
355
356
357
358
359
360
361
362
363
364
365
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 325

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



405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 405

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, -1)
                   else
                     r.split(NONE_FIELD_DELIMITER, -1)
                   end
      key = +"" if key.nil?
      key.sub!(/:\s*\z/, '')  # remove ':' from key
      k = parent_key.nil? ? to_key(key) : "#{parent_key}#{@description_key_delimiter}#{to_key(key)}"
      taken = record.key?(k) || RESERVED_RECORD_KEYS.include?(k)
      if value.nil?
        unless key.empty?
          previous_key = taken ? nil : k
          parent_key = to_key(key)
        end
      else
        # parsed value sometimes contain unexpected "\t". So remove it.
        value.strip!
        # merge empty key values into the previous non-empty key record.
        # XXX: This is for empty privileges record key.
        # We should investigate whether an another case exists or not.
        if key.empty?
          record[previous_key] = [record[previous_key], value].flatten.reject {|e| e.nil?} if previous_key
        elsif taken
          previous_key = nil
        else
          record[k] = value
          previous_key = k
        end
      end
    }
  }
end

#refresh_subscriptionsObject



219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 219

def refresh_subscriptions
  clear_subscritpions

  @chs.each do |ch, read_existing_events, session|
    retry_on_error(ch) do
      begin
        ch, subscribe = subscription(ch, read_existing_events, session)
        @subscriptions[ch] = subscribe
      rescue Winevt::EventLog::ChannelNotFoundError => e
        log.warn "#{e.message}"
      end
    end
  end
  subscribe_channels(@subscriptions)
end

#retry_on_error(channel, times: 15) ⇒ Object



203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 203

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



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

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



182
183
184
185
186
187
188
189
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 182

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



285
286
287
288
289
290
291
292
293
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 285

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



255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 255

def subscription(ch, read_existing_events, remote_session)
  bookmark = nil
  bookmarkXml = @bookmarks_storage.get(ch) || ""
  unless bookmarkXml.empty?
    if bookmark_valid?(bookmarkXml, ch)
      bookmark = Winevt::EventLog::Bookmark.new(bookmarkXml)
    else
      log.warn "This stored bookmark is incomplete for using. Referring `read_existing_events` parameter to subscribe: #{bookmarkXml}, channel: #{ch}"
    end
  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
    if !@render_as_xml && !@preserve_sid_on_hash
      subscribe.preserve_sid = @preserve_sid_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



448
449
450
451
452
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 448

def to_key(key)
  key.downcase! if @downcase_description_keys
  key.gsub!(' '.freeze, @description_word_delimiter)
  key
end

#unsupported_locale?(locale, description_locale) ⇒ Boolean

Returns:

  • (Boolean)


178
179
180
# File 'lib/fluent/plugin/in_windows_eventlog2.rb', line 178

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