-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPathTraversalController.java
More file actions
377 lines (340 loc) · 12.7 KB
/
PathTraversalController.java
File metadata and controls
377 lines (340 loc) · 12.7 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
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
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package com.example.vulnerable;
import org.springframework.web.bind.annotation.*;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import java.io.*;
import java.nio.file.*;
import java.util.*;
/**
* VULNERABLE: Path Traversal Vulnerabilities
*
* Demonstrates multiple path traversal attack vectors that allow
* attackers to read arbitrary files from the server.
*
* Related CVEs:
* - CVE-2021-22060: Spring Framework Path Traversal
* - CVE-2021-29425: Apache Commons IO Path Traversal
*
* CWE-22: Improper Limitation of a Pathname to a Restricted Directory
* CVSS Score: 7.5 (HIGH)
*
* Impact:
* - Read sensitive files (/etc/passwd, application.properties)
* - Access source code
* - Read configuration files
* - Information disclosure
*
* WARNING: This code is intentionally vulnerable for educational purposes.
* DO NOT deploy to production!
*/
@RestController
@RequestMapping("/api/files")
public class PathTraversalController {
private static final String BASE_DIR = "uploads/";
/**
* VULNERABLE: Path Traversal via filename parameter
*
* CVE: Related to CVE-2021-22060 (Spring Framework)
* CWE-22: Path Traversal
* CVSS: 7.5 (HIGH)
*
* Attack Examples:
* - /api/files/read?filename=../../../etc/passwd
* - /api/files/read?filename=..\..\..\..\windows\system32\config\sam
* - /api/files/read?filename=../../../../application.properties
* - /api/files/read?filename=../../src/main/resources/application.yml
*
* Impact: Read any file on the server
*/
@GetMapping("/read")
public Map<String, Object> readFile(@RequestParam String filename) {
try {
// CRITICAL VULNERABILITY: No path validation
File file = new File(BASE_DIR + filename); // ❌ CWE-22
if (!file.exists()) {
return Map.of(
"success", false,
"error", "File not found",
"path", file.getAbsolutePath()
);
}
// Read file content
String content = new String(Files.readAllBytes(file.toPath()));
return Map.of(
"success", true,
"filename", filename,
"path", file.getAbsolutePath(),
"content", content,
"size", file.length(),
"warning", "VULNERABLE: Path traversal (CWE-22)"
);
} catch (Exception e) {
return Map.of(
"success", false,
"error", e.getMessage(),
"warning", "VULNERABLE: Path traversal (CWE-22)"
);
}
}
/**
* VULNERABLE: Path Traversal via download endpoint
*
* CVE: Related to CVE-2021-22060 (Spring Framework)
* CWE-22: Path Traversal
* CVSS: 7.5 (HIGH)
*
* Attack Examples:
* - /api/files/download?file=../../../etc/shadow
* - /api/files/download?file=../../../../root/.ssh/id_rsa
* - /api/files/download?file=../../pom.xml
*
* Impact: Download any file from the server
*/
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam String file) {
try {
// CRITICAL VULNERABILITY: No path validation
Path filePath = Paths.get(BASE_DIR).resolve(file); // ❌ CWE-22
Resource resource = new UrlResource(filePath.toUri());
if (!resource.exists()) {
return ResponseEntity.notFound().build();
}
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + resource.getFilename() + "\"")
.body(resource);
} catch (Exception e) {
return ResponseEntity.badRequest().build();
}
}
/**
* VULNERABLE: Path Traversal via file listing
*
* CWE-22: Path Traversal
* CVSS: 5.3 (MEDIUM)
*
* Attack Examples:
* - /api/files/list?directory=../../../etc
* - /api/files/list?directory=../../src
*
* Impact: List contents of any directory
*/
@GetMapping("/list")
public Map<String, Object> listFiles(@RequestParam String directory) {
try {
// CRITICAL VULNERABILITY: No path validation
File dir = new File(BASE_DIR + directory); // ❌ CWE-22
if (!dir.exists() || !dir.isDirectory()) {
return Map.of(
"success", false,
"error", "Directory not found",
"path", dir.getAbsolutePath()
);
}
File[] files = dir.listFiles();
List<Map<String, Object>> fileList = new ArrayList<>();
if (files != null) {
for (File f : files) {
fileList.add(Map.of(
"name", f.getName(),
"type", f.isDirectory() ? "directory" : "file",
"size", f.length(),
"path", f.getAbsolutePath()
));
}
}
return Map.of(
"success", true,
"directory", directory,
"path", dir.getAbsolutePath(),
"files", fileList,
"count", fileList.size(),
"warning", "VULNERABLE: Path traversal (CWE-22)"
);
} catch (Exception e) {
return Map.of(
"success", false,
"error", e.getMessage(),
"warning", "VULNERABLE: Path traversal (CWE-22)"
);
}
}
/**
* VULNERABLE: Path Traversal via file deletion
*
* CWE-22: Path Traversal
* CVSS: 8.1 (HIGH)
*
* Attack Examples:
* - /api/files/delete?filename=../../../important-file.txt
* - /api/files/delete?filename=../../application.properties
*
* Impact: Delete any file on the server
*/
@DeleteMapping("/delete")
public Map<String, Object> deleteFile(@RequestParam String filename) {
try {
// CRITICAL VULNERABILITY: No path validation
File file = new File(BASE_DIR + filename); // ❌ CWE-22
if (!file.exists()) {
return Map.of(
"success", false,
"error", "File not found",
"path", file.getAbsolutePath()
);
}
boolean deleted = file.delete();
return Map.of(
"success", deleted,
"filename", filename,
"path", file.getAbsolutePath(),
"message", deleted ? "File deleted" : "Failed to delete file",
"warning", "VULNERABLE: Path traversal (CWE-22)"
);
} catch (Exception e) {
return Map.of(
"success", false,
"error", e.getMessage(),
"warning", "VULNERABLE: Path traversal (CWE-22)"
);
}
}
/**
* VULNERABLE: Path Traversal via file upload
*
* CVE: Related to CVE-2021-29425 (Apache Commons IO)
* CWE-22: Path Traversal
* CVSS: 7.5 (HIGH)
*
* Attack Examples:
* - Upload with filename: ../../../evil.jsp
* - Upload with filename: ../../webapps/shell.war
*
* Impact: Write files to arbitrary locations
*/
@PostMapping("/upload")
public Map<String, Object> uploadFile(
@RequestParam String filename,
@RequestBody String content) {
try {
// CRITICAL VULNERABILITY: No path validation
File file = new File(BASE_DIR + filename); // ❌ CWE-22
// Create parent directories if needed
file.getParentFile().mkdirs();
// Write content to file
Files.write(file.toPath(), content.getBytes());
return Map.of(
"success", true,
"filename", filename,
"path", file.getAbsolutePath(),
"size", file.length(),
"message", "File uploaded successfully",
"warning", "VULNERABLE: Path traversal (CWE-22)"
);
} catch (Exception e) {
return Map.of(
"success", false,
"error", e.getMessage(),
"warning", "VULNERABLE: Path traversal (CWE-22)"
);
}
}
/**
* Information endpoint showing vulnerability details
*/
@GetMapping("/info")
public Map<String, Object> vulnerabilityInfo() {
return Map.of(
"vulnerability", "Path Traversal",
"cwe", "CWE-22",
"cvss", "7.5 (HIGH)",
"related_cves", Arrays.asList(
"CVE-2021-22060 (Spring Framework)",
"CVE-2021-29425 (Apache Commons IO)"
),
"description", "Improper limitation of a pathname to a restricted directory",
"impact", Arrays.asList(
"Read sensitive files",
"Access source code",
"Read configuration files",
"Delete arbitrary files",
"Write files to arbitrary locations"
),
"vulnerable_endpoints", Arrays.asList(
"GET /api/files/read?filename=...",
"GET /api/files/download?file=...",
"GET /api/files/list?directory=...",
"DELETE /api/files/delete?filename=...",
"POST /api/files/upload"
),
"attack_examples", Arrays.asList(
"/api/files/read?filename=../../../etc/passwd",
"/api/files/read?filename=../../../../application.properties",
"/api/files/download?file=../../pom.xml",
"/api/files/list?directory=../../../etc",
"/api/files/delete?filename=../../important-file.txt"
),
"mitigation", Arrays.asList(
"Validate and sanitize file paths",
"Use allowlist of allowed directories",
"Resolve canonical paths",
"Check if resolved path is within allowed directory",
"Use Path.normalize() and validate result"
),
"references", Arrays.asList(
"https://cwe.mitre.org/data/definitions/22.html",
"https://owasp.org/www-community/attacks/Path_Traversal"
)
);
}
/**
* FIXED VERSION: Safe file reading with path validation
*/
@GetMapping("/safe-read")
public Map<String, Object> safeReadFile(@RequestParam String filename) {
try {
// SAFE: Validate filename
if (filename.contains("..") || filename.contains("/") || filename.contains("\\")) {
return Map.of(
"success", false,
"error", "Invalid filename",
"message", "Filename cannot contain path traversal characters"
);
}
// SAFE: Resolve canonical path and validate
Path basePath = Paths.get(BASE_DIR).toRealPath();
Path filePath = basePath.resolve(filename).normalize();
// SAFE: Check if file is within allowed directory
if (!filePath.startsWith(basePath)) {
return Map.of(
"success", false,
"error", "Access denied",
"message", "File must be within allowed directory"
);
}
File file = filePath.toFile();
if (!file.exists()) {
return Map.of(
"success", false,
"error", "File not found"
);
}
String content = new String(Files.readAllBytes(file.toPath()));
return Map.of(
"success", true,
"filename", filename,
"content", content,
"size", file.length(),
"security", "Path validated and sanitized"
);
} catch (Exception e) {
return Map.of(
"success", false,
"error", "Failed to read file",
"message", e.getMessage()
);
}
}
}