Ejemplo n.º 1
0
    def create_aut_env(self):  # Spaeter on Button Click z.B.
        ''' this method creates the simulation'''               
        
        api_log_path = os.path.join(os.path.dirname(__file__), "../logs/api.log")
        api.show_logging(logging.INFO, api_log_path, True)
        my_env = api.create_environment(2500)
        
        ecu_spec = SimpleECUSpec([], 200, 200)
        ecu_group_1 = api.set_ecus(my_env, 10, 'SecureECU', ecu_spec)
        
        ecu_spec = SimpleECUSpec(['SEC 1'], 200, 200)
        ecu_spec.set_ecu_setting('t_ecu_auth_trigger_process', 100)
        ecu_spec.set_ecu_setting('t_ecu_auth_trigger_intervall', 1000)
        
        sec_mod_group = api.set_ecus(my_env, 1, 'SecLwAuthSecurityModule', ecu_spec)
        
        bus_spec = SimpleBusSpec(['CAN_0'])
        bus_group = api.set_busses(my_env, 1, 'StdCANBus', bus_spec)
        api.connect_bus_by_obj(my_env, 'CAN_0', ecu_group_1 + sec_mod_group)
        
        api.register_ecu_groups_to_secmod(my_env, sec_mod_group[0].ecu_id, [ecu_group_1])
        
        certeros = api.create_cert_manager()
        for ecu in APICore()._ecu_list_from_groups([[ecu_group_1]]):  # UNINTENDED HACK
            api.generate_valid_ecu_cert_cfg(certeros, ecu.ecu_id, CAEnum.CA_L313, 'SEC 1', 0, float('inf'))
        api.generate_valid_sec_mod_cert_cfg(certeros, 'SEC 1', CAEnum.CA_L313, 0, float('inf'))
        api.apply_certification(my_env, certeros)
        
        
        stream_1 = MessageStream(my_env.get_env(), 'SecureECU_0', ['SecureECU_1', 'SecureECU_4', 'SecureECU_5'], 13, float('inf'), 0, float('inf'))
        stream_2 = MessageStream(my_env.get_env(), 'SecureECU_1', ['SecureECU_3', 'SecureECU_2', 'SecureECU_5'], 12, float('inf'), 0, float('inf'))
        stream_3 = MessageStream(my_env.get_env(), 'SecureECU_0', ['SecureECU_4', 'SecureECU_1', 'SecureECU_5'], 222, float('inf'), 0, float('inf'))
        stream_4 = MessageStream(my_env.get_env(), 'SecureECU_3', ['SecureECU_0', 'SecureECU_1', 'SecureECU_5'], 11, float('inf'), 0, float('inf'))
        stream_5 = MessageStream(my_env.get_env(), 'SecureECU_4', ['SecureECU_2', 'SecureECU_1', 'SecureECU_3'], 500, float('inf'), 0, float('inf'))
        api.add_allowed_stream(my_env, 'SEC 1', stream_1)
        api.add_allowed_stream(my_env, 'SEC 1', stream_2)
        api.add_allowed_stream(my_env, 'SEC 1', stream_3)
        api.add_allowed_stream(my_env, 'SEC 1', stream_4)
        api.add_allowed_stream(my_env, 'SEC 1', stream_5)
        
        t_set = TimingFunctionSet()
        ecu_func_set = StdSecurLwSecModTimingFunctions(main_library_tag='CyaSSL')
        t_set.set_mapping_from_function_set('SEC 1', ecu_func_set)
        api.apply_timing_functions_set(my_env, 'SEC 1', t_set)
          
        t_set2 = TimingFunctionSet() 
        ecu_func_set = StdSecurECUTimingFunctions(main_library_tag='CyaSSL')
        
        for ecu in APICore()._ecu_list_from_groups([[ecu_group_1]]):  # UNINTENDED HACK
            t_set2.set_mapping_from_function_set(ecu.ecu_id, ecu_func_set) 
            api.apply_timing_functions_set(my_env, ecu.ecu_id, t_set2)

        api.connect_monitor(my_env, self.monitor, 50)
        api.build_simulation(my_env)
        
        ''' start this in a new thread'''
        sim = SimulationThread(self, my_env)
        sim.start()
 def preprocess(self, env, mapp):
     
     self.ecu_spec = SimpleECUSpec(mapp["id_list"] , mapp["send_buffer"], mapp["rec_buffer"])        
     for k in mapp["ecu_settings"]:
         self.ecu_spec.set_ecu_setting(k, mapp["ecu_settings"][k])  
             
     self.ecu_group = api.ecu_sim_api.set_ecus(env, mapp["nr_ecus"], 'SecureECU', self.ecu_spec)
