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
  | 
from flask import Flask, request, jsonify, render_template_string
import jwt
import asyncio
import yaml
import os
app = Flask(__name__)
JWT_SECRET = "@o70xO$0%#qR9#m0"
JWT_ALGO = "HS256"
FORBIDDEN = ['__', 'import', 'os', 'eval', 'exec', 'open', 'read', 'write', 
             'system', 'subprocess', 'communicate', 'Popen', 'decode', "\\"]
HTML_PAGE = '''
<!DOCTYPE html>
<html>
<head>
    <title>Vault</title>
    <style>
        body { font-family: "Segoe UI", sans-serif; background-color: #f4f4f4; padding: 40px; text-align: center; }
        #user-info { margin-bottom: 40px; font-weight: bold; font-size: 18px; color: #333; }
        #sandbox-container { margin-top: 30px; }
        select, input, button { font-size: 16px; margin: 10px; padding: 8px; border-radius: 6px; border: 1px solid #ccc; }
        #result { background: #222; color: #0f0; padding: 15px; width: 80%; margin: 20px auto; white-space: pre-wrap; border-radius: 8px; text-align: left; }
        button { background-color: #4CAF50; color: white; border: none; cursor: pointer; }
        button:hover { background-color: #45a049; }
        input[type="file"] { display: block; margin: 10px auto; }
    </style>
</head>
<body>
    <div id="user-info">Loading user info...</div>
    <div id="sandbox-container">
        <select id="mode">
            <option value="yaml" selected>YAML</option>
            <option value="python">Python</option>
        </select>
        <br>
        <input type="file" id="codefile">
        <br>
        <button onclick="runCode()">▶ Execute from File</button>
        <pre id="result">Waiting for output...</pre>
    </div>
    <script>
        let token = "";
        fetch("/auth")
            .then(res => res.json())
            .then(data => {
                token = data.token;
                const payload = JSON.parse(atob(token.split('.')[1]));
                document.getElementById("user-info").innerHTML =
                    "<span style='color:#444'>👤 " + payload.username + "</span> | " +
                    "<span style='color:#4CAF50'>Role: " + payload.role + "</span>";
            });
        function runCode() {
            const fileInput = document.getElementById('codefile');
            const mode = document.getElementById("mode").value;
            if (fileInput.files.length === 0) {
                document.getElementById("result").textContent = '{"error": "Please select a file to upload."}';
                return;
            }
            const file = fileInput.files[0];
            const formData = new FormData();
            formData.append('codefile', file);
            formData.append('mode', mode);
            fetch("/sandbox", {
                method: "POST",
                headers: {
                    "Authorization": "Bearer " + token
                },
                body: formData
            })
            .then(res => res.json())
            .then(data => {
                document.getElementById("result").textContent = JSON.stringify(data, null, 2);
            });
        }
    </script>
</body>
</html>
'''
@app.route('/')
def index():
    return render_template_string(HTML_PAGE)
@app.route('/auth')
def auth():
    token = jwt.encode({'username': 'guest', 'role': 'user'}, JWT_SECRET, algorithm=JWT_ALGO)
    if isinstance(token, bytes):
        token = token.decode()
    return jsonify({'token': token})
def is_code_safe(code: str) -> bool:
    return not any(word in code for word in FORBIDDEN)
@app.route('/sandbox', methods=['POST'])
def sandbox():
    auth_header = request.headers.get('Authorization', '')
    if not auth_header.startswith('Bearer '):
        return jsonify({'error': 'Invalid token format'}), 401
    
    token = auth_header.replace('Bearer ', '')
    if 'codefile' not in request.files:
        return jsonify({'error': 'No file part in the request'}), 400
    file = request.files['codefile']
    if file.filename == '':
        return jsonify({'error': 'No file selected'}), 400
    mode = request.form.get('mode', 'python')
    try:
        code = file.read().decode('utf-8')
    except Exception as e:
        return jsonify({'error': f'Could not read or decode file: {e}'}), 400
    if not all([token, code, mode]):
        return jsonify({'error': 'Token, code, or mode is empty'}), 400
    try:
        payload = jwt.decode(token, JWT_SECRET, algorithms=[JWT_ALGO])
    except Exception as e:
        partial_key = JWT_SECRET[:-2]
        return {
            'error': 'JWT Decode Failed. Key Hint',
            'hint': f'Key starts with "{partial_key}**". The 2 missing chars are alphanumeric (letters and numbers).'
        }, 500
    if payload.get('role') != 'admin':
        return {'error': 'Permission Denied: admin only'}, 403
    if mode == 'python':
        if not is_code_safe(code):
            return {'error': 'forbidden keyword detected'}, 400
        try:
            scope = {}
            exec(code, scope)
            result = scope['run']()
            return {'result': result}
        except Exception as e:
            return {'error': str(e)}, 500
    elif mode == 'yaml':
        try:
            obj = yaml.load(code, Loader=yaml.UnsafeLoader)
            return {'result': str(obj)}
        except Exception as e:
            return {'error': str(e)}, 500
    return {'error': 'invalid mode'}, 400
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=80)
  |