Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file added .github/.keep
Empty file.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
[![Review Assignment Due Date](https://classroom.github.com/assets/deadline-readme-button-22041afd0340ce965d47ae6ef1cefeee28c7c493a6346c4f15d667ab976d596c.svg)](https://classroom.github.com/a/NSTTkgmb)
# Лабораторная работа №4 — Анализ и тестирование безопасности веб-приложения

## Цель
Expand Down
591 changes: 591 additions & 0 deletions REPORT.md

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ repositories {

dependencies {
implementation 'io.javalin:javalin:6.3.0'
implementation 'com.fasterxml.jackson.core:jackson-databind:2.17.2'
implementation 'org.slf4j:slf4j-simple:2.0.13'

testImplementation platform('org.junit:junit-bom:6.0.0')
Expand Down
1 change: 1 addition & 0 deletions semgrep-report.sarif

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
package ru.itmo.testing.lab4.pentest;

import io.javalin.Javalin;
import org.junit.jupiter.api.*;
import ru.itmo.testing.lab4.controller.UserAnalyticsController;

import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;

import static org.junit.jupiter.api.Assertions.*;

/**
* =============================================================================
* PENTEST-ОТЧЁТ: CWE-209 — Information Exposure Through Error Messages
* =============================================================================
*
* Компонент: POST /recordSession, GET /monthlyActivity, GET /exportReport, POST /notify
* CWE: CWE-209 (Generation of Error Message Containing Sensitive Information)
* CVSS v3.1: 5.3 (Medium) — AV:N/AC:L/PR:N/UI:N/S:U/C:L/I:N/A:N
* Статус: CONFIRMED
*
* ОПИСАНИЕ:
* Несколько эндпоинтов перехватывают исключения и возвращают e.getMessage()
* напрямую клиенту. Сообщения об ошибках содержат имена внутренних классов,
* детали парсинга и стек-информацию, что раскрывает внутреннюю архитектуру
* приложения и облегчает дальнейшую эксплуатацию.
*
* ВЕКТОР АТАКИ:
* 1. POST /recordSession?userId=user&loginTime=INVALID&logoutTime=2025-01-01T10:00
* → "Invalid data: Text 'INVALID' could not be parsed at index 0"
* 2. GET /monthlyActivity?userId=user&month=INVALID
* → "Invalid data: Text 'INVALID' could not be parsed at index 0"
*
* ВЛИЯНИЕ:
* - Раскрытие технологического стека (java.time.format.DateTimeParseException)
* - Помощь атакующему в подборе корректных форматов для injection-атак
* - Утечка файловых путей и имён классов
*
* МЕРЫ ЗАЩИТЫ:
* - Возвращать клиенту только общие сообщения: "Invalid input"
* - Логировать детали на стороне сервера
* - Использовать глобальный обработчик ошибок Javalin
* =============================================================================
*/
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class InformationDisclosurePentestTest {

private static final int TEST_PORT = 7780;
private static final String BASE_URL = "http://localhost:" + TEST_PORT;

private static Javalin app;
private static HttpClient http;

@BeforeAll
static void startServer() throws Exception {
app = UserAnalyticsController.createApp();
app.start(TEST_PORT);
http = HttpClient.newHttpClient();

send("POST", "/register?userId=info_user&userName=InfoTest");
}

@AfterAll
static void stopServer() {
app.stop();
}

// -------------------------------------------------------------------------
// EXPLOIT: /recordSession раскрывает детали парсинга дат
// -------------------------------------------------------------------------

@Test
@Order(1)
@DisplayName("[EXPLOIT] /recordSession раскрывает исключение при невалидной дате")
void recordSessionLeaksParseException() throws Exception {
HttpResponse<String> response = send("POST",
"/recordSession?userId=info_user&loginTime=INVALID&logoutTime=2025-01-01T10:00:00");

assertEquals(400, response.statusCode());

String body = response.body();
assertTrue(body.contains("Invalid data:"),
"Ответ содержит префикс 'Invalid data:'");
assertTrue(body.contains("could not be parsed"),
"УЯЗВИМОСТЬ ПОДТВЕРЖДЕНА: сообщение об ошибке раскрывает детали парсинга — " +
"атакующий узнаёт, какой формат даты ожидается");
}

@Test
@Order(2)
@DisplayName("[EXPLOIT] /recordSession раскрывает позицию ошибки в строке")
void recordSessionLeaksErrorPosition() throws Exception {
HttpResponse<String> response = send("POST",
"/recordSession?userId=info_user&loginTime=2025-13-01T10:00:00&logoutTime=2025-01-01T10:00:00");

assertEquals(400, response.statusCode());

String body = response.body();
assertTrue(body.contains("Invalid data:"),
"Ошибка парсинга раскрывает детали формата даты");
}

// -------------------------------------------------------------------------
// EXPLOIT: /monthlyActivity раскрывает детали исключений
// -------------------------------------------------------------------------

@Test
@Order(3)
@DisplayName("[EXPLOIT] /monthlyActivity раскрывает исключение при невалидном месяце")
void monthlyActivityLeaksParseException() throws Exception {
HttpResponse<String> response = send("GET",
"/monthlyActivity?userId=info_user&month=INVALID");

assertEquals(400, response.statusCode());

String body = response.body();
assertTrue(body.contains("Invalid data:"),
"УЯЗВИМОСТЬ ПОДТВЕРЖДЕНА: ошибка парсинга YearMonth раскрыта клиенту");
assertTrue(body.contains("could not be parsed"),
"Сообщение содержит детали внутреннего парсера java.time");
}

@Test
@Order(4)
@DisplayName("[EXPLOIT] /monthlyActivity раскрывает IllegalArgumentException для пользователя без сессий")
void monthlyActivityLeaksNoSessionsException() throws Exception {
send("POST", "/register?userId=no_sessions_user&userName=NoSessions");

HttpResponse<String> response = send("GET",
"/monthlyActivity?userId=no_sessions_user&month=2025-01");

assertEquals(400, response.statusCode());

String body = response.body();
assertTrue(body.contains("No sessions found"),
"Сообщение раскрывает внутреннюю логику проверки сессий");
}

// -------------------------------------------------------------------------
// EXPLOIT: /notify раскрывает детали сетевых ошибок
// -------------------------------------------------------------------------

@Test
@Order(5)
@DisplayName("[EXPLOIT] /notify раскрывает детали DNS-ошибки при невалидном URL")
void notifyLeaksDnsError() throws Exception {
HttpResponse<String> response = send("POST",
"/notify?userId=info_user&callbackUrl=" + enc("http://this.host.does.not.exist.invalid/path"));

assertEquals(500, response.statusCode());

String body = response.body();
assertTrue(body.contains("Notification failed:"),
"УЯЗВИМОСТЬ ПОДТВЕРЖДЕНА: сообщение об ошибке содержит детали сетевой ошибки — " +
"раскрывает, что сервер выполняет DNS-резолвинг");
}

@Test
@Order(6)
@DisplayName("[EXPLOIT] /notify раскрывает детали при неверной схеме URL")
void notifyLeaksProtocolError() throws Exception {
HttpResponse<String> response = send("POST",
"/notify?userId=info_user&callbackUrl=" + enc("ftp://example.com/file"));

assertEquals(500, response.statusCode());

String body = response.body();
assertTrue(body.contains("Notification failed:"),
"Детали ошибки протокола раскрыты клиенту");
}

// -------------------------------------------------------------------------
// BOUNDARY: проверяем граничные случаи
// -------------------------------------------------------------------------

@Test
@Order(7)
@DisplayName("[BOUNDARY] Корректные данные не генерируют сообщений об ошибках")
void validDataNoErrorLeakage() throws Exception {
send("POST", "/recordSession?userId=info_user" +
"&loginTime=2025-01-01T10:00:00&logoutTime=2025-01-01T11:00:00");

HttpResponse<String> response = send("GET",
"/monthlyActivity?userId=info_user&month=2025-01");

assertEquals(200, response.statusCode());
assertFalse(response.body().contains("Exception"),
"Корректный запрос не должен содержать слово 'Exception' в ответе");
}

@Test
@Order(8)
@DisplayName("[BOUNDARY] Отсутствие параметров возвращает 400 без утечки деталей")
void missingParamsNoDetailedError() throws Exception {
HttpResponse<String> response = send("POST", "/recordSession");

assertEquals(400, response.statusCode());
assertEquals("Missing parameters", response.body(),
"Отсутствие параметров возвращает общее сообщение (корректно)");
}

// -------------------------------------------------------------------------
// Вспомогательные методы
// -------------------------------------------------------------------------

private static String enc(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8);
}

private static HttpResponse<String> send(String method, String path) throws Exception {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(BASE_URL + path))
.method(method, HttpRequest.BodyPublishers.noBody())
.build();
return http.send(request, HttpResponse.BodyHandlers.ofString());
}
}
Loading