Ejemplo n.º 3
0
LWASpecPresets().apply_spec(ecu_spec, 'ecu')
ecu_group_3 = api.set_ecus(sim_env, 2, 'RegularSecureECU', ecu_spec)
 
ecu_spec = RegularECUSpec(["RegularSecureECU_18", "Any_ECU_Name"], 20000, 20000)
ecu_spec.set_apply_jitter(0.0001)
# ecu_spec.set_startup_delay(140)  # start this ecu with delay of 15

LWASpecPresets().apply_spec(ecu_spec, 'ecu')
ecu_group_4 = api.set_ecus(sim_env, 3, 'RegularSecureECU', ecu_spec)
 
#===============================================================================
#     Creating Security modules
#===============================================================================

# create the ECU specification
ecu_spec = SimpleECUSpec(['SEC 1'], 200000, 200000)  # 200 KB

# adjust the specification
ecu_spec.set_ecu_setting('t_ecu_auth_trigger_process', 0)  
ecu_spec.set_ecu_setting('t_ecu_auth_trigger_intervall', 1000)  
ecu_spec.set_apply_jitter(0.0001)
LWASpecPresets().apply_spec(ecu_spec, 'sec_mod')

# create exactly one security module
sec_mod_group = api.set_ecus(sim_env, 1, 'SecLwAuthSecurityModule', ecu_spec)
security_module = sec_mod_group[0]

#===============================================================================
#     Creating Gateways
#===============================================================================
class SecureECUAddWidget(AbstractAddPlugin):
    ''' This is the interface that connects the GUI and the actions to
        execute for a SecureECU when it is to be created in the new
        simulation window '''
    
    GUI_NAME = "ECU Secure"
    GUI_ICON = os.getcwd() + r'/icons/secure_ecu.png'

    def __init__(self, parent):
        AbstractAddPlugin.__init__(self, parent)        
        self._create_widgets(parent)
        self.parent = parent
                
        self.set_ecu_settings = {}
        self.set_time_lib = {}
        self.has_sec_mod_cert = False
        self.id = uuid.uuid4()
        
        self.ecu_group = None
        
    def set_gui(self, mapp):
        ''' set the gui from the map received '''
        try:
            if "id_list" in mapp: self.id_list.setText(str(mapp["id_list"]))
            if "send_buffer" in mapp: self.send_buf_textedit.setText(str(mapp["send_buffer"]))
            if "rec_buffer" in mapp: self.rec_buf_textedit.setText(str(mapp["rec_buffer"]))
            if "nr_ecus" in mapp: self.nr_ecus_textedit.setText(str(mapp["nr_ecus"]))
            
            if "ecu_settings" in mapp: self.set_ecu_settings = mapp["ecu_settings"]
            self._set_cb_changed()
            
            if "ecu_timing" in mapp: self.set_time_lib = mapp["ecu_timing"]
            index = self.ecu_set_time_sel_cb.findText(self.set_time_lib[self.ecu_set_time_cb.currentText()])
            self.ecu_set_time_sel_cb.setCurrentIndex(index)  
            self._cur_set_time_entry = self.ecu_set_time_cb.currentText()  
            
            if "has_sec_mod_cert" in mapp: self.has_sec_mod_cert = mapp["has_sec_mod_cert"]
            if not self.has_sec_mod_cert: self.has_sec_mod_cert_cb.setCurrentIndex(0)
            
        except:
            ECULogger().log_traceback()

    def get_map(self):
        
        
        mapping_values = {}
        # Read the values from the gui and save them  
        # General Information      
        mapping_values["id_list"] = self._wrap(eval, self.id_list.text(), [])
        mapping_values["send_buffer"] = self._wrap(int, self.send_buf_textedit.text(), 200)
        mapping_values["rec_buffer"] = self._wrap(int, self.rec_buf_textedit.text(), 200)
        mapping_values["nr_ecus"] = self._wrap(int, self.nr_ecus_textedit.text(), 0)
        
        if self.ecu_set_te.text():
            self.set_ecu_settings[self._cur_set_entry] = self.ecu_set_te.text()
        mapping_values["ecu_settings"] = self.set_ecu_settings
        
        # Certification and Timing
        self.set_time_lib[self._cur_set_time_entry] = self.ecu_set_time_sel_cb.currentText()  # Final entry
        mapping_values['ecu_timing'] = self.set_time_lib
        mapping_values['has_sec_mod_cert'] = self.has_sec_mod_cert        

#         mapping_values['connected_sec_mod'] = None
        
        return mapping_values

    def preprocess(self, env, mapp):
        
        self.ecu_spec = SimpleECUSpec(mapp["id_list"] , mapp["send_buffer"], mapp["rec_buffer"])        
        for k in mapp["ecu_settings"]:
            self.ecu_spec.set_ecu_setting(k, mapp["ecu_settings"][k])  
                
        self.ecu_group = api.ecu_sim_api.set_ecus(env, mapp["nr_ecus"], 'SecureECU', self.ecu_spec)
    
    def get_actions(self):
        ''' returns the connections that can be made '''        
        
        actions = {}
        
        actions['valid_cert'] = 'Generate Valid Certificate'
                
        return actions
        
    def execute_action(self, env_connect, *args):
        pass

    def main_process(self, env, mapp):
        print("Main")

    def postprocess(self, env, mapp):
        print("Post")

    def _create_widgets(self, parent):

        # Layout
        GBuilder().set_props(self, None, 100, 100)  
        main_lo = QVBoxLayout()
        self.setLayout(main_lo)
        
        # Title
        main_lo.addWidget(GBuilder().label(parent, "<b>Description:</b>"))
        hl = QHBoxLayout()        
        self.desc_label = GBuilder().label(parent, "Add a new SecureECU. This ECU resembles the ECU Part in a Lightweight Authentication Mechanism.")
        self.desc_label.setFixedWidth(400)
        self.icon = GBuilder().image(parent, SecureECUAddWidget.GUI_ICON, 2)        
        hl.addWidget(self.desc_label)
        hl.addWidget(self.icon)
        main_lo.addLayout(hl)
        
        line = GBuilder().hor_line(parent)
        main_lo.addWidget(line);
                
        # Constructor Inputs
        main_lo.addWidget(GBuilder().label(parent, "<b>General Information:</b>"))
        lo0, self.id_list = GBuilder().label_text(parent, "List of IDs (optional):", label_width=120)
        lo1, self.send_buf_textedit = GBuilder().label_text(parent, "Sending BufferSize:", label_width=120)
        lo2, self.rec_buf_textedit = GBuilder().label_text(parent, "Receiving Buffer Size:", label_width=120)
        lo3, self.nr_ecus_textedit = GBuilder().label_text(parent, "Number of ECUs:", label_width=120)
        main_lo.addLayout(lo0)
        main_lo.addLayout(lo1)
        main_lo.addLayout(lo2)
        main_lo.addLayout(lo3)

        # ECU Settings
        items = self._get_ecu_settings()
        hl, self.ecu_set_cb, self.ecu_set_te = GBuilder().combobox_text(parent, items, self._set_cb_changed)
        self._cur_set_entry = self.ecu_set_cb.currentText()
        main_lo.addLayout(hl)
        
        # Timing Mapping 
        line = GBuilder().hor_line(parent)
        main_lo.addWidget(line);
        lab = GBuilder().label(parent, "<b>Timing and Certification:</b>")
        lab.setFixedHeight(20)
        main_lo.addWidget(lab)
        
        itm = StdSecurECUTimingFunctions()
        avail_items = itm.available_tags
        items = itm.function_map.keys()        
        hl1 = QHBoxLayout()
        self.ecu_set_time_cb = GBuilder().combobox(parent, items, self._set_time_cb_changed)
        self._cur_set_time_entry = self.ecu_set_time_cb.currentText()   
        
        self.ecu_set_time_sel_cb = GBuilder().combobox(parent, avail_items, self._set_time_cb_changed)
        self._cur_set_time_sel_entry = self.ecu_set_time_sel_cb.currentText()
        hl1.addWidget(self.ecu_set_time_cb)
        hl1.addWidget(self.ecu_set_time_sel_cb)
        main_lo.addLayout(hl1)

        # Certification (has a valid certificate or not)
