Skip to content
Permalink

Comparing changes

Choose two branches to see what’s changed or to start a new pull request. If you need to, you can also or learn more about diff comparisons.

Open a pull request

Create a new pull request by comparing changes across two branches. If you need to, you can also . Learn more about diff comparisons here.
base repository: Ox-EngSci/CWM-ProgNets-2023
Failed to load repositories. Confirm that selected base ref is valid, then try again.
Loading
base: main
Choose a base ref
...
head repository: MrJimbo2002/CWM-ProgNets
Failed to load repositories. Confirm that selected head ref is valid, then try again.
Loading
compare: main
Choose a head ref
Able to merge. These branches can be automatically merged.

Commits on May 22, 2023

  1. Add files via upload

    MrJimbo2002 authored May 22, 2023
    Copy the full SHA
    c83238e View commit details
  2. Add files via upload

    MrJimbo2002 authored May 22, 2023
    Copy the full SHA
    935ea7a View commit details
  3. Add files via upload

    MrJimbo2002 authored May 22, 2023
    Copy the full SHA
    c297a74 View commit details
  4. Add files via upload

    MrJimbo2002 authored May 22, 2023
    Copy the full SHA
    348d1cd View commit details

Commits on May 23, 2023

  1. Add files via upload

    MrJimbo2002 authored May 23, 2023
    Copy the full SHA
    508ae55 View commit details
  2. Add files via upload

    MrJimbo2002 authored May 23, 2023
    Copy the full SHA
    b4fc692 View commit details
  3. Copy the full SHA
    f8f703d View commit details
  4. Copy the full SHA
    70568f4 View commit details
  5. Delete ping_test0001.txt

    MrJimbo2002 authored May 23, 2023
    Copy the full SHA
    b3b5a5e View commit details
  6. Add files via upload

    MrJimbo2002 authored May 23, 2023
    Copy the full SHA
    0c68a0e View commit details
  7. Add files via upload

    MrJimbo2002 authored May 23, 2023
    Copy the full SHA
    a87b3b7 View commit details
  8. Add files via upload

    MrJimbo2002 authored May 23, 2023
    Copy the full SHA
    eb09e61 View commit details
  9. Add files via upload

    MrJimbo2002 authored May 23, 2023
    Copy the full SHA
    0bb20dc View commit details

Commits on May 24, 2023

  1. Add files via upload

    MrJimbo2002 authored May 24, 2023
    Copy the full SHA
    8a5360e View commit details
  2. Add files via upload

    MrJimbo2002 authored May 24, 2023
    Copy the full SHA
    083744f View commit details

Commits on May 25, 2023

  1. Add files via upload

    MrJimbo2002 authored May 25, 2023
    Copy the full SHA
    4b164d4 View commit details
  2. Copy the full SHA
    81439b7 View commit details
  3. Add files via upload

    MrJimbo2002 authored May 25, 2023
    Copy the full SHA
    5d544b0 View commit details
  4. Create assignment

    MrJimbo2002 authored May 25, 2023
    Copy the full SHA
    e55a323 View commit details
  5. Delete assignment

    MrJimbo2002 authored May 25, 2023
    Copy the full SHA
    1294371 View commit details
  6. Create 11111.txt

    MrJimbo2002 authored May 25, 2023
    Copy the full SHA
    3e32e87 View commit details
  7. Delete 11111.txt

    MrJimbo2002 authored May 25, 2023
    Copy the full SHA
    8368770 View commit details
  8. Add files via upload

    MrJimbo2002 authored May 25, 2023
    Copy the full SHA
    1adebcd View commit details
  9. Create assignment6

    MrJimbo2002 authored May 25, 2023
    Copy the full SHA
    0841165 View commit details
  10. Delete assignment6

    MrJimbo2002 authored May 25, 2023
    Copy the full SHA
    2bf2876 View commit details
  11. Create test

    MrJimbo2002 authored May 25, 2023
    Copy the full SHA
    e3f3186 View commit details
  12. Copy the full SHA
    6500603 View commit details
  13. Copy the full SHA
    ca1ece9 View commit details
  14. Copy the full SHA
    9ed672f View commit details
  15. Copy the full SHA
    bc9c334 View commit details
  16. Copy the full SHA
    25ad9cf View commit details
  17. Copy the full SHA
    d709701 View commit details
  18. Copy the full SHA
    d588897 View commit details
  19. Update Firewall.p4

    MrJimbo2002 authored May 25, 2023
    Copy the full SHA
    9c4643e View commit details

Commits on May 26, 2023

  1. Add files via upload

    MrJimbo2002 authored May 26, 2023
    Copy the full SHA
    e25b30f View commit details

Commits on May 27, 2023

  1. Copy the full SHA
    682e978 View commit details
  2. Delete send_1.py

    MrJimbo2002 authored May 27, 2023
    Copy the full SHA
    bfa45b7 View commit details
  3. Copy the full SHA
    9720f39 View commit details
  4. Delete reflector.p4

    MrJimbo2002 authored May 27, 2023
    Copy the full SHA
    911e4c5 View commit details
  5. Copy the full SHA
    b406a9a View commit details
35 changes: 35 additions & 0 deletions assignment1/sendm.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
#!/usr/bin/python

from scapy.all import Ether, IP, sendp, get_if_hwaddr, get_if_list, TCP, Raw, UDP
import sys
import random, string


def randomword(length):
return ''.join(random.choice(string.ascii_lowercase) for i in range(length))

def send_random_traffic(num_packets, interface, src_ip, dst_ip):
dst_mac = "00:00:00:00:00:01"
src_mac= "CA:FE:CA:FE:CA:FE"
total_pkts = 0
port = 1024
for i in range(num_packets):
data = randomword(458)
p = Ether(dst=dst_mac,src=src_mac)/IP(dst=dst_ip,src=src_ip)
p = p/TCP(sport= 5555, dport=port)/Raw(load=data)
sendp(p, iface = interface, inter = 0.01)
# If you want to see the contents of the packet, uncomment the line below
# print(p.show())
total_pkts += 1
print("Sent %s packets in total" % total_pkts)

if __name__ == '__main__':
if len(sys.argv) < 5:
print("Usage: python send.py number_of_packets interface_name src_ip_address dst_ip_address")
sys.exit(1)
else:
num_packets = sys.argv[1]
interface = sys.argv[2]
src_ip = sys.argv[3]
dst_ip = sys.argv[4]
send_random_traffic(int(num_packets), interface, src_ip, dst_ip)
Binary file not shown.
Binary file added assignment2/Bidirectional Plot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions assignment2/Iperf.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
953
945
940
943
943
945
934
943
948
936
Binary file added assignment2/Iperf3 Plot.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
10 changes: 10 additions & 0 deletions assignment2/Iperf3_Test1.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
959
941
941
941
940
941
940
941
942
948
22 changes: 22 additions & 0 deletions assignment2/Iperf_bidir.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
915
928
925
934
926
937
925
929
915
935
925
936
926
933
925
929
926
934
926
936
923
931
Binary file added assignment2/Ping_Test 1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added assignment2/Ping_Test 2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
100 changes: 100 additions & 0 deletions assignment2/ping_test.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
0.452
0.471
0.476
0.512
0.483
0.475
0.488
0.473
0.492
0.483
0.469
0.476
0.472
0.482
0.482
0.465
0.466
0.480
0.530
0.483
0.468
0.484
0.473
0.523
0.484
0.462
0.466
0.472
0.524
0.473
0.467
0.480
0.480
0.504
0.481
0.472
0.477
0.483
0.495
0.472
0.468
0.478
0.499
0.506
0.474
0.463
0.466
0.507
0.486
0.468
0.390
0.472
0.504
0.479
0.472
0.466
0.365
0.493
0.485
0.465
0.465
0.492
0.485
0.472
0.467
0.463
0.468
0.458
0.472
0.460
0.451
0.528
0.536
0.395
0.463
0.468
0.470
0.530
0.470
0.385
0.471
0.398
0.558
0.483
0.478
0.470
0.473
0.545
0.483
0.482
0.476
0.494
0.537
0.482
0.468
0.478
0.487
0.503
0.472
0.475
1,000 changes: 1,000 additions & 0 deletions assignment2/ping_test00001.txt

Large diffs are not rendered by default.

1,001 changes: 1,001 additions & 0 deletions assignment2/ping_test0001.txt

Large diffs are not rendered by default.

1,000 changes: 1,000 additions & 0 deletions assignment2/ping_test001.txt

Large diffs are not rendered by default.

30 changes: 30 additions & 0 deletions assignment2/plot_iperf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# !/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt

# parameters to modify
filename="Iperf_bidir.txt"
label='label'
xlabel = 'time/s'
ylabel = 'bandwidth(Mbits per second)'
title='Bandwidth Bidirectional Plot'
fig_name='test.png'


bitrate = np.loadtxt(filename, dtype="float")
print(bitrate)
bitrate_forward = bitrate[: : 2]
bitrate_backward = bitrate[1: : 2]


plt.plot( bitrate_backward,label= 'backward_bandwidth')
# Plot some data on the (implicit) axes.

plt.plot( bitrate_forward,label = 'forward_bandwidth')

plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
plt.legend()
plt.savefig(fig_name)
plt.show()
29 changes: 29 additions & 0 deletions assignment2/plot_iperf3.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# !/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt

# parameters to modify
filename="Iperf3_Test1.txt"
label='label'
xlabel = 'time/s'
ylabel = 'bandwidth(Mbits per second)'
title='Bandwidth Plot'
fig_name='test.png'


bitrate = np.loadtxt(filename, dtype="float")
print(bitrate)


plt.plot( bitrate,label= 'Bitrate_iperf3_Test1')
# Plot some data on the (implicit) axes.

plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
plt.legend()
plt.savefig(fig_name)
plt.show()



26 changes: 26 additions & 0 deletions assignment2/plot_ping.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
# !/usr/bin/python3
import numpy as np
import matplotlib.pyplot as plt

# parameters to modify
filename="ping_test001.txt"
label='ping'
xlabel = 'Ping Time'
ylabel = 'CDF'
title='Simple plot'
fig_name='test.png'


t = np.loadtxt(filename, delimiter=" ", dtype="float")
print(t)
data = t
data_sorted = np.sort(data)
p = 1. * np.arange(len(data))/(len(data)-1)

plt.plot(data_sorted, p, label=label) # Plot some data on the (implicit) axes.
plt.xlabel(xlabel)
plt.ylabel(ylabel)
plt.title(title)
plt.legend()
plt.savefig(fig_name)
plt.show()
Binary file not shown.
269 changes: 269 additions & 0 deletions assignment4/calc_stage2.p4
Original file line number Diff line number Diff line change
@@ -0,0 +1,269 @@
/* -*- P4_16 -*- */

/*
* P4 Calculator
*
* This program implements a simple protocol. It can be carried over Ethernet
* (Ethertype 0x1234).
*
* The Protocol header looks like this:
*
* 0 1 2 3
* +----------------+----------------+----------------+---------------+
* | P | 4 | Version | Op |
* +----------------+----------------+----------------+---------------+
* | Operand A |
* +----------------+----------------+----------------+---------------+
* | Operand B |
* +----------------+----------------+----------------+---------------+
* | Result |
* +----------------+----------------+----------------+---------------+
*
* P is an ASCII Letter 'P' (0x50)
* 4 is an ASCII Letter '4' (0x34)
* Version is currently 0.1 (0x01)
* Op is an operation to Perform:
* '+' (0x2b) Result = OperandA + OperandB
* '-' (0x2d) Result = OperandA - OperandB
* '&' (0x26) Result = OperandA & OperandB
* '|' (0x7c) Result = OperandA | OperandB
* '^' (0x5e) Result = OperandA ^ OperandB
*
* The device receives a packet, performs the requested operation, fills in the
* result and sends the packet back out of the same port it came in on, while
* swapping the source and destination addresses.
*
* If an unknown operation is specified or the header is not valid, the packet
* is dropped
*/

#include <core.p4>
#include <v1model.p4>

/*
* Define the headers the program will recognize
*/

/*
* Standard Ethernet header
*/
header ethernet_t {
bit<48> dstAddr;
bit<48> srcAddr;
bit<16> etherType;
}

/*
* This is a custom protocol header for the calculator. We'll use
* etherType 0x1234 for it (see parser)
*/
const bit<16> P4CALC_ETYPE = 0x1234;
const bit<8> P4CALC_P = 0x50; // 'P'
const bit<8> P4CALC_4 = 0x34; // '4'
const bit<8> P4CALC_VER = 0x01; // v0.1
const bit<8> P4CALC_PLUS = 0x2b; // '+'
const bit<8> P4CALC_MINUS = 0x2d; // '-'
const bit<8> P4CALC_AND = 0x26; // '&'
const bit<8> P4CALC_OR = 0x7c; // '|'
const bit<8> P4CALC_CARET = 0x5e; // '^'

header p4calc_t {
bit<8> op;
/* TODO
* fill p4calc_t header with P, four, ver, op, operand_a, operand_b, and res
entries based on above protocol header definition.
*/
bit<8> p;
bit<8> four;
bit<8> ver;
bit<32> operand_a;
bit<32> operand_b;
bit<32> res;

}

/*
* All headers, used in the program needs to be assembled into a single struct.
* We only need to declare the type, but there is no need to instantiate it,
* because it is done "by the architecture", i.e. outside of P4 functions
*/
struct headers {
ethernet_t ethernet;
p4calc_t p4calc;
}

/*
* All metadata, globally used in the program, also needs to be assembled
* into a single struct. As in the case of the headers, we only need to
* declare the type, but there is no need to instantiate it,
* because it is done "by the architecture", i.e. outside of P4 functions
*/

struct metadata {
/* In our case it is empty */
}

/*************************************************************************
*********************** P A R S E R ***********************************
*************************************************************************/
parser MyParser(packet_in packet,
out headers hdr,
inout metadata meta,
inout standard_metadata_t standard_metadata) {
state start {
packet.extract(hdr.ethernet);
transition select(hdr.ethernet.etherType) {
P4CALC_ETYPE : check_p4calc;
default : accept;
}
}

state check_p4calc {
/* TODO: just uncomment the following parse block */

transition select(packet.lookahead<p4calc_t>().p,
packet.lookahead<p4calc_t>().four,
packet.lookahead<p4calc_t>().ver) {
(P4CALC_P, P4CALC_4, P4CALC_VER) : parse_p4calc;
default : accept;
}
}

state parse_p4calc {
packet.extract(hdr.p4calc);
transition accept;
}
}

/*************************************************************************
************ C H E C K S U M V E R I F I C A T I O N *************
*************************************************************************/
control MyVerifyChecksum(inout headers hdr,
inout metadata meta) {
apply { }
}

/*************************************************************************
************** I N G R E S S P R O C E S S I N G *******************
*************************************************************************/
control MyIngress(inout headers hdr,
inout metadata meta,
inout standard_metadata_t standard_metadata) {
action send_back(bit<32> result) {
/* TODO
* - put the result back in hdr.p4calc.res
* - swap MAC addresses in hdr.ethernet.dstAddr and
* hdr.ethernet.srcAddr using a temp variable
* - Send the packet back to the port it came from
by saving standard_metadata.ingress_port into
standard_metadata.egress_spec
*/
hdr.p4calc.res = result;

bit<48> tem_mac;
tem_mac = hdr.ethernet.dstAddr;
hdr.ethernet.dstAddr = hdr.ethernet.srcAddr;
hdr.ethernet.srcAddr = tem_mac;

standard_metadata.egress_spec = standard_metadata.ingress_port;
}

action operation_add() {
/* TODO call send_back with operand_a + operand_b */
send_back(hdr.p4calc.operand_a + hdr.p4calc.operand_b);
}

action operation_sub() {
/* TODO call send_back with operand_a - operand_b */
send_back(hdr.p4calc.operand_a - hdr.p4calc.operand_b);
}

action operation_and() {
/* TODO call send_back with operand_a & operand_b */
send_back(hdr.p4calc.operand_a & hdr.p4calc.operand_b);
}

action operation_or() {
/* TODO call send_back with operand_a | operand_b */
send_back(hdr.p4calc.operand_a | hdr.p4calc.operand_b);
}

action operation_xor() {
/* TODO call send_back with operand_a ^ operand_b */
send_back(hdr.p4calc.operand_a ^ hdr.p4calc.operand_b);
}

action operation_drop() {
mark_to_drop(standard_metadata);
}

table calculate {
key = {
hdr.p4calc.op : exact;
}
actions = {
operation_add;
operation_sub;
operation_and;
operation_or;
operation_xor;
operation_drop;
}
const default_action = operation_drop();
const entries = {
P4CALC_PLUS : operation_add();
P4CALC_MINUS: operation_sub();
P4CALC_AND : operation_and();
P4CALC_OR : operation_or();
P4CALC_CARET: operation_xor();
}
}

apply {
if (hdr.p4calc.isValid()) {
calculate.apply();
} else {
operation_drop();
}
}
}

/*************************************************************************
**************** E G R E S S P R O C E S S I N G *******************
*************************************************************************/
control MyEgress(inout headers hdr,
inout metadata meta,
inout standard_metadata_t standard_metadata) {
apply { }
}

/*************************************************************************
************* C H E C K S U M C O M P U T A T I O N **************
*************************************************************************/

control MyComputeChecksum(inout headers hdr, inout metadata meta) {
apply { }
}

/*************************************************************************
*********************** D E P A R S E R *******************************
*************************************************************************/
control MyDeparser(packet_out packet, in headers hdr) {
apply {
packet.emit(hdr.ethernet);
packet.emit(hdr.p4calc);
}
}

/*************************************************************************
*********************** S W I T T C H **********************************
*************************************************************************/

V1Switch(
MyParser(),
MyVerifyChecksum(),
MyIngress(),
MyEgress(),
MyComputeChecksum(),
MyDeparser()
) main;
104 changes: 104 additions & 0 deletions assignment4/calc_stage2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
#!/usr/bin/env python3

import re

from scapy.all import *

class P4calc(Packet):
name = "P4calc"
fields_desc = [ StrFixedLenField("P", "P", length=1),
StrFixedLenField("Four", "4", length=1),
XByteField("version", 0x01),
StrFixedLenField("op", "+", length=1),
IntField("operand_a", 0),
IntField("operand_b", 0),
IntField("result", 0xDEADBABE)]

bind_layers(Ether, P4calc, type=0x1234)

class NumParseError(Exception):
pass

class OpParseError(Exception):
pass

class Token:
def __init__(self,type,value = None):
self.type = type
self.value = value

def num_parser(s, i, ts):
pattern = "^\s*([0-9]+)\s*"
match = re.match(pattern,s[i:])
if match:
ts.append(Token('num', match.group(1)))
return i + match.end(), ts
raise NumParseError('Expected number literal.')


def op_parser(s, i, ts):
pattern = "^\s*([-+&|^])\s*"
match = re.match(pattern,s[i:])
if match:
ts.append(Token('num', match.group(1)))
return i + match.end(), ts
raise NumParseError("Expected binary operator '-', '+', '&', '|', or '^'.")


def make_seq(p1, p2):
def parse(s, i, ts):
i,ts2 = p1(s,i,ts)
return p2(s,i,ts2)
return parse

def get_if():
ifs=get_if_list()
iface= "enx0c37965f8a10" # "h1-eth0"
#for i in get_if_list():
# if "eth0" in i:
# iface=i
# break;
#if not iface:
# print("Cannot find eth0 interface")
# exit(1)
#print(iface)
return iface

def main():

p = make_seq(num_parser, make_seq(op_parser,num_parser))
s = ''
#iface = get_if()
iface = "enx0c37965f8a10"

while True:
s = input('> ')
if s == "quit":
break
print(s)
try:
i,ts = p(s,0,[])
pkt = Ether(dst='00:04:00:00:00:00', type=0x1234) / P4calc(op=ts[1].value,
operand_a=int(ts[0].value),
operand_b=int(ts[2].value))

pkt = pkt/' '

#pkt.show()
resp = srp1(pkt, iface=iface,timeout=5, verbose=False)
if resp:
p4calc=resp[P4calc]
if p4calc:
print(p4calc.result)
else:
print("cannot find P4calc header in the packet")
else:
print("Didn't receive response")
except Exception as error:
print(error)


if __name__ == '__main__':
main()


Binary file not shown.
2 changes: 2 additions & 0 deletions assignment5/commands3.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
table_add MyIngress.ipv4_lpm MyIngress.ipv4_forward 169.254.21.80/32 => 0c:37:96:5f:8a:27 0
table_add MyIngress.ipv4_lpm MyIngress.ipv4_forward 169.254.46.161/32 => 0c:37:96:5f:8a:10 1
23 changes: 21 additions & 2 deletions assignment5/l3switch.p4
Original file line number Diff line number Diff line change
@@ -53,7 +53,19 @@ parser MyParser(packet_in packet,

state start {
/* TODO: add parser logic */
packet.extract(hdr.ethernet);
transition select(hdr.ethernet.type) {
0x800 : parse_ipv4;

transition accept;
}
}



state parse_ipv4{
packet.extract(hdr.ipv4);
transition accept;
}
}

@@ -80,6 +92,10 @@ control MyIngress(inout headers hdr,

action ipv4_forward(macAddr_t dstAddr, egressSpec_t port) {
/* TODO: fill out code in action body */
hdr.ethernet.srcAddr = hdr.ethernet.dstAddr;
hdr.ethernet.dstAddr = dstAddr;
standard.metadata.egress_spec = port;
hdr.ipv4.ttl = hdr.ipv4.ttl - 1;
}

table ipv4_lpm {
@@ -99,8 +115,9 @@ control MyIngress(inout headers hdr,
/* TODO: fix ingress control logic
* - ipv4_lpm should be applied only when IPv4 header is valid
*/
ipv4_lpm.apply();
}
if(hdr.ipv4.isValid()){
ipv4_lpm.apply();
}
}

/*************************************************************************
@@ -145,6 +162,8 @@ control MyComputeChecksum(inout headers hdr, inout metadata meta) {
control MyDeparser(packet_out packet, in headers hdr) {
apply {
/* TODO: add deparser logic */
packet.emit(hdr.ethernet);
packet.emit(hdr.ipv4);
}
}

182 changes: 182 additions & 0 deletions assignment5/l3switch2.p4
Original file line number Diff line number Diff line change
@@ -0,0 +1,182 @@
/* -*- P4_16 -*- */
#include <core.p4>
#include <v1model.p4>

const bit<16> TYPE_IPV4 = 0x800;

/*************************************************************************
*********************** H E A D E R S ***********************************
*************************************************************************/

typedef bit<9> egressSpec_t;
typedef bit<48> macAddr_t;
typedef bit<32> ip4Addr_t;

header ethernet_t {
macAddr_t dstAddr;
macAddr_t srcAddr;
bit<16> etherType;
}

