File size: 10,513 Bytes
b3fa92f
 
 
 
 
 
 
ef5da6b
9403ec8
b3fa92f
1e61fc6
 
 
 
 
 
 
 
b3fa92f
 
ef5da6b
b3fa92f
 
 
ef5da6b
b3fa92f
 
 
ef5da6b
b3fa92f
 
 
1e61fc6
 
ef5da6b
b3fa92f
 
 
ef5da6b
1e61fc6
b3fa92f
 
ef5da6b
1e61fc6
b3fa92f
 
 
1e61fc6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b3fa92f
aca9561
 
 
 
 
 
 
 
 
 
1e61fc6
 
 
 
b3fa92f
1e61fc6
 
b3fa92f
 
 
 
1e61fc6
b3fa92f
 
 
 
1e61fc6
b3fa92f
1e61fc6
b3fa92f
 
 
 
 
 
 
1e61fc6
b3fa92f
1e61fc6
b3fa92f
 
 
 
 
1e61fc6
 
ef5da6b
1e61fc6
b3fa92f
1e61fc6
 
 
 
b3fa92f
1e61fc6
 
 
 
b3fa92f
1e61fc6
 
 
b3fa92f
1e61fc6
b3fa92f
1e61fc6
b3fa92f
1e61fc6
b3fa92f
 
1e61fc6
b3fa92f
 
1e61fc6
b3fa92f
1e61fc6
b3fa92f
 
 
 
 
1e61fc6
b3fa92f
 
1e61fc6
6272059
1e61fc6
6272059
 
 
 
aca9561
6272059
aca9561
6272059
 
c179942
ef5da6b
103a0e6
ef5da6b
6272059
 
aca9561
6272059
ef5da6b
6272059
ef5da6b
 
 
 
 
 
 
 
 
 
aca9561
6272059
ef5da6b
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
import streamlit as st 
import pandas as pd 
import matplotlib.pyplot as plt
import time 
import numpy as np 
import seaborn as sns 
import tensorflow as tf
from streamlit_extras.dataframe_explorer import dataframe_explorer
import os

# Constants
APP_TITLE = "SAVE_ME"
APP_LOGO = "matrix-hacker-background.jpg"  
FEEDBACK_FILE = 'predictions_feedback.csv'  
DESCRIPTION = """
<h2 style='color: #7D7D7D;'>Système de Détection d'Intrusion Basé sur l'Apprentissage Profond</h2>
<p>Dans un monde numérique en constante évolution, les menaces en ligne deviennent de plus en plus sophistiquées. Les systèmes de détection d'intrusion traditionnels peuvent ne pas suffire pour contrer ces attaques avancées. C'est pourquoi nous avons développé un système de détection d'intrusion (IDS) <strong>révolutionnaire</strong> basé sur l'apprentissage profond, offrant une sécurité renforcée et une détection précise des anomalies.</p>
"""
parameters = {
    "Action": {
        "description": "C'est la décision finale de votre modèle, indiquant s'il considère le trafic comme une intrusion ou non. Valeurs possibles: 'Intrusion' ou 'Non Intrusion'.",
        "image": "hackers-film-ddos-attack-threat-video.jpg"  
    },
    "Bytes Sent": {
        "description": "Nombre total d'octets envoyés par l'entité au cours de la connexion.",
        "image": "blue-optic-fiber-with-ethernet-cables.jpg"  
    },
    "Bytes Received": {
        "description": "Nombre total d'octets reçus par l'entité au cours de la connexion.",
        "image": "computer-hacker-hooded-shirt-typing-software-algorithms-stealing-data-from-computer-network-laptop.jpg"  
    }
}
params = {
    "pkts_sent": {
        "description": "Nombre total de paquets envoyés durant la connexion.",
        "image": "password-with-hand-holding-tweezers-binary-code.jpg"  
    },
    "pkts_received": {
        "description": "Nombre total de paquets reçus durant la connexion.",
        "image": "hackers-film-ddos-attack-threat-video.jpg"  
    },
    "Elapsed Time (sec)": {
        "description": "Temps écoulé en secondes durant la connexion ou l'événement observé.",
        "image": "html-css-collage-concept-with-hacker.jpg"  
    }
}

st.set_page_config(layout="wide", page_title=APP_TITLE, page_icon=APP_LOGO, initial_sidebar_state="expanded")

@st.cache_data
def loadDataframe(path):
    return pd.read_csv(path)

@st.cache_data
def loadModel():
    return tf.keras.models.load_model("security.h5")

def simulate_intrusion():
    col1, col2 = st.columns(2)
    with col1:
        bytes_sent = st.number_input("Bytes Sent", min_value=0, value=1)
        bytes_received = st.number_input("Bytes Received", min_value=0, value=1)
        elapsed_time = st.number_input("Elapsed Time (sec)", min_value=0, value=1)
        
    with col2:
        pkts_sent = st.number_input("Packets Sent", min_value=0, value=1)
        pkts_received = st.number_input("Packets Received", min_value=0, value=12)

    input_data = {
        "Bytes Sent": [bytes_sent if bytes_sent else 0],
        "Bytes Received": [bytes_received if bytes_received else 0],
        "Elapsed Time (sec)": [elapsed_time if elapsed_time else 0],
        "pkts_sent": [pkts_sent if pkts_sent else 0],
        "pkts_received": [pkts_received if pkts_received else 0]
    }
    
    return pd.DataFrame(input_data, index=[0])

def save_feedback(data):
    data.to_csv(FEEDBACK_FILE, mode='a', header=not os.path.exists(FEEDBACK_FILE), index=False)

def check_feedback(input_data):
    existing = feedback_data[
        (feedback_data['Bytes Sent'] == input_data['Bytes Sent'][0]) &
        (feedback_data['Bytes Received'] == input_data['Bytes Received'][0]) &
        (feedback_data['Elapsed Time (sec)'] == input_data['Elapsed Time (sec)'][0]) &
        (feedback_data['pkts_sent'] == input_data['pkts_sent'][0]) &
        (feedback_data['pkts_received'] == input_data['pkts_received'][0])
    ]
    return existing

# Load model and feedback data
MODEL = loadModel()
DATA = loadDataframe("finalDf.csv")

if os.path.exists(FEEDBACK_FILE):
    feedback_data = pd.read_csv(FEEDBACK_FILE)
else:
    feedback_data = pd.DataFrame(columns=['Bytes Sent', 'Bytes Received', 'Elapsed Time (sec)', 
                                          'pkts_sent', 'pkts_received', 'Model Prediction', 'User Correction'])

MenuNavigation =  ["🏠 Accueil", "📈 Analyse", "📊 Visualisation", "🤺 Simulation"]

st.sidebar.image(APP_LOGO, width=255)

chooseMenu = st.sidebar.selectbox("Où allons 🚔 nous Aujourd'hui? ", MenuNavigation)

if chooseMenu == MenuNavigation[0]:
    st.markdown("<h1 style='text-align:center;color: #005580; text-transform: uppercase; text-tranform:underline,'><u>{} </u></h1>".format(APP_TITLE), unsafe_allow_html=True)
    st.markdown("<p style='text-align:center; color: gray;'><i>Securité Sécurisée</i></p>", unsafe_allow_html=True)
    st.markdown("<h1 style='text-align:center;color: #005580; text-transform: uppercase; text-tranform:underline,'>{}: La meilleure approche pour votre sécurité</h1>".format(APP_TITLE), unsafe_allow_html=True)
    col1, col2 = st.columns((1, 2))
    with col1:
        st.image("html-css-collage-concept-with-hacker.jpg")
    with col2:
        st.write(DESCRIPTION, unsafe_allow_html=True)
    st.markdown("<h1 style='text-align:center; text-transform: uppercase; text-tranform:underline; color: #005580'>LES PARAMETRES DE NOTRE MODEL</h1>", unsafe_allow_html=True)
    col1, col2 = st.columns(2)

    with col1:
        for param, info in parameters.items():
            col1x, col2x = st.columns([1, 3])  
            with col1x:
                st.image(info['image'], use_column_width=True)  
            with col2x:
                st.markdown(f"""
                ### Paramètre: **{param}**
                {info['description']}
            """, unsafe_allow_html=True)
    with col2:
        for param, info in params.items():
            col1x, col2x = st.columns([1, 3])  
            with col1x:
                st.image(info['image'], use_column_width=True)  
            with col2x:
                st.markdown(f"""
                ### Paramètre: **{param}**
                {info['description']}
            """, unsafe_allow_html=True)

elif chooseMenu == MenuNavigation[1]:
    col1, col2, col3, col4, col5 = st.columns(5)
    sumByte = np.sum(DATA["Bytes Sent"]) + np.sum(DATA["Bytes Received"])
    col1.metric(label="Nombre De Données", value=DATA.shape[0], delta=5000)
    col2.metric(label="Nombre Moyens de Paquets ", value=int((DATA.pkts_sent.sum() + DATA.pkts_received.sum()) / DATA.shape[0]), delta=100)
    col3.metric(label="Nombre Moyen de Bytes", value=int(sumByte / DATA.shape[0]), delta=10000)
    col4.metric(label="Moyenne du temps des requêtes", value=int(DATA["Elapsed Time (sec)"].sum() / DATA.shape[0]), delta=1000)
    col5.metric(label="Maximum de Paquets", value=max(DATA.pkts_sent.astype(int) + DATA.pkts_received.astype(int)), delta=82)
    
    st.title("Filtrez le dataFrame")
    filtered_DataFrame = dataframe_explorer(DATA, case=False)
    st.dataframe(filtered_DataFrame, use_container_width=True)
    st.dataframe(DATA.drop("Action", axis=1).describe(), use_container_width=True, hide_index=False)

elif chooseMenu == MenuNavigation[2]:
    st.markdown("<h1 style='text-align:center;color: gray; text-transform: uppercase; text-tranform:underline; color: #005580'>Observons Nos données Avec les Graphes</h1>", unsafe_allow_html=True)
    my_grid = grid(2, [2, 4, 1], 1, 4, vertical_align="bottom")

    my_grid.line_chart(DATA.drop(["Bytes Sent", "Bytes Received", "Action", "Elapsed Time (sec)"], axis=1), use_container_width=True)
    my_grid.line_chart(DATA[["pkts_sent", "pkts_received"]], use_container_width=True)
    col1, col2 = st.columns(2)
    with col1:
        st.write(DATA.drop("Action", axis=1).describe())
    with col2:
        mask = np.triu(np.ones_like(DATA.drop("Action", axis=1).corr(), dtype=bool))
        f, ax = plt.subplots(figsize=(3, 4))
        cmap = sns.diverging_palette(230, 20, as_cmap=True)
        sns.heatmap(DATA.drop("Action", axis=1).corr(), mask=mask, cmap=cmap, vmax=.2, center=0,
                    square=True, linewidths=.3, cbar_kws={"shrink": .4})
        st.pyplot(f, use_container_width=False)  

    st.title("Variable Vs Action")  
    varMenu = ['Bytes Sent', 'Bytes Received', 'Elapsed Time (sec)', 'pkts_sent', 'pkts_received']
    colx = st.selectbox("Exprimer", varMenu)

    fig, ax = plt.subplots(figsize=(4, 2))
    sns.histplot(data=DATA[DATA[colx] < 100], x=colx, hue="Action", bins=12, kde=True, palette=["red", "green"], ax=ax)
    ax.set_title(f'Distribution de {colx} VS Action')
    st.pyplot(fig, use_container_width=False)

elif chooseMenu == MenuNavigation[3]:
    st.markdown("<h1 style='text-align:center;color: #005580; text-transform: uppercase; text-tranform:underline,'>SIMULATION DE VOS REQUETES </h1>", unsafe_allow_html=True)
    data_Input = simulate_intrusion()
    y_pred = MODEL.predict(data_Input)
    y_pred_class = (y_pred > 0.5).astype(int).flatten()
    data_Input["Model Prediction"] = ["Intrusion" if x == 0 else "No Intrusion" for x in y_pred_class]

    existing_feedback = check_feedback(data_Input)

    if not existing_feedback.empty:
        st.write("Cette situation a déjà été rencontrée.")
        st.write(f"Ancienne Prédiction du modèle: {existing_feedback['Model Prediction'].values[0]}")
        st.write(f"Action corrigée par l'utilisateur : {existing_feedback['User Correction'].values[0]}")
        data_Input["Model Prediction"]=existing_feedback['User Correction'].values[0]

    else:
        st.write("Prédiction du Modèle: " + data_Input["Model Prediction"].values[0])
        
        user_correction = st.selectbox("Cette prédiction est-elle correcte?", ["Oui", "Non"])
        corrected_action=""
        if user_correction == "Non":
            # Set corrected_action to the inverse of the prediction
            if data_Input["Model Prediction"].values[0] == "Intrusion":
                corrected_action = "No Intrusion"
            else:
                corrected_action = "Intrusion"
            feedback_entry = data_Input.copy()
            feedback_entry["User Correction"] = corrected_action
            feedback_entry["Model Prediction"] = data_Input["Model Prediction"].values[0]  # Keep original prediction
            save_feedback(feedback_entry)
     

    st.dataframe(data_Input, use_container_width=True)