Skip to content

Instantly share code, notes, and snippets.

@serverwentdown
Last active March 4, 2022 02:55
Show Gist options
  • Save serverwentdown/3febf9988ea0230aac790a1b4f3e1e22 to your computer and use it in GitHub Desktop.
Save serverwentdown/3febf9988ea0230aac790a1b4f3e1e22 to your computer and use it in GitHub Desktop.
Some really useless script that generates IPv6 hops using netns for your traceroute pleasure.
import sys
import itertools
from netaddr import *
PREFIX = IPNetwork('fd00:0:3:1337::/64')
NAME = 'virtual0'
COUNT = 30
UPSTREAM=0
DOWNSTREAM=1
print(f'#!/bin/sh')
subnets = PREFIX.subnet(127)
subnet = next(subnets)
downstreams = [
subnet[DOWNSTREAM]
for subnet in itertools.islice(PREFIX.subnet(127), COUNT)
]
print(f'if [[ "$1" == "setup" ]]; then')
print(f'set -ex')
# Configure a bridge that will connect to everyone
gw_host = subnet[UPSTREAM]
print(f'ip link add {NAME}b0 type bridge')
print(f'ip -6 addr add dev {NAME}b0 {gw_host}/{subnet.prefixlen}')
print(f'ip link set {NAME}b0 up')
for i in range(COUNT):
# Configure a veth pair for the bridge and the namespace
print(f'ip link add {NAME}ns{i}br0 type veth peer name {NAME}ns{i}e0')
print(f'brctl addif {NAME}b0 {NAME}ns{i}br0')
print(f'ip link set {NAME}ns{i}br0 up')
# Create a namespace and add one of the veth
print(f'ip netns add {NAME}ns{i}')
print(f'ip link set {NAME}ns{i}e0 netns {NAME}ns{i}')
print(f'ip netns exec {NAME}ns{i} ip link set lo up')
upstream_host = subnet[UPSTREAM]
upstream_address = subnet[DOWNSTREAM]
subnet = next(subnets)
downstream_address = subnet[UPSTREAM]
downstream_host = subnet[DOWNSTREAM]
# Add this namespace addresses
print(f'ip netns exec {NAME}ns{i} ip -6 addr add dev {NAME}ns{i}e0 {upstream_address}/{subnet.prefixlen}')
print(f'ip netns exec {NAME}ns{i} ip -6 addr add dev {NAME}ns{i}e0 {downstream_address}/{subnet.prefixlen}')
print(f'ip netns exec {NAME}ns{i} ip link set {NAME}ns{i}e0 up')
# Add upstream routes
print(f'ip netns exec {NAME}ns{i} ip -6 route add ::/0 via {upstream_host}')
# Add downstream routes
for j in range(i+1, COUNT):
downstream_net = downstreams[j]
print(f'ip netns exec {NAME}ns{i} ip -6 route add {downstream_net}/{subnet.prefixlen} via {downstream_host}')
# Enable forwarding
print(f'ip netns exec {NAME}ns{i} sysctl net.ipv6.conf.all.forwarding=1')
# Configure master route
for i in range(1, COUNT):
downstream_net = downstreams[i]
print(f'ip -6 route add {downstream_net}/{subnet.prefixlen} via {downstreams[0]}')
print(f'elif [[ "$1" == "teardown" ]]; then')
print(f'set -x')
for i in range(COUNT-1, -1, -1):
print(f'ip netns delete {NAME}ns{i}')
print(f'ip link delete {NAME}ns{i}br0')
print(f'ip link delete {NAME}b0 type bridge')
print(f'else')
print('echo "Usage: $0 {setup|teardown}"')
print(f'fi')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment