Spring Boot - самоподписанный mTLS - необходимый сертификат - PullRequest
0 голосов
/ 12 июля 2020

У меня проблема с конфигурацией mTLS в приложении Spring Boot.

Вопрос: Как авторизовать запрос с помощью самозаверяющего сертификата, если сертификат является обязательным из-за опции client-auth: need

Шаги, выполненные до сих пор:

Я создаю один самозаверяющий сертификат с помощью команды:

keytool -genkeypair -alias xx-test -keyalg RSA -keysize 2048 -keystore keystore.jks -validity 150 -storepass xxxxxxxxxxxx

затем в application.yml у меня есть конфигурация, которая использует это недавно созданное хранилище ключей:

server:
  ssl:
    enable: true
    key-alias: xx-test
    key-password: xxxxxxxxxxxx
    key-store-password: xxxxxxxxxxxx
    key-store-type: pkcs12
    key-store: classpath:keystore.p12

    client-auth: need # Can be also want/need
    trust-store: classpath:keystore.p12
    trust-store-type: pkcs12
    trust-store-password: xxxxxxxxxxxx

когда у меня client-auth: want вместо need chrome браузер сообщает мне, что сертификат недействителен, но я могу прочитать конечную точку. В Spring Boot сообщение: javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown.

Когда я меняю настройку на client-auth: need chrome cast ERR_BAD_SSL_CLIENT_AUTH_CERT и Spring boot cast

Closing SSLConduit after exception on handshake
javax.net.ssl.SSLHandshakeException: Empty client certificate chain
    at sun.security.ssl.Alert.createSSLException(Alert.java:131) ~[?:?]
    at sun.security.ssl.Alert.createSSLException(Alert.java:117) ~[?:?]
    at sun.security.ssl.TransportContext.fatal(TransportContext.java:311) ~[?:?]
    at sun.security.ssl.TransportContext.fatal(TransportContext.java:267) ~[?:?]
    at sun.security.ssl.TransportContext.fatal(TransportContext.java:258) ~[?:?]
    at sun.security.ssl.CertificateMessage$T13CertificateConsumer.onConsumeCertificate(CertificateMessage.java:1176) ~[?:?]
    at sun.security.ssl.CertificateMessage$T13CertificateConsumer.consume(CertificateMessage.java:1163) ~[?:?]
    at sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:396) ~[?:?]
    at sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:444) ~[?:?]
    at sun.security.ssl.SSLEngineImpl$DelegatedTask$DelegatedAction.run(SSLEngineImpl.java:1260) ~[?:?]
    at sun.security.ssl.SSLEngineImpl$DelegatedTask$DelegatedAction.run(SSLEngineImpl.java:1247) ~[?:?]
    at java.security.AccessController.doPrivileged(AccessController.java:691) ~[?:?]
    at sun.security.ssl.SSLEngineImpl$DelegatedTask.run(SSLEngineImpl.java:1192) ~[?:?]
    at io.undertow.protocols.ssl.SslConduit$5.run(SslConduit.java:1107) ~[undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[?:?]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[?:?]
    at java.lang.Thread.run(Thread.java:830) ~[?:?]

также помещается самозаверяющий сертификат в Trusted Root Certification Authorities в Windows.

с опцией -Djavax.net.debug=SSL,keymanager,trustmanager,ssl:handshake, ошибка описана более подробно:


javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.340 CEST|SSLExtensions.java:189|Consumed extension: supported_versions
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.340 CEST|ClientHello.java:838|Negotiated protocol version: TLSv1.3
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.340 CEST|SSLExtensions.java:189|Consumed extension: psk_key_exchange_modes
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.340 CEST|PreSharedKeyExtension.java:840|Handling pre_shared_key absence.
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.340 CEST|ServerNameExtension.java:327|no server name matchers, ignore server name indication
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.341 CEST|SSLExtensions.java:189|Consumed extension: server_name
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.341 CEST|SSLExtensions.java:170|Ignore unavailable extension: max_fragment_length
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.341 CEST|SSLExtensions.java:189|Consumed extension: status_request
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.341 CEST|SSLExtensions.java:189|Consumed extension: supported_groups
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.341 CEST|SSLExtensions.java:160|Ignore unsupported extension: ec_point_formats
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.341 CEST|SSLExtensions.java:189|Consumed extension: signature_algorithms
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.341 CEST|SSLExtensions.java:170|Ignore unavailable extension: signature_algorithms_cert
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.341 CEST|AlpnExtension.java:277|Ignore server unenabled extension: application_layer_protocol_negotiation
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.341 CEST|SSLExtensions.java:189|Consumed extension: application_layer_protocol_negotiation
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.341 CEST|SSLExtensions.java:160|Ignore unsupported extension: status_request_v2
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.341 CEST|SSLExtensions.java:160|Ignore unsupported extension: extended_master_secret
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.341 CEST|SSLExtensions.java:160|Ignore unsupported extension: session_ticket
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.341 CEST|SSLExtensions.java:170|Ignore unavailable extension: cookie
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.341 CEST|KeyShareExtension.java:340|Ignore unsupported named group: UNDEFINED-NAMED-GROUP(60138)
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.342 CEST|SSLExtensions.java:189|Consumed extension: key_share
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.342 CEST|SSLExtensions.java:160|Ignore unsupported extension: renegotiation_info
javax.net.ssl|WARNING|2C|XNIO-1 task-4|2020-07-13 19:37:02.342 CEST|SSLExtensions.java:212|Ignore impact of unsupported extension: server_name
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.342 CEST|SSLExtensions.java:204|Ignore unavailable extension: max_fragment_length
javax.net.ssl|WARNING|2C|XNIO-1 task-4|2020-07-13 19:37:02.342 CEST|SSLExtensions.java:212|Ignore impact of unsupported extension: status_request
javax.net.ssl|WARNING|2C|XNIO-1 task-4|2020-07-13 19:37:02.342 CEST|SSLExtensions.java:212|Ignore impact of unsupported extension: supported_groups
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.343 CEST|SSLExtensions.java:221|Populated with extension: signature_algorithms
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.343 CEST|SSLExtensions.java:204|Ignore unavailable extension: signature_algorithms_cert
javax.net.ssl|WARNING|2C|XNIO-1 task-4|2020-07-13 19:37:02.343 CEST|SSLExtensions.java:212|Ignore impact of unsupported extension: application_layer_protocol_negotiation
javax.net.ssl|WARNING|2C|XNIO-1 task-4|2020-07-13 19:37:02.343 CEST|SSLExtensions.java:212|Ignore impact of unsupported extension: supported_versions
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.343 CEST|SSLExtensions.java:204|Ignore unavailable extension: cookie
javax.net.ssl|WARNING|2C|XNIO-1 task-4|2020-07-13 19:37:02.343 CEST|SSLExtensions.java:212|Ignore impact of unsupported extension: psk_key_exchange_modes
javax.net.ssl|WARNING|2C|XNIO-1 task-4|2020-07-13 19:37:02.343 CEST|SSLExtensions.java:212|Ignore impact of unsupported extension: key_share
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.343 CEST|SSLExtensions.java:204|Ignore unavailable extension: pre_shared_key
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.343 CEST|ServerHello.java:733|use cipher suite TLS_AES_256_GCM_SHA384
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.345 CEST|SSLExtensions.java:257|Ignore, context unavailable extension: pre_shared_key
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.345 CEST|ServerHello.java:587|Produced ServerHello handshake message (
"ServerHello": {.....}

javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.346 CEST|SSLCipher.java:1867|KeyLimit read side: algorithm = AES/GCM/NOPADDING:KEYUPDATE
countdown value = 137438953472
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.347 CEST|SSLCipher.java:2021|KeyLimit write side: algorithm = AES/GCM/NOPADDING:KEYUPDATE
countdown value = 137438953472
javax.net.ssl|ALL|2C|XNIO-1 task-4|2020-07-13 19:37:02.347 CEST|ServerNameExtension.java:537|No expected server name indication response
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.347 CEST|SSLExtensions.java:257|Ignore, context unavailable extension: server_name
javax.net.ssl|ALL|2C|XNIO-1 task-4|2020-07-13 19:37:02.347 CEST|MaxFragExtension.java:469|Ignore unavailable max_fragment_length extension
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.347 CEST|SSLExtensions.java:257|Ignore, context unavailable extension: max_fragment_length
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.348 CEST|AlpnExtension.java:365|Ignore unavailable extension: application_layer_protocol_negotiation
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.348 CEST|SSLExtensions.java:257|Ignore, context unavailable extension: application_layer_protocol_negotiation
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.348 CEST|EncryptedExtensions.java:137|Produced EncryptedExtensions message ("EncryptedExtensions": [
  "supported_groups (10)": {
    "versions": [x25519, secp256r1, secp384r1, secp521r1, x448, ffdhe2048, ffdhe3072, ffdhe4096, ffdhe6144, ffdhe8192]
  }
]
)
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.356 CEST|CertificateRequest.java:882|Produced CertificateRequest message (....)
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.368 CEST|CertificateVerify.java:1113|Produced server CertificateVerify handshake message (
"CertificateVerify": {....}
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.369 CEST|Finished.java:777|Produced server Finished handshake message (
"Finished": {.....}



2020-07-13 19:37:02 DEBUG [XNIO-1 I/O-6] request - UT005013: An IOException occurred
javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
    at sun.security.ssl.Alert.createSSLException(Alert.java:131) ~[?:?]
    at sun.security.ssl.Alert.createSSLException(Alert.java:117) ~[?:?]
    at sun.security.ssl.TransportContext.fatal(TransportContext.java:311) ~[?:?]
    at sun.security.ssl.Alert$AlertConsumer.consume(Alert.java:291) ~[?:?]
    at sun.security.ssl.TransportContext.dispatch(TransportContext.java:184) ~[?:?]
    at sun.security.ssl.SSLTransport.decode(SSLTransport.java:164) ~[?:?]
    at sun.security.ssl.SSLEngineImpl.decode(SSLEngineImpl.java:729) ~[?:?]
    at sun.security.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:684) ~[?:?]
    at sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:499) ~[?:?]
    at sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:475) ~[?:?]
    at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:634) ~[?:?]
    at io.undertow.protocols.ssl.SslConduit.doUnwrap(SslConduit.java:773) ~[undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at io.undertow.protocols.ssl.SslConduit.doWrap(SslConduit.java:898) ~[undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at io.undertow.protocols.ssl.SslConduit.doHandshake(SslConduit.java:665) ~[undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at io.undertow.protocols.ssl.SslConduit.access$900(SslConduit.java:68) ~[undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at io.undertow.protocols.ssl.SslConduit$SslReadReadyHandler.readReady(SslConduit.java:1172) [undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at org.xnio.nio.NioSocketConduit.handleReady(NioSocketConduit.java:88) [xnio-nio-3.3.8.Final.jar:3.3.8.Final]
    at org.xnio.nio.WorkerThread.run(WorkerThread.java:561) [xnio-nio-3.3.8.Final.jar:3.3.8.Final]
2020-07-13 19:37:02 DEBUG [XNIO-1 I/O-5] request - UT005013: An IOException occurred
javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
    at sun.security.ssl.Alert.createSSLException(Alert.java:131) ~[?:?]
    at sun.security.ssl.Alert.createSSLException(Alert.java:117) ~[?:?]
    at sun.security.ssl.TransportContext.fatal(TransportContext.java:311) ~[?:?]
    at sun.security.ssl.Alert$AlertConsumer.consume(Alert.java:291) ~[?:?]
    at sun.security.ssl.TransportContext.dispatch(TransportContext.java:184) ~[?:?]
    at sun.security.ssl.SSLTransport.decode(SSLTransport.java:164) ~[?:?]
    at sun.security.ssl.SSLEngineImpl.decode(SSLEngineImpl.java:729) ~[?:?]
    at sun.security.ssl.SSLEngineImpl.readRecord(SSLEngineImpl.java:684) ~[?:?]
    at sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:499) ~[?:?]
    at sun.security.ssl.SSLEngineImpl.unwrap(SSLEngineImpl.java:475) ~[?:?]
    at javax.net.ssl.SSLEngine.unwrap(SSLEngine.java:634) ~[?:?]
    at io.undertow.protocols.ssl.SslConduit.doUnwrap(SslConduit.java:773) ~[undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at io.undertow.protocols.ssl.SslConduit.doWrap(SslConduit.java:898) ~[undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at io.undertow.protocols.ssl.SslConduit.doHandshake(SslConduit.java:665) ~[undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at io.undertow.protocols.ssl.SslConduit.access$900(SslConduit.java:68) ~[undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at io.undertow.protocols.ssl.SslConduit$SslReadReadyHandler.readReady(SslConduit.java:1172) [undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at org.xnio.nio.NioSocketConduit.handleReady(NioSocketConduit.java:88) [xnio-nio-3.3.8.Final.jar:3.3.8.Final]
    at org.xnio.nio.WorkerThread.run(WorkerThread.java:561) [xnio-nio-3.3.8.Final.jar:3.3.8.Final]
2020-07-13 19:37:02 DEBUG [XNIO-1 I/O-4] request - UT005013: An IOException occurred
java.nio.channels.ClosedChannelException: null
    at io.undertow.protocols.ssl.SslConduit.doWrap(SslConduit.java:892) ~[undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at io.undertow.protocols.ssl.SslConduit.doHandshake(SslConduit.java:665) ~[undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at io.undertow.protocols.ssl.SslConduit.access$900(SslConduit.java:68) ~[undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at io.undertow.protocols.ssl.SslConduit$SslReadReadyHandler.readReady(SslConduit.java:1172) [undertow-core-2.0.30.Final.jar:2.0.30.Final]
    at org.xnio.nio.NioSocketConduit.handleReady(NioSocketConduit.java:88) [xnio-nio-3.3.8.Final.jar:3.3.8.Final]
    at org.xnio.nio.WorkerThread.run(WorkerThread.java:561) [xnio-nio-3.3.8.Final.jar:3.3.8.Final]
javax.net.ssl|DEBUG|2C|XNIO-1 task-4|2020-07-13 19:37:02.370 CEST|SSLCipher.java:2021|KeyLimit write side: algorithm = AES/GCM/NOPADDING:KEYUPDATE
countdown value = 137438953472
javax.net.ssl|DEBUG|17|XNIO-1 I/O-3|2020-07-13 19:37:02.372 CEST|ChangeCipherSpec.java:246|Consuming ChangeCipherSpec message
javax.net.ssl|DEBUG|2D|XNIO-1 task-5|2020-07-13 19:37:02.382 CEST|CertificateMessage.java:1160|Consuming client Certificate handshake message (
"Certificate": {
  "certificate_request_context": "",
  "certificate_list": [  
]
}
)

Однако это не говорит мне слишком много

1 Ответ

0 голосов
/ 24 июля 2020

Решение:

Наконец, у меня возникла небольшая проблема с неправильным промежуточным сертификатом в цепочке.

Кроме того, я решил создать настраиваемую конфигурацию сервера, реализация которой аналогична этой:

@Component
public class UndertowConfiguration implements WebServerFactoryCustomizer<UndertowServletWebServerFactory> {
    ...
    @Override
    public void customize(UndertowServletWebServerFactory factory) {
        factory.addBuilderCustomizers((Undertow.Builder builder) -> {
            try {
                SSLContext sslContext = SSLContext.getInstance("TLS");
                sslContext.init(keyStoreManager.createKeyStore(),
                        trustStoreManager.createTrustStoreManager(),
                        new SecureRandom());
                builder.addHttpsListener(serverPortConfiguration.getSecurePort(), "0.0.0.0", sslContext)
                        .setSocketOption(Options.SSL_CLIENT_AUTH_MODE, SslClientAuthMode.REQUIRED);
            } catch (NoSuchAlgorithmException | KeyStoreException | IOException | CertificateException | UnrecoverableKeyException | KeyManagementException e) {
                e.printStackTrace();
            }
        });
    }

и укажите c webClient для трансляции запроса на другой сервер как:

@Bean
public WebClient webClient() throws IOException, CertificateException, NoSuchAlgorithmException, KeyStoreException, UnrecoverableKeyException {
            SslContext sslContext = SslContextBuilder.forClient()
                    .keyManager(keyStoreManager.createKeyStore())
                    .trustManager(trustStoreManager.createTrustStoreManager())
                    .build();
            httpClient = HttpClient.create()
                .secure(sslContextSpec -> sslContextSpec.sslContext(sslContext));
        }

        return WebClient.builder()
                .clientConnector(new ReactorClientHttpConnector(httpClient))
                .build();
    }

Когда пользовательский sslContext был применен к обоим из них, он начинает работать. Однако сертификаты - это действительно сложная вещь для отладки.

Я надеюсь, что этот пост поможет кому-нибудь с этой проблемой. Также -Djavax.net.debug=all помогает с отладкой и пониманием реальной проблемы с сертификатами в значительной степени.

...