Class: FreeBsdPorts

Inherits:
PortsInfo show all
Defined in:
lib/resources/port.rb

Overview

extracts information from sockstat

Instance Attribute Summary

Attributes inherited from PortsInfo

#inspec

Instance Method Summary collapse

Methods inherited from PortsInfo

#initialize

Constructor Details

This class inherits a constructor from PortsInfo

Instance Method Details

#infoObject



247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/resources/port.rb', line 247

def info
  cmd = inspec.command('sockstat -46l')
  return nil if cmd.exit_status.to_i != 0

  ports = []
  # split on each newline
  cmd.stdout.each_line do |line|
    port_info = parse_sockstat_line(line)

    # push data, if not headerfile
    next unless %w{tcp tcp6 udp udp6}.include?(port_info[:protocol])
    ports.push(port_info)
  end
  ports
end

#parse_net_address(net_addr, protocol) ⇒ Object



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/resources/port.rb', line 263

def parse_net_address(net_addr, protocol)
  case protocol
  when 'tcp4', 'udp4'
    # replace * with 0.0.0.0
    net_addr = net_addr.gsub(/^\*:/, '0.0.0.0:') if /^*:(\d+)$/.match(net_addr)
    ip_addr = URI('addr://'+net_addr)
    host = ip_addr.host
    port = ip_addr.port
  when 'tcp6', 'udp6'
    return [] if net_addr == '*:*' # abort for now
    # replace * with 0:0:0:0:0:0:0:0
    net_addr = net_addr.gsub(/^\*:/, '0:0:0:0:0:0:0:0:') if /^*:(\d+)$/.match(net_addr)
    # extract port
    ip6 = /^(\S+):(\d+)$/.match(net_addr)
    ip6addr = ip6[1]
    ip_addr = URI("addr://[#{ip6addr}]:#{ip6[2]}")
    # replace []
    host = ip_addr.host[1..ip_addr.host.size-2]
    port = ip_addr.port
  end
  [host, port]
rescue URI::InvalidURIError => e
  warn "Could not parse #{net_addr}, #{e}"
  nil
end

#parse_sockstat_line(line) ⇒ Object



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
# File 'lib/resources/port.rb', line 289

def parse_sockstat_line(line)
  # 1 - USER, 2 - COMMAND, 3 - PID, 4 - FD 5 - PROTO, 6 - LOCAL ADDRESS, 7 - FOREIGN ADDRESS
  parsed = /^(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)$/.match(line)
  return {} if parsed.nil?

  # extract ip information
  protocol = parsed[5].downcase
  host, port = parse_net_address(parsed[6], protocol)
  return {} if host.nil? or port.nil?

  # extract process
  process = parsed[2]

  # extract PID
  pid = parsed[3]
  pid = pid.to_i if /^\d+$/.match(pid)

  # map tcp4 and udp4
  protocol = 'tcp' if protocol.eql?('tcp4')
  protocol = 'udp' if protocol.eql?('udp4')

  # map data
  {
    port: port,
    address: host,
    protocol: protocol,
    process: process,
    pid: pid,
  }
end