-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp(1).py
408 lines (330 loc) ยท 15.8 KB
/
app(1).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
400
401
402
403
404
405
406
407
408
import os
import pymysql
import pymysql.cursors
import logging
import random
import time
import threading
import subprocess
import pandas as pd
from joblib import load
from flask import Flask, request, session, redirect, render_template, flash, jsonify, abort
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from collections import deque
import pyshark
import numpy as np
from Database.models import db, Fcuser, UserCity
from Database.MySQL import save_login_info_mysql, save_location_mysql, user_data, ip_data, validation_ip_data, attack_data
from Database.sqlite import save_login_info_sqlite, save_clicked_city
from forms import RegisterForm, LoginForm
from validation import get_user_location, calculate_distance, find_closest_city
from map import executor, cities, get_weather
# Flask ์ ํ๋ฆฌ์ผ์ด์
์์ฑ
app = Flask(__name__)
# Flask ์ ํ๋ฆฌ์ผ์ด์
์ ์คํํ๋ ํ์ผ์ ๊ฒฝ๋ก
current_directory = os.path.abspath(os.path.dirname(__file__))
# ๋ก๊น
์ค์
logging.basicConfig(filename='app.log', level=logging.INFO)
# ๋คํธ์ํฌ ์ธํฐํ์ด์ค ์ ํ
interface = 'en0'
# ์บก์ฒํ IP ์ฃผ์ ์ค์
ip_address = '172.30.1.56'
port = 5050
# ์บก์ฒํ ํจํท ํํฐ ์ค์
capture_filter = f'ip src {ip_address}'
# ํ ๋ฒ์ ์บก์ฒํ ํจํท ์ ์ค์
capture_count = 500 # ์์ ๊ฐ, ํ์ํ ๋งํผ ์ค์
# ์ฌ์ ํ์ต๋ ๋ชจ๋ธ๊ณผ ์ค์ผ์ผ๋ฌ ๋ก๋
model = load('/Users/chonakyung/modelmodel/ddos_detection_model.joblib')
scaler = load('/Users/chonakyung/Desktop/capstone/packet/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 update_validation_ips():
# global validation_ips
# while True:
# validation_ips = validation_ip_data()
# time.sleep(10)
# update_thread = threading.Thread(target=update_validation_ips)
# update_thread.daemon = True
# update_thread.start()
# ๋๋์ค ๊ณต๊ฒฉ ๊ฐ์ง
def capture_packets():
packet_info_list = []
capture = pyshark.LiveCapture(interface=interface, bpf_filter=capture_filter)
iat_times = deque(maxlen=capture_count)
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 {}
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_info_list.append(packet_info)
if len(packet_info_list) >= capture_count:
break
# with open('/Users/chonakyung/modelmodel/packet_info.json', 'w') as json_file:
# json.dump(packet_info_list, json_file, indent=4)
# print(f"{capture_count}๊ฐ์ ํจํท ์บก์ฒ ๋ฐ ์ ์ฅ์ด ์๋ฃ๋์์ต๋๋ค.")
# print(f"JSON ํ์ผ์ ์ ์ฅ๋ ํจํท ๊ฐ์: {len(packet_info_list)}")
# return packet_info_list
try:
with open('/Users/chonakyung/modelmodel/packet_info.json', 'w') as json_file:
json.dump(packet_info_list, json_file, indent=4)
print(f"{capture_count}๊ฐ์ ํจํท ์บก์ฒ ๋ฐ ์ ์ฅ์ด ์๋ฃ๋์์ต๋๋ค.")
print(f"JSON ํ์ผ์ ์ ์ฅ๋ ํจํท ๊ฐ์: {len(packet_info_list)}")
except Exception as e:
print(f"JSON ํ์ผ ์ ์ฅ ์ค ์ค๋ฅ ๋ฐ์: {e}")
return packet_info_list
def predict_attack(packet_info_list):
protocol_map = {'TCP': 6, 'UDP': 17}
for packet_info in packet_info_list:
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'
]
df = pd.DataFrame(packet_info_list, columns=features)
sample_data = df.reindex(columns=scaler.feature_names_in_, fill_value=0)
sample_data_scaled = scaler.transform(sample_data)
prediction = model.predict(sample_data_scaled)
print("Prediction:", prediction)
return prediction
def main():
while True:
packet_info_list = capture_packets()
if packet_info_list:
predict_attack(packet_info_list)
time.sleep(5) # 5์ด๋ง๋ค ํจํท ์บก์ฒ ๋ฐ ์์ธก ์ํ
# def attack_detection(packet_info_list):
# protocol_map = {'TCP': 6, 'UDP': 17}
# for packet_info in packet_info_list:
# 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'
# ]
# df = pd.DataFrame(packet_info_list, columns=features)
# sample_data = df.reindex(columns=scaler.feature_names_in_, fill_value=0)
# sample_data_scaled = scaler.transform(sample_data)
# prediction = model.predict(sample_data_scaled)
# print("Prediction:", prediction)
# return prediction
# def is_attack_detected():
# packet_info_list = capture_packet()
# if not packet_info_list:
# return []
# predictions = attack_detection(packet_info_list)
# return predictions
# def periodic_prediction():
# while True:
# predictions = is_attack_detected()
# if predictions and all(pred == 1 for pred in predictions):
# logging.warning("DDoS attack detected!")
# else:
# logging.info("No DDoS attack detected.")
# time.sleep(10) # ์ฃผ๊ธฐ์ ์ผ๋ก ์์ธก ์ํ (10์ด๋ง๋ค)
# predict_thread = threading.Thread(target=periodic_prediction)
# predict_thread.daemon = True
# predict_thread.start()
# ๋ฉ์ธ ํ๋ฉด
@app.route('/')
def hello():
# ์ธ์
์ ์ ์ฅ๋ ์ฌ์ฉ์ ID
userid = session.get('userid', None)
# ํด๋ผ์ด์ธํธ IP ์ฃผ์ ๊ฐ์ ธ์ค๊ธฐ
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
# SQLite์ ์ ์ฅ
save_login_info_sqlite(userid, ip_address)
# MySQL์ ์ ์ฅ
save_login_info_mysql(userid, ip_address)
# ๋ง์ฝ ๊ด๋ฆฌ์๋ก ๋ก๊ทธ์ธํ ๊ฒฝ์ฐ์๋ ์ธ์
์ admin์ด๋ผ๋ ํค๋ฅผ ์ถ๊ฐ
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('/admin', methods=['GET', 'POST'])
def admin():
# ์ธ์
์ ์ ์ฅ๋ ์ฌ์ฉ์ ID
userid = session.get('userid', None)
# ๋๋์ค ๊ณต๊ฒฉ์ ๊ฐ์งํ๋ฉด ๊ฒฝ๊ณ ๋ฉ์์ง๋ฅผ ํ๋ ์ ๋ฉ์์ง๋ก ์ ์ฅ
if is_attack_detected():
flash('๋๋์ค ๊ณต๊ฒฉ์ด ๊ฐ์ง๋์์ต๋๋ค. ์๋น์ค ์ด์ฉ์ด ์ ํ๋ ์ ์์ต๋๋ค.', 'danger')
ddos = True
else:
ddos = False
if 'admin' in session:
user_table = user_data()
ip_table = ip_data()
else:
flash('๊ด๋ฆฌ์๋ง ์ ๊ทผํ ์ ์๋ ํ์ด์ง์
๋๋ค.', 'danger')
return redirect('/')
return render_template('admin.html', userid=userid, ddos=ddos, user_data=user_table, ip_data=ip_table)
# ์ง๋
@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():
# ํด๋ผ์ด์ธํธ์ IP ์ฃผ์ ๊ฐ์ ธ์ค๊ธฐ
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()
# UserCity ํ
์ด๋ธ์์ ๋ชจ๋ ๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ
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)
# GET ์์ฒญ์ ๋ํ ์๋ต
return render_template('rsp_game.html', userid=userid)
# ๋ฉ์ธ ํจ์
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()
# # ๋ฐฑ๊ทธ๋ผ์ด๋์์ packet_test.py ์คํ
# subprocess.Popen(["python", "/Users/chonakyung/modelmodel/packet_test.py"])
# ๋ฐฑ๊ทธ๋ผ์ด๋์์ ํจํท ์บก์ฒ ๋ฐ ์์ธก ์ํ
packet_capture_thread = threading.Thread(target=main)
packet_capture_thread.daemon = True
packet_capture_thread.start()
app.run(host='0.0.0.0', port="5050", debug=True)