I am doing a CTF challenge, but my question is not about how to solve it, rather the syntax. The challenge is to read the secret key in Flask server's configuration. It is stored in the app.secret_key
variable and I want to alert it on the screen by XSS.
Question: how can I access that variable in Flask code from javascript and put it in <script>alert(variable)</script>
snippet?
I tried <script type="text/javascript">let v="{{=app.secret_key}}"; alert(v); </script>
<script type="text/javascript">let v="{{=app.secret_key}}"; alert(v); </script>
<script type="text/javascript">let v="{{=app.secret_key}}"; alert(v); </script>
but it gave Internal Server Error.
First, it must be said, in general you should should absolutely not do this . app.secret_key
should never, ever be exposed publicly and should be regarded as a closely guarded secret. Hence the name. But since you're doing this for presumably good reasons involving your game, let's continue.
Probably the simplest way to expose Python variables to JavaScript is directly in the template by dumping JSON. Consider this code:
import json
from flask import Flask, render_template
app = Flask(__name__)
app.secret_key = 'THIS IS SECRET'
@app.route('/')
def hello_world():
server_vars = {
'secretKey': app.secret_key,
'favoriteFoods': ['Eggs', 'Spam']
}
return render_template(
'hello.html',
server_vars=json.dumps(server_vars)
)
if __name__ == '__main__':
app.run()
We're rendering the template hello.html
and sending it a template variable, server_vars
, which is a rendered JSON string of the same server-side variable, which is a dictionary. This enables us to send any number arbitrary JSON-compatible variables to JavaScript. See hello.html
:
<!doctype html>
<html lang="en">
<head>
<title>Document</title>
</head>
<body>
<script>
window.serverVars = {{ server_vars | safe }};
alert(window.serverVars.secretKey)
console.log('btw, my favorite foods are', window.serverVars.favoriteFoods)
</script>
</body>
</html>
Notice that in addition to sending secretKey, we actually sent a Python list, which was converted into an array in JavaScript.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.