Skip to content

Instantly share code, notes, and snippets.

@superswan
Last active November 28, 2022 15:35
Show Gist options
  • Save superswan/7fbb7515e5aa3b80a13a24bdb0ffcbdc to your computer and use it in GitHub Desktop.
Save superswan/7fbb7515e5aa3b80a13a24bdb0ffcbdc to your computer and use it in GitHub Desktop.
Block ASN on SonicWall via SSH CLI
#!/usr/bin/env python
# ASN blocker
import sys, paramiko
from paramiko_expect import SSHClientInteraction
import socket
import struct
def cidr_to_netmask(cidr):
network, net_bits = cidr.split('/')
host_bits = 32 - int(net_bits)
netmask = socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << host_bits)))
return network, netmask
sonicwall_ip = '192.168.2.254'
SSH_USER = 'admin'
PROMPT = 'admin@>'
ADDR_OBJ = '_BL_AUTO_'
password = input("Password> ")
with open('blacklist.txt', 'r') as fin:
blacklist = fin.read().splitlines()
client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(sonicwall_ip, port=22, username=SSH_USER, password=password)
with SSHClientInteraction(client, timeout=0.8, display=True) as interact:
interact.expect(PROMPT)
interact.send("configure")
if not (interact.expect('config()#')):
quit()
for i,host in enumerate(blacklist):
networkid, netmask = cidr_to_netmask(host)
addr_obj_name = ADDR_OBJ + str(i)
address_object = f"address-object ipv4 {addr_obj_name} zone WAN"
address_prompt = f"(add-ipv4-address-object[{addr_obj_name}])#"
interact.expect(address_prompt)
interact.send(address_object)
interact.expect(address_prompt)
interact.send(f"network {networkid} {netmask}")
interact.expect('config()#')
interact.send("exit")
interact.expect('config()#')
interact.send("commit")
output = interact.current_output_clean
print(output)

Requires paramiko, paramiko-expect

** Fabric doesn't work on SonicWall as it doesn't support exec_command() **

Get ASN Blocklist from

https://www.enjen.net/asn-blocklist/index.php?asn=22363&type=iplist add &api=1 to URL for text file

Reddit thread on creating address objects from cli

start by SSH'ing to the device and type

configure

create object with name PC1 with IP 1.1.1.1 (example)

address-object ipv4 PC1 zone WAN
host 1.1.1.1
exit

naturally, you can create multiple objects, but need to 'exit' after each one

create object group with name BLOCKLIST

(note, when you create a group, it will put you in 'group' config mode)

address-group ipv4 BLOCKLIST add object PC1 to object group BLOCKLIST

(this will only work when you're in the 'group' config mode)

address-object ipv4 PC1 create rule from WAN<->WAN

access-rule from WAN to WAN action deny source address group BLOCKLIST make sure to commit at the end

commit

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment