Exemple #1
0
    def init_floating_network(self):
        """
        Initialize the floating network component for the emulator.
        Will not do anything if already initialized.
        """
        if self.net is not None and self.floating_switch is None:
            # create a floating network
            fn = self.floating_network = Net("default")
            fn.id = str(uuid.uuid4())
            fn.set_cidr(self.floating_netmask)

            # create a subnet
            fn.subnet_id = str(uuid.uuid4())
            fn.subnet_name = fn.name + "-sub"

            # create a port for the host
            port = Port("root-port")
            #port.id = str(uuid.uuid4())
            port.net_name = fn.name

            # get next free ip
            root_ip = fn.get_new_ip_address(port.name)
            port.ip_address = root_ip
            # floating ip network setup
            # wierd way of getting a datacenter object
            first_dc = self.net.dcs.values()[0]
            # set a dpid for the switch. for this we have to get the id of the next possible dc
            self.floating_switch = self.net.addSwitch("fs1", dpid=hex(first_dc._get_next_dc_dpid())[2:])
            # this is the interface appearing on the physical host
            self.floating_root = Node('root', inNamespace=False)
            self.net.hosts.append(self.floating_root)
            self.net.nameToNode['root'] = self.floating_root
            self.floating_intf = self.net.addLink(self.floating_root, self.floating_switch).intf1
            self.floating_root.setIP(root_ip, intf=self.floating_intf)
            self.floating_nodes[(self.floating_root.name, root_ip)] = self.floating_root
	def checkOVS(self):
		root = Node('root', inNamespace=False)
		modinfo = root.cmd("modinfo openvswitch | grep version: |awk -F':' '{print $2}' | awk '{ gsub (\" \", \"\", $0); print}'")
		versions = modinfo.split("\n")
		version = versions[0]
		print "modinfo openviswitch : " + version
		# SS 2017-10-21 I've disabled the version check because in the packaged openvswitch there is no version info
		# modversion = float(version[:3])
		# if modversion < 2.3:
		# 	error( 'OVS Kernel Module does not respect version requirement\nPlease check your OVS installation\n' )
		# 	exit( 1 )

		vswitchdinfo = root.cmd("ovs-vswitchd --version | grep ovs-vswitchd |awk -F')' '{print $2}' | awk '{ gsub (\" \", \"\", $0); print}'")
		versions = vswitchdinfo.split("\n")
		version = versions[0]
		print "ovs-vswitchd --version : " + version

		#vswitchdversion = float(version[:3])
		#if vswitchdversion < 2.3:
		major = version.split(".")[0]
		minor = version.split(".")[1]
		if major < 2:
			error( 'OVS vswitchd does not respect version requirement\nPlease check your OVS installation\n' )
			exit( 1 )
		if minor < 3:
			error( 'OVS vswitchd does not respect version requirement\nPlease check your OVS installation\n' )
			exit( 1 )		

		# SS 2017-10-21 I've disabled the version check because in the packaged openvswitch there is no version info
		# if modversion != vswitchdversion:
		# 	error( 'OVS Kernel module version and OVS vswitchd version are different\nPlease check your OVS installation\n' )
		# 	exit( 1)

		openvswitchd = root.cmd('ls %s 2> /dev/null | wc -l' % self.ovs_initd)
def connectToInternet( network ):
    "Connect the network to the internet"
    switch = network.switches[ 0 ]  # switch to use
    ip = '10.0.0.254'  # our IP address on host network
    routes = [ '10.0.0.0/24' ]  # host networks to route to
    prefixLen = 24 # subnet mask length
    inetIface = "eth0" # host interface for internet connectivity

    # Create a node in root namespace and link to switch 0
    root = Node( 'root', inNamespace=False )
    intf = Link( root, switch ).intf1
    #intf = createLink( root, switch )[ 0 ]
    #root.setIP( intf, ip, prefixLen )
    root.setIP( ip, prefixLen, intf)

    # Start network that now includes link to root namespace
    network.start()

    # Start NAT and establish forwarding
    startNAT( inetIface, root )

    # Establish routes from end hosts
    for host in network.hosts:
        host.cmd( 'ip route flush root 0/0' )
        #host.cmd( 'route add -net 10.0.0.0/24 dev ' + host.intfs[0] )
        host.cmd( 'route add -net 10.0.0.0/24 dev ' + host.intfs[0].name )
        host.cmd( 'route add default gw ' + ip )
        
    return root
Exemple #4
0
	def checkSR(self):
		root = Node( 'root', inNamespace=False)
		sr = root.cmd('ls %s 2> /dev/null | wc -l' % self.SR_exec)
		if '1' not in sr:
			error( 'Cannot find required executable fpm-of.bin\nPlease make sure that fpm-of.bin is properly installed in ' + self.SR_path + '\n'
				   'Otherwise change sr_path variable according to your configuration\n' )
			exit( 1 )
class MyTopo(object):
    def __init__(self, cname='onos', cips=['10.0.3.1']):
        # Create network with multiple controllers
        self.net = Mininet(controller=RemoteController, switch=OVSKernelSwitch,
                           build=False)
 
        # Add controllers with input IPs to the network
        ctrls = [RemoteController(cname, cip, 6633) for cip in cips]
        for ctrl in ctrls:
            print ctrl.ip
            self.net.addController(ctrl)
 
        # Add switch
        self.s2 = self.net.addSwitch('s2', dpid='00000000000000a2')
	
	# Connect root namespace to the switch
	self.root = Node('root', inNamespace=False)
	intf = self.net.addLink(self.root, self.s2).intf1
	self.root.setIP('10.0.0.1/32', intf=intf)

	# Add host
	h2 = self.net.addHost('h2', ip='10.0.0.12/24', mac='00:00:00:00:00:02')
	self.net.addLink(h2, self.s2)

    def run(self):
        self.net.build()
        self.net.start()
        self.s2.cmd('ovs-vsctl set bridge s2 protocols=OpenFlow13')
        self.s2.cmd('ovs-vsctl add-port s2 vxlan2')
        self.s2.cmd('ovs-vsctl set interface vxlan2 type=vxlan option:remote_ip=104.236.158.75 option:key=flow')
	self.root.cmd('route add -net 10.0.0.0/24 dev root-eth0')
        CLI(self.net)
        self.net.stop()
Exemple #6
0
def startNetwork(network, switch, ip, routes):
    root = Node('root', inNamespace=False)
    intf = Link(root, switch).intf1
    root.setIP(ip, intf=intf)
    network.start()
    for route in routes:
        root.cmd( 'route add -net ' + route + ' dev ' + str( intf ) )
def connectToInternet(network, switch='s1', rootip='10.254', subnet='10.0/8'):
    """Connect the network to the internet
       switch: switch to connect to root namespace
       rootip: address for interface in root namespace
       subnet: Mininet subnet"""
    switch = network.get(switch)
    prefixLen = subnet.split('/')[1]

    # Create a node in root namespace
    root = Node('root', inNamespace=False)

    # Prevent network-manager from interfering with our interface
    fixNetworkManager(root, 'root-eth0')

    # Create link between root NS and switch
    link = network.addLink(root, switch)
    link.intf1.setIP(rootip, prefixLen)

    # Start network that now includes link to root namespace
    network.start()

    # Start NAT and establish forwarding
    startNAT(root)

    # Establish routes from end hosts
    for host in network.hosts:
        host.cmd('ip route flush root 0/0')
        host.cmd('route add -net', subnet, 'dev', host.defaultIntf())
        host.cmd('route add default gw', rootip)

    # set up MTU
    root.cmd('ifconfig root-eth0 mtu 1300')

    return root
Exemple #8
0
	def checkOVS(self):
		root = Node('root', inNamespace=False)
		modinfo = root.cmd("modinfo openvswitch | grep version: |awk -F':' '{print $2}' | awk '{ gsub (\" \", \"\", $0); print}'")
		versions = modinfo.split("\n")
		version = versions[0]
		modversion = float(version[:3])
		if modversion < 2.3:
			error( 'OVS Kernel Module does not respect version requirement\nPlease check your OVS installation\n' )
			exit( 1 )

		vswitchdinfo = root.cmd("ovs-vswitchd --version | grep ovs-vswitchd |awk -F')' '{print $2}' | awk '{ gsub (\" \", \"\", $0); print}'")
		versions = vswitchdinfo.split("\n")
		version = versions[0]
		vswitchdversion = float(version[:3])
		if vswitchdversion < 2.3:
			error( 'OVS vswitchd does not respect version requirement\nPlease check your OVS installation\n' )
			exit( 1 )

		if modversion != vswitchdversion:
			error( 'OVS Kernel module version and OVS vswitchd version are different\nPlease check your OVS installation\n' )
			exit( 1)

		openvswitchd = root.cmd('ls %s 2> /dev/null | wc -l' % self.ovs_initd)
		if '1' not in openvswitchd:
			error( 'Cannot find required executable /etc/init.d/openvswitchd\nPlease make sure that OVS is properly installed\n')
			exit( 1 )
Exemple #9
0
 def stop( self, deleteIntfs=False ):
     dev_null = open(os.devnull, 'w')
     subprocess.call( [ 'docker rm -f ' + self.name ],
                      stdin=dev_null, stdout=dev_null,
                      stderr=dev_null, shell=True )
     dev_null.close()
     Node.stop( self, deleteIntfs )
Exemple #10
0
def connectToRootNS(network, switch, ip, routes):
    root = Node('root', inNamespace=False)
    intf = network.addLink(root, switch).intf1
    root.setIP(ip, intf=intf)
    network.start()
    for route in routes:
        root.cmd('route add -net {} dev {} '.format(route, intf)) 
    def checkOVS(self):
        root = Node('root', inNamespace=False)
        modinfo = root.cmd(
            "modinfo openvswitch | grep version: |awk -F':' '{print $2}' | awk '{ gsub (\" \", \"\", $0); print}'"
        )
        versions = modinfo.split("\n")
        version = versions[0]
        print "modinfo openviswitch : " + version
        # SS 2017-10-21 I've disabled the version check because in the packaged openvswitch there is no version info
        # modversion = float(version[:3])
        # if modversion < 2.3:
        # 	error( 'OVS Kernel Module does not respect version requirement\nPlease check your OVS installation\n' )
        # 	exit( 1 )

        vswitchdinfo = root.cmd(
            "ovs-vswitchd --version | grep ovs-vswitchd |awk -F')' '{print $2}' | awk '{ gsub (\" \", \"\", $0); print}'"
        )
        versions = vswitchdinfo.split("\n")
        version = versions[0]
        print "ovs-vswitchd --version : " + version
        vswitchdversion = float(version[:3])
        if vswitchdversion < 2.3:
            error(
                'OVS vswitchd does not respect version requirement\nPlease check your OVS installation\n'
            )
            exit(1)

        # SS 2017-10-21 I've disabled the version check because in the packaged openvswitch there is no version info
        # if modversion != vswitchdversion:
        # 	error( 'OVS Kernel module version and OVS vswitchd version are different\nPlease check your OVS installation\n' )
        # 	exit( 1)

        openvswitchd = root.cmd('ls %s 2> /dev/null | wc -l' % self.ovs_initd)
Exemple #12
0
    def __init__(self, name, inMountNamespace=False, inPIDNamespace=False,
                 inUTSNamespace=False, **params):
        """name: name of node
           inNamespace: in network namespace?
           inMountNamespace: has private mountspace?
           inPIDNamespace: has private PID namespace?
           params: Node parameters (see config() for details)"""

        # PID and Mount Namespace handling
        self.inPIDNamespace = inPIDNamespace
        self.inUTSNamespace = inUTSNamespace
        self.inMountNamespace = inMountNamespace

        # Private config monitoring
        self.hasPrivateLogs = False
        self.hasPrivateRun = False

        # Sanity check on namespace config
        if self.inPIDNamespace is True and self.inMountNamespace is False:
            raise Exception('PID namespaces require mount namespace for /proc')

        # Stash extended configuration information
        self.services = {}  # dict of services and parameters for this node
        self.privateMounts = {}  # dict of private mounts for this node

        # Network information
        self.loIntfs = {}

        # Request initialization of the BaseNode
        BaseNode.__init__(self, name, **params)
Exemple #13
0
    def __init__(self,
                 name,
                 inMountNamespace=False,
                 inPIDNamespace=False,
                 inUTSNamespace=False,
                 **params):
        """name: name of node
           inNamespace: in network namespace?
           inMountNamespace: has private mountspace?
           inPIDNamespace: has private PID namespace?
           params: Node parameters (see config() for details)"""

        # PID and Mount Namespace handling
        self.inPIDNamespace = inPIDNamespace
        self.inUTSNamespace = inUTSNamespace
        self.inMountNamespace = inMountNamespace

        # Private config monitoring
        self.hasPrivateLogs = False
        self.hasPrivateRun = False

        # Sanity check on namespace config
        if self.inPIDNamespace is True and self.inMountNamespace is False:
            raise Exception('PID namespaces require mount namespace for /proc')

        # Stash extended configuration information
        self.services = {}  # dict of services and parameters for this node
        self.privateMounts = {}  # dict of private mounts for this node

        # Network information
        self.loIntfs = {}

        # Request initialization of the BaseNode
        BaseNode.__init__(self, name, **params)
Exemple #14
0
def start():

    global net, attacker, running

    if running:
        return '\nServer already running.\n'

    setLogLevel('info')

    topo = MixTopo()
    net = Mininet(topo=topo)

    s1 = net['s1']
    plc2 = net['plc2']
    plc3 = net['plc3']

    s2, rtu2a, scada = net.get('s2', 'rtu2a', 'scada')
    rtu2b, attacker2 = net.get('rtu2b', 'attacker2')
    s3 = net.get('s3')

    # NOTE: root-eth0 interface on the host
    root = Node('root', inNamespace=False)
    intf = net.addLink(root, s3).intf1
    print('DEBUG root intf: {}'.format(intf))
    root.setIP('10.0.0.30', intf=intf)
    # NOTE: all packet from root to the 10.0.0.0 network
    root.cmd('route add -net ' + '10.0.0.0' + ' dev ' + str(intf))


    net.start()
    info('Welcome')

    # NOTE: use for debugging
    #s1.cmd('tcpdump -i s1-eth1 -w /tmp/s1-eth1.pcap &')
    #s1.cmd('tcpdump -i s1-eth2 -w /tmp/s1-eth2.pcap &')

    SLEEP = 0.5

    # NOTE: swat challenge 1 and 2
    plc3.cmd(sys.executable + ' plc3.py &')
    sleep(SLEEP)
    plc2.cmd(sys.executable + ' plc2.py &')
    sleep(SLEEP)

    # NOTE: wadi challenge 1
    scada.cmd(sys.executable + ' scada.py &')
    sleep(SLEEP)
    rtu2a.cmd(sys.executable + ' rtu2a.py &')
    sleep(SLEEP)
    # NOTE: wadi challenge 2
    rtu2b.cmd(sys.executable + ' rtu2b.py &')
    sleep(SLEEP)


    running = True
    return '\nServer started.\n'
Exemple #15
0
 def stop(self, *args, **kwargs):
     if self._is_active:
         self.stopcmd(self, *args, **kwargs)
         self._is_active = False
         # bypass Controller stop method
         Node.stop(self)
     else:
         warn(
             newline('<! Cannot stop the inactive controller', self.name,
                     '!>'))
Exemple #16
0
 def sendInt(self, sig=signal.SIGINT):
     """Interrupt running command."""
     if self.lastPid and self.inPIDNamespace:
         # Cannot kill via os.kill (wrong PID namespace)
         # Instead, we kill by running 'kill -SIGNAL pid
         # inside of the namespace itself....
         killStr = "kill -%d %d" % (sig, self.lastPid)
         self.pexec(killStr)
     else:
         BaseNode.sendInt(self)
Exemple #17
0
 def sendInt(self, sig=signal.SIGINT):
     """Interrupt running command."""
     if self.lastPid and self.inPIDNamespace:
         # Cannot kill via os.kill (wrong PID namespace)
         # Instead, we kill by running 'kill -SIGNAL pid
         # inside of the namespace itself....
         killStr = "kill -%d %d" % (sig, self.lastPid)
         self.pexec(killStr)
     else:
         BaseNode.sendInt(self)
def myNet(cname='controller', cargs='-v ptcp:'):
    "create network from scratch using Open vSwitch."
    info("*** Createing nodes\n")
    controller=Node('c0',inNamespace=False)
    switch=Node('s1',inNamespace=False)
    switch1=Node('s1',inNamespace=False)
    h0=Node('h0')
    h1=Node('h1')
    
    
Exemple #19
0
 def checkSR(self):
     root = Node('root', inNamespace=False)
     sr = root.cmd('ls %s 2> /dev/null | wc -l' % self.SR_exec)
     if '1' not in sr:
         error(
             'Cannot find required executable fpm-of.bin\nPlease make sure that fpm-of.bin is properly installed in '
             + self.SR_path + '\n'
             'Otherwise change sr_path variable according to your configuration\n'
         )
         exit(1)
Exemple #20
0
def fixSwitchIntf(swi):
    for i in range(0, len(swi)):
        for obj in swi[i].nameToIntf:
            if 'lo' not in obj:
                fixNetworkManager(obj)
        fixNetworkManager(swi[i])
    root = Node('root', inNamespace=False)
    print "Restarting Network Manager"
    time.sleep(10)
    root.cmd('service network-manager restart')
    time.sleep(2)
def configure_l2_accessnetwork():
	print "*** Configure L2 Access Networks"
	root = Node( 'root', inNamespace=False )
	print "*** Configure L2 Access Ports" 
	for key, value in ACCESS_TO_TAG.iteritems():
		print "*** Configure", key, "As Access Port, TAG=", value
		root.cmd("ovs-vsctl set port %s tag=%s" %(key, value))
	print "*** Configure L2 Trunk Ports"
	for key, value in TRUNK_TO_TAG.iteritems():
		print "*** Configure", key, "As Trunk Port, TAG=", value
		root.cmd("ovs-vsctl set port %s trunks=%s" %(key, value))
def fixSwitchIntf(swi):
  for i in range(0, len(swi)):
    for obj in swi[i].nameToIntf:
      if 'lo' not in obj:
	fixNetworkManager(obj)	
    fixNetworkManager(swi[i])    
  root = Node( 'root', inNamespace=False )
  print "Restarting Network Manager"
  time.sleep(10)
  root.cmd('service network-manager restart')
  time.sleep(2)
Exemple #23
0
 def __init__(self, name, image=None, port_map=None, fs_map=None, **kwargs):
     if image is None:
         raise UnboundLocalError('Docker image is not specified')
     img_id = subprocess.check_output(['docker', 'images', '-q', image])
     if not img_id:
         raise ValueError('Docker image "%s" does not exist' % image)
     self.docker_image = image
     self.port_map = port_map
     self.fs_map = fs_map
     kwargs['inNamespace'] = True
     Node.__init__(self, name, **kwargs)
Exemple #24
0
 def __init__(self, name, image=None, port_map=None, fs_map=None, **kwargs):
     if image is None:
         raise UnboundLocalError('Docker image is not specified')
     img_id = subprocess.check_output(['docker', 'images', '-q', image])
     if not img_id:
         raise ValueError('Docker image "%s" does not exist' % image)
     self.docker_image = image
     self.port_map = port_map
     self.fs_map = fs_map
     kwargs['inNamespace'] = True
     Node.__init__(self, name, **kwargs)
Exemple #25
0
	def checkQuagga(self):
		root = Node( 'root', inNamespace=False )
		zebra = root.cmd('ls %s 2> /dev/null | wc -l' % self.zebra_exec)
		if '1' not in zebra:
			error( 'Cannot find required executable zebra\nPlease make sure that Zebra is properly installed in ' + self.quaggaPath + '\n'
				   'Otherwise change quaggaPath variable according to your configuration\n' )
			exit( 1 )
		ospfd = root.cmd('ls %s 2> /dev/null | wc -l' % self.ospfd_exec)
		if '1' not in ospfd:
			error( 'Cannot find required executable ospfd\nPlease make sure that OSPFD is properly installed in ' + self.quaggaPath + '\n'
				   'Otherwise change quaggaPath variable according to your configuration\n' )
			exit( 1 )
Exemple #26
0
def sshd_connectToRootNS(args,network):
	
	#we create node root and attach it to a swtich
	switch = network.getNodeByName(args.names.sw_sshd[0])

	#ip of root
	ip = '172.16.255.1/32' 
	
	root = Node( 'root', inNamespace=False )
	intf = Link( root, switch ).intf1
	root.setIP( ip, intf=intf )

	return root,intf
Exemple #27
0
def connectToRootNS(network, switch, ip, routes):
    root = Node('root', inNamespace=False)
    intf = network.addLink(root, switch).intf1
    root.setIP(ip, intf=intf)
    root.setMAC("10:00:00:00:00:00")

    network.start()
    for route in routes:
        root.cmd('route add -net ' + route + ' dev ' + str(intf))
        print("route add completed=================")
    for route in routes:
        root.cmd('route add -net ' + route + ' dev ' + str(intf))
        print("route add completed=================")
    def __init__(self, verbose=False):

        self.checkPATHs()

        Mininet.__init__(self, build=False)

        self.cr_oshis = []
        self.pe_oshis = []
        self.ce_routers = []
        self.ctrls = []
        self.nodes_in_rn = []
        self.node_to_data = defaultdict(list)
        self.node_to_node = {}
        self.node_to_default_via = {}
        self.coex = {}
        

        self.verbose = verbose
        lg.setLogLevel('info')

        self.vlls = []

        self.node_to_pw_data = defaultdict(list)
        self.pws = []

        self.cer_to_customer = {}
        self.customer_to_vtepallocator = {}

        self.vsfs = []
        self.pe_cer_to_vsf = {}

        self.is_vs = False
        self.vss = []
        self.vss_data = []
        self.id_peo_to_vs = {}
        self.last_ipnet = IPv4Network(u'0.0.0.0/24')

        self.id_to_node = {}
        self.ip_to_mac = {}

        self.overall_info = {}
        
        self.mgmt = None

        root = Node( 'root', inNamespace=False )
        root.cmd('/etc/init.d/network-manager stop')
        mylog("*** Stop Network Manager\n")

        self.cluster_to_ctrl = defaultdict(list)
        self.cluster_to_nodes = defaultdict(list)
        self.nodes_to_cluster = {}
Exemple #29
0
    def __init__(self, numEdgeSwitches=4):

        super(FattreeTopology, self).__init__()

        # add switches
        numHosts = 4 * numEdgeSwitches
        numCoreSwitches = 2
        hosts = range(1, numHosts + 1)
        firstSwitch = max(101, numHosts + 1)
        edgeSwitches = range(firstSwitch, numEdgeSwitches + firstSwitch)
        self.edgeSwitches = edgeSwitches
        coreSwitches = range(numEdgeSwitches + firstSwitch,
                             numEdgeSwitches + firstSwitch + numCoreSwitches)
        self.coreSwitches = coreSwitches

        # Add switches
        for s in edgeSwitches:
            self.add_node(s, Node(is_switch=True))

        for s in coreSwitches:
            self.add_node(s, Node(is_switch=True))

        # Add hosts
        for h in hosts:
            self.add_node(h, Node(is_switch=False))

        # Add links
        for h in hosts:
            if h <= 4:
                self.add_edge(h, firstSwitch)
            elif h <= 8:
                self.add_edge(h, firstSwitch + 1)
            elif h <= 12:
                self.add_edge(h, firstSwitch + 2)
            else:
                self.add_edge(h, firstSwitch + 3)

        # Add monitoring host
        # self.add_node(99, Node(is_switch=False))

        for s1 in edgeSwitches:
            if (s1 - firstSwitch) < numEdgeSwitches / 2:
                self.add_edge(s1, coreSwitches[0])
            else:
                self.add_edge(s1, coreSwitches[1])
            # connect monitor to every edge switch
            # self.add_edge(99, s1)

        self.add_edge(coreSwitches[0], coreSwitches[1])

        self.enable_all()
Exemple #30
0
    def fixEnvironment(self):

        mylog("*** Fix environment\n")

        for node in self.nodes_in_rn:
            fixIntf(node)
        root = Node('root', inNamespace=False)

        mylog("*** Stop unwanted traffic\n")
        root.cmd('stop avahi-daemon')
        #root.cmd('killall dhclient')

        mylog("*** Kill old processes\n")
        root.cmd('killall -r zebra')
        root.cmd('killall -r ospfd')
        root.cmd('killall sshd')

        cfile = '/etc/environment'
        line1 = 'VTYSH_PAGER=more\n'
        config = open(cfile).read()
        if (line1) not in config:
            mylog('*** Adding %s to %s\n' % (line1.strip(), cfile))
            with open(cfile, 'a') as f:
                f.write(line1)
            f.close()

        if os.path.exists(self.temp_cfg):
            os.remove(self.temp_cfg)
Exemple #31
0
    def __init__(self, verbose=False):

        self.checkPATHs()

        Mininet.__init__(self, build=False)

        self.cr_oshis = []
        self.pe_oshis = []
        self.ce_routers = []
        self.ctrls = []
        self.nodes_in_rn = []
        self.node_to_data = defaultdict(list)
        self.node_to_node = {}
        self.node_to_default_via = {}
        self.coex = {}

        self.verbose = verbose
        lg.setLogLevel('info')

        self.vlls = []

        self.node_to_pw_data = defaultdict(list)
        self.pws = []

        self.cer_to_customer = {}
        self.customer_to_vtepallocator = {}

        self.vsfs = []
        self.pe_cer_to_vsf = {}

        self.is_vs = False
        self.vss = []
        self.vss_data = []
        self.id_peo_to_vs = {}
        self.last_ipnet = IPv4Network(u'0.0.0.0/24')

        self.id_to_node = {}
        self.ip_to_mac = {}

        self.overall_info = {}

        self.mgmt = None

        root = Node('root', inNamespace=False)
        root.cmd('/etc/init.d/network-manager stop')
        mylog("*** Stop Network Manager\n")

        self.cluster_to_ctrl = defaultdict(list)
        self.cluster_to_nodes = defaultdict(list)
        self.nodes_to_cluster = {}
Exemple #32
0
def connectToRootNS(net,
                    ip='10.123.123.1',
                    mac='00123456789A',
                    prefixLen=8,
                    routes=['10.0.0.0/8']):
    print "*** Creating controller"
    c0 = net.addController('c0', ip='127.0.0.1', port=6633)
    rootswitch = net.addSwitch('roots1', )
    rootswitch.dpid = 'FFFFFFFFFFFFFFFF'
    # Connect hosts to root namespace via switch. Starts network.
    # network: Mininet() network object
    # ip: IP address for root namespace node
    # prefixLen: IP address prefix length (e.g. 8, 16, 24)
    # routes: host networks to route to"
    # Create a node in root namespace and link to switch 0
    root = Node('root', inNamespace=False)
    intf = Link(root, rootswitch).intf1
    intf.setMAC(mac)
    root.setIP(ip, prefixLen, intf)
    print "*** Added Interface", str(intf), "Connected To Root-NameSpace"
    fixNetworkManager(str(intf))
    for host in net.hosts:
        net.addLink(host, rootswitch)
    # Add routes from root ns to hosts
    for route in routes:
        root.cmd('route add -net ' + route + ' dev ' + str(intf))
    root.cmd('service network-manager restart')
    return rootswitch
def connectToRootNS( network, switch, ip, routes ):
    """Connect hosts to root namespace via switch. Starts network.
      network: Mininet() network object
      switch: switch to connect to root namespace
      ip: IP address for root namespace node
      routes: host networks to route to"""
    # Create a node in root namespace and link to switch 0
    root = Node( 'root', inNamespace=False )
    intf = network.addLink( root, switch ).intf1
    root.setIP( ip, intf=intf )
    # Start network that now includes link to root namespace
    network.start()
    # Add routes from root ns to hosts
    for route in routes:
        root.cmd( 'route add -net ' + route + ' dev ' + str( intf ) )
Exemple #34
0
    def __init__( self, name, sw_path = "dc_full",
		  dpid=None,
		  opts='',
                  thrift_port = None,
                  pcap_dump = False,
                  verbose = False, **kwargs ):
        Node.__init__( self, name, **kwargs )
        self.dpid = self.defaultDpid(dpid)
	self.opts = opts
	self.sw_path = sw_path
        self.verbose = verbose
        logfile = '/tmp/p4ns.%s.log' % self.name
        self.output = open(logfile, 'w')
        self.thrift_port = thrift_port
        self.pcap_dump = pcap_dump
Exemple #35
0
    def config(self, privateLogDir=None, privateRunDir=None,
               privateMounts=None, services=None, hostname=None,
               loIntfs=None, **_params):
        """Configure Node according to (optional) parameters:
           mac: MAC address for default interface
           ip: IP address for default interface
           defaultRoute: default route for all traffic
           privateLogDir = boolean or path to dir to bind over /var/log
           privateRunDir = boolean or path to dir to bind over /run
           privateMounts = mount / path properties objects
           loopbackIntfs = list of loopback interfaces and parameters
           services = service objects for service manager"""

        r = BaseNode.config(self, **_params)
        # Process private mounts and services in this order:
        # (1) - privateLogDir (/var/log), privateRunDir (/run) if requested
        # (2) - user private mounts
        # (3) - services and service mounts
        # (4) - setup hostname, loopback adapters, and other network components
        self.setParam(r, 'setupPrivateLogs', privateLogDir=privateLogDir)
        self.setParam(r, 'setupPrivateRun', privateRunDir=privateRunDir)
        self.setParam(r, 'setupPrivateMounts', privateMounts=privateMounts)
        self.setParam(r, 'setupServices', services=services)
        self.setParam(r, 'setupHostname', hostname=hostname)
        self.setParam(r, 'setupLoopbacks', loIntfs=loIntfs)
        return r
Exemple #36
0
def find_node(start: Node, node_name: str) -> Optional[Intf]:
    """
    :param start: The starting node of the search
    :param node_name: The name of the node to find
    :return: The interface of the node connected to start with node_name as name
    """

    if start.name == node_name:
        return start.intf()

    visited = set()  # type: Set[IPIntf]
    to_visit = realIntfList(start)
    # Explore all interfaces recursively, until we find one
    # connected to the node
    while to_visit:
        i = to_visit.pop()
        if i in visited:
            continue
        visited.add(i)
        for n in i.broadcast_domain.interfaces:
            if n.node.name == node_name:
                return n
            if L3Router.is_l3router_intf(n):
                to_visit.extend(realIntfList(n.node))
    return None
Exemple #37
0
def address_pair(n: Node, use_v4=True, use_v6=True) \
        -> Tuple[Optional[str], Optional[str]]:
    """Returns a tuple (ip, ip6) with ip/ip6 being one of the IPv4/IPv6
       addresses of the node n"""
    from .link import IPIntf  # Prevent circular imports
    v4_str = v6_str = None
    for itf in n.intfList():
        # Mininet switches have a loopback interface
        # declared as an Intf.
        # This object does not have ips() or ip6s() methods.
        if not isinstance(itf, IPIntf):
            continue

        if use_v4 and v4_str is None:
            itf.updateIP()
            v4 = next(itf.ips(), None)
            v4_str = v4.ip.compressed if v4 is not None else v4
        if use_v6 and v6_str is None:
            itf.updateIP6()
            v6 = next(itf.ip6s(exclude_lls=True), None)
            v6_str = v6.ip.compressed if v6 is not None else v6
        if (not use_v4 or v4_str is not None) \
                and (not use_v6 or v6_str is not None):
            break
    return v4_str, v6_str
Exemple #38
0
    def config(self,
               privateLogDir=None,
               privateRunDir=None,
               privateMounts=None,
               services=None,
               hostname=None,
               loIntfs=None,
               **_params):
        """Configure Node according to (optional) parameters:
           mac: MAC address for default interface
           ip: IP address for default interface
           defaultRoute: default route for all traffic
           privateLogDir = boolean or path to dir to bind over /var/log
           privateRunDir = boolean or path to dir to bind over /run
           privateMounts = mount / path properties objects
           loopbackIntfs = list of loopback interfaces and parameters
           services = service objects for service manager"""

        r = BaseNode.config(self, **_params)
        # Process private mounts and services in this order:
        # (1) - privateLogDir (/var/log), privateRunDir (/run) if requested
        # (2) - user private mounts
        # (3) - services and service mounts
        # (4) - setup hostname, loopback adapters, and other network components
        self.setParam(r, 'setupPrivateLogs', privateLogDir=privateLogDir)
        self.setParam(r, 'setupPrivateRun', privateRunDir=privateRunDir)
        self.setParam(r, 'setupPrivateMounts', privateMounts=privateMounts)
        self.setParam(r, 'setupServices', services=services)
        self.setParam(r, 'setupHostname', hostname=hostname)
        self.setParam(r, 'setupLoopbacks', loIntfs=loIntfs)
        return r
def connectToRootNS( network, switch, ip, prefixLen, routes ):
    "Connect hosts to root namespace via switch. Starts network."
    "network: Mininet() network object"
    "switch: switch to connect to root namespace"
    "ip: IP address for root namespace node"
    "prefixLen: IP address prefix length (e.g. 8, 16, 24)"
    "routes: host networks to route to"
    # Create a node in root namespace and link to switch 0
    root = Node( 'root', inNamespace=False )
    intf = TCLink( root, switch ).intf1
    root.setIP( ip, prefixLen, intf )
    # Start network that now includes link to root namespace
    network.start()
    # Add routes from root ns to hosts
    for route in routes:
        root.cmd( 'route add -net ' + route + ' dev ' + str( intf ) )
Exemple #40
0
def connectToInternet(network, switch='s2', rootip='10.254', subnet='10.0/8'):
    """Connect the network to the internet
switch: switch to connect to root namespace
rootip: address for interface in root namespace
subnet: Mininet subnet"""
    switch = network.get(switch)
    prefixLen = subnet.split('/')[1]

    # Create a node in root namespace
    root = Node('root', inNamespace=False)

    # Prevent network-manager from interfering with our interface
    fixNetworkManager(root, 'root-eth0')

    # Create link between root NS and switch
    link = network.addLink(root, switch)
    #,bw=100,max_queue_size=500,use_htb=True)
    link.intf1.setIP(rootip, prefixLen)
    # Start network that now includes link to root namespace
    network.start()

    # Start NAT and establish forwarding
    startNAT(root)

    # Setting up DHCP
    print "IF 0 ROOT ->" + str(os.getuid())
    out = network.hosts[0].cmd('sudo dhcpd')
    print "DHCPD = " + out

    # Establish routes from end hosts
    for host in network.hosts:
        host.cmd('ip route flush root 0/0')
        host.cmd('route add -net', subnet, 'dev', host.defaultIntf())
        host.cmd('route add default gw', rootip)
    return root
Exemple #41
0
    def _ping_set(self, src: Node,
                  dst_dict: Mapping[Node, Union[IPv4Address, IPv6Address, str]],
                  timeout: Optional[str], v4=True) -> Tuple[int, int]:
        """Do the actual ping to the dict of {dst: dst_ip} from src

           :param src: origin of the ping
           :param dst_dict: destinations {dst: dst_ip} of the ping
           :param timeout: the time to wait for a response, as string
           :param v4: whether IPv4 or IPv6 is used
           :param return: a tuple (lost packets, sent packets)"""
        if len(dst_dict) == 0:
            return 0, 0
        lost = 0
        packets = 0
        opts = ''
        if timeout:
            opts = '-W %s' % timeout

        log.output("%s --%s--> " % (src.name, "IPv4" if v4 else "IPv6"))
        for dst, dst_ip in dst_dict.items():
            result = src.cmd('%s -c1 %s %s' % ("ping" if v4 else PING6_CMD,
                                               opts, dst_ip))
            sent, received = self._parsePing(result)
            lost += sent - received
            packets += sent
            log.output("%s " % dst.name if received else "X ")
        log.output('\n')

        return lost, packets
Exemple #42
0
def connectToGateway(network,
                     switch='s1',
                     rootip='10.128.0.254',
                     subnet='10.128.0.0/9'):
    """Connect the network to the internet
       switch: switch to connect to root namespace
       rootip: address for interface in root namespace
       subnet: Mininet subnet"""
    switch = network.get(switch)
    prefixLen = subnet.split('/')[1]

    # Create a node in root namespace
    root = Node('root', inNamespace=False)

    # Prevent network-manager from interfering with our interface
    fixNetworkManager(root, 'root-eth0')

    # Create link between root NS and switch
    link = network.addLink(root, switch)
    link.intf1.setIP(rootip, prefixLen)

    # Start network that now includes link to root namespace
    #    network.start()

    return root
Exemple #43
0
def connectToRootNS( network, switch, routes ):
    """Connect hosts to root namespace via switch. Starts network.
      network: Mininet() network object
      switch: switch to connect to root namespace
      ip: IP address for root namespace node
      prefixLen: IP address prefix length (e.g. 8, 16, 24)
      routes: host networks to route to"""
    # Create a node in root namespace and link to switch 0
    root = Node( 'root', inNamespace=False )
    intf = Link( root, switch ).intf1
    # root.setIP( ip, prefixLen, intf )
    # Start network that now includes link to root namespace
    network.start()
    # Add routes from root ns to hosts
    for route in routes:
        root.cmd( 'route add -net ' + route + ' dev ' + str( intf ) )
Exemple #44
0
    def init_floating_network(self):
        """
        Initialize the floating network component for the emulator.
        Will not do anything if already initialized.
        """
        if self.net is not None and self.floating_switch is None:
            # create a floating network
            fn = self.floating_network = Net("default")
            fn.id = str(uuid.uuid4())
            fn.set_cidr(self.floating_netmask)

            # create a subnet
            fn.subnet_id = str(uuid.uuid4())
            fn.subnet_name = fn.name + "-sub"

            # create a port for the host
            port = Port("root-port")
            #port.id = str(uuid.uuid4())
            port.net_name = fn.name

            # get next free ip
            root_ip = fn.get_new_ip_address(port.name)
            port.ip_address = root_ip
            # floating ip network setup
            # wierd way of getting a datacenter object
            first_dc = self.net.dcs.values()[0]
            # set a dpid for the switch. for this we have to get the id of the next possible dc
            self.floating_switch = self.net.addSwitch("fs1", dpid=hex(first_dc._get_next_dc_dpid())[2:])
            # this is the interface appearing on the physical host
            self.floating_root = Node('root', inNamespace=False)
            self.net.hosts.append(self.floating_root)
            self.net.nameToNode['root'] = self.floating_root
            self.floating_intf = self.net.addLink(self.floating_root, self.floating_switch).intf1
            self.floating_root.setIP(root_ip, intf=self.floating_intf)
            self.floating_nodes[(self.floating_root.name, root_ip)] = self.floating_root
Exemple #45
0
def connectToInternet(network, switch='s1', rootip='10.254', subnet='10.0/8'):
    """Connect the network to the internet
       switch: switch to connect to root namespace
       rootip: address for interface in root namespace
       subnet: Mininet subnet"""
    switch = network.get(switch)
    prefixLen = subnet.split('/')[1]

    # Criando node no namespace raiz
    root = Node('root', inNamespace=False)

    # Interface gerenciador prevencao
    fixNetworkManager(root, 'root-eth0')

    # Criando link
    link = network.addLink(root, switch)
    link.intf1.setIP(rootip, prefixLen)

    # Start network
    network.start()

    # Start NAT
    startNAT(root)

    # Estabelecendo rotas entre hosts
    for host in network.hosts:
        host.cmd('ip route flush root 0/0')
        host.cmd('route add -net', subnet, 'dev', host.defaultIntf())
        host.cmd('route add default gw', rootip)

    return root
Exemple #46
0
    def connectTo(self, Node):
        "Fetch next available port number on destination node and generate a remote interface name"
        remoteCandidIntfName = Node.name + "-eth" + str(Node.newPort())
        "Pass the remote intf name to generate a link"
        self.createLink(remoteCandidIntfName)
        "Connect the other end of the created link to the passed mininet node"
        """
		if type(Node) is (Node or Host or OVSSwitch):
	             _intf = Intf( remoteCandidIntfName, node=Node )
		     return 	          
                #Node.incrIfIndex()
		"""
        if isinstance(Node, NFVMiddlebox):
            Node.incrIfIndex()
        else:
            _intf = Intf(remoteCandidIntfName, node=Node)
        return
Exemple #47
0
    def config(self, app=None, cache=None, **params):

        r = Node.config(self, **params)

        self.setParam(r, 'app', app=app)
        self.setParam(r, 'cache', cache=cache)

        return r
Exemple #48
0
    def config(self, app=None, cache=None, **params):

        r = Node.config(self, **params)

        self.setParam(r, 'app', app=app)
        self.setParam(r, 'cache', cache=cache)

        return r
Exemple #49
0
	def connectTo(self,Node):
		"Fetch next available port number on destination node and generate a remote interface name"
		remoteCandidIntfName = Node.name +"-eth" + str(Node.newPort())
		"Pass the remote intf name to generate a link"
		self.createLink(remoteCandidIntfName)
		"Connect the other end of the created link to the passed mininet node"
		"""
		if type(Node) is (Node or Host or OVSSwitch):
	             _intf = Intf( remoteCandidIntfName, node=Node )
		     return 	          
                #Node.incrIfIndex()
		"""
		if isinstance(Node, NFVMiddlebox):
	             Node.incrIfIndex()
		else:
                     _intf = Intf( remoteCandidIntfName, node=Node )
		return
Exemple #50
0
def scratchNet(cname='controller', cargs='-v ptcp:'):
    #create network from scratch using Open vswitch
    info("***Creating nodes\n")
    controller = Node('c0', inNamespace=False)
    switch0 = Node('s0', inNamespace=False)
    h0 = Node('h0')
    h1 = Node('h1')

    info("***Creating links\n")
    Link(h0, switch0)
    Link(h1, switch0)

    info(" ***Configuring hosts\n")
    h0.setIP('192.168.123.1/24')
    h1.setIP('192.168.123.2/24')
    info(str(h0) + '\n')
    info(str(h1) + '\n')
Exemple #51
0
 def __init__(self,
              name,
              inNamespace=False,
              command='controller',
              cargs='-v ptcp:%d',
              cdir=None,
              ip="127.0.0.1",
              port=6653,
              protocol='tcp',
              **params):
     self.command = command
     self.cargs = cargs
     self.cdir = cdir
     self.ip = ip
     self.port = port
     self.protocol = protocol
     Node.__init__(self, name, inNamespace=inNamespace, ip=ip, **params)
Exemple #52
0
    def config(self, app=None, cache=None, **params):

        r = Node.config(self, **params)

        self.setParam(r, 'app', app=app)
        self.setParam(r, 'cache', cache=cache)
        print "ndn_host.py------------NdnHost cla-----config() method-----------"
        return r
    def fixEnvironment(self):
        
        mylog("*** Fix environment\n")

        for node in self.nodes_in_rn:
            fixIntf(node)
        root = Node( 'root', inNamespace=False )
        
        mylog("*** Stop unwanted traffic\n")
        root.cmd('stop avahi-daemon')
        #root.cmd('killall dhclient')

        mylog("*** Kill old processes\n")
        root.cmd('killall -r zebra')
        root.cmd('killall -r ospfd')
        root.cmd('killall sshd')
    
        cfile = '/etc/environment'
        line1 = 'VTYSH_PAGER=more\n'
        config = open( cfile ).read()
        if ( line1 ) not in config:
            mylog( '*** Adding %s to %s\n' %(line1.strip(), cfile))
            with open( cfile, 'a' ) as f:
                f.write( line1 )
            f.close();

        if os.path.exists(self.temp_cfg):
            os.remove(self.temp_cfg)
Exemple #54
0
    def config(self, fib=None, app=None, cache=None, **params):

        r = Node.config(self, **params)

        self.setParam(r, 'app', fib=fib)   # why is this not app=app, to be investigated
        self.setParam(r, 'fib', app=app)   # and this fib=fib
        self.setParam(r, 'cache', cache=cache)

        return r
	def checkQuagga(self):
		root = Node( 'root', inNamespace=False )
		zebra = root.cmd('ls %s 2> /dev/null | wc -l' % OSHI.zebra_exec)
		if '1' not in zebra:
			OSHI.zebra_exec = OSHI.zebra_exec_2
			zebra = root.cmd('ls %s 2> /dev/null | wc -l' % OSHI.zebra_exec)
			if '1' not in zebra:
				error( 'Cannot find required executable zebra\nPlease make sure that Zebra is properly installed in ' + OSHI.quaggaPath_msg + '\n'
				   		'Otherwise change configuration in Dreamer-Mininet-Extensions/nodes.py \n' )
				exit( 1 )
		ospfd = root.cmd('ls %s 2> /dev/null | wc -l' % OSHI.ospfd_exec)
		if '1' not in ospfd:
			OSHI.ospfd_exec = OSHI.ospfd_exec_2
			ospfd = root.cmd('ls %s 2> /dev/null | wc -l' % OSHI.ospfd_exec)
			if '1' not in ospfd:
				error( 'Cannot find required executable ospfd\nPlease make sure that OSPFD is properly installed in ' + OSHI.quaggaPath_msg + '\n'
					   'Otherwise change configuration in Dreamer-Mininet-Extensions/nodes.py \n' )
				exit( 1 )
def configure_vll_pusher(net):
	print "*** Create Configuration File For Vll Pusher"
	path = vll_path + "vll_pusher.cfg"
	vll_pusher_cfg = open(path,"w")
	for i in range(0, len(LHS_tunnel_aoshi)):
		aoshi = LHS_tunnel_aoshi[i]		
		lhs_dpid = net.getNodeByName(aoshi).dpid
		lhs_dpid = ':'.join(s.encode('hex') for s in lhs_dpid.decode('hex'))
		port = LHS_tunnel_port[i]
		lhs_port = port
		aoshi = RHS_tunnel_aoshi[i]		
		rhs_dpid = net.getNodeByName(aoshi).dpid
		rhs_dpid = ':'.join(s.encode('hex') for s in rhs_dpid.decode('hex'))
		port = RHS_tunnel_port[i]
		rhs_port = port
		vll_pusher_cfg.write("%s|%s|%s|%s|%d|%d|\n" % (lhs_dpid, rhs_dpid, lhs_port, rhs_port, LHS_tunnel_vlan[i], RHS_tunnel_vlan[i]))
	vll_pusher_cfg.close()
	root = Node( 'root', inNamespace=False )
	root.cmd("chmod 777 %s" %(path))
Exemple #57
0
class testHwintf( unittest.TestCase ):

    prompt = 'mininet>'

    def setUp( self ):
        self.h3 = Node( 't0', ip='10.0.0.3/8' )
        self.n0 = Node( 't1', inNamespace=False )
        Link( self.h3, self.n0 )
        self.h3.configDefault()

    def testLocalPing( self ):
        "Verify connectivity between virtual hosts using pingall"
        p = pexpect.spawn( 'python -m mininet.examples.hwintf %s' % self.n0.intf() )
        p.expect( self.prompt )
        p.sendline( 'pingall' )
        p.expect ( '(\d+)% dropped' )
        percent = int( p.match.group( 1 ) ) if p.match else -1
        self.assertEqual( percent, 0 )
        p.expect( self.prompt )
        p.sendline( 'exit' )
        p.wait()

    def testExternalPing( self ):
        "Verify connnectivity between virtual host and virtual-physical 'external' host "
        p = pexpect.spawn( 'python -m mininet.examples.hwintf %s' % self.n0.intf() )
        p.expect( self.prompt )
        # test ping external to internal
        expectStr = '(\d+) packets transmitted, (\d+) received'
        m = re.search( expectStr, self.h3.cmd( 'ping -v -c 1 10.0.0.1' ) )
        tx = m.group( 1 )
        rx = m.group( 2 )
        self.assertEqual( tx, rx )
        # test ping internal to external
        p.sendline( 'h1 ping -c 1 10.0.0.3')
        p.expect( expectStr )
        tx = p.match.group( 1 )
        rx = p.match.group( 2 )
        self.assertEqual( tx, rx )
        p.expect( self.prompt )
        p.sendline( 'exit' )
        p.wait()

    def tearDown( self ):
        self.h3.stop( deleteIntfs=True )
        self.n0.stop( deleteIntfs=True )
Exemple #58
0
def createAgentNet( k, routeIP ):
    net = Mininet( controller=Controller, switch=OVSBridge )

    print "*** Creating agent network"
    sw = net.addSwitch( 's%s' % (k+1) )
    for i in range( 1, k+1 ):
        host = net.addHost( 'agent%s' % i, ip='171.0.0.%s/16' % i )
        intf = net.addLink( sw, host ).intf2
        if routeIP != '127.0.0.1':
            # host.setHostRoute( routeIP, intf ) # this api does not work!!!
            host.cmd( 'ip route add %s dev %s' % ( routeIP, str( intf ) ) )

    # c = net.addController('c1', controller=Controller, ip='127.0.0.1', port=6699)

    root = Node( 'root', inNamespace=False )
    intf = net.addLink( root, sw ).intf1
    root.setIP( '171.0.123.1/16', intf=intf )
    # root.cmd( 'route add -net 171.0.0.0/16 dev ' + str( intf ) )

    net.build()
    # c.start()
    sw.start( [] )
    return net