feat: build wahrwelt A/D toolkit
This commit is contained in:
1 parent
303438d206
commit
653924d8c6
564 files changed
+36310
-49998
No files matched your search
@@ -0,0 +1,18 @@
|
||||
.git
|
||||
.gitignore
|
||||
.gitmodules
|
||||
.gitlab-ci.yml
|
||||
build
|
||||
out
|
||||
docs
|
||||
screenshots
|
||||
docker
|
||||
pcaps
|
||||
rsa_keys
|
||||
node_modules
|
||||
frontend/node_modules
|
||||
frontend/dist
|
||||
frontend/coverage
|
||||
*.log
|
||||
docker-compose.yml
|
||||
README_EN.md
|
||||
@@ -0,0 +1,37 @@
|
||||
FROM node:slim AS frontend
|
||||
WORKDIR /workspace/frontend
|
||||
COPY frontend/package.json ./
|
||||
RUN npm install --global npm \
|
||||
&& npm install --no-audit --no-fund --package-lock=false
|
||||
COPY frontend/ ./
|
||||
RUN npm test && npm run build
|
||||
|
||||
FROM gradle:latest AS gradle-dist
|
||||
|
||||
FROM eclipse-temurin:27-jdk AS app-build
|
||||
COPY --from=gradle-dist /opt/gradle /opt/gradle
|
||||
ENV GRADLE_HOME=/opt/gradle \
|
||||
PATH=/opt/gradle/bin:$PATH \
|
||||
JAVA_TOOL_OPTIONS=-Xmx2g
|
||||
WORKDIR /workspace
|
||||
COPY settings.gradle.kts build.gradle.kts ./
|
||||
COPY src/ ./src/
|
||||
COPY --from=frontend /workspace/frontend/dist/ ./src/main/resources/static/
|
||||
RUN gradle --no-daemon --max-workers=2 test bootJar
|
||||
|
||||
FROM eclipse-temurin:27-jre
|
||||
RUN apt-get update \
|
||||
&& apt-get upgrade -y --no-install-recommends \
|
||||
&& apt-get install --no-install-recommends -y curl libpcap0.8 \
|
||||
&& rm -f /usr/bin/pebble \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& mkdir -p /app \
|
||||
&& chown 10001:10001 /app
|
||||
WORKDIR /app
|
||||
COPY --from=app-build --chown=10001:10001 /workspace/build/libs/packmate-1.0.0.jar /app/packmate.jar
|
||||
COPY --from=project /LICENSE /usr/share/licenses/wahrwelt/LICENSE
|
||||
USER 10001:10001
|
||||
EXPOSE 65000
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=45s --retries=3 \
|
||||
CMD curl --max-time 3 --fail --silent --output /dev/null "http://127.0.0.1:${SERVER_PORT:-65000}/healthz"
|
||||
ENTRYPOINT ["java", "-Djna.tmpdir=/jna-tmp", "-XX:MaxRAMPercentage=75.0", "-jar", "/app/packmate.jar"]
|
||||
@@ -0,0 +1,43 @@
|
||||
# Packmate
|
||||
|
||||
Packmate показывает сетевые потоки, запросы и ответы, найденные шаблоны и службы. По умолчанию приложение разбирает локальный PCAP в режиме `FILE`; интерфейс доступен через адрес loopback хоста.
|
||||
|
||||
## Запуск
|
||||
|
||||
Из корня wahrwelt выполните `./control init`, затем запустите:
|
||||
|
||||
```sh
|
||||
./control pack
|
||||
```
|
||||
|
||||
Откройте `http://127.0.0.1:${PACKMATE_PORT:-65000}` и войдите с `PACKMATE_USERNAME` и `PACKMATE_PASSWORD` из корневого `.env`. Для анализа замените созданный `local/pcaps/capture.pcap` нужным файлом, затем нажмите `Старт FILE`. Пустой файл, созданный командой `init`, позволяет запустить сервис до добавления PCAP.
|
||||
|
||||
Файл и каталог `local/rsa_keys` монтируются в контейнер только для чтения. Ключи RSA нужны только для поддерживаемого исходным проектом TLS_RSA_WITH_AES.
|
||||
|
||||
Проверка готовности доступна по `GET /healthz` без авторизации и не возвращает сведений о конфигурации.
|
||||
|
||||
## Режим LIVE
|
||||
|
||||
LIVE не включен по умолчанию. Он использует host network, чтобы видеть трафик Linux-узла. Применяйте его только на собственном Linux-узле и только для трафика, который вы вправе анализировать. Укажите в корневом `.env` интерфейс, видящий этот трафик (`PACKMATE_INTERFACE_NAME`), локальный адрес (`PACKMATE_LOCAL_IP`) и при необходимости `PACKMATE_DB_PORT`, затем выполните:
|
||||
|
||||
```sh
|
||||
docker compose -f compose.yaml -f components/packmate/compose.live.yaml up --build packmate packmate-db
|
||||
```
|
||||
|
||||
Этот режим добавляет только `NET_RAW` и `NET_ADMIN`; он не использует `privileged` и Docker socket. База данных публикуется только на `127.0.0.1:${PACKMATE_DB_PORT:-65432}`, а веб-интерфейс слушает `BIND_ADDRESS` (по умолчанию `127.0.0.1`) и `PACKMATE_PORT`.
|
||||
|
||||
## Переменные и проверки
|
||||
|
||||
Остановка с сохранением данных: `./control pack down`. Журнал: `./control pack logs`.
|
||||
Корневой `.env` должен содержать непустые `PACKMATE_PASSWORD` и `PACKMATE_DB_PASSWORD`. Команда `./control init` создает файл с секретами, если его еще нет. Полный список переменных приведен в корневом [`.env.example`](../../.env.example).
|
||||
|
||||
Локальные проверки из каталога компонента:
|
||||
|
||||
```sh
|
||||
cd components/packmate/frontend
|
||||
npm install --package-lock=false && npm test && npm run typecheck && npm run build
|
||||
cd ../../..
|
||||
./control pack
|
||||
```
|
||||
|
||||
Источники и лицензии перечислены в [общем LICENSE](../../LICENSE).
|
||||
@@ -0,0 +1,72 @@
|
||||
plugins {
|
||||
id("org.springframework.boot") version "latest.release"
|
||||
id("java")
|
||||
}
|
||||
|
||||
group = "ru.serega6531"
|
||||
version = "1.0.0"
|
||||
|
||||
java {
|
||||
toolchain {
|
||||
languageVersion = JavaLanguageVersion.of(27)
|
||||
}
|
||||
}
|
||||
|
||||
configurations {
|
||||
get("compileOnly").apply {
|
||||
extendsFrom(configurations.annotationProcessor.get())
|
||||
}
|
||||
}
|
||||
|
||||
repositories {
|
||||
mavenCentral()
|
||||
}
|
||||
|
||||
dependencies {
|
||||
implementation(platform("org.springframework.boot:spring-boot-dependencies:latest.release"))
|
||||
implementation(platform("tools.jackson:jackson-bom:latest.release"))
|
||||
implementation("org.apache.tomcat.embed:tomcat-embed-core:latest.release")
|
||||
implementation("org.apache.tomcat.embed:tomcat-embed-el:latest.release")
|
||||
implementation("org.apache.tomcat.embed:tomcat-embed-websocket:latest.release")
|
||||
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
|
||||
implementation("org.springframework.boot:spring-boot-starter-webmvc")
|
||||
implementation("org.springframework.boot:spring-boot-starter-security")
|
||||
implementation("org.springframework.boot:spring-boot-starter-websocket")
|
||||
implementation("org.springframework.session:spring-session-core")
|
||||
implementation("org.apache.commons:commons-lang3:latest.release")
|
||||
implementation("commons-io:commons-io:latest.release")
|
||||
|
||||
implementation("org.pcap4j:pcap4j-core:latest.release")
|
||||
implementation("org.pcap4j:pcap4j-packetfactory-static:latest.release")
|
||||
|
||||
constraints {
|
||||
implementation("net.java.dev.jna:jna:latest.release") {
|
||||
because("Поддерживаем актуальную стабильную версию JNA для native libpcap.")
|
||||
}
|
||||
}
|
||||
|
||||
implementation("com.google.guava:guava:latest.release")
|
||||
implementation("com.google.re2j:re2j:latest.release")
|
||||
implementation("org.java-websocket:Java-WebSocket:latest.release")
|
||||
implementation("org.bouncycastle:bcprov-jdk18on:latest.release")
|
||||
implementation("org.bouncycastle:bctls-jdk18on:latest.release")
|
||||
implementation("org.modelmapper:modelmapper:latest.release")
|
||||
implementation("com.athaydes.rawhttp:rawhttp-core:latest.release")
|
||||
|
||||
compileOnly("org.jetbrains:annotations:latest.release")
|
||||
compileOnly("org.projectlombok:lombok:latest.release")
|
||||
runtimeOnly("org.postgresql:postgresql:latest.release")
|
||||
annotationProcessor("org.projectlombok:lombok:latest.release")
|
||||
testImplementation("org.springframework.boot:spring-boot-starter-test")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter:latest.release")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher:latest.release")
|
||||
}
|
||||
|
||||
tasks.test {
|
||||
useJUnitPlatform()
|
||||
jvmArgs("-XX:+EnableDynamicAgentLoading", "-Djdk.attach.allowAttachSelf=true")
|
||||
}
|
||||
|
||||
tasks.withType<JavaCompile>().configureEach {
|
||||
options.release = 27
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
services:
|
||||
packmate:
|
||||
environment:
|
||||
PACKMATE_CAPTURE_MODE: LIVE
|
||||
PACKMATE_INTERFACE_NAME: ${PACKMATE_INTERFACE_NAME:?Задайте PACKMATE_INTERFACE_NAME для режима LIVE}
|
||||
PACKMATE_LOCAL_IP: ${PACKMATE_LOCAL_IP:?Задайте PACKMATE_LOCAL_IP для режима LIVE}
|
||||
SERVER_ADDRESS: ${BIND_ADDRESS:-127.0.0.1}
|
||||
SERVER_PORT: ${PACKMATE_PORT:-65000}
|
||||
SPRING_DATASOURCE_URL: jdbc:postgresql://127.0.0.1:${PACKMATE_DB_PORT:-65432}/packmate
|
||||
network_mode: host
|
||||
networks: !reset []
|
||||
ports: !reset []
|
||||
cap_add:
|
||||
- NET_RAW
|
||||
- NET_ADMIN
|
||||
|
||||
packmate-db:
|
||||
ports:
|
||||
- "127.0.0.1:${PACKMATE_DB_PORT:-65432}:5432"
|
||||
@@ -0,0 +1,72 @@
|
||||
services:
|
||||
packmate:
|
||||
build:
|
||||
context: .
|
||||
additional_contexts:
|
||||
project: ../..
|
||||
dockerfile: Dockerfile
|
||||
depends_on:
|
||||
packmate-db:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
SERVER_ADDRESS: 0.0.0.0
|
||||
SERVER_PORT: "65000"
|
||||
SPRING_DATASOURCE_URL: jdbc:postgresql://packmate-db:5432/packmate
|
||||
SPRING_DATASOURCE_USERNAME: packmate
|
||||
SPRING_DATASOURCE_PASSWORD: ${PACKMATE_DB_PASSWORD:?Задайте PACKMATE_DB_PASSWORD}
|
||||
PACKMATE_USERNAME: ${PACKMATE_USERNAME:-packmate}
|
||||
PACKMATE_PASSWORD: ${PACKMATE_PASSWORD:?Задайте PACKMATE_PASSWORD}
|
||||
PACKMATE_CAPTURE_MODE: ${PACKMATE_CAPTURE_MODE:-FILE}
|
||||
PACKMATE_INTERFACE_NAME: ${PACKMATE_INTERFACE_NAME:-lo}
|
||||
PACKMATE_PCAP_FILE: ${PACKMATE_PCAP_FILE:-/pcaps/capture.pcap}
|
||||
PACKMATE_LOCAL_IP: ${PACKMATE_LOCAL_IP:-192.0.2.1}
|
||||
ports:
|
||||
- "${BIND_ADDRESS:-127.0.0.1}:${PACKMATE_PORT:-65000}:65000"
|
||||
volumes:
|
||||
- ../../local/pcaps:/pcaps:ro
|
||||
- ../../local/rsa_keys:/app/rsa_keys:ro
|
||||
networks:
|
||||
- default
|
||||
- packmate-data
|
||||
read_only: true
|
||||
tmpfs:
|
||||
- /tmp:rw,noexec,nosuid,nodev,mode=1777,size=64m
|
||||
- /jna-tmp:rw,exec,nosuid,nodev,uid=10001,gid=10001,mode=0700,size=16m
|
||||
cap_drop:
|
||||
- ALL
|
||||
mem_limit: ${PACKMATE_MEMORY_LIMIT:-2g}
|
||||
pids_limit: 256
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
restart: unless-stopped
|
||||
|
||||
packmate-db:
|
||||
build:
|
||||
context: ../../containers
|
||||
dockerfile: postgres.Dockerfile
|
||||
environment:
|
||||
POSTGRES_DB: packmate
|
||||
POSTGRES_USER: packmate
|
||||
POSTGRES_PASSWORD: ${PACKMATE_DB_PASSWORD:?Задайте PACKMATE_DB_PASSWORD}
|
||||
volumes:
|
||||
- packmate-db:/var/lib/postgresql
|
||||
networks:
|
||||
- packmate-data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U packmate -d packmate"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 10s
|
||||
mem_limit: 1g
|
||||
pids_limit: 128
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
restart: unless-stopped
|
||||
|
||||
volumes:
|
||||
packmate-db:
|
||||
|
||||
networks:
|
||||
packmate-data:
|
||||
internal: true
|
||||
@@ -0,0 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<meta name="theme-color" content="#30343a" />
|
||||
<link rel="icon" type="image/jpeg" href="/logo.jpg" />
|
||||
<meta name="description" content="wahrwelt: просмотр трафика в Packmate" />
|
||||
<title>wahrwelt / Packmate</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,28 @@
|
||||
{
|
||||
"name": "wahrwelt-packmate-ui",
|
||||
"version": "1.0.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite --host 127.0.0.1",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"test": "vitest run",
|
||||
"build": "tsc --noEmit && vite build"
|
||||
},
|
||||
"dependencies": {
|
||||
"react": ">=19.3.0",
|
||||
"react-dom": ">=19.3.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@testing-library/jest-dom": ">=7.0.1",
|
||||
"@testing-library/react": ">=16.3.3",
|
||||
"@testing-library/user-event": ">=14.6.8",
|
||||
"@types/react": ">=19.3.0",
|
||||
"@types/react-dom": ">=19.3.0",
|
||||
"@vitejs/plugin-react": ">=6.1.2",
|
||||
"happy-dom": ">=21.0.1",
|
||||
"typescript": ">=7.0.2",
|
||||
"vite": ">=8.3.4",
|
||||
"vitest": ">=5.0.4"
|
||||
}
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 23 KiB |
@@ -0,0 +1,219 @@
|
||||
import { act, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import App from "./App";
|
||||
import type { Packet, Service, Stream } from "./types";
|
||||
|
||||
const { apiMock } = vi.hoisted(() => ({
|
||||
apiMock: {
|
||||
services: vi.fn(),
|
||||
createService: vi.fn(),
|
||||
updateService: vi.fn(),
|
||||
deleteService: vi.fn(),
|
||||
patterns: vi.fn(),
|
||||
createPattern: vi.fn(),
|
||||
updatePattern: vi.fn(),
|
||||
setPatternEnabled: vi.fn(),
|
||||
deletePattern: vi.fn(),
|
||||
lookBack: vi.fn(),
|
||||
streams: vi.fn(),
|
||||
packets: vi.fn(),
|
||||
setFavorite: vi.fn(),
|
||||
pcapStarted: vi.fn(),
|
||||
startPcap: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("./api", () => ({ api: apiMock }));
|
||||
class MockWebSocket {
|
||||
static instances: MockWebSocket[] = [];
|
||||
onopen: (() => void) | null = null;
|
||||
onmessage: ((event: MessageEvent<string>) => void) | null = null;
|
||||
onerror: (() => void) | null = null;
|
||||
onclose: (() => void) | null = null;
|
||||
close = vi.fn();
|
||||
|
||||
constructor(readonly url: string) {
|
||||
MockWebSocket.instances.push(this);
|
||||
}
|
||||
}
|
||||
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
const promise = new Promise<T>((done) => { resolve = done; });
|
||||
return { promise, resolve };
|
||||
}
|
||||
|
||||
function service(port: number, name: string): Service {
|
||||
return {
|
||||
port,
|
||||
name,
|
||||
decryptTls: false,
|
||||
http: false,
|
||||
urldecodeHttpRequests: false,
|
||||
mergeAdjacentPackets: false,
|
||||
parseWebSockets: false,
|
||||
};
|
||||
}
|
||||
|
||||
function stream(id: number, port = 80): Stream {
|
||||
return {
|
||||
id,
|
||||
service: port,
|
||||
protocol: "TCP",
|
||||
startTimestamp: 1_700_000_000_000,
|
||||
endTimestamp: 1_700_000_000_100,
|
||||
foundPatternsIds: [],
|
||||
favorite: false,
|
||||
ttl: 64,
|
||||
userAgentHash: null,
|
||||
sizeBytes: 10,
|
||||
packetsCount: 1,
|
||||
};
|
||||
}
|
||||
|
||||
function packet(id: number, text: string): Packet {
|
||||
return {
|
||||
id,
|
||||
matches: [],
|
||||
timestamp: 1_700_000_000_000 + id,
|
||||
incoming: true,
|
||||
ungzipped: false,
|
||||
webSocketParsed: false,
|
||||
tlsDecrypted: false,
|
||||
hasHttpBody: false,
|
||||
content: btoa(String.fromCharCode(...new TextEncoder().encode(text))),
|
||||
};
|
||||
}
|
||||
|
||||
function pageOfStreams(firstId = 10): Stream[] {
|
||||
return Array.from({ length: 10 }, (_, index) => stream(firstId - index));
|
||||
}
|
||||
|
||||
function pageOfPackets(firstId = 100): Packet[] {
|
||||
return Array.from({ length: 10 }, (_, index) => packet(firstId - index, `пакет-${firstId - index}`));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
MockWebSocket.instances = [];
|
||||
vi.stubGlobal("WebSocket", MockWebSocket);
|
||||
window.history.replaceState({}, "", "/");
|
||||
localStorage.clear();
|
||||
localStorage.setItem("packmate.pageSize", "10");
|
||||
for (const method of Object.values(apiMock)) {
|
||||
method.mockReset();
|
||||
}
|
||||
apiMock.services.mockResolvedValue([service(80, "HTTP"), service(443, "HTTPS")]);
|
||||
apiMock.patterns.mockResolvedValue([]);
|
||||
apiMock.pcapStarted.mockResolvedValue(false);
|
||||
});
|
||||
|
||||
it("получает события через WebSocket и сохраняет остановку короткого PCAP", async () => {
|
||||
const startRequest = deferred<void>();
|
||||
apiMock.streams.mockResolvedValue([]);
|
||||
apiMock.startPcap.mockReturnValue(startRequest.promise);
|
||||
const view = render(<App />);
|
||||
const startButton = await screen.findByTitle("Начать обработку PCAP-файла");
|
||||
const socket = MockWebSocket.instances.at(-1)!;
|
||||
expect(socket.url).toBe(`ws://${window.location.host}/api/ws`);
|
||||
|
||||
fireEvent.click(startButton);
|
||||
await act(async () => {
|
||||
socket.onmessage?.(new MessageEvent("message", {
|
||||
data: JSON.stringify({ type: "PCAP_STARTED", value: null }),
|
||||
}));
|
||||
socket.onmessage?.(new MessageEvent("message", {
|
||||
data: JSON.stringify({ type: "PCAP_STOPPED", value: null }),
|
||||
}));
|
||||
startRequest.resolve();
|
||||
});
|
||||
|
||||
expect(screen.getByTitle("Начать обработку PCAP-файла")).toBeInTheDocument();
|
||||
view.unmount();
|
||||
expect(socket.close).toHaveBeenCalledOnce();
|
||||
});
|
||||
|
||||
describe("смена выборки во время загрузки", () => {
|
||||
it("не добавляет позднюю страницу потоков к выбранному другому сервису", async () => {
|
||||
const oldPage = deferred<Stream[]>();
|
||||
apiMock.streams.mockImplementation((port: number | undefined, query: { startingFrom: number | null }) => {
|
||||
if (port === 443) {
|
||||
return Promise.resolve([stream(900, 443)]);
|
||||
}
|
||||
return query.startingFrom === null ? Promise.resolve(pageOfStreams()) : oldPage.promise;
|
||||
});
|
||||
|
||||
render(<App />);
|
||||
await screen.findByRole("button", { name: /#10 TCP/ });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Загрузить еще потоки" }));
|
||||
await waitFor(() => expect(apiMock.streams).toHaveBeenCalledWith(
|
||||
undefined,
|
||||
expect.objectContaining({ startingFrom: 1 }),
|
||||
expect.any(AbortSignal),
|
||||
));
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /HTTPS #443/ }));
|
||||
await screen.findByRole("button", { name: /#900 TCP/ });
|
||||
|
||||
await act(async () => oldPage.resolve([stream(99, 80)]));
|
||||
expect(screen.queryByRole("button", { name: /#99 TCP/ })).not.toBeInTheDocument();
|
||||
expect(screen.getByRole("button", { name: /#900 TCP/ })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("игнорирует поздние пакеты старого потока и не снимает индикатор нового запроса", async () => {
|
||||
const initialPage = deferred<Packet[]>();
|
||||
const currentPage = deferred<Packet[]>();
|
||||
apiMock.streams.mockResolvedValue(pageOfStreams());
|
||||
apiMock.packets.mockImplementation((streamId: number, query: { startingFrom: number | null }) => {
|
||||
if (streamId === 10 && query.startingFrom === null) {
|
||||
return initialPage.promise;
|
||||
}
|
||||
if (streamId === 9 && query.startingFrom === null) {
|
||||
return currentPage.promise;
|
||||
}
|
||||
return Promise.resolve([]);
|
||||
});
|
||||
|
||||
render(<App />);
|
||||
fireEvent.click(await screen.findByRole("button", { name: /#10 TCP/ }));
|
||||
await waitFor(() => expect(apiMock.packets).toHaveBeenCalledWith(10, { startingFrom: null, pageSize: 10 }, expect.any(AbortSignal)));
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /#9 TCP/ }));
|
||||
await waitFor(() => expect(apiMock.packets).toHaveBeenCalledWith(9, { startingFrom: null, pageSize: 10 }, expect.any(AbortSignal)));
|
||||
await act(async () => initialPage.resolve(pageOfPackets(80)));
|
||||
expect(screen.getByText("Загрузка пакетов...")).toBeInTheDocument();
|
||||
|
||||
await act(async () => currentPage.resolve([packet(1, "актуальный пакет")]));
|
||||
expect(await screen.findByText("актуальный пакет")).toBeInTheDocument();
|
||||
expect(screen.queryByText(/пакет-80/)).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it("отменяет позднюю дополнительную страницу пакетов после выбора другого потока", async () => {
|
||||
const oldPage = deferred<Packet[]>();
|
||||
apiMock.streams.mockResolvedValue(pageOfStreams());
|
||||
apiMock.packets.mockImplementation((streamId: number, query: { startingFrom: number | null }) => {
|
||||
if (streamId === 10 && query.startingFrom === null) {
|
||||
return Promise.resolve(pageOfPackets());
|
||||
}
|
||||
if (streamId === 10) {
|
||||
return oldPage.promise;
|
||||
}
|
||||
return Promise.resolve([packet(2, "пакет выбранного потока")]);
|
||||
});
|
||||
|
||||
render(<App />);
|
||||
fireEvent.click(await screen.findByRole("button", { name: /#10 TCP/ }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: "Загрузить еще пакеты" }));
|
||||
await waitFor(() => expect(apiMock.packets).toHaveBeenCalledWith(
|
||||
10,
|
||||
{ startingFrom: 91, pageSize: 10 },
|
||||
expect.any(AbortSignal),
|
||||
));
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /#9 TCP/ }));
|
||||
expect(await screen.findByText("пакет выбранного потока")).toBeInTheDocument();
|
||||
await act(async () => oldPage.resolve([packet(80, "пакет-старого потока")]));
|
||||
|
||||
expect(screen.queryByText("пакет-старого потока")).not.toBeInTheDocument();
|
||||
expect(screen.getByText("пакет выбранного потока")).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,95 @@
|
||||
import type {
|
||||
Packet,
|
||||
Pattern,
|
||||
PatternInput,
|
||||
Service,
|
||||
Stream,
|
||||
} from "./types";
|
||||
|
||||
const apiRoot = "/api";
|
||||
|
||||
export class ApiError extends Error {
|
||||
readonly status: number;
|
||||
|
||||
constructor(status: number, serverMessage?: string) {
|
||||
super(status === 401 ? "Требуется войти в Packmate" : serverMessage ?? `Ошибка сервера: ${status}`);
|
||||
this.name = "ApiError";
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
const headers = new Headers(init.headers);
|
||||
if (init.body !== undefined && !headers.has("Content-Type")) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
|
||||
const response = await fetch(`${apiRoot}/${path.replace(/^\/+/, "")}`, {
|
||||
...init,
|
||||
headers,
|
||||
credentials: "same-origin",
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
let serverMessage: string | undefined;
|
||||
if (response.status >= 400 && response.status < 500
|
||||
&& response.headers.get("Content-Type")?.includes("application/json")) {
|
||||
try {
|
||||
const body: unknown = await response.json();
|
||||
if (typeof body === "object" && body !== null && "message" in body
|
||||
&& typeof body.message === "string") {
|
||||
serverMessage = body.message.slice(0, 240);
|
||||
}
|
||||
} catch {
|
||||
serverMessage = undefined;
|
||||
}
|
||||
}
|
||||
throw new ApiError(response.status, serverMessage);
|
||||
}
|
||||
if (response.status === 204) {
|
||||
return undefined as T;
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
if (text.length === 0) {
|
||||
return undefined as T;
|
||||
}
|
||||
return JSON.parse(text) as T;
|
||||
}
|
||||
|
||||
function post<T>(path: string, body?: unknown, signal?: AbortSignal): Promise<T> {
|
||||
return request(path, {
|
||||
method: "POST",
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
signal,
|
||||
});
|
||||
}
|
||||
|
||||
export const api = {
|
||||
services: () => request<Service[]>("service/"),
|
||||
createService: (service: Service) => post<Service>("service/", service),
|
||||
updateService: (port: number, service: Service) => post<Service>(`service/${port}`, service),
|
||||
deleteService: (port: number) => request<void>(`service/${port}`, { method: "DELETE" }),
|
||||
patterns: () => request<Pattern[]>("pattern/"),
|
||||
createPattern: (pattern: PatternInput) => post<Pattern>("pattern/", pattern),
|
||||
updatePattern: (id: number, pattern: Pick<Pattern, "name" | "color">) =>
|
||||
post<Pattern>(`pattern/${id}`, pattern),
|
||||
setPatternEnabled: (id: number, enabled: boolean) =>
|
||||
post<void>(`pattern/${id}/enable?enabled=${String(enabled)}`),
|
||||
deletePattern: (id: number) => request<void>(`pattern/${id}`, { method: "DELETE" }),
|
||||
lookBack: (id: number, minutes: number) => post<void>(`pattern/${id}/lookback`, minutes),
|
||||
streams: (
|
||||
servicePort: number | undefined,
|
||||
payload: { startingFrom: number | null; pageSize: number; pattern: { id: number } | null; favorites: boolean },
|
||||
signal?: AbortSignal,
|
||||
) => post<Stream[]>(`stream/${servicePort ?? "all"}`, payload, signal),
|
||||
packets: (
|
||||
streamId: number,
|
||||
payload: { startingFrom: number | null; pageSize: number },
|
||||
signal?: AbortSignal,
|
||||
) => post<Packet[]>(`packet/${streamId}`, payload, signal),
|
||||
setFavorite: (streamId: number, favorite: boolean) =>
|
||||
post<void>(`stream/${streamId}/${favorite ? "favorite" : "unfavorite"}`),
|
||||
pcapStarted: () => request<boolean>("pcap/started"),
|
||||
startPcap: () => post<void>("pcap/start"),
|
||||
};
|
||||
@@ -0,0 +1,106 @@
|
||||
import { useMemo } from "react";
|
||||
import { decodePacket, hexDump, packetSegments, packetText, pythonBytes, safePatternColor } from "../packet";
|
||||
import type { Packet, Pattern } from "../types";
|
||||
|
||||
interface PacketViewProps {
|
||||
packet: Packet;
|
||||
previous?: Packet;
|
||||
patterns: Pattern[];
|
||||
hexdumpMode: boolean;
|
||||
blockSize: number;
|
||||
lineNumberBase: number;
|
||||
notify: (message: string) => void;
|
||||
}
|
||||
|
||||
function dateText(timestamp: number): string {
|
||||
return new Intl.DateTimeFormat("ru-RU", {
|
||||
dateStyle: "short",
|
||||
timeStyle: "medium",
|
||||
}).format(new Date(timestamp));
|
||||
}
|
||||
|
||||
async function copyText(value: string): Promise<void> {
|
||||
if (navigator.clipboard?.writeText) {
|
||||
await navigator.clipboard.writeText(value);
|
||||
return;
|
||||
}
|
||||
const field = document.createElement("textarea");
|
||||
field.value = value;
|
||||
field.setAttribute("readonly", "");
|
||||
field.style.position = "fixed";
|
||||
field.style.opacity = "0";
|
||||
document.body.append(field);
|
||||
field.select();
|
||||
const copied = document.execCommand("copy");
|
||||
field.remove();
|
||||
if (!copied) {
|
||||
throw new Error("Буфер обмена недоступен");
|
||||
}
|
||||
}
|
||||
|
||||
export function PacketView({
|
||||
packet,
|
||||
previous,
|
||||
patterns,
|
||||
hexdumpMode,
|
||||
blockSize,
|
||||
lineNumberBase,
|
||||
notify,
|
||||
}: PacketViewProps) {
|
||||
const bytes = useMemo(() => decodePacket(packet.content), [packet.content]);
|
||||
const segments = useMemo(() => packetSegments(packet, patterns), [packet, patterns]);
|
||||
const body = useMemo(
|
||||
() => hexdumpMode ? hexDump(bytes, blockSize, lineNumberBase) : packetText(bytes),
|
||||
[bytes, blockSize, hexdumpMode, lineNumberBase],
|
||||
);
|
||||
const flags = [
|
||||
packet.ungzipped ? "GZIP" : "",
|
||||
packet.webSocketParsed ? "WS" : "",
|
||||
packet.tlsDecrypted ? "TLS" : "",
|
||||
].filter(Boolean);
|
||||
|
||||
const copy = async (value: string, label: string) => {
|
||||
try {
|
||||
await copyText(value);
|
||||
notify(`${label}: скопировано`);
|
||||
} catch {
|
||||
notify("Не удалось скопировать данные");
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<article className={`packet ${packet.incoming ? "packet-request" : "packet-response"}`}>
|
||||
<header className="packet-header">
|
||||
<div className="packet-meta">
|
||||
<strong>#{packet.id}</strong>
|
||||
<time dateTime={new Date(packet.timestamp).toISOString()}>{dateText(packet.timestamp)}</time>
|
||||
{previous && <span>+{packet.timestamp - previous.timestamp} мс</span>}
|
||||
<span className="packet-direction">{packet.incoming ? "Запрос" : "Ответ"}</span>
|
||||
{flags.map((flag) => <span className="packet-flag" key={flag}>{flag}</span>)}
|
||||
</div>
|
||||
<div className="packet-actions">
|
||||
<button type="button" className="text-button" onClick={() => void copy(bytesToHex(bytes), "HEX")}>
|
||||
Копировать HEX
|
||||
</button>
|
||||
<button type="button" className="text-button" onClick={() => void copy(packetText(bytes), "Текст")}>
|
||||
Копировать текст
|
||||
</button>
|
||||
<button type="button" className="text-button" onClick={() => void copy(pythonBytes(bytes), "Python bytes")}>
|
||||
Копировать как Python bytes
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
<pre className="packet-content">
|
||||
{hexdumpMode
|
||||
? body
|
||||
: segments.map((segment, index) => segment.pattern
|
||||
? <mark key={`${segment.pattern.id}-${index}`} style={{ backgroundColor: safePatternColor(segment.pattern.color) }}>{segment.text}</mark>
|
||||
: <span key={`text-${index}`}>{segment.text}</span>)}
|
||||
</pre>
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
function bytesToHex(bytes: Uint8Array): string {
|
||||
return Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import { StrictMode } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import App from "./App";
|
||||
import "./styles.css";
|
||||
|
||||
const root = document.getElementById("root");
|
||||
if (!root) {
|
||||
throw new Error("Не найден корневой элемент интерфейса Packmate");
|
||||
}
|
||||
|
||||
createRoot(root).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
);
|
||||
@@ -0,0 +1,79 @@
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { PacketView } from "./components/PacketView";
|
||||
import { decodePacket, hexDump, packetSegments } from "./packet";
|
||||
import type { Packet, Pattern } from "./types";
|
||||
|
||||
const pattern: Pattern = {
|
||||
id: 3,
|
||||
enabled: true,
|
||||
deleted: false,
|
||||
name: "Маркер",
|
||||
value: "secret",
|
||||
color: "#ff5959",
|
||||
searchType: "SUBSTRING",
|
||||
directionType: "BOTH",
|
||||
actionType: "FIND",
|
||||
serviceId: null,
|
||||
};
|
||||
|
||||
function packet(text: string): Packet {
|
||||
return {
|
||||
id: 8,
|
||||
matches: [],
|
||||
timestamp: 1_700_000_000_000,
|
||||
incoming: true,
|
||||
ungzipped: false,
|
||||
webSocketParsed: false,
|
||||
tlsDecrypted: false,
|
||||
hasHttpBody: false,
|
||||
content: btoa(String.fromCharCode(...new TextEncoder().encode(text))),
|
||||
};
|
||||
}
|
||||
|
||||
describe("отображение содержимого пакета", () => {
|
||||
it("подсвечивает диапазон совпадения без преобразования байтового содержимого в HTML", () => {
|
||||
const value = packet("до secret после <script>alert(1)</script>");
|
||||
value.matches = [{ patternId: pattern.id, startPosition: 3, endPosition: 8 }];
|
||||
|
||||
const segments = packetSegments(value, [pattern]);
|
||||
expect(segments).toEqual([
|
||||
{ text: "до " },
|
||||
{ text: "secret", pattern },
|
||||
{ text: " после <script>alert(1)</script>" },
|
||||
]);
|
||||
|
||||
const view = render(<PacketView
|
||||
packet={value}
|
||||
patterns={[pattern]}
|
||||
hexdumpMode={false}
|
||||
blockSize={16}
|
||||
lineNumberBase={10}
|
||||
notify={() => undefined}
|
||||
/>);
|
||||
expect(screen.getByText("secret").tagName).toBe("MARK");
|
||||
expect(view.container.querySelector("script")).toBeNull();
|
||||
expect(view.container.textContent).toContain("<script>alert(1)</script>");
|
||||
});
|
||||
|
||||
it("считает диапазон SUBBYTES в байтах, а не UTF-16 позициях", () => {
|
||||
const bytes = new TextEncoder().encode("Жx");
|
||||
const value: Packet = {
|
||||
...packet(""),
|
||||
content: btoa(String.fromCharCode(...bytes)),
|
||||
matches: [{ patternId: 3, startPosition: 2, endPosition: 2 }],
|
||||
};
|
||||
const bytePattern = { ...pattern, searchType: "SUBBYTES" as const, value: "78" };
|
||||
|
||||
expect(packetSegments(value, [bytePattern])).toEqual([
|
||||
{ text: "Ж" },
|
||||
{ text: "x", pattern: bytePattern },
|
||||
]);
|
||||
});
|
||||
|
||||
it("строит читаемые строки HEX-дампа с выбранной шириной", () => {
|
||||
expect(hexDump(decodePacket("AQIDBA=="), 2, 16)).toBe(
|
||||
"0000000000: 01 02 |..|\n0000000002: 03 04 |..|",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import type { FoundPattern, Packet, Pattern, PatternSearchType } from "./types";
|
||||
|
||||
export interface TextSegment {
|
||||
text: string;
|
||||
pattern?: Pattern;
|
||||
}
|
||||
|
||||
export function decodePacket(content: string): Uint8Array {
|
||||
const binary = atob(content);
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let index = 0; index < binary.length; index += 1) {
|
||||
bytes[index] = binary.charCodeAt(index);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
export function packetText(bytes: Uint8Array): string {
|
||||
return new TextDecoder("utf-8", { fatal: false }).decode(bytes);
|
||||
}
|
||||
|
||||
function rangeForMatch(
|
||||
bytes: Uint8Array,
|
||||
match: FoundPattern,
|
||||
searchType: PatternSearchType,
|
||||
): [number, number] {
|
||||
if (searchType !== "SUBBYTES") {
|
||||
return [match.startPosition, match.endPosition + 1];
|
||||
}
|
||||
|
||||
const start = Math.max(0, Math.min(bytes.length, match.startPosition));
|
||||
const end = Math.max(start, Math.min(bytes.length, match.endPosition + 1));
|
||||
return [packetText(bytes.subarray(0, start)).length, packetText(bytes.subarray(0, end)).length];
|
||||
}
|
||||
|
||||
export function packetSegments(packet: Packet, patterns: Pattern[]): TextSegment[] {
|
||||
const bytes = decodePacket(packet.content);
|
||||
const text = packetText(bytes);
|
||||
const byId = new Map(patterns.map((pattern) => [pattern.id, pattern]));
|
||||
const ranges = packet.matches
|
||||
.flatMap((match) => {
|
||||
const pattern = byId.get(match.patternId);
|
||||
if (!pattern || pattern.deleted || pattern.actionType !== "FIND") {
|
||||
return [];
|
||||
}
|
||||
const [start, end] = rangeForMatch(bytes, match, pattern.searchType);
|
||||
const safeStart = Math.max(0, Math.min(text.length, start));
|
||||
const safeEnd = Math.max(safeStart, Math.min(text.length, end));
|
||||
return safeEnd > safeStart ? [{ start: safeStart, end: safeEnd, pattern }] : [];
|
||||
})
|
||||
.sort((left, right) => left.start - right.start || left.end - right.end);
|
||||
|
||||
const segments: TextSegment[] = [];
|
||||
let cursor = 0;
|
||||
for (const range of ranges) {
|
||||
if (range.start < cursor) {
|
||||
continue;
|
||||
}
|
||||
if (range.start > cursor) {
|
||||
segments.push({ text: text.slice(cursor, range.start) });
|
||||
}
|
||||
segments.push({ text: text.slice(range.start, range.end), pattern: range.pattern });
|
||||
cursor = range.end;
|
||||
}
|
||||
if (cursor < text.length || segments.length === 0) {
|
||||
segments.push({ text: text.slice(cursor) });
|
||||
}
|
||||
return segments;
|
||||
}
|
||||
|
||||
export function hexDump(bytes: Uint8Array, blockSize: number, lineNumberBase: number): string {
|
||||
const width = Number.isFinite(blockSize) ? Math.max(1, Math.min(128, Math.trunc(blockSize))) : 16;
|
||||
const base = lineNumberBase === 16 ? 16 : 10;
|
||||
const rows: string[] = [];
|
||||
|
||||
for (let offset = 0; offset < bytes.length; offset += width) {
|
||||
const block = bytes.subarray(offset, Math.min(offset + width, bytes.length));
|
||||
const address = offset.toString(base).padStart(10, "0");
|
||||
const hex = Array.from(block, (byte) => byte.toString(16).padStart(2, "0").toUpperCase());
|
||||
const paddedHex = [...hex, ...Array.from({ length: width - block.length }, () => " ")]
|
||||
.join(" ");
|
||||
const chars = Array.from(block, (byte) =>
|
||||
byte >= 0x20 && byte <= 0x7e ? String.fromCharCode(byte) : ".",
|
||||
).join("");
|
||||
rows.push(`${address}: ${paddedHex} |${chars.padEnd(width, " ")}|`);
|
||||
}
|
||||
|
||||
return rows.join("\n");
|
||||
}
|
||||
|
||||
export function pythonBytes(bytes: Uint8Array): string {
|
||||
return `b'${Array.from(bytes, (byte) => `\\x${byte.toString(16).padStart(2, "0")}`).join("")}'`;
|
||||
}
|
||||
|
||||
export function safePatternColor(color: string): string {
|
||||
if (/^#[\da-f]{3}(?:[\da-f]{3}|[\da-f]{5})?$/i.test(color)) {
|
||||
return color;
|
||||
}
|
||||
if (/^(?:red|green|blue|orange|purple|teal|yellow|white|black|gray|grey)$/i.test(color)) {
|
||||
return color;
|
||||
}
|
||||
return "#ff5959";
|
||||
}
|
||||
@@ -0,0 +1,992 @@
|
||||
:root {
|
||||
color-scheme: light;
|
||||
--topbar: #30343a;
|
||||
--topbar-text: #f4f5f6;
|
||||
--panel: #f7f8f9;
|
||||
--panel-border: #d4d8dd;
|
||||
--text: #22262b;
|
||||
--muted: #68717b;
|
||||
--accent: #087cf0;
|
||||
--request: #fff6f4;
|
||||
--response: #f0f9fc;
|
||||
--highlight: #ffe083;
|
||||
--danger: #d94050;
|
||||
--shadow: 0 5px 18px rgb(0 0 0 / 20%);
|
||||
font-family: "Open Sans", "Segoe UI", Arial, sans-serif;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
font-synthesis: none;
|
||||
text-rendering: optimizeLegibility;
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] {
|
||||
color-scheme: dark;
|
||||
--topbar: #202328;
|
||||
--topbar-text: #f4f5f6;
|
||||
--panel: #24282d;
|
||||
--panel-border: #444b53;
|
||||
--text: #e4e8ec;
|
||||
--muted: #aeb6bf;
|
||||
--accent: #70b3ff;
|
||||
--request: #34383e;
|
||||
--response: #2b5378;
|
||||
--highlight: #79651c;
|
||||
--danger: #ff737f;
|
||||
--shadow: 0 5px 18px rgb(0 0 0 / 45%);
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
min-width: 360px;
|
||||
min-height: 100vh;
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
button,
|
||||
input,
|
||||
select {
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
button {
|
||||
color: inherit;
|
||||
}
|
||||
|
||||
button:focus-visible,
|
||||
input:focus-visible,
|
||||
select:focus-visible,
|
||||
summary:focus-visible {
|
||||
outline: 3px solid #55a8ff;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
cursor: wait;
|
||||
opacity: 0.65;
|
||||
}
|
||||
|
||||
.app-shell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100vh;
|
||||
min-height: 420px;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
z-index: 4;
|
||||
display: flex;
|
||||
min-height: 54px;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
padding: 0 12px;
|
||||
overflow-x: auto;
|
||||
color: var(--topbar-text);
|
||||
background: var(--topbar);
|
||||
box-shadow: 0 2px 7px rgb(0 0 0 / 22%);
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex: none;
|
||||
font-size: 20px;
|
||||
font-weight: 500;
|
||||
letter-spacing: 0.01em;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.brand img {
|
||||
width: 56px;
|
||||
height: 32px;
|
||||
object-fit: cover;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.brand small {
|
||||
font-size: 12px;
|
||||
color: #c5cbd3;
|
||||
}
|
||||
|
||||
.traffic-stats {
|
||||
display: flex;
|
||||
flex: none;
|
||||
gap: 4px;
|
||||
color: #9eb5c8;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.traffic-stats abbr {
|
||||
text-decoration: underline dotted;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
.stats-separator {
|
||||
color: #77818b;
|
||||
}
|
||||
|
||||
.service-tabs {
|
||||
display: flex;
|
||||
min-width: max-content;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.service-tabs > button,
|
||||
.service-tab > button {
|
||||
min-height: 34px;
|
||||
padding: 6px 8px;
|
||||
border: 0;
|
||||
border-radius: 3px;
|
||||
color: #dce2e8;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.service-tabs > button:hover,
|
||||
.service-tab > button:hover,
|
||||
.service-tabs > button.active,
|
||||
.service-tab.active > button {
|
||||
color: #fff;
|
||||
background: #41474f;
|
||||
}
|
||||
|
||||
.service-tab {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.service-tab small {
|
||||
color: #a8b0b8;
|
||||
}
|
||||
|
||||
.service-tab > .service-edit {
|
||||
min-width: 26px;
|
||||
padding: 4px;
|
||||
color: #dce2e8;
|
||||
}
|
||||
|
||||
.service-tabs .add-service {
|
||||
min-width: 32px;
|
||||
color: #c5f1d1;
|
||||
font-size: 21px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.pattern-menu {
|
||||
position: relative;
|
||||
flex: none;
|
||||
}
|
||||
|
||||
.pattern-menu summary {
|
||||
padding: 8px 5px;
|
||||
border-radius: 3px;
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.pattern-menu summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.pattern-menu summary::after {
|
||||
margin-left: 6px;
|
||||
content: "▾";
|
||||
}
|
||||
|
||||
.pattern-menu[open] summary,
|
||||
.pattern-menu summary:hover {
|
||||
color: #fff;
|
||||
background: #41474f;
|
||||
}
|
||||
|
||||
.pattern-popover {
|
||||
position: fixed;
|
||||
top: 48px;
|
||||
left: 192px;
|
||||
z-index: 7;
|
||||
width: min(740px, calc(100vw - 24px));
|
||||
max-height: min(70vh, 720px);
|
||||
padding: 8px;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--panel-border);
|
||||
border-radius: 5px;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.pattern-add,
|
||||
.pattern-all {
|
||||
display: block;
|
||||
width: 100%;
|
||||
padding: 9px 12px;
|
||||
border: 0;
|
||||
border-radius: 3px;
|
||||
color: var(--text);
|
||||
text-align: left;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.pattern-add {
|
||||
color: #fff;
|
||||
text-align: center;
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.pattern-all {
|
||||
margin: 4px 0;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.pattern-row {
|
||||
display: flex;
|
||||
min-height: 44px;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding: 6px 5px;
|
||||
border-top: 1px solid var(--panel-border);
|
||||
}
|
||||
|
||||
.pattern-select {
|
||||
flex: 1;
|
||||
min-width: 180px;
|
||||
padding: 5px;
|
||||
border: 0;
|
||||
color: var(--text);
|
||||
text-align: left;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.pattern-select:disabled {
|
||||
cursor: default;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.pattern-select span {
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.pattern-ignore .pattern-select {
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.disabled-pattern {
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
.pattern-actions {
|
||||
display: flex;
|
||||
flex: none;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.pattern-actions button {
|
||||
padding: 5px 7px;
|
||||
border: 1px solid var(--panel-border);
|
||||
border-radius: 3px;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.pattern-actions button:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.selected-pattern {
|
||||
flex: none;
|
||||
max-width: 210px;
|
||||
overflow: hidden;
|
||||
color: #d5eaff;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.settings-button {
|
||||
flex: none;
|
||||
min-width: 34px;
|
||||
margin-left: auto;
|
||||
padding: 5px;
|
||||
border: 0;
|
||||
color: #e3e8ed;
|
||||
font-size: 19px;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.workspace {
|
||||
display: flex;
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
display: flex;
|
||||
width: 25%;
|
||||
min-width: 235px;
|
||||
max-width: 360px;
|
||||
flex: none;
|
||||
flex-direction: column;
|
||||
border-right: 1px solid var(--panel-border);
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
.sidebar-toolbar {
|
||||
display: flex;
|
||||
min-height: 48px;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 7px 9px;
|
||||
background: linear-gradient(#fff, #eef0f2);
|
||||
}
|
||||
|
||||
:root[data-theme="dark"] .sidebar-toolbar {
|
||||
background: linear-gradient(#2d3238, #25292e);
|
||||
}
|
||||
|
||||
.tool-button {
|
||||
min-width: 34px;
|
||||
height: 34px;
|
||||
padding: 2px 6px;
|
||||
border: 1px solid currentColor;
|
||||
border-radius: 4px;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.pause-button {
|
||||
color: #259b4b;
|
||||
}
|
||||
|
||||
.pause-button.selected {
|
||||
color: #fff;
|
||||
background: #d94250;
|
||||
}
|
||||
|
||||
.favorite-button {
|
||||
color: #dc3545;
|
||||
font-size: 21px;
|
||||
}
|
||||
|
||||
.favorite-button.selected {
|
||||
color: #fff;
|
||||
background: #dc3545;
|
||||
}
|
||||
|
||||
.hex-button {
|
||||
color: #087cf0;
|
||||
}
|
||||
|
||||
.hex-button.selected {
|
||||
color: #fff;
|
||||
background: #087cf0;
|
||||
}
|
||||
|
||||
.file-button {
|
||||
color: #d28b00;
|
||||
}
|
||||
|
||||
.to-top-button {
|
||||
min-width: 36px;
|
||||
margin-left: auto;
|
||||
color: #07859a;
|
||||
font-size: 22px;
|
||||
}
|
||||
|
||||
.stream-search {
|
||||
position: relative;
|
||||
display: flex;
|
||||
padding: 4px 9px 7px;
|
||||
border-bottom: 1px solid var(--panel-border);
|
||||
}
|
||||
|
||||
.stream-search input {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
padding: 7px 28px 7px 9px;
|
||||
border: 1px solid var(--panel-border);
|
||||
border-radius: 4px;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
.stream-search button {
|
||||
position: absolute;
|
||||
top: 7px;
|
||||
right: 14px;
|
||||
border: 0;
|
||||
color: var(--muted);
|
||||
font-size: 19px;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.stream-list {
|
||||
min-height: 0;
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.stream-list ul {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.stream-item {
|
||||
position: relative;
|
||||
border-bottom: 1px solid var(--panel-border);
|
||||
transition: background-color 120ms ease;
|
||||
}
|
||||
|
||||
.stream-item:hover {
|
||||
background: color-mix(in srgb, var(--accent) 8%, var(--panel));
|
||||
}
|
||||
|
||||
.stream-item.stream-selected {
|
||||
background: color-mix(in srgb, var(--accent) 15%, var(--panel));
|
||||
box-shadow: inset 3px 0 var(--accent);
|
||||
}
|
||||
|
||||
.stream-item.stream-favorite {
|
||||
background-color: color-mix(in srgb, #dc3545 9%, var(--panel));
|
||||
}
|
||||
|
||||
.stream-select {
|
||||
display: flex;
|
||||
width: 100%;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 2px;
|
||||
padding: 10px 36px 10px 17px;
|
||||
border: 0;
|
||||
color: var(--text);
|
||||
line-height: 1.35;
|
||||
text-align: left;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.stream-select strong {
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.stream-select time,
|
||||
.stream-ttl {
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.stream-patterns {
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.stream-star {
|
||||
position: absolute;
|
||||
top: 8px;
|
||||
right: 8px;
|
||||
padding: 0 3px;
|
||||
border: 0;
|
||||
color: #d94050;
|
||||
font-size: 19px;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.stream-star.is-favorite {
|
||||
color: #d94050;
|
||||
}
|
||||
|
||||
.list-message {
|
||||
padding: 9px 12px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.load-more {
|
||||
display: block;
|
||||
width: calc(100% - 18px);
|
||||
margin: 9px;
|
||||
padding: 8px;
|
||||
border: 1px solid var(--panel-border);
|
||||
border-radius: 4px;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.load-more:hover {
|
||||
border-color: var(--accent);
|
||||
}
|
||||
|
||||
.packet-pane {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
padding: 14px 22px 24px;
|
||||
overflow: auto;
|
||||
background: var(--panel);
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.packet-legend {
|
||||
position: sticky;
|
||||
top: -14px;
|
||||
z-index: 2;
|
||||
display: flex;
|
||||
min-height: 38px;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
padding: 3px 0;
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
.legend-request {
|
||||
padding: 1px 3px;
|
||||
background: var(--request);
|
||||
box-shadow: 0 0 3px 3px var(--request);
|
||||
}
|
||||
|
||||
.legend-response {
|
||||
padding: 1px 3px;
|
||||
background: var(--response);
|
||||
box-shadow: 0 0 3px 3px var(--response);
|
||||
}
|
||||
|
||||
.socket-state {
|
||||
margin-left: auto;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.theme-toggle {
|
||||
margin-left: 10px;
|
||||
padding: 5px 7px;
|
||||
border: 1px solid var(--panel-border);
|
||||
border-radius: 3px;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.stream-heading {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 7px 14px;
|
||||
margin: 1px 0 10px;
|
||||
padding: 8px 10px;
|
||||
border-bottom: 1px solid var(--panel-border);
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.stream-heading strong {
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
.empty-detail {
|
||||
margin: 32px 0;
|
||||
color: var(--muted);
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.packet {
|
||||
margin: 0 0 14px;
|
||||
padding: 7px 0 9px;
|
||||
border-bottom: 1px solid var(--panel-border);
|
||||
box-shadow: 0 5px 8px -9px #4b4e51;
|
||||
}
|
||||
|
||||
.packet-request {
|
||||
background: var(--request);
|
||||
}
|
||||
|
||||
.packet-response {
|
||||
background: var(--response);
|
||||
}
|
||||
|
||||
.packet-header {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 6px 12px;
|
||||
padding: 2px 6px 7px;
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--panel-border) 75%, transparent);
|
||||
}
|
||||
|
||||
.packet-meta,
|
||||
.packet-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 4px 10px;
|
||||
}
|
||||
|
||||
.packet-meta time,
|
||||
.packet-meta > span {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.packet-direction {
|
||||
color: var(--text) !important;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.packet-flag {
|
||||
padding: 1px 4px;
|
||||
border: 1px solid var(--panel-border);
|
||||
border-radius: 3px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.text-button {
|
||||
padding: 2px 0;
|
||||
border: 0;
|
||||
color: var(--accent);
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.text-button:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.packet-content {
|
||||
margin: 0;
|
||||
padding: 11px 7px 8px;
|
||||
overflow-x: auto;
|
||||
color: var(--text);
|
||||
font-family: "Ubuntu Mono", "Cascadia Mono", "Liberation Mono", monospace;
|
||||
font-size: 13px;
|
||||
line-height: 1.55;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
tab-size: 4;
|
||||
}
|
||||
|
||||
.packet-content mark {
|
||||
padding: 0 1px;
|
||||
color: #151515;
|
||||
box-shadow: 0 0 1px 1px currentColor;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.packet-more,
|
||||
.packet-end {
|
||||
max-width: 420px;
|
||||
margin: 12px auto;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.muted {
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.notice {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin: 0 0 8px;
|
||||
padding: 7px 10px;
|
||||
border: 1px solid color-mix(in srgb, var(--accent) 35%, var(--panel-border));
|
||||
border-radius: 4px;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
box-shadow: 0 2px 6px rgb(0 0 0 / 10%);
|
||||
}
|
||||
|
||||
.notice button {
|
||||
border: 0;
|
||||
color: var(--muted);
|
||||
font-size: 19px;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.statusbar {
|
||||
min-height: 22px;
|
||||
padding: 3px 9px;
|
||||
border-top: 1px solid var(--panel-border);
|
||||
color: var(--muted);
|
||||
font-size: 11px;
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
.dialog-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 10;
|
||||
display: grid;
|
||||
align-items: center;
|
||||
justify-items: center;
|
||||
padding: 18px;
|
||||
overflow: auto;
|
||||
background: rgb(0 0 0 / 55%);
|
||||
}
|
||||
|
||||
.dialog {
|
||||
width: min(780px, 100%);
|
||||
max-height: min(92vh, 980px);
|
||||
overflow: auto;
|
||||
border: 1px solid #727982;
|
||||
border-radius: 7px;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.dialog-header {
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
padding: 13px 20px;
|
||||
border-bottom: 1px solid var(--panel-border);
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
.dialog-header h2 {
|
||||
margin: 0;
|
||||
font-size: clamp(20px, 3vw, 28px);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.dialog-close {
|
||||
padding: 0 5px;
|
||||
border: 0;
|
||||
color: var(--muted);
|
||||
font-size: 27px;
|
||||
background: transparent;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.dialog-body {
|
||||
padding: 16px 20px 20px;
|
||||
}
|
||||
|
||||
.form-field {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.form-field > span {
|
||||
font-size: 16px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.form-field input:not([type="checkbox"]):not([type="color"]),
|
||||
.form-field select {
|
||||
width: 100%;
|
||||
min-height: 42px;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid #adb5bd;
|
||||
border-radius: 4px;
|
||||
color: var(--text);
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
.form-field input[type="color"] {
|
||||
width: 100%;
|
||||
height: 44px;
|
||||
padding: 4px;
|
||||
border: 1px solid var(--panel-border);
|
||||
border-radius: 4px;
|
||||
background: var(--panel);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.form-field small {
|
||||
color: var(--muted);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.service-options {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
margin: 5px 0 20px;
|
||||
padding: 12px 13px;
|
||||
border: 1px solid var(--panel-border);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.service-options legend {
|
||||
padding: 0 6px;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.service-options label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 9px;
|
||||
}
|
||||
|
||||
.service-options input {
|
||||
width: 17px;
|
||||
height: 17px;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
|
||||
.dialog-actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
gap: 8px;
|
||||
margin-top: 20px;
|
||||
padding-top: 14px;
|
||||
border-top: 1px solid var(--panel-border);
|
||||
}
|
||||
|
||||
.dialog-actions button {
|
||||
min-height: 38px;
|
||||
padding: 8px 14px;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.button-primary {
|
||||
color: #fff;
|
||||
background: #087cf0;
|
||||
}
|
||||
|
||||
.button-secondary {
|
||||
color: #fff;
|
||||
background: #68717b;
|
||||
}
|
||||
|
||||
.button-danger {
|
||||
color: #fff;
|
||||
background: #d94050;
|
||||
}
|
||||
|
||||
.dialog-delete {
|
||||
margin-right: auto;
|
||||
}
|
||||
|
||||
.validation-message {
|
||||
color: var(--danger);
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.topbar {
|
||||
gap: 8px;
|
||||
padding: 0 8px;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
width: 32%;
|
||||
min-width: 210px;
|
||||
}
|
||||
|
||||
.packet-pane {
|
||||
padding-right: 14px;
|
||||
padding-left: 14px;
|
||||
}
|
||||
|
||||
.selected-pattern {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 650px) {
|
||||
body {
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.app-shell {
|
||||
height: auto;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
.topbar {
|
||||
flex-wrap: wrap;
|
||||
min-height: 54px;
|
||||
padding: 6px 8px;
|
||||
}
|
||||
|
||||
.brand {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.service-tabs {
|
||||
order: 5;
|
||||
width: 100%;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.workspace {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.sidebar {
|
||||
width: 100%;
|
||||
max-width: none;
|
||||
min-width: 0;
|
||||
max-height: 45vh;
|
||||
border-right: 0;
|
||||
border-bottom: 1px solid var(--panel-border);
|
||||
}
|
||||
|
||||
.stream-list {
|
||||
max-height: calc(45vh - 94px);
|
||||
}
|
||||
|
||||
.packet-pane {
|
||||
min-height: 48vh;
|
||||
padding: 9px 10px 20px;
|
||||
}
|
||||
|
||||
.pattern-popover {
|
||||
top: 48px;
|
||||
left: 8px;
|
||||
}
|
||||
|
||||
.pattern-row {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.pattern-actions {
|
||||
flex-wrap: wrap;
|
||||
padding-left: 5px;
|
||||
}
|
||||
|
||||
.statusbar {
|
||||
position: sticky;
|
||||
bottom: 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import "@testing-library/jest-dom/vitest";
|
||||
import { cleanup } from "@testing-library/react";
|
||||
import { afterEach } from "vitest";
|
||||
|
||||
afterEach(cleanup);
|
||||
@@ -0,0 +1,80 @@
|
||||
export type PatternSearchType = "REGEX" | "SUBSTRING" | "SUBBYTES";
|
||||
export type PatternDirectionType = "INPUT" | "OUTPUT" | "BOTH";
|
||||
export type PatternActionType = "FIND" | "IGNORE";
|
||||
|
||||
export interface Service {
|
||||
port: number;
|
||||
name: string;
|
||||
decryptTls: boolean;
|
||||
http: boolean;
|
||||
urldecodeHttpRequests: boolean;
|
||||
mergeAdjacentPackets: boolean;
|
||||
parseWebSockets: boolean;
|
||||
}
|
||||
|
||||
export interface Pattern {
|
||||
id: number;
|
||||
enabled: boolean;
|
||||
deleted: boolean;
|
||||
name: string;
|
||||
value: string;
|
||||
color: string;
|
||||
searchType: PatternSearchType;
|
||||
directionType: PatternDirectionType;
|
||||
actionType: PatternActionType;
|
||||
serviceId: number | null;
|
||||
}
|
||||
|
||||
export interface PatternInput extends Omit<Pattern, "id" | "enabled" | "deleted"> {
|
||||
id?: number;
|
||||
}
|
||||
|
||||
export interface Stream {
|
||||
id: number;
|
||||
service: number;
|
||||
protocol: string;
|
||||
startTimestamp: number;
|
||||
endTimestamp: number;
|
||||
foundPatternsIds: number[];
|
||||
favorite: boolean;
|
||||
ttl: number;
|
||||
userAgentHash: string | null;
|
||||
sizeBytes: number;
|
||||
packetsCount: number;
|
||||
}
|
||||
|
||||
export interface FoundPattern {
|
||||
patternId: number;
|
||||
startPosition: number;
|
||||
endPosition: number;
|
||||
}
|
||||
|
||||
export interface Packet {
|
||||
id: number;
|
||||
matches: FoundPattern[];
|
||||
timestamp: number;
|
||||
incoming: boolean;
|
||||
ungzipped: boolean;
|
||||
webSocketParsed: boolean;
|
||||
tlsDecrypted: boolean;
|
||||
hasHttpBody: boolean;
|
||||
content: string;
|
||||
}
|
||||
|
||||
export interface RouteState {
|
||||
servicePort?: number;
|
||||
streamId?: number;
|
||||
patternId?: number;
|
||||
}
|
||||
|
||||
export interface CountersUpdate {
|
||||
totalPackets: number;
|
||||
totalStreams: number;
|
||||
servicesPackets: Record<string, number>;
|
||||
servicesStreams: Record<string, number>;
|
||||
}
|
||||
|
||||
export interface SubscriptionMessage {
|
||||
type: string;
|
||||
value: unknown;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/// <reference types="vite/client" />
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"useDefineForClassFields": true,
|
||||
"lib": ["ES2022", "DOM", "DOM.Iterable"],
|
||||
"module": "ESNext",
|
||||
"skipLibCheck": true,
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
"strict": true,
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"noFallthroughCasesInSwitch": true,
|
||||
"noUncheckedIndexedAccess": true,
|
||||
"noImplicitOverride": true
|
||||
},
|
||||
"include": ["src", "vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import react from "@vitejs/plugin-react";
|
||||
import { defineConfig } from "vitest/config";
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react()],
|
||||
base: "/",
|
||||
server: {
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: process.env.PACKMATE_API_ORIGIN ?? "http://127.0.0.1:65000",
|
||||
changeOrigin: true,
|
||||
ws: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
test: {
|
||||
environment: "happy-dom",
|
||||
setupFiles: ["./src/test/setup.ts"],
|
||||
restoreMocks: true,
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
pluginManagement {
|
||||
repositories {
|
||||
gradlePluginPortal()
|
||||
}
|
||||
}
|
||||
rootProject.name = "packmate"
|
||||
@@ -0,0 +1,13 @@
|
||||
package ru.serega6531.packmate;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class PackmateApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(PackmateApplication.class, args);
|
||||
}
|
||||
|
||||
}
|
||||
+69
@@ -0,0 +1,69 @@
|
||||
package ru.serega6531.packmate.configuration;
|
||||
|
||||
import org.modelmapper.Converter;
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.modelmapper.TypeMap;
|
||||
import org.pcap4j.core.PcapNativeException;
|
||||
import org.springframework.boot.context.properties.ConfigurationPropertiesScan;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import ru.serega6531.packmate.model.Pattern;
|
||||
import ru.serega6531.packmate.model.Stream;
|
||||
import ru.serega6531.packmate.model.pojo.StreamDto;
|
||||
import ru.serega6531.packmate.pcap.FilePcapWorker;
|
||||
import ru.serega6531.packmate.pcap.LivePcapWorker;
|
||||
import ru.serega6531.packmate.pcap.NoOpPcapWorker;
|
||||
import ru.serega6531.packmate.pcap.PcapWorker;
|
||||
import ru.serega6531.packmate.properties.PackmateProperties;
|
||||
import ru.serega6531.packmate.service.ServicesService;
|
||||
import ru.serega6531.packmate.service.StreamService;
|
||||
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Configuration
|
||||
@EnableScheduling
|
||||
@EnableAsync
|
||||
@ConfigurationPropertiesScan("ru.serega6531.packmate.properties")
|
||||
public class ApplicationConfiguration {
|
||||
|
||||
@Bean(destroyMethod = "shutdown")
|
||||
public PcapWorker pcapWorker(ServicesService servicesService,
|
||||
StreamService streamService,
|
||||
PackmateProperties properties
|
||||
) throws PcapNativeException, UnknownHostException {
|
||||
return switch (properties.captureMode()) {
|
||||
case LIVE -> new LivePcapWorker(servicesService, streamService, properties.localIp(), properties.interfaceName());
|
||||
case FILE ->
|
||||
new FilePcapWorker(servicesService, streamService, properties.localIp(), properties.pcapFile());
|
||||
case VIEW -> new NoOpPcapWorker();
|
||||
};
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ModelMapper modelMapper() {
|
||||
ModelMapper modelMapper = new ModelMapper();
|
||||
|
||||
addStreamMapper(modelMapper);
|
||||
|
||||
return modelMapper;
|
||||
}
|
||||
|
||||
private void addStreamMapper(ModelMapper modelMapper) {
|
||||
TypeMap<Stream, StreamDto> streamMapper = modelMapper.createTypeMap(Stream.class, StreamDto.class);
|
||||
|
||||
Converter<Set<Pattern>, Set<Integer>> patternSetToIdSet = ctx -> ctx.getSource()
|
||||
.stream()
|
||||
.map(Pattern::getId)
|
||||
.collect(Collectors.toSet());
|
||||
|
||||
streamMapper.addMappings(mapping ->
|
||||
mapping.using(patternSetToIdSet)
|
||||
.map(Stream::getFoundPatterns, StreamDto::setFoundPatternsIds)
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package ru.serega6531.packmate.configuration;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.net.URI;
|
||||
import java.net.URISyntaxException;
|
||||
import java.util.Locale;
|
||||
import java.util.Set;
|
||||
|
||||
final class SameOriginMutationFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final Set<String> SAFE_METHODS = Set.of("GET", "HEAD", "OPTIONS", "TRACE");
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
FilterChain filterChain
|
||||
) throws ServletException, IOException {
|
||||
String path = request.getRequestURI();
|
||||
boolean apiMutation = path.startsWith("/api/")
|
||||
&& !SAFE_METHODS.contains(request.getMethod().toUpperCase(Locale.ROOT));
|
||||
boolean websocketHandshake = (path.equals("/api/ws") || path.startsWith("/api/ws/"))
|
||||
&& "websocket".equalsIgnoreCase(request.getHeader("Upgrade"));
|
||||
if ((apiMutation || websocketHandshake)
|
||||
&& !isSameOrigin(request)) {
|
||||
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
|
||||
response.setContentType("application/json");
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
response.getWriter().write("{\"message\":\"Источник запроса не совпадает с адресом Packmate.\"}");
|
||||
return;
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
private boolean isSameOrigin(HttpServletRequest request) {
|
||||
String originHeader = request.getHeader("Origin");
|
||||
if (originHeader == null || originHeader.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
URI origin = new URI(originHeader);
|
||||
String scheme = request.getScheme();
|
||||
if (!origin.isAbsolute()
|
||||
|| origin.getHost() == null
|
||||
|| origin.getUserInfo() != null
|
||||
|| origin.getRawQuery() != null
|
||||
|| origin.getRawFragment() != null
|
||||
|| (origin.getRawPath() != null && !origin.getRawPath().isEmpty())
|
||||
|| scheme == null
|
||||
|| !origin.getScheme().equalsIgnoreCase(scheme)
|
||||
|| !origin.getHost().equalsIgnoreCase(request.getServerName())) {
|
||||
return false;
|
||||
}
|
||||
|
||||
int originPort = origin.getPort() == -1 ? defaultPort(origin.getScheme()) : origin.getPort();
|
||||
return originPort == request.getServerPort();
|
||||
} catch (URISyntaxException | IllegalArgumentException exception) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private int defaultPort(String scheme) {
|
||||
if ("http".equalsIgnoreCase(scheme)) {
|
||||
return 80;
|
||||
}
|
||||
if ("https".equalsIgnoreCase(scheme)) {
|
||||
return 443;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package ru.serega6531.packmate.configuration;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.security.authentication.event.AuthenticationFailureBadCredentialsEvent;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.core.userdetails.User;
|
||||
import org.springframework.security.core.userdetails.UserDetails;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;
|
||||
import ru.serega6531.packmate.properties.PackmateProperties;
|
||||
import org.springframework.security.config.Customizer;
|
||||
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
@Slf4j
|
||||
public class SecurityConfiguration {
|
||||
|
||||
@Bean
|
||||
public InMemoryUserDetailsManager userDetailsService(PackmateProperties properties, PasswordEncoder passwordEncoder) {
|
||||
if (properties.web().accountLogin() == null || properties.web().accountLogin().isBlank()) {
|
||||
throw new IllegalStateException("Нужно задать PACKMATE_USERNAME.");
|
||||
}
|
||||
if (properties.web().accountPassword() == null || properties.web().accountPassword().isBlank()) {
|
||||
throw new IllegalStateException("Нужно задать PACKMATE_PASSWORD.");
|
||||
}
|
||||
|
||||
UserDetails user = User.builder()
|
||||
.username(properties.web().accountLogin())
|
||||
.password(passwordEncoder.encode(properties.web().accountPassword()))
|
||||
.roles("USER")
|
||||
.build();
|
||||
|
||||
return new InMemoryUserDetailsManager(user);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
return http
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.addFilterBefore(new SameOriginMutationFilter(), BasicAuthenticationFilter.class)
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
.requestMatchers("/healthz", "/site.webmanifest").permitAll()
|
||||
.anyRequest().authenticated()
|
||||
)
|
||||
.httpBasic(Customizer.withDefaults())
|
||||
.headers(headers -> headers.frameOptions(frameOptions -> frameOptions.sameOrigin()))
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@EventListener
|
||||
public void authenticationFailed(AuthenticationFailureBadCredentialsEvent e) {
|
||||
log.info("Неудачная попытка входа");
|
||||
}
|
||||
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package ru.serega6531.packmate.configuration;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.socket.config.annotation.EnableWebSocket;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
|
||||
import org.springframework.web.socket.config.annotation.WebSocketHandlerRegistry;
|
||||
import ru.serega6531.packmate.controller.WebSocketHandler;
|
||||
|
||||
@EnableWebSocket
|
||||
@Configuration
|
||||
public class WebSocketConfiguration implements WebSocketConfigurer {
|
||||
|
||||
private final WebSocketHandler webSocketHandler;
|
||||
|
||||
@Autowired
|
||||
public WebSocketConfiguration(WebSocketHandler webSocketHandler) {
|
||||
this.webSocketHandler = webSocketHandler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
|
||||
registry.addHandler(webSocketHandler, "/api/ws");
|
||||
}
|
||||
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package ru.serega6531.packmate.controller;
|
||||
|
||||
import org.springframework.stereotype.Controller;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
|
||||
@Controller
|
||||
public class FrontendController {
|
||||
|
||||
@GetMapping("/{servicePort:[0-9]+}")
|
||||
public String serviceRoute() {
|
||||
return "forward:/index.html";
|
||||
}
|
||||
|
||||
@GetMapping("/{servicePort:[0-9]+}/{streamId:[0-9]+}")
|
||||
public String streamRoute() {
|
||||
return "forward:/index.html";
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package ru.serega6531.packmate.controller;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
@RestController
|
||||
public class HealthController {
|
||||
|
||||
@GetMapping("/healthz")
|
||||
public ResponseEntity<Void> health() {
|
||||
return ResponseEntity.ok().build();
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package ru.serega6531.packmate.controller;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.serega6531.packmate.model.pojo.PacketDto;
|
||||
import ru.serega6531.packmate.model.pojo.PacketPagination;
|
||||
import ru.serega6531.packmate.service.StreamService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/packet/")
|
||||
public class PacketController {
|
||||
|
||||
private final StreamService streamService;
|
||||
|
||||
@Autowired
|
||||
public PacketController(StreamService streamService) {
|
||||
this.streamService = streamService;
|
||||
}
|
||||
|
||||
@PostMapping("/{streamId}")
|
||||
public List<PacketDto> getPacketsForStream(@PathVariable long streamId, @RequestBody PacketPagination pagination) {
|
||||
return streamService.getPackets(streamId, pagination.getStartingFrom(), pagination.getPageSize());
|
||||
}
|
||||
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package ru.serega6531.packmate.controller;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.serega6531.packmate.model.pojo.PatternCreateDto;
|
||||
import ru.serega6531.packmate.model.pojo.PatternDto;
|
||||
import ru.serega6531.packmate.model.pojo.PatternUpdateDto;
|
||||
import ru.serega6531.packmate.service.PatternService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/pattern/")
|
||||
public class PatternController {
|
||||
|
||||
private final PatternService service;
|
||||
|
||||
@Autowired
|
||||
public PatternController(PatternService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<PatternDto> getPatterns() {
|
||||
return service.findAll()
|
||||
.stream().map(service::toDto)
|
||||
.toList();
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/enable")
|
||||
public void enable(@PathVariable int id, @RequestParam boolean enabled) {
|
||||
service.enable(id, enabled);
|
||||
}
|
||||
|
||||
@DeleteMapping("/{id}")
|
||||
public void delete(@PathVariable int id) {
|
||||
service.delete(id);
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/lookback")
|
||||
public void lookBack(@PathVariable int id, @RequestBody int minutes) {
|
||||
service.lookBack(id, minutes);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public PatternDto addPattern(@RequestBody PatternCreateDto dto) {
|
||||
return service.create(dto);
|
||||
}
|
||||
|
||||
@PostMapping("/{id}")
|
||||
public PatternDto updatePattern(@PathVariable int id, @RequestBody PatternUpdateDto dto) {
|
||||
return service.update(id, dto);
|
||||
}
|
||||
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package ru.serega6531.packmate.controller;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import ru.serega6531.packmate.exception.PatternValidationException;
|
||||
import ru.serega6531.packmate.exception.RequestValidationException;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class PatternValidationHandler {
|
||||
|
||||
@ExceptionHandler(PatternValidationException.class)
|
||||
public ResponseEntity<Map<String, String>> handleInvalidPattern(PatternValidationException exception) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("message", exception.getMessage()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(RequestValidationException.class)
|
||||
public ResponseEntity<Map<String, String>> handleInvalidRequest(RequestValidationException exception) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(Map.of("message", exception.getMessage()));
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package ru.serega6531.packmate.controller;
|
||||
|
||||
import org.pcap4j.core.PcapNativeException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.serega6531.packmate.service.PcapService;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/pcap/")
|
||||
public class PcapController {
|
||||
|
||||
private final PcapService service;
|
||||
|
||||
@Autowired
|
||||
public PcapController(PcapService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@GetMapping("/started")
|
||||
public boolean started() {
|
||||
return service.isStarted();
|
||||
}
|
||||
|
||||
@PostMapping("/start")
|
||||
public void start() throws PcapNativeException {
|
||||
service.start();
|
||||
}
|
||||
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package ru.serega6531.packmate.controller;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.serega6531.packmate.model.pojo.ServiceCreateDto;
|
||||
import ru.serega6531.packmate.model.pojo.ServiceDto;
|
||||
import ru.serega6531.packmate.model.pojo.ServiceUpdateDto;
|
||||
import ru.serega6531.packmate.service.ServicesService;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/service/")
|
||||
public class ServiceController {
|
||||
|
||||
private final ServicesService service;
|
||||
|
||||
@Autowired
|
||||
public ServiceController(ServicesService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
public List<ServiceDto> getServices() {
|
||||
return service.findAll();
|
||||
}
|
||||
|
||||
@DeleteMapping("/{port}")
|
||||
public void deleteService(@PathVariable int port) {
|
||||
service.deleteByPort(port);
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
public ServiceDto addService(@RequestBody ServiceCreateDto dto) {
|
||||
return this.service.create(dto);
|
||||
}
|
||||
|
||||
@PostMapping("/{port}")
|
||||
public ServiceDto updateService(@PathVariable int port, @RequestBody ServiceUpdateDto dto) {
|
||||
return this.service.update(port, dto);
|
||||
}
|
||||
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package ru.serega6531.packmate.controller;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import ru.serega6531.packmate.model.pojo.StreamDto;
|
||||
import ru.serega6531.packmate.model.pojo.StreamPagination;
|
||||
import ru.serega6531.packmate.service.StreamService;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/stream/")
|
||||
public class StreamController {
|
||||
|
||||
private final StreamService service;
|
||||
|
||||
@Autowired
|
||||
public StreamController(StreamService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@PostMapping("/all")
|
||||
public List<StreamDto> getStreams(@RequestBody StreamPagination pagination) {
|
||||
return service.findAll(pagination, Optional.empty(), pagination.isFavorites());
|
||||
}
|
||||
|
||||
@PostMapping("/{port}")
|
||||
public List<StreamDto> getStreams(@PathVariable int port, @RequestBody StreamPagination pagination) {
|
||||
return service.findAll(pagination, Optional.of(port), pagination.isFavorites());
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/favorite")
|
||||
public void favoriteStream(@PathVariable long id) {
|
||||
service.setFavorite(id, true);
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/unfavorite")
|
||||
public void unfavoriteStream(@PathVariable long id) {
|
||||
service.setFavorite(id, false);
|
||||
}
|
||||
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package ru.serega6531.packmate.controller;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.socket.CloseStatus;
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
import org.springframework.web.socket.handler.TextWebSocketHandler;
|
||||
import ru.serega6531.packmate.service.SubscriptionService;
|
||||
|
||||
@SuppressWarnings("NullableProblems")
|
||||
@Component
|
||||
public class WebSocketHandler extends TextWebSocketHandler {
|
||||
|
||||
private final SubscriptionService subscriptionService;
|
||||
|
||||
@Autowired
|
||||
public WebSocketHandler(SubscriptionService subscriptionService) {
|
||||
this.subscriptionService = subscriptionService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterConnectionEstablished(WebSocketSession session) {
|
||||
subscriptionService.addSubscriber(session);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) {
|
||||
subscriptionService.removeSubscriber(session);
|
||||
}
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package ru.serega6531.packmate.exception;
|
||||
|
||||
public class PatternValidationException extends RuntimeException {
|
||||
|
||||
public PatternValidationException(String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package ru.serega6531.packmate.exception;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Data
|
||||
public class PcapFileNotFoundException extends RuntimeException {
|
||||
|
||||
private final File file;
|
||||
private final File directory;
|
||||
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package ru.serega6531.packmate.exception;
|
||||
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
@Data
|
||||
public class PcapInterfaceNotFoundException extends RuntimeException {
|
||||
|
||||
private final String requestedInterface;
|
||||
private final List<String> existingInterfaces;
|
||||
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package ru.serega6531.packmate.exception;
|
||||
|
||||
public class RequestValidationException extends RuntimeException {
|
||||
|
||||
public RequestValidationException(String message) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
+41
@@ -0,0 +1,41 @@
|
||||
package ru.serega6531.packmate.exception.analyzer;
|
||||
|
||||
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer;
|
||||
import org.springframework.boot.diagnostics.FailureAnalysis;
|
||||
import ru.serega6531.packmate.exception.PcapFileNotFoundException;
|
||||
|
||||
import java.io.File;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
public class PcapFileNotFoundFailureAnalyzer extends AbstractFailureAnalyzer<PcapFileNotFoundException> {
|
||||
@Override
|
||||
protected FailureAnalysis analyze(Throwable rootFailure, PcapFileNotFoundException cause) {
|
||||
String description = "Файл " + cause.getFile().getAbsolutePath() + " не найден.";
|
||||
String existingFilesMessage;
|
||||
|
||||
File[] existingFiles = cause.getDirectory().listFiles();
|
||||
|
||||
if (existingFiles == null) {
|
||||
return new FailureAnalysis(
|
||||
description,
|
||||
"Поместите файл PCAP в каталог ./pcaps. Сейчас этого каталога нет.",
|
||||
cause
|
||||
);
|
||||
}
|
||||
|
||||
if (existingFiles.length == 0) {
|
||||
existingFilesMessage = "Каталог ./pcaps пуст.";
|
||||
} else {
|
||||
List<String> existingFilesNames = Arrays.stream(existingFiles).map(File::getName).toList();
|
||||
existingFilesMessage = "В каталоге " + cause.getDirectory().getAbsolutePath() + " найдены файлы: " + existingFilesNames;
|
||||
}
|
||||
|
||||
return new FailureAnalysis(
|
||||
description,
|
||||
"Проверьте имя файла и поместите его в каталог ./pcaps.\n" +
|
||||
existingFilesMessage,
|
||||
cause
|
||||
);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package ru.serega6531.packmate.exception.analyzer;
|
||||
|
||||
import org.springframework.boot.diagnostics.AbstractFailureAnalyzer;
|
||||
import org.springframework.boot.diagnostics.FailureAnalysis;
|
||||
import ru.serega6531.packmate.exception.PcapInterfaceNotFoundException;
|
||||
|
||||
public class PcapInterfaceNotFoundFailureAnalyzer extends AbstractFailureAnalyzer<PcapInterfaceNotFoundException> {
|
||||
@Override
|
||||
protected FailureAnalysis analyze(Throwable rootFailure, PcapInterfaceNotFoundException cause) {
|
||||
return new FailureAnalysis(
|
||||
"Сетевой интерфейс \"" + cause.getRequestedInterface() + "\" не найден.",
|
||||
"Проверьте PACKMATE_INTERFACE_NAME. Доступные интерфейсы: " + cause.getExistingInterfaces(),
|
||||
cause
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package ru.serega6531.packmate.model;
|
||||
|
||||
import lombok.*;
|
||||
import org.hibernate.Hibernate;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.Table;
|
||||
import java.util.Objects;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@RequiredArgsConstructor
|
||||
@Entity
|
||||
@Table(name = "service")
|
||||
public class CtfService {
|
||||
|
||||
@Id
|
||||
private Integer port;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
private boolean decryptTls;
|
||||
|
||||
private boolean http;
|
||||
|
||||
private boolean urldecodeHttpRequests;
|
||||
|
||||
private boolean mergeAdjacentPackets;
|
||||
|
||||
private boolean parseWebSockets;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
|
||||
CtfService that = (CtfService) o;
|
||||
return port != null && Objects.equals(port, that.port);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return getClass().hashCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package ru.serega6531.packmate.model;
|
||||
|
||||
import lombok.*;
|
||||
import org.hibernate.Hibernate;
|
||||
import org.hibernate.annotations.GenericGenerator;
|
||||
import org.hibernate.annotations.Parameter;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.util.Objects;
|
||||
|
||||
@Entity
|
||||
@GenericGenerator(
|
||||
name = "found_pattern_generator",
|
||||
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
|
||||
parameters = {
|
||||
@Parameter(name = "sequence_name", value = "found_pattern_seq"),
|
||||
@Parameter(name = "initial_value", value = "1"),
|
||||
@Parameter(name = "increment_size", value = "2000"),
|
||||
@Parameter(name = "optimizer", value = "hilo")
|
||||
}
|
||||
)
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
@Builder
|
||||
@Getter
|
||||
@ToString
|
||||
@Table(indexes = { @Index(name = "found_pattern_packet_id_index", columnList = "packet_id DESC") })
|
||||
public class FoundPattern {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "found_pattern_generator")
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(optional = false)
|
||||
@JoinColumn(name = "packet_id", nullable = false)
|
||||
@Setter
|
||||
private Packet packet;
|
||||
|
||||
private int patternId;
|
||||
|
||||
private int startPosition;
|
||||
|
||||
private int endPosition;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
|
||||
FoundPattern that = (FoundPattern) o;
|
||||
return id != null && Objects.equals(id, that.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return getClass().hashCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package ru.serega6531.packmate.model;
|
||||
|
||||
import lombok.*;
|
||||
import org.hibernate.Hibernate;
|
||||
import org.hibernate.annotations.GenericGenerator;
|
||||
import org.hibernate.annotations.Parameter;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@RequiredArgsConstructor
|
||||
@Entity
|
||||
@GenericGenerator(
|
||||
name = "packet_generator",
|
||||
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
|
||||
parameters = {
|
||||
@Parameter(name = "sequence_name", value = "packet_seq"),
|
||||
@Parameter(name = "initial_value", value = "1"),
|
||||
@Parameter(name = "increment_size", value = "20000"),
|
||||
@Parameter(name = "optimizer", value = "hilo")
|
||||
}
|
||||
)
|
||||
@AllArgsConstructor
|
||||
@Builder(toBuilder = true)
|
||||
@Table(indexes = { @Index(name = "stream_id_index", columnList = "stream_id") })
|
||||
public class Packet {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(generator = "packet_generator")
|
||||
private Long id;
|
||||
|
||||
@Transient
|
||||
private Long tempId;
|
||||
|
||||
@Transient
|
||||
private int ttl;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "stream_id", nullable = false)
|
||||
private Stream stream;
|
||||
|
||||
@OneToMany(mappedBy = "packet", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
private Set<FoundPattern> matches;
|
||||
|
||||
private long timestamp;
|
||||
|
||||
private boolean incoming; // true, если пакет идет от клиента к серверу.
|
||||
|
||||
private boolean httpProcessed = false;
|
||||
|
||||
private boolean webSocketParsed = false;
|
||||
|
||||
private boolean tlsDecrypted = false;
|
||||
|
||||
private boolean hasHttpBody = false;
|
||||
|
||||
@Column(nullable = false)
|
||||
private byte[] content;
|
||||
|
||||
@Transient
|
||||
public String getContentString() {
|
||||
return new String(content);
|
||||
}
|
||||
|
||||
public String toString() {
|
||||
return "Packet(id=" + id + ", content=" + getContentString() + ")";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
|
||||
Packet packet = (Packet) o;
|
||||
return id != null && Objects.equals(id, packet.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return getClass().hashCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package ru.serega6531.packmate.model;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.GeneratedValue;
|
||||
import jakarta.persistence.Id;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.hibernate.Hibernate;
|
||||
import org.hibernate.annotations.GenericGenerator;
|
||||
import org.hibernate.annotations.Parameter;
|
||||
import ru.serega6531.packmate.model.enums.PatternActionType;
|
||||
import ru.serega6531.packmate.model.enums.PatternDirectionType;
|
||||
import ru.serega6531.packmate.model.enums.PatternSearchType;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@RequiredArgsConstructor
|
||||
@ToString
|
||||
@Entity(name = "pattern")
|
||||
@GenericGenerator(
|
||||
name = "pattern_generator",
|
||||
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
|
||||
parameters = {
|
||||
@Parameter(name = "sequence_name", value = "pattern_seq"),
|
||||
@Parameter(name = "initial_value", value = "1"),
|
||||
@Parameter(name = "increment_size", value = "1")
|
||||
}
|
||||
)
|
||||
public class Pattern {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(generator = "pattern_generator")
|
||||
private Integer id;
|
||||
|
||||
@Column(nullable = false)
|
||||
private boolean enabled;
|
||||
|
||||
@Column(nullable = false)
|
||||
private boolean deleted = false;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String name;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String value;
|
||||
|
||||
@Column(nullable = false)
|
||||
private String color; // Цвет для CSS.
|
||||
|
||||
@Enumerated
|
||||
@Column(nullable = false)
|
||||
private PatternSearchType searchType;
|
||||
|
||||
@Enumerated
|
||||
@Column(nullable = false)
|
||||
private PatternDirectionType directionType;
|
||||
|
||||
@Enumerated
|
||||
@Column(nullable = false)
|
||||
private PatternActionType actionType;
|
||||
|
||||
private Integer serviceId;
|
||||
|
||||
private long searchStartTimestamp;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
|
||||
Pattern pattern = (Pattern) o;
|
||||
return id != null && Objects.equals(id, pattern.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return getClass().hashCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package ru.serega6531.packmate.model;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.Setter;
|
||||
import lombok.ToString;
|
||||
import org.hibernate.Hibernate;
|
||||
import org.hibernate.annotations.GenericGenerator;
|
||||
import org.hibernate.annotations.Parameter;
|
||||
import ru.serega6531.packmate.model.enums.Protocol;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
@ToString
|
||||
@RequiredArgsConstructor
|
||||
@Entity
|
||||
@GenericGenerator(
|
||||
name = "stream_generator",
|
||||
strategy = "org.hibernate.id.enhanced.SequenceStyleGenerator",
|
||||
parameters = {
|
||||
@Parameter(name = "sequence_name", value = "stream_seq"),
|
||||
@Parameter(name = "initial_value", value = "1"),
|
||||
@Parameter(name = "increment_size", value = "1000"),
|
||||
@Parameter(name = "optimizer", value = "hilo")
|
||||
}
|
||||
)
|
||||
@Table(indexes = {@Index(name = "stream_id_desc_index", columnList = "id DESC")})
|
||||
public class Stream {
|
||||
|
||||
@Id
|
||||
@GeneratedValue(generator = "stream_generator")
|
||||
private Long id;
|
||||
|
||||
@Column(name = "service_id", nullable = false)
|
||||
private int service;
|
||||
|
||||
@Enumerated
|
||||
@Column(nullable = false)
|
||||
private Protocol protocol;
|
||||
|
||||
@OneToMany(mappedBy = "stream", cascade = CascadeType.ALL, orphanRemoval = true)
|
||||
@OrderBy("id")
|
||||
@ToString.Exclude
|
||||
private List<Packet> packets;
|
||||
|
||||
private long startTimestamp;
|
||||
|
||||
private long endTimestamp;
|
||||
|
||||
@ManyToMany
|
||||
@JoinTable(
|
||||
name = "stream_found_patterns",
|
||||
joinColumns = @JoinColumn(name = "stream_id"),
|
||||
inverseJoinColumns = @JoinColumn(name = "pattern_id")
|
||||
)
|
||||
@ToString.Exclude
|
||||
private Set<Pattern> foundPatterns = new HashSet<>();
|
||||
|
||||
private boolean favorite;
|
||||
|
||||
@Column(nullable = false, columnDefinition = "smallint")
|
||||
private int ttl;
|
||||
|
||||
@Column(columnDefinition = "char(3)")
|
||||
private String userAgentHash;
|
||||
|
||||
@Column(name = "size_bytes", nullable = false)
|
||||
private Integer sizeBytes;
|
||||
|
||||
@Column(name = "packets_count", nullable = false)
|
||||
private Integer packetsCount;
|
||||
|
||||
@Override
|
||||
public boolean equals(Object o) {
|
||||
if (this == o) return true;
|
||||
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o)) return false;
|
||||
Stream stream = (Stream) o;
|
||||
return id != null && Objects.equals(id, stream.id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
return getClass().hashCode();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
package ru.serega6531.packmate.model.enums;
|
||||
|
||||
public enum CaptureMode {
|
||||
|
||||
LIVE, FILE, VIEW
|
||||
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package ru.serega6531.packmate.model.enums;
|
||||
|
||||
public enum PatternActionType {
|
||||
FIND, IGNORE
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package ru.serega6531.packmate.model.enums;
|
||||
|
||||
public enum PatternDirectionType {
|
||||
INPUT, OUTPUT, BOTH
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
package ru.serega6531.packmate.model.enums;
|
||||
|
||||
public enum PatternSearchType {
|
||||
REGEX, SUBSTRING, SUBBYTES
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package ru.serega6531.packmate.model.enums;
|
||||
|
||||
public enum Protocol {
|
||||
TCP, UDP
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package ru.serega6531.packmate.model.enums;
|
||||
|
||||
public enum SubscriptionMessageType {
|
||||
SAVE_SERVICE, SAVE_PATTERN,
|
||||
DELETE_SERVICE,
|
||||
NEW_STREAM,
|
||||
FINISH_LOOKBACK,
|
||||
COUNTERS_UPDATE,
|
||||
ENABLE_PATTERN, DISABLE_PATTERN,
|
||||
PCAP_STARTED, PCAP_STOPPED
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
public class Counter {
|
||||
|
||||
private int value = 0;
|
||||
|
||||
public void increment() {
|
||||
value++;
|
||||
}
|
||||
|
||||
public void increment(int num) {
|
||||
value += num;
|
||||
}
|
||||
|
||||
}
|
||||
+8
@@ -0,0 +1,8 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
public record CountersHolder(Map<Integer, Integer> servicesPackets, Map<Integer, Integer> servicesStreams,
|
||||
int totalPackets, int totalStreams) {
|
||||
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class FoundPatternDto {
|
||||
|
||||
private int patternId;
|
||||
private int startPosition;
|
||||
private int endPosition;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@Data
|
||||
public class PacketDto {
|
||||
|
||||
private Long id;
|
||||
private Set<FoundPatternDto> matches;
|
||||
private long timestamp;
|
||||
private boolean incoming;
|
||||
private boolean ungzipped;
|
||||
private boolean webSocketParsed;
|
||||
private boolean tlsDecrypted;
|
||||
private boolean hasHttpBody;
|
||||
private byte[] content;
|
||||
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import lombok.Data;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
|
||||
@Data
|
||||
public class PacketPagination {
|
||||
|
||||
@Nullable
|
||||
private Long startingFrom;
|
||||
|
||||
private int pageSize;
|
||||
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import lombok.Data;
|
||||
import ru.serega6531.packmate.model.enums.PatternActionType;
|
||||
import ru.serega6531.packmate.model.enums.PatternDirectionType;
|
||||
import ru.serega6531.packmate.model.enums.PatternSearchType;
|
||||
|
||||
@Data
|
||||
public class PatternCreateDto {
|
||||
|
||||
private String name;
|
||||
private String value;
|
||||
private String color;
|
||||
private PatternSearchType searchType;
|
||||
private PatternDirectionType directionType;
|
||||
private PatternActionType actionType;
|
||||
private Integer serviceId;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import lombok.Data;
|
||||
import ru.serega6531.packmate.model.enums.PatternActionType;
|
||||
import ru.serega6531.packmate.model.enums.PatternDirectionType;
|
||||
import ru.serega6531.packmate.model.enums.PatternSearchType;
|
||||
|
||||
@Data
|
||||
public class PatternDto {
|
||||
|
||||
private int id;
|
||||
private boolean enabled;
|
||||
private boolean deleted;
|
||||
private String name;
|
||||
private String value;
|
||||
private String color;
|
||||
private PatternSearchType searchType;
|
||||
private PatternDirectionType directionType;
|
||||
private PatternActionType actionType;
|
||||
private Integer serviceId;
|
||||
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class PatternUpdateDto {
|
||||
|
||||
private String name;
|
||||
private String color;
|
||||
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ServiceCreateDto {
|
||||
|
||||
private int port;
|
||||
private String name;
|
||||
private boolean decryptTls;
|
||||
private boolean http;
|
||||
private boolean urldecodeHttpRequests;
|
||||
private boolean mergeAdjacentPackets;
|
||||
private boolean parseWebSockets;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ServiceDto {
|
||||
|
||||
private int port;
|
||||
private String name;
|
||||
private boolean decryptTls;
|
||||
private boolean http;
|
||||
private boolean urldecodeHttpRequests;
|
||||
private boolean mergeAdjacentPackets;
|
||||
private boolean parseWebSockets;
|
||||
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class ServiceUpdateDto {
|
||||
|
||||
private int port;
|
||||
private String name;
|
||||
private boolean decryptTls;
|
||||
private boolean http;
|
||||
private boolean urldecodeHttpRequests;
|
||||
private boolean mergeAdjacentPackets;
|
||||
private boolean parseWebSockets;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import lombok.Data;
|
||||
import ru.serega6531.packmate.model.enums.Protocol;
|
||||
|
||||
import java.util.Set;
|
||||
|
||||
@Data
|
||||
public class StreamDto {
|
||||
|
||||
private Long id;
|
||||
private int service;
|
||||
private Protocol protocol;
|
||||
private long startTimestamp;
|
||||
private long endTimestamp;
|
||||
private Set<Integer> foundPatternsIds;
|
||||
private boolean favorite;
|
||||
private int ttl;
|
||||
private String userAgentHash;
|
||||
private int sizeBytes;
|
||||
private int packetsCount;
|
||||
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import lombok.Data;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import ru.serega6531.packmate.model.Pattern;
|
||||
|
||||
@Data
|
||||
public class StreamPagination {
|
||||
|
||||
@Nullable
|
||||
private Long startingFrom;
|
||||
|
||||
private int pageSize;
|
||||
|
||||
private boolean favorites; // Искать только избранные потоки или все.
|
||||
|
||||
@Nullable
|
||||
private Pattern pattern; // Если задан, искать потоки с этим паттерном.
|
||||
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import ru.serega6531.packmate.model.enums.SubscriptionMessageType;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
public class SubscriptionMessage {
|
||||
|
||||
private SubscriptionMessageType type;
|
||||
private Object value;
|
||||
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package ru.serega6531.packmate.model.pojo;
|
||||
|
||||
import ru.serega6531.packmate.model.enums.Protocol;
|
||||
|
||||
import java.net.InetAddress;
|
||||
|
||||
public record UnfinishedStream(InetAddress firstIp, InetAddress secondIp, int firstPort, int secondPort,
|
||||
Protocol protocol) {
|
||||
|
||||
@Override
|
||||
public boolean equals(Object obj) {
|
||||
if (!(obj instanceof UnfinishedStream o)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
boolean ipEq1 = firstIp.equals(o.firstIp) && secondIp.equals(o.secondIp);
|
||||
boolean ipEq2 = firstIp.equals(o.secondIp) && secondIp.equals(o.firstIp);
|
||||
boolean portEq1 = firstPort == o.firstPort && secondPort == o.secondPort;
|
||||
boolean portEq2 = firstPort == o.secondPort && secondPort == o.firstPort;
|
||||
|
||||
return (ipEq1 || ipEq2) && (portEq1 || portEq2) && protocol == o.protocol;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int hashCode() {
|
||||
final int PRIME = 59;
|
||||
|
||||
int result = firstIp.hashCode() * secondIp.hashCode();
|
||||
result = result * PRIME + (firstPort * secondPort);
|
||||
result = result * PRIME + protocol.hashCode();
|
||||
|
||||
return result;
|
||||
}
|
||||
}
|
||||
+304
@@ -0,0 +1,304 @@
|
||||
package ru.serega6531.packmate.pcap;
|
||||
|
||||
import com.google.common.collect.*;
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
|
||||
import org.apache.commons.lang3.tuple.ImmutablePair;
|
||||
import org.apache.commons.lang3.tuple.Pair;
|
||||
import org.pcap4j.core.BpfProgram;
|
||||
import org.pcap4j.core.PacketListener;
|
||||
import org.pcap4j.core.PcapHandle;
|
||||
import org.pcap4j.core.PcapPacket;
|
||||
import org.pcap4j.packet.*;
|
||||
import ru.serega6531.packmate.model.CtfService;
|
||||
import ru.serega6531.packmate.model.enums.Protocol;
|
||||
import ru.serega6531.packmate.model.pojo.UnfinishedStream;
|
||||
import ru.serega6531.packmate.service.ServicesService;
|
||||
import ru.serega6531.packmate.service.StreamService;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
public abstract class AbstractPcapWorker implements PcapWorker, PacketListener {
|
||||
|
||||
private final ServicesService servicesService;
|
||||
private final StreamService streamService;
|
||||
|
||||
protected volatile PcapHandle pcap = null;
|
||||
protected final ExecutorService loopExecutorService;
|
||||
|
||||
protected String filter = "tcp or udp";
|
||||
|
||||
// Во время работы должен быть задан.
|
||||
protected ExecutorService processorExecutorService;
|
||||
|
||||
private final InetAddress localIp;
|
||||
|
||||
private long packetIdCounter = 0; // Доступ однопоточный, поэтому AtomicLong не требуется.
|
||||
|
||||
private final ListMultimap<UnfinishedStream, ru.serega6531.packmate.model.Packet> unfinishedTcpStreams = ArrayListMultimap.create();
|
||||
private final ListMultimap<UnfinishedStream, ru.serega6531.packmate.model.Packet> unfinishedUdpStreams = ArrayListMultimap.create();
|
||||
|
||||
// В следующих множествах хранятся адреса источника соответствующего пакета.
|
||||
private final SetMultimap<UnfinishedStream, Pair<InetAddress, Integer>> fins = HashMultimap.create();
|
||||
private final SetMultimap<UnfinishedStream, Pair<InetAddress, Integer>> acks = HashMultimap.create();
|
||||
|
||||
protected AbstractPcapWorker(ServicesService servicesService,
|
||||
StreamService streamService,
|
||||
InetAddress localIp) throws UnknownHostException {
|
||||
this.servicesService = servicesService;
|
||||
this.streamService = streamService;
|
||||
|
||||
this.localIp = localIp;
|
||||
|
||||
BasicThreadFactory factory = new BasicThreadFactory.Builder()
|
||||
.namingPattern("pcap-loop").build();
|
||||
loopExecutorService = Executors.newSingleThreadExecutor(factory);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void gotPacket(PcapPacket capturedPacket) {
|
||||
gotPacket(capturedPacket, pcap);
|
||||
}
|
||||
|
||||
protected void gotPacket(PcapPacket capturedPacket, PcapHandle capture) {
|
||||
if (capture == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
final Packet rawPacket = capturedPacket.getPacket();
|
||||
|
||||
InetAddress sourceIp;
|
||||
InetAddress destIp;
|
||||
int ttl;
|
||||
|
||||
if (rawPacket.contains(IpV4Packet.class)) {
|
||||
final IpV4Packet.IpV4Header ipHeader = rawPacket.get(IpV4Packet.class).getHeader();
|
||||
sourceIp = ipHeader.getSrcAddr();
|
||||
destIp = ipHeader.getDstAddr();
|
||||
ttl = Byte.toUnsignedInt(ipHeader.getTtl());
|
||||
} else if (rawPacket.contains(IpV6Packet.class)) {
|
||||
final IpV6Packet.IpV6Header ipHeader = rawPacket.get(IpV6Packet.class).getHeader();
|
||||
sourceIp = ipHeader.getSrcAddr();
|
||||
destIp = ipHeader.getDstAddr();
|
||||
ttl = Byte.toUnsignedInt(ipHeader.getHopLimit());
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
final long time = capturedPacket.getTimestamp().toEpochMilli();
|
||||
|
||||
if (rawPacket.contains(TcpPacket.class)) {
|
||||
final TcpPacket packet = rawPacket.get(TcpPacket.class);
|
||||
gotTcpPacket(packet, sourceIp, destIp, ttl, time);
|
||||
} else if (rawPacket.contains(UdpPacket.class)) {
|
||||
final UdpPacket packet = rawPacket.get(UdpPacket.class);
|
||||
gotUdpPacket(packet, sourceIp, destIp, ttl, time);
|
||||
}
|
||||
}
|
||||
|
||||
private void gotTcpPacket(TcpPacket packet, InetAddress sourceIp, InetAddress destIp, int ttl, long time) {
|
||||
final TcpPacket.TcpHeader tcpHeader = packet.getHeader();
|
||||
int sourcePort = tcpHeader.getSrcPort().valueAsInt();
|
||||
int destPort = tcpHeader.getDstPort().valueAsInt();
|
||||
boolean ack = tcpHeader.getAck();
|
||||
boolean fin = tcpHeader.getFin();
|
||||
boolean rst = tcpHeader.getRst();
|
||||
byte[] content = packet.getPayload() != null ? packet.getPayload().getRawData() : new byte[0];
|
||||
|
||||
String sourceIpString = sourceIp.getHostAddress();
|
||||
String destIpString = destIp.getHostAddress();
|
||||
|
||||
final Optional<CtfService> serviceOptional =
|
||||
servicesService.findService(sourceIp, sourcePort, destIp, destPort);
|
||||
|
||||
if (serviceOptional.isPresent()) {
|
||||
processorExecutorService.execute(() -> {
|
||||
UnfinishedStream stream = addNewPacket(sourceIp, destIp, time, sourcePort, destPort, ttl, content, Protocol.TCP);
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("TCP {} {}:{} -> {}:{}, номер пакета {}",
|
||||
serviceOptional.get(), sourceIpString, sourcePort, destIpString, destPort,
|
||||
unfinishedTcpStreams.get(stream).size());
|
||||
}
|
||||
|
||||
checkTcpTermination(ack, fin, rst, new ImmutablePair<>(sourceIp, sourcePort), new ImmutablePair<>(destIp, destPort), stream);
|
||||
});
|
||||
} else { // сервис не найден
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("tcp {}:{} -> {}:{}", sourceIpString, sourcePort, destIpString, destPort);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void gotUdpPacket(UdpPacket packet, InetAddress sourceIp, InetAddress destIp, int ttl, long time) {
|
||||
final UdpPacket.UdpHeader udpHeader = packet.getHeader();
|
||||
int sourcePort = udpHeader.getSrcPort().valueAsInt();
|
||||
int destPort = udpHeader.getDstPort().valueAsInt();
|
||||
byte[] content = packet.getPayload() != null ? packet.getPayload().getRawData() : new byte[0];
|
||||
|
||||
String sourceIpString = sourceIp.getHostAddress();
|
||||
String destIpString = destIp.getHostAddress();
|
||||
|
||||
final Optional<CtfService> serviceOptional =
|
||||
servicesService.findService(sourceIp, sourcePort, destIp, destPort);
|
||||
|
||||
if (serviceOptional.isPresent()) {
|
||||
processorExecutorService.execute(() -> {
|
||||
UnfinishedStream stream = addNewPacket(sourceIp, destIp, time, sourcePort, destPort, ttl, content, Protocol.UDP);
|
||||
|
||||
if (log.isDebugEnabled()) {
|
||||
log.debug("UDP {} {}:{} -> {}:{}, номер пакета {}",
|
||||
serviceOptional.get(), sourceIpString, sourcePort, destIpString, destPort,
|
||||
unfinishedUdpStreams.get(stream).size());
|
||||
}
|
||||
});
|
||||
} else { // сервис не найден
|
||||
if (log.isTraceEnabled()) {
|
||||
log.trace("udp {}:{} -> {}:{}", sourceIpString, sourcePort, destIpString, destPort);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private UnfinishedStream addNewPacket(InetAddress sourceIp, InetAddress destIp, long time,
|
||||
int sourcePort, int destPort, int ttl, byte[] content, Protocol protocol) {
|
||||
var incoming = destIp.equals(localIp);
|
||||
var stream = new UnfinishedStream(sourceIp, destIp, sourcePort, destPort, protocol);
|
||||
|
||||
var packet = ru.serega6531.packmate.model.Packet.builder()
|
||||
.tempId(packetIdCounter++)
|
||||
.ttl(ttl)
|
||||
.timestamp(time)
|
||||
.incoming(incoming)
|
||||
.content(content)
|
||||
.build();
|
||||
|
||||
final var streams = (protocol == Protocol.TCP) ? this.unfinishedTcpStreams : this.unfinishedUdpStreams;
|
||||
|
||||
if (!streams.containsKey(stream)) {
|
||||
log.debug("Начат новый поток");
|
||||
}
|
||||
|
||||
streams.put(stream, packet);
|
||||
return stream;
|
||||
}
|
||||
|
||||
/**
|
||||
* Udp не имеет фазы закрытия, поэтому закрывается только по таймауту
|
||||
*/
|
||||
private void checkTcpTermination(boolean ack, boolean fin, boolean rst,
|
||||
Pair<InetAddress, Integer> sourceIpAndPort,
|
||||
Pair<InetAddress, Integer> destIpAndPort,
|
||||
UnfinishedStream stream) {
|
||||
|
||||
if (fin) {
|
||||
fins.put(stream, sourceIpAndPort);
|
||||
}
|
||||
|
||||
if (ack && fins.containsEntry(stream, destIpAndPort)) { // проверяем destIp, потому что ищем ответ на его fin
|
||||
acks.put(stream, sourceIpAndPort);
|
||||
}
|
||||
|
||||
// если соединение разорвано с помощью rst или закрыто с помощью fin-ack-fin-ack
|
||||
if (rst || (acks.containsEntry(stream, sourceIpAndPort) && acks.containsEntry(stream, destIpAndPort))) {
|
||||
streamService.saveNewStream(stream, unfinishedTcpStreams.get(stream));
|
||||
|
||||
unfinishedTcpStreams.removeAll(stream);
|
||||
fins.removeAll(stream);
|
||||
acks.removeAll(stream);
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@SneakyThrows
|
||||
public void closeAllStreams(Protocol protocol) {
|
||||
final var streams = (protocol == Protocol.TCP) ? this.unfinishedTcpStreams : this.unfinishedUdpStreams;
|
||||
|
||||
Multimaps.asMap(streams).forEach((key, value) ->
|
||||
streamService.saveNewStream(key, new ArrayList<>(value)));
|
||||
|
||||
streams.clear();
|
||||
if (protocol == Protocol.TCP) {
|
||||
fins.clear();
|
||||
acks.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@SneakyThrows
|
||||
public int closeTimeoutStreams(Protocol protocol, long timeoutMillis) {
|
||||
return processorExecutorService.submit(() -> {
|
||||
int streamsClosed = 0;
|
||||
|
||||
final long time = System.currentTimeMillis();
|
||||
final var streams = (protocol == Protocol.TCP) ? this.unfinishedTcpStreams : this.unfinishedUdpStreams;
|
||||
|
||||
final var oldStreams = Multimaps.asMap(streams).entrySet().stream()
|
||||
.filter(entry -> {
|
||||
final var packets = entry.getValue();
|
||||
return time - packets.get(packets.size() - 1).getTimestamp() > timeoutMillis;
|
||||
})
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
|
||||
|
||||
for (var entry : oldStreams.entrySet()) {
|
||||
final UnfinishedStream stream = entry.getKey();
|
||||
final var packets = entry.getValue();
|
||||
|
||||
if (streamService.saveNewStream(stream, packets)) {
|
||||
streamsClosed++;
|
||||
}
|
||||
|
||||
if (protocol == Protocol.TCP) {
|
||||
fins.removeAll(stream);
|
||||
acks.removeAll(stream);
|
||||
}
|
||||
|
||||
streams.removeAll(stream);
|
||||
}
|
||||
|
||||
return streamsClosed;
|
||||
}).get();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFilter(String filter) {
|
||||
this.filter = filter;
|
||||
applyFilter();
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
protected void applyFilter() {
|
||||
if(filter != null && pcap != null && pcap.isOpen()) {
|
||||
pcap.setFilter(filter, BpfProgram.BpfCompileMode.OPTIMIZE);
|
||||
}
|
||||
}
|
||||
|
||||
protected void shutdownExecutor(ExecutorService executor, String executorName) {
|
||||
if (executor == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
executor.shutdown();
|
||||
try {
|
||||
if (!executor.awaitTermination(10, TimeUnit.SECONDS)) {
|
||||
log.warn("Поток обработки {} не завершился вовремя, отправляется сигнал остановки", executorName);
|
||||
executor.shutdownNow();
|
||||
if (!executor.awaitTermination(5, TimeUnit.SECONDS)) {
|
||||
log.error("Поток обработки {} не завершился после сигнала остановки", executorName);
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException exception) {
|
||||
executor.shutdownNow();
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
package ru.serega6531.packmate.pcap;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.tomcat.util.threads.InlineExecutorService;
|
||||
import org.pcap4j.core.PcapNativeException;
|
||||
import org.pcap4j.core.PcapHandle;
|
||||
import org.pcap4j.core.NotOpenException;
|
||||
import org.pcap4j.core.Pcaps;
|
||||
import org.pcap4j.core.PcapPacket;
|
||||
import ru.serega6531.packmate.exception.PcapFileNotFoundException;
|
||||
import ru.serega6531.packmate.model.enums.Protocol;
|
||||
import ru.serega6531.packmate.service.ServicesService;
|
||||
import ru.serega6531.packmate.service.StreamService;
|
||||
|
||||
import java.io.EOFException;
|
||||
import java.io.File;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
@Slf4j
|
||||
public class FilePcapWorker extends AbstractPcapWorker {
|
||||
|
||||
private final File directory;
|
||||
|
||||
private final File file;
|
||||
private final AtomicBoolean running = new AtomicBoolean();
|
||||
private volatile Runnable stoppedCallback = () -> {};
|
||||
private volatile CountDownLatch loopFinished = new CountDownLatch(0);
|
||||
private volatile CountDownLatch stopFinished = new CountDownLatch(0);
|
||||
|
||||
public FilePcapWorker(ServicesService servicesService,
|
||||
StreamService streamService,
|
||||
InetAddress localIp,
|
||||
String filename) throws UnknownHostException {
|
||||
super(servicesService, streamService, localIp);
|
||||
|
||||
File configuredFile = new File(filename);
|
||||
if (configuredFile.isAbsolute()) {
|
||||
file = configuredFile;
|
||||
directory = configuredFile.getParentFile();
|
||||
} else {
|
||||
directory = new File("pcaps");
|
||||
file = new File(directory, filename);
|
||||
}
|
||||
validateFileExists();
|
||||
|
||||
processorExecutorService = new InlineExecutorService();
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
@Override
|
||||
public void start(Runnable onStarted, Runnable onStopped) {
|
||||
log.info("Открывается файл захвата: {}", file.getAbsolutePath());
|
||||
PcapHandle capture = openCapture();
|
||||
pcap = capture;
|
||||
CountDownLatch startGate = new CountDownLatch(1);
|
||||
CountDownLatch currentLoopFinished = new CountDownLatch(1);
|
||||
CountDownLatch currentStopFinished = new CountDownLatch(1);
|
||||
loopFinished = currentLoopFinished;
|
||||
stopFinished = currentStopFinished;
|
||||
try {
|
||||
applyFilter();
|
||||
stoppedCallback = onStopped;
|
||||
running.set(true);
|
||||
loopExecutorService.execute(() -> runAfterStart(startGate, currentLoopFinished, capture));
|
||||
onStarted.run();
|
||||
startGate.countDown();
|
||||
} catch (Throwable exception) {
|
||||
running.set(false);
|
||||
startGate.countDown();
|
||||
currentLoopFinished.countDown();
|
||||
currentStopFinished.countDown();
|
||||
if (capture.isOpen()) {
|
||||
capture.close();
|
||||
}
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
protected PcapHandle openCapture() throws PcapNativeException {
|
||||
return Pcaps.openOffline(file.getAbsolutePath());
|
||||
}
|
||||
|
||||
private void runAfterStart(CountDownLatch startGate, CountDownLatch loopFinished, PcapHandle capture) {
|
||||
try {
|
||||
startGate.await();
|
||||
if (running.get() && pcap == capture) {
|
||||
runScan(capture, loopFinished);
|
||||
}
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.info("Обработка файла захвата прервана");
|
||||
} catch (RuntimeException exception) {
|
||||
log.error("Не удалось обработать файл захвата", exception);
|
||||
} finally {
|
||||
loopFinished.countDown();
|
||||
stop(capture);
|
||||
}
|
||||
}
|
||||
|
||||
private void runScan(PcapHandle capture, CountDownLatch loopFinished) {
|
||||
try {
|
||||
while (running.get() && pcap == capture && capture.isOpen()) {
|
||||
try {
|
||||
final PcapPacket packet = capture.getNextPacketEx();
|
||||
gotPacket(packet, capture);
|
||||
} catch (PcapNativeException | NotOpenException | TimeoutException exception) {
|
||||
log.error("Ошибка чтения файла захвата: {}", exception.getMessage());
|
||||
break;
|
||||
} catch (EOFException exception) {
|
||||
log.info("Чтение файла захвата завершено");
|
||||
break;
|
||||
} catch (RuntimeException exception) {
|
||||
log.error("Ошибка обработки пакета из файла захвата", exception);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
loopFinished.countDown();
|
||||
stop(capture);
|
||||
}
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
public void stop() {
|
||||
stop(pcap);
|
||||
}
|
||||
|
||||
private void stop(PcapHandle capture) {
|
||||
if (capture == null || pcap != capture) {
|
||||
return;
|
||||
}
|
||||
CountDownLatch currentStopFinished = stopFinished;
|
||||
if (!running.compareAndSet(true, false)) {
|
||||
awaitLoopFinished(currentStopFinished);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (capture.isOpen()) {
|
||||
capture.close();
|
||||
log.info("Файл захвата закрыт");
|
||||
}
|
||||
} catch (RuntimeException exception) {
|
||||
log.warn("Не удалось закрыть файл захвата", exception);
|
||||
}
|
||||
|
||||
try {
|
||||
awaitLoopFinished(loopFinished);
|
||||
closeAllStreams(Protocol.TCP);
|
||||
closeAllStreams(Protocol.UDP);
|
||||
} finally {
|
||||
try {
|
||||
stoppedCallback.run();
|
||||
} finally {
|
||||
currentStopFinished.countDown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void awaitLoopFinished(CountDownLatch currentLoopFinished) {
|
||||
boolean interrupted = false;
|
||||
while (true) {
|
||||
try {
|
||||
currentLoopFinished.await();
|
||||
break;
|
||||
} catch (InterruptedException exception) {
|
||||
interrupted = true;
|
||||
}
|
||||
}
|
||||
if (interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
stop();
|
||||
shutdownExecutor(loopExecutorService, "pcap-loop");
|
||||
shutdownExecutor(processorExecutorService, "pcap-inline");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExecutorState() {
|
||||
return "inline";
|
||||
}
|
||||
|
||||
private void validateFileExists() {
|
||||
if (!file.exists()) {
|
||||
throw new PcapFileNotFoundException(file, directory);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package ru.serega6531.packmate.pcap;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.concurrent.BasicThreadFactory;
|
||||
import org.pcap4j.core.PcapNativeException;
|
||||
import org.pcap4j.core.PcapHandle;
|
||||
import org.pcap4j.core.PcapNetworkInterface;
|
||||
import org.pcap4j.core.Pcaps;
|
||||
import ru.serega6531.packmate.model.enums.Protocol;
|
||||
import ru.serega6531.packmate.exception.PcapInterfaceNotFoundException;
|
||||
import ru.serega6531.packmate.service.ServicesService;
|
||||
import ru.serega6531.packmate.service.StreamService;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.ArrayBlockingQueue;
|
||||
import java.util.concurrent.CountDownLatch;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.RejectedExecutionException;
|
||||
import java.util.concurrent.RejectedExecutionHandler;
|
||||
import java.util.concurrent.ThreadPoolExecutor;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
@Slf4j
|
||||
public class LivePcapWorker extends AbstractPcapWorker {
|
||||
|
||||
private static final int PROCESSOR_QUEUE_CAPACITY = 1024;
|
||||
|
||||
private final PcapNetworkInterface device;
|
||||
private final AtomicBoolean running = new AtomicBoolean();
|
||||
private volatile Runnable stoppedCallback = () -> {};
|
||||
private volatile CountDownLatch loopFinished = new CountDownLatch(0);
|
||||
private volatile CountDownLatch stopFinished = new CountDownLatch(0);
|
||||
|
||||
public LivePcapWorker(ServicesService servicesService,
|
||||
StreamService streamService,
|
||||
InetAddress localIp,
|
||||
String interfaceName) throws PcapNativeException, UnknownHostException {
|
||||
super(servicesService, streamService, localIp);
|
||||
device = Pcaps.getDevByName(interfaceName);
|
||||
|
||||
if (device == null) {
|
||||
List<String> existingInterfaces = Pcaps.findAllDevs().stream().map(PcapNetworkInterface::getName).toList();
|
||||
throw new PcapInterfaceNotFoundException(interfaceName, existingInterfaces);
|
||||
}
|
||||
|
||||
BasicThreadFactory factory = new BasicThreadFactory.Builder()
|
||||
.namingPattern("pcap-processor").build();
|
||||
processorExecutorService = new ThreadPoolExecutor(
|
||||
1,
|
||||
1,
|
||||
0L,
|
||||
TimeUnit.MILLISECONDS,
|
||||
new ArrayBlockingQueue<>(PROCESSOR_QUEUE_CAPACITY),
|
||||
factory,
|
||||
new BlockingBackpressurePolicy()
|
||||
);
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
public void start(Runnable onStarted, Runnable onStopped) throws PcapNativeException {
|
||||
log.info("Открывается сетевой интерфейс: {}", device.getName());
|
||||
var capture = device.openLive(65536, PcapNetworkInterface.PromiscuousMode.PROMISCUOUS, 100);
|
||||
pcap = capture;
|
||||
CountDownLatch startGate = new CountDownLatch(1);
|
||||
CountDownLatch currentLoopFinished = new CountDownLatch(1);
|
||||
CountDownLatch currentStopFinished = new CountDownLatch(1);
|
||||
loopFinished = currentLoopFinished;
|
||||
stopFinished = currentStopFinished;
|
||||
try {
|
||||
applyFilter();
|
||||
stoppedCallback = onStopped;
|
||||
running.set(true);
|
||||
loopExecutorService.execute(() -> runAfterStart(startGate, currentLoopFinished, capture));
|
||||
onStarted.run();
|
||||
startGate.countDown();
|
||||
} catch (Throwable exception) {
|
||||
running.set(false);
|
||||
startGate.countDown();
|
||||
currentLoopFinished.countDown();
|
||||
currentStopFinished.countDown();
|
||||
if (capture.isOpen()) {
|
||||
capture.close();
|
||||
}
|
||||
throw exception;
|
||||
}
|
||||
}
|
||||
|
||||
private void runAfterStart(CountDownLatch startGate, CountDownLatch currentLoopFinished, PcapHandle capture) {
|
||||
try {
|
||||
startGate.await();
|
||||
if (!running.get() || pcap != capture) {
|
||||
return;
|
||||
}
|
||||
log.info("Перехват сетевого трафика запущен");
|
||||
capture.loop(-1, this);
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt();
|
||||
log.info("Перехват сетевого трафика прерван");
|
||||
} catch (Exception exception) {
|
||||
log.error("Ошибка при перехвате сетевого пакета", exception);
|
||||
} finally {
|
||||
currentLoopFinished.countDown();
|
||||
stop(capture);
|
||||
}
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
public void stop() {
|
||||
stop(pcap);
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private void stop(PcapHandle capture) {
|
||||
if (capture == null || pcap != capture) {
|
||||
return;
|
||||
}
|
||||
CountDownLatch currentStopFinished = stopFinished;
|
||||
if (!running.compareAndSet(true, false)) {
|
||||
awaitLoopFinished(currentStopFinished);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
if (capture.isOpen()) {
|
||||
capture.breakLoop();
|
||||
capture.close();
|
||||
}
|
||||
} catch (RuntimeException exception) {
|
||||
log.warn("Не удалось сразу закрыть интерфейс захвата", exception);
|
||||
}
|
||||
|
||||
try {
|
||||
awaitLoopFinished(loopFinished);
|
||||
flushProcessorQueue();
|
||||
} catch (RuntimeException exception) {
|
||||
log.error("Не удалось завершить обработку очереди захвата", exception);
|
||||
} finally {
|
||||
try {
|
||||
log.info("Перехват сетевого трафика остановлен");
|
||||
stoppedCallback.run();
|
||||
} finally {
|
||||
currentStopFinished.countDown();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void awaitLoopFinished(CountDownLatch currentLoopFinished) {
|
||||
boolean interrupted = false;
|
||||
while (true) {
|
||||
try {
|
||||
currentLoopFinished.await();
|
||||
break;
|
||||
} catch (InterruptedException exception) {
|
||||
interrupted = true;
|
||||
}
|
||||
}
|
||||
if (interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
}
|
||||
}
|
||||
|
||||
private void flushProcessorQueue() {
|
||||
flushAndWait(processorExecutorService, () -> {
|
||||
closeAllStreams(Protocol.TCP);
|
||||
closeAllStreams(Protocol.UDP);
|
||||
});
|
||||
}
|
||||
|
||||
static void flushAndWait(ExecutorService executor, Runnable flushTask) {
|
||||
try {
|
||||
executor.submit(flushTask).get();
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new IllegalStateException("Ожидание завершения очереди захвата прервано", exception);
|
||||
} catch (ExecutionException exception) {
|
||||
throw new IllegalStateException("Ошибка при сохранении незавершенных потоков", exception.getCause());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
stop();
|
||||
shutdownExecutor(processorExecutorService, "pcap-processor");
|
||||
shutdownExecutor(loopExecutorService, "pcap-loop");
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExecutorState() {
|
||||
return processorExecutorService.toString();
|
||||
}
|
||||
|
||||
static final class BlockingBackpressurePolicy implements RejectedExecutionHandler {
|
||||
@Override
|
||||
public void rejectedExecution(Runnable task, ThreadPoolExecutor executor) {
|
||||
while (!executor.isShutdown()) {
|
||||
try {
|
||||
if (executor.getQueue().offer(task, 100, TimeUnit.MILLISECONDS)) {
|
||||
if (executor.isShutdown() && executor.getQueue().remove(task)) {
|
||||
throw new RejectedExecutionException("Очередь обработки захвата уже остановлена");
|
||||
}
|
||||
return;
|
||||
}
|
||||
} catch (InterruptedException exception) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new RejectedExecutionException("Ожидание свободного места в очереди захвата прервано", exception);
|
||||
}
|
||||
}
|
||||
throw new RejectedExecutionException("Очередь обработки захвата уже остановлена");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package ru.serega6531.packmate.pcap;
|
||||
|
||||
import ru.serega6531.packmate.model.enums.Protocol;
|
||||
|
||||
public class NoOpPcapWorker implements PcapWorker {
|
||||
@Override
|
||||
public void start(Runnable onStarted, Runnable onStopped) {
|
||||
onStarted.run();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void stop() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void shutdown() {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void closeAllStreams(Protocol protocol) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public int closeTimeoutStreams(Protocol protocol, long timeoutMillis) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setFilter(String filter) {
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getExecutorState() {
|
||||
return "none";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package ru.serega6531.packmate.pcap;
|
||||
|
||||
import org.pcap4j.core.PcapNativeException;
|
||||
import ru.serega6531.packmate.model.enums.Protocol;
|
||||
|
||||
public interface PcapWorker {
|
||||
|
||||
void start(Runnable onStarted, Runnable onStopped) throws PcapNativeException;
|
||||
void stop();
|
||||
void shutdown();
|
||||
|
||||
/**
|
||||
* Выполняется в вызывающем потоке
|
||||
*/
|
||||
void closeAllStreams(Protocol protocol);
|
||||
|
||||
/**
|
||||
* Выполняется в потоке обработчика
|
||||
*/
|
||||
int closeTimeoutStreams(Protocol protocol, long timeoutMillis);
|
||||
|
||||
void setFilter(String filter);
|
||||
|
||||
String getExecutorState();
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package ru.serega6531.packmate.properties;
|
||||
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import ru.serega6531.packmate.model.enums.CaptureMode;
|
||||
|
||||
import java.net.InetAddress;
|
||||
|
||||
@ConfigurationProperties("packmate")
|
||||
public record PackmateProperties(
|
||||
CaptureMode captureMode,
|
||||
String interfaceName,
|
||||
String pcapFile,
|
||||
InetAddress localIp,
|
||||
WebProperties web,
|
||||
TimeoutProperties timeout,
|
||||
CleanupProperties cleanup,
|
||||
boolean ignoreEmptyPackets
|
||||
) {
|
||||
|
||||
public record WebProperties(
|
||||
String accountLogin,
|
||||
String accountPassword
|
||||
) {}
|
||||
|
||||
public record TimeoutProperties(
|
||||
int udpStreamTimeout,
|
||||
int tcpStreamTimeout,
|
||||
int checkInterval
|
||||
){}
|
||||
|
||||
public record CleanupProperties(
|
||||
boolean enabled,
|
||||
int threshold,
|
||||
int interval
|
||||
){}
|
||||
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package ru.serega6531.packmate.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.serega6531.packmate.model.Pattern;
|
||||
|
||||
public interface PatternRepository extends JpaRepository<Pattern, Integer> {
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package ru.serega6531.packmate.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import ru.serega6531.packmate.model.CtfService;
|
||||
|
||||
public interface ServiceRepository extends JpaRepository<CtfService, Integer> {
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package ru.serega6531.packmate.repository;
|
||||
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import ru.serega6531.packmate.model.Packet;
|
||||
import ru.serega6531.packmate.model.Stream;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface StreamRepository extends JpaRepository<Stream, Long>, JpaSpecificationExecutor<Stream> {
|
||||
|
||||
@Query("UPDATE Stream SET favorite = :favorite WHERE id = :id")
|
||||
@Modifying
|
||||
void setFavorite(long id, boolean favorite);
|
||||
|
||||
long deleteByEndTimestampBeforeAndFavoriteIsFalse(long threshold);
|
||||
|
||||
@Query("SELECT p FROM Packet p " +
|
||||
"LEFT JOIN FETCH p.matches " +
|
||||
"WHERE p.stream.id = :streamId " +
|
||||
"AND (:startingFrom IS NULL OR p.id > :startingFrom) " +
|
||||
"ORDER BY p.id"
|
||||
)
|
||||
List<Packet> getPackets(long streamId, Long startingFrom, Pageable pageable);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package ru.serega6531.packmate.service;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Service;
|
||||
import ru.serega6531.packmate.model.enums.SubscriptionMessageType;
|
||||
import ru.serega6531.packmate.model.pojo.Counter;
|
||||
import ru.serega6531.packmate.model.pojo.CountersHolder;
|
||||
import ru.serega6531.packmate.model.pojo.SubscriptionMessage;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class CountingService {
|
||||
|
||||
private final SubscriptionService subscriptionService;
|
||||
|
||||
private final Map<Integer, Counter> servicesPackets = new HashMap<>();
|
||||
private final Map<Integer, Counter> servicesStreams = new HashMap<>();
|
||||
|
||||
private Counter totalPackets = new Counter();
|
||||
private Counter totalStreams = new Counter();
|
||||
|
||||
@Autowired
|
||||
public CountingService(SubscriptionService subscriptionService) {
|
||||
this.subscriptionService = subscriptionService;
|
||||
}
|
||||
|
||||
synchronized void countStream(int serviceId, int packets) {
|
||||
getCounter(servicesPackets, serviceId).increment(packets);
|
||||
getCounter(servicesStreams, serviceId).increment();
|
||||
|
||||
totalPackets.increment(packets);
|
||||
totalStreams.increment();
|
||||
}
|
||||
|
||||
@Scheduled(cron = "0 * * ? * *")
|
||||
public void sendCounters() {
|
||||
CountersHolder counters;
|
||||
synchronized (this) {
|
||||
counters = new CountersHolder(toIntegerMap(servicesPackets), toIntegerMap(servicesStreams),
|
||||
totalPackets.getValue(), totalStreams.getValue());
|
||||
servicesPackets.clear();
|
||||
servicesStreams.clear();
|
||||
totalPackets = new Counter();
|
||||
totalStreams = new Counter();
|
||||
}
|
||||
subscriptionService.broadcast(new SubscriptionMessage(SubscriptionMessageType.COUNTERS_UPDATE, counters));
|
||||
}
|
||||
|
||||
private Map<Integer, Integer> toIntegerMap(Map<Integer, Counter> map) {
|
||||
return map.entrySet().stream()
|
||||
.collect(Collectors.toMap(
|
||||
Map.Entry::getKey,
|
||||
ent -> ent.getValue().getValue()));
|
||||
}
|
||||
|
||||
private Counter getCounter(Map<Integer, Counter> counters, int serviceId) {
|
||||
return counters.computeIfAbsent(serviceId, c -> new Counter());
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package ru.serega6531.packmate.service;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
import com.google.common.cache.Cache;
|
||||
import com.google.common.cache.CacheBuilder;
|
||||
import org.springframework.security.crypto.codec.Hex;
|
||||
import ru.serega6531.packmate.model.FoundPattern;
|
||||
import ru.serega6531.packmate.model.Pattern;
|
||||
import ru.serega6531.packmate.utils.KMPByteSearcher;
|
||||
import ru.serega6531.packmate.utils.KMPStringSearcher;
|
||||
import com.google.re2j.Matcher;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.io.StringReader;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
|
||||
public class PatternMatcher {
|
||||
|
||||
private static final Cache<String, com.google.re2j.Pattern> compiledRegexes = CacheBuilder.newBuilder()
|
||||
.maximumSize(256)
|
||||
.build();
|
||||
|
||||
private final byte[] contentBytes;
|
||||
private final String content;
|
||||
private final List<Pattern> patterns;
|
||||
|
||||
private final Set<FoundPattern> result = new HashSet<>();
|
||||
|
||||
public PatternMatcher(byte[] contentBytes, List<Pattern> patterns) {
|
||||
this.contentBytes = contentBytes;
|
||||
this.content = new String(contentBytes);
|
||||
this.patterns = patterns;
|
||||
}
|
||||
|
||||
public Set<FoundPattern> findMatches() {
|
||||
patterns.forEach(this::match);
|
||||
return result;
|
||||
}
|
||||
|
||||
private void match(Pattern pattern) {
|
||||
switch (pattern.getSearchType()) {
|
||||
case REGEX -> matchRegex(pattern);
|
||||
case SUBSTRING -> matchSubstring(pattern);
|
||||
case SUBBYTES -> matchSubbytes(pattern);
|
||||
}
|
||||
}
|
||||
|
||||
private void matchRegex(Pattern pattern) {
|
||||
final var regex = compileRegex(pattern.getValue());
|
||||
final Matcher matcher = regex.matcher(content);
|
||||
|
||||
while (matcher.find()) {
|
||||
if (matcher.start() == matcher.end()) {
|
||||
continue;
|
||||
}
|
||||
addIfPossible(FoundPattern.builder()
|
||||
.patternId(pattern.getId())
|
||||
.startPosition(matcher.start())
|
||||
.endPosition(matcher.end() - 1)
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
private void matchSubstring(Pattern pattern) {
|
||||
final String value = pattern.getValue();
|
||||
if (value.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
KMPStringSearcher searcher = new KMPStringSearcher(value.toCharArray());
|
||||
StringReader reader = new StringReader(content);
|
||||
|
||||
while (true) {
|
||||
int end = searcher.search(reader) - 1;
|
||||
|
||||
if (end < 0) {
|
||||
searcher.reset();
|
||||
return;
|
||||
}
|
||||
|
||||
int start = end - value.length() + 1;
|
||||
addIfPossible(FoundPattern.builder()
|
||||
.patternId(pattern.getId())
|
||||
.startPosition(start)
|
||||
.endPosition(end)
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private void matchSubbytes(Pattern pattern) {
|
||||
final byte[] value = Hex.decode(pattern.getValue());
|
||||
if (value.length == 0) {
|
||||
return;
|
||||
}
|
||||
KMPByteSearcher searcher = new KMPByteSearcher(value);
|
||||
InputStream is = new ByteArrayInputStream(contentBytes);
|
||||
|
||||
while (true) {
|
||||
int end = searcher.search(is) - 1;
|
||||
|
||||
if (end < 0) {
|
||||
searcher.reset();
|
||||
return;
|
||||
}
|
||||
|
||||
int start = end - value.length + 1;
|
||||
addIfPossible(FoundPattern.builder()
|
||||
.patternId(pattern.getId())
|
||||
.startPosition(start)
|
||||
.endPosition(end)
|
||||
.build());
|
||||
}
|
||||
}
|
||||
|
||||
private void addIfPossible(FoundPattern found) {
|
||||
if (result.stream().noneMatch(match ->
|
||||
between(match.getStartPosition(), match.getEndPosition(), found.getStartPosition()) ||
|
||||
between(match.getStartPosition(), match.getEndPosition(), found.getEndPosition()))) {
|
||||
result.add(found);
|
||||
}
|
||||
}
|
||||
|
||||
private boolean between(int a, int b, int x) {
|
||||
return a <= x && x <= b;
|
||||
}
|
||||
|
||||
static void compilePattern(Pattern pattern) {
|
||||
switch (pattern.getSearchType()) {
|
||||
case REGEX -> compileRegex(pattern.getValue());
|
||||
case SUBSTRING -> {
|
||||
if (pattern.getValue().isEmpty()) {
|
||||
throw new IllegalArgumentException("Текстовый шаблон не может быть пустым.");
|
||||
}
|
||||
}
|
||||
case SUBBYTES -> {
|
||||
if (Hex.decode(pattern.getValue()).length == 0) {
|
||||
throw new IllegalArgumentException("Байтовый шаблон не может быть пустым.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static com.google.re2j.Pattern compileRegex(String expression) {
|
||||
try {
|
||||
return compiledRegexes.get(expression, () -> com.google.re2j.Pattern.compile(expression));
|
||||
} catch (ExecutionException e) {
|
||||
Throwable cause = e.getCause();
|
||||
if (cause instanceof RuntimeException runtimeException) {
|
||||
throw runtimeException;
|
||||
}
|
||||
throw new IllegalArgumentException("Некорректное регулярное выражение.", cause);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package ru.serega6531.packmate.service;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.serega6531.packmate.model.CtfService;
|
||||
import ru.serega6531.packmate.model.FoundPattern;
|
||||
import ru.serega6531.packmate.model.Pattern;
|
||||
import ru.serega6531.packmate.model.enums.PatternActionType;
|
||||
import ru.serega6531.packmate.model.enums.PatternDirectionType;
|
||||
import ru.serega6531.packmate.model.enums.SubscriptionMessageType;
|
||||
import ru.serega6531.packmate.model.pojo.PatternCreateDto;
|
||||
import ru.serega6531.packmate.model.pojo.PatternDto;
|
||||
import ru.serega6531.packmate.model.pojo.PatternUpdateDto;
|
||||
import ru.serega6531.packmate.model.pojo.SubscriptionMessage;
|
||||
import ru.serega6531.packmate.repository.PatternRepository;
|
||||
import ru.serega6531.packmate.exception.PatternValidationException;
|
||||
import ru.serega6531.packmate.exception.RequestValidationException;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class PatternService {
|
||||
|
||||
private final PatternRepository repository;
|
||||
private final StreamService streamService;
|
||||
private final SubscriptionService subscriptionService;
|
||||
|
||||
private final Map<Integer, Pattern> patterns = new ConcurrentHashMap<>();
|
||||
|
||||
@Autowired
|
||||
public PatternService(PatternRepository repository,
|
||||
@Lazy StreamService streamService,
|
||||
SubscriptionService subscriptionService) {
|
||||
this.repository = repository;
|
||||
this.streamService = streamService;
|
||||
this.subscriptionService = subscriptionService;
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
repository.findAll().forEach(p -> patterns.put(p.getId(), p));
|
||||
log.info("Загружено паттернов: {}", patterns.size());
|
||||
}
|
||||
|
||||
public Pattern find(int id) {
|
||||
return patterns.get(id);
|
||||
}
|
||||
|
||||
public Collection<Pattern> findAll() {
|
||||
return patterns.values();
|
||||
}
|
||||
|
||||
public Set<FoundPattern> findMatches(byte[] bytes, CtfService service, PatternDirectionType directionType, PatternActionType actionType) {
|
||||
final List<Pattern> list = patterns.values().stream()
|
||||
.filter(pattern -> pattern.isEnabled() && !pattern.isDeleted())
|
||||
.filter(p -> p.getServiceId() == null || p.getServiceId().equals(service.getPort()))
|
||||
.filter(p -> p.getActionType() == actionType)
|
||||
.filter(p -> p.getDirectionType() == directionType || p.getDirectionType() == PatternDirectionType.BOTH)
|
||||
.toList();
|
||||
return new PatternMatcher(bytes, list).findMatches();
|
||||
}
|
||||
|
||||
public Set<FoundPattern> matchOne(byte[] bytes, Pattern pattern) {
|
||||
return new PatternMatcher(bytes, List.of(pattern)).findMatches();
|
||||
}
|
||||
|
||||
public void enable(int id, boolean enabled) {
|
||||
RequestValidation.requireIdentifier(id, "Идентификатор паттерна");
|
||||
final Pattern pattern = find(id);
|
||||
if (pattern != null) {
|
||||
pattern.setEnabled(enabled);
|
||||
final Pattern saved = repository.save(pattern);
|
||||
patterns.put(id, saved);
|
||||
|
||||
if (enabled) {
|
||||
log.info("Паттерн включен: id={}", id);
|
||||
subscriptionService.broadcast(new SubscriptionMessage(SubscriptionMessageType.ENABLE_PATTERN, id));
|
||||
} else {
|
||||
log.info("Паттерн приостановлен: id={}", id);
|
||||
subscriptionService.broadcast(new SubscriptionMessage(SubscriptionMessageType.DISABLE_PATTERN, id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void delete(int id) {
|
||||
RequestValidation.requireIdentifier(id, "Идентификатор паттерна");
|
||||
final Pattern pattern = find(id);
|
||||
if (pattern != null) {
|
||||
pattern.setDeleted(true);
|
||||
final Pattern saved = repository.save(pattern);
|
||||
patterns.put(id, saved);
|
||||
|
||||
log.info("Паттерн удален: id={}", id);
|
||||
subscriptionService.broadcast(new SubscriptionMessage(SubscriptionMessageType.SAVE_PATTERN, toDto(saved)));
|
||||
}
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public PatternDto create(PatternCreateDto dto) {
|
||||
validateCreate(dto);
|
||||
Pattern pattern = fromDto(dto);
|
||||
|
||||
pattern.setEnabled(true);
|
||||
pattern.setDeleted(false);
|
||||
pattern.setSearchStartTimestamp(System.currentTimeMillis());
|
||||
|
||||
Pattern saved = save(pattern);
|
||||
return toDto(saved);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public PatternDto update(int id, PatternUpdateDto dto) {
|
||||
RequestValidation.requireIdentifier(id, "Идентификатор паттерна");
|
||||
if (dto == null) {
|
||||
throw new RequestValidationException("Не переданы параметры паттерна.");
|
||||
}
|
||||
RequestValidation.requireName(dto.getName(), "Название паттерна");
|
||||
RequestValidation.requirePatternColor(dto.getColor());
|
||||
Pattern pattern = repository.findById(id).orElseThrow();
|
||||
|
||||
pattern.setName(dto.getName());
|
||||
pattern.setColor(dto.getColor());
|
||||
|
||||
Pattern saved = save(pattern);
|
||||
return toDto(saved);
|
||||
}
|
||||
|
||||
private Pattern save(Pattern pattern) {
|
||||
try {
|
||||
PatternMatcher.compilePattern(pattern);
|
||||
} catch (IllegalArgumentException e) {
|
||||
String message = pattern.getSearchType() == ru.serega6531.packmate.model.enums.PatternSearchType.REGEX
|
||||
? "Некорректный шаблон регулярного выражения. Используется RE2/J; lookaround и обратные ссылки не поддерживаются."
|
||||
: "Некорректное значение шаблона. Проверьте текст или шестнадцатеричную запись байтов.";
|
||||
throw new PatternValidationException(message, e);
|
||||
}
|
||||
|
||||
final Pattern saved = repository.save(pattern);
|
||||
patterns.put(saved.getId(), saved);
|
||||
|
||||
log.info("Создан паттерн id={}", saved.getId());
|
||||
subscriptionService.broadcast(new SubscriptionMessage(SubscriptionMessageType.SAVE_PATTERN, toDto(saved)));
|
||||
|
||||
return saved;
|
||||
}
|
||||
|
||||
public void lookBack(int id, int minutes) {
|
||||
RequestValidation.requireIdentifier(id, "Идентификатор паттерна");
|
||||
RequestValidation.requireLookback(minutes);
|
||||
final Pattern pattern = find(id);
|
||||
if (pattern != null && pattern.getActionType() == PatternActionType.FIND) {
|
||||
long end = pattern.getSearchStartTimestamp();
|
||||
long start = end - TimeUnit.MINUTES.toMillis(minutes);
|
||||
|
||||
pattern.setSearchStartTimestamp(start);
|
||||
repository.save(pattern);
|
||||
|
||||
log.info("Поиск по паттерну id={} с {} по {}", id,
|
||||
Instant.ofEpochMilli(start), Instant.ofEpochMilli(end));
|
||||
streamService.processLookbackPattern(pattern, start, end);
|
||||
}
|
||||
}
|
||||
|
||||
public Pattern fromDto(PatternCreateDto dto) {
|
||||
Pattern pattern = new Pattern();
|
||||
pattern.setName(dto.getName());
|
||||
pattern.setValue(dto.getValue());
|
||||
pattern.setColor(dto.getColor());
|
||||
pattern.setSearchType(dto.getSearchType());
|
||||
pattern.setDirectionType(dto.getDirectionType());
|
||||
pattern.setActionType(dto.getActionType());
|
||||
pattern.setServiceId(dto.getServiceId());
|
||||
return pattern;
|
||||
}
|
||||
|
||||
public PatternDto toDto(Pattern pattern) {
|
||||
PatternDto dto = new PatternDto();
|
||||
dto.setId(pattern.getId());
|
||||
dto.setEnabled(pattern.isEnabled());
|
||||
dto.setDeleted(pattern.isDeleted());
|
||||
dto.setName(pattern.getName());
|
||||
dto.setValue(pattern.getValue());
|
||||
dto.setColor(pattern.getColor());
|
||||
dto.setSearchType(pattern.getSearchType());
|
||||
dto.setDirectionType(pattern.getDirectionType());
|
||||
dto.setActionType(pattern.getActionType());
|
||||
dto.setServiceId(pattern.getServiceId());
|
||||
return dto;
|
||||
}
|
||||
|
||||
private void validateCreate(PatternCreateDto dto) {
|
||||
if (dto == null) {
|
||||
throw new RequestValidationException("Не переданы параметры паттерна.");
|
||||
}
|
||||
RequestValidation.requireName(dto.getName(), "Название паттерна");
|
||||
RequestValidation.requirePatternValue(dto.getValue());
|
||||
RequestValidation.requirePatternColor(dto.getColor());
|
||||
if (dto.getSearchType() == null || dto.getDirectionType() == null || dto.getActionType() == null) {
|
||||
throw new RequestValidationException("Нужно указать способ поиска, направление и действие паттерна.");
|
||||
}
|
||||
if (dto.getServiceId() != null) {
|
||||
RequestValidation.requirePort(dto.getServiceId());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
package ru.serega6531.packmate.service;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.pcap4j.core.PcapNativeException;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import ru.serega6531.packmate.model.enums.SubscriptionMessageType;
|
||||
import ru.serega6531.packmate.model.pojo.ServiceDto;
|
||||
import ru.serega6531.packmate.model.pojo.SubscriptionMessage;
|
||||
import ru.serega6531.packmate.pcap.NoOpPcapWorker;
|
||||
import ru.serega6531.packmate.pcap.PcapWorker;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class PcapService {
|
||||
|
||||
private volatile boolean started = false;
|
||||
|
||||
private final SubscriptionService subscriptionService;
|
||||
private final PcapWorker worker;
|
||||
|
||||
@Autowired
|
||||
public PcapService(SubscriptionService subscriptionService, PcapWorker worker) {
|
||||
this.subscriptionService = subscriptionService;
|
||||
this.worker = worker;
|
||||
}
|
||||
|
||||
public boolean isStarted() {
|
||||
return started || worker instanceof NoOpPcapWorker;
|
||||
}
|
||||
|
||||
public synchronized void start() throws PcapNativeException {
|
||||
if (!started) {
|
||||
worker.start(this::markStarted, this::markStopped);
|
||||
}
|
||||
}
|
||||
|
||||
private synchronized void markStarted() {
|
||||
started = true;
|
||||
subscriptionService.broadcast(new SubscriptionMessage(SubscriptionMessageType.PCAP_STARTED, null));
|
||||
}
|
||||
|
||||
private synchronized void markStopped() {
|
||||
if (started) {
|
||||
started = false;
|
||||
subscriptionService.broadcast(new SubscriptionMessage(SubscriptionMessageType.PCAP_STOPPED, null));
|
||||
}
|
||||
}
|
||||
|
||||
public void updateFilter(Collection<ServiceDto> services) {
|
||||
String filter;
|
||||
|
||||
if (services.isEmpty()) {
|
||||
filter = "tcp or udp";
|
||||
} else {
|
||||
final String ports = services.stream()
|
||||
.map(ServiceDto::getPort)
|
||||
.map(p -> "port " + p)
|
||||
.collect(Collectors.joining(" or "));
|
||||
|
||||
final String format = "(tcp or udp) and (%s)";
|
||||
filter = String.format(format, ports);
|
||||
}
|
||||
|
||||
log.debug("Новый фильтр: {}", filter);
|
||||
|
||||
worker.setFilter(filter);
|
||||
}
|
||||
|
||||
public String getExecutorState() {
|
||||
return worker.getExecutorState();
|
||||
}
|
||||
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package ru.serega6531.packmate.service;
|
||||
|
||||
import ru.serega6531.packmate.exception.RequestValidationException;
|
||||
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public final class RequestValidation {
|
||||
|
||||
private static final int MAX_PAGE_SIZE = 500;
|
||||
private static final int MAX_NAME_LENGTH = 100;
|
||||
private static final int MAX_PATTERN_LENGTH = 4096;
|
||||
private static final int MAX_LOOKBACK_MINUTES = 10_080;
|
||||
private static final Pattern COLOR = Pattern.compile(
|
||||
"(?i)^(#[0-9a-f]{3}(?:[0-9a-f]{3})?|red|green|blue|orange|purple|teal|yellow|white|black|gray|grey)$"
|
||||
);
|
||||
|
||||
private RequestValidation() {}
|
||||
|
||||
public static void requirePort(int port) {
|
||||
if (port < 1 || port > 65_535) {
|
||||
throw new RequestValidationException("Порт должен быть в диапазоне от 1 до 65535.");
|
||||
}
|
||||
}
|
||||
|
||||
public static void requireIdentifier(long identifier, String label) {
|
||||
if (identifier < 1) {
|
||||
throw new RequestValidationException(label + " должен быть положительным числом.");
|
||||
}
|
||||
}
|
||||
|
||||
public static void requireName(String value, String label) {
|
||||
if (value == null || value.isBlank() || value.length() > MAX_NAME_LENGTH) {
|
||||
throw new RequestValidationException(label + " должен содержать от 1 до 100 символов.");
|
||||
}
|
||||
}
|
||||
|
||||
public static void requirePatternValue(String value) {
|
||||
if (value == null || value.isBlank() || value.length() > MAX_PATTERN_LENGTH) {
|
||||
throw new RequestValidationException("Значение паттерна должно содержать от 1 до 4096 символов.");
|
||||
}
|
||||
}
|
||||
|
||||
public static void requirePatternColor(String value) {
|
||||
if (value == null || !COLOR.matcher(value).matches()) {
|
||||
throw new RequestValidationException("Цвет паттерна задан в неподдерживаемом формате.");
|
||||
}
|
||||
}
|
||||
|
||||
public static void requirePage(Long startingFrom, int pageSize) {
|
||||
if (startingFrom != null && startingFrom < 1) {
|
||||
throw new RequestValidationException("Идентификатор начала страницы должен быть положительным.");
|
||||
}
|
||||
if (pageSize < 1 || pageSize > MAX_PAGE_SIZE) {
|
||||
throw new RequestValidationException("Размер страницы должен быть в диапазоне от 1 до 500.");
|
||||
}
|
||||
}
|
||||
|
||||
public static void requireLookback(int minutes) {
|
||||
if (minutes < 1 || minutes > MAX_LOOKBACK_MINUTES) {
|
||||
throw new RequestValidationException("Период поиска должен быть от 1 до 10080 минут.");
|
||||
}
|
||||
}
|
||||
}
|
||||
+152
@@ -0,0 +1,152 @@
|
||||
package ru.serega6531.packmate.service;
|
||||
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.serega6531.packmate.properties.PackmateProperties;
|
||||
import ru.serega6531.packmate.model.CtfService;
|
||||
import ru.serega6531.packmate.model.enums.SubscriptionMessageType;
|
||||
import ru.serega6531.packmate.model.pojo.ServiceCreateDto;
|
||||
import ru.serega6531.packmate.model.pojo.ServiceDto;
|
||||
import ru.serega6531.packmate.model.pojo.ServiceUpdateDto;
|
||||
import ru.serega6531.packmate.model.pojo.SubscriptionMessage;
|
||||
import ru.serega6531.packmate.repository.ServiceRepository;
|
||||
import ru.serega6531.packmate.exception.RequestValidationException;
|
||||
|
||||
import java.net.InetAddress;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class ServicesService {
|
||||
|
||||
private final ServiceRepository repository;
|
||||
private final SubscriptionService subscriptionService;
|
||||
private final PcapService pcapService;
|
||||
|
||||
private final InetAddress localIp;
|
||||
|
||||
private final Map<Integer, CtfService> services = new ConcurrentHashMap<>();
|
||||
private final ModelMapper modelMapper;
|
||||
|
||||
@Autowired
|
||||
public ServicesService(ServiceRepository repository,
|
||||
SubscriptionService subscriptionService,
|
||||
@Lazy PcapService pcapService,
|
||||
ModelMapper modelMapper,
|
||||
PackmateProperties properties) {
|
||||
this.repository = repository;
|
||||
this.subscriptionService = subscriptionService;
|
||||
this.pcapService = pcapService;
|
||||
this.modelMapper = modelMapper;
|
||||
this.localIp = properties.localIp();
|
||||
}
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
repository.findAll().forEach(s -> services.put(s.getPort(), s));
|
||||
log.info("Загружено служб: {}", services.size());
|
||||
}
|
||||
|
||||
public CtfService find(int id) {
|
||||
return services.get(id);
|
||||
}
|
||||
|
||||
public Optional<CtfService> findService(InetAddress firstIp, int firstPort, InetAddress secondIp, int secondPort) {
|
||||
if (firstIp.equals(localIp)) {
|
||||
return findByPort(firstPort);
|
||||
} else if (secondIp.equals(localIp)) {
|
||||
return findByPort(secondPort);
|
||||
}
|
||||
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
private Optional<CtfService> findByPort(int port) {
|
||||
return Optional.ofNullable(services.get(port));
|
||||
}
|
||||
|
||||
public List<ServiceDto> findAll() {
|
||||
return services.values()
|
||||
.stream()
|
||||
.map(this::toDto)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public void deleteByPort(int port) {
|
||||
RequestValidation.requirePort(port);
|
||||
log.info("Удалена служба на порту {}", port);
|
||||
|
||||
services.remove(port);
|
||||
repository.deleteById(port);
|
||||
|
||||
subscriptionService.broadcast(new SubscriptionMessage(SubscriptionMessageType.DELETE_SERVICE, port));
|
||||
|
||||
updateFilter();
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ServiceDto create(ServiceCreateDto dto) {
|
||||
if (dto == null) {
|
||||
throw new RequestValidationException("Не переданы параметры службы.");
|
||||
}
|
||||
RequestValidation.requirePort(dto.getPort());
|
||||
RequestValidation.requireName(dto.getName(), "Название службы");
|
||||
if (repository.existsById(dto.getPort())) {
|
||||
throw new RequestValidationException("Служба с таким портом уже существует.");
|
||||
}
|
||||
|
||||
CtfService service = fromDto(dto);
|
||||
|
||||
log.info("Добавлена служба на порту {}", service.getPort());
|
||||
|
||||
return save(service);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public ServiceDto update(int port, ServiceUpdateDto dto) {
|
||||
RequestValidation.requirePort(port);
|
||||
if (dto == null) {
|
||||
throw new RequestValidationException("Не переданы параметры службы.");
|
||||
}
|
||||
RequestValidation.requireName(dto.getName(), "Название службы");
|
||||
CtfService service = repository.findById(port).orElseThrow();
|
||||
|
||||
log.info("Изменена служба на порту {}", service.getPort());
|
||||
|
||||
modelMapper.map(dto, service);
|
||||
service.setPort(port);
|
||||
return save(service);
|
||||
}
|
||||
|
||||
private ServiceDto save(CtfService service) {
|
||||
final CtfService saved = repository.save(service);
|
||||
services.put(saved.getPort(), saved);
|
||||
|
||||
subscriptionService.broadcast(new SubscriptionMessage(SubscriptionMessageType.SAVE_SERVICE, toDto(saved)));
|
||||
|
||||
updateFilter();
|
||||
|
||||
return toDto(saved);
|
||||
}
|
||||
|
||||
public void updateFilter() {
|
||||
pcapService.updateFilter(findAll());
|
||||
}
|
||||
|
||||
private ServiceDto toDto(CtfService service) {
|
||||
return modelMapper.map(service, ServiceDto.class);
|
||||
}
|
||||
|
||||
private CtfService fromDto(ServiceCreateDto dto) {
|
||||
return modelMapper.map(dto, CtfService.class);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,358 @@
|
||||
package ru.serega6531.packmate.service;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.jetbrains.annotations.Nullable;
|
||||
import org.modelmapper.ModelMapper;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.jpa.domain.Specification;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Propagation;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import ru.serega6531.packmate.properties.PackmateProperties;
|
||||
import ru.serega6531.packmate.model.CtfService;
|
||||
import ru.serega6531.packmate.model.FoundPattern;
|
||||
import ru.serega6531.packmate.model.Packet;
|
||||
import ru.serega6531.packmate.model.Pattern;
|
||||
import ru.serega6531.packmate.model.Stream;
|
||||
import ru.serega6531.packmate.model.enums.PatternActionType;
|
||||
import ru.serega6531.packmate.model.enums.PatternDirectionType;
|
||||
import ru.serega6531.packmate.model.enums.SubscriptionMessageType;
|
||||
import ru.serega6531.packmate.model.pojo.PacketDto;
|
||||
import ru.serega6531.packmate.model.pojo.StreamDto;
|
||||
import ru.serega6531.packmate.model.pojo.StreamPagination;
|
||||
import ru.serega6531.packmate.model.pojo.SubscriptionMessage;
|
||||
import ru.serega6531.packmate.model.pojo.UnfinishedStream;
|
||||
import ru.serega6531.packmate.exception.RequestValidationException;
|
||||
import ru.serega6531.packmate.repository.StreamRepository;
|
||||
import ru.serega6531.packmate.service.optimization.RsaKeysHolder;
|
||||
import ru.serega6531.packmate.service.optimization.StreamOptimizer;
|
||||
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Matcher;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class StreamService {
|
||||
|
||||
private final StreamRepository repository;
|
||||
private final PatternService patternService;
|
||||
private final ServicesService servicesService;
|
||||
private final CountingService countingService;
|
||||
private final SubscriptionService subscriptionService;
|
||||
private final RsaKeysHolder keysHolder;
|
||||
private final ModelMapper modelMapper;
|
||||
private final boolean ignoreEmptyPackets;
|
||||
|
||||
private final java.util.regex.Pattern userAgentPattern = java.util.regex.Pattern.compile("User-Agent: (.+)\\r\\n");
|
||||
|
||||
@Autowired
|
||||
public StreamService(StreamRepository repository,
|
||||
PatternService patternService,
|
||||
ServicesService servicesService,
|
||||
CountingService countingService,
|
||||
SubscriptionService subscriptionService,
|
||||
RsaKeysHolder keysHolder,
|
||||
ModelMapper modelMapper,
|
||||
PackmateProperties properties) {
|
||||
this.repository = repository;
|
||||
this.patternService = patternService;
|
||||
this.servicesService = servicesService;
|
||||
this.countingService = countingService;
|
||||
this.subscriptionService = subscriptionService;
|
||||
this.keysHolder = keysHolder;
|
||||
this.modelMapper = modelMapper;
|
||||
this.ignoreEmptyPackets = properties.ignoreEmptyPackets();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true, если поток сохранен
|
||||
*/
|
||||
@Transactional(propagation = Propagation.NEVER)
|
||||
public boolean saveNewStream(UnfinishedStream unfinishedStream, List<Packet> packets) {
|
||||
final var serviceOptional = servicesService.findService(
|
||||
unfinishedStream.firstIp(),
|
||||
unfinishedStream.firstPort(),
|
||||
unfinishedStream.secondIp(),
|
||||
unfinishedStream.secondPort()
|
||||
);
|
||||
|
||||
if (serviceOptional.isEmpty()) {
|
||||
log.warn("Не удалось сохранить поток: служба на порту {} или {} не существует",
|
||||
unfinishedStream.firstPort(), unfinishedStream.secondPort());
|
||||
return false;
|
||||
}
|
||||
CtfService service = serviceOptional.get();
|
||||
|
||||
if (ignoreEmptyPackets) {
|
||||
packets.removeIf(packet -> packet.getContent().length == 0);
|
||||
|
||||
if (packets.isEmpty()) {
|
||||
log.debug("Поток содержит только пустые пакеты и не будет сохранен");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
countingService.countStream(service.getPort(), packets.size());
|
||||
|
||||
int packetsSize = packets.stream().mapToInt(p -> p.getContent().length).sum();
|
||||
int packetsCount = packets.size();
|
||||
|
||||
List<Packet> optimizedPackets = new StreamOptimizer(keysHolder, service, packets).optimizeStream();
|
||||
|
||||
if (isStreamIgnored(optimizedPackets, service)) {
|
||||
log.debug("Новый поток пропущен");
|
||||
return false;
|
||||
}
|
||||
|
||||
Optional<Packet> firstIncoming = packets.stream()
|
||||
.filter(Packet::isIncoming)
|
||||
.findFirst();
|
||||
|
||||
final Stream stream = new Stream();
|
||||
stream.setProtocol(unfinishedStream.protocol());
|
||||
stream.setTtl(firstIncoming.map(Packet::getTtl).orElse(0));
|
||||
stream.setStartTimestamp(packets.get(0).getTimestamp());
|
||||
stream.setEndTimestamp(packets.get(packets.size() - 1).getTimestamp());
|
||||
stream.setService(service.getPort());
|
||||
|
||||
String userAgentHash = getUserAgentHash(optimizedPackets);
|
||||
stream.setUserAgentHash(userAgentHash);
|
||||
|
||||
stream.setSizeBytes(packetsSize);
|
||||
stream.setPacketsCount(packetsCount);
|
||||
|
||||
Set<Pattern> foundPatterns = matchPatterns(optimizedPackets, service);
|
||||
stream.setFoundPatterns(foundPatterns);
|
||||
stream.setPackets(optimizedPackets);
|
||||
|
||||
for (Packet packet : optimizedPackets) {
|
||||
packet.setStream(stream);
|
||||
}
|
||||
|
||||
Stream savedStream = save(stream);
|
||||
|
||||
subscriptionService.broadcast(new SubscriptionMessage(SubscriptionMessageType.NEW_STREAM, streamToDto(savedStream)));
|
||||
return true;
|
||||
}
|
||||
|
||||
@Async
|
||||
@Transactional
|
||||
public void processLookbackPattern(Pattern pattern, long start, long end) {
|
||||
List<Stream> streams = findAllBetweenTimestamps(start, end);
|
||||
|
||||
for (Stream stream : streams) {
|
||||
boolean found = matchPattern(stream.getPackets(), pattern);
|
||||
if (found) {
|
||||
stream.getFoundPatterns().add(pattern);
|
||||
repository.save(stream);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("Завершен поиск по паттерну '{}'", pattern.getName());
|
||||
subscriptionService.broadcast(new SubscriptionMessage(SubscriptionMessageType.FINISH_LOOKBACK, pattern.getId()));
|
||||
}
|
||||
|
||||
private String getUserAgentHash(List<Packet> packets) {
|
||||
String ua = null;
|
||||
for (Packet packet : packets) {
|
||||
String content = packet.getContentString();
|
||||
final Matcher matcher = userAgentPattern.matcher(content);
|
||||
if (matcher.find()) {
|
||||
ua = matcher.group(1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (ua != null) {
|
||||
return calculateUserAgentHash(ua);
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private String calculateUserAgentHash(String ua) {
|
||||
char[] alphabet = "abcdefghijklmnopqrstuvwxyz0123456789".toCharArray();
|
||||
int l = alphabet.length;
|
||||
int hashCode = ua.hashCode();
|
||||
if (hashCode == Integer.MIN_VALUE) { // abs(MIN_VALUE) вернет то же значение
|
||||
hashCode = Integer.MAX_VALUE;
|
||||
}
|
||||
final int hash = Math.abs(hashCode) % (l * l * l);
|
||||
return "" + alphabet[hash % l] + alphabet[(hash / l) % l] + alphabet[(hash / (l * l)) % l];
|
||||
}
|
||||
|
||||
private Set<Pattern> matchPatterns(List<Packet> packets, CtfService service) {
|
||||
Set<Pattern> foundPatterns = new HashSet<>();
|
||||
|
||||
for (Packet packet : packets) {
|
||||
PatternDirectionType direction = packet.isIncoming() ? PatternDirectionType.INPUT : PatternDirectionType.OUTPUT;
|
||||
final Set<FoundPattern> matches = patternService.findMatches(packet.getContent(), service,
|
||||
direction, PatternActionType.FIND);
|
||||
|
||||
packet.setMatches(matches);
|
||||
matches.forEach(m -> m.setPacket(packet));
|
||||
|
||||
foundPatterns.addAll(matches.stream()
|
||||
.map(FoundPattern::getPatternId)
|
||||
.map(patternService::find)
|
||||
.toList());
|
||||
}
|
||||
|
||||
return foundPatterns;
|
||||
}
|
||||
|
||||
private boolean matchPattern(List<Packet> packets, Pattern pattern) {
|
||||
boolean matched = false;
|
||||
|
||||
for (Packet packet : packets) {
|
||||
PatternDirectionType direction = packet.isIncoming() ? PatternDirectionType.INPUT : PatternDirectionType.OUTPUT;
|
||||
|
||||
if (pattern.getDirectionType() != PatternDirectionType.BOTH && pattern.getDirectionType() != direction) {
|
||||
continue;
|
||||
}
|
||||
|
||||
final Set<FoundPattern> matches = patternService.matchOne(packet.getContent(), pattern);
|
||||
|
||||
if (!matches.isEmpty()) {
|
||||
packet.getMatches().addAll(matches);
|
||||
matches.forEach(m -> m.setPacket(packet));
|
||||
|
||||
matched = true;
|
||||
}
|
||||
}
|
||||
|
||||
return matched;
|
||||
}
|
||||
|
||||
private boolean isStreamIgnored(List<Packet> packets, CtfService service) {
|
||||
for (Packet packet : packets) {
|
||||
PatternDirectionType direction = packet.isIncoming() ? PatternDirectionType.INPUT : PatternDirectionType.OUTPUT;
|
||||
final Set<FoundPattern> matches = patternService.findMatches(packet.getContent(), service,
|
||||
direction, PatternActionType.IGNORE);
|
||||
if (!matches.isEmpty()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private Stream save(Stream stream) {
|
||||
Stream saved;
|
||||
if (stream.getId() == null) {
|
||||
saved = repository.save(stream);
|
||||
log.debug("Сохранен поток с идентификатором {}", saved.getId());
|
||||
} else {
|
||||
saved = repository.save(stream);
|
||||
}
|
||||
|
||||
return saved;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<PacketDto> getPackets(long streamId, @Nullable Long startingFrom, int pageSize) {
|
||||
RequestValidation.requireIdentifier(streamId, "Идентификатор потока");
|
||||
RequestValidation.requirePage(startingFrom, pageSize);
|
||||
return repository.getPackets(streamId, startingFrom, Pageable.ofSize(pageSize))
|
||||
.stream()
|
||||
.map(this::packetToDto)
|
||||
.toList();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return количество удаленных записей
|
||||
*/
|
||||
@Transactional
|
||||
public long cleanupOldStreams(ZonedDateTime before) {
|
||||
return repository.deleteByEndTimestampBeforeAndFavoriteIsFalse(before.toEpochSecond() * 1000);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void setFavorite(long id, boolean favorite) {
|
||||
RequestValidation.requireIdentifier(id, "Идентификатор потока");
|
||||
repository.setFavorite(id, favorite);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public List<StreamDto> findAll(StreamPagination pagination, Optional<Integer> service, boolean onlyFavorites) {
|
||||
if (pagination == null) {
|
||||
throw new RequestValidationException("Не переданы параметры страницы.");
|
||||
}
|
||||
RequestValidation.requirePage(pagination.getStartingFrom(), pagination.getPageSize());
|
||||
service.ifPresent(RequestValidation::requirePort);
|
||||
if (pagination.getPattern() != null) {
|
||||
Integer patternId = pagination.getPattern().getId();
|
||||
if (patternId == null) {
|
||||
throw new RequestValidationException("Не указан идентификатор паттерна.");
|
||||
}
|
||||
RequestValidation.requireIdentifier(patternId, "Идентификатор паттерна");
|
||||
}
|
||||
PageRequest page = PageRequest.of(0, pagination.getPageSize(), Sort.Direction.DESC, "id");
|
||||
|
||||
Specification<Stream> spec = Specification.unrestricted();
|
||||
|
||||
if (pagination.getStartingFrom() != null) {
|
||||
spec = spec.and(streamIdLessThan(pagination.getStartingFrom()));
|
||||
}
|
||||
|
||||
if (service.isPresent()) {
|
||||
spec = spec.and(streamServiceEquals(service.get()));
|
||||
}
|
||||
|
||||
if (onlyFavorites) {
|
||||
spec = spec.and(streamIsFavorite());
|
||||
}
|
||||
|
||||
if (pagination.getPattern() != null) {
|
||||
spec = spec.and(streamPatternsContains(pagination.getPattern()));
|
||||
}
|
||||
|
||||
return repository.findAll(spec, page)
|
||||
.getContent()
|
||||
.stream()
|
||||
.map(this::streamToDto)
|
||||
.toList();
|
||||
}
|
||||
|
||||
public List<Stream> findAllBetweenTimestamps(long start, long end) {
|
||||
Specification<Stream> spec = streamTimestampBetween(start, end);
|
||||
return repository.findAll(spec);
|
||||
}
|
||||
|
||||
public StreamDto streamToDto(Stream stream) {
|
||||
return modelMapper.map(stream, StreamDto.class);
|
||||
}
|
||||
|
||||
public PacketDto packetToDto(Packet packet) {
|
||||
return modelMapper.map(packet, PacketDto.class);
|
||||
}
|
||||
|
||||
private Specification<Stream> streamServiceEquals(long service) {
|
||||
return (root, query, cb) -> cb.equal(root.get("service"), service);
|
||||
}
|
||||
|
||||
private Specification<Stream> streamIsFavorite() {
|
||||
return (root, query, cb) -> cb.equal(root.get("favorite"), true);
|
||||
}
|
||||
|
||||
private Specification<Stream> streamIdLessThan(long id) {
|
||||
return (root, query, cb) -> cb.lessThan(root.get("id"), id);
|
||||
}
|
||||
|
||||
private Specification<Stream> streamTimestampBetween(long start, long end) {
|
||||
return (root, query, cb) -> cb.between(root.get("startTimestamp"), start, end);
|
||||
}
|
||||
|
||||
private Specification<Stream> streamPatternsContains(Pattern pattern) {
|
||||
return (root, query, cb) -> cb.isMember(pattern, root.get("foundPatterns"));
|
||||
}
|
||||
|
||||
}
|
||||
+67
@@ -0,0 +1,67 @@
|
||||
package ru.serega6531.packmate.service;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.socket.TextMessage;
|
||||
import org.springframework.web.socket.WebSocketSession;
|
||||
import org.springframework.web.socket.CloseStatus;
|
||||
import org.springframework.web.socket.handler.ConcurrentWebSocketSessionDecorator;
|
||||
import tools.jackson.core.JacksonException;
|
||||
import tools.jackson.databind.ObjectMapper;
|
||||
import ru.serega6531.packmate.model.pojo.SubscriptionMessage;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class SubscriptionService {
|
||||
|
||||
private final Map<String, WebSocketSession> subscribers = new ConcurrentHashMap<>();
|
||||
|
||||
private final ObjectMapper mapper;
|
||||
|
||||
@Autowired
|
||||
public SubscriptionService(ObjectMapper mapper) {
|
||||
this.mapper = mapper;
|
||||
}
|
||||
|
||||
public void addSubscriber(WebSocketSession session) {
|
||||
subscribers.put(session.getId(), new ConcurrentWebSocketSessionDecorator(session, 5000, 1024 * 1024));
|
||||
log.info("Подписан клиент: {}", session.getId());
|
||||
}
|
||||
|
||||
public void removeSubscriber(WebSocketSession session) {
|
||||
subscribers.remove(session.getId());
|
||||
log.info("Отписан клиент: {}", session.getId());
|
||||
}
|
||||
|
||||
/**
|
||||
* Вызов потокобезопасный
|
||||
*/
|
||||
@SneakyThrows
|
||||
public void broadcast(SubscriptionMessage message) {
|
||||
final TextMessage messageJson = objectToTextMessage(message);
|
||||
subscribers.forEach((id, s) -> {
|
||||
try {
|
||||
s.sendMessage(messageJson);
|
||||
} catch (IOException | IllegalStateException e) {
|
||||
subscribers.remove(id, s);
|
||||
log.warn("Соединение WebSocket закрыто после ошибки отправки: {}", id);
|
||||
try {
|
||||
s.close(CloseStatus.SERVER_ERROR);
|
||||
} catch (IOException ignored) {
|
||||
// Соединение уже недоступно.
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private TextMessage objectToTextMessage(SubscriptionMessage object) throws JacksonException {
|
||||
return new TextMessage(mapper.writeValueAsString(object));
|
||||
}
|
||||
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package ru.serega6531.packmate.service.optimization;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import rawhttp.core.HttpMessage;
|
||||
import rawhttp.core.RawHttp;
|
||||
import rawhttp.core.RawHttpOptions;
|
||||
import rawhttp.core.body.BodyReader;
|
||||
import rawhttp.core.errors.InvalidHttpHeader;
|
||||
import rawhttp.core.errors.InvalidHttpRequest;
|
||||
import rawhttp.core.errors.InvalidHttpResponse;
|
||||
import rawhttp.core.errors.InvalidMessageFrame;
|
||||
import rawhttp.core.errors.UnknownEncodingException;
|
||||
import ru.serega6531.packmate.model.Packet;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Slf4j
|
||||
public class HttpProcessor {
|
||||
|
||||
private static final RawHttp rawHttp = new RawHttp(RawHttpOptions.strict());
|
||||
|
||||
public void process(List<Packet> packets) {
|
||||
packets.stream()
|
||||
.filter(p -> !p.isWebSocketParsed())
|
||||
.forEach(this::processPacket);
|
||||
}
|
||||
|
||||
private void processPacket(Packet packet) {
|
||||
try {
|
||||
ByteArrayInputStream contentStream = new ByteArrayInputStream(packet.getContent());
|
||||
HttpMessage message;
|
||||
|
||||
if (packet.isIncoming()) {
|
||||
message = rawHttp.parseRequest(contentStream).eagerly();
|
||||
} else {
|
||||
message = rawHttp.parseResponse(contentStream).eagerly();
|
||||
}
|
||||
|
||||
packet.setContent(getDecodedMessage(message));
|
||||
packet.setHasHttpBody(message.getBody().isPresent());
|
||||
} catch (IOException | InvalidHttpRequest | InvalidHttpResponse | InvalidHttpHeader | InvalidMessageFrame |
|
||||
UnknownEncodingException e) {
|
||||
log.warn("Не удалось разобрать HTTP-пакет", e);
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] getDecodedMessage(HttpMessage message) throws IOException {
|
||||
ByteArrayOutputStream os = new ByteArrayOutputStream(256);
|
||||
|
||||
message.getStartLine().writeTo(os);
|
||||
message.getHeaders().writeTo(os);
|
||||
|
||||
Optional<? extends BodyReader> body = message.getBody();
|
||||
if (body.isPresent()) {
|
||||
body.get().writeDecodedTo(os, 256);
|
||||
}
|
||||
|
||||
return os.toByteArray();
|
||||
}
|
||||
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
package ru.serega6531.packmate.service.optimization;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import ru.serega6531.packmate.model.Packet;
|
||||
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
@Slf4j
|
||||
public class HttpUrldecodeProcessor {
|
||||
|
||||
/**
|
||||
* Декодирует URL-кодирование HTTP-пакетов до смены направления или конца потока.
|
||||
*/
|
||||
@SneakyThrows
|
||||
public void urldecodeRequests(List<Packet> packets) {
|
||||
boolean httpStarted = false;
|
||||
|
||||
for (Packet packet : packets) {
|
||||
if (packet.isIncoming()) {
|
||||
String content = packet.getContentString();
|
||||
if (content.contains("HTTP/")) {
|
||||
httpStarted = true;
|
||||
}
|
||||
|
||||
if (httpStarted) {
|
||||
try {
|
||||
content = URLDecoder.decode(content, StandardCharsets.UTF_8);
|
||||
packet.setContent(content.getBytes());
|
||||
} catch (IllegalArgumentException e) {
|
||||
log.warn("Не удалось декодировать URL-кодированные данные HTTP", e);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
httpStarted = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package ru.serega6531.packmate.service.optimization;
|
||||
|
||||
import ru.serega6531.packmate.model.Packet;
|
||||
import ru.serega6531.packmate.utils.PacketUtils;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public class PacketsMerger {
|
||||
|
||||
/**
|
||||
* Сжать соседние пакеты в одном направлении в один. Не склеивает WS и не-WS пакеты.
|
||||
*/
|
||||
public void mergeAdjacentPackets(List<Packet> packets) {
|
||||
int start = 0;
|
||||
int packetsInRow = 0;
|
||||
Packet previous = null;
|
||||
|
||||
for (int i = 0; i < packets.size(); i++) {
|
||||
Packet packet = packets.get(i);
|
||||
if (previous == null || !shouldBeInSameBatch(packet, previous)) {
|
||||
if (packetsInRow > 1) {
|
||||
compress(packets, start, i);
|
||||
|
||||
i = start + 1; // Переходим к элементу сразу после объединенного блока.
|
||||
}
|
||||
start = i;
|
||||
packetsInRow = 1;
|
||||
} else {
|
||||
packetsInRow++;
|
||||
}
|
||||
|
||||
previous = packet;
|
||||
}
|
||||
|
||||
if (packetsInRow > 1) {
|
||||
compress(packets, start, packets.size());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Объединяет элементы от start до end в один пакет.
|
||||
*/
|
||||
private void compress(List<Packet> packets, int start, int end) {
|
||||
final List<Packet> cut = packets.subList(start, end);
|
||||
final long timestamp = cut.get(0).getTimestamp();
|
||||
final boolean httpProcessed = cut.stream().anyMatch(Packet::isHttpProcessed);
|
||||
final boolean webSocketParsed = cut.stream().anyMatch(Packet::isWebSocketParsed);
|
||||
final boolean tlsDecrypted = cut.get(0).isTlsDecrypted();
|
||||
final boolean incoming = cut.get(0).isIncoming();
|
||||
final byte[] content = PacketUtils.mergePackets(cut);
|
||||
|
||||
packets.removeAll(cut);
|
||||
packets.add(start, Packet.builder()
|
||||
.incoming(incoming)
|
||||
.timestamp(timestamp)
|
||||
.httpProcessed(httpProcessed)
|
||||
.webSocketParsed(webSocketParsed)
|
||||
.tlsDecrypted(tlsDecrypted)
|
||||
.content(content)
|
||||
.build());
|
||||
}
|
||||
|
||||
private boolean shouldBeInSameBatch(Packet p1, Packet p2) {
|
||||
return p1.isIncoming() == p2.isIncoming() &&
|
||||
p1.isWebSocketParsed() == p2.isWebSocketParsed();
|
||||
}
|
||||
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package ru.serega6531.packmate.service.optimization;
|
||||
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.math.BigInteger;
|
||||
import java.nio.file.Files;
|
||||
import java.security.KeyFactory;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.spec.InvalidKeySpecException;
|
||||
import java.security.spec.PKCS8EncodedKeySpec;
|
||||
import java.util.Base64;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service
|
||||
@Slf4j
|
||||
public class RsaKeysHolder {
|
||||
|
||||
// Ключ: модуль N открытого ключа RSA.
|
||||
private final Map<BigInteger, RSAPrivateKey> keys = new HashMap<>();
|
||||
|
||||
public RSAPrivateKey getKey(BigInteger modulus) {
|
||||
return keys.get(modulus);
|
||||
}
|
||||
|
||||
@EventListener(ApplicationReadyEvent.class)
|
||||
public void afterStartup(ApplicationReadyEvent event) {
|
||||
log.info("Загружаются ключи RSA");
|
||||
File dir = new File("rsa_keys");
|
||||
if (dir.exists() && dir.isDirectory()) {
|
||||
for (File keyFile : Objects.requireNonNull(dir.listFiles())) {
|
||||
addKey(keyFile);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
public void addKey(File keyFile) {
|
||||
if (!keyFile.exists()) {
|
||||
throw new IllegalArgumentException("Файл ключа не существует.");
|
||||
}
|
||||
|
||||
try {
|
||||
RSAPrivateKey privateKey = loadFromFile(keyFile);
|
||||
keys.put(privateKey.getModulus(), privateKey);
|
||||
log.info("Загружен ключ RSA");
|
||||
} catch (IOException | InvalidKeySpecException e) {
|
||||
log.error("Не удалось загрузить ключ RSA", e);
|
||||
}
|
||||
}
|
||||
|
||||
private RSAPrivateKey loadFromFile(File keyFile) throws IOException, InvalidKeySpecException, NoSuchAlgorithmException {
|
||||
String content = Files.readString(keyFile.toPath());
|
||||
|
||||
content = content.replaceAll("-----BEGIN (RSA )?PRIVATE KEY-----", "")
|
||||
.replaceAll("-----END (RSA )?PRIVATE KEY-----", "")
|
||||
.replace("\n", "");
|
||||
|
||||
byte[] keyBytes = Base64.getDecoder().decode(content);
|
||||
|
||||
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
|
||||
KeyFactory kf = KeyFactory.getInstance("RSA");
|
||||
return (RSAPrivateKey) kf.generatePrivate(spec);
|
||||
}
|
||||
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package ru.serega6531.packmate.service.optimization;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import ru.serega6531.packmate.model.CtfService;
|
||||
import ru.serega6531.packmate.model.Packet;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@AllArgsConstructor
|
||||
@Slf4j
|
||||
public class StreamOptimizer {
|
||||
|
||||
private final RsaKeysHolder keysHolder;
|
||||
private final CtfService service;
|
||||
private List<Packet> packets;
|
||||
|
||||
private final PacketsMerger merger = new PacketsMerger();
|
||||
private final HttpUrldecodeProcessor urldecodeProcessor = new HttpUrldecodeProcessor();
|
||||
private final HttpProcessor httpProcessor = new HttpProcessor();
|
||||
|
||||
|
||||
/**
|
||||
* Вызвать для выполнения оптимизаций на переданном списке пакетов.
|
||||
*/
|
||||
public List<Packet> optimizeStream() {
|
||||
if (service.isDecryptTls()) {
|
||||
try {
|
||||
decryptTls();
|
||||
} catch (Exception e) {
|
||||
log.warn("Ошибка при разборе TLS-потока", e);
|
||||
return packets;
|
||||
}
|
||||
}
|
||||
|
||||
if (service.isParseWebSockets()) {
|
||||
try {
|
||||
parseWebSockets();
|
||||
} catch (Exception e) {
|
||||
log.warn("Ошибка при разборе WebSocket-потока", e);
|
||||
return packets;
|
||||
}
|
||||
}
|
||||
|
||||
if (service.isUrldecodeHttpRequests()) {
|
||||
try {
|
||||
urldecodeProcessor.urldecodeRequests(packets);
|
||||
} catch (Exception e) {
|
||||
log.warn("Ошибка при декодировании URL-кодированных данных", e);
|
||||
return packets;
|
||||
}
|
||||
}
|
||||
|
||||
if (service.isMergeAdjacentPackets() || service.isHttp()) {
|
||||
try {
|
||||
merger.mergeAdjacentPackets(packets);
|
||||
} catch (Exception e) {
|
||||
log.warn("Ошибка при объединении соседних пакетов", e);
|
||||
return packets;
|
||||
}
|
||||
}
|
||||
|
||||
if (service.isHttp()) {
|
||||
try {
|
||||
httpProcessor.process(packets);
|
||||
} catch (Exception e) {
|
||||
log.warn("Ошибка при разборе HTTP-потока", e);
|
||||
return packets;
|
||||
}
|
||||
}
|
||||
|
||||
return packets;
|
||||
}
|
||||
|
||||
private void decryptTls() {
|
||||
final TlsDecryptor tlsDecryptor = new TlsDecryptor(packets, keysHolder);
|
||||
tlsDecryptor.decryptTls();
|
||||
|
||||
if (tlsDecryptor.isParsed()) {
|
||||
packets = tlsDecryptor.getParsedPackets();
|
||||
}
|
||||
}
|
||||
|
||||
private void parseWebSockets() {
|
||||
if (!packets.get(0).getContentString().contains("HTTP/")) {
|
||||
return;
|
||||
}
|
||||
|
||||
final WebSocketsParser parser = new WebSocketsParser(packets);
|
||||
if (!parser.isParsed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
packets = parser.getParsedPackets();
|
||||
}
|
||||
|
||||
}
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
package ru.serega6531.packmate.service.optimization;
|
||||
|
||||
import com.google.common.collect.ArrayListMultimap;
|
||||
import com.google.common.collect.ListMultimap;
|
||||
import lombok.Getter;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.bouncycastle.tls.ExporterLabel;
|
||||
import org.bouncycastle.tls.PRFAlgorithm;
|
||||
import org.bouncycastle.tls.crypto.TlsSecret;
|
||||
import org.bouncycastle.tls.crypto.impl.bc.BcTlsCrypto;
|
||||
import org.bouncycastle.tls.crypto.impl.bc.BcTlsSecret;
|
||||
import org.pcap4j.packet.IllegalRawDataException;
|
||||
import org.pcap4j.util.ByteArrays;
|
||||
import ru.serega6531.packmate.model.Packet;
|
||||
import ru.serega6531.packmate.service.optimization.tls.TlsPacket;
|
||||
import ru.serega6531.packmate.service.optimization.tls.keys.TlsKeyUtils;
|
||||
import ru.serega6531.packmate.service.optimization.tls.numbers.CipherSuite;
|
||||
import ru.serega6531.packmate.service.optimization.tls.numbers.ContentType;
|
||||
import ru.serega6531.packmate.service.optimization.tls.numbers.HandshakeType;
|
||||
import ru.serega6531.packmate.service.optimization.tls.records.ApplicationDataRecord;
|
||||
import ru.serega6531.packmate.service.optimization.tls.records.HandshakeRecord;
|
||||
import ru.serega6531.packmate.service.optimization.tls.records.handshakes.*;
|
||||
|
||||
import javax.crypto.BadPaddingException;
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.IllegalBlockSizeException;
|
||||
import javax.crypto.NoSuchPaddingException;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.security.InvalidAlgorithmParameterException;
|
||||
import java.security.InvalidKeyException;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.security.cert.Certificate;
|
||||
import java.security.cert.CertificateException;
|
||||
import java.security.cert.CertificateFactory;
|
||||
import java.security.interfaces.RSAPrivateKey;
|
||||
import java.security.interfaces.RSAPublicKey;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
@Slf4j
|
||||
@RequiredArgsConstructor
|
||||
public class TlsDecryptor {
|
||||
|
||||
private static final Pattern cipherSuitePattern = Pattern.compile("TLS_RSA_WITH_([A-Z0-9_]+)_[A-Z0-9]+");
|
||||
|
||||
private final List<Packet> packets;
|
||||
private final RsaKeysHolder keysHolder;
|
||||
|
||||
@Getter
|
||||
private boolean parsed = false;
|
||||
private List<Packet> result;
|
||||
|
||||
private ListMultimap<Packet, TlsPacket.TlsHeader> tlsPackets;
|
||||
private byte[] clientRandom;
|
||||
private byte[] serverRandom;
|
||||
|
||||
public void decryptTls() {
|
||||
tlsPackets = ArrayListMultimap.create(packets.size(), 1);
|
||||
|
||||
try {
|
||||
for (Packet p : packets) {
|
||||
tlsPackets.putAll(p, createTlsHeaders(p));
|
||||
}
|
||||
} catch (IllegalRawDataException e) {
|
||||
log.warn("Не удалось разобрать TLS-пакеты", e);
|
||||
return;
|
||||
}
|
||||
|
||||
var clientHelloOpt = getHandshake(HandshakeType.CLIENT_HELLO);
|
||||
var serverHelloOpt = getHandshake(HandshakeType.SERVER_HELLO);
|
||||
|
||||
if (clientHelloOpt.isEmpty() || serverHelloOpt.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
var clientHello = (ClientHelloHandshakeRecordContent) clientHelloOpt.get();
|
||||
var serverHello = (ServerHelloHandshakeRecordContent) serverHelloOpt.get();
|
||||
|
||||
CipherSuite cipherSuite = serverHello.getCipherSuite();
|
||||
|
||||
if (cipherSuite.name().startsWith("TLS_RSA_WITH_")) {
|
||||
Matcher matcher = cipherSuitePattern.matcher(cipherSuite.name());
|
||||
//noinspection ResultOfMethodCallIgnored
|
||||
matcher.find();
|
||||
String blockCipher = matcher.group(1);
|
||||
|
||||
clientRandom = clientHello.getRandom();
|
||||
serverRandom = serverHello.getRandom();
|
||||
|
||||
decryptTlsRsa(blockCipher);
|
||||
}
|
||||
}
|
||||
|
||||
@SneakyThrows
|
||||
private void decryptTlsRsa(String blockCipher) {
|
||||
String[] blockCipherParts = blockCipher.split("_");
|
||||
String blockCipherAlgo = blockCipherParts[0];
|
||||
int blockCipherSize = Integer.parseInt(blockCipherParts[1]);
|
||||
String blockCipherMode = blockCipherParts[2];
|
||||
|
||||
if (!blockCipherAlgo.equals("AES")) {
|
||||
return;
|
||||
}
|
||||
|
||||
int keyLength = blockCipherSize / 8;
|
||||
|
||||
Optional<RSAPublicKey> publicKeyOpt = getRsaPublicKey();
|
||||
|
||||
if (publicKeyOpt.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
RSAPublicKey publicKey = publicKeyOpt.get();
|
||||
RSAPrivateKey privateKey = keysHolder.getKey(publicKey.getModulus());
|
||||
if (privateKey == null) {
|
||||
log.warn("Не найден закрытый ключ RSA для модуля сертификата");
|
||||
return;
|
||||
}
|
||||
|
||||
Optional<BcTlsSecret> preMasterOptional = getPreMaster(privateKey);
|
||||
if (preMasterOptional.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
BcTlsSecret preMaster = preMasterOptional.get();
|
||||
|
||||
byte[] randomCS = ArrayUtils.addAll(clientRandom, serverRandom);
|
||||
byte[] randomSC = ArrayUtils.addAll(serverRandom, clientRandom);
|
||||
|
||||
TlsSecret masterSecret = preMaster.deriveUsingPRF(
|
||||
PRFAlgorithm.tls_prf_sha256, ExporterLabel.master_secret, randomCS, 48);
|
||||
byte[] expanded = masterSecret.deriveUsingPRF(
|
||||
PRFAlgorithm.tls_prf_sha256, ExporterLabel.key_expansion, randomSC, 72 + keyLength * 2).extract();
|
||||
|
||||
byte[] clientMacKey = new byte[20];
|
||||
byte[] serverMacKey = new byte[20];
|
||||
byte[] clientEncryptionKey = new byte[keyLength];
|
||||
byte[] serverEncryptionKey = new byte[keyLength];
|
||||
byte[] clientIV = new byte[16];
|
||||
byte[] serverIV = new byte[16];
|
||||
|
||||
ByteBuffer bb = ByteBuffer.wrap(expanded);
|
||||
bb.get(clientMacKey);
|
||||
bb.get(serverMacKey);
|
||||
bb.get(clientEncryptionKey);
|
||||
bb.get(serverEncryptionKey);
|
||||
bb.get(clientIV);
|
||||
bb.get(serverIV);
|
||||
|
||||
Optional<Cipher> clientCipherOpt = createCipher(blockCipherMode, clientEncryptionKey, clientIV);
|
||||
Optional<Cipher> serverCipherOpt = createCipher(blockCipherMode, serverEncryptionKey, serverIV);
|
||||
|
||||
if (clientCipherOpt.isEmpty() || serverCipherOpt.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Cipher clientCipher = clientCipherOpt.get();
|
||||
Cipher serverCipher = serverCipherOpt.get();
|
||||
|
||||
result = new ArrayList<>(packets.size());
|
||||
|
||||
for (Packet packet : packets) {
|
||||
List<TlsPacket.TlsHeader> tlsData = tlsPackets.get(packet);
|
||||
|
||||
for (TlsPacket.TlsHeader tlsPacket : tlsData) {
|
||||
if (tlsPacket.getContentType() == ContentType.APPLICATION_DATA) {
|
||||
byte[] data = ((ApplicationDataRecord) tlsPacket.getRecord()).getData();
|
||||
boolean client = packet.isIncoming();
|
||||
|
||||
Cipher cipher = client ? clientCipher : serverCipher;
|
||||
byte[] decoded = cipher.doFinal(data);
|
||||
|
||||
decoded = clearDecodedData(decoded);
|
||||
|
||||
result.add(
|
||||
packet.toBuilder()
|
||||
.content(decoded)
|
||||
.tlsDecrypted(true)
|
||||
.build()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
parsed = true;
|
||||
}
|
||||
|
||||
@SneakyThrows(value = {NoSuchAlgorithmException.class, NoSuchPaddingException.class})
|
||||
private Optional<BcTlsSecret> getPreMaster(RSAPrivateKey privateKey) {
|
||||
Optional<HandshakeRecordContent> opt = getHandshake(HandshakeType.CLIENT_KEY_EXCHANGE);
|
||||
|
||||
if (opt.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
var clientKeyExchange = (BasicHandshakeRecordContent) opt.get();
|
||||
|
||||
try {
|
||||
byte[] encryptedPreMaster = TlsKeyUtils.getClientRsaPreMaster(clientKeyExchange.getContent(), 0);
|
||||
|
||||
Cipher rsa = Cipher.getInstance("RSA/ECB/PKCS1Padding");
|
||||
rsa.init(Cipher.DECRYPT_MODE, privateKey);
|
||||
byte[] preMaster = rsa.doFinal(encryptedPreMaster);
|
||||
return Optional.of(new BcTlsSecret(new BcTlsCrypto(null), preMaster));
|
||||
} catch (InvalidKeyException | IllegalBlockSizeException | BadPaddingException e) {
|
||||
log.warn("Не удалось получить предварительный ключ TLS", e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private Optional<RSAPublicKey> getRsaPublicKey() {
|
||||
var certificateHandshakeOpt = getHandshake(HandshakeType.CERTIFICATE);
|
||||
|
||||
if (certificateHandshakeOpt.isEmpty()) {
|
||||
return Optional.empty();
|
||||
}
|
||||
|
||||
var certificateHandshake = (CertificateHandshakeRecordContent) certificateHandshakeOpt.get();
|
||||
List<byte[]> chain = certificateHandshake.getRawCertificates();
|
||||
byte[] rawCertificate = chain.get(0);
|
||||
|
||||
try {
|
||||
CertificateFactory cf = CertificateFactory.getInstance("X.509");
|
||||
Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(rawCertificate));
|
||||
RSAPublicKey publicKey = (RSAPublicKey) certificate.getPublicKey();
|
||||
return Optional.of(publicKey);
|
||||
} catch (CertificateException e) {
|
||||
log.warn("Не удалось прочитать сертификат TLS", e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
@SneakyThrows(value = {NoSuchAlgorithmException.class, NoSuchPaddingException.class})
|
||||
private Optional<Cipher> createCipher(String mode, byte[] key, byte[] iv) {
|
||||
Cipher cipher = Cipher.getInstance("AES/" + mode + "/PKCS5Padding");
|
||||
SecretKeySpec serverSkeySpec = new SecretKeySpec(key, "AES");
|
||||
IvParameterSpec serverIvParameterSpec = new IvParameterSpec(iv);
|
||||
|
||||
try {
|
||||
cipher.init(Cipher.DECRYPT_MODE, serverSkeySpec, serverIvParameterSpec);
|
||||
|
||||
return Optional.of(cipher);
|
||||
} catch (InvalidKeyException | InvalidAlgorithmParameterException e) {
|
||||
log.warn("Не удалось расшифровать TLS", e);
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] clearDecodedData(byte[] decoded) {
|
||||
int start = 16;
|
||||
int end = decoded.length - 21; // почему?)
|
||||
decoded = ByteArrays.getSubArray(decoded, start, end - start);
|
||||
return decoded;
|
||||
}
|
||||
|
||||
private Optional<HandshakeRecordContent> getHandshake(HandshakeType handshakeType) {
|
||||
return tlsPackets.values().stream()
|
||||
.filter(p -> p.getContentType() == ContentType.HANDSHAKE)
|
||||
.map(p -> ((HandshakeRecord) p.getRecord()))
|
||||
.filter(r -> r.getHandshakeType() == handshakeType)
|
||||
.map(HandshakeRecord::getContent)
|
||||
.findFirst();
|
||||
}
|
||||
|
||||
private List<TlsPacket.TlsHeader> createTlsHeaders(Packet p) throws IllegalRawDataException {
|
||||
List<TlsPacket.TlsHeader> headers = new ArrayList<>();
|
||||
TlsPacket tlsPacket = TlsPacket.newPacket(p.getContent(), 0, p.getContent().length);
|
||||
|
||||
headers.add(tlsPacket.getHeader());
|
||||
|
||||
while (tlsPacket.getPayload() != null) {
|
||||
tlsPacket = (TlsPacket) tlsPacket.getPayload();
|
||||
headers.add(tlsPacket.getHeader());
|
||||
}
|
||||
|
||||
return headers;
|
||||
}
|
||||
|
||||
public List<Packet> getParsedPackets() {
|
||||
if (!parsed) {
|
||||
throw new IllegalStateException("Данные TLS не разобраны.");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
+238
@@ -0,0 +1,238 @@
|
||||
package ru.serega6531.packmate.service.optimization;
|
||||
|
||||
import lombok.Getter;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.lang3.ArrayUtils;
|
||||
import org.java_websocket.drafts.Draft_6455;
|
||||
import org.java_websocket.exceptions.InvalidDataException;
|
||||
import org.java_websocket.exceptions.InvalidHandshakeException;
|
||||
import org.java_websocket.extensions.permessage_deflate.PerMessageDeflateExtension;
|
||||
import org.java_websocket.framing.DataFrame;
|
||||
import org.java_websocket.framing.Framedata;
|
||||
import org.java_websocket.handshake.HandshakeImpl1Client;
|
||||
import org.java_websocket.handshake.HandshakeImpl1Server;
|
||||
import ru.serega6531.packmate.model.Packet;
|
||||
import ru.serega6531.packmate.utils.BytesUtils;
|
||||
import ru.serega6531.packmate.utils.PacketUtils;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
public class WebSocketsParser {
|
||||
|
||||
private static final java.util.regex.Pattern WEBSOCKET_KEY_PATTERN =
|
||||
Pattern.compile("Sec-WebSocket-Key: (.+)\\r\\n");
|
||||
private static final java.util.regex.Pattern WEBSOCKET_EXTENSIONS_PATTERN =
|
||||
Pattern.compile("Sec-WebSocket-Extensions?: (.+)\\r\\n");
|
||||
private static final java.util.regex.Pattern WEBSOCKET_VERSION_PATTERN =
|
||||
Pattern.compile("Sec-WebSocket-Version: (\\d+)\\r\\n");
|
||||
private static final java.util.regex.Pattern WEBSOCKET_ACCEPT_PATTERN =
|
||||
Pattern.compile("Sec-WebSocket-Accept: (.+)\\r\\n");
|
||||
|
||||
private static final String WEBSOCKET_UPGRADE_HEADER = "upgrade: websocket\r\n";
|
||||
private static final String WEBSOCKET_CONNECTION_HEADER = "connection: upgrade\r\n";
|
||||
|
||||
private final List<Packet> packets;
|
||||
|
||||
@Getter
|
||||
private boolean parsed = false;
|
||||
private List<Packet> parsedPackets;
|
||||
|
||||
public WebSocketsParser(List<Packet> packets) {
|
||||
this.packets = packets;
|
||||
detectWebSockets();
|
||||
}
|
||||
|
||||
private void detectWebSockets() {
|
||||
final List<Packet> clientHandshakePackets = packets.stream()
|
||||
.takeWhile(Packet::isIncoming)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
final String clientHandshake = getHandshake(clientHandshakePackets);
|
||||
if (clientHandshake == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
int httpEnd = -1;
|
||||
for (int i = clientHandshakePackets.size(); i < packets.size(); i++) {
|
||||
Packet packet = packets.get(i);
|
||||
byte[] content = packet.getContent();
|
||||
if (BytesUtils.startsWith(content, "HTTP/1.1 101 Switching Protocols".getBytes())) {
|
||||
int endPos = BytesUtils.indexOf(content, "\r\n\r\n".getBytes()) + "\r\n\r\n".length();
|
||||
if (endPos != content.length) {
|
||||
byte[] handshakePart = ArrayUtils.subarray(content, 0, endPos);
|
||||
byte[] payloadPart = ArrayUtils.subarray(content, endPos, content.length);
|
||||
|
||||
Packet handshakePacket = mimicPacket(packet, handshakePart, false);
|
||||
Packet payloadPacket = mimicPacket(packet, payloadPart, true);
|
||||
|
||||
packets.add(i, handshakePacket);
|
||||
packets.set(i + 1, payloadPacket);
|
||||
}
|
||||
httpEnd = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (httpEnd == -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Packet> serverHandshakePackets = packets.subList(clientHandshakePackets.size(), httpEnd);
|
||||
final String serverHandshake = getHandshake(serverHandshakePackets);
|
||||
if (serverHandshake == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
HandshakeImpl1Server serverHandshakeImpl = fillServerHandshake(serverHandshake);
|
||||
HandshakeImpl1Client clientHandshakeImpl = fillClientHandshake(clientHandshake);
|
||||
|
||||
if (serverHandshakeImpl == null || clientHandshakeImpl == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Draft_6455 draft = new Draft_6455(new PerMessageDeflateExtension());
|
||||
|
||||
try {
|
||||
draft.acceptHandshakeAsServer(clientHandshakeImpl);
|
||||
draft.acceptHandshakeAsClient(clientHandshakeImpl, serverHandshakeImpl);
|
||||
} catch (InvalidHandshakeException e) {
|
||||
log.warn("Не удалось разобрать рукопожатие WebSocket", e);
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Packet> wsPackets = packets.subList(
|
||||
httpEnd,
|
||||
packets.size());
|
||||
|
||||
if (wsPackets.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
final List<Packet> handshakes = packets.subList(0, httpEnd);
|
||||
|
||||
parse(wsPackets, handshakes, draft);
|
||||
}
|
||||
|
||||
private Packet mimicPacket(Packet packet, byte[] content, boolean ws) {
|
||||
return packet.toBuilder()
|
||||
.content(content)
|
||||
.webSocketParsed(ws)
|
||||
.build();
|
||||
}
|
||||
|
||||
private void parse(final List<Packet> wsPackets, final List<Packet> handshakes, Draft_6455 draft) {
|
||||
List<List<Packet>> sides = PacketUtils.sliceToSides(wsPackets);
|
||||
parsedPackets = new ArrayList<>(handshakes);
|
||||
|
||||
for (List<Packet> side : sides) {
|
||||
final Packet lastPacket = side.get(0);
|
||||
|
||||
final byte[] wsContent = PacketUtils.mergePackets(side);
|
||||
|
||||
final ByteBuffer buffer = ByteBuffer.wrap(wsContent);
|
||||
List<Framedata> frames;
|
||||
|
||||
try {
|
||||
frames = draft.translateFrame(buffer);
|
||||
} catch (InvalidDataException e) {
|
||||
log.warn("Не удалось разобрать данные WebSocket", e);
|
||||
return;
|
||||
}
|
||||
|
||||
for (Framedata frame : frames) {
|
||||
if (frame instanceof DataFrame) {
|
||||
parsedPackets.add(
|
||||
lastPacket.toBuilder()
|
||||
.content(frame.getPayloadData().array())
|
||||
.webSocketParsed(true)
|
||||
.build()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
parsed = true;
|
||||
}
|
||||
|
||||
public List<Packet> getParsedPackets() {
|
||||
if (!parsed) {
|
||||
throw new IllegalStateException("Данные WebSocket не разобраны.");
|
||||
}
|
||||
|
||||
return parsedPackets;
|
||||
}
|
||||
|
||||
private String getHandshake(final List<Packet> packets) {
|
||||
final String handshake = new String(PacketUtils.mergePackets(packets));
|
||||
|
||||
if (!handshake.toLowerCase().contains(WEBSOCKET_CONNECTION_HEADER)
|
||||
|| !handshake.toLowerCase().contains(WEBSOCKET_UPGRADE_HEADER)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return handshake;
|
||||
}
|
||||
|
||||
private HandshakeImpl1Client fillClientHandshake(String clientHandshake) {
|
||||
Matcher matcher = WEBSOCKET_VERSION_PATTERN.matcher(clientHandshake);
|
||||
if (!matcher.find()) {
|
||||
return null;
|
||||
}
|
||||
String version = matcher.group(1);
|
||||
|
||||
matcher = WEBSOCKET_KEY_PATTERN.matcher(clientHandshake);
|
||||
if (!matcher.find()) {
|
||||
return null;
|
||||
}
|
||||
String key = matcher.group(1);
|
||||
|
||||
matcher = WEBSOCKET_EXTENSIONS_PATTERN.matcher(clientHandshake);
|
||||
String extensions = null;
|
||||
if (matcher.find()) {
|
||||
extensions = matcher.group(1);
|
||||
}
|
||||
|
||||
HandshakeImpl1Client clientHandshakeImpl = new HandshakeImpl1Client();
|
||||
|
||||
clientHandshakeImpl.put("Upgrade", "websocket");
|
||||
clientHandshakeImpl.put("Connection", "Upgrade");
|
||||
clientHandshakeImpl.put("Sec-WebSocket-Version", version);
|
||||
clientHandshakeImpl.put("Sec-WebSocket-Key", key);
|
||||
|
||||
if (extensions != null) {
|
||||
clientHandshakeImpl.put("Sec-WebSocket-Extensions", extensions);
|
||||
}
|
||||
|
||||
return clientHandshakeImpl;
|
||||
}
|
||||
|
||||
private HandshakeImpl1Server fillServerHandshake(String serverHandshake) {
|
||||
Matcher matcher = WEBSOCKET_ACCEPT_PATTERN.matcher(serverHandshake);
|
||||
if (!matcher.find()) {
|
||||
return null;
|
||||
}
|
||||
String accept = matcher.group(1);
|
||||
|
||||
matcher = WEBSOCKET_EXTENSIONS_PATTERN.matcher(serverHandshake);
|
||||
String extensions = null;
|
||||
if (matcher.find()) {
|
||||
extensions = matcher.group(1);
|
||||
}
|
||||
|
||||
HandshakeImpl1Server serverHandshakeImpl = new HandshakeImpl1Server();
|
||||
|
||||
serverHandshakeImpl.put("Upgrade", "websocket");
|
||||
serverHandshakeImpl.put("Connection", "Upgrade");
|
||||
serverHandshakeImpl.put("Sec-WebSocket-Accept", accept);
|
||||
serverHandshakeImpl.put("Sec-WebSocket-Extensions", extensions);
|
||||
|
||||
return serverHandshakeImpl;
|
||||
}
|
||||
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package ru.serega6531.packmate.service.optimization.tls;
|
||||
|
||||
import org.pcap4j.packet.AbstractPacket;
|
||||
import org.pcap4j.packet.IllegalRawDataException;
|
||||
import org.pcap4j.packet.Packet;
|
||||
import org.pcap4j.util.ByteArrays;
|
||||
import ru.serega6531.packmate.service.optimization.tls.numbers.ContentType;
|
||||
import ru.serega6531.packmate.service.optimization.tls.numbers.TlsVersion;
|
||||
import ru.serega6531.packmate.service.optimization.tls.records.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import static org.pcap4j.util.ByteArrays.BYTE_SIZE_IN_BYTES;
|
||||
import static org.pcap4j.util.ByteArrays.SHORT_SIZE_IN_BYTES;
|
||||
|
||||
public class TlsPacket extends AbstractPacket {
|
||||
|
||||
private final TlsPacket.TlsHeader header;
|
||||
private final Packet payload;
|
||||
|
||||
public static TlsPacket newPacket(byte[] rawData, int offset, int length) throws IllegalRawDataException {
|
||||
ByteArrays.validateBounds(rawData, offset, length);
|
||||
return new TlsPacket(rawData, offset, length);
|
||||
}
|
||||
|
||||
private TlsPacket(byte[] rawData, int offset, int length) throws IllegalRawDataException {
|
||||
this.header = new TlsPacket.TlsHeader(rawData, offset, length);
|
||||
|
||||
int payloadLength = length - header.length();
|
||||
if (payloadLength > 0) {
|
||||
this.payload = TlsPacket.newPacket(rawData, offset + header.length(), payloadLength);
|
||||
} else {
|
||||
this.payload = null;
|
||||
}
|
||||
}
|
||||
|
||||
private TlsPacket(TlsPacket.Builder builder) {
|
||||
if (builder == null) {
|
||||
throw new NullPointerException("Построитель TLS-пакета не задан.");
|
||||
}
|
||||
|
||||
this.payload = builder.payloadBuilder != null ? builder.payloadBuilder.build() : null;
|
||||
this.header = new TlsPacket.TlsHeader(builder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public TlsHeader getHeader() {
|
||||
return header;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Packet getPayload() {
|
||||
return payload;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Builder getBuilder() {
|
||||
return new Builder(this);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String buildString() {
|
||||
StringBuilder sb = new StringBuilder(getHeader().toString());
|
||||
|
||||
TlsPacket p = (TlsPacket) getPayload();
|
||||
|
||||
if (p != null) {
|
||||
sb.append('\n');
|
||||
sb.append(p.toString());
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
public static final class TlsHeader extends AbstractHeader {
|
||||
|
||||
/*
|
||||
0x0 - Тип содержимого
|
||||
0x1 - Версия
|
||||
0x3 - Длина
|
||||
0x5 - Содержимое записи
|
||||
*/
|
||||
|
||||
private static final int CONTENT_TYPE_OFFSET = 0;
|
||||
private static final int VERSION_OFFSET = CONTENT_TYPE_OFFSET + BYTE_SIZE_IN_BYTES;
|
||||
private static final int LENGTH_OFFSET = VERSION_OFFSET + SHORT_SIZE_IN_BYTES;
|
||||
private static final int RECORD_OFFSET = LENGTH_OFFSET + SHORT_SIZE_IN_BYTES;
|
||||
|
||||
private ContentType contentType;
|
||||
private TlsVersion version;
|
||||
private short recordLength;
|
||||
private TlsRecord record;
|
||||
|
||||
private TlsHeader(Builder builder) {
|
||||
// TODO: добавить построение заголовка TLS.
|
||||
}
|
||||
|
||||
private TlsHeader(byte[] rawData, int offset, int length) throws IllegalRawDataException {
|
||||
ByteArrays.validateBounds(rawData, offset, RECORD_OFFSET);
|
||||
this.contentType = ContentType.getInstance(ByteArrays.getByte(rawData, CONTENT_TYPE_OFFSET + offset));
|
||||
this.version = TlsVersion.getInstance(ByteArrays.getShort(rawData, VERSION_OFFSET + offset));
|
||||
this.recordLength = ByteArrays.getShort(rawData, LENGTH_OFFSET + offset);
|
||||
|
||||
if (contentType == ContentType.HANDSHAKE) {
|
||||
this.record = HandshakeRecord.newInstance(rawData, offset + RECORD_OFFSET, recordLength);
|
||||
} else if (contentType == ContentType.CHANGE_CIPHER_SPEC) {
|
||||
this.record = ChangeCipherSpecRecord.newInstance(rawData, offset + RECORD_OFFSET, recordLength);
|
||||
} else if (contentType == ContentType.APPLICATION_DATA) {
|
||||
this.record = ApplicationDataRecord.newInstance(rawData, offset + RECORD_OFFSET, recordLength);
|
||||
} else if (contentType == ContentType.ALERT) {
|
||||
this.record = AlertRecord.newInstance(rawData, offset + RECORD_OFFSET, recordLength);
|
||||
} else if (contentType == ContentType.HEARTBEAT) {
|
||||
this.record = HeartbeatRecord.newInstance(rawData, offset + RECORD_OFFSET, recordLength);
|
||||
} else {
|
||||
throw new IllegalArgumentException("Неизвестный тип содержимого TLS: " + contentType);
|
||||
}
|
||||
}
|
||||
|
||||
public ContentType getContentType() {
|
||||
return contentType;
|
||||
}
|
||||
|
||||
public TlsVersion getVersion() {
|
||||
return version;
|
||||
}
|
||||
|
||||
public TlsRecord getRecord() {
|
||||
return record;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected List<byte[]> getRawFields() {
|
||||
List<byte[]> rawFields = new ArrayList<>();
|
||||
rawFields.add(new byte[]{contentType.value()});
|
||||
rawFields.add(ByteArrays.toByteArray(version.value()));
|
||||
rawFields.add(ByteArrays.toByteArray(recordLength));
|
||||
// TODO: добавить сериализацию содержимого записи.
|
||||
return rawFields;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int length() {
|
||||
return RECORD_OFFSET + recordLength;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected String buildString() {
|
||||
return "Заголовок TLS [" + length() + " байт]\n" +
|
||||
" Версия: " + version + "\n" +
|
||||
" Тип: " + contentType + "\n" +
|
||||
record.toString();
|
||||
}
|
||||
}
|
||||
|
||||
public static final class Builder extends AbstractBuilder {
|
||||
|
||||
private Packet.Builder payloadBuilder;
|
||||
|
||||
public Builder() {
|
||||
}
|
||||
|
||||
public Builder(TlsPacket packet) {
|
||||
this.payloadBuilder = packet.payload != null ? packet.payload.getBuilder() : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Packet build() {
|
||||
return new TlsPacket(this);
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package ru.serega6531.packmate.service.optimization.tls.extensions;
|
||||
|
||||
import org.pcap4j.util.ByteArrays;
|
||||
import ru.serega6531.packmate.service.optimization.tls.extensions.keyshare.KeyShareExtension;
|
||||
import ru.serega6531.packmate.service.optimization.tls.numbers.ExtensionType;
|
||||
|
||||
public abstract class TlsExtension {
|
||||
|
||||
/*
|
||||
0x0 - Тип
|
||||
0x2 - Длина
|
||||
0x4 - Содержимое
|
||||
0x4+length - Конец
|
||||
*/
|
||||
|
||||
protected ExtensionType type;
|
||||
protected short extensionLength;
|
||||
|
||||
public static TlsExtension newInstance(ExtensionType type, byte[] rawData, int offset,
|
||||
short extensionLength, boolean client) {
|
||||
if (extensionLength > 0) {
|
||||
ByteArrays.validateBounds(rawData, offset, extensionLength);
|
||||
}
|
||||
|
||||
if (type == ExtensionType.KEY_SHARE) {
|
||||
return KeyShareExtension.newInstance(type, rawData, offset, extensionLength, client);
|
||||
} else {
|
||||
return new UnimplementedTlsExtension(type, rawData, offset, extensionLength);
|
||||
}
|
||||
}
|
||||
|
||||
public TlsExtension(ExtensionType type, short extensionLength) {
|
||||
this.type = type;
|
||||
this.extensionLength = extensionLength;
|
||||
}
|
||||
|
||||
public ExtensionType getType() {
|
||||
return type;
|
||||
}
|
||||
|
||||
public short getLength() {
|
||||
return extensionLength;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return type.name();
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package ru.serega6531.packmate.service.optimization.tls.extensions;
|
||||
|
||||
import ru.serega6531.packmate.service.optimization.tls.numbers.ExtensionType;
|
||||
|
||||
public class UnimplementedTlsExtension extends TlsExtension {
|
||||
|
||||
private byte[] data;
|
||||
|
||||
public UnimplementedTlsExtension(ExtensionType type, byte[] rawData, int offset, short extensionLength) {
|
||||
super(type, extensionLength);
|
||||
|
||||
data = new byte[extensionLength];
|
||||
System.arraycopy(rawData, offset, data, 0, extensionLength);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
if(extensionLength > 0) {
|
||||
return type.name() + " [" + extensionLength + " bytes]";
|
||||
} else {
|
||||
return type.name();
|
||||
}
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package ru.serega6531.packmate.service.optimization.tls.extensions.keyshare;
|
||||
|
||||
import org.pcap4j.util.ByteArrays;
|
||||
import ru.serega6531.packmate.service.optimization.tls.numbers.ExtensionType;
|
||||
|
||||
import static org.pcap4j.util.ByteArrays.SHORT_SIZE_IN_BYTES;
|
||||
|
||||
public class ClientKeyShareExtension extends KeyShareExtension {
|
||||
|
||||
private static final int KEY_SHARE_LENGTH_OFFSET = 0;
|
||||
private static final int KEY_SHARE_ENTRY_OFFSET = KEY_SHARE_LENGTH_OFFSET + SHORT_SIZE_IN_BYTES;
|
||||
|
||||
private short keyShareLength;
|
||||
|
||||
public ClientKeyShareExtension(ExtensionType type, byte[] rawData, int offset, short extensionLength) {
|
||||
super(type, extensionLength);
|
||||
this.keyShareLength = ByteArrays.getShort(rawData, KEY_SHARE_LENGTH_OFFSET + offset); // Поле присутствует не всегда.
|
||||
int cursor = KEY_SHARE_ENTRY_OFFSET + offset;
|
||||
ByteArrays.validateBounds(rawData, cursor, keyShareLength);
|
||||
readEntries(rawData, KEY_SHARE_ENTRY_OFFSET + offset, offset + keyShareLength);
|
||||
}
|
||||
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package ru.serega6531.packmate.service.optimization.tls.extensions.keyshare;
|
||||
|
||||
import org.pcap4j.util.ByteArrays;
|
||||
import ru.serega6531.packmate.service.optimization.tls.numbers.KeyGroup;
|
||||
|
||||
import static org.pcap4j.util.ByteArrays.SHORT_SIZE_IN_BYTES;
|
||||
|
||||
public class KeyShareEntry {
|
||||
|
||||
private static final int GROUP_OFFSET = 0;
|
||||
private static final int KEY_EXHANGE_LENGTH_OFFSET = GROUP_OFFSET + SHORT_SIZE_IN_BYTES;
|
||||
private static final int KEY_EXCHANGE_OFFSET = KEY_EXHANGE_LENGTH_OFFSET + SHORT_SIZE_IN_BYTES;
|
||||
|
||||
private KeyGroup group;
|
||||
private short keyExhangeLength;
|
||||
private byte[] keyExchange;
|
||||
|
||||
public KeyShareEntry(byte[] rawData, int offset) {
|
||||
this.group = KeyGroup.getInstance(ByteArrays.getShort(rawData, GROUP_OFFSET + offset));
|
||||
this.keyExhangeLength = ByteArrays.getShort(rawData, KEY_EXHANGE_LENGTH_OFFSET + offset);
|
||||
keyExchange = new byte[keyExhangeLength];
|
||||
System.arraycopy(rawData, KEY_EXCHANGE_OFFSET + offset, keyExchange, 0, keyExhangeLength);
|
||||
}
|
||||
|
||||
public int size() {
|
||||
return SHORT_SIZE_IN_BYTES + SHORT_SIZE_IN_BYTES + keyExhangeLength;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return group.name();
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package ru.serega6531.packmate.service.optimization.tls.extensions.keyshare;
|
||||
|
||||
import org.pcap4j.util.ByteArrays;
|
||||
import ru.serega6531.packmate.service.optimization.tls.extensions.TlsExtension;
|
||||
import ru.serega6531.packmate.service.optimization.tls.numbers.ExtensionType;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
public abstract class KeyShareExtension extends TlsExtension {
|
||||
|
||||
private final List<KeyShareEntry> entries = new ArrayList<>();
|
||||
|
||||
public static KeyShareExtension newInstance(ExtensionType type, byte[] rawData, int offset,
|
||||
short extensionLength, boolean client) {
|
||||
ByteArrays.validateBounds(rawData, offset, extensionLength);
|
||||
|
||||
if(client) {
|
||||
return new ClientKeyShareExtension(type, rawData, offset, extensionLength);
|
||||
} else {
|
||||
return new ServerKeyShareExtension(type, rawData, offset, extensionLength);
|
||||
}
|
||||
}
|
||||
|
||||
protected KeyShareExtension(ExtensionType type, short extensionLength) {
|
||||
super(type, extensionLength);
|
||||
}
|
||||
|
||||
protected void readEntries(byte[] rawData, int cursor, int end) {
|
||||
while (cursor < end) {
|
||||
KeyShareEntry entry = readEntry(rawData, cursor);
|
||||
cursor += entry.size();
|
||||
}
|
||||
}
|
||||
|
||||
protected KeyShareEntry readEntry(byte[] rawData, int cursor) {
|
||||
KeyShareEntry entry = new KeyShareEntry(rawData, cursor);
|
||||
entries.add(entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String toString() {
|
||||
return type.name() + " " + entries.toString();
|
||||
}
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package ru.serega6531.packmate.service.optimization.tls.extensions.keyshare;
|
||||
|
||||
import ru.serega6531.packmate.service.optimization.tls.numbers.ExtensionType;
|
||||
|
||||
public class ServerKeyShareExtension extends KeyShareExtension {
|
||||
|
||||
private static final int KEY_SHARE_ENTRY_OFFSET = 0;
|
||||
|
||||
public ServerKeyShareExtension(ExtensionType type, byte[] rawData, int offset, short extensionLength) {
|
||||
super(type, extensionLength);
|
||||
readEntry(rawData, KEY_SHARE_ENTRY_OFFSET + offset);
|
||||
}
|
||||
|
||||
}
|
||||
Loaded 100 of 564 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user