header ipv4_t {
bit<4> version;
bit<4> ihl;
bit<8> diffserv;
bit<16> totalLen;
bit<16> identification;
bit<3> flags;
bit<13> fragOffset;
bit<8> ttl;
bit<8> protocol;
bit<16> hdrChecksum;
ip4Addr_t srcAddr;
ip4Addr_t dstAddr;
}

struct metadata {
/* empty */
}

struct headers {
ethernet_t ethernet;
ipv4_t ipv4;
}

/*************************************************************************
*********************** P A R S E R ***********************************
*************************************************************************/

parser MyParser(packet_in packet,
out headers hdr,
inout metadata meta,
inout standard_metadata_t standard_metadata) {

state start {
packet.extract(hdr.ethernet);
transition select(hdr.ethernet.etherType) {
TYPE_IPV4: parse_ipv4;
default: accept;
}
}

state parse_ipv4 {
packet.extract(hdr.ipv4);
/* TODO: add parser logic */
transition accept;
}
}


/*************************************************************************
************ C H E C K S U M V E R I F I C A T I O N *************
*************************************************************************/

control MyVerifyChecksum(inout headers hdr, inout metadata meta) {
apply { }
}


/*************************************************************************
************** I N G R E S S P R O C E S S I N G *******************
*************************************************************************/

control MyIngress(inout headers hdr,
inout metadata meta,
inout standard_metadata_t standard_metadata) {
action drop() {
mark_to_drop(standard_metadata);
}

action ipv4_forward(macAddr_t dstAddr, egressSpec_t port) {
standard_metadata.egress_spec = port;
hdr.ethernet.srcAddr = hdr.ethernet.dstAddr;
hdr.ethernet.dstAddr = dstAddr;
hdr.ipv4.ttl = hdr.ipv4.ttl -1;


/* TODO: fill out code in action body */
}

table ipv4_lpm {

key = {
hdr.ipv4.dstAddr: lpm;
}
actions = {
ipv4_forward;
drop;
NoAction;
}
size = 1024;
default_action = NoAction();
}

apply {
/* TODO: fix ingress control logic
* - ipv4_lpm should be applied only when IPv4 header is valid
*/
if (hdr.ipv4.isValid()) {
ipv4_lpm.apply();
}
}
}

/*************************************************************************
**************** E G R E S S P R O C E S S I N G *******************
*************************************************************************/

control MyEgress(inout headers hdr,
inout metadata meta,
inout standard_metadata_t standard_metadata) {
apply { }
}

/*************************************************************************
************* C H E C K S U M C O M P U T A T I O N **************
*************************************************************************/

control MyComputeChecksum(inout headers hdr, inout metadata meta) {
apply {
update_checksum(
hdr.ipv4.isValid(),
{ hdr.ipv4.version,
hdr.ipv4.ihl,
hdr.ipv4.diffserv,
hdr.ipv4.totalLen,
hdr.ipv4.identification,
hdr.ipv4.flags,
hdr.ipv4.fragOffset,
hdr.ipv4.ttl,
hdr.ipv4.protocol,
hdr.ipv4.srcAddr,
hdr.ipv4.dstAddr },
hdr.ipv4.hdrChecksum,
HashAlgorithm.csum16);
}
}


/*************************************************************************
*********************** D E P A R S E R *******************************
*************************************************************************/

control MyDeparser(packet_out packet, in headers hdr) {
apply {
packet.emit(hdr.ethernet);
packet.emit(hdr.ipv4);
/* TODO: add deparser logic */
}
}

/*************************************************************************
*********************** S W I T C H *******************************
*************************************************************************/

V1Switch(
MyParser(),
MyVerifyChecksum(),
MyIngress(),
MyEgress(),
MyComputeChecksum(),
MyDeparser()
) main;
Binary file not shown.
Binary file not shown.
279 changes: 279 additions & 0 deletions assignment6/Firewall.p4
Original file line number Diff line number Diff line change
@@ -0,0 +1,279 @@
/* -*- P4_16 -*- */
#include <core.p4>
#include <v1model.p4>

//#define MAX_DDos_Size 131072
//#define DDoS_threshold 200

const bit<16> TYPE_IPV4 = 0x800;

/*************************************************************************
*********************** H E A D E R S ***********************************
*************************************************************************/

typedef bit<9> egressSpec_t;
typedef bit<48> macAddr_t;
typedef bit<32> ip4Addr_t;


header ethernet_t {
macAddr_t dstAddr;
macAddr_t srcAddr;
bit<16> etherType;
}

header ipv4_t {
bit<4> version;
bit<4> ihl;
bit<8> diffserv;
bit<16> totalLen;
bit<16> identification;
bit<3> flags;
bit<13> fragOffset;
bit<8> ttl;
bit<8> protocol;
bit<16> hdrChecksum;
ip4Addr_t srcAddr;
ip4Addr_t dstAddr;
}

header tcp_t {
bit<16> srcPort;
bit<16> dstPort;
bit<32> seqNo;
bit<32> ackNo;
bit<4> dataOffset;
bit<3> res;
bit<3> ecn;
bit<6> ctrl;
bit<16> window;
bit<16> checksum;
bit<16> urgentPtr;
}

header udp_t {
bit<16> srcPort;
bit<16> dstPort;
bit<16> udplen;
bit<16> udpchk;
}


//set up a global variable val in structures of metadata//
struct metadata {
bit<32> val;
bit<32> hit;
}

struct headers {
ethernet_t ethernet;
ipv4_t ipv4;
tcp_t tcp;
udp_t udp;
//define protocols across all layers detected in headers/
}


/*************************************************************************
*********************** P A R S E R ***********************************
*************************************************************************/

parser MyParser(packet_in packet,
out headers hdr,
inout metadata meta,
inout standard_metadata_t standard_metadata) {

state start {
/*add parser logic */
packet.extract(hdr.ethernet);
transition select(hdr.ethernet.etherType) {
0x800 : parse_ipv4;
default: accept;
}
}



state parse_ipv4{
packet.extract(hdr.ipv4);
transition select(hdr.ipv4.protocol){

8w0x6: parse_tcp;
8w0x11:parse_udp;
default: accept;
}
}

state parse_tcp{
packet.extract(hdr.tcp);
transition accept;
}

state parse_udp{
packet.extract(hdr.udp);
transition accept;
}

}


/*************************************************************************
************ C H E C K S U M V E R I F I C A T I O N *************
*************************************************************************/

control MyVerifyChecksum(inout headers hdr, inout metadata meta) {
apply { }
}


/*************************************************************************
************** I N G R E S S P R O C E S S I N G *******************
*************************************************************************/

control MyIngress(inout headers hdr,
inout metadata meta,
inout standard_metadata_t standard_metadata) {

//The majoy appending function of my firewall corresponds to the DDOS attact protection utilising registers as temporary store of count min sketch values.
//The settling quota of maximum number of a specific IP address is defined as 200 and cms refers to count min sketch as abbreviation below.
//Index of Count-Min-Sketch of size 1024


register<bit<32>>(2) r;


action drop() {
mark_to_drop(standard_metadata);
}

action ipv4_forward(macAddr_t dstAddr, egressSpec_t port) {

hdr.ethernet.srcAddr = hdr.ethernet.dstAddr;
hdr.ethernet.dstAddr = dstAddr;
standard_metadata.egress_spec = port;
hdr.ipv4.ttl = hdr.ipv4.ttl - 1;
meta.hit = 1;

//under ipv4_forward action, try to add "counters" increased by one in registers stored in global variable val.


}




table ipv4 {
key = {

//define all the allowed white list ipv4 source and destination address and udp source and destination port.

hdr.ipv4.dstAddr: exact;
hdr.ipv4.srcAddr: exact;
hdr.ipv4.protocol:exact;
hdr.udp.srcPort: exact;
hdr.udp.dstPort : exact;

}

actions = {
ipv4_forward;
drop;
NoAction;
}

size = 1024;
default_action = NoAction;
}


apply {

//ipv4 should be applied only when IPv4 header is valid//
meta.hit = 0;

if(meta.hit == 0){
ipv4.apply();
}
else{
drop();
}


r.read(meta.val, 0);
meta.val = meta.val + 1;
r.write(0, meta.val);

if (meta.val > 100){
drop();
}
else{
ip4Addr_t temp;
temp = hdr.ipv4.srcAddr;
hdr.ipv4.srcAddr = hdr.ipv4.dstAddr;
hdr.ipv4.dstAddr = temp;
standard_metadata.egress_spec = standard_metadata.ingress_port;
}



}
}
/*************************************************************************
**************** E G R E S S P R O C E S S I N G *******************
*************************************************************************/

control MyEgress(inout headers hdr,
inout metadata meta,
inout standard_metadata_t standard_metadata) {
apply { }
}

/*************************************************************************
************* C H E C K S U M C O M P U T A T I O N **************
*************************************************************************/

control MyComputeChecksum(inout headers hdr, inout metadata meta) {
apply {
update_checksum(
hdr.ipv4.isValid(),
{ hdr.ipv4.version,
hdr.ipv4.ihl,
hdr.ipv4.diffserv,
hdr.ipv4.totalLen,
hdr.ipv4.identification,
hdr.ipv4.flags,
hdr.ipv4.fragOffset,
hdr.ipv4.ttl,
hdr.ipv4.protocol,
hdr.ipv4.srcAddr,
hdr.ipv4.dstAddr },
hdr.ipv4.hdrChecksum,
HashAlgorithm.csum16);
}
}


/*************************************************************************
*********************** D E P A R S E R *******************************
*************************************************************************/

control MyDeparser(packet_out packet, in headers hdr) {
apply {
//* add deparser logic */
packet.emit(hdr.ethernet);
packet.emit(hdr.ipv4);
}
}

/*************************************************************************
*********************** S W I T C H *******************************
*************************************************************************/

V1Switch(
MyParser(),
MyVerifyChecksum(),
MyIngress(),
MyEgress(),
MyComputeChecksum(),
MyDeparser()
) main;
1 change: 1 addition & 0 deletions assignment6/commands.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
table_add MyIngress.ipv4 MyIngress.ipv4_forward 192.168.10.1 192.168.10.2 17 5000 1024 => 0c:37:96:5f:8a:0 0
74 changes: 74 additions & 0 deletions assignment6/cwm
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
#!/bin/bash

INPUT="$1"

# Server side
# IP address of source host with CIDR (netmask)
SRC_IP="169.254.21.80/16"
# IP address of destination host
DST_IP="169.254.21.222"
# MAC address of destination host
DST_MAC="e4:5f:01:8c:7e:52"
# Interface name (USB-Ethernet) of the host
ETH="eth0"

# Switch side (Raspberry Pi)
# The directory to your P4 program
DIR="/home/ubuntu/CWM-ProgNets/assignment6"
# Modify the name of P4 program here
P4_NAME="Firewall"
# The name of the first interface on Raspberry Pi
INT1="enx0c37965f8a10"
# The name of the second interface on Raspberry Pi
# Note: you may need to change the run/exec command if a single interface is used
INT2="eth1"

#configure IP address
if [ "$INPUT" = "ip" ]
then
sudo ip addr add dev $ETH $SRC_IP
#Add a route
elif [ "$INPUT" = "route" ]
then
sudo ip route add dev $ETH $DST_IP
#Configure ARP
elif [ "$INPUT" = "arp" ]
then
sudo arp -s $DST_IP $DST_MAC
#Configure route and ARP
elif [ "$INPUT" = "config" ]
then
sudo ip route add dev $ETH $DST_IP
sudo arp -s $DST_IP $DST_MAC
#Compile P4 program
elif [ "$INPUT" = "compile" ]
then
p4c --target bmv2 --arch v1model --std p4-16 $DIR$P4_NAME.p4
#Run P4 program
elif [ "$INPUT" = "run" ]
then
if [ -f "$P4_NAME.json" ]; then
sudo simple_switch -i 0@$INT1 $DIR/$P4_NAME.json &
else
echo "Please compile P4 program first!"
fi
#Compile and run a P4 program
elif [ "$INPUT" = "exec" ]
then
p4c --target bmv2 --arch v1model --std p4-16 $P4_NAME.p4
if [ -f "$P4_NAME.json" ]; then
sudo simple_switch -i 0@$INT1 $P4_NAME.json &
fi
#Kill all running p4 programs
elif [ "$INPUT" = "kill" ]
then
sudo kill $(ps aux|grep simple_switch|awk '{if($0 ~ /json/) print $2}')
#Load control plane configurations using CLI
elif [ "$INPUT" = "cli" ]
then
simple_switch_CLI < $DIR/commands.txt
else
echo "Please type correct parameters"
fi


37 changes: 37 additions & 0 deletions assignment6/send.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
#!/usr/bin/python

from scapy.all import Ether, IP, sendp, get_if_hwaddr, get_if_list, TCP, Raw, UDP
import sys
import random, string


def randomword(length):
return ''.join(random.choice(string.ascii_lowercase) for i in range(length))

def send_random_traffic(num_packets, interface, src_ip, dst_ip):
dst_mac = "00:00:00:00:00:01"
src_mac= "00:00:00:00:00:02"


total_pkts = 0
port = 1024
for i in range(num_packets):
data = randomword(22)
p = Ether(dst=dst_mac,src=src_mac)/IP(dst=dst_ip,src=src_ip)
p = p/UDP(sport= 5000, dport=port)/Raw(load=data)
sendp(p, iface = interface, inter = 0.01)
# If you want to see the contents of the packet, uncomment the line below
# print(p.show())
total_pkts += 1
print("Sent %s packets in total" % total_pkts)

if __name__ == '__main__':
if len(sys.argv) < 5:
print("Usage: python send.py number_of_packets interface_name src_ip_address dst_ip_address")
sys.exit(1)
else:
num_packets = sys.argv[1]
interface = sys.argv[2]
src_ip = sys.argv[3]
dst_ip = sys.argv[4]
send_random_traffic(int(num_packets), interface, src_ip, dst_ip)
1 change: 1 addition & 0 deletions assignment6/test
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
1111