def final_update(self, attackDetails, responseTechniques): bestResponseTechnique = '' #Loop through the techniques for technique in responseTechniques: #Find the best response technique for the metric requested if responseTechniques[technique]['is_most_efficient']: bestResponseTechnique = technique break #Print out the data for response techniques print(tabulate_data(responseTechniques)) #Check if the onRoadCar is using the best response technique if self.responseTechniqueApplied == bestResponseTechnique: self.socket.send(serialize('ack', "best response technique is applied")) print("{} is already using the most efficient response technique. ACK sent!".format(self.vin)) else: #Send the final update print("Sending final update!") print("-------------------------") self.UPDATE_ACK = threading.Event() self.socket.send(serialize('update', attackDetails + " " + bestResponseTechnique)) #Wait for the car to ACK self.UPDATE_ACK.wait() #Clear the flag self.UPDATE_ACK.clear() print("Update applied successfully!") print("-------------------------")
def show(request): """ show user infomation """ access_token_input = input_for_show_func(request) kan_user = KanUser('', access_token_input) kan_user.verify_and_login() if kan_user.is_logged_in(): response_dict = extract_class_instance_to_dict(kan_user.get_user()) response = HttpResponse(serialize(response_dict)) else: response = HttpResponse(serialize(None)) return response
def response_performed(attackDetails, responseTechnique, techniquePath): #Send a message to server letting it know that the response technique is performed client.sock.send( serialize('ack', '{}!.!{}'.format('response performed', responseTechnique))) #The client waits for the server to finish the effectiveness test attack print('Waiting for the server to perform the effectiveness attack') client.FINISH_TESTING_EFFECTIVENESS.wait() #If both are true, that means the response technique failed to stop the attack print('Server done with effectiveness attack') if UNDER_ATTACK.is_set(): isEffective = False elif not UNDER_ATTACK.is_set(): isEffective = True #Clear flags UNDER_ATTACK.clear() client.FINISH_TESTING_EFFECTIVENESS.clear() #Load the saved file print('Loading the log file') logFile = read_data('data/logs/{}/{}.json'.format(attackDetails, responseTechnique)) #Add effective status to the json file logFile['is_effective'] = isEffective #Send the log so we don't keep the server waiting for log file, in case this was the last technique to be assessed print('Sending the log file') client.sock.send( send_log( 'log', "{}!.!{}!.!{}!.!{}".format( specifications['software_version'], specifications['hardware_specifications'], attackDetails, responseTechnique), logFile)) #After sending the log, delete the log file try: os.remove('data/logs/{}/{}.json'.format(attackDetails, responseTechnique)) except: print("Error while deleting file: ", logFile) #Revert changes done when the response technique applied print('Running revert operation') subprocess.run(shlex.split("{} {}".format(techniquePath, "revert"))) print('Revert operation successful') #After getting back to the original state, change busy status to false specifications['is_busy'] = False #Save changes save_data('data/specifications.json', specifications) #Inform the server that the car is no longer busy print( 'Sending busy status to server. Setting it to false (the car is ready for more work)' ) client.sock.send( serialize('ack', '{}!.!{}'.format('client busy status', 'false')))
def verify(request): """ verify user infomation, return access_token """ sohupassport_uuid, access_token_input = input_for_verify_func(request) kan_user = KanUser(sohupassport_uuid, access_token_input) kan_user.verify_and_login() if kan_user.is_logged_in(): response_dict = dict() response_dict['access_token'] = kan_user.get_access_token() response = HttpResponse(serialize(response_dict)) else: response = HttpResponse(serialize(None)) return response
def filter_data(data): #Analyze the data, it might have multiple messages stacked together data = data.split(b'!:END:!') #Loop through the messages, skipping last element that returns an empty byte string for message in data[:-1]: #If a message is received if b'!:message:!' in message: print('string message received!') filteredData = message.replace(b'!:message:!',b'') message = pickle.loads(filteredData) print('From server: ' + message) #If a file is received elif b'!:file:!' in message: filteredData = message.replace(b'!:file:!',b'') print('File received!') #file_received(self, filteredData) elif b'!:update:!' in message: filteredData = message.replace(b'!:update:!',b'') message = pickle.loads(filteredData).split() apply_update(message[0], message[1]) sock.send(serialize('ack', 'update ok')) RESPONSE_ACK.set() elif b'!:ack:!' in message: filteredData = message.replace(b'!:ack:!',b'') message = pickle.loads(filteredData) if message == "best response technique is applied": print('ACK message received from server, running the best response technique.') RESPONSE_ACK.set() elif message == "finish testing effectiveness": FINISH_TESTING_EFFECTIVENESS.set() else: print(data)
def filter_data(self, data): #Analyze the data, it might have multiple messages stacked together data = data.split(b'!:END:!') #Loop through the messages, skipping last element that returns an empty byte string for message in data[:-1]: #If an init message is received if b'!:init:!' in message: filteredData = message.replace(b'!:init:!',b'') init_message_received(self, filteredData) #If an ACK message is received elif b'!:ack:!' in message: filteredData = message.replace(b'!:ack:!',b'') ack_message_received(self, filteredData) #If a message is received elif b'!:message:!' in message: print(message) filteredData = message.replace(b'!:message:!',b'') message_received(self, filteredData) #If a file is received elif b'!:log:!' in message: filteredData = message.replace(b'!:log:!',b'') log_received(filteredData) #If an evaluation request is received elif b'!:request_evaluation:!' in message: if self.specifications['is_collaborative'] == False: filteredData = message.replace(b'!:request_evaluation:!',b'') evaluation_requested(self, filteredData) else: self.socket.send(serialize('message', 'Request Evaluation is only for non-collaborative systems.')) else: print(message)
def update(request): """ update user infomation """ access_token_input, user_info_dict = input_for_update_func(request) kan_user = KanUser('', access_token_input) kan_user.verify_and_login() if kan_user.is_logged_in(): kan_user.set_kan_username(user_info_dict.get('kan_username', '')) kan_user.set_kan_self_description(user_info_dict.get('kan_self_description', '')) response_dict = extract_class_instance_to_dict(kan_user.get_user()) response = HttpResponse(serialize(response_dict)) else: response = HttpResponse(serialize(None)) return response
def __init__(self, socket, address, id, name, signal): threading.Thread.__init__(self) self.socket = socket self.address = address self.id = id self.name = name self.signal = signal self.socket.send(serialize('message', 'Successfully connected.'))
def update(request): """ update user infomation """ access_token_input, user_info_dict = input_for_update_func(request) kan_user = KanUser('', access_token_input) kan_user.verify_and_login() if kan_user.is_logged_in(): kan_user.set_kan_username(user_info_dict.get('kan_username', '')) kan_user.set_kan_self_description( user_info_dict.get('kan_self_description', '')) response_dict = extract_class_instance_to_dict(kan_user.get_user()) response = HttpResponse(serialize(response_dict)) else: response = HttpResponse(serialize(None)) return response
def request_evaluation(attackDetails): #Load the response system responseSystem = read_data('data/response_system.json') #Request for evaluation from the server client.sock.sendall( serialize('request_evaluation', attackDetails + '!.!' + responseSystem[attackDetails])) #Wait for the ACK from server client.RESPONSE_ACK.wait()
def save_search(): """ If user is logged in, save search to user, else save to session and redirect user to login """ if current_user.is_authenticated: s = Search.create(request.json) current_user.searches.append(s) db.session.commit() return 'saved' else: session['search'] = serialize(request.json) return 'login'
def update_and_attack(onRoadCar, attackDetails, responseTechnique): #Check for non busy collaborative cars with the same software version and hardware specs print("Checking for non-busy collaborative cars") car = find_car(onRoadCar) print("Car ID: {} will start assessing: {} now!".format(car.vin, responseTechnique)) #Event to wait for an ACK message regarding the update car.UPDATE_ACK = threading.Event() print("Sending update...") print("-------------------------") #Send update with the response technique to use car.socket.send(serialize('update', attackDetails + " " + responseTechnique)) #Wait for the car to ACK car.UPDATE_ACK.wait() #Clear the ACK flag car.UPDATE_ACK.clear() print("Update applied successfully!") print("-------------------------") #Create and add the task into the work list task = WorkTask(car, attackDetails, responseTechnique) workList.append(task) print("Simulating {} attack on car: {} using technique: {}".format(attackDetails, car.vin, responseTechnique)) print("*************************") #Start the attack simulation process attackData = read_data('data/attack_simulations.json') attackPath = attackData[attackDetails] #Run the attack script print('car address is: {}'.format(car.address[0])) print(type(car.address[0])) print('attack path is: {}'.format(attackPath)) subprocess.run(shlex.split("{} {}".format(attackPath, car.address[0]))) #After initiating the attack, measure the duration task.startTime = time.time() print("start: ", task.startTime) #Wait for effectiveness ACK from client showing that the client has performed the response technique and waiting for the effectiveness test task.EFFECTIVENESS_ACK.wait() #Mark the elapsed time task.elapsedTime = time.time() - task.startTime #Re-initiate the attack simulation again to check for effectiveness #Keep in mind that the car might get disconnected, so rely on the VIN instead #Run the attack script print('Re-initiating the attack to test for effectiveness...') subprocess.run(shlex.split("{} {}".format(attackPath, task.car.address[0]))) #After running the attack script, send a message to let the client know that the server has finished attacking task.car.socket.send(serialize('ack', 'finish testing effectiveness')) #Wait for ACK on receiving the log file print("Waiting for the log file...") task.LOG_ACK.wait() #Update the technique's data responseTechniquesData[task.car.softwareVersion][task.car.hardwareSpecifications][attackDetails][responseTechnique]['is_assessed'] = True responseTechniquesData[task.car.softwareVersion][task.car.hardwareSpecifications][attackDetails][responseTechnique]['duration'] = task.elapsedTime #Remove task from the work list workList.remove(task) #Check if this is the last task if not workList: ASSESSMENT_FLAG.set()
import subprocess import shlex #Connect to the server import client #System under attack flag event UNDER_ATTACK = threading.Event() #Initialization of the system #Initialization by loading the response techniques avaiable responseTechniquesData = read_data('data/response_techniques.json') #Get the specifications of the system specifications = read_data('data/specifications.json') #Send specifications to the server after serializing it client.sock.sendall(serialize('init', specifications)) def check_undergoing_assessment(): #First off, check if the car status is busy to see if there are unsent log files if specifications['is_busy']: print('The car is in busy status! Checking previous logs...') #If still busy, then look for an un-sent log to the server. This happens when the client reboots, for example #Get folder names (attack names, basically) attackList = os.listdir('data/logs/') #Loop through each subdirectory (attack) and send the response log import glob for attackName in attackList: src = "data/logs/{}/*.json".format(attackName) files = glob.glob(src, recursive=False) # Loop through files