Search in sources :

Example 36 with DTLSConnector

use of org.eclipse.californium.scandium.DTLSConnector in project californium by eclipse.

the class SecureBlockwiseTest method createSecureServer.

private void createSecureServer(MatcherMode mode) {
    AdvancedPskStore pskStore = new AdvancedSinglePskStore(IDENITITY, KEY.getBytes());
    Configuration configuration = network.createTestConfig().set(CoapConfig.ACK_TIMEOUT, 200, TimeUnit.MILLISECONDS).set(CoapConfig.ACK_INIT_RANDOM, 1f).set(CoapConfig.ACK_TIMEOUT_SCALE, 1f).set(CoapConfig.EXCHANGE_LIFETIME, 10, TimeUnit.SECONDS).set(CoapConfig.MAX_MESSAGE_SIZE, DEFAULT_BLOCK_SIZE).set(CoapConfig.PREFERRED_BLOCK_SIZE, DEFAULT_BLOCK_SIZE).set(CoapConfig.RESPONSE_MATCHING, mode).set(DtlsConfig.DTLS_RECEIVER_THREAD_COUNT, 2).set(DtlsConfig.DTLS_CONNECTOR_THREAD_COUNT, 2);
    DtlsConnectorConfig dtlsConfig = DtlsConnectorConfig.builder(configuration).setAddress(TestTools.LOCALHOST_EPHEMERAL).setLoggingTag("server").setAdvancedPskStore(pskStore).build();
    DTLSConnector serverConnector = new DTLSConnector(dtlsConfig);
    CoapEndpoint.Builder builder = new CoapEndpoint.Builder();
    builder.setConnector(serverConnector);
    builder.setConfiguration(configuration);
    CoapEndpoint serverEndpoint = builder.build();
    CoapServer server = new CoapServer();
    cleanup.add(server);
    server.addEndpoint(serverEndpoint);
    resource = new MyResource(TARGET);
    server.add(resource);
    server.start();
    uri = TestTools.getUri(serverEndpoint, TARGET);
    // prepare secure client endpoint
    DtlsConnectorConfig clientdtlsConfig = DtlsConnectorConfig.builder(configuration).setAddress(TestTools.LOCALHOST_EPHEMERAL).setLoggingTag("client").setAdvancedPskStore(pskStore).build();
    DTLSConnector clientConnector = new DTLSConnector(clientdtlsConfig);
    builder = new CoapEndpoint.Builder();
    builder.setConnector(clientConnector);
    builder.setConfiguration(configuration);
    EndpointManager.getEndpointManager().setDefaultEndpoint(builder.build());
}
Also used : AdvancedSinglePskStore(org.eclipse.californium.scandium.dtls.pskstore.AdvancedSinglePskStore) Configuration(org.eclipse.californium.elements.config.Configuration) AdvancedPskStore(org.eclipse.californium.scandium.dtls.pskstore.AdvancedPskStore) CoapServer(org.eclipse.californium.core.CoapServer) CoapEndpoint(org.eclipse.californium.core.network.CoapEndpoint) DtlsConnectorConfig(org.eclipse.californium.scandium.config.DtlsConnectorConfig) DTLSConnector(org.eclipse.californium.scandium.DTLSConnector)

Example 37 with DTLSConnector

use of org.eclipse.californium.scandium.DTLSConnector in project openhab-addons by openhab.

the class TradfriGatewayHandler method establishConnection.

private void establishConnection() {
    TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);
    this.gatewayURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + DEVICES;
    this.gatewayInfoURI = "coaps://" + configuration.host + ":" + configuration.port + "/" + GATEWAY + "/" + GATEWAY_DETAILS;
    try {
        URI uri = new URI(gatewayURI);
        deviceClient = new TradfriCoapClient(uri);
    } catch (URISyntaxException e) {
        logger.error("Illegal gateway URI '{}': {}", gatewayURI, e.getMessage());
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
        return;
    }
    DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder();
    builder.setPskStore(new StaticPskStore(configuration.identity, configuration.preSharedKey.getBytes()));
    builder.setMaxConnections(100);
    builder.setStaleConnectionThreshold(60);
    dtlsConnector = new DTLSConnector(builder.build());
    endPoint = new CoapEndpoint.Builder().setConnector(dtlsConnector).build();
    deviceClient.setEndpoint(endPoint);
    updateStatus(ThingStatus.UNKNOWN);
    // schedule a new scan every minute
    scanJob = scheduler.scheduleWithFixedDelay(this::startScan, 0, 1, TimeUnit.MINUTES);
}
Also used : StaticPskStore(org.eclipse.californium.scandium.dtls.pskstore.StaticPskStore) TradfriGatewayConfig(org.openhab.binding.tradfri.internal.config.TradfriGatewayConfig) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) CoapEndpoint(org.eclipse.californium.core.network.CoapEndpoint) DtlsConnectorConfig(org.eclipse.californium.scandium.config.DtlsConnectorConfig) DTLSConnector(org.eclipse.californium.scandium.DTLSConnector) TradfriCoapClient(org.openhab.binding.tradfri.internal.TradfriCoapClient)

Example 38 with DTLSConnector

use of org.eclipse.californium.scandium.DTLSConnector in project openhab-addons by openhab.

the class TradfriGatewayHandler method obtainIdentityAndPreSharedKey.

/**
 * Authenticates against the gateway with the security code in order to receive a pre-shared key for a newly
 * generated identity.
 * As this requires a remote request, this method might be long-running.
 *
 * @return true, if credentials were successfully obtained, false otherwise
 */
protected boolean obtainIdentityAndPreSharedKey() {
    TradfriGatewayConfig configuration = getConfigAs(TradfriGatewayConfig.class);
    String identity = UUID.randomUUID().toString().replace("-", "");
    String preSharedKey = null;
    CoapResponse gatewayResponse;
    String authUrl = null;
    String responseText = null;
    try {
        DtlsConnectorConfig.Builder builder = new DtlsConnectorConfig.Builder();
        builder.setPskStore(new StaticPskStore("Client_identity", configuration.code.getBytes()));
        DTLSConnector dtlsConnector = new DTLSConnector(builder.build());
        CoapEndpoint.Builder authEndpointBuilder = new CoapEndpoint.Builder();
        authEndpointBuilder.setConnector(dtlsConnector);
        CoapEndpoint authEndpoint = authEndpointBuilder.build();
        authUrl = "coaps://" + configuration.host + ":" + configuration.port + "/15011/9063";
        CoapClient deviceClient = new CoapClient(new URI(authUrl));
        deviceClient.setTimeout(TimeUnit.SECONDS.toMillis(10));
        deviceClient.setEndpoint(authEndpoint);
        JsonObject json = new JsonObject();
        json.addProperty(CLIENT_IDENTITY_PROPOSED, identity);
        gatewayResponse = deviceClient.post(json.toString(), 0);
        authEndpoint.destroy();
        deviceClient.shutdown();
        if (gatewayResponse == null) {
            // seems we ran in a timeout, which potentially also happens
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "No response from gateway. Might be due to an invalid security code.");
            return false;
        }
        if (gatewayResponse.isSuccess()) {
            responseText = gatewayResponse.getResponseText();
            json = JsonParser.parseString(responseText).getAsJsonObject();
            preSharedKey = json.get(NEW_PSK_BY_GW).getAsString();
            if (isNullOrEmpty(preSharedKey)) {
                logger.error("Received pre-shared key is empty for thing {} on gateway at {}", getThing().getUID(), configuration.host);
                updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, "Pre-shared key was not obtain successfully");
                return false;
            } else {
                logger.info("Received pre-shared key for gateway '{}'", configuration.host);
                logger.debug("Using identity '{}' with pre-shared key '{}'.", identity, preSharedKey);
                Configuration editedConfig = editConfiguration();
                editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_CODE, null);
                editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_IDENTITY, identity);
                editedConfig.put(TradfriBindingConstants.GATEWAY_CONFIG_PRE_SHARED_KEY, preSharedKey);
                updateConfiguration(editedConfig);
                return true;
            }
        } else {
            logger.warn("Failed obtaining pre-shared key for identity '{}' (response code '{}', response text '{}')", identity, gatewayResponse.getCode(), isNullOrEmpty(gatewayResponse.getResponseText()) ? "<empty>" : gatewayResponse.getResponseText());
            updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, String.format("Failed obtaining pre-shared key with status code '%s'", gatewayResponse.getCode()));
        }
    } catch (URISyntaxException e) {
        logger.error("Illegal gateway URI '{}'", authUrl, e);
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
    } catch (JsonParseException e) {
        logger.warn("Invalid response received from gateway '{}'", responseText, e);
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, String.format("Invalid response received from gateway '%s'", responseText));
    } catch (ConnectorException | IOException e) {
        logger.debug("Error connecting to gateway ", e);
        updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, String.format("Error connecting to gateway."));
    }
    return false;
}
Also used : CoapResponse(org.eclipse.californium.core.CoapResponse) Configuration(org.openhab.core.config.core.Configuration) JsonObject(com.google.gson.JsonObject) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) JsonParseException(com.google.gson.JsonParseException) URI(java.net.URI) DtlsConnectorConfig(org.eclipse.californium.scandium.config.DtlsConnectorConfig) DTLSConnector(org.eclipse.californium.scandium.DTLSConnector) CoapClient(org.eclipse.californium.core.CoapClient) TradfriCoapClient(org.openhab.binding.tradfri.internal.TradfriCoapClient) StaticPskStore(org.eclipse.californium.scandium.dtls.pskstore.StaticPskStore) TradfriGatewayConfig(org.openhab.binding.tradfri.internal.config.TradfriGatewayConfig) ConnectorException(org.eclipse.californium.elements.exception.ConnectorException) CoapEndpoint(org.eclipse.californium.core.network.CoapEndpoint)

Example 39 with DTLSConnector

use of org.eclipse.californium.scandium.DTLSConnector in project californium.tools by eclipse.

the class SamplerEndpointsManager method getSampleEndpoint.

public SamplerEndpoint getSampleEndpoint(String scheme, String identity, byte[] secret, long idleTimeMillis, Configuration configuration) {
    String key = scheme + "://" + identity + "@";
    SamplerEndpoint samplerEndpoint = ENDPOINTS.get(key);
    if (samplerEndpoint == null || samplerEndpoint.expired()) {
        Connector connector;
        if (CoAP.COAP_SECURE_URI_SCHEME.equals(scheme)) {
            AdvancedPskStore psk = new AdvancedSinglePskStore(identity, secret);
            DtlsConnectorConfig.Builder dtlsBuilder = DtlsConnectorConfig.builder(configuration);
            dtlsBuilder.setAdvancedPskStore(psk);
            DTLSConnector dtlsConnector = new DTLSConnector(dtlsBuilder.build());
            dtlsConnector.setExecutor(EXECUTOR);
            connector = dtlsConnector;
        } else {
            connector = new UDPConnector(null, configuration);
        }
        CoapEndpoint.Builder coapBuilder = new CoapEndpoint.Builder();
        coapBuilder.setConfiguration(configuration);
        coapBuilder.setConnector(connector);
        CoapEndpoint endpoint = coapBuilder.build();
        endpoint.setExecutors(EXECUTOR, TIMER);
        samplerEndpoint = new SamplerEndpoint(key, endpoint, idleTimeMillis);
        SamplerEndpoint previous = ENDPOINTS.putIfAbsent(key, samplerEndpoint);
        if (previous == null) {
            try {
                endpoint.start();
            } catch (IOException e) {
                ENDPOINTS.remove(key, samplerEndpoint);
                samplerEndpoint = null;
                LOGGER.warn("Setup failed for {}!", key, e);
            }
            LOGGER.debug("Endpoint for {} created.", key);
        } else {
            samplerEndpoint.close();
            samplerEndpoint = previous;
        }
    } else {
        samplerEndpoint.setIdleTime(idleTimeMillis);
    }
    return samplerEndpoint;
}
Also used : UDPConnector(org.eclipse.californium.elements.UDPConnector) DTLSConnector(org.eclipse.californium.scandium.DTLSConnector) Connector(org.eclipse.californium.elements.Connector) AdvancedSinglePskStore(org.eclipse.californium.scandium.dtls.pskstore.AdvancedSinglePskStore) IOException(java.io.IOException) DtlsConnectorConfig(org.eclipse.californium.scandium.config.DtlsConnectorConfig) DTLSConnector(org.eclipse.californium.scandium.DTLSConnector) UDPConnector(org.eclipse.californium.elements.UDPConnector) AdvancedPskStore(org.eclipse.californium.scandium.dtls.pskstore.AdvancedPskStore) CoapEndpoint(org.eclipse.californium.core.network.CoapEndpoint)

Aggregations

DTLSConnector (org.eclipse.californium.scandium.DTLSConnector)39 CoapEndpoint (org.eclipse.californium.core.network.CoapEndpoint)29 DtlsConnectorConfig (org.eclipse.californium.scandium.config.DtlsConnectorConfig)28 InetSocketAddress (java.net.InetSocketAddress)15 Configuration (org.eclipse.californium.elements.config.Configuration)15 Endpoint (org.eclipse.californium.core.network.Endpoint)9 CoapServer (org.eclipse.californium.core.CoapServer)8 AdvancedSinglePskStore (org.eclipse.californium.scandium.dtls.pskstore.AdvancedSinglePskStore)7 URI (java.net.URI)5 Builder (org.eclipse.californium.scandium.config.DtlsConnectorConfig.Builder)5 IOException (java.io.IOException)4 URISyntaxException (java.net.URISyntaxException)4 StaticPskStore (org.eclipse.californium.scandium.dtls.pskstore.StaticPskStore)4 CoapClient (org.eclipse.californium.core.CoapClient)3 NetworkConfig (org.eclipse.californium.core.network.config.NetworkConfig)3 Connector (org.eclipse.californium.elements.Connector)3 DtlsHealthLogger (org.eclipse.californium.scandium.DtlsHealthLogger)3 MdcConnectionListener (org.eclipse.californium.scandium.MdcConnectionListener)3 AdvancedPskStore (org.eclipse.californium.scandium.dtls.pskstore.AdvancedPskStore)3 AsyncAdvancedPskStore (org.eclipse.californium.scandium.dtls.pskstore.AsyncAdvancedPskStore)3