def example_setup(num_clients=3, num_servers=3):
    ### EXAMPLE PARAMETERS
    # NETWORK BREAKDOWN
    ethernet = [2,3,4,1000]
    ip_core  = [5,6,7,1002]
    gateway  = [1001]

    # SUBNET ADDRESSING
    eth_prefix = '10.0.0.'
    ip_prefix  = '10.0.1.'
    prefix_len = 24
    eth_cidr = eth_prefix + '0/' + str(prefix_len)
    ip_cidr = ip_prefix + '0/' + str(prefix_len)

    # END HOST ADDRESSES
    public_ip = IP('10.0.1.100')
    fake_mac = MAC('BB:BB:BB:BB:BB:BB')
    eth_macs = { IP(eth_prefix+str(i+1)) : MAC('00:00:00:00:00:0'+str(i)) \
                     for i in range(1,1+num_clients) }
    ip_macs = { IP(ip_prefix+str(i+1)) : MAC('00:00:00:00:00:0'+str(i+num_clients)) \
                    for i in range(1,1+num_servers) }
    host_macs = dict(eth_macs.items() + ip_macs.items())
    host_macs.update({IP(public_ip) : fake_mac})

    ### POLICIES FOR THIS EXAMPLE
    eth_pol = mac_learner() 
    ip_pol = mac_learner() 
    gw_pol = gateway_forwarder(eth_cidr,ip_cidr,host_macs)
    
    return ((switch_in(ethernet) & eth_pol) + 
            (switch_in(gateway)  & gw_pol ) +
            (switch_in(ip_core)  & ip_pol ))    
Example #2
0
def main():
    from pyretic.modules.mac_learner import mac_learner
    from pyretic.examples.Monitor import Monitor
    from pyretic.examples.firewall import firewall_policy
    ARPPkt = match(ethtype=ARP_TYPE)
    Clients = 1
    Servers = 2
    Device_1 = 4
    Device_2 = 3
    PublicIP_1 = IP("10.0.100.1")
    PublicIP_2 = IP("10.0.100.2")
    ClientIPs = [
        IP("10.0.0.1"),
        IP("10.0.0.2"),
        IP("10.0.0.3"),
        IP("10.0.0.4")
    ]
    ServerIPs_1 = [IP("10.0.0.5"), IP("10.0.0.6")]
    ServerIPs_2 = [IP("10.0.0.7"), IP("10.0.0.8")]
    LB_1 = LoadBalancer(Device_1, ClientIPs, ServerIPs_1, PublicIP_1)
    LB_2 = LoadBalancer(Device_2, ClientIPs, ServerIPs_2, PublicIP_2)
    LB_Monitor_Policy = ((ARPPkt >> mac_learner()) + (LB_1 >> mac_learner()) +
                         (LB_2 >> mac_learner()) + Monitor(10))

    return if_(firewall_policy, drop, LB_Monitor_Policy)
def example_setup(num_clients=3, num_servers=3):
    ### EXAMPLE PARAMETERS
    # NETWORK BREAKDOWN
    ethernet = [2, 3, 4, 1000]
    ip_core = [5, 6, 7, 1002]
    gateway = [1001]

    # SUBNET ADDRESSING
    eth_prefix = '10.0.0.'
    ip_prefix = '10.0.1.'
    prefix_len = 24
    eth_cidr = eth_prefix + '0/' + str(prefix_len)
    ip_cidr = ip_prefix + '0/' + str(prefix_len)

    # END HOST ADDRESSES
    public_ip = IP('10.0.1.100')
    fake_mac = MAC('BB:BB:BB:BB:BB:BB')
    eth_macs = { IP(eth_prefix+str(i+1)) : MAC('00:00:00:00:00:0'+str(i)) \
                     for i in range(1,1+num_clients) }
    ip_macs = { IP(ip_prefix+str(i+1)) : MAC('00:00:00:00:00:0'+str(i+num_clients)) \
                    for i in range(1,1+num_servers) }
    host_macs = dict(eth_macs.items() + ip_macs.items())
    host_macs.update({IP(public_ip): fake_mac})

    ### POLICIES FOR THIS EXAMPLE
    eth_pol = mac_learner()
    ip_pol = virtualize(mac_learner(), merge(name=5, from_switches=ip_core))
    gw_pol = gateway_forwarder(eth_cidr, ip_cidr, host_macs)

    return ((switch_in(ethernet) >> eth_pol) + (switch_in(gateway) >> gw_pol) +
            (switch_in(ip_core) >> ip_pol))
Example #4
0
def main():
    print "load balancer"
    # ips = [IPAddr('10.0.0.1'),IPAddr('10.0.0.2'),IPAddr('10.0.0.3')]
    ips = [IPAddr("10.0.0.3"), IPAddr("10.0.0.4")]
    # macs = [EthAddr("00:00:00:00:00:01"),EthAddr("00:00:00:00:00:02"),EthAddr("00:00:00:00:00:03")]
    macs = [EthAddr("00:00:00:00:00:03"), EthAddr("00:00:00:00:00:04")]
    ports = [10000, 11000]

    rrlb_on_switch = rrlb(2, ips, macs, ports)

    forwardARP = match(ethtype=0x0806)
    forwardICMP = match(ethtype=0x0800, protocol=1)
    return if_(forwardICMP | forwardARP, mac_learner(), rrlb_on_switch >> mac_learner())
def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment
    policyFileContent = open(policy_file)
    # skip first line
    policyFileContent.readline()

    # start with a policy that doesn't match any packets
    not_allowed = none

    while True:
        line = policyFileContent.readline()
        if not line:
            break
        print line
        # info[1] == mac_0, info[2] == mac_1
        info = line.split(',')
        info[2].strip('\n')

        # and add traffic that isn't allowed
        not_allowed = union([
            not_allowed,
            match(dstmac=EthAddr(info[2])) >> match(srcmac=EthAddr(info[1]))
        ])
        not_allowed = union([
            not_allowed,
            match(dstmac=EthAddr(info[1])) >> match(srcmac=EthAddr(info[2]))
        ])

    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #6
