from pygments.lexers import guess_lexer, guess_lexer_for_filename from pygments.formatters import HtmlFormatter from pygments import highlight from flask import Flask, Response, request, abort, redirect from random import SystemRandom from functools import wraps import string import os.path app = Flask(__name__) app.config.from_pyfile(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'app.cfg')) rng = SystemRandom() def check_auth(username, password): # Side channel attack on string comparison! return username == app.config['USERNAME'] and password == app.config['PASSWORD'] def requires_auth(f): @wraps(f) def decorated(*args, **kwargs): auth = request.authorization if not auth or not check_auth(auth.username, auth.password): return Response('Wrong username/password', 401, {'WWW-Authenticate': 'Basic realm="Aleph Paste"'}) return f(*args, **kwargs) return decorated @app.route('/') def landing(): return redirect('https://git.zx2c4.com/alephpaste/about/', code=302) @app.route('/', methods=['POST']) @requires_auth def new_paste(): if 'paste' not in request.files: abort(400) while True: paste = ''.join(rng.choice(string.ascii_letters + string.digits) for _ in range(8)) file_name = os.path.join(app.config['FILES_PATH'], paste + '.txt') if not os.path.exists(file_name): break f = request.files['paste'] f.save(file_name) f.close() return app.config['URI_BASE'] + '/' + paste + '\n' @app.route('/', methods=['DELETE']) @requires_auth def delete_paste(paste): try: os.unlink(os.path.join(app.config['FILES_PATH'], paste + '.txt')) except: abort(404) return '' @app.route('/') def send_paste(paste): return Response(mimetype='text/plain', headers={'X-Accel-Redirect': os.path.join(app.config['FILES_ACCEL'], paste + '.txt')}) @app.route('//') def send_highlighted_paste_guess(paste): return send_highlighted_paste(paste, None) @app.route('//') def send_highlighted_paste(paste, ftype): try: f = open(os.path.join(app.config['FILES_PATH'], paste + '.txt'), 'r') text = f.read() f.close() if ftype is None or len(ftype) == 0: lexer = guess_lexer(text) else: lexer = guess_lexer_for_filename(paste + '.' + ftype, text) formatter = HtmlFormatter(style='pastie', full=True, title='{0} - Aleph Paste'.format(paste), linenos='table', anchorlinenos=True, lineanchors="line") return highlight(text, lexer, formatter) except: return send_paste(paste)