diff --git a/REPORT.md b/REPORT.md index 18afadb..9c4924f 100644 --- a/REPORT.md +++ b/REPORT.md @@ -18,6 +18,7 @@ TODO: схема процессов/хранилищ, источник исти | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | | Argon2id storage и калибровка | `scripts/benchmark-argon2.ps1`, `PasswordConfigTest` | PASS: итоговый профиль 32768 KiB/t=2/p=1; p95 encode 150.3 мс, verify 142.7 мс при 0.75 CPU/768 MiB; PHC хранит параметры и уникальный 16-byte salt | `README.md`, benchmark output, unit test | +| LB → каждая API-реплика | `scripts/test-mtls.ps1`, `TrustedClientCertificateFilterTest` | PASS: обе реплики отдельно отклоняют no-cert, foreign CA и доверенный cert с чужим URI SAN; LB identity принята; API port не опубликован | `compose.yaml`, runtime test, unit test | | Compose hardening | `scripts/check-compose-hardening.ps1` | PASS: только три loopback HTTPS-порта; limits/capability/read-only policy проверены | `compose.yaml`, самопроверка скрипта | | Certificates/secrets lifecycle | `scripts/check-security-lifecycle.ps1` | PASS: 20 cert/key bundles валидны; expiry, SAN, пары ключей, Git ignore и возраст SecretID проверены | вывод команды без secret values | | Публичный smoke | `scripts/verify-https-resilience.ps1` | PASS: полный API-сценарий, включая ACL и вложения, выполнен через HTTPS с проверкой CA и hostname | вывод команды | diff --git a/contracts/trust-matrix.md b/contracts/trust-matrix.md index 68dc10a..a806c0e 100644 --- a/contracts/trust-matrix.md +++ b/contracts/trust-matrix.md @@ -9,7 +9,7 @@ | Связь | Endpoint / порт | Протокол и server trust | Client identity и минимальные права | Lifecycle | Проверяемый отказ / доказательство | Статус | | --- | --- | --- | --- | --- | --- | --- | | Клиент → nginx | `https://localhost:8443` | TLS 1.2/1.3; `secrets/tls/ca.crt`; SAN `localhost`; hostname verification | Public registration/health, Basic login, Bearer business API; `X-User-Id` не identity | Session 3600 s, максимум 3 активных; logout/replacement revoke; leaf 30 d | `make test-security`; чужой/пустой CA, wrong hostname, expired leaf → certificate error; revoked token → 401; login burst → 429 + Retry-After | **PASS** для внешнего TLS/auth/session/rate-limit контракта | -| nginx → API replicas | `https://api:8443` | mTLS; service CA + SAN `spiffe://hla-lab7/api`; API доверяет отдельному LB client CA | nginx SAN `spiffe://hla-lab7/lb`; точный URI SAN проверяет `TrustedClientCertificateFilter`; API port не публикуется | Leaf 30 d, local regeneration/restart | `scripts/test-mtls.ps1`: no cert, foreign CA, trusted cert SAN `.../worker` rejected; LB cert → health 200 | **PASS** | +| nginx → API replicas | `https://api:8443` | mTLS; service CA + SAN `spiffe://hla-lab7/api`; API доверяет отдельному LB client CA | nginx SAN `spiffe://hla-lab7/lb`; точный URI SAN до auth проверяет `TrustedClientCertificateFilter`; API port не публикуется | Leaf 30 d, local regeneration/restart | `scripts/test-mtls.ps1` обращается к каждой реплике отдельно: no cert и foreign CA отклоняются handshake; trusted cert SAN `.../worker` получает 403; LB cert → health 200; прямой published port отсутствует | **PASS** | | API → PostgreSQL | `postgres:5432` | TLS `verify-full`; service CA + SAN `DNS:postgres`; plaintext rejected by `pg_hba.conf` | `messenger_api`: runtime CRUD без superuser/DDL/role management | Static stand secret, rotate/reconnect; dynamic credentials remain extension | Wrong CA/hostname fails; DDL/role management denied | **PASS (уровень 3)** | | Worker → PostgreSQL | `postgres:5432` | TLS `verify-full` | `messenger_worker`: jobs/attachments/variants; нет users password/session/membership | Отдельный secret | `SELECT password_hash`, update membership denied; job transitions allowed | **PASS (уровень 3)** | | API → MinIO | `https://minio:9000` | TLS verify; service CA + SAN `DNS:minio` | `messenger-api`, без admin/policy | Static stand secret, отдельно от root | Anonymous и `mc admin` denied; allowed prefix succeeds | **PASS на 3; GAP:** OpenBao rotation/prefix split | diff --git a/scripts/test-mtls.ps1 b/scripts/test-mtls.ps1 index 096ad9b..e3f0e1e 100644 --- a/scripts/test-mtls.ps1 +++ b/scripts/test-mtls.ps1 @@ -4,22 +4,43 @@ param([string]$EnvFile = '.env') $ErrorActionPreference = 'Stop' Set-Location (Join-Path $PSScriptRoot '..') -function Invoke-Probe([string]$TlsArguments) { - $script = "printf 'GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n' | openssl s_client -connect api:8443 -servername api -CAfile /run/pki/service-ca/ca.crt $TlsArguments 2>&1" - $output = docker compose --env-file $EnvFile run --rm --no-deps --entrypoint /bin/sh nginx -c $script +function Invoke-Probe([string]$Target, [string]$TlsArguments) { + $script = "printf 'GET /health/ready HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n' | openssl s_client -quiet -connect ${Target}:8443 -servername api -CAfile /run/pki/service-ca/ca.crt $TlsArguments 2>&1" + $output = (& docker compose --env-file $EnvFile run --rm --no-deps --entrypoint /bin/sh nginx -c $script 2>&1) return ($output -join "`n") } -$noCertificate = Invoke-Probe '' -if ($noCertificate -match 'HTTP/1.1 200') { throw 'mTLS failure: API accepted a client without a certificate' } +$published = (& docker compose --env-file $EnvFile port api 8443 2>$null) -join "`n" +if (-not [string]::IsNullOrWhiteSpace($published)) { + throw "mTLS bypass: API port is published directly at $published" +} -$foreignCa = Invoke-Probe '-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key' -if ($foreignCa -match 'HTTP/1.1 200') { throw 'mTLS failure: API accepted a foreign client CA' } +$replicas = @(& docker compose --env-file $EnvFile ps -q api) +if ($replicas.Count -lt 2) { throw 'At least two running API replicas are required for the mTLS test' } -$wrongIdentity = Invoke-Probe '-cert /run/pki/wrong-lb-client/tls.crt -key /run/pki/wrong-lb-client/tls.key' -if ($wrongIdentity -notmatch 'HTTP/1.1 403') { throw 'mTLS failure: trusted CA with forbidden SAN was not rejected with 403' } +foreach($replica in $replicas) { + $target = (& docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' $replica).Trim() + if ([string]::IsNullOrWhiteSpace($target)) { throw "No internal address found for API replica $replica" } -$allowed = Invoke-Probe '-cert /run/pki/lb/tls.crt -key /run/pki/lb/tls.key' -if ($allowed -notmatch 'HTTP/1.1 200') { throw 'mTLS failure: allowed LB identity did not reach API health' } + $noCertificate = Invoke-Probe $target '' + if ($noCertificate -match 'HTTP/1.1' -or $noCertificate -notmatch 'certificate required|handshake failure') { + throw "mTLS failure: API replica $replica did not reject a missing client certificate during TLS handshake" + } -Write-Host 'PASS: no cert, foreign CA and forbidden SAN rejected; LB identity accepted.' + $foreignCa = Invoke-Probe $target '-cert /run/pki/api-client/tls.crt -key /run/pki/api-client/tls.key' + if ($foreignCa -match 'HTTP/1.1' -or $foreignCa -notmatch 'certificate unknown|unknown ca|bad certificate') { + throw "mTLS failure: API replica $replica did not reject a foreign client CA during TLS handshake" + } + + $wrongIdentity = Invoke-Probe $target '-cert /run/pki/wrong-lb-client/tls.crt -key /run/pki/wrong-lb-client/tls.key' + if ($wrongIdentity -notmatch 'HTTP/1.1 403') { + throw "mTLS failure: API replica $replica accepted or mishandled a trusted certificate with forbidden URI SAN" + } + + $allowed = Invoke-Probe $target '-cert /run/pki/lb/tls.crt -key /run/pki/lb/tls.key' + if ($allowed -notmatch 'HTTP/1.1 200') { + throw "mTLS failure: allowed LB identity did not reach API replica $replica" + } +} + +Write-Host "PASS: $($replicas.Count) API replicas require a client certificate and LB CA; forbidden URI SAN is rejected; only the LB identity succeeds; no API port is published." diff --git a/src/main/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilter.java b/src/main/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilter.java index 9925f6f..eb37665 100644 --- a/src/main/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilter.java +++ b/src/main/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilter.java @@ -34,7 +34,13 @@ public class TrustedClientCertificateFilter extends OncePerRequestFilter { X509Certificate[] certificates = (X509Certificate[]) request.getAttribute( "jakarta.servlet.request.X509Certificate"); if (certificates == null || certificates.length == 0 || !hasAllowedUri(certificates[0])) { - response.sendError(HttpServletResponse.SC_FORBIDDEN, "Client certificate identity is not allowed"); + // Do not use sendError: its internal /error dispatch can be intercepted + // by Spring Security and turn this identity rejection into an ambiguous 401. + response.setStatus(HttpServletResponse.SC_FORBIDDEN); + response.setContentType("application/json"); + response.setHeader("Cache-Control", "no-store"); + response.getWriter().write( + "{\"error\":{\"code\":\"forbidden\",\"message\":\"Client certificate identity is not allowed\"}}"); return; } chain.doFilter(request, response); diff --git a/src/test/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilterTest.java b/src/test/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilterTest.java index 95114fb..46553cc 100644 --- a/src/test/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilterTest.java +++ b/src/test/java/com/example/mtusi_messenger/security/TrustedClientCertificateFilterTest.java @@ -9,33 +9,50 @@ import java.security.cert.X509Certificate; import java.util.List; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; class TrustedClientCertificateFilterTest { - private final TrustedClientCertificateFilter filter = - new TrustedClientCertificateFilter("spiffe://hla-lab7/lb"); + private static final String ALLOWED_URI = "spiffe://hla-lab7/lb"; @Test - void rejectsWrongUriEvenWhenTlsAlreadyTrustedTheCertificate() throws Exception { - MockHttpServletResponse response = invoke("spiffe://hla-lab7/worker"); + void rejectsRequestWithoutClientCertificate() throws Exception { + MockHttpServletResponse response = apply(null); + assertEquals(403, response.getStatus()); + assertEquals("no-store", response.getHeader("Cache-Control")); + assertEquals("application/json", response.getContentType()); + } + + @Test + void rejectsTrustedCertificateWithWrongUriSan() throws Exception { + MockHttpServletResponse response = apply(certificate("spiffe://hla-lab7/worker")); assertEquals(403, response.getStatus()); } @Test - void acceptsExactLoadBalancerUri() throws Exception { - MockHttpServletResponse response = invoke("spiffe://hla-lab7/lb"); + void acceptsOnlyTheConfiguredUriSan() throws Exception { + MockHttpServletResponse response = apply(certificate(ALLOWED_URI)); assertEquals(200, response.getStatus()); + assertNull(response.getErrorMessage()); } - private MockHttpServletResponse invoke(String uri) throws Exception { - X509Certificate certificate = mock(X509Certificate.class); - when(certificate.getSubjectAlternativeNames()).thenReturn(List.of(List.of(6, uri))); - MockHttpServletRequest request = new MockHttpServletRequest("GET", "/health/ready"); - request.setAttribute("jakarta.servlet.request.X509Certificate", - new X509Certificate[]{certificate}); + private MockHttpServletResponse apply(X509Certificate certificate) throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + if (certificate != null) { + request.setAttribute("jakarta.servlet.request.X509Certificate", + new X509Certificate[]{certificate}); + } MockHttpServletResponse response = new MockHttpServletResponse(); - filter.doFilter(request, response, new MockFilterChain()); + new TrustedClientCertificateFilter(ALLOWED_URI) + .doFilter(request, response, new MockFilterChain()); return response; } + + private X509Certificate certificate(String uriSan) throws Exception { + X509Certificate certificate = mock(X509Certificate.class); + when(certificate.getSubjectAlternativeNames()).thenReturn( + List.of(List.of(6, uriSan))); + return certificate; + } }