#         hl, self.has_sec_mod_cert_cb, lab = GBuilder().label_combobox(parent, "Has Security Module Certificate", ["Yes", "No"], self._has_sec_mod_cb_changed)
#         main_lo.addLayout(hl)

    def _get_ecu_settings(self):
        SecureECU().settings = sorted(SecureECU().settings, key=lambda key: SecureECU().settings[key])
        
        return SecureECU().settings
        
    def _has_sec_mod_cb_changed(self):
        try:
            if self.has_sec_mod_cert_cb.currentText() == "Yes":
                self.has_sec_mod_cert = True
            else:
                self.has_sec_mod_cert = False
        except:
            pass
        
    def _set_time_cb_changed(self):   

        try:
            # Save old value
            if self._cur_set_time_entry == self.ecu_set_time_cb.currentText():
                self.set_time_lib[self._cur_set_time_entry] = self.ecu_set_time_sel_cb.currentText()
                self._cur_set_time_entry = self.ecu_set_time_cb.currentText()
                return
            
            # Load the next one
            try:
                index = self.ecu_set_time_sel_cb.findText(self.set_time_lib[self.ecu_set_time_cb.currentText()])
                self.ecu_set_time_sel_cb.setCurrentIndex(index)                           
            except:
                self.ecu_set_time_sel_cb.setCurrentIndex(0)        
            self._cur_set_time_entry = self.ecu_set_time_cb.currentText()                           
        except:
            pass
        
    def _set_cb_changed(self):        
        try:
            # Save old value
            if self.ecu_set_te.text():
                self.set_ecu_settings[self._cur_set_entry] = self.ecu_set_te.text()
            
            # Load the next one
            try:
                self.ecu_set_te.setText(self.set_ecu_settings[self.ecu_set_cb.currentText()])                
            except:
                self.ecu_set_te.setText('')            
            self._cur_set_entry = self.ecu_set_cb.currentText()
        except:
            pass
        
    def _wrap(self, func, prime, second):
        try:
            el = func(prime)
            return el
        except:
            return second
Ejemplo n.º 5
0
    def prepare_configuration(self, simpy_env, life_time):
        ''' this method prepares the configuration on the side of the 
            ECU simulation. It sets up the defined environment by mapping
            the ECU Ids as they are defined in the battery management system
            on the ECUs and the defined specs. So the constellation used is
            implemented here.
            
            Input:  simpy_env    simpy.Environment        environment used in the battery management system
                    life_time    float                    life time of the simulation
            Output: -
        '''
        # lifetime
        life_time = 50000
                
        # logging