0
def main():
    # Copy the code you used to read firewall-policies.csv last week
    data = open(policy_file)
    data.readline()
    # start with a policy that doesn't match any packets
    not_allowed = none
    while 1:
        line = data.readline()
        if not line:
            break
        # print line
        id, mac_0, mac_1 = line.split(',')
        # and add traffic that isn't allowed
        not_allowed = union([
            not_allowed,
            match(dstmac=EthAddr(mac_1)) >> match(srcmac=EthAddr(mac_0))
        ])
        not_allowed = union([
            not_allowed,
            match(dstmac=EthAddr(mac_0)) >> match(srcmac=EthAddr(mac_1))
        ])
    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment
    # start with a policy that doesn't match any packets
    not_allowed = none
    allowed = none

    acl = []
    with open(policy_file, 'rb') as f:
        reader = csv.DictReader(f)
        for row in reader:
            element = [MAC(row['mac_0']), MAC(row['mac_1'])]
            inv_element = [MAC(row['mac_1']), MAC(row['mac_0'])]
            acl.append(element)
            acl.append(inv_element)

    for [i, j] in acl:
        print[i, j]
        not_allowed = not_allowed | (match(srcmac=i) & match(dstmac=j)
                                     | match(srcmac=j) & match(dstmac=i))

# express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    #return mac_learner()
    return allowed >> mac_learner()
Example #8
0
def main():
    # Copy the code you used to read firewall-policies.csv last week
    acl = []
    # access control list

    csvFile = open(policy_file, "rb")
    inStream = csv.reader(csvFile, delimiter=",")
    for row in inStream:
        acl.append(row)
    acl.pop(0)
    for item in acl:
        item.pop(0)
        # print item

        # start with a policy that doesn't match any packets
    not_allowed = none
    # and add traffic that isn't allowed
    # for <each pair of MAC address in firewall-policies.csv>:
    for item in acl:
        not_allowed = (
            not_allowed
            | match(srcmac=EthAddr(item[0]), dstmac=EthAddr(item[1]))
            | match(srcmac=EthAddr(item[1]), dstmac=EthAddr(item[0]))
        )

    # express allowed traffic in terms of not_allowed - hint use '~'
    # allowed = none
    # for item in acl:
    # allowed = allowed + ~match(srcmac=EthAddr(item[0]),dstmac=EthAddr(item[1])) + ~match(srcmac=EthAddr(item[1]),dstmac=EthAddr(item[0]))

    allowed = ~not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    # return allowed >> act_like_switch()
    return allowed >> mac_learner()
def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment
    fileOpen = open(policy_file)
    fileOpen.readline()
    # start with a policy that doesn't match any packets
    not_allowed = none
    while True:
        readLine = fileOpen.readline()
        if not readLine:
            break
        print readLine
        csvInfo = readLine.split(',')
        csvInfo[2].strip('\n')

        # and add traffic that isn't allowed
        not_allowed = union( [not_allowed, match(dstmac=EthAddr(csvInfo[2])) >>
            match(srcmac=EthAddr(csvInfo[1]))] )
        not_allowed = union( [not_allowed, match(dstmac=EthAddr(csvInfo[1])) >>
            match(srcmac=EthAddr(csvInfo[2]))] )


    # and add traffic that isn't allowed
    # for <each pair of MAC address in firewall-policies.csv>:
    #     not_allowed = union( [
    #         <traffic going in one direction>,
    #         <traffic going in the other direction> ] )

    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment
    policyFileContent = open(policy_file)
    # skip first line
    policyFileContent.readline()

    # start with a policy that doesn't match any packets
    not_allowed = none

    while True:
        line = policyFileContent.readline()
        if not line:
            break
        print line
        # info[1] == mac_0, info[2] == mac_1
        info = line.split(',')
        info[2].strip('\n')

        # and add traffic that isn't allowed
        not_allowed = union( [not_allowed, match(dstmac=EthAddr(info[2])) >>
            match(srcmac=EthAddr(info[1]))] )
        not_allowed = union( [not_allowed, match(dstmac=EthAddr(info[1])) >>
            match(srcmac=EthAddr(info[2]))] )

    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #11
0
def main():
    bfs1 = [1, 2, 3]
    bfs2 = [1, 4]
    pol = if_(ARP, arp(), mac_learner())
    #    pol = mac_learner()
    return virtualize(virtualize(pol, merge(from_switches=[1, 4])),
                      merge(from_switches=[1, 2, 3]))
Example #12
0
def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment
    policies = []

    with open(policy_file, "r") as pf:
        next(pf)
        for line in pf:
            line = line.rstrip()
            tokens = line.split(",")
            mac_0 = MAC(tokens[1])
            mac_1 = MAC(tokens[2])
            policies.append((mac_0, mac_1))

    # start with a policy that doesn't match any packets
    not_allowed = none
    
    # and add traffic that isn't allowed
    for (mac_0, mac_1) in policies:
        not_allowed = union([ (match(srcmac=mac_0) & match(dstmac=mac_1))
                                                   |
                              (match(srcmac=mac_1) & match(dstmac=mac_0))
                                                   |
                              not_allowed
                            ])

    #print not_allowed
    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed
    #print allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #13
0
def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment

    not_allowed = none
    with open(policy_file, 'rb') as mycsv:
        reader_macfilter_from_file = csv.DictReader(mycsv)
        for row in reader_macfilter_from_file:
            ssssssss

            not_allowed = union([
                not_allowed,
                union([
                    match(srcmac=MAC(row['mac_0']), dstmac=MAC(row['mac_1'])),
                    match(srcmac=MAC(row['mac_1']), dstmac=MAC(row['mac_0']))
                ])
            ])

    # start with a policy that doesn't match any packets

    # and add traffic that isn't allowed

    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    #print "not_allowed : "
    #print not_allowed
    #print "allowed :"
    #print allowed
    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #14
0
def main():
    re = RegexpQuery(
        "(?P<verb>GET|POST|DELETE|PUT|HEAD)\s*(?P<path>.*?)\s*HTTP/(?P<http>.*?)\n"
    )
    re.register_callback(print_urls)

    return mac_learner() + re
Example #15
0
def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment
    
    not_allowed=none
    with open(policy_file,'rb') as mycsv:
        reader_macfilter_from_file=csv.DictReader(mycsv)
        for row in reader_macfilter_from_file:
            ssssssss

            not_allowed = union( [not_allowed,union( [match(srcmac=MAC(row['mac_0']),
                                                             dstmac=MAC(row['mac_1'])
                                                             ),
                                                      match(srcmac=MAC(row['mac_1']),
                                                            dstmac=MAC(row['mac_0']))
                                                      ]
                                                     )
                                  ]
                                 )

    # start with a policy that doesn't match any packets
    
    
    # and add traffic that isn't allowed
    
    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed
                                             
    #print "not_allowed : "
    #print not_allowed
    #print "allowed :"
    #print allowed
    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #16
0
def main(config, mode, modrepeat=None):
    # Open configuration file
    try:
        fd = open(config, 'r')
    except IOError as err:
        print 'IO Exception: ', err
        sys.exit(1)
        
    # Get mode, check validity
    if mode != 'auto' and mode != 'manual':
        print 'Wrong mode value. Exiting!'
        sys.exit(1)
        
    # Check test mode.
    repeat = 0
    if modrepeat is not None:
        if modrepeat != 0:
            repeat = modrepeat

    # Read configuration file
    content = fd.read()
    fd.close()
    
    # Parse configuration file
    app_to_module_map, app_composition_str = parse_configuration_file(content, mode, repeat)
    
    if len(app_to_module_map) == 0:
        print 'Configuration file seems incorrect. Exiting.'
        sys.exit(1)

    # Run resonance
# return resonance(app_to_module_map, app_composition_str) >> mac_learner()
    return resonance(app_to_module_map, app_composition_str) >> (mac_learner() + scan())
Example #17
0
def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment
    f = open(policy_file, 'r')

    # start with a policy that doesn't match any packets
    not_allowed = none

    # and add traffic that isn't allowed
    #for <each pair of MAC address in firewall-policies.csv>:
    #    not_allowed = union( [
    #        <traffic going in one direction>,
    #        <traffic going in the other direction> ] )

    line = f.readline()
    print "line_1: %s" % line
    while 1:
        line = f.readline()
        if not line: break
        print "line_n: %s" % line
        mac1 = line[2:19]
        mac2 = line[20:37]
        not_allowed = not_allowed | match(
            srcmac=MAC(mac1), dstmac=MAC(mac2)) | match(srcmac=MAC(mac2),
                                                        dstmac=MAC(mac1))
        print "not_allowed: %s" % not_allowed
    f.close()

    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #18
0
def main():
        #logging.basicConfig(filename='log/sdnlb.log', level=logging.INFO,format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S %p')
        logging.basicConfig(filename='log/sdnlb.log', level=logging.INFO,format='%(asctime)s %(message)s', datefmt='%d/%m/%Y %H:%M:%S %p',filemode='w')
        #logger = logging.getLogger('sdnlblogger')
        #logger = logging.getLogger(__name__)
        logger = logging.getLogger()
        logger.info("shit")
        printConfigInfo(logger)
	algoType = sdnlb_conf.algo
	algo = AlgoFactory.getAlgoInstance(algoType)

	rrlb_sdn = LoadBalancer(sdnlb_conf.switch,sdnlb_conf.sip,sdnlb_conf.smac,algo)

	forwardARP = match(ethtype=0x0806)
	forwardICMP = match(ethtype=0x0800,protocol=1)
	return if_(forwardICMP | forwardARP, mac_learner(), \
			rrlb_sdn >>mac_learner())
Example #19
0
	def Start(self):
		# Handle ARP
		ARPPkt = match(ethtype=ARP_TYPE)

		# Instantiate Firewalls
		AccessControl = self.FW.ApplyFirewall()

		# Instantiate Load Balancer
		LB  = LoadBalancer(self.LB_Device, self.ClientIPs, self.ServerIPs, self.PublicIP)

		self.policy = 	(
					( ARPPkt >> mac_learner() ) +				# ARP - L2 Learning Switches
					( LB >> mac_learner() >> AccessControl ) +	# Load Balancer + Firewall
					Monitor(MonitoringInterval)					# Monitoring
				)

		return self.policy
Example #20
0
def main():
  global policy
  global flag

  flag = flag()
  # policy = tag() >> mac_learner() >> (flag + untag()) Don't need tagging
  policy = mac_learner() + flag
  print policy
  return policy
Example #21
0
def main():
    global policy
    global flag

    flag = flag()
    # policy = tag() >> mac_learner() >> (flag + untag()) Don't need tagging
    policy = mac_learner() + flag
    print policy
    return policy
Example #22
0
def main():
    bfs1  = [1,2,3]
    bfs2  = [1,4]
    pol = if_(ARP,arp(),mac_learner())
#    pol = mac_learner()
    return virtualize(
        virtualize(pol,
                   BFS_vdef(from_switches=[1,4])),
        BFS_vdef(from_switches=[1,2,3]))
Example #23
0
def main ():
    HOST, PORT = "localhost", 9002

    my_smart_balancer = smart_balancer()
    server = SmartBalancerTCPServer((HOST,PORT), MyTCPHandler, my_smart_balancer)
    serverThread = threading.Thread(target=start_server, args=(server,))
    serverThread.daemon = True
    serverThread.start()
    
    return my_smart_balancer >> mac_learner()
