-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
1498 lines (1260 loc) · 55.7 KB
/
Copy pathapp.py
File metadata and controls
1498 lines (1260 loc) · 55.7 KB
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sqlite3
import os
import requests
import random
from flask import Flask, render_template, request, redirect, url_for, session, flash, send_from_directory, jsonify
from werkzeug.utils import secure_filename
from werkzeug.security import generate_password_hash, check_password_hash
import json
from datetime import datetime
from chat_engine import chat_engine
app = Flask(__name__)
app.secret_key = 'xssbook_vulnerable_secret_key_123'
app.config['UPLOAD_FOLDER'] = 'uploads'
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024 # 16MB max file size
# Ensure upload directory exists
os.makedirs(app.config['UPLOAD_FOLDER'], exist_ok=True)
# Database initialization
def init_db():
conn = sqlite3.connect('xssbook.db')
cursor = conn.cursor()
# Users table
cursor.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
email TEXT UNIQUE NOT NULL,
password_hash TEXT NOT NULL,
name TEXT NOT NULL,
bio TEXT DEFAULT '',
signature TEXT DEFAULT '',
avatar TEXT DEFAULT '',
cover_photo TEXT DEFAULT '',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
# Posts table (cached posts from APIs)
cursor.execute('''
CREATE TABLE IF NOT EXISTS posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
content TEXT NOT NULL,
image_url TEXT DEFAULT '',
video_url TEXT DEFAULT '',
is_cached BOOLEAN DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')
# Notifications table
cursor.execute('''
CREATE TABLE IF NOT EXISTS notifications (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
type TEXT NOT NULL,
message TEXT NOT NULL,
related_user_id INTEGER,
is_read BOOLEAN DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users (id),
FOREIGN KEY (related_user_id) REFERENCES users (id)
)
''')
# Comments table
cursor.execute('''
CREATE TABLE IF NOT EXISTS comments (
id INTEGER PRIMARY KEY AUTOINCREMENT,
post_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
content TEXT NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (post_id) REFERENCES posts (id),
FOREIGN KEY (user_id) REFERENCES users (id)
)
''')
# Likes table
cursor.execute('''
CREATE TABLE IF NOT EXISTS likes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
post_id INTEGER NOT NULL,
user_id INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (post_id) REFERENCES posts (id),
FOREIGN KEY (user_id) REFERENCES users (id),
UNIQUE(post_id, user_id)
)
''')
# Friend requests table
cursor.execute('''
CREATE TABLE IF NOT EXISTS friend_requests (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sender_id INTEGER NOT NULL,
receiver_id INTEGER NOT NULL,
status TEXT DEFAULT 'pending',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (sender_id) REFERENCES users (id),
FOREIGN KEY (receiver_id) REFERENCES users (id),
UNIQUE(sender_id, receiver_id)
)
''')
# Friends table
cursor.execute('''
CREATE TABLE IF NOT EXISTS friends (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user1_id INTEGER NOT NULL,
user2_id INTEGER NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user1_id) REFERENCES users (id),
FOREIGN KEY (user2_id) REFERENCES users (id),
UNIQUE(user1_id, user2_id)
)
''')
# Messages table
cursor.execute('''
CREATE TABLE IF NOT EXISTS messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sender_id INTEGER NOT NULL,
receiver_id INTEGER NOT NULL,
content TEXT NOT NULL,
is_read BOOLEAN DEFAULT 0,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (sender_id) REFERENCES users (id),
FOREIGN KEY (receiver_id) REFERENCES users (id)
)
''')
conn.commit()
conn.close()
# Sample data population
def populate_sample_data():
conn = sqlite3.connect('xssbook.db')
cursor = conn.cursor()
# Check if data already exists
cursor.execute('SELECT COUNT(*) FROM users')
if cursor.fetchone()[0] > 0:
conn.close()
return
try:
# Fetch dummy users from RandomUser API
response = requests.get('https://randomuser.me/api/?results=20&nat=us,gb,ca,au', timeout=10)
users_data = response.json()['results']
dummy_users = []
# Create dummy users with vulnerabilities
for i, user_data in enumerate(users_data):
username = f"{user_data['login']['username']}{random.randint(1, 999)}"
name = f"{user_data['name']['first']} {user_data['name']['last']}"
email = user_data['email']
avatar = user_data['picture']['large']
cover_photo = f"https://picsum.photos/1200/400?random={i + 100}"
# Add normal, safe bios for dummy users
safe_bios = [
f"Hello! I'm {name}, nice to meet you!",
f"Welcome to my profile! Love connecting with new people.",
f"Tech enthusiast and passionate developer",
f"Love coding and learning new technologies!",
f"Check out my website for my latest projects!",
f"Coffee lover ☕ Always ready for a chat!",
f"Adventure seeker 🌍",
f"Photographer 📸",
f"Foodie 🍕",
f"Music lover 🎵",
f"Travel enthusiast ✈️",
f"Fitness lover 💪",
f"Book worm 📚",
f"Gaming enthusiast 🎮",
f"Nature lover 🌲"
]
bio = random.choice(safe_bios)
# Safe signatures for dummy users
safe_signatures = [
"Moving forward with passion!",
"Always learning something new",
"Best regards and happy coding!",
"Stay connected and keep growing!",
"Happy coding and best wishes!",
"Peace out! ✌️",
"Stay awesome! 🌟",
"Keep learning! 📚",
"Dream big! 💫",
"Spread kindness 💖",
"Live, laugh, love! 😊",
"Carpe Diem! ⭐",
"Be yourself! 🌈",
"Never give up! 💪",
"Enjoy the journey! 🚀"
]
signature = random.choice(safe_signatures)
password_hash = generate_password_hash('password123')
cursor.execute('''
INSERT INTO users (username, email, password_hash, name, bio, signature, avatar, cover_photo)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
''', (username, email, password_hash, name, bio, signature, avatar, cover_photo))
dummy_users.append({
'id': cursor.lastrowid,
'username': username,
'name': name
})
# Create interesting posts with safe content for dummy users
safe_posts = [
{
'content': "Just learned about web security best practices!",
'image_url': "https://picsum.photos/800/600?random=1"
},
{
'content': "Check out this cool website I found today!",
'image_url': ""
},
{
'content': "Beautiful sunset today! Perfect weather for photography.",
'image_url': "https://picsum.photos/800/600?random=2"
},
{
'content': "Love this new framework I'm learning. Very intuitive!",
'image_url': ""
},
{
'content': "Coffee break time! ☕ Perfect way to recharge.",
'image_url': "https://picsum.photos/800/600?random=3"
},
{
'content': "Working on a new project with some exciting features!",
'image_url': "https://picsum.photos/800/600?random=4"
},
{
'content': "Amazing concert last night! The music was absolutely fantastic",
'image_url': "https://picsum.photos/800/600?random=5"
},
{
'content': "Learning React and loving every minute of it! Such a powerful library.",
'image_url': ""
},
{
'content': "Beach day! 🏖️ Perfect weather for swimming and relaxing.",
'image_url': "https://picsum.photos/800/600?random=6"
},
{
'content': "Just finished reading an amazing book! 📚 Highly recommend it to everyone.",
'image_url': "https://picsum.photos/800/600?random=7"
},
{
'content': "Cooking experiment today! Trying out a new recipe I found online.",
'image_url': "https://picsum.photos/800/600?random=8"
},
{
'content': "Mountain hiking adventure! 🏔️ The view from the top was breathtaking.",
'image_url': "https://picsum.photos/800/600?random=9"
},
{
'content': "Pet update: My cat learned a new trick today! So proud of her.",
'image_url': "https://picsum.photos/800/600?random=10"
},
{
'content': "Game night with friends! 🎮 We played until 3 AM and it was worth it.",
'image_url': "https://picsum.photos/800/600?random=11"
},
{
'content': "Travel plans are coming together! Europe here I come!",
'image_url': "https://picsum.photos/800/600?random=12"
},
{
'content': "Art gallery visit today! 🎨 So much inspiration and creativity in one place.",
'image_url': "https://picsum.photos/800/600?random=13"
},
{
'content': "Fitness journey update: Making great progress this month!",
'image_url': ""
},
{
'content': "Garden update! 🌱 My tomatoes are finally ready to harvest.",
'image_url': "https://picsum.photos/800/600?random=14"
},
{
'content': "Movie night: Watched a fantastic film! Highly recommend it.",
'image_url': ""
},
{
'content': "Weekend farmers market! 🥕 Fresh vegetables and friendly vendors.",
'image_url': "https://picsum.photos/800/600?random=15"
}
]
# Create posts for dummy users
for i, post in enumerate(safe_posts):
if i < len(dummy_users):
user = dummy_users[i]
cursor.execute('''
INSERT INTO posts (user_id, content, image_url, is_cached)
VALUES (?, ?, ?, 1)
''', (user['id'], post['content'], post['image_url']))
# Create some friend relationships between dummy users (auto-friendship)
for i in range(len(dummy_users)):
for j in range(i + 1, min(i + 4, len(dummy_users))):
user1_id = dummy_users[i]['id']
user2_id = dummy_users[j]['id']
cursor.execute('''
INSERT OR IGNORE INTO friends (user1_id, user2_id)
VALUES (?, ?)
''', (min(user1_id, user2_id), max(user1_id, user2_id)))
# Add safe comments for dummy users
safe_comments = [
"Great post! Thanks for sharing.",
"Love it! Very inspiring content.",
"Awesome content! Keep it up.",
"Thanks for sharing this! Really helpful.",
"Amazing! Looking forward to more posts like this.",
"Nice work! 👍",
"Incredible post!",
"Keep it up!",
"So inspiring!",
"Well said!"
]
cursor.execute('SELECT id FROM posts')
post_ids = [row[0] for row in cursor.fetchall()]
for post_id in post_ids:
# Add 1-3 comments per post
for _ in range(random.randint(1, 3)):
if dummy_users:
commenter = random.choice(dummy_users)
comment_content = random.choice(safe_comments)
cursor.execute('''
INSERT INTO comments (post_id, user_id, content)
VALUES (?, ?, ?)
''', (post_id, commenter['id'], comment_content))
conn.commit()
print(f"Created {len(dummy_users)} dummy users with posts and friendships")
except Exception as e:
print(f"Error creating dummy data: {e}")
# Create basic dummy users if API fails
basic_users = [
('alice_wonder', 'alice@example.com', 'Alice Wonderland', 'Curious explorer and adventure enthusiast'),
('bob_builder', 'bob@example.com', 'Bob Builder', 'Can we fix it? Yes we can! Construction expert.'),
('charlie_brown', 'charlie@example.com', 'Charlie Brown', 'Good grief! Baseball and comic enthusiast.')
]
for username, email, name, bio in basic_users:
password_hash = generate_password_hash('password123')
avatar = f"https://ui-avatars.com/api/?name={name.replace(' ', '+')}&background=1877f2&color=fff&size=200"
cover_photo = f"https://picsum.photos/1200/400?random={hash(username) % 100}"
cursor.execute('''
INSERT INTO users (username, email, password_hash, name, bio, avatar, cover_photo)
VALUES (?, ?, ?, ?, ?, ?, ?)
''', (username, email, password_hash, name, bio, avatar, cover_photo))
# Helper functions
def get_db_connection():
conn = sqlite3.connect('xssbook.db')
conn.row_factory = sqlite3.Row
return conn
def get_user_by_id(user_id):
conn = get_db_connection()
user = conn.execute('SELECT * FROM users WHERE id = ?', (user_id,)).fetchone()
conn.close()
return user
def get_posts_with_users():
conn = get_db_connection()
posts = conn.execute('''
SELECT p.*, u.name, u.username, u.avatar,
(SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count,
(SELECT COUNT(*) FROM comments WHERE post_id = p.id) as comment_count
FROM posts p
JOIN users u ON p.user_id = u.id
ORDER BY p.created_at DESC
''').fetchall()
conn.close()
return posts
def get_friendship_status(user1_id, user2_id):
"""Get friendship status between two users"""
conn = get_db_connection()
# Check if they are friends
friendship = conn.execute('''
SELECT id FROM friends
WHERE (user1_id = ? AND user2_id = ?) OR (user1_id = ? AND user2_id = ?)
''', (user1_id, user2_id, user2_id, user1_id)).fetchone()
if friendship:
conn.close()
return 'friends'
# Check if there's a pending request from current user to target user
outgoing_request = conn.execute('''
SELECT id FROM friend_requests
WHERE sender_id = ? AND receiver_id = ? AND status = 'pending'
''', (user1_id, user2_id)).fetchone()
if outgoing_request:
conn.close()
return 'request_sent'
# Check if there's a pending request from target user to current user
incoming_request = conn.execute('''
SELECT id FROM friend_requests
WHERE sender_id = ? AND receiver_id = ? AND status = 'pending'
''', (user2_id, user1_id)).fetchone()
if incoming_request:
conn.close()
return 'request_received'
conn.close()
return 'none'
# VULNERABILITY: Flawed sanitization functions
def sanitize_basic(content):
"""VULNERABLE: Only removes <script> tags - easily bypassed"""
if content is None:
return ""
return content.replace('<script>', '').replace('</script>', '')
def sanitize_partial(content):
"""VULNERABLE: Only escapes < and > - misses attributes and other tags"""
if content is None:
return ""
return content.replace('<', '<').replace('>', '>')
def sanitize_blacklist(content):
"""VULNERABLE: Blacklist approach - easily bypassed with case variations"""
if content is None:
return ""
blacklisted = ['<script>', '</script>', '<iframe>', '</iframe>']
result = content
for item in blacklisted:
result = result.replace(item, '')
return result
# Routes
@app.route('/')
def index():
posts = get_posts_with_users()
current_user = None
if 'user_id' in session:
current_user = get_user_by_id(session['user_id'])
return render_template('index.html', posts=posts, current_user=current_user)
@app.route('/register', methods=['GET', 'POST'])
def register():
if request.method == 'POST':
username = request.form['username']
email = request.form['email']
password = request.form['password']
name = request.form['name']
if not all([username, email, password, name]):
flash('All fields are required!')
return render_template('register.html')
conn = get_db_connection()
# Check if user exists
existing_user = conn.execute(
'SELECT id FROM users WHERE username = ? OR email = ?',
(username, email)
).fetchone()
if existing_user:
flash('Username or email already exists!')
conn.close()
return render_template('register.html')
# Create new user
password_hash = generate_password_hash(password)
cursor = conn.execute('''
INSERT INTO users (username, email, password_hash, name)
VALUES (?, ?, ?, ?)
''', (username, email, password_hash, name))
new_user_id = cursor.lastrowid
# Create some welcome friend requests from existing users
existing_users = conn.execute('SELECT id FROM users WHERE id != ? LIMIT 3', (new_user_id,)).fetchall()
for user in existing_users:
try:
conn.execute('''
INSERT INTO friend_requests (sender_id, receiver_id, status)
VALUES (?, ?, 'pending')
''', (user['id'], new_user_id))
except:
pass # Ignore duplicates
conn.commit()
conn.close()
flash('Registration successful! You have some friend requests waiting.')
return redirect(url_for('login'))
return render_template('register.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
conn = get_db_connection()
user = conn.execute(
'SELECT * FROM users WHERE username = ?',
(username,)
).fetchone()
conn.close()
if user and check_password_hash(user['password_hash'], password):
session['user_id'] = user['id']
session['username'] = user['username']
session['name'] = user['name']
# Check if user needs to complete profile setup
if not user['avatar'] and not user['bio']:
return redirect(url_for('setup_profile'))
return redirect(url_for('index'))
else:
flash('Invalid username or password!')
return render_template('login.html')
@app.route('/logout')
def logout():
session.clear()
return redirect(url_for('index'))
@app.route('/profile/<username>')
def profile(username):
conn = get_db_connection()
user = conn.execute('SELECT * FROM users WHERE username = ?', (username,)).fetchone()
if not user:
flash('User not found!')
return redirect(url_for('index'))
posts = conn.execute('''
SELECT p.*, u.name, u.username, u.avatar,
(SELECT COUNT(*) FROM likes WHERE post_id = p.id) as like_count,
(SELECT COUNT(*) FROM comments WHERE post_id = p.id) as comment_count
FROM posts p
JOIN users u ON p.user_id = u.id
WHERE u.id = ?
ORDER BY p.created_at DESC
''', (user['id'],)).fetchall()
current_user = None
is_own_profile = False
friendship_status = 'none'
if 'user_id' in session:
current_user = get_user_by_id(session['user_id'])
is_own_profile = (session['user_id'] == user['id'])
if not is_own_profile:
friendship_status = get_friendship_status(session['user_id'], user['id'])
conn.close()
return render_template('profile.html', user=user, posts=posts, current_user=current_user,
is_own_profile=is_own_profile, friendship_status=friendship_status)
@app.route('/edit_profile', methods=['GET', 'POST'])
def edit_profile():
if 'user_id' not in session:
return redirect(url_for('login'))
if request.method == 'POST':
name = request.form['name']
bio = request.form['bio']
signature = request.form['signature'] # VULNERABLE: No sanitization
avatar_url = request.form.get('avatar_url', '')
# Handle file upload for avatar
if 'avatar_file' in request.files:
file = request.files['avatar_file']
if file and file.filename:
filename = secure_filename(file.filename)
# Add timestamp to avoid filename conflicts
filename = f"{int(datetime.now().timestamp())}_{filename}"
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)
if file.filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
avatar_url = url_for('uploaded_file', filename=filename)
conn = get_db_connection()
conn.execute('''
UPDATE users SET name = ?, bio = ?, signature = ?, avatar = ?
WHERE id = ?
''', (name, bio, signature, avatar_url, session['user_id']))
conn.commit()
conn.close()
session['name'] = name
flash('Profile updated successfully!')
return redirect(url_for('profile', username=session['username']))
user = get_user_by_id(session['user_id'])
return render_template('edit_profile.html', user=user)
@app.route('/setup_profile')
def setup_profile():
if 'user_id' not in session:
return redirect(url_for('login'))
user = get_user_by_id(session['user_id'])
# Check if user needs profile setup (no avatar or bio)
if user['avatar'] or user['bio']:
return redirect(url_for('profile', username=user['username']))
return render_template('setup_profile.html', user=user)
@app.route('/complete_profile', methods=['POST'])
def complete_profile():
if 'user_id' not in session:
return redirect(url_for('login'))
bio = request.form.get('bio', '')
avatar_url = request.form.get('avatar_url', '')
# Handle file upload for avatar
if 'avatar_file' in request.files:
file = request.files['avatar_file']
if file and file.filename:
filename = secure_filename(file.filename)
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)
if file.filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
avatar_url = url_for('uploaded_file', filename=filename)
# If no custom avatar, get a random one
if not avatar_url:
try:
random_user_response = requests.get('https://randomuser.me/api/', timeout=5)
random_user_data = random_user_response.json()
avatar_url = random_user_data['results'][0]['picture']['large']
except:
avatar_url = f"https://via.placeholder.com/150x150/1877f2/ffffff?text={session['name'][0]}"
conn = get_db_connection()
conn.execute('''
UPDATE users SET bio = ?, avatar = ?
WHERE id = ?
''', (bio, avatar_url, session['user_id']))
conn.commit()
conn.close()
flash('Profile setup completed!')
return redirect(url_for('profile', username=session['username']))
@app.route('/create_post', methods=['POST'])
def create_post():
if 'user_id' not in session:
return redirect(url_for('login'))
content = request.form['content']
image_url = request.form.get('image_url', '')
video_url = request.form.get('video_url', '')
# Handle file upload
if 'file' in request.files:
file = request.files['file']
if file and file.filename:
filename = secure_filename(file.filename) # Secure filename but content is still vulnerable
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file.save(file_path)
if file.filename.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')):
image_url = url_for('uploaded_file', filename=filename)
elif file.filename.lower().endswith(('.mp4', '.avi', '.mov')):
video_url = url_for('uploaded_file', filename=filename)
# VULNERABLE: Minimal sanitization on content
sanitized_content = sanitize_basic(content)
conn = get_db_connection()
conn.execute('''
INSERT INTO posts (user_id, content, image_url, video_url)
VALUES (?, ?, ?, ?)
''', (session['user_id'], sanitized_content, image_url, video_url))
conn.commit()
conn.close()
return redirect(url_for('index'))
@app.route('/add_comment', methods=['POST'])
def add_comment():
if 'user_id' not in session:
return redirect(url_for('login'))
post_id = request.form['post_id']
content = request.form['content']
# VULNERABLE: No sanitization on comments
conn = get_db_connection()
conn.execute('''
INSERT INTO comments (post_id, user_id, content)
VALUES (?, ?, ?)
''', (post_id, session['user_id'], content))
conn.commit()
conn.close()
return redirect(url_for('index'))
@app.route('/search')
def search():
query = request.args.get('q', '')
results = []
if query:
conn = get_db_connection()
# VULNERABLE: Direct query injection into template without sanitization
results = conn.execute('''
SELECT p.*, u.name, u.username, u.avatar
FROM posts p
JOIN users u ON p.user_id = u.id
WHERE p.content LIKE ? OR u.name LIKE ?
ORDER BY p.created_at DESC
''', (f'%{query}%', f'%{query}%')).fetchall()
conn.close()
current_user = None
if 'user_id' in session:
current_user = get_user_by_id(session['user_id'])
return render_template('search.html', query=query, results=results, current_user=current_user)
@app.route('/personalize')
def personalize():
"""VULNERABLE: DOM-based XSS through URL parameter"""
current_user = None
if 'user_id' in session:
current_user = get_user_by_id(session['user_id'])
return render_template('personalize.html', current_user=current_user)
@app.route('/get_comments/<int:post_id>')
def get_comments(post_id):
conn = get_db_connection()
comments = conn.execute('''
SELECT c.*, u.name, u.username, u.avatar
FROM comments c
JOIN users u ON c.user_id = u.id
WHERE c.post_id = ?
ORDER BY c.created_at ASC
''', (post_id,)).fetchall()
conn.close()
return jsonify([{
'id': comment['id'],
'content': comment['content'], # VULNERABLE: Raw content returned
'name': comment['name'],
'username': comment['username'],
'avatar': comment['avatar'],
'created_at': comment['created_at']
} for comment in comments])
@app.route('/like_post', methods=['POST'])
def like_post():
if 'user_id' not in session:
return jsonify({'error': 'Not logged in'}), 401
post_id = request.json.get('post_id')
conn = get_db_connection()
# Check if already liked
existing_like = conn.execute(
'SELECT id FROM likes WHERE post_id = ? AND user_id = ?',
(post_id, session['user_id'])
).fetchone()
if existing_like:
# Unlike
conn.execute('DELETE FROM likes WHERE post_id = ? AND user_id = ?',
(post_id, session['user_id']))
liked = False
else:
# Like
conn.execute('INSERT INTO likes (post_id, user_id) VALUES (?, ?)',
(post_id, session['user_id']))
liked = True
# Get updated like count
like_count = conn.execute(
'SELECT COUNT(*) FROM likes WHERE post_id = ?',
(post_id,)
).fetchone()[0]
conn.commit()
conn.close()
return jsonify({'liked': liked, 'like_count': like_count})
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory(app.config['UPLOAD_FOLDER'], filename)
@app.route('/send_friend_request', methods=['POST'])
def send_friend_request():
if 'user_id' not in session:
return jsonify({'error': 'Not logged in'}), 401
receiver_id = request.json.get('receiver_id')
sender_id = session['user_id']
if sender_id == receiver_id:
return jsonify({'error': 'Cannot send friend request to yourself'}), 400
conn = get_db_connection()
# Check current friendship status
friendship_status = get_friendship_status(sender_id, receiver_id)
if friendship_status == 'friends':
conn.close()
return jsonify({'error': 'Already friends'}), 400
if friendship_status == 'request_sent':
conn.close()
return jsonify({'error': 'Friend request already sent'}), 400
if friendship_status == 'request_received':
conn.close()
return jsonify({'error': 'This user has already sent you a friend request. Check your friend requests.'}), 400
# Get receiver info to check if they're a dummy user
receiver = conn.execute('SELECT username, name FROM users WHERE id = ?', (receiver_id,)).fetchone()
sender = conn.execute('SELECT username, name FROM users WHERE id = ?', (sender_id,)).fetchone()
if not receiver:
conn.close()
return jsonify({'error': 'User not found'}), 404
# Create friend request
cursor = conn.cursor()
cursor.execute('''
INSERT INTO friend_requests (sender_id, receiver_id, status)
VALUES (?, ?, 'pending')
''', (sender_id, receiver_id))
request_id = cursor.lastrowid
# Check if receiver is a dummy user (check password)
receiver_data = conn.execute('SELECT password_hash FROM users WHERE id = ?', (receiver_id,)).fetchone()
is_dummy = False
if receiver_data:
is_dummy = check_password_hash(receiver_data['password_hash'], 'password123')
if is_dummy:
# Auto-accept from dummy users
cursor.execute('''
UPDATE friend_requests SET status = 'accepted' WHERE id = ?
''', (request_id,))
# Add to friends table
cursor.execute('''
INSERT INTO friends (user1_id, user2_id)
VALUES (?, ?)
''', (min(sender_id, receiver_id), max(sender_id, receiver_id)))
# Create notification for sender
cursor.execute('''
INSERT INTO notifications (user_id, type, message, related_user_id)
VALUES (?, ?, ?, ?)
''', (sender_id, 'friend_accepted', f'{receiver["name"]} accepted your friend request!', receiver_id))
conn.commit()
conn.close()
return jsonify({'success': True, 'message': 'Friend request automatically accepted!', 'auto_accepted': True})
else:
# Create notification for receiver
cursor.execute('''
INSERT INTO notifications (user_id, type, message, related_user_id)
VALUES (?, ?, ?, ?)
''', (receiver_id, 'friend_request', f'{sender["name"]} sent you a friend request!', sender_id))
conn.commit()
conn.close()
return jsonify({'success': True, 'message': 'Friend request sent'})
@app.route('/respond_friend_request', methods=['POST'])
def respond_friend_request():
if 'user_id' not in session:
return jsonify({'error': 'Not logged in'}), 401
sender_id = request.json.get('sender_id')
action = request.json.get('action') # 'accept' or 'decline'
receiver_id = session['user_id']
if action not in ['accept', 'decline']:
return jsonify({'error': 'Invalid action'}), 400
conn = get_db_connection()
# Check if friend request exists
friend_request = conn.execute('''
SELECT id FROM friend_requests
WHERE sender_id = ? AND receiver_id = ? AND status = 'pending'
''', (sender_id, receiver_id)).fetchone()
if not friend_request:
conn.close()
return jsonify({'error': 'Friend request not found'}), 404
cursor = conn.cursor()
if action == 'accept':
# Update request status
cursor.execute('''
UPDATE friend_requests SET status = 'accepted' WHERE id = ?
''', (friend_request['id'],))
# Add to friends table
cursor.execute('''
INSERT INTO friends (user1_id, user2_id)
VALUES (?, ?)
''', (min(sender_id, receiver_id), max(sender_id, receiver_id)))
# Get names for notifications
sender = conn.execute('SELECT name FROM users WHERE id = ?', (sender_id,)).fetchone()
receiver = conn.execute('SELECT name FROM users WHERE id = ?', (receiver_id,)).fetchone()
# Create notification for sender
cursor.execute('''
INSERT INTO notifications (user_id, type, message, related_user_id)
VALUES (?, ?, ?, ?)
''', (sender_id, 'friend_accepted', f'{receiver["name"]} accepted your friend request!', receiver_id))
message = 'Friend request accepted!'
else:
# Update request status to declined
cursor.execute('''
UPDATE friend_requests SET status = 'declined' WHERE id = ?
''', (friend_request['id'],))
message = 'Friend request declined'
conn.commit()
conn.close()
return jsonify({'success': True, 'message': message})
@app.route('/get_friend_requests')
def get_friend_requests():
if 'user_id' not in session:
return jsonify({'error': 'Not logged in'}), 401
conn = get_db_connection()
# Get pending friend requests
requests_data = conn.execute('''
SELECT fr.id, fr.sender_id, u.name, u.username, u.avatar, fr.created_at
FROM friend_requests fr
JOIN users u ON fr.sender_id = u.id
WHERE fr.receiver_id = ? AND fr.status = 'pending'
ORDER BY fr.created_at DESC
''', (session['user_id'],)).fetchall()
conn.close()
return jsonify([{
'id': req['id'],
'sender_id': req['sender_id'],
'name': req['name'],
'username': req['username'],
'avatar': req['avatar'],
'created_at': req['created_at']
} for req in requests_data])
@app.route('/get_friends')
def get_friends():
if 'user_id' not in session:
return jsonify({'error': 'Not logged in'}), 401
conn = get_db_connection()