#         api_log_path = os.path.join(os.path.dirname(__file__), "../logs/api.log")
#         api.show_logging(logging.INFO, api_log_path, True)
        
        # create environment
        sim_env = api.create_environment(life_time)
        sim_env.set_env(simpy_env)
        ecu_list = []
        
        # generate a ecu from the ECU specs setting the adapter
        for ecu_id in self.available_can_adapters():            
            # logging.info("ECU ID %s: " % ecu_id)
            
            # define individual ECU Spec 
            ecu_spec = copy.deepcopy(self._ecu_spec)
            ecu_class_name = self._ecu_class_name
            if ecu_id in self._individual_spec:
                ecu_spec = self._individual_spec[ecu_id][0]
                ecu_class_name = self._individual_spec[ecu_id][1]
            ecu_spec.ecu_id_list = [str(ecu_id)]
            
            # create ecu            
            ecu = api.set_ecus(sim_env, 1, ecu_class_name, ecu_spec)[0]
            ecu_list += [ecu]
            
            # connect ecu to adapter
            ecu.connect_adapter(self.can_bus_adapter[ecu_id])
        
        # add security module
        # create ECU specification
        ecu_spec = SimpleECUSpec(['SEC 1'], 200000, 200000)  # 200 KB
        ecu_spec.set_ecu_setting('t_ecu_auth_trigger_process', 0)  
        ecu_spec.set_ecu_setting('t_ecu_auth_trigger_intervall', 80000)  
        ecu_spec.set_apply_jitter(0.0001)
        sec_mod_group = api.set_ecus(sim_env, 1, 'SecLwAuthSecurityModule', ecu_spec)
        security_module = sec_mod_group[0]
        
        # connect to one bus
        # create the bus specifications
        bus_spec = SimpleBusSpec(['CAN_0'])
        api.set_busses(sim_env, 1, 'StdCANBus', bus_spec)
        api.connect_bus_by_obj(sim_env, 'CAN_0', ecu_list + sec_mod_group) 
                
        # security constellation
        all_ecu_groups = [ecu_list]
        api.register_ecu_groups_to_secmod(sim_env, sec_mod_group[0].ecu_id, all_ecu_groups)         
        certificate_manager = api.create_cert_manager()
        all_created_ecus = api.ecu_list_from_groups([all_ecu_groups])
        ecu_ids = [str(ecu.ecu_id) for ecu in all_created_ecus]        
        for ecu_id in ecu_ids:
            api.generate_valid_ecu_cert_cfg(certificate_manager, ecu_id, CAEnum.CA_L313, security_module.ecu_id, 0, float('inf'))
        api.generate_valid_sec_mod_cert_cfg(certificate_manager, security_module.ecu_id, CAEnum.CA_L313, ecu_ids, 0, float('inf'))
        api.apply_certification(sim_env, certificate_manager)
         
        # define allowed streams -------------------------------------------------------------- TODO very IMPORTANT
        for broadcast_stream_id in [0x0080, 0x0081, 0x0082, 0x0083, 0x0012, 0x0013, 0x0020, 0x00A0, 0x00A1 ]:
            for ecu_id in ecu_ids:
                lst = copy.deepcopy(ecu_ids)
                lst.remove(ecu_id)                
                stream = MessageStream(ecu_id, lst, broadcast_stream_id, float('inf'), 0, float('inf'))
                api.add_allowed_stream(sim_env, security_module.ecu_id, stream)
        #  -------------------------------------------------------------- TODO very IMPORTANT
        
        # set gateways
        api.autoset_gateway_filters(sim_env, sec_mod_group[0].ecu_id)

        # set timing functions
        function_set = TimingFunctionSet()        
        ecu_func_set = StdSecurLwSecModTimingFunctions(main_library_tag='CyaSSL')        
        ecu_func_set.library_tags['t_ecu_auth_reg_msg_validate_cert'] = 'Crypto_Lib_SW'
        function_set.set_mapping_from_function_set(security_module.ecu_id, ecu_func_set)
        api.apply_timing_functions_set(sim_env, security_module.ecu_id, function_set)
        function_set_2 = TimingFunctionSet() 
        ecu_func_set = StdSecurECUTimingFunctions(main_library_tag='CyaSSL')
        ecu_func_set.library_tags['t_adv_msg_secmodcert_enc'] = 'Crypto_Lib_SW'
        for ecu_id in ecu_ids:
            function_set_2.set_mapping_from_function_set(ecu_id, ecu_func_set) 
            api.apply_timing_functions_set(sim_env, ecu_id, function_set_2)
             
        # add monitor
        if self._monitor and self._result_reader:
            api.connect_monitor(sim_env, self._monitor, 0.5)  
            api.connect_result_reader(sim_env, self._monitor, self._result_reader)
             
            # run view if defined 
            if self._view:
                self._view.show(self._result_reader, self._view_options, self.q_application)                

        # run simulation
        api.open_simulation_stop_button(sim_env)
        api.build_simulation(sim_env)
        api.run_simulation(sim_env)