def example_setup(num_clients=3, num_servers=3):
    ### EXAMPLE PARAMETERS
    # NETWORK BREAKDOWN
    ethernet = [2,3,4,1000]
    ip_core  = [5,6,7,1002]
    gateway  = [1001]

    # SUBNET ADDRESSING
    eth_prefix = '10.0.0.'
    ip_prefix  = '10.0.1.'
    prefix_len = 24
    eth_cidr = eth_prefix + '0/' + str(prefix_len)
    ip_cidr = ip_prefix + '0/' + str(prefix_len)

    # END HOST ADDRESSES
    public_ip = IP('10.0.1.100')
    fake_mac = MAC('BB:BB:BB:BB:BB:BB')
    eth_macs = { IP(eth_prefix+str(i+1)) : MAC('00:00:00:00:00:0'+str(i)) \
                     for i in range(1,1+num_clients) }
    ip_macs = { IP(ip_prefix+str(i+1)) : MAC('00:00:00:00:00:0'+str(i+num_clients)) \
                    for i in range(1,1+num_servers) }
    host_macs = dict(eth_macs.items() + ip_macs.items())
    host_macs.update({IP(public_ip) : fake_mac})

    # PARAMETERS FOR FIREWALL/LOAD BALANCER
    R = [IP(ip_prefix + str(i)) for i in range(2, 2+num_servers)]
    H = {IP(eth_prefix + str(i)) : 0 for i in range(2,2+num_clients)}
    W = {(c,public_ip) for c in H.keys()}

    ### POLICIES FOR THIS EXAMPLE
    eth_pol = mac_learner()
    alb = dynamic(lb)(public_ip,R,H) >> fix_dstmac(ip_macs) 
    afw = if_(ARP,passthrough,dynamic(fw)(W))
    ip_pol = if_(match(srcip=eth_cidr), 
                 afw >> alb, 
                 alb >> afw) >> mac_learner() 
    ip_pol = virtualize(ip_pol,BFS_vdef(name=5,from_switches=ip_core))
    gw_pol = gateway_forwarder(eth_cidr,ip_cidr,host_macs)

    return ((switch_in(ethernet) & eth_pol) + 
            (switch_in(gateway)  & gw_pol ) +
            (switch_in(ip_core)  & ip_pol ))    
def example_setup(num_clients=3, num_servers=3):
    ### EXAMPLE PARAMETERS
    # NETWORK BREAKDOWN
    ethernet = [2,3,4,1000]
    ip_core  = [5,6,7,1002]
    gateway  = [1001]

    # SUBNET ADDRESSING
    eth_prefix = '10.0.0.'
    ip_prefix  = '10.0.1.'
    prefix_len = 24
    eth_cidr = eth_prefix + '0/' + str(prefix_len)
    ip_cidr = ip_prefix + '0/' + str(prefix_len)

    # END HOST ADDRESSES
    public_ip = IP('10.0.1.100')
    fake_mac = MAC('BB:BB:BB:BB:BB:BB')
    eth_macs = { IP(eth_prefix+str(i+1)) : MAC('00:00:00:00:00:0'+str(i)) \
                     for i in range(1,1+num_clients) }
    ip_macs = { IP(ip_prefix+str(i+1)) : MAC('00:00:00:00:00:0'+str(i+num_clients)) \
                    for i in range(1,1+num_servers) }
    host_macs = dict(eth_macs.items() + ip_macs.items())
    host_macs.update({IP(public_ip) : fake_mac})

    # PARAMETERS FOR FIREWALL/LOAD BALANCER
    R = [IP(ip_prefix + str(i)) for i in range(2, 2+num_servers)]
    H = {IP(eth_prefix + str(i)) : 0 for i in range(2,2+num_clients)}
    W = {(c,public_ip) for c in H.keys()}

    ### POLICIES FOR THIS EXAMPLE
    eth_pol = mac_learner()
    alb = dynamic(lb)(public_ip,R,H) >> fix_dstmac(ip_macs) 
    afw = if_(ARP,passthrough,dynamic(fw)(W))
    ip_pol = if_(match(srcip=eth_cidr), 
                 afw >> alb, 
                 alb >> afw) >> mac_learner() 
    ip_pol = virtualize(ip_pol,BFS_vdef(name=5,from_switches=ip_core))
    gw_pol = gateway_forwarder(eth_cidr,ip_cidr,host_macs)

    return (switch_in(ethernet)[ eth_pol ] + 
            switch_in(gateway)[  gw_pol  ] +
            switch_in(ip_core)[  ip_pol  ])    
Example #26
0
def main(clients, servers):
    from pyretic.modules.mac_learner import mac_learner

    clients   = int(clients)
    servers   = int(servers)

    ip_prefix = "10.0.0."
    public_ip = IP(ip_prefix + "100")
    print("public ip address is %s." % public_ip)
    
    client_ips = [IP(ip_prefix+str(i)) for i in range(1, clients+1)]
    server_ips = [IP(ip_prefix+str(i)) for i in range(1+clients, clients+servers+1)]
    
    return rrlb(client_ips, server_ips, public_ip) >> mac_learner()
Example #27
0
def main(Clients, Servers):
	from pyretic.modules.mac_learner import mac_learner

	Clients   = int(Clients)
	Servers   = int(Servers)
	Device    = 4

	IP_Prefix = "10.0.0."
	PublicIP = IP(IP_Prefix + "100")
	print("Public ip address is %s." % PublicIP)
    
	ClientIPs = [IP(IP_Prefix+str(i)) for i in range(1, Clients+1)]
	ServerIPs = [IP(IP_Prefix+str(i)) for i in range(1+Clients, Clients+Servers+1)]
    
	return LoadBalancer(Device, ClientIPs, ServerIPs, PublicIP) >> mac_learner()
def main():
	from pyretic.modules.mac_learner import mac_learner
	from pyretic.examples.Monitor import Monitor
	from pyretic.examples.firewall import firewall_policy
	ARPPkt = match(ethtype=ARP_TYPE)
	Clients = 1
	Servers = 2
	Device_1 = 4
	Device_2 = 3
	PublicIP_1 = IP("10.0.100.1")
	PublicIP_2 = IP("10.0.100.2")
	ClientIPs = [IP("10.0.0.1"), IP("10.0.0.2"), IP("10.0.0.3"), IP("10.0.0.4")]
	ServerIPs_1 = [IP("10.0.0.5"), IP("10.0.0.6")]
	ServerIPs_2 = [IP("10.0.0.7"), IP("10.0.0.8")]
	LB_1 = LoadBalancer(Device_1, ClientIPs, ServerIPs_1, PublicIP_1)
	LB_2 = LoadBalancer(Device_2, ClientIPs, ServerIPs_2, PublicIP_2)
	LB_Monitor_Policy = (
			(ARPPkt >> mac_learner()) +
			( LB_1 >> mac_learner()) +
			( LB_2 >> mac_learner()) +
			Monitor(10)
		)

	return if_(firewall_policy, drop, LB_Monitor_Policy)
Example #29
0
	def ApplyFirewall(self):
		# Set rules to devices
		ac1 = self.ConfigureFW1()
		ac2 = self.ConfigureFW2()

		# Update block object
		if self.Blocked:
			self.Blocked = self.Blocked | ac1 | ac2
		else:
			self.Blocked = ac1 | ac2

		# The packets tha match Block object are dropped. The rest are forwarded.
		self.Allowed = if_(self.Blocked, drop, mac_learner())

		# Update policy object
		return self.UpdatePolicy()
def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment

    # start with a policy that doesn't match any packets
    not_allowed = none

    # and add traffic that isn't allowed
    with open(policy_file, 'rb') as f:
        reader = csv.DictReader(f)
        for row in reader:
            not_allowed = not_allowed + match(srcmac=MAC(row['mac_0']), dstmac=MAC(row['mac_1'])) + match(srcmac=MAC(row['mac_1']), dstmac=MAC(row['mac_0']))

    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #31
0
def main():
    # Copy the code you used to read firewall-policies.csv last week

    # start with a policy that doesn't match any packets
    not_allowed = none
    # and add traffic that isn't allowed
    for rule in rules_lst:
        rule_parts = rule.split(",")
        not_allowed = not_allowed | \ 
            match(srcmac=MAC(rule_parts[1]),dstmac=MAC(rule_parts[2])) | \ 
            match(srcmac=MAC(rule_parts[2]),dstmac=MAC(rule_parts[1])))

    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
def main(clients, servers):
    from pyretic.modules.mac_learner import mac_learner
    
    num_clients = int(clients)
    num_servers = int(servers)

    print "clients %d" % num_clients
    print "servers %d" % num_servers

    # CALCULATE IPS
    ip_prefix = '10.0.0.'
    public_ip = IP(ip_prefix + str(100))
    print "public_ip = %s" % public_ip
    
    client_ips = [IP(ip_prefix + str(i)) for i in range(1, 1+num_clients)]
    H = {c : 0 for c in client_ips}
    R = [IP(ip_prefix + str(i)) for i in range(1+num_clients, 1+num_clients+num_servers)]

    return static_lb(public_ip,R,H) >> mac_learner()     ## TEST ABOVE WORKS
def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment

    # start with a policy that doesn't match any packets
    not_allowed = none

    # and add traffic that isn't allowed
    with open(policy_file, 'rb') as f:
        reader = csv.DictReader(f)
        for row in reader:
            not_allowed = not_allowed + match(
                srcmac=MAC(row['mac_0']), dstmac=MAC(row['mac_1'])) + match(
                    srcmac=MAC(row['mac_1']), dstmac=MAC(row['mac_0']))

    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #34
0
def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment
    firewall_entries = []
    with open(policy_file) as f:
        next(f)
        csv_entries =  csv.reader(f, delimiter=',')
        for row in csv_entries:
            firewall_entries.append(row[1:])

    # and add traffic that isn't allowed
    not_allowed = union(
                  [match(srcmac=MAC(pair[0]), dstmac=MAC(pair[1])) for pair in firewall_entries] + 
                  [match(srcmac=MAC(pair[1]), dstmac=MAC(pair[0])) for pair in firewall_entries] )

    print not_allowed
    # express all wed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #35
0
def main():
    # Copy the code you used to read firewall-policies.csv last week
	def readPolicies(file) :
		macSet = Set()
		with open(file,'rb') as csvfile :
			fields  = csv.DictReader(csvfile)
			for row in fields:
				macSet.add( (row['mac_0'], row['mac_1']) )
		return macSet

	# start with a policy that doesn't match any packets
	not_allowed = none
	# and add traffic that isn't allowed
	for src, dst in readPolicies(policy_file):
		not_allowed = not_allowed + \
		( match(dstmac=MAC(dst)) >>  match(srcmac = MAC(src)) ) +\
		 ( match(dstmac=MAC(src)) >>  match(srcmac = MAC(dst) ))

    	allowed = ~ not_allowed 

    # and only send allowed traffic to the mac learning (act_like_switch) logic
	return allowed >> mac_learner()
def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment
    blockList=[]

    with open(policy_file) as f:
    	next(f)
    	reader = csv.reader(f, delimiter=',')
    	for row in reader:
    	    blockList.append(row[1:])

    # start with a policy that doesn't match any packets
    not_allowed = none

    # and add traffic that isn't allowed
    not_allowed = union([match(srcmac = MAC (pair[0]),dstmac = MAC(pair[1])) | 
            	match(srcmac = MAC (pair[1]),dstmac = MAC(pair[0])) for pair in blockList])

    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~ not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #37
0
def main():
    # Copy the code you used to read firewall-policies.csv last week
    data = open(policy_file)
    data.readline()
    # start with a policy that doesn't match any packets
    not_allowed = none
    while 1:
        line = data.readline()
        if not line:
            break
        # print line
        id, mac_0, mac_1 = line.split(',')
        # and add traffic that isn't allowed
        not_allowed = union( [not_allowed, match(dstmac=EthAddr(mac_1)) >>
            match(srcmac=EthAddr(mac_0))] )
        not_allowed = union( [not_allowed, match(dstmac=EthAddr(mac_0)) >>
            match(srcmac=EthAddr(mac_1))] )
    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #38
0
def main():
    rules = []

    f = open(policy_file)
    try:
        reader = csv.reader(f)
        for row in islice(reader, 1, None):
            rules.append({'src':row[1], 'dst':row[2]});
    finally:
        f.close()

    # start with a policy that doesn't match any packets
    not_allowed = none

    for rule in rules:
        not_allowed = not_allowed | match(srcmac=MAC(rule['src']), dstmac=MAC(rule['dst']))
        not_allowed = not_allowed | match(srcmac=MAC(rule['dst']), dstmac=MAC(rule['src']))

    allowed = ~not_allowed 

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #39
0
    def __init__(self): 
        super(metrics,self).__init__()

        # Probing attributes
	self.network = None
        self.topology = None
	self.logger = None	
        self.timer = None
        self.lock = threading.Lock()
        self.ipToSwitch = {} 
	self.seqCounter = 0
	# rather than use sequence number, we use alternating black/white
        # packets, where this is the packet 'protocol'
        self.switchToPort = None
        # Policies, callbacks, etc
        self.newIpQuery = packets(1,['srcip'])
	self.newIpQuery.register_callback(self.registerIp)
	self.query = packets()
        self.query.register_callback(self.registerProbe) 
        self.ipRules = None
	self.directRoute = None
	self.macLearn = mac_learner() 
	self.policy = drop
        self.floodPolicy = flood()
        self.dropPolicy = drop
	self.metricsPolicy = None
	self.reRoutingPolicy = None	
	self.inverseRoutingPolicy = None
	self.test2q = packets()
	self.test3q = packets()
	self.test4q = packets()
	self.test4q.register_callback(self.test2)
	self.test3q.register_callback(self.test)
	self.test5q = packets()
	self.test5q.register_callback(self.test3)
	self.test2q.register_callback(self.test)

	self.rulesSelfCheck = {}
Example #40
0
def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment
    fileOpen = open(policy_file)
    fileOpen.readline()
    # start with a policy that doesn't match any packets
    not_allowed = none
    while True:
        readLine = fileOpen.readline()
        if not readLine:
            break
        print readLine
        csvInfo = readLine.split(',')
        csvInfo[2].strip('\n')

        # and add traffic that isn't allowed
        not_allowed = union([
            not_allowed,
            match(dstmac=EthAddr(csvInfo[2])) >>
            match(srcmac=EthAddr(csvInfo[1]))
        ])
        not_allowed = union([
            not_allowed,
            match(dstmac=EthAddr(csvInfo[1])) >>
            match(srcmac=EthAddr(csvInfo[2]))
        ])

    # and add traffic that isn't allowed
    # for <each pair of MAC address in firewall-policies.csv>:
    #     not_allowed = union( [
    #         <traffic going in one direction>,
    #         <traffic going in the other direction> ] )

    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #41
0
def main():
    #intiailisation of the policies
    not_allowed = none

    # Useful Pyretic policies
    # match(f=v): filters only those packets whose header field f's value matches v
    # ~A: negates a match
    # A & B: logical intersection of matches A and B
    # A | B: logical union of matches A and B
    # fwd(a): forward packet out port a
    # flood(): send all packets to all ports on a network minimum spanning tree, except for the input port
    # A >> B: A's output becomes B's input
    # A + B: A's output and B's output are combined
    # if_(M,A,B): if packet filtered by M, then use A, otherwise use B

    #start with a policy that does not match any packet
    #and add traffic that is not allowed
    #for each pair two rules

    ifile = open(policy_file, "rb")
    reader = csv.reader(ifile)
    rownum = 0
    for row in reader:
        # Save header row.
        if rownum != 0:
            rule1 = match(srcmac=MAC(row[1])) & match(dstmac=MAC(row[2]))
            rule2 = match(srcmac=MAC(row[2])) & match(dstmac=MAC(row[1]))
            not_allowed = not_allowed | rule1 | rule2
        rownum += 1
    ifile.close()

    #express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    #and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #42
0
def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment
    blockList = []

    with open(policy_file) as f:
        next(f)
        reader = csv.reader(f, delimiter=',')
        for row in reader:
            blockList.append(row[1:])

    # start with a policy that doesn't match any packets
    not_allowed = none

    # and add traffic that isn't allowed
    not_allowed = union([
        match(srcmac=MAC(pair[0]), dstmac=MAC(pair[1]))
        | match(srcmac=MAC(pair[1]), dstmac=MAC(pair[0])) for pair in blockList
    ])

    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = ~not_allowed

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()
Example #43
0
		def allow_MAC(self,mac_var):
                tup_mac=(mac_var)
                flag=1
                print "Allowing MAC:",mac_var
                self.policy=if_(match(srcmac=EthAddr(mac_var)),mac_learner(),if_(match(dstmac=EthAddr(mac_var)),mac_learner(),self.policy))
                """result=checkAddress(1,mac_var)
Example #44
0
def staticFilterTcp():
	return if_(match(ethtype=packet.IPV4, protocol=packet.TCP_PROTO),genDynRules(),mac_learner())
Example #45
0
from pyretic.lib.corelib import *
from pyretic.lib.std import *

from pyretic.modules.mac_learner import mac_learner
import os

# insert the name of the module and policy you want to import
from pyretic.examples.<....> import <....>
policy_file = "%s/pyretic/pyretic/examples/firewall-policies.csv" % os.environ[ 'HOME' ]

def main():
    # Copy the code you used to read firewall-policies.csv from the Pox Firewall assignment

    # start with a policy that doesn't match any packets
    not_allowed = none

    # and add traffic that isn't allowed
    for <each pair of MAC address in firewall-policies.csv>:
        not_allowed = union( [
            <traffic going in one direction>,
            <traffic going in the other direction> ] )

    # express allowed traffic in terms of not_allowed - hint use '~'
    allowed = <...>

    # and only send allowed traffic to the mac learning (act_like_switch) logic
    return allowed >> mac_learner()



Example #46
0
def main():
    return pyretic_gardenwall() >> mac_learner()
Example #47
0
def main():
    #    return (packet_counts() +
    #            byte_counts() +
    #            mac_learner())
    return (proactive_counts() + mac_learner())
def main():
    from pyretic.modules.mac_learner import mac_learner

    return soft_cap_enforcer() >> mac_learner()
Example #49
0
def arp_and_mac_learn():
    """Handle ARPs and do MAC learning"""
    return if_(ARP, arp(), mac_learner())
                print "******************************************************************"
                mac_var=raw_input("Enter MAC you want to block : ")
                self.block_MAC(mac_var)
            elif ch==5:
                exit()
            else:
                print "******************************************************************"
                print "Invalid choice"
        except ValueError:
            print "Invalid User Input"

    def allow_IP(self,ip_var):
        #tup_ip=(ip_var)
		flag=0
        print "Allowing ip :",ip_var
		self.policy=if_(match(srcip=IPAddr(ip_var)),mac_learner(),self.policy)>>if_(match(dstip=IPAddr(ip_var)),mac_learner(),self.policy)
		"""result=checkAddress(0,ip_var)
        if result=="present":
			print "IP %s is already allowed"%ip_var
		else:
			UIFirewall.ips.append(ip_var)
			self.policy=if_(match(srcip=IPAddr(ip_var)),mac_learner,self.policy)>>if_(match(dstip=IPAddr(ip_var)),mac_learner,self.policy)
        """
		
		"""
		try:
            index=UIFirewall.ips.index(ip_var)
            print "IP %s is already allowed"%ip_var
            
        except:
            UIFirewall.ips.append(ip_var)
Example #51
0
def setup(num_internet_hosts=253, num_dmz_servers=1, num_internal_hosts=2):
    #-----------------
    #Network breakdown (virtual components)
    internal_net_edge = [1000]
    gateway = [1001]
    blackhole_checker_redirector = [1002]
    firewall = [1003]
    internet_edge = [1004]

    #-----------------
    #IP subnets
    internal_prefix = '10.1.1.'
    internet_prefix = '10.1.2.'
    prefix_len = 24
    internal_cidr = internal_prefix + '0/' + str(prefix_len)
    internet_cidr = internet_prefix + '0/' + str(prefix_len)

    #-----------------
    #End hosts and servers
    internal_ip_to_macs = {
        IP(internal_prefix + str(i + 1)): MAC('00:00:00:00:00:0' + str(i))
        for i in range(1, 1 + num_internal_hosts + num_dmz_servers)
    }
    internet_ip_to_macs = {
        IP(internet_prefix + str(i + 1)): MAC('00:00:00:00:00:04')
        for i in range(1, 1 + num_internet_hosts)
    }
    host_ip_to_macs = dict(internal_ip_to_macs.items() +
                           internet_ip_to_macs.items())

    #-----------------
    #params for blackhole checker/redirector

    #threshold rate of packets belonging to the same (srcip,dstip,dstport) flow (careful: TCP protocol!)
    #if this rate is surpassed, we conider this a possible DoS and redirect
    #the flow to the blackhole host for further examination
    threshold_rate = 5  #packets per sec (you can tune it if needed)
    blackhole_port_dict = {
        'untrusted': 2,
        'trusted': 1,
        'blackhole': 3
    }  #see exercise setup (figure 2)
    ips_and_tcp_ports_to_protect = [("10.1.1.4", 80)]  #protect apache server

    #-----------------
    #params for firewall
    firewall_port_dict = {
        'untrusted': 2,
        'trusted': 1
    }  #see exercise setup (ports of firewall, figure 2)

    whitelist = set([])
    for i in internal_ip_to_macs.keys():
        for j in internet_ip_to_macs.keys():
            internal_ip = str(i)
            internet_ip = str(j)

            #here we check if the internal_ip is the server
            #and if this is the server we make by-directional connection
            #else we make one direction connection
            if internal_ip != '10.1.1.4':
                whitelist.add((internal_ip, internet_ip))
            else:
                whitelist.add((internal_ip, internet_ip))
                whitelist.add((internet_ip, internal_ip))
            #ATTENTION: Build whitelist!!! (see how firewall expects it)
    print "Firewall whitelist"
    print whitelist

    #-----------------
    #policies
    #ATTENTION: internal network edge policy???
    #ATTENTION: gateway policy???
    #ATTENTION: black-hole host policy??
    #ATTENTION: firewall policy???-->ATTENTION: besides the IP whitelist, the firewall policy should let ARP packets reach the gateway! (hint: use 'if_')
    #ATTENTION: internet edge policy???

    #initial test policies for firewall and blackhole
    #blackhole_pol=
    blackhole_pol = BlackholeCheckerRedirector(threshold_rate,
                                               blackhole_port_dict,
                                               ips_and_tcp_ports_to_protect)
    # proo8ei to paketo
    firewall_pol = (
        if_(ARP, passthrough, fw(whitelist)) >> dumb_forwarder(1, 2))
    #idio level
    eth_pol = mac_learner()
    ip_pol = mac_learner()

    gw_pol = gateway_forwarder(internal_cidr, internet_cidr, host_ip_to_macs)

    return ((switch_in(blackhole_checker_redirector) >> blackhole_pol) +
            (switch_in(firewall) >> firewall_pol) +
            (switch_in(internal_net_edge) >> eth_pol) +
            (switch_in(gateway) >> gw_pol) +
            (switch_in(internet_edge) >> ip_pol))
Example #52
0
def main():
    return pyretic_gardenwall() >> mac_learner()
Example #53
0
def main():
    return (packet_counts() + packet_sizes() + mac_learner())
def main():
  from pyretic.modules.mac_learner import mac_learner

  return soft_cap_enforcer() >> mac_learner()
  
Example #55
0
 def __init__(self):
         super(UIFirewall,self).__init__(true)
         self.policy=mac_learner()
         ob=Thread(target=self.UI_Loop)
         ob.start()
Example #56
0
class UIFirewall(DynamicPolicy):
        ips=[]
        macs=[]
        flag=0

        def __init__(self):
                super(UIFirewall,self).__init__(true)
                self.policy=mac_learner()
                ob=Thread(target=self.UI_Loop)
                ob.start()

        def UI_Loop(self):
                print "\t\t\t Starting Controller...."
                print "*********************WELCOME TO UI CONTROLLER*********************"

                while True:
                #get argument
                        print "\nUSER CHOICE:\n-->1.Allow IP\n-->2.Block IP\n-->3.Allow MAC\n-->4.Block MAC\n-->5.Exit"
                        print "\n******************************************************************"
                        self.accept_user_choice()

        def accept_user_choice(self):
                try:
                        ch=int(raw_input("Please enter your choice --> "))
                        print "\n"
                        if ch==1:
                                print "******************************************************************"

                                ip_var=raw_input("Enter IP address you want to allow : ")
                                match = re.search(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', ip_var)
                                if match:
									 self.allow_IP(ip_var)
                                else:
                                        print "invalid IP"
                        elif ch==2:
                                print "******************************************************************"
                                ip_var=raw_input("Enter IP address you want to block : ")
                                match = re.search(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$', ip_var)
                                if match:
                                        self.block_IP(ip_var)
                                else:
                                        print "invalid IP"

                        elif ch==3:
                                print "******************************************************************"
                                mac_var=raw_input("Enter MAC you want to allow : ")
                                if re.match(r"([\dA-F]{2}(?:[:][\dA-F]{2}){5})",mac_var):
                                        self.allow_MAC(mac_var)
                                else:
                                        print "Invalid MAC"
                        elif ch==4:
                                print "******************************************************************"
                                mac_var=raw_input("Enter MAC you want to block : ")
                                if re.match(r"([\dA-F]{2}(?:[:][\dA-F]{2}){5})",mac_var):
                                        self.block_MAC(mac_var)
                                else:
                                        print "Invalid MAC"
                        elif ch==5:
                                exit()
                        else:
                                print "******************************************************************"
                                print "Invalid choice"
                except ValueError:
                        print "Invalid User Input"

        def allow_IP(self,ip_var):
                #tup_ip=(ip_var)
                flag=0
				print "Allowing ip :",ip_var
                #self.policy=if_(~match(srcip=IPAddr(ip_var)),drop,mac_learner)>>if_(~match(dstip=IPAddr(ip_var)),drop,mac_learner)
                self.policy=if_(match(srcip=IPAddr(ip_var)),mac_learner(),if_(match(dstip=IPAddr(ip_var)),mac_learner(),self.policy))
                print self.policy
                """result=checkAddress(0,ip_var)
                if result=="present":
                        print "IP %s is already allowed"%ip_var
                else:
                        UIFirewall.ips.append(ip_var)
                        self.policy=if_(match(srcip=IPAddr(ip_var)),mac_learner,self.policy)>>if_(match(dstip=IPAddr(ip_var)),mac_learner,self.policy)
                """


                """try:
Example #57
0
def setup(num_internet_hosts=253, num_dmz_servers=1, num_internal_hosts=2):
    #-----------------
    #Network breakdown (the virtual components in Pyretic)
    internal_net_edge = [1000]
    gateway = [1001]
    flow_monitor_blackhole_redirector = [1002]
    firewall = [1003]
    internet_edge = [1004]

    #-----------------
    #IP subnets
    internal_prefix = '10.1.1.'
    internet_prefix = '10.1.2.'
    prefix_len = 24
    internal_cidr = internal_prefix + '0/' + str(prefix_len)
    internet_cidr = internet_prefix + '0/' + str(prefix_len)

    #-----------------
    #End hosts and servers
    internal_ip_to_macs = {
        IP(internal_prefix + str(i)): MAC('00:00:00:00:00:0' + str(i))
        for i in range(1, 1 + num_internal_hosts + num_dmz_servers)
    }
    internet_ip_to_macs = {
        IP(internet_prefix + str(i)): MAC('00:00:00:00:00:04')
        for i in range(1, 1 + num_internet_hosts)
    }
    host_ip_to_macs = dict(internal_ip_to_macs.items() +
                           internet_ip_to_macs.items())

    print "Third Arguement:" + str(host_ip_to_macs)
    #-----------------
    #Parameters for flow monitor and blackhole redirector.
    #Threshold rate of packets belonging to the same (srcip,dstip,dstport) flow.
    #If this rate is surpassed, the flow is suspected to be a DoS attack; then redirect flow to the blackhole host.
    threshold_rate = 5  #packets per sec (you can change this if you want to check)
    blackhole_port_dict = {
        'untrusted': 2,
        'trusted': 1,
        'blackhole': 3
    }  #see Figure 2 in the project description
    ips_and_tcp_ports_to_protect = [("10.1.1.3", 80)
                                    ]  #protect the Apache server

    #-----------------
    #Parameters for the stateful firewall
    firewall_port_dict = {
        'untrusted': 2,
        'trusted': 1
    }  #see Figure 2 in project description
    whitelist = set([])
    for i in internal_ip_to_macs.keys():
        for j in internet_ip_to_macs.keys():
            internal_ip = str(i)
            internet_ip = str(j)
            if (internal_ip == '10.1.1.3'):
                whitelist.add((internal_ip, internet_ip))
                whitelist.add((internet_ip, internal_ip))
            else:
                whitelist.add((internal_ip, internet_ip))

### write your code ###: Build whitelist of IP addresses (see how firewall expects it)
    print "Firewall whitelist:"
    print whitelist

    #-----------------
    #Define policies
    ### write your code ###: internal network edge policy?
    internal_network_edge_policy = mac_learner()
    ### write your code ###: gateway policy?
    gateway_policy = gateway_forwarder(internal_cidr, internet_cidr,
                                       host_ip_to_macs)
    ### write your code ###: blackhole host policy?
    blackhole_policy = FlowMonitorBlackholeRedirector(
        threshold_rate, blackhole_port_dict, ips_and_tcp_ports_to_protect)
    ### write your code ###: firewall policy? Note that besides the IP addresses in the firewall whitelist, the firewall policy should let ARP packets reach the gateway (hint: use 'if_')

    ### write your code ###: internet edge policy???
    internet_edge_policy = mac_learner()
    #Commands to do initial test of policies for firewall and blackhole
    firewall_policy = if_(ARP, passthrough, fw(whitelist)) >> dumb_forwarder(
        firewall_port_dict['trusted'], firewall_port_dict['untrusted'])

    #-----------------
    ### write your code ###: return ? --> Combine the policies! (Hint: check gateway_3switch_example_basic.py in the ~/pyretic/pyretic/examples directory)
    return (
        (switch_in(internal_net_edge) >> internal_network_edge_policy) +
        (switch_in(gateway) >> gateway_policy) +
        (switch_in(flow_monitor_blackhole_redirector) >> blackhole_policy) +
        (switch_in(firewall) >> firewall_policy) +
        (switch_in(internet_edge) >> internet_edge_policy))
def main():
    return (packet_counts() + byte_counts() + mac_learner())
Example #59
0
def main(**kwargs):
    return test_setup(test_mains, mac_learner(), **kwargs)