Search in sources :

Example 1 with SingleNodeConnectionIdGenerator

use of org.eclipse.californium.scandium.dtls.SingleNodeConnectionIdGenerator in project californium by eclipse.

the class SecureObserveTest method testSecureObserveServerAddressChangedWithCid.

/**
 * Test observe using a DTLS connection when the observed server changed the
 * address using a dtls connection id.
 */
@Test
public void testSecureObserveServerAddressChangedWithCid() throws Exception {
    createSecureServer(MatcherMode.STRICT, new SingleNodeConnectionIdGenerator(6));
    createInverseNat();
    CoapClient client = new CoapClient(uri);
    CountingCoapHandler handler = new CountingCoapHandler();
    CoapObserveRelation rel = client.observeAndWait(handler);
    assertFalse("Observe relation not established!", rel.isCanceled());
    // onLoad is called asynchronous to returning the response
    // therefore wait for one onLoad
    assertTrue(handler.waitOnLoadCalls(1, TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS));
    assertFalse("Response not received", rel.isCanceled());
    assertThat("Response not received", rel.getCurrent(), is(notNullValue()));
    assertEquals("\"resource says hi for the 1 time\"", rel.getCurrent().getResponseText());
    EndpointContext context1 = rel.getCurrent().advanced().getSourceContext();
    assertThat("context-1 missing", context1, is(notNullValue()));
    for (int i = 0; i < REPEATS; ++i) {
        resource.changed("client");
        Thread.sleep(50);
    }
    assertTrue("Missing notifies", handler.waitOnLoadCalls(REPEATS + 1, TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS));
    nat.reassignNewLocalAddresses();
    // trigger handshake
    resource.changed("client");
    // wait for established session
    assertTrue("Missing notifies", handler.waitOnLoadCalls(REPEATS + 2, TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS));
    for (int i = 0; i < REPEATS; ++i) {
        resource.changed("client");
        Thread.sleep(50);
    }
    assertTrue("Missing notifies after address changed", handler.waitOnLoadCalls(REPEATS + REPEATS + 2, TIMEOUT_IN_MILLIS, TimeUnit.MILLISECONDS));
    assertThat("sending response missing", resource.getCurrentResponse(), is(notNullValue()));
    assertThat("sending response caused error", resource.getCurrentResponse().getSendError(), is(nullValue()));
    EndpointContext context2 = rel.getCurrent().advanced().getSourceContext();
    assertThat("context-2 missing", context2, is(notNullValue()));
    assertThat(context2.get(DtlsEndpointContext.KEY_HANDSHAKE_TIMESTAMP), is(context1.get(DtlsEndpointContext.KEY_HANDSHAKE_TIMESTAMP)));
    String natURI = uri.replace(":" + context1.getPeerAddress().getPort() + "/", ":" + context2.getPeerAddress().getPort() + "/");
    System.out.println("URI: change " + uri + " to " + natURI);
    client.setURI(natURI);
    CoapResponse coapResponse = client.get();
    assertThat("response missing", coapResponse, is(notNullValue()));
    client.shutdown();
}
Also used : CoapResponse(org.eclipse.californium.core.CoapResponse) SingleNodeConnectionIdGenerator(org.eclipse.californium.scandium.dtls.SingleNodeConnectionIdGenerator) DtlsEndpointContext(org.eclipse.californium.elements.DtlsEndpointContext) EndpointContext(org.eclipse.californium.elements.EndpointContext) CountingCoapHandler(org.eclipse.californium.core.test.CountingCoapHandler) CoapObserveRelation(org.eclipse.californium.core.CoapObserveRelation) CoapClient(org.eclipse.californium.core.CoapClient) CoapEndpoint(org.eclipse.californium.core.network.CoapEndpoint) Test(org.junit.Test)

Example 2 with SingleNodeConnectionIdGenerator

use of org.eclipse.californium.scandium.dtls.SingleNodeConnectionIdGenerator in project californium by eclipse.

the class DtlsClusterConnectorTest method initClient.

@Before
public void initClient() throws IOException {
    AdvancedSinglePskStore testPskStore = new AdvancedSinglePskStore(ConnectorHelper.CLIENT_IDENTITY, ConnectorHelper.CLIENT_IDENTITY_SECRET.getBytes());
    DtlsConnectorConfig config = DtlsConnectorConfig.builder(configuration).set(DtlsConfig.DTLS_MAX_CONNECTIONS, 10).set(DtlsConfig.DTLS_STALE_CONNECTION_THRESHOLD, 6000, TimeUnit.SECONDS).setLoggingTag("client").setAdvancedPskStore(testPskStore).setConnectionIdGenerator(new SingleNodeConnectionIdGenerator(4)).build();
    clientConnections = ConnectorHelper.createDebugConnectionStore(config);
    clientConnector = new DTLSConnector(config, clientConnections);
    clientChannel = new LatchDecrementingRawDataChannel();
    clientConnector.setRawDataReceiver(clientChannel);
    clientConnector.start();
}
Also used : AdvancedSinglePskStore(org.eclipse.californium.scandium.dtls.pskstore.AdvancedSinglePskStore) LatchDecrementingRawDataChannel(org.eclipse.californium.scandium.ConnectorHelper.LatchDecrementingRawDataChannel) SingleNodeConnectionIdGenerator(org.eclipse.californium.scandium.dtls.SingleNodeConnectionIdGenerator) DtlsConnectorConfig(org.eclipse.californium.scandium.config.DtlsConnectorConfig) Before(org.junit.Before)

Example 3 with SingleNodeConnectionIdGenerator

use of org.eclipse.californium.scandium.dtls.SingleNodeConnectionIdGenerator in project californium by eclipse.

the class ConnectorUtil method build.

/**
 * Build connector.
 *
 * @param bind address to bind connector to
 * @param dtlsBuilder preconfigured dtls builder. Maybe {@code null}.
 * @param trust alias of trusted certificate, or {@code null} to trust all
 *            received certificates.
 * @param cipherSuites cipher suites to support.
 */
public void build(InetSocketAddress bind, DtlsConnectorConfig.Builder dtlsBuilder, String trust, CipherSuite... cipherSuites) {
    List<CipherSuite> suites = Arrays.asList(cipherSuites);
    if (dtlsBuilder == null) {
        dtlsBuilder = DtlsConnectorConfig.builder(new Configuration());
    }
    dtlsBuilder.set(DtlsConfig.DTLS_ADDITIONAL_ECC_TIMEOUT, 1000, TimeUnit.MILLISECONDS).set(DtlsConfig.DTLS_RETRANSMISSION_TIMEOUT, 1000, TimeUnit.MILLISECONDS).set(DtlsConfig.DTLS_RECEIVER_THREAD_COUNT, 2).set(DtlsConfig.DTLS_CONNECTOR_THREAD_COUNT, 2).set(DtlsConfig.DTLS_RECOMMENDED_CIPHER_SUITES_ONLY, false).setAddress(bind).setConnectionIdGenerator(new SingleNodeConnectionIdGenerator(6));
    if (CipherSuite.containsPskBasedCipherSuite(suites)) {
        dtlsBuilder.setAdvancedPskStore(new AdvancedSinglePskStore(CredentialslUtil.OPENSSL_PSK_IDENTITY, CredentialslUtil.OPENSSL_PSK_SECRET));
    }
    if (CipherSuite.containsCipherSuiteRequiringCertExchange(suites)) {
        if (credentials != null && dtlsBuilder.getIncompleteConfig().getCertificateIdentityProvider() == null) {
            Credentials credentials = nextCredentials != null ? nextCredentials : this.credentials;
            dtlsBuilder.setCertificateIdentityProvider(new SingleCertificateProvider(credentials.getPrivateKey(), credentials.getCertificateChain(), CertificateType.X_509, CertificateType.RAW_PUBLIC_KEY));
        }
        if (dtlsBuilder.getIncompleteConfig().getAdvancedCertificateVerifier() == null) {
            Builder builder = StaticNewAdvancedCertificateVerifier.builder();
            if (TRUST_CA.equals(trust)) {
                builder.setTrustedCertificates(trustCa);
            } else if (TRUST_ROOT.equals(trust)) {
                builder.setTrustedCertificates(trustRoot);
            } else {
                builder.setTrustAllCertificates();
            }
            builder.setTrustAllRPKs();
            dtlsBuilder.setAdvancedCertificateVerifier(builder.build());
        }
    }
    dtlsBuilder.set(DtlsConfig.DTLS_CIPHER_SUITES, suites);
    connector = new DTLSConnector(dtlsBuilder.build());
    alertCatcher.resetAlert();
    connector.setAlertHandler(alertCatcher);
    nextCredentials = null;
}
Also used : AdvancedSinglePskStore(org.eclipse.californium.scandium.dtls.pskstore.AdvancedSinglePskStore) Configuration(org.eclipse.californium.elements.config.Configuration) SingleNodeConnectionIdGenerator(org.eclipse.californium.scandium.dtls.SingleNodeConnectionIdGenerator) CipherSuite(org.eclipse.californium.scandium.dtls.cipher.CipherSuite) Builder(org.eclipse.californium.scandium.dtls.x509.StaticNewAdvancedCertificateVerifier.Builder) SingleCertificateProvider(org.eclipse.californium.scandium.dtls.x509.SingleCertificateProvider) Credentials(org.eclipse.californium.elements.util.SslContextUtil.Credentials) DTLSConnector(org.eclipse.californium.scandium.DTLSConnector)

Example 4 with SingleNodeConnectionIdGenerator

use of org.eclipse.californium.scandium.dtls.SingleNodeConnectionIdGenerator in project californium by eclipse.

the class NatTestHelper method createSecureServer.

void createSecureServer(Integer cidLength) throws IOException {
    ConnectionIdGenerator cidGenerator = cidLength == null ? null : new SingleNodeConnectionIdGenerator(cidLength);
    createSecureServer(cidGenerator);
}
Also used : SingleNodeConnectionIdGenerator(org.eclipse.californium.scandium.dtls.SingleNodeConnectionIdGenerator) NodeConnectionIdGenerator(org.eclipse.californium.scandium.dtls.NodeConnectionIdGenerator) ConnectionIdGenerator(org.eclipse.californium.scandium.dtls.ConnectionIdGenerator) SingleNodeConnectionIdGenerator(org.eclipse.californium.scandium.dtls.SingleNodeConnectionIdGenerator)

Example 5 with SingleNodeConnectionIdGenerator

use of org.eclipse.californium.scandium.dtls.SingleNodeConnectionIdGenerator in project californium by eclipse.

the class DTLSConnectorAdvancedTest method loadKeys.

@BeforeClass
public static void loadKeys() throws IOException, GeneralSecurityException {
    serverHelper = new ConnectorHelper(network);
    serverHealth = new DtlsHealthLogger("server");
    serverCidGenerator = new SingleNodeConnectionIdGenerator(6);
    AdvancedMultiPskStore pskStore = new AdvancedMultiPskStore();
    pskStore.setKey(CLIENT_IDENTITY, CLIENT_IDENTITY_SECRET.getBytes());
    pskStore.setKey(SCOPED_CLIENT_IDENTITY, SCOPED_CLIENT_IDENTITY_SECRET.getBytes(), SERVERNAME);
    serverPskStore = new AsyncAdvancedPskStore(pskStore) {

        @Override
        public PskSecretResult requestPskSecretResult(final ConnectionId cid, final ServerNames serverNames, final PskPublicInformation identity, final String hmacAlgorithm, SecretKey otherSecret, byte[] seed, boolean useExtendedMasterSecret) {
            LOGGER.info("get PSK secrets");
            PskSecretResult result = null;
            if (0 < pskHandshakeResponses) {
                result = super.requestPskSecretResult(cid, serverNames, identity, hmacAlgorithm, otherSecret, seed, useExtendedMasterSecret);
                if (1 < pskHandshakeResponses) {
                    final int delay = getDelay();
                    try {
                        setDelay(1);
                        for (int index = 1; index < pskHandshakeResponses; ++index) {
                            super.requestPskSecretResult(cid, serverNames, identity, hmacAlgorithm, otherSecret, seed, useExtendedMasterSecret);
                        }
                    } finally {
                        setDelay(delay);
                    }
                }
            }
            return result;
        }
    };
    serverCertificateVerifier = new AsyncNewAdvancedCertificateVerifier(DtlsTestTools.getTrustedCertificates(), new RawPublicKeyIdentity[0], null) {

        @Override
        public CertificateVerificationResult verifyCertificate(final ConnectionId cid, final ServerNames serverName, InetSocketAddress remotePeer, final boolean clientUsage, boolean verifyDestination, final boolean truncateCertificatePath, final CertificateMessage message) {
            LOGGER.info("verify certificate");
            CertificateVerificationResult result = null;
            if (0 < verifyHandshakeResponses) {
                result = super.verifyCertificate(cid, serverName, remotePeer, clientUsage, verifyDestination, truncateCertificatePath, message);
                if (1 < verifyHandshakeResponses) {
                    final int delay = getDelay();
                    try {
                        setDelay(1);
                        for (int index = 1; index < verifyHandshakeResponses; ++index) {
                            super.verifyCertificate(cid, serverName, remotePeer, clientUsage, verifyDestination, truncateCertificatePath, message);
                        }
                    } finally {
                        setDelay(delay);
                    }
                }
            }
            return result;
        }
    };
    serverResumptionVerifier = new AsyncResumptionVerifier() {

        @Override
        public ResumptionVerificationResult verifyResumptionRequest(final ConnectionId cid, final ServerNames serverName, final SessionId sessionId) {
            LOGGER.info("verify resumption");
            ResumptionVerificationResult result = null;
            if (0 < resumeHandshakeResponses) {
                result = super.verifyResumptionRequest(cid, serverName, sessionId);
                if (1 < resumeHandshakeResponses) {
                    final int delay = getDelay();
                    try {
                        setDelay(1);
                        for (int index = 1; index < resumeHandshakeResponses; ++index) {
                            super.verifyResumptionRequest(cid, serverName, sessionId);
                        }
                    } finally {
                        setDelay(delay);
                    }
                }
            }
            return result;
        }
    };
    serverCertificateProvider = new AsyncCertificateProvider(DtlsTestTools.getPrivateKey(), DtlsTestTools.getServerCertificateChain(), CertificateType.RAW_PUBLIC_KEY, CertificateType.X_509) {

        @Override
        public CertificateIdentityResult requestCertificateIdentity(final ConnectionId cid, final boolean client, final List<X500Principal> issuers, final ServerNames serverName, final List<CertificateKeyAlgorithm> certificateKeyAlgorithms, final List<SignatureAndHashAlgorithm> signaturesAndHashAlgorithms, final List<SupportedGroup> curves) {
            LOGGER.info("verify resumption");
            CertificateIdentityResult result = null;
            if (0 < certificateHandshakeResponses) {
                result = super.requestCertificateIdentity(cid, client, issuers, serverName, certificateKeyAlgorithms, signaturesAndHashAlgorithms, curves);
                if (1 < certificateHandshakeResponses) {
                    final int delay = getDelay();
                    try {
                        setDelay(1);
                        for (int index = 1; index < certificateHandshakeResponses; ++index) {
                            super.requestCertificateIdentity(cid, client, issuers, serverName, certificateKeyAlgorithms, signaturesAndHashAlgorithms, curves);
                        }
                    } finally {
                        setDelay(delay);
                    }
                }
            }
            return result;
        }
    };
    serverHelper.serverBuilder.set(DtlsConfig.DTLS_RETRANSMISSION_TIMEOUT, RETRANSMISSION_TIMEOUT_MS, TimeUnit.MILLISECONDS).set(DtlsConfig.DTLS_MAX_RETRANSMISSIONS, MAX_RETRANSMISSIONS).set(DtlsConfig.DTLS_MAX_TRANSMISSION_UNIT, 1024).setConnectionIdGenerator(serverCidGenerator).setHealthHandler(serverHealth).setAdvancedPskStore(serverPskStore).setCertificateIdentityProvider(serverCertificateProvider).setAdvancedCertificateVerifier(serverCertificateVerifier).setResumptionVerifier(serverResumptionVerifier);
    serverHelper.startServer();
    serverConfigSingleRecord = DtlsConnectorConfig.builder(serverHelper.serverConfig).set(DtlsConfig.DTLS_USE_MULTI_RECORD_MESSAGES, false).build();
    executor = ExecutorsUtil.newFixedThreadPool(2, new TestThreadFactory("DTLS-ADVANCED-"));
    timer = new TestScheduledExecutorService();
    clientHealth = new DtlsHealthLogger("client");
}
Also used : AsyncAdvancedPskStore(org.eclipse.californium.scandium.dtls.pskstore.AsyncAdvancedPskStore) AsyncResumptionVerifier(org.eclipse.californium.scandium.dtls.resumption.AsyncResumptionVerifier) InetSocketAddress(java.net.InetSocketAddress) TestScheduledExecutorService(org.eclipse.californium.elements.util.TestScheduledExecutorService) CertificateMessage(org.eclipse.californium.scandium.dtls.CertificateMessage) SignatureAndHashAlgorithm(org.eclipse.californium.scandium.dtls.SignatureAndHashAlgorithm) ConnectionId(org.eclipse.californium.scandium.dtls.ConnectionId) SupportedGroup(org.eclipse.californium.scandium.dtls.cipher.XECDHECryptography.SupportedGroup) TestThreadFactory(org.eclipse.californium.elements.util.TestThreadFactory) SessionId(org.eclipse.californium.scandium.dtls.SessionId) CertificateKeyAlgorithm(org.eclipse.californium.scandium.dtls.cipher.CipherSuite.CertificateKeyAlgorithm) ServerNames(org.eclipse.californium.scandium.util.ServerNames) AsyncNewAdvancedCertificateVerifier(org.eclipse.californium.scandium.dtls.x509.AsyncNewAdvancedCertificateVerifier) AsyncCertificateProvider(org.eclipse.californium.scandium.dtls.x509.AsyncCertificateProvider) SingleNodeConnectionIdGenerator(org.eclipse.californium.scandium.dtls.SingleNodeConnectionIdGenerator) RawPublicKeyIdentity(org.eclipse.californium.elements.auth.RawPublicKeyIdentity) ResumptionVerificationResult(org.eclipse.californium.scandium.dtls.ResumptionVerificationResult) PskPublicInformation(org.eclipse.californium.scandium.dtls.PskPublicInformation) CertificateVerificationResult(org.eclipse.californium.scandium.dtls.CertificateVerificationResult) SecretKey(javax.crypto.SecretKey) PskSecretResult(org.eclipse.californium.scandium.dtls.PskSecretResult) X500Principal(javax.security.auth.x500.X500Principal) CertificateIdentityResult(org.eclipse.californium.scandium.dtls.CertificateIdentityResult) AdvancedMultiPskStore(org.eclipse.californium.scandium.dtls.pskstore.AdvancedMultiPskStore) BeforeClass(org.junit.BeforeClass)

Aggregations

SingleNodeConnectionIdGenerator (org.eclipse.californium.scandium.dtls.SingleNodeConnectionIdGenerator)5 AdvancedSinglePskStore (org.eclipse.californium.scandium.dtls.pskstore.AdvancedSinglePskStore)2 InetSocketAddress (java.net.InetSocketAddress)1 SecretKey (javax.crypto.SecretKey)1 X500Principal (javax.security.auth.x500.X500Principal)1 CoapClient (org.eclipse.californium.core.CoapClient)1 CoapObserveRelation (org.eclipse.californium.core.CoapObserveRelation)1 CoapResponse (org.eclipse.californium.core.CoapResponse)1 CoapEndpoint (org.eclipse.californium.core.network.CoapEndpoint)1 CountingCoapHandler (org.eclipse.californium.core.test.CountingCoapHandler)1 DtlsEndpointContext (org.eclipse.californium.elements.DtlsEndpointContext)1 EndpointContext (org.eclipse.californium.elements.EndpointContext)1 RawPublicKeyIdentity (org.eclipse.californium.elements.auth.RawPublicKeyIdentity)1 Configuration (org.eclipse.californium.elements.config.Configuration)1 Credentials (org.eclipse.californium.elements.util.SslContextUtil.Credentials)1 TestScheduledExecutorService (org.eclipse.californium.elements.util.TestScheduledExecutorService)1 TestThreadFactory (org.eclipse.californium.elements.util.TestThreadFactory)1 LatchDecrementingRawDataChannel (org.eclipse.californium.scandium.ConnectorHelper.LatchDecrementingRawDataChannel)1 DTLSConnector (org.eclipse.californium.scandium.DTLSConnector)1 DtlsConnectorConfig (org.eclipse.californium.scandium.config.DtlsConnectorConfig)1