# -*- coding: binary -*-

module Msf::Exploit::Remote::HTTP::NagiosXi::Version
  include Msf::Exploit::Remote::HTTP::NagiosXi::URIs

  # Versions of NagiosXI pre-5.2 have different formats (5r1.0, 2014r2.7, 2012r2.8b, etc.) that Rex cannot handle,
  # so we set pre-5.2 versions to 1.0.0 for easier Rex comparison because the module only works on post-5.2 versions.
  PRE_5_2_VERSION_REGEX = '^\d{4}r\d(?:\.\d)?(?:(?:RC\d)|(?:[a-z]{1,3}))?$'

  # Extracts the Nagios XI version information from an HTTP response body obtained after authentication.
  # Works for index.php and perhaps other backend pages.
  #
  # @param res_backend [String] HTTP response body
  # @return [String, nil], String containing the Nagios XI version if successful, nil otherwise
  def nagios_xi_version(res_backend)
    version = res_backend.scan(/product=nagiosxi&version=(.+?)&/)&.flatten&.first
  end

  # Tries to obtain the Nagios XI version from the login.php page. This will not work for older Nagios XI versions.
  #
  # @return [Array], Array containing the Nagios XI version and nil if successful, otherwise Array containing an error code and an error message
  def nagios_xi_version_no_auth
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => nagios_xi_login_url,
    })

    unless res
      return [1, 'Connection failed']
    end

    unless [200,302].include?(res.code) && res.body.include?('>Nagios XI<')
      return [3, 'Target is not a Nagios XI application']
    end

    nagios_version = res.body.scan(/name="version" value="(\d+\.\d+\.\d+)">/)&.flatten&.first

    if nagios_version.nil?
      return [2, 'Unable to obtain Nagios XI version from the login page.']
    end

    [nagios_version, nil]
  end

end

