Skip to content

Commit ddd7b40

Browse files
committed
vad problem med github
1 parent 0a53b7f commit ddd7b40

1 file changed

Lines changed: 56 additions & 4 deletions

File tree

src/main/java/org/example/StaticFileHandler.java

Lines changed: 56 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,13 +26,65 @@ public StaticFileHandler(String webRoot) {
2626
}
2727

2828
public void sendGetRequest(OutputStream outputStream, String uri) throws IOException {
29-
byte[] fileBytes = cacheFilter.getOrFetch(uri,
30-
path -> Files.readAllBytes(new File(webRoot, path).toPath())
31-
);
29+
try {
30+
// Sanera URI: ta bort frågetecken, hashtaggar, ledande snedstreck och null-bytes
31+
String sanitizedUri = sanitizeUri(uri);
32+
33+
// Kontrollera för sökvägsgenomgång-attacker
34+
if (isPathTraversal(sanitizedUri)) {
35+
sendErrorResponse(outputStream, 403, "Forbidden");
36+
return;
37+
}
38+
39+
byte[] fileBytes = cacheFilter.getOrFetch(sanitizedUri,
40+
path -> Files.readAllBytes(new File(webRoot, path).toPath())
41+
);
42+
43+
HttpResponseBuilder response = new HttpResponseBuilder();
44+
response.setHeaders(Map.of("Content-Type", "text/html; charset=utf-8"));
45+
response.setBody(fileBytes);
46+
PrintWriter writer = new PrintWriter(outputStream, true);
47+
writer.println(response.build());
48+
49+
} catch (IOException e) {
50+
// Hantera saknad fil och andra IO-fel
51+
try {
52+
sendErrorResponse(outputStream, 404, "Not Found");
53+
} catch (IOException ex) {
54+
ex.printStackTrace();
55+
}
56+
}
57+
}
58+
59+
private String sanitizeUri(String uri) {
60+
// Ta bort frågesträngar (?)
61+
uri = uri.split("\\?")[0];
62+
63+
// Ta bort fragment (#)
64+
uri = uri.split("#")[0];
65+
66+
// Ta bort null-bytes
67+
uri = uri.replace("\0", "");
68+
69+
// Ta bort ledande snedstreck
70+
while (uri.startsWith("/")) {
71+
uri = uri.substring(1);
72+
}
3273

74+
return uri;
75+
}
76+
77+
private boolean isPathTraversal(String uri) {
78+
// Kontrollera för kataloggenomgång-försök
79+
return uri.contains("..") || uri.contains("~");
80+
}
81+
82+
private void sendErrorResponse(OutputStream outputStream, int statusCode, String statusMessage) throws IOException {
3383
HttpResponseBuilder response = new HttpResponseBuilder();
84+
response.setStatusCode(statusCode);
3485
response.setHeaders(Map.of("Content-Type", "text/html; charset=utf-8"));
35-
response.setBody(fileBytes);
86+
String body = "<html><body><h1>" + statusCode + " " + statusMessage + "</h1></body></html>";
87+
response.setBody(body);
3688
PrintWriter writer = new PrintWriter(outputStream, true);
3789
writer.println(response.build());
3890
}

0 commit comments

Comments
 (0)