Sweetening

Untitled

Oct 17th, 2024
26
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.61 KB | None | 0 0
  1. from flask import Flask, request, render_template, redirect, url_for, flash, g, session, send_file
  2. import io
  3. import base64
  4. from flask_login import LoginManager, UserMixin, login_user, login_required, logout_user, current_user
  5. from functools import wraps
  6. import sqlite3
  7. import pickle
  8. import os
  9. import uuid
  10. from werkzeug.utils import secure_filename
  11. from datetime import datetime, timedelta
  12.  
  13. app = Flask(__name__)
  14. app.secret_key = os.urandom(24)
  15. DATABASE = '/tmp/database.db'
  16.  
  17. login_manager = LoginManager()
  18. login_manager.init_app(app)
  19.  
  20. class User(UserMixin):
  21. def __init__(self, id):
  22. self.id = id
  23.  
  24. def get_db():
  25. db = getattr(g, '_database', None)
  26. if db is None:
  27. db = g._database = sqlite3.connect(DATABASE)
  28. return db
  29.  
  30. @app.teardown_appcontext
  31. def close_connection(exception):
  32. db = getattr(g, '_database', None)
  33. if db is not None:
  34. db.close()
  35.  
  36. @login_manager.user_loader
  37. def user_loader(user_id):
  38. conn = get_db()
  39. c = conn.cursor()
  40. c.execute("SELECT username FROM users WHERE username=?", (user_id,))
  41. user_data = c.fetchone()
  42. if user_data is None:
  43. return None
  44. return User(user_data[0])
  45.  
  46. @app.before_request
  47. def before_request():
  48. g.user = current_user
  49. if g.user.is_authenticated:
  50. conn = get_db()
  51. c = conn.cursor()
  52. c.execute("SELECT timestamp FROM activesessions WHERE username=?", (g.user.id,))
  53. active_session = c.fetchone()
  54. if active_session:
  55. timestamp = active_session[0]
  56. if datetime.now() - datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S.%f") > timedelta(minutes=5):
  57. flash('Your session has expired')
  58. logout_user()
  59. return redirect(url_for('home'))
  60. else:
  61. c.execute("UPDATE activesessions SET timestamp=? WHERE username=?",
  62. (datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f'), g.user.id))
  63. conn.commit()
  64.  
  65. @app.route('/')
  66. def home():
  67. return render_template('login.html')
  68.  
  69. @app.route('/files')
  70. @login_required
  71. def files():
  72. conn = get_db()
  73. c = conn.cursor()
  74. c.execute("SELECT filename FROM files")
  75. file_list = c.fetchall()
  76. return render_template('files.html', files=file_list)
  77.  
  78. def DBClean(string):
  79. return ''.join(c for c in string if c.isalnum() or c in ['_', '-'])
  80.  
  81. @app.route('/login', methods=['POST'])
  82. def login():
  83. username = DBClean(request.form['username'])
  84. password = DBClean(request.form['password'])
  85.  
  86. conn = get_db()
  87. c = conn.cursor()
  88. c.execute("SELECT * FROM users WHERE username=? AND password=?", (username, password))
  89. user = c.fetchone()
  90.  
  91. if user:
  92. session_id = str(uuid.uuid4())
  93. c.execute("INSERT INTO activesessions (sessionid, username, timestamp) VALUES (?, ?, ?)",
  94. (session_id, username, datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')))
  95. conn.commit()
  96.  
  97. session['username'] = username
  98. session['session_id'] = session_id
  99. login_user(User(username))
  100. return redirect(url_for('files'))
  101. else:
  102. flash('Username or password is incorrect')
  103. return redirect(url_for('home'))
  104.  
  105. @app.route('/logout', methods=['GET'])
  106. def logout():
  107. if 'session_id' in session:
  108. conn = get_db()
  109. c = conn.cursor()
  110. c.execute("DELETE FROM activesessions WHERE sessionid=?", (session['session_id'],))
  111. conn.commit()
  112. session.pop('username', None)
  113. session.pop('session_id', None)
  114. logout_user()
  115. return redirect(url_for('home'))
  116.  
  117. @app.route('/download/<filename>/<sessionid>', methods=['GET'])
  118. def download_file(filename, sessionid):
  119. conn = get_db()
  120. c = conn.cursor()
  121. c.execute("SELECT * FROM activesessions WHERE sessionid=?", (sessionid,))
  122.  
  123. active_session = c.fetchone()
  124. if active_session is None:
  125. flash('No active session found')
  126. return redirect(url_for('home'))
  127.  
  128. c.execute("SELECT data FROM files WHERE filename=?", (filename,))
  129. file_data = c.fetchone()
  130. if file_data is None:
  131. flash('File not found')
  132. return redirect(url_for('files'))
  133.  
  134. file_blob = pickle.loads(base64.b64decode(file_data[0]))
  135. try:
  136. return send_file(io.BytesIO(file_blob), download_name=filename, as_attachment=True)
  137. except TypeError:
  138. flash("ERROR: Failed to retrieve file. Are you trying to hack us?!?")
  139. return redirect(url_for('files'))
  140.  
  141. @app.route('/upload', methods=['POST'])
  142. @login_required
  143. def upload_file():
  144. flash('Sorry, the administrator has temporarily disabled file upload capability.')
  145. return redirect(url_for('files'))
  146.  
  147. def init_db():
  148. with app.app_context():
  149. db = get_db()
  150. c = db.cursor()
  151.  
  152. c.execute("CREATE TABLE IF NOT EXISTS users (username text PRIMARY KEY, password text)")
  153. c.execute("CREATE TABLE IF NOT EXISTS activesessions (sessionid text, username text, timestamp text)")
  154. c.execute("CREATE TABLE IF NOT EXISTS files (filename text PRIMARY KEY, data blob, sessionid text)")
  155.  
  156. c.execute("INSERT OR IGNORE INTO files VALUES ('flag.txt', ?, NULL)",
  157. (base64.b64encode(pickle.dumps(b'lol just kidding this isnt really where the flag is')).decode('utf-8'),))
  158. c.execute("INSERT OR IGNORE INTO files VALUES ('NahamCon-2024-Speakers.xlsx', ?, NULL)",
  159. (base64.b64encode(pickle.dumps(b'lol gottem')).decode('utf-8'),))
  160. db.commit()
  161.  
  162. if __name__ == '__main__':
  163. with app.app_context():
  164. init_db()
  165. app.run(debug=False, host="0.0.0.0")
  166.  
Add Comment
Please, Sign In to add comment