Python Port Knocking Script

Simple port knocking script using scapy because scapy is awesome and I’ll take any opportunity to use it. Also, Python lives on all of my devices, so I can use one tool across all of them. I found a script here that I then modified to suit my needs. The author, snj, seems to have made it for a CTF or something similar, so there was a lot there that I did not need.

TODO:
Right now the IP and port numbers are hard-coded in. In the future, we could improve the script by getting them from arguments. Additionally, importing everything from scapy takes forever. The biggest improvement would be to either not use scapy, or figure out what, specifically, we need from scapy, and import only those things.

#!/usr/bin/python

# https://gist.github.com/snj/9382c63ad49050e1b9ba

from scapy.all import *
import time

def knock(ports):
    print "[*] Knocking on ports "+str(ports)
    for dport in range(0, len(ports)):
        ip = IP(dst = "192.168.1.59")
        SYN = ip/TCP(dport=ports[dport], flags="S", window=14600, options=[('MSS',1460)])
        send(SYN)

def execKnock(ports):
    knock(ports)
    print "Port opened"
    time.sleep(10)
    print "Port closed"

oports = [7303,40303,33528]
cports = [33528,40303,7303]
execKnock(oports)

Raspberry Pi – iptables Script

While we don’t have many rules in our firewall, it can end up being convenient to have a script on-hand so that we can automatically restore the rules that we want. I copied the structure from these guys and filled my own rules in (I left some of their intriguing bits in as comments for the time being).

nano /root/setupFirewall.sh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#!/bin/bash
# Set up iptables baseline

# Flush rules to work from a clean slate
iptables -F

# Set default policies for INPUT, FORWARD, and OUTPUT chains
#iptables -P INPUT DROP
#iptables -P FORWARD DROP
#iptables -P OUTPUT ACCEPT

# Allow access for localhost
iptables -A INPUT -i lo -j ACCEPT

# Accept packets belonging to established and related connections
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT

# Add access from other computers on our network
#iptables -A INPUT -s <IP Address 1> -j ACCEPT
#iptables -A INPUT -s <IP Address n> -j ACCEPT

# Open port for HTTP
iptables -A INPUT -p tcp --dport 80 -j ACCEPT

# Deny All
iptables -A INPUT -j DROP

# List iptables chains
iptables -L --line-numbers
chmod 700 /root/setupFirewall.sh

Don’t forget that last bit. Not only does it allow us to execute the script, but probably more importantly it hides our firewall configuration from unauthorized eyes. Again, obscurity is NOT security, but it can help augment security.