-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclasswork8.js
More file actions
177 lines (152 loc) · 5.84 KB
/
Copy pathclasswork8.js
File metadata and controls
177 lines (152 loc) · 5.84 KB
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
const express = require('express');
const router = express.Router();
const jwt = require('jsonwebtoken');
const crypto = require('crypto');
const { SECRET_KEY, SESSION_ID } = require('./config');
const users = {
student: { password: 'pass123', role: 'student' },
admin: { password: 'admin123', role: 'admin' }
};
// Login route for this challenge
router.post('/login', (req, res) => {
const { username, password } = req.body;
const user = users[username];
if (!user || user.password !== password) {
return res.status(401).json({
error: 'Invalid credentials',
hint: 'Try username: student/admin, password: pass123/admin123'
});
}
const challenge = crypto.randomBytes(8).toString('hex');
const token = jwt.sign(
{ user: username, role: user.role, challenge, iat: Math.floor(Date.now() / 1000) },
SECRET_KEY,
{ expiresIn: '5m' }
);
res.cookie('sessionid', SESSION_ID, { httpOnly: true });
res.json({
token,
challenge,
message: 'Use this token and challenge for the DELETE endpoint',
instructions: {
step1: 'Compute MD5 hash of the challenge value',
step2: 'Create JSON payload with challenge and response',
step3: 'Generate HMAC-SHA256 signature of the payload',
step4: 'Send DELETE request with all headers and signature'
}
});
});
// Protected DELETE route
router.delete('/', (req, res) => {
const userAgent = req.headers['user-agent'];
const contentType = req.headers['content-type'];
const customHeader = req.headers['x-custom-header'];
const cookie = req.cookies.sessionid;
const authHeader = req.headers['authorization'];
const signature = req.headers['x-payload-signature'];
if (userAgent && userAgent.toLowerCase().includes('mozilla')) {
return res.status(403).json({ error: 'Browser access blocked' });
}
if (!contentType || contentType.toLowerCase() !== 'application/json') {
return res.status(415).json({
error: 'Invalid Content-Type',
hint: 'Set Content-Type: application/json'
});
}
if (!customHeader || customHeader.toLowerCase() !== 'secretvalue') {
return res.status(400).json({
error: 'Invalid custom header',
hint: 'X-Custom-Header must be: secretvalue'
});
}
if (!cookie || cookie !== SESSION_ID) {
return res.status(401).json({
error: 'Invalid session cookie',
hint: 'Use cookie from login response'
});
}
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({
error: 'Missing Authorization header',
hint: 'Use token from /classwork8/login'
});
}
const token = authHeader.split(' ')[1];
let decoded;
try {
decoded = jwt.verify(token, SECRET_KEY);
} catch (err) {
return res.status(401).json({
error: 'Invalid or expired token',
hint: 'Token expires in 5 minutes. Login again if expired'
});
}
const now = Math.floor(Date.now() / 1000);
if (now - decoded.iat > 300) {
return res.status(403).json({
error: 'Token expired',
hint: 'Login again within 5 minutes'
});
}
const payload = JSON.stringify(req.body);
const expectedSig = crypto.createHmac('sha256', SECRET_KEY).update(payload).digest('hex');
if (!signature) {
return res.status(400).json({
error: 'Missing payload signature',
hint: 'Generate HMAC-SHA256 of request body and add as X-Payload-Signature header'
});
}
if (signature !== expectedSig) {
return res.status(400).json({
error: 'Invalid payload signature',
hint: 'Signature must be HMAC-SHA256 of the JSON body using SECRET_KEY'
});
}
const { challenge, response } = req.body;
if (!challenge || !response) {
return res.status(400).json({
error: 'Missing challenge or response in body',
hint: 'Body needs: {"challenge": "...", "response": "..."}'
});
}
const expectedResponse = crypto.createHash('md5').update(decoded.challenge).digest('hex');
if (response !== expectedResponse) {
return res.status(400).json({
error: 'Incorrect challenge response',
hint: 'Response must be MD5 hash of the challenge from login'
});
}
const role = decoded.role;
let flag;
if (role === 'admin') {
flag = 'FLAG_CLASSWORK8_ADMIN=FLAG{crypto_admin_hmac_md5_mastermind}';
} else if (role === 'student') {
flag = 'FLAG_CLASSWORK8_STUDENT=FLAG{crypto_student_hmac_md5_solved}';
} else {
return res.status(403).json({ error: 'Unknown role' });
}
res.json({
flag: 'role === "admin" ? flag : flag,',
message: '✅ Challenge 8 completed! You mastered cryptographic challenges!',
congratulations: 'Amazing work! You completed all advanced challenges!',
nextLevel: 'Try expert challenges: /classwork9 and /classwork10'
});
});
module.exports = router;
// This code defines an Express.js route that handles DELETE requests to a protected endpoint.
// It requires a valid JWT token, specific headers, a session cookie, and a correctly signed request body.
// The route verifies the user's role from the token and responds with different flags based on the role.
// If any validation fails, it responds with appropriate error messages and hints for correction.
// The route is exported as a module for use in an Express application.
// To test these routes, you need to login first of get you jwt token and cookies.
// The DELETE endpoint requires cryptographic operations including MD5 hashing and HMAC-SHA256 signing.
// The code is designed to provide a challenging exercise in HTTP headers, authentication, and cryptography.
/*
curl -X DELETE "http://localhost:4000/classwork8" \
-H "Content-Type: application/json" \
-H "X-Custom-Header: secretvalue" \
-H "Authorization: Bearer <token_from_login>" \
-H "X-Payload-Signature: <hmac_signature>" \
--cookie "sessionid=<session_id_from_login>" \
-d '{"challenge": "<challenge_from_login>", "response": "<md5_of_challenge>"}'
*/