Path: blob/master/web-gui/tests/functional/test_server.py
1292 views
import os1import time2import pytest3from multiprocessing import Process4from buildyourownbotnet import c25from buildyourownbotnet.core.dao import session_dao, task_dao6from buildyourownbotnet.server import SessionThread7from buildyourownbotnet.models import Session8from buildyourownbotnet.core import dummy_payload_for_testing9from ..conftest import app_client, new_user1011def test_payload_connection(app_client, new_user):12"""13Given an instance of the C2 socket server and an instance of a dummy payload,14when the payload attempts to connect to the server,15check that a secure connection is established.1617This is a multi-step process which involves the following:181) TCP connection192) Diffie-Hellman IKE to generate a secure 256 bit symmetric key,203) Payload sends server info about the client machine214) Server creates a new session thread to handle the connection with the client,225) Session metadata is stored the database236) Client/server can now send AES-256-CBC encrypted messages over the network24"""25# attempt connection26try:27payload = dummy_payload_for_testing.Payload(host='0.0.0.0', port='1337', gui='1', owner=new_user.username)28payload_process = Process(target=payload.run)29payload_process.start()30except Exception as e:31pytest.fail(f"Connection failed: {e}")3233# check 256 bit key generated by Diffie-Hellman IKE successfully, matches on client and server34assert payload.key is not None35assert len(payload.key) == 323637# check session thread created correctly38time.sleep(2)39session_threads = c2.sessions.get(new_user.username)40assert session_threads is not None41assert isinstance(session_threads, dict)42assert len(session_threads) == 143uid = list(session_threads.keys())[0]44session_thread = session_threads[uid]45assert isinstance(session_thread, SessionThread)4647# check session metadata stored in database48session_metadata = session_dao.get_session(uid)49assert session_metadata is not None50assert isinstance(session_metadata, Session)5152# test send/receive data between client/server53command = 'echo hello world'54try:55# store issued task in database56task = task_dao.handle_task({'task': command, 'session': session_thread.info.get('uid')})5758# send task and get response59session_thread.send_task(task)60response = session_thread.recv_task()6162# update task record with result in database63result_dict = task_dao.handle_task(response)64result = str(result_dict['result']).encode()6566# if end-to-end encryption and remote command execution has worked, response will be 'hello world'67assert result == b'hello world\n'68except Exception as e:69pytest.fail(f"Session command raised exception: {e}")70finally:71# kill payload72session_thread.kill()73payload_process.terminate()74757677