-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.py
executable file
Β·399 lines (319 loc) Β· 16.6 KB
/
app.py
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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
import os
import pymysql
import pymysql.cursors
import logging
import random
import time
import threading
import pyshark
import csv
import pandas as pd
import numpy as np
from sklearn.preprocessing import StandardScaler
from flask import Flask, request, session, redirect, render_template, flash, jsonify, abort
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
from sklearn.metrics import accuracy_score
from sklearn.metrics import classification_report
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
import time
from sklearn.ensemble import RandomForestClassifier
from joblib import dump
import joblib
from joblib import load
from Database.models import db, Fcuser, UserCity
from Database.sqlite import save_login_info_sqlite, save_clicked_city
from forms import RegisterForm, LoginForm
from attack import detect_dos_attack
from validation import get_user_location, calculate_distance, find_closest_city
from map import executor, cities, get_weather
# Flask μ ν리μΌμ΄μ
μμ±
app = Flask(__name__)
# λ‘κΉ
μ€μ
logging.basicConfig(filename='app.log', level=logging.INFO)
# λͺ¨λΈκ³Ό μ€μΌμΌλ¬ λΆλ¬μ€κΈ°
#model = load('/Users/chonakyung/modelmodel/DDOS_model (1).joblib')
#scaler = load('/Users/chonakyung/modelmodel/scaler .joblib')
# λ€νΈμν¬ μΈν°νμ΄μ€ μ ν
interface = 'en0'
# μΊ‘μ²ν IP μ£Όμ μ€μ
ip_address = '172.30.1.38'
port = 5050
# λͺ¨λΈ ν΄λμ€ μ μ
class Model:
def __init__(self, data, labels):
self.data = data
self.y = labels
self.scaler = StandardScaler().fit(self.data)
X = self.scaler.transform(self.data)
self.X_train, self.X_test, self.y_train, self.y_test = train_test_split(X, self.y, random_state=42, test_size=0.3)
self.RF = None
def RandomForest(self):
start_time = time.time()
self.RF = RandomForestClassifier(
criterion='gini', n_estimators=500, min_samples_split=10, max_features='sqrt',
oob_score=True, random_state=1, n_jobs=-1
).fit(self.X_train, self.y_train)
predicted_rf = self.RF.predict(self.X_test)
rf_accuracy = accuracy_score(self.y_test, predicted_rf)
print(f"Accuracy of RF is : {round(rf_accuracy * 100, 2)}%", '\n')
print("########################################################################")
print(classification_report(predicted_rf, self.y_test))
print("########################################################################")
print(" = = %s seconds = = " % (time.time() - start_time))
def predict(self, sample_data):
loaded_scaler = load('/Users/chonakyung/μ‘°μ λνκ΅/2024-1/μΊ‘μ€ν€λμμΈ/modelmodel/New_scaler.joblib')
new_data = loaded_scaler.transform(sample_data)
predicted_labels = self.RF.predict(new_data)
return predicted_labels
# λͺ¨λΈκ³Ό μ€μΌμΌλ¬ λΆλ¬μ€κΈ°
model_path = '/Users/chonakyung/μ‘°μ λνκ΅/2024-1/μΊ‘μ€ν€λμμΈ/modelmodel/Classification_model (1).joblib'
try:
model = joblib.load(model_path)
except AttributeError as e:
print(f"Error loading model: {e}")
scaler = joblib.load('/Users/chonakyung/μ‘°μ λνκ΅/2024-1/μΊ‘μ€ν€λμμΈ/modelmodel/New_scaler.joblib')
# μ€μκ° ν¨ν· μΊ‘μ² λ° μ²λ¦¬ ν¨μ
def extract_flags(tcp_layer):
flags = {
'FIN': 1 if tcp_layer.get_field_value('flags_fin') == '1' else 0,
'SYN': 1 if tcp_layer.get_field_value('flags_syn') == '1' else 0,
'RST': 1 if tcp_layer.get_field_value('flags_reset') == '1' else 0,
'PSH': 1 if tcp_layer.get_field_value('flags_push') == '1' else 0,
'ACK': 1 if tcp_layer.get_field_value('flags_ack') == '1' else 0,
'URG': 1 if tcp_layer.get_field_value('flags_urg') == '1' else 0,
'ECE': 1 if tcp_layer.get_field_value('flags_ecn') == '1' else 0,
}
return flags
def capture_and_predict_packets(interface, ip_address, port, capture_count=500):
while True:
try:
capture_filter = f'ip src {ip_address}'
capture = pyshark.LiveCapture(interface=interface, bpf_filter=capture_filter)
iat_times = []
packet_infos = []
for packet in capture.sniff_continuously(packet_count=capture_count):
if 'IP' in packet:
ip_layer = packet.ip
tcp_layer = packet.tcp if hasattr(packet, 'tcp') else None
# νλκ·Έ μΆμΆ
flags = extract_flags(tcp_layer) if tcp_layer else {}
# μ΄μ ν¨ν· μκ°κ³Ό νμ¬ ν¨ν· μκ° μ°¨μ΄ (IAT: Inter-Arrival Time)
if 'last_time' in locals():
iat = float(packet.sniff_time.timestamp()) - last_time
iat_times.append(iat)
last_time = float(packet.sniff_time.timestamp())
packet_info = {
'Flow Duration': int(float(packet.frame_info.time_relative) * 1e9),
'Total Fwd Packets': int(1) if tcp_layer and tcp_layer.srcport == port else 0,
'Total Backward Packets': int(1) if tcp_layer and tcp_layer.dstport == port else 0,
'Flow Packets/s': float(packet.frame_info.time_delta) if hasattr(packet.frame_info, 'time_delta') else 0,
'Flow Bytes/s': float(len(packet)) / float(packet.frame_info.time_delta) if hasattr(packet.frame_info, 'time_delta') and float(packet.frame_info.time_delta) > 0 else 0,
'Avg Packet Size': float(len(packet)),
'FIN Flag Count': flags.get('FIN', 0),
'SYN Flag Count': flags.get('SYN', 0),
'RST Flag Count': flags.get('RST', 0),
'PSH Flag Count': flags.get('PSH', 0),
'ACK Flag Count': flags.get('ACK', 0),
'URG Flag Count': flags.get('URG', 0),
'ECE Flag Count': flags.get('ECE', 0),
'Fwd Packets Length Total': int(packet.length) if tcp_layer and tcp_layer.srcport == port else 0,
'Bwd Packets Length Total': int(packet.length) if tcp_layer and tcp_layer.dstport == port else 0,
'Flow IAT Mean': np.mean(iat_times) if iat_times else 0,
'Flow IAT Std': np.std(iat_times) if iat_times else 0,
'Idle Mean': np.mean(iat_times) if iat_times else 0, # Assuming idle time is same as IAT for now
'Protocol': packet.transport_layer if hasattr(packet, 'transport_layer') else None
}
packet_infos.append(packet_info)
protocol_map = {'TCP': 6, 'UDP': 17}
for packet_info in packet_infos:
if packet_info['Protocol'] in protocol_map:
packet_info['Protocol'] = protocol_map[packet_info['Protocol']]
features = [
'Flow Duration', 'Total Fwd Packets', 'Total Backward Packets', 'Flow Packets/s',
'Flow Bytes/s', 'Avg Packet Size', 'FIN Flag Count', 'SYN Flag Count',
'RST Flag Count', 'PSH Flag Count', 'ACK Flag Count', 'URG Flag Count',
'ECE Flag Count', 'Fwd Packets Length Total', 'Bwd Packets Length Total',
'Flow IAT Mean', 'Flow IAT Std', 'Idle Mean', 'Protocol'
]
sample_data = pd.DataFrame(packet_infos, columns=features)
sample_data = sample_data.reindex(columns=scaler.feature_names_in_, fill_value=0)
sample_data_scaled = scaler.transform(sample_data)
predictions = model.predict(sample_data_scaled)
# ν°λ―Έλμ μμΈ‘ κ²°κ³Ό μΆλ ₯
print(f"Predictions: {predictions}")
# μΌμ μκ° λκΈ° ν λ€μ μΊ‘μ² μμ
time.sleep(1)
except Exception as e:
print(f"Error during packet capture and prediction: {e}")
time.sleep(5)
# last_time = float(packet.sniff_time.timestamp())
# packet_info = {
# 'Flow Duration': int(float(packet.frame_info.time_relative) * 1e9),
# 'Total Fwd Packets': int(1) if tcp_layer and tcp_layer.srcport == port else 0,
# 'Total Backward Packets': int(1) if tcp_layer and tcp_layer.dstport == port else 0,
# 'Flow Packets/s': float(packet.frame_info.time_delta) if hasattr(packet.frame_info, 'time_delta') else 0,
# 'Flow Bytes/s': float(len(packet)) / float(packet.frame_info.time_delta) if hasattr(packet.frame_info, 'time_delta') and float(packet.frame_info.time_delta) > 0 else 0,
# 'Avg Packet Size': float(len(packet)),
# 'FIN Flag Count': flags.get('FIN', 0),
# 'SYN Flag Count': flags.get('SYN', 0),
# 'RST Flag Count': flags.get('RST', 0),
# 'PSH Flag Count': flags.get('PSH', 0),
# 'ACK Flag Count': flags.get('ACK', 0),
# 'URG Flag Count': flags.get('URG', 0),
# 'ECE Flag Count': flags.get('ECE', 0),
# 'Fwd Packets Length Total': int(packet.length) if tcp_layer and tcp_layer.srcport == port else 0,
# 'Bwd Packets Length Total': int(packet.length) if tcp_layer and tcp_layer.dstport == port else 0,
# 'Flow IAT Mean': np.mean(iat_times) if iat_times else 0,
# 'Flow IAT Std': np.std(iat_times) if iat_times else 0,
# 'Idle Mean': np.mean(iat_times) if iat_times else 0, # Assuming idle time is same as IAT for now
# 'Protocol': packet.transport_layer if hasattr(packet, 'transport_layer') else None
# }
# packet_infos.append(packet_info)
# protocol_map = {'TCP': 6, 'UDP': 17}
# for packet_info in packet_infos:
# if packet_info['Protocol'] in protocol_map:
# packet_info['Protocol'] = protocol_map[packet_info['Protocol']]
# features = [
# 'Flow Duration', 'Total Fwd Packets', 'Total Backward Packets', 'Flow Packets/s',
# 'Flow Bytes/s', 'Avg Packet Size', 'FIN Flag Count', 'SYN Flag Count',
# 'RST Flag Count', 'PSH Flag Count', 'ACK Flag Count', 'URG Flag Count',
# 'ECE Flag Count', 'Fwd Packets Length Total', 'Bwd Packets Length Total',
# 'Flow IAT Mean', 'Flow IAT Std', 'Idle Mean', 'Protocol'
# ]
# sample_data = pd.DataFrame(packet_infos, columns=features)
# sample_data = sample_data.reindex(columns=scaler.feature_names_in_, fill_value=0)
# sample_data_scaled = scaler.transform(sample_data)
# predictions = model.predict(sample_data_scaled)
# # ν°λ―Έλμ μμΈ‘ κ²°κ³Ό μΆλ ₯
# print(f"Predictions: {predictions}")
# time.sleep(1)
@app.route('/analyze_packets', methods=['GET'])
def analyze_packets():
predictions = capture_and_predict_packets(interface, ip_address, port)
return f"Predictions: {predictions}"
# λ©μΈ νλ©΄
@app.route('/')
def hello():
userid = session.get('userid', None)
client_ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
city_name = request.args.get('city')
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
latitude, longitude = get_user_location(client_ip)
if city_name:
log_message = f"[{timestamp}] '{userid}'κ° '{client_ip}'μμ '{city_name}'λ₯Ό ν΄λ¦νμ΅λλ€."
logging.info(log_message)
closest_city = find_closest_city(client_ip, cities)
if city_name == closest_city:
is_closest = True
else:
is_closest = False
save_clicked_city(userid, client_ip, latitude, longitude, city_name, is_closest)
return render_template('hello.html', userid=userid, client_ip=client_ip, city_name=city_name)
# νμ κ°μ
@app.route('/register', methods=['GET', 'POST'])
def register():
form = RegisterForm()
if form.validate_on_submit():
fcuser = Fcuser()
fcuser.userid = form.data.get('userid')
fcuser.username = form.data.get('username')
fcuser.password = form.data.get('password')
db.session.add(fcuser)
db.session.commit()
flash("κ°μ
μλ£", 'success')
return render_template('hello.html', form=form)
return render_template('register.html', form=form)
# λ‘κ·ΈμΈ
@app.route('/login', methods=['GET', 'POST'])
def login():
form = LoginForm()
if form.validate_on_submit():
userid = form.data.get('userid')
session['userid'] = userid
ip_address = request.remote_addr
save_login_info_sqlite(userid, ip_address)
if userid == "admin":
session['admin'] = True
return redirect('/')
return render_template('login.html', form=form)
# λ‘κ·Έμμ
@app.route('/logout', methods=['GET'])
def logout():
if 'userid' in session:
userid = session.pop('userid')
flash('λ‘κ·Έμμ λμμ΅λλ€.', 'success')
session.pop('admin', None)
return redirect('/')
# μ§λ
@app.route('/map')
def map():
userid = session.get('userid', None)
cities = [
{"name": "μμΈ", "lat": 37.5665, "lon": 126.9780},
{"name": "ν리", "lat": 48.8566, "lon": 2.3522},
{"name": "λ΄μ", "lat": 40.7128, "lon": -74.0060},
{"name": "리μ°λ°μλ€μ΄λ£¨", "lat": -22.9068, "lon": -43.1729},
{"name": "μΉ΄μ΄λ‘", "lat": 30.0444, "lon": 31.2357},
{"name": "μλλ", "lat": -33.8688, "lon": 151.2093}
]
weather_data = list(executor.map(get_weather, cities))
return render_template('map.html', weather_data=weather_data, userid=userid)
@app.route('/clicked_city_info')
def clicked_city_info():
client_ip = request.environ.get('HTTP_X_REAL_IP', request.remote_addr)
client_latitude, client_longitude = get_user_location(client_ip)
closest_city = find_closest_city(client_ip, cities)
clicked_city_info = UserCity.query.filter_by(client_ip=client_ip, clicked_city=closest_city).first()
all_user_city_data = UserCity.query.all()
return render_template('clicked_city_info.html', client_latitude=client_latitude, client_longitude=client_longitude, closest_city=closest_city, clicked_city_info=clicked_city_info, all_user_city_data=all_user_city_data)
# κ²μ
@app.route('/game', methods=['GET', 'POST'])
def rsp_game():
userid = session.get('userid', None)
if request.method == 'POST':
player_choice = request.form.get('choice')
choices = ['Rock', 'Paper', 'Scissors']
computer_choice = random.choice(choices)
if player_choice == computer_choice:
result = f"μ»΄ν¨ν°μ μ νμ [{computer_choice}]\n λΉκ²Όμ΅λλ€!"
elif (player_choice == "Rock" and computer_choice == "Scissors") or \
(player_choice == "Scissors" and computer_choice == "Paper") or \
(player_choice == "Paper" and computer_choice == "Rock"):
result = f"μ»΄ν¨ν°μ μ νμ [{computer_choice}]\n μ΄κ²Όμ΅λλ€!"
else:
result = f"μ»΄ν¨ν°μ μ νμ [{computer_choice}]\n μ‘μ΅λλ€!"
if userid:
logging.info(f"{userid}λμ΄ {player_choice}μ(λ₯Ό) μ ννμμ΅λλ€.")
logging.info(f"μ»΄ν¨ν°κ° {computer_choice}μ(λ₯Ό) μ ννμμ΅λλ€.")
elif userid == None:
logging.info(f"μ¬μ©μκ° {player_choice}μ(λ₯Ό) μ ννμμ΅λλ€.")
logging.info(f"μ»΄ν¨ν°κ° {computer_choice}μ(λ₯Ό) μ ννμμ΅λλ€.")
response = {'result': result}
logging.info(result)
return jsonify(response)
return render_template('rsp_game.html', userid=userid)
def start_packet_capture():
capture_and_predict_packets(interface, ip_address, port)
# λ©μΈ ν¨μ
if __name__ == "__main__":
basedir = os.path.abspath(os.path.dirname(__file__))
dbfile = os.path.join(basedir, 'db.sqlite')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + dbfile
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
app.config['SECRET_KEY'] = 'wcsfeufhwiquehfdx'
db.init_app(app)
db.app = app
with app.app_context():
db.create_all()
# ν¨ν· μΊ‘μ² μ€λ λ μμ
capture_thread = threading.Thread(target=start_packet_capture)
capture_thread.daemon = True
capture_thread.start()
app.run(host='0.0.0.0', port="5050", debug=True)