def simpleTest(): info('*** Starting network\n') topo = TestingTopo() c1 = RemoteController('c1', ip='127.0.0.1') net = Containernet(topo=topo, link=link, controller=c1) # d1 = net.addDocker('d1', dimage="tests", volumes=["/home/osboxes/Documents/tests/:/mnt/vol1:rw"]) net.addLink(d1, net.get('s1')) s1 = net.get('s1') net.start() # Connect switch to Internet NAT s1.cmdPrint('ovs-vsctl add-port s1 enp0s3') # Setup mirrored port interface s1.cmdPrint('ovs-vsctl add-port s1 snort0') s1.cmdPrint('ovs-vsctl set interface snort0 type=internal') s1.cmdPrint('sudo ip link set snort0 up') s1.cmdPrint('ovs-vsctl show') # Disable docker NAT connection d1.cmdPrint('ifconfig eth0 down') # Reset and connect d1 to internet through s1 d1.cmdPrint('ifconfig d1-eth0 0') d1.cmdPrint('dhclient d1-eth0') # Confirm d1 is connected to internet d1.cmdPrint('ping -c 2 google.com') info('*** Running CLI\n') CLI(net) # Quit CLI to start packet capture tcpdump = 'sudo timeout 930 tcpdump -i snort0 -w /home/osboxes/Documents/tests/pcaps/vulahometrain1.pcap' process = subprocess.Popen(tcpdump.split()) # Start selenium powered application test (simulate website interaction) d1.cmdPrint('python /mnt/vol1/WebTrafficSDN/vulatest.py') #CLI(net) tcpdump = 'sudo timeout 930 tcpdump -i snort0 -w /home/osboxes/Documents/tests/pcaps/youtubehometrain1.pcap' process = subprocess.Popen(tcpdump.split()) d1.cmdPrint('python /mnt/vol1/WebTrafficSDN/youtubetest.py') #CLI(net) tcpdump = 'sudo timeout 930 tcpdump -i snort0 -w /home/osboxes/Documents/tests/pcaps/outlookhometrain1.pcap' process = subprocess.Popen(tcpdump.split()) d1.cmdPrint('python /mnt/vol1/WebTrafficSDN/outlooktest.py') info('*** Stopping network') net.stop()
h52.cmd('brctl addif br0 h52-eth0') h52.cmd('brctl addif br0 h52-eth1') h52.cmd('ifconfig h52-eth0 up') h52.cmd('ifconfig h52-eth1 up') h52.cmd('ifconfig br0 up') net.start() t = Thread(target=CLI, args=(net, )) t.start() agent = Agent() agent.listenFiles("127.0.0.1", "paths", listenPaths_port) agent.listenFiles("127.0.0.1", "link_status", listenLinkStatus_port) ################## Begin test ################## sleep(1) net.get('h1').cmd('cd home/ && python server.py "10.0.1.1" 60001 "50mb.flv" &') net.get('h5').cmd('cd home/ && python server.py "10.0.1.5" 60001 "50mb.flv" &') net.get('h2').cmd('cd ../videos/client2/ && xterm -name "h2" &') net.get('h3').cmd('cd ../videos/client3/ && xterm -name "h3" &') net.get('h4').cmd('cd ../videos/client4/ && xterm -name "h4" &') while timestep < 11: pass h52.cmd('ebtables -A FORWARD -s 00:00:00:00:00:04 -j DROP') h52.cmd('ebtables -A FORWARD -d 00:00:00:00:00:04 -j DROP') h51.cmd('ebtables -A FORWARD -s 00:00:00:00:00:04 -j DROP') h51.cmd('ebtables -A FORWARD -d 00:00:00:00:00:04 -j DROP') t.join() ################## End test ##################
class Scenario(object): """ Base scenario class. Performs the functions to run and document a scenario. Should be extended by any other implemented scenarios, all public methods are extensible. Extension classes should have the class name `Import` as per the `start` file. """ # These attributes allow for the filtering/ordering of scenarios when presenting them to students name = "Base Scenario" """Scenario name. Used in the produced documentation""" enabled = False """If the scenario should be shown to users.""" weight = -1 """Used to order scenarios before presenting them to users, the lower the weight the earlier in the list.""" def __init__(self, teacher=False, developer=False, seed=None): # type: (bool, bool, str) -> None """ :type teacher: bool :param teacher: Is the user a teacher. :type developer: bool :param developer: Is the user a developer. :type seed: str :param seed: str: Random number generator seed, likely student ID. """ self.teacher = teacher self.developer = developer self.net = None # type: Containernet """Containernet: The network of devices.""" self.questions = [] # type: List[Tuple[str, str]] """List[Tuple[str, str]]: List of question & answer combinations used for task & answer documents.""" self.answer_document = Document() """Document: `python-docx` document used to provide the scenario answers to teachers.""" self.task_document = Document() """Document: `python-docx` document used to provide the scenario task to users.""" # Use the inputted seed, if given, to randomise the network self.seed = seed """Seed parameter passed to __init__, used to randomise the network parameters. Added to answer sheets given to teachers so they know the student's ID.""" if self.seed is not None: random.seed(self.name + self.seed) # If no seed, set seed to "random" # to indicate the outputted docuemnts are for a random seed else: self.seed = "random" def run(self): """Main function that executes the rest of the scenario.""" # Default to only error log printing for students setLogLevel('error') if self.teacher: # Allow teaches to see more complete logs setLogLevel('info') if self.developer: # Show debug logs for development setLogLevel('debug') # Create Containernet network self.create_network() # Start Containernet network self.run_network() # Generate task/answer sheets self.generate_task(self.task_document) self.generate_questions() self._add_questions(self.task_document) self._add_answers(self.answer_document) self.save_documents() if self.developer: # If we're a developer, start the CLI # so we can test from the command line CLI(self.net) self.net.stop() return def create_network(self, controller=Controller): """Create Containernet network.""" info('*** Running Cleanup\n') cleanup() self.net = Containernet(controller=controller) if controller is not None: self.add_controller() def add_controller(self): """Adds a controller to the network.""" self.net.addController() def _add_answers(self, doc): doc.add_heading('Answers', level=3) for idx, question in enumerate(self.questions): # If the question has 2 items print it as a question and answer if question[1] != "": doc.add_paragraph(str(idx + 1) + '. ' + question[0] + ': ').add_run(question[1]).bold = True # Else don't print it def generate_task(self, doc): """Adds a header and information on how to connect to the network (if applicable). Scenarios should extend this to provide users with details on the task.""" doc.add_heading('%s' % self.name, level=2) kali = self.net.get('kali') # type: Kali if kali: kali.add_hint(doc) def generate_questions(self): pass def _add_questions(self, doc): doc.add_heading('Questions', level=3) for idx, question in enumerate(self.questions): # If the question has 2 items print it as a question if question[1] != "": doc.add_paragraph(str(idx + 1) + '. ' + question[0] + '? ') # Else print it as a statement else: doc.add_paragraph(question[0]) def save_documents(self, studentDirectory='./student/', teacherDirectory='./teacher/', studentAllowedAnswers=False, staticTaskDocument=True): """ Saves the task and answer documents locally so they can be provided to users. :param studentDirectory: Location of the student-accessible folder on the VM :type studentDirectory: string :param teacherDirectory: Location of the teacher-accessible folder on the VM :type teacherDirectory: string :param studentAllowedAnswers: Is the student provided the answer document for the task. :type studentAllowedAnswers: bool :param staticTaskDocument: Is the task document the same for every student. :type staticTaskDocument: bool """ # Create neccisary directories if they do not exist for directory in [studentDirectory, teacherDirectory]: if not os.path.exists(directory): os.makedirs(directory) # -- Answer sheet -- # For teachers, generate a document named "[Scenario name]-[Stduent ID].docx" self.answer_document.save(teacherDirectory + self.name + '-' + self.seed + '.docx') # If we're a student, generate a document named "[Scenario name]-answers.docx" if studentAllowedAnswers: self.answer_document.save(studentDirectory + self.name + '-answers.docx') # -- Task sheet -- # If the task sheet is the same for all students if staticTaskDocument: taskLocation = teacherDirectory + self.name + '.docx' # Create the task sheet self.task_document.save(taskLocation) # If we're a student # if not self.teacher: self.task_document.save(studentDirectory + self.name + '.docx') def run_ftp(self, studentDirectory='./student/', teacherDirectory='./teacher'): """ Runs a PyFTPlib FTP server to provide users with access to their task/answer documents. :param studentDirectory: Location of the student-accessible folder on the VM :type studentDirectory: string :param teacherDirectory: Location of the teacher-accessible folder on the VM :type teacherDirectory: string """ authorizer = DummyAuthorizer() pw = '%05x' % random.randrange(16**5) if self.teacher: authorizer.add_user(username="******", password=pw, homedir=teacherDirectory) else: authorizer.add_user(username="******", password=pw, homedir=studentDirectory) handler = FTPHandler handler.authorizer = authorizer handler.banner = "DVNG tasks ftp server" # Instantiate FTP server class and listen on 0.0.0.0:2121 address = ('', 21) server = MultiprocessFTPServer(address, handler) # set a limit for connections server.max_cons = 256 server.max_cons_per_ip = 5 # start ftp server print("Task sheets are available over ftp on port 21\n" + "\tUsername: %s\n" % ("teacher" if self.teacher else "student") + "\tPassword: %s\n" % pw + "Keep this terminal open until you've retreived your files.") logging.basicConfig(level=logging.CRITICAL) server.serve_forever() def run_network(self): """Starts the Containernet network.""" self.net.start()
graph2Network(G, net) net.start() currentInstance = datetime.strftime(datetime.now(), '%Y%m%d%H%M') subprocess.call(['mkdir measurements/%s/' % currentInstance], shell=True) #print currentInstance doc = open('measurements/currentInstance.txt', 'w+') doc.write(currentInstance) doc.close() config = open('dfget.yml', 'w+') #config.write('minRate: 327680\n') #Verlaengern der Timeout Zeit def 20480 #config.write('minRate: 512\n') #Verlaengern der Timeout Zeit def 20480 config.write('nodes:\n') #Liste mit Supernodes fuer dfget for node in G.nodes(): if net.get(node).name in set.servers: config.write('- ' + net.get(node).IP() + ':8002\n') config.close() containerInfo() set.readNodes() set.serverList() print("Restarting links for ipv6") restartLinks(G, net) print("Start Container") startDocker(G, net) print("Limit links") limitLinks(G, net, 'hallo') time.sleep(5) print("Check for faulty containers")
def run(self, sim_args, curtime, entrypoint): if any(v not in environ for v in ['CLIENT', 'CLIENT_PARAMS', 'SERVER', 'SERVER', 'CLIENT_LOGS', 'SERVER_LOGS', 'CL_COMMIT', 'SV_COMMIT']): # TODO show help exit(1) client_image = environ['CLIENT'] client_params = environ['CLIENT_PARAMS'] server_image = environ['SERVER'] server_params = environ['SERVER_PARAMS'] cl_logdir = environ['CLIENT_LOGS'] sv_logdir = environ['SERVER_LOGS'] clcommit = environ['CL_COMMIT'] svcommit = environ['SV_COMMIT'] setLogLevel('info') net = Containernet(controller=Controller) info('*** Adding controller\n') net.addController('c0') info('*** Adding docker containers\n') server_vs = [sv_logdir + ':/logs'] # add kernel debug volume to allow eBPF code to run if sim_args.k: server_vs.append( '/sys/kernel/debug:/sys/kernel/debug:ro') server = net.addDocker('server', ip='10.0.0.251', environment={"ROLE": "server", "SERVER_PARAMS": server_params, "COMMIT": svcommit}, dimage=server_image + ":latest", volumes=server_vs) client = net.addDocker('client', ip='10.0.0.252', environment={"ROLE": "client", "CLIENT_PARAMS": client_params, "COMMIT": clcommit}, dimage=client_image + ":latest", volumes=[cl_logdir + ':/logs']) info('*** Adding switches\n') s1 = net.addSwitch('s1') s2 = net.addSwitch('s2') info('*** Creating links\n') net.addLink(s1, s2, cls=TCLink, delay=sim_args.delay, bw=sim_args.bandwidth, max_queue_size=sim_args.queue) net.addLink(s1, client) net.addLink(s2, server) info('\n*** Updating and building client/server\n') server.cmd('./updateAndBuild.sh') client.cmd('./updateAndBuild.sh') info('*** Starting network\n') net.start() info('***Add reordering to server intf\n') net.get('s2').cmd('tc qdisc change dev s2-eth1 parent 5:1 netem delay ' + sim_args.delay + ' reorder 100% gap ' + str(sim_args.reordergap) + ' limit ' + str(sim_args.queue)) capture = PacketCapture() if sim_args.k: client.cmd(entrypoint + " &") else: server.cmd(entrypoint + " &" ) capture.startCapture() info('\n' + entrypoint + '\n') if sim_args.k: info(server.cmd(entrypoint) + "\n") else: info(client.cmd(entrypoint) + "\n") # Wait some time to allow server finish writing to log file sleep(3) capture.stopCapture() info('*** Stopping network') net.stop()