Perimeter firewall scanning for open outbound ports

One of the main principles to follow when setting up your perimeter firewall is to only allow traffic that is absolutely necessary through, and explicitly deny all other traffic.

Being able to see what ports are available on the perimeter will help you to understand the attack surface better and what ports are available for use.

Setting up the attacker machine

For this we will need an external attack box. We will setup a python listener script and redirect all traffic to port 9999.

Python listener script

#!/usr/bin/python

import re
import socket
import struct
import signal

open_ports = {}

def handler(signum, frame):
    res = input("Ctrl-c was pressed. Do you really want to exit? y/n ")
    if res == 'y':
        print('')
        print(open_ports)
        exit(1)

signal.signal(signal.SIGINT, handler)

SO_ORIGINAL_DST = 80

s = socket.socket()
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('0.0.0.0', 9999))
s.listen(10)

print('[i] Started listener on port 9999 ...')
print('')

while True:
    csock, caddr = s.accept()
    orig_dst = csock.getsockopt(socket.SOL_IP, SO_ORIGINAL_DST, 16)

    orig_port = struct.unpack('>H', orig_dst[2:4])
    orig_addr = socket.inet_ntoa(orig_dst[4:8])

    if caddr[0] not in open_ports:
        open_ports[caddr[0]] = []

    open_ports[caddr[0]].append(orig_port)

    print('[i] Connection from: ', caddr)
    print('[*] Connection attempt to: ', orig_port)

Setting up the NAT forward rule

We will need to setup a NAT rule to forward all incoming traffic to port 9999 (our python listening port).

sudo iptables -t nat -A PREROUTING -p tcp -d 192.168.99.16 -j REDIRECT --to-ports 9999

Pre-routing – This chain is applied to any incoming packet once it is entered the network stack and this chain is processed even before any routing decision has been made regarding the final destination of the packet.

-t nat: This table is consulted when a packet that creates a new connection is encountered. It consists of three built-ins: PREROUTING (for altering packets as soon as they come in), OUTPUT (for altering locally-generated packets before routing), and POSTROUTING (for altering packets as they are about to go out).

To view the iptables rules use the following command:

sudo iptables -t nat -v -L -n --line-number

Deleting the rule:

sudo iptables -t nat -D PREROUTING 1

Setting up the victim machine

Using the Invoke-PortScan.ps1 module from PowerSploit you can now start the port scan against your attacker box. Any reply on the attacker box indicates that port allows outbound traffic through the firewall

Invoke-Portscan -Hosts 192.168.99.16 -T 4 -Ports 1-65535

Last updated