Commit 7fe7da80 by Lei

initial commit

parents
from time import time
import csv
from binascii import hexlify
from datetime import datetime
import numpy
from colorama import Fore
from scapy.utils import raw, wrpcap
from scapy.layers.dot11 import RadioTap
from .fuzzing import field_length
from . import fuzzing
# Saving options
SaveToPCAP = True
SaveCSVStruct = True
GlobalConfig = None
IssuesByState = {} # Countain found vulnerabilities
IssueCounter = 0
IssuesTotalCounter = 0
IssueLastTime = time()
IssuePeriod = float('inf')
TransitionCount = 0
TransitionLastCount = 0
IterationLastTime = time()
IterationTime = float('inf')
STATE = 'STATE'
REASON = 'REASON'
FUZZED_PKT = 'FUZZED_PKT'
RECEIVED_PKT = 'RECEIVED_PKT'
TIME = 'TIME'
FUZZED_FIELDS_NAME = 'FUZZED_FIELDS_NAME'
FUZZED_FIELDS_VALUE = 'FUZZED_FIELDS_VALUE'
DUPLICATED_PACKET = 'DUPLICATED_PKT'
ITERATION_NUMBER = 'ITERATION_NUMBER'
model_name = ''
iterationCount = 0
def ConfigureFitness(config):
global GlobalConfig
GlobalConfig = config
def Iteration():
global IterationLastTime
global IterationTime
global iterationCount
t = time()
ret = t - IterationLastTime
IterationLastTime = t
IterationTime = ret
iterationCount += 1
return ret
def Transition(reset=False):
global TransitionCount
global TransitionLastCount
TransitionCount += 1
if reset:
TransitionLastCount = TransitionCount
TransitionCount = 0
return TransitionLastCount
# Issue rate
def AnomalyDetected(state, pkt, summary_text):
global IssueCounter
global IssueLastTime
global IssuePeriod
global IssuesTotalCounter
global model_name
global iterationCount
issue_time = time()
fuzzed_pkt = None
pkts_to_save = []
IssuesTotalCounter += 1
if fuzzing.last_fuzzed_packet is not None:
fuzzed_pkt = fuzzing.last_fuzzed_packet
print(Fore.YELLOW + "Last fuzzed packet: " + fuzzed_pkt.summary())
# If state of the issue is not found in the issues dictionary
if state not in IssuesByState:
# Initialize the entry by the state name
IssuesByState[state] = {
REASON: [],
FUZZED_PKT: [],
RECEIVED_PKT: [],
TIME: [],
FUZZED_FIELDS_NAME: [],
FUZZED_FIELDS_VALUE: [],
DUPLICATED_PACKET: [],
ITERATION_NUMBER: []
}
# Gets the time between any issue
IssuePeriod = issue_time - IssueLastTime
IssueLastTime = issue_time
issues = IssuesByState[state]
reasons = issues[REASON]
packet_description = issues[RECEIVED_PKT]
# if summary of the invalid packet is not already in the reason array
if summary_text not in reasons or (pkt is not None and pkt.summary() not in packet_description):
IssueCounter = IssueCounter + 1
if pkt is not None:
print(Fore.RED + 'Pkt received: ' + pkt.summary())
# Append it to the array as a unique issue
reasons.append(summary_text)
# Append the last fuzzed packet (None for non fuzzing related)
if fuzzed_pkt is not None:
fuzzing.last_fuzzed_packet = None
issues[FUZZED_PKT].append(fuzzed_pkt.summary())
pkts_to_save.append(fuzzed_pkt.copy())
issues[FUZZED_FIELDS_NAME].append(list(fuzzing.last_fuzzed_packet_fields[fuzzing.NAME]))
issues[FUZZED_FIELDS_VALUE].append(list(fuzzing.last_fuzzed_packet_fields[fuzzing.VALUE]))
else:
issues[FUZZED_PKT].append('None')
issues[FUZZED_FIELDS_NAME].append('None')
issues[FUZZED_FIELDS_VALUE].append('None')
# Append the received packet (None for crash)
if pkt is not None:
pcap_pkt = pkt
issues[RECEIVED_PKT].append(pcap_pkt.summary())
pkts_to_save.append(pkt.copy())
else:
issues[RECEIVED_PKT].append(None)
if fuzzing.last_mirror_packet is not None:
# pkts_to_save.append(fuzzing.last_mirror_packet)
issues[DUPLICATED_PACKET].append(fuzzing.last_mirror_packet)
else:
issues[DUPLICATED_PACKET].append('None')
fuzzing.last_mirror_packet = None
# Timestamp of the issue
issue_time_formatted = str(datetime.fromtimestamp(issue_time)).replace(':', '_')
issues[TIME].append(issue_time_formatted)
issues[ITERATION_NUMBER].append(iterationCount)
if SaveToPCAP:
if len(pkts_to_save) > 0:
# for o in pkts_to_save:
# print(Fore.RED + o.summary())
try:
wrpcap('logs/' + model_name + '/pcap/' + issue_time_formatted + '_' + summary_text + '.pcap',
pkts_to_save)
except:
pass
if SaveCSVStruct:
with open('logs/' + model_name + '/csv/' + issue_time_formatted + '.csv', 'w') as csvfile:
columns = [TIME, STATE, RECEIVED_PKT, REASON, FUZZED_PKT, FUZZED_FIELDS_NAME, FUZZED_FIELDS_VALUE,
DUPLICATED_PACKET, ITERATION_NUMBER]
# Create CSV columns
# columns = [STATE]
# for column in IssuesByState[IssuesByState.keys()[0]]:
# columns.append(column)
writer = csv.DictWriter(csvfile, fieldnames=columns)
writer.writeheader()
for state_key in IssuesByState:
state_issue = IssuesByState[state_key]
for idx, issue_summary in enumerate(state_issue[REASON]):
value = 'None'
if fuzzed_pkt is not None:
value = state_issue[FUZZED_FIELDS_VALUE]
if isinstance(value, list):
value = str(value)
else:
value = '0x' + hexlify(value)
writer.writerow({
TIME: state_issue[TIME][idx],
STATE: state_key,
RECEIVED_PKT: state_issue[RECEIVED_PKT][idx],
REASON: issue_summary,
FUZZED_PKT: state_issue[FUZZED_PKT][idx],
FUZZED_FIELDS_NAME: state_issue[FUZZED_FIELDS_NAME][idx],
FUZZED_FIELDS_VALUE: value,
DUPLICATED_PACKET: state_issue[DUPLICATED_PACKET][idx],
ITERATION_NUMBER: state_issue[ITERATION_NUMBER][idx]
})
idx += 1
return IssueCounter
def Validate(packet, state, expected_layers):
pkt_layers = get_packet_expected_layers_from_state(packet, state, expected_layers)
if pkt_layers and len(pkt_layers) > 0:
fields_cost = 0
for pkt_layer in pkt_layers:
# fields_name = [field.name for field in pkt_layer.fields_desc]
# fields_size = [field_length(getattr(pkt_layer, field_name)) for field_name in fields_name]
# fields_size = fields_size
# fields_cost += numpy.prod( # multiply everything
# numpy.multiply(fields_size, 2)) # multiply size by 2
fields_cost = fields_cost + 1
return fields_cost
else:
return 0
def get_packet_expected_layers_from_state(packet, state, expected_layers):
counter = 0 # start after Dot11
layers = []
if state in expected_layers:
while True:
layer = packet.getlayer(counter)
counter += 1
if layer is None:
break
for layerClass in expected_layers[state].states_expected:
if layerClass == type(layer):
layers.append(layer)
return layers
else:
return None
import re
import os
regex_is_mac_str = re.compile("[A-Fa-f0-9]{2}:")
def is_mac(s):
return regex_is_mac_str.match(s) is not None
def gen_nonce(size):
"""Return a nonce of @size element of random bytes as a string"""
return raw(os.urandom(size))
import csv
column_name = 'issues_count'
log_data = [(1, 5L, -9.0, 0.198384831622735, -8.8, 2.3796790749778354),
(2, 10L, -9.0, 0.10379160858796604, -9.0, 2.314434674458951),
(3, 15L, -10.0, 0.1881653085525367, -9.2, 2.2842594659504813),
(4, 20L, -10.0, 0.2213113193198547, -9.2, 1.7647010350614019),
(5, 25L, -10.0, 0.08655818736733391, -9.2, 1.5051836808617511),
(6, 30L, -10.0, 0.12540520898545407, -9.4, 1.40149463703155),
(7, 35L, -10.0, 0.12154288575809202, -9.4, 1.5473831561050122),
(8, 40L, -10.0, 0.08280008796010746, -9.4, 1.563758989170399),
(9, 45L, -10.0, 0.11044359615464132, -9.4, 1.4005970553525795),
(10, 50L, -10.0, 0.07966413685851961, -9.4, 1.5190235796214204),
(11, 55L, -10.0, 0.08611410446355712, -9.4, 1.4194504821271534),
(12, 60L, -10.0, 0.08376277658371688, -9.4, 1.4602536651590847),
(13, 65L, -10.0, 0.0644784702829888, -9.4, 1.1554711025844067),
(14, 70L, -10.0, 0.0705190785862602, -9.4, 1.1846847425979334),
(15, 75L, -10.0, 0.06807939596760032, -9.4, 1.2445091948157074),
(16, 80L, -10.0, 0.055352436990784654, -9.4, 1.349574194133837),
(17, 85L, -10.0, 0.06068887530437946, -9.6, 1.1539203957178061),
(18, 90L, -10.0, 0.04520143699934159, -9.6, 1.3396291717034114),
(19, 95L, -10.0, 0.0368090741812241, -9.6, 1.2864620169013994),
(20, 100L, -10.0, 0.055768794378364565, -9.6, 1.1366389403982762),
(21, 105L, -10.0, 0.03190038245827167, -9.6, 1.203859073844187),
(22, 110L, -10.0, 0.051221964793464476, -9.6, 1.161350847449445),
(23, 115L, -10.0, 0.03943438046869376, -9.6, 1.2737995564506472),
(24, 120L, -10.0, 0.03855719674244369, -9.6, 1.1360180575955967),
(25, 125L, -10.0, 0.05309185616425705, -9.6, 1.1180838721661739)]
with open('cost_function_graph.csv', 'w') as csvfile:
columns = ['X', column_name]
writer = csv.DictWriter(csvfile, fieldnames=columns)
writer.writeheader()
for entry in log_data:
writer.writerow({
'X': entry[0],
column_name: entry[2]
})
from threading import Timer, Thread
import inspect
import sys
from transitions.extensions import HierarchicalGraphMachine
from transitions.extensions.states import add_state_features, Tags, _LOGGER
from transitions.core import State, listify
from transitions.extensions.diagrams import TransitionGraphSupport
from transitions.extensions.nesting import NestedTransition
# from .webserver import start_webserver, send_graph, send_vulnerability
from scapy.utils import wrpcap
from scapy.packet import Packet
from colorama import Fore
from . import fitness
class StdOutHook:
def write(self, data):
sys.__stdout__.write(data + Fore.RESET)
class Timeout(State):
""" Adds timeout functionality to a state. Timeouts are handled model-specific.
Attributes:
timeout (float): Seconds after which a timeout function should be called.
on_timeout (list): Functions to call when a timeout is triggered.
"""
dynamic_methods = ['on_timeout']
timer = None
timer_event_data = None
def __init__(self, *args, **kwargs):
"""
Args:
**kwargs: If kwargs contain 'timeout', assign the float value to self.timeout. If timeout
is set, 'on_timeout' needs to be passed with kwargs as well or an AttributeError will
be thrown. If timeout is not passed or equal 0.
"""
self.timeout = kwargs.pop('timeout', 0)
self._on_timeout = None
if self.timeout > 0:
try:
self.on_timeout = kwargs.pop('on_timeout')
except KeyError:
raise AttributeError("Timeout state requires 'on_timeout' when timeout is set.")
else:
self._on_timeout = kwargs.pop('on_timeout', [])
self.runner = {}
super(Timeout, self).__init__(*args, **kwargs)
def enter(self, event_data):
""" Extends `transitions.core.State.enter` by starting a timeout timer for the current model
when the state is entered and self.timeout is larger than 0.
"""
if self.timeout > 0:
self.timer_event_data = event_data
self.timer = self.start_timer(event_data)
self.runner[id(event_data.model)] = self.timer
super(Timeout, self).enter(event_data)
def exit(self, event_data):
""" Extends `transitions.core.State.exit` by canceling a timer for the current model. """
self.stop_timer()
super(Timeout, self).exit(event_data)
def _process_timeout(self, event_data):
if event_data.machine.print_timeout:
print(Fore.YELLOW + '[!] State timeout')
for callback in self.on_timeout:
event_data.machine.callback(callback, event_data)
def start_timer(self, event_data):
timer = Timer(self.timeout, self._process_timeout, args=(event_data,))
timer.setDaemon(True)
timer.start()
return timer
def reset_timer(self):
if self.timer:
self.timer.cancel()
self.timer = self.start_timer(self.timer_event_data)
self.runner[id(self.timer_event_data.model)] = self.timer
def stop_timer(self):
if self.timer:
self.timer.cancel()
@property
def on_timeout(self):
""" List of strings and callables to be called when the state timeouts. """
return self._on_timeout
@on_timeout.setter
def on_timeout(self, value):
""" Listifies passed values and assigns them to on_timeout."""
self._on_timeout = listify(value)
class CustomNestedGraphTransition(TransitionGraphSupport, NestedTransition):
"""
A transition type to be used with (subclasses of) `HierarchicalGraphMachine` and
`LockedHierarchicalGraphMachine`.
"""
def _change_state(self, event_data):
event_data.machine.source = self.source
event_data.machine.destination = self.dest
if event_data.machine.print_transitions:
print(Fore.BLUE + 'Transition:' + Fore.LIGHTCYAN_EX + self.source + Fore.BLUE +
' ---> ' + Fore.LIGHTCYAN_EX + self.dest)
super(CustomNestedGraphTransition, self)._change_state(event_data)
def creat_log_dirs(model_name):
# Create target Directory if don't exist
def verify_and_create(path):
if not os.path.exists(path):
os.mkdir(path)
verify_and_create('logs')
verify_and_create('logs/' + model_name)
verify_and_create('logs/' + model_name + '/pcap')
verify_and_create('logs/' + model_name + '/csv')
verify_and_create('logs/' + model_name + '/monitor_serial')
verify_and_create('logs/' + model_name + '/sessions')
verify_and_create('logs/' + model_name + '/anomalies')
@add_state_features(Tags, Timeout)
class GreyhunterStateMachine(HierarchicalGraphMachine):
transition_cls = CustomNestedGraphTransition
# State machine variables
model_name = None
config_file = None
idle_state = None # type: str
enable_webserver = False
file_count = 0
print_transitions = False
print_timeout = False
source = None
destination = None
pcap_session_packets = []
pcap_anomaly_packets = []
pcap_anomaly_packets_number = 0
def __init__(self, *args, **kwargs):
self.model_name = inspect.currentframe().f_back.f_code.co_filename.split('/')[-1].split('.py')[0]
creat_log_dirs(self.model_name)
fitness.model_name = self.model_name
self.idle_state = kwargs.pop('idle_state', '')
self.enable_webserver = kwargs.pop('enable_webserver', False)
# if self.enable_webserver:
# kwargs['after_state_change'] = send_graph
self.print_transitions = kwargs.pop('print_transitions', False)
print("pop print_transition:", self.print_transitions)
self.print_timeout = kwargs.pop('print_timeout', False)
print("pop print_timeout:", self.print_timeout)
kwargs['title'] = ""
kwargs['show_auto_transitions'] = False
kwargs['model'] = inspect.currentframe().f_back.f_locals['self']
# TODO: save stdout along with logs
# sys.stdout = custom_print
Packet.fuzzed = False # Monkeypatch Packet class
super(GreyhunterStateMachine, self).__init__(*args, **kwargs)
model = kwargs['model']
# if self.enable_webserver:
# start_webserver(model)
def add_packets(self, pkt):
self.pcap_session_packets.append(pkt)
self.pcap_anomaly_packets.append(pkt)
self.pcap_anomaly_packets_number += 1
# print('2: ' + str(pkt.fuzzed))
def save_packets(self):
self.file_count += 1
def save_file_thread():
try:
temp_pkts = self.pcap_session_packets
wrpcap('logs/' + self.model_name + '/sessions/session_' + str(self.file_count), temp_pkts)
except:
pass
self.pcap_session_packets = None
self.pcap_session_packets = []
# temp_pkts = self.pcap_session_packets
# wrpcap('logs/' + self.model_name + '/sessions/session_' + str(self.file_count), temp_pkts)
Thread(target=save_file_thread).start()
def save_anomaly_packets(self, anomaly_name):
def save_file_thread():
try:
temp_pkts = self.pcap_anomaly_packets
wrpcap('logs/' + self.model_name + '/anomalies/' + anomaly_name + '_' + str(self.file_count), temp_pkts)
except:
pass
self.pcap_anomaly_packets_number = 0
self.pcap_anomaly_packets = None
self.pcap_anomaly_packets = []
Thread(target=save_file_thread).start()
def report_anomaly(self, msg=None, pkt=None):
message = 'ANOMALY detected in state ' + self.model.state
if msg:
message = msg + '\n' + message
print(Fore.RED + '[ANOMALY] ' + message)
fitness.AnomalyDetected(self.model.state, pkt, message)
# send_vulnerability(fitness.IssueCounter, message, error=False) # Inform user interface
self.save_anomaly_packets('anomaly')
def report_crash(self):
message = 'CRASH detected in state ' + self.model.state
print(Fore.RED + '[CRASH] ' + message)
fitness.AnomalyDetected(self.model.state, None, message)
# send_vulnerability(fitness.IssueCounter, message, error=True) # Inform user interface
self.save_anomaly_packets('crash')
def reset_state_timeout(self):
state = self.get_state(self.model.state)
if isinstance(state, Timeout):
state.reset_timer()
def reset_machine(self):
func = getattr(self.model, 'to_' + self.idle_state)
func()
# import time
# from scapy.layers.bluetooth import *
# from scapy.utils import raw
#
# s = HCI_Hdr() / HCI_ACL_Hdr() / L2CAP_Hdr() / SM_Hdr() / SM_Pairing_Request()
#
# data = bytearray(raw(s))
#
# c_array = ''
#
# c_array = 'uint8_t packet[] = { '
# for idx, b in enumerate(data):
# c_array += hex(b)
# if idx is not len(data) - 1:
# c_array += ', '
# if idx != 0 and idx % 8 == 0:
# c_array += '\n'
# c_array += ' };'
#
# print(c_array)
#
# x = '0001020304'.decode('hex')
#
# x = HCI_Hdr(x)
# x.show()
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
from scapy.layers.bluetooth4LE import *
from scapy.utils import raw, wrpcap, rdpcap
from binascii import hexlify
read_pkts = rdpcap('test.pcap')
pkts = []
# for pkt in read_pkts:
# pkts.append(BTLE(pkt.load))
# wrpcap('pairing.pcap', pkts)
print(read_pkts[0].summary())
read_pkts[0].show()
print('finished')
import npyscreen
class TestApp(npyscreen.NPSApp):
def main(self):
# These lines create the form and populate it with widgets.
# A fairly complex screen in only 8 or so lines of code - a line for each control.
F = npyscreen.Form(name="Welcome to Npyscreen", )
t = F.add(npyscreen.TitleText, name="Text:", )
fn = F.add(npyscreen.TitleFilename, name="Filename:")
fn2 = F.add(npyscreen.TitleFilenameCombo, name="Filename2:")
dt = F.add(npyscreen.TitleDateCombo, name="Date:")
s = F.add(npyscreen.TitleSlider, out_of=12, name="Slider")
ml = F.add(npyscreen.MultiLineEdit,
value="""try typing here!\nMutiline text, press ^R to reformat.\n""",
max_height=5, rely=9)
ms = F.add(npyscreen.TitleSelectOne, max_height=4, value=[1, ], name="Pick One",
values=["Option1", "Option2", "Option3"], scroll_exit=True)
ms2 = F.add(npyscreen.TitleMultiSelect, max_height=-2, value=[1, ], name="Pick Several",
values=["Option1", "Option2", "Option3"], scroll_exit=True)
# This lets the user interact with the Form.
F.edit()
self.add(npyscreen.TitleDateCombo, name="Date:", max_width=x // 2)
print(ms.get_selected_objects())
if __name__ == "__main__":
App = TestApp()
App.run()
# Common imports
import threading
import json
import logging
import os
from time import sleep, time
# Flask imports
from flask import Flask, request
from flask_socketio import SocketIO
from colorama import Fore, Back
model = None
clientConected = 0
app = Flask(__name__)
socket = SocketIO(app, async_mode='threading', logger=False, engineio_logger=False, cors_allowed_origins='*')
boot_time = None
def flaskServer():
socket.run(app, host='0.0.0.0', port=3000)
def start_webserver(model_instance):
global model, clientConected, app, boot_time
model = model_instance
app.debug = False
app.logger.disabled = True
log = logging.getLogger('werkzeug')
log.disabled = True
flask = threading.Thread(target=flaskServer)
flask.daemon = True
boot_time = time()
flask.start()
print(Fore.YELLOW + 'SocketIO Webserver started')
def send_graph():
global clientConected
if clientConected:
g = model.get_graph()
g.graph_attr.update(size="15.0,8.0")
socket.emit('GraphUpdate', {'graph': g.to_string(), 'stateName': model.state})
@app.route('/')
def index():
return 'hello'
@socket.on('connect')
def connect():
global clientConected
clientConected += 1
print('Web server connection')
if model is None:
return
send_graph()
@socket.on('disconnect')
def disconnect():
global clientConected
clientConected -= 1
print('disconnect ')
@socket.on('ResetMachineState')
def ResetMachineState():
if model is None:
return
try:
model.machine.reset_machine()
except:
return 'ERROR'
return 'OK'
@socket.on('SignalCrash')
def SignalCrash():
if model is None:
return
model.monitor_crash_detected()
def send_vulnerability(code, message, error=False):
if clientConected:
socket.emit('Vulnerability', {'code': code, 'message': message, 'error': error})
def send_fitness(issue_count, issue_period, iteration_transitions, iteration_time, iteration_number, issue_total):
if clientConected:
socket.emit('Iteration', {'IssueCount': issue_count, 'IssuePeriod': issue_period,
'Transitions': iteration_transitions, 'IterTime': iteration_time,
'Iteration': iteration_number, 'IssueTotalCount': issue_total})
@socket.on('GraphDot')
def graphString():
if model is None:
return
g = model.get_graph()
g.graph_attr.update(size="15.0,8.0")
return g.to_string()
@socket.on('GetFuzzerConfig')
def GetFuzzerConfig():
global states_fuzzer_config
config = []
for state in states_fuzzer_config:
state_config = states_fuzzer_config[state]
for attribute_name in state_config.field_names:
val = getattr(state_config, attribute_name)
val_type = type(val)
if val_type is int:
config.append(val)
elif val_type is list:
if len(val) > 0 and type(val[0]) is int:
config += val
return config
@socket.on('Reset')
def Reset():
request.environ.get('werkzeug.server.shutdown')()
os.kill(os.getpid(), 2)
@socket.on('GetBootTime')
def GetFuzzerConfig():
if model is None:
return
return boot_time
@socket.on('GetFitness')
def GetFitness():
if model is None:
return
IssuePeriod = fitness.IssuePeriod
if IssuePeriod == float("inf"):
IssuePeriod = 0
IterationTime = fitness.IterationTime
if IterationTime == float("inf"):
IterationTime = 0
obj = {'IssueCount': fitness.IssueCounter,
'IssuePeriod': IssuePeriod,
'Transitions': fitness.TransitionLastCount,
'IterTime': IterationTime,
'Iteration': model.iterations,
'IssueTotalCount': fitness.IssuesTotalCounter}
return json.dumps(obj) + '\n'
@socket.on('GetModelConfig')
def GetModelConfig():
if model is None:
try:
f = file(model.config_file, 'r')
return f.read()
except:
return '{}'
return model.get_config()
@socket.on('SetModelConfig')
def SetModelConfig(data):
global model
f = file(model.config_file, 'w')
f.write(json.dumps(data, indent=4))
f.close()
request.environ.get('werkzeug.server.shutdown')()
os.kill(os.getpid(), 2)
@socket.on('SetFuzzerConfig')
def SetFuzzerConfig(config):
global states_fuzzer_config
print(Back.WHITE + Fore.BLACK + 'Fuzzing input set to: ' + str(config))
idx = 0
for state in states_fuzzer_config:
state_config = states_fuzzer_config[state]
for attribute_name in state_config.field_names:
val = getattr(state_config, attribute_name)
val_type = type(val)
if val_type is int:
setattr(state_config, attribute_name, config[idx])
idx += 1
elif val_type is list:
val_len = len(val)
if val_len > 0 and type(val[0]) is int:
setattr(state_config, attribute_name, config[idx:idx + val_len])
idx += val_len
def SetFuzzerConfig(fuzz_cfg):
global states_fuzzer_config
states_fuzzer_config = fuzz_cfg
TIME,STATE,RECEIVED_PKT,REASON,FUZZED_PKT,FUZZED_FIELDS_NAME,FUZZED_FIELDS_VALUE,DUPLICATED_PKT,ITERATION_NUMBER
2022-12-27 06_58_29.934358,INITIALIZING,HCI Command / HCI_Command_Hdr,ANOMALY detected in state INITIALIZING,None,None,None,None,0
TIME,STATE,RECEIVED_PKT,REASON,FUZZED_PKT,FUZZED_FIELDS_NAME,FUZZED_FIELDS_VALUE,DUPLICATED_PKT,ITERATION_NUMBER
2022-12-27 06_58_29.934358,INITIALIZING,HCI Command / HCI_Command_Hdr,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.435515,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Filter,ANOMALY detected in state INITIALIZING,None,None,None,None,0
TIME,STATE,RECEIVED_PKT,REASON,FUZZED_PKT,FUZZED_FIELDS_NAME,FUZZED_FIELDS_VALUE,DUPLICATED_PKT,ITERATION_NUMBER
2022-12-27 06_58_29.934358,INITIALIZING,HCI Command / HCI_Command_Hdr,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.435515,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Filter,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.488588,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Connect_Accept_Timeout,ANOMALY detected in state INITIALIZING,None,None,None,None,0
TIME,STATE,RECEIVED_PKT,REASON,FUZZED_PKT,FUZZED_FIELDS_NAME,FUZZED_FIELDS_VALUE,DUPLICATED_PKT,ITERATION_NUMBER
2022-12-27 06_58_29.934358,INITIALIZING,HCI Command / HCI_Command_Hdr,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.435515,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Filter,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.488588,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Connect_Accept_Timeout,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.774382,INITIALIZING,HCI Command / HCI_Command_Hdr / Raw,ANOMALY detected in state INITIALIZING,None,None,None,None,0
TIME,STATE,RECEIVED_PKT,REASON,FUZZED_PKT,FUZZED_FIELDS_NAME,FUZZED_FIELDS_VALUE,DUPLICATED_PKT,ITERATION_NUMBER
2022-12-27 06_58_29.934358,INITIALIZING,HCI Command / HCI_Command_Hdr,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.435515,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Filter,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.488588,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Connect_Accept_Timeout,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.774382,INITIALIZING,HCI Command / HCI_Command_Hdr / Raw,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.986322,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Mask,ANOMALY detected in state INITIALIZING,None,None,None,None,0
TIME,STATE,RECEIVED_PKT,REASON,FUZZED_PKT,FUZZED_FIELDS_NAME,FUZZED_FIELDS_VALUE,DUPLICATED_PKT,ITERATION_NUMBER
2022-12-27 06_58_29.934358,INITIALIZING,HCI Command / HCI_Command_Hdr,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.435515,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Filter,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.488588,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Connect_Accept_Timeout,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.774382,INITIALIZING,HCI Command / HCI_Command_Hdr / Raw,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.986322,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Mask,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.067688,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Write_Simple_Pairing_mode,ANOMALY detected in state INITIALIZING,None,None,None,None,0
TIME,STATE,RECEIVED_PKT,REASON,FUZZED_PKT,FUZZED_FIELDS_NAME,FUZZED_FIELDS_VALUE,DUPLICATED_PKT,ITERATION_NUMBER
2022-12-27 06_58_29.934358,INITIALIZING,HCI Command / HCI_Command_Hdr,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.435515,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Filter,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.488588,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Connect_Accept_Timeout,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.774382,INITIALIZING,HCI Command / HCI_Command_Hdr / Raw,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.986322,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Mask,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.067688,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Write_Simple_Pairing_mode,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.112880,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_LE_Host_Supported,ANOMALY detected in state INITIALIZING,None,None,None,None,0
TIME,STATE,RECEIVED_PKT,REASON,FUZZED_PKT,FUZZED_FIELDS_NAME,FUZZED_FIELDS_VALUE,DUPLICATED_PKT,ITERATION_NUMBER
2022-12-27 06_58_29.934358,INITIALIZING,HCI Command / HCI_Command_Hdr,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.435515,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Filter,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.488588,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Connect_Accept_Timeout,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.774382,INITIALIZING,HCI Command / HCI_Command_Hdr / Raw,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.986322,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Mask,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.067688,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Write_Simple_Pairing_mode,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.112880,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_LE_Host_Supported,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.206342,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_LE_Set_Random_Address,ANOMALY detected in state INITIALIZING,None,None,None,None,0
TIME,STATE,RECEIVED_PKT,REASON,FUZZED_PKT,FUZZED_FIELDS_NAME,FUZZED_FIELDS_VALUE,DUPLICATED_PKT,ITERATION_NUMBER
2022-12-27 06_58_29.934358,INITIALIZING,HCI Command / HCI_Command_Hdr,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.435515,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Filter,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.488588,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Connect_Accept_Timeout,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.774382,INITIALIZING,HCI Command / HCI_Command_Hdr / Raw,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.986322,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Mask,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.067688,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Write_Simple_Pairing_mode,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.112880,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_LE_Host_Supported,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.206342,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_LE_Set_Random_Address,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.334513,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Write_Local_Name,ANOMALY detected in state INITIALIZING,None,None,None,None,0
TIME,STATE,RECEIVED_PKT,REASON,FUZZED_PKT,FUZZED_FIELDS_NAME,FUZZED_FIELDS_VALUE,DUPLICATED_PKT,ITERATION_NUMBER
2022-12-27 06_58_29.934358,INITIALIZING,HCI Command / HCI_Command_Hdr,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.435515,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Filter,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.488588,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Connect_Accept_Timeout,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.774382,INITIALIZING,HCI Command / HCI_Command_Hdr / Raw,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.986322,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Mask,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.067688,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Write_Simple_Pairing_mode,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.112880,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_LE_Host_Supported,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.206342,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_LE_Set_Random_Address,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.334513,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Write_Local_Name,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.541826,CONNECT_REQ,HCI Command / HCI_Command_Hdr / HCI_Cmd_Write_Local_Name,ANOMALY detected in state CONNECT_REQ,None,None,None,None,0
TIME,STATE,RECEIVED_PKT,REASON,FUZZED_PKT,FUZZED_FIELDS_NAME,FUZZED_FIELDS_VALUE,DUPLICATED_PKT,ITERATION_NUMBER
2022-12-27 06_58_29.934358,INITIALIZING,HCI Command / HCI_Command_Hdr,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.435515,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Filter,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.488588,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Connect_Accept_Timeout,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.774382,INITIALIZING,HCI Command / HCI_Command_Hdr / Raw,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_30.986322,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Set_Event_Mask,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.067688,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Write_Simple_Pairing_mode,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.112880,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_LE_Host_Supported,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.206342,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_LE_Set_Random_Address,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.334513,INITIALIZING,HCI Command / HCI_Command_Hdr / HCI_Cmd_Write_Local_Name,ANOMALY detected in state INITIALIZING,None,None,None,None,0
2022-12-27 06_58_32.541826,CONNECT_REQ,HCI Command / HCI_Command_Hdr / HCI_Cmd_Write_Local_Name,ANOMALY detected in state CONNECT_REQ,None,None,None,None,0
2022-12-27 06_58_32.590165,CONNECT_REQ,HCI Command / HCI_Command_Hdr / Raw,ANOMALY detected in state CONNECT_REQ,None,None,None,None,0
### fast usage
step 1. Install the environment according to the requirement.txt
step 2. run ble_controller_v1.py using "sudo python3 ble_controller_v1.py"
### If anything goes wrong, please contact me at rayjean@163.com.
\ No newline at end of file
pyserial==3.4
pyrecord==1.0.1
psutil==5.6.3
numpy==1.16
Flask==0.11.1
pygraphviz==1.5
colorama==0.4.1
cryptography==2.8
pycryptodome==3.8.2
socketio==0.1.7
ddt==1.2.1
Flask-SocketIO==5.1.0
logbook==1.4.4
graphiv==0.20
pycallgraph==1.0.1
pygmo==2.16.0
socketIO-client==0.7.2
\ No newline at end of file
479731f
\ No newline at end of file
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Philippe Biondi <phil@secdev.org>
# This program is published under a GPLv2 license
"""
Scapy: create, send, sniff, dissect and manipulate network packets.
Usable either from an interactive console or as a Python library.
http://www.secdev.org/projects/scapy
"""
import os
import re
import subprocess
_SCAPY_PKG_DIR = os.path.dirname(__file__)
def _version_from_git_describe():
"""
Read the version from ``git describe``. It returns the latest tag with an
optional suffix if the current directory is not exactly on the tag.
Example::
$ git describe --always
v2.3.2-346-g164a52c075c8
The tag prefix (``v``) and the git commit sha1 (``-g164a52c075c8``) are
removed if present.
If the current directory is not exactly on the tag, a ``.devN`` suffix is
appended where N is the number of commits made after the last tag.
Example::
>>> _version_from_git_describe()
'2.3.2.dev346'
"""
if not os.path.isdir(os.path.join(os.path.dirname(_SCAPY_PKG_DIR), '.git')): # noqa: E501
raise ValueError('not in scapy git repo')
process = subprocess.Popen(['git', 'describe', '--always'],
cwd=_SCAPY_PKG_DIR,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = process.communicate()
if process.returncode == 0:
tag = out.decode().strip()
match = re.match('^v?(.+?)-(\\d+)-g[a-f0-9]+$', tag)
if match:
# remove the 'v' prefix and add a '.devN' suffix
return '%s.dev%s' % (match.group(1), match.group(2))
else:
# just remove the 'v' prefix
return re.sub('^v', '', tag)
else:
raise subprocess.CalledProcessError(process.returncode, err)
def _version():
version_file = os.path.join(_SCAPY_PKG_DIR, 'VERSION')
try:
tag = _version_from_git_describe()
# successfully read the tag from git, write it in VERSION for
# installation and/or archive generation.
with open(version_file, 'w') as fdesc:
fdesc.write(tag)
return tag
except Exception:
# failed to read the tag from git, try to read it from a VERSION file
try:
with open(version_file, 'r') as fdsec:
tag = fdsec.read()
return tag
except Exception:
# Rely on git archive "export-subst" git attribute.
# See 'man gitattributes' for more details.
git_archive_id = '$Format:%h %d$'
sha1 = git_archive_id.strip().split()[0]
match = re.search('tag:(\\S+)', git_archive_id)
if match:
return "git-archive.dev" + match.group(1)
elif sha1:
return "git-archive.dev" + sha1
else:
return 'unknown.version'
VERSION = __version__ = _version()
VERSION_MAIN = re.search(r"[0-9.]+", VERSION).group()
if __name__ == "__main__":
from scapy.main import interact
interact()
# This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more information
# Copyright (C) Philippe Biondi <phil@secdev.org>
# This program is published under a GPLv2 license
"""
Scapy: create, send, sniff, dissect and manipulate network packets.
Usable either from an interactive console or as a Python library.
http://www.secdev.org/projects/scapy
"""
from scapy.main import interact
interact()
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This source diff could not be displayed because it is too large. You can view the blob instead.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment