Search in sources :

Example 1 with IotHubSSLContext

use of com.microsoft.azure.sdk.iot.deps.auth.IotHubSSLContext in project azure-iot-sdk-java by Azure.

the class AmqpsIotHubConnection method onConnectionBound.

@Override
public void onConnectionBound(Event event) {
    Transport transport = event.getTransport();
    // Convert from seconds to milliseconds since this proton-j API only accepts keep alive in milliseconds
    transport.setIdleTimeout(keepAliveInterval * 1000);
    if (this.isWebsocketConnection) {
        addWebSocketLayer(transport);
    }
    try {
        Iterator<DeviceClientConfig> configsIterator = this.deviceClientConfigs.iterator();
        DeviceClientConfig defaultConfig = configsIterator.hasNext() ? configsIterator.next() : null;
        SSLContext sslContext;
        if (defaultConfig != null) {
            sslContext = defaultConfig.getAuthenticationProvider().getSSLContext();
        } else if (this.sslContext != null) {
            // This should only be hit when a user creates a multiplexing client and specifies an SSLContext
            // that they want to use
            sslContext = this.sslContext;
        } else {
            // This should only be hit when a user creates a multiplexing client and doesn't specify an SSLContext
            // that they want to use
            sslContext = new IotHubSSLContext().getSSLContext();
        }
        if (this.authenticationType == DeviceClientConfig.AuthType.SAS_TOKEN) {
            Sasl sasl = transport.sasl();
            sasl.setMechanisms("ANONYMOUS");
        }
        SslDomain domain = Proton.sslDomain();
        domain.setSslContext(sslContext);
        domain.setPeerAuthentication(SslDomain.VerifyMode.VERIFY_PEER);
        domain.init(SslDomain.Mode.CLIENT);
        transport.ssl(domain);
    } catch (IOException | CertificateException | NoSuchAlgorithmException | KeyStoreException | KeyManagementException e) {
        this.savedException = new TransportException(e);
        log.error("Encountered an exception while setting ssl domain for the amqp connection", this.savedException);
    }
    // Adding proxy layer needs to be done after sending SSL message
    if (proxySettings != null) {
        addProxyLayer(transport, event.getConnection().getHostname() + ":" + WEB_SOCKET_PORT);
    }
}
Also used : CertificateException(java.security.cert.CertificateException) SSLContext(javax.net.ssl.SSLContext) IotHubSSLContext(com.microsoft.azure.sdk.iot.deps.auth.IotHubSSLContext) IOException(java.io.IOException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) TransportException(com.microsoft.azure.sdk.iot.device.exceptions.TransportException) KeyManagementException(java.security.KeyManagementException) IotHubSSLContext(com.microsoft.azure.sdk.iot.deps.auth.IotHubSSLContext)

Example 2 with IotHubSSLContext

use of com.microsoft.azure.sdk.iot.deps.auth.IotHubSSLContext in project azure-iot-sdk-java by Azure.

the class IotHubX509SoftwareIotHubAuthenticationProviderTest method getSSLContextGets.

// Tests_SRS_IOTHUBX509AUTHENTICATION_34_005: [This function shall return the saved IotHubSSLContext.]
@Test
public void getSSLContextGets() throws CertificateException, UnrecoverableKeyException, NoSuchAlgorithmException, IOException, KeyManagementException, KeyStoreException, TransportException {
    // arrange
    new NonStrictExpectations() {

        {
            Deencapsulation.invoke(mockIotHubSSLContext, "getSSLContext");
            result = mockSSLContext;
        }
    };
    IotHubAuthenticationProvider x509Auth = new IotHubX509SoftwareAuthenticationProvider(hostname, gatewayHostname, deviceId, moduleId, publicKeyCertificate, false, privateKey, false);
    Deencapsulation.setField(x509Auth, "iotHubSSLContext", mockIotHubSSLContext);
    // act
    SSLContext actualSSLContext = x509Auth.getSSLContext();
    // assert
    assertEquals(mockSSLContext, actualSSLContext);
}
Also used : SSLContext(javax.net.ssl.SSLContext) IotHubSSLContext(com.microsoft.azure.sdk.iot.deps.auth.IotHubSSLContext) Test(org.junit.Test)

Example 3 with IotHubSSLContext

use of com.microsoft.azure.sdk.iot.deps.auth.IotHubSSLContext in project azure-iot-sdk-java by Azure.

the class ServiceClientTests method cloudToDeviceTelemetry.

public void cloudToDeviceTelemetry(boolean withProxy, boolean withPayload, boolean withLargestPayload, boolean withCustomSSLContext, boolean withAzureSasCredential) throws Exception {
    // We remove and recreate the device for a clean start
    RegistryManager registryManager = RegistryManager.createFromConnectionString(iotHubConnectionString, RegistryManagerOptions.builder().httpReadTimeout(HTTP_READ_TIMEOUT).build());
    TestDeviceIdentity testDeviceIdentity = Tools.getTestDevice(iotHubConnectionString, IotHubClientProtocol.AMQPS, AuthenticationType.SAS, false);
    Device device = testDeviceIdentity.getDevice();
    Device deviceGetBefore = registryManager.getDevice(device.getDeviceId());
    // Create service client
    ProxyOptions proxyOptions = null;
    if (withProxy) {
        Proxy testProxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(testProxyHostname, testProxyPort));
        proxyOptions = new ProxyOptions(testProxy);
    }
    SSLContext sslContext = null;
    if (withCustomSSLContext) {
        sslContext = new IotHubSSLContext().getSSLContext();
    }
    ServiceClientOptions serviceClientOptions = ServiceClientOptions.builder().proxyOptions(proxyOptions).sslContext(sslContext).build();
    ServiceClient serviceClient;
    if (withAzureSasCredential) {
        serviceClient = buildServiceClientWithAzureSasCredential(testInstance.protocol, serviceClientOptions);
    } else {
        serviceClient = new ServiceClient(iotHubConnectionString, testInstance.protocol, serviceClientOptions);
    }
    serviceClient.open();
    Message message;
    if (withPayload) {
        if (withLargestPayload) {
            message = new Message(LARGEST_PAYLOAD);
        } else {
            message = new Message(SMALL_PAYLOAD);
        }
    } else {
        message = new Message();
    }
    serviceClient.send(device.getDeviceId(), message);
    Device deviceGetAfter = registryManager.getDevice(device.getDeviceId());
    serviceClient.close();
    Tools.disposeTestIdentity(testDeviceIdentity, iotHubConnectionString);
    // Assert
    assertEquals(buildExceptionMessage("", hostName), deviceGetBefore.getDeviceId(), deviceGetAfter.getDeviceId());
    assertEquals(buildExceptionMessage("", hostName), 0, deviceGetBefore.getCloudToDeviceMessageCount());
    assertEquals(buildExceptionMessage("", hostName), 1, deviceGetAfter.getCloudToDeviceMessageCount());
    registryManager.close();
}
Also used : IotHubSSLContext(com.microsoft.azure.sdk.iot.deps.auth.IotHubSSLContext) Proxy(java.net.Proxy) ProxyOptions(com.microsoft.azure.sdk.iot.service.ProxyOptions) Message(com.microsoft.azure.sdk.iot.service.Message) CorrelationDetailsLoggingAssert.buildExceptionMessage(tests.integration.com.microsoft.azure.sdk.iot.helpers.CorrelationDetailsLoggingAssert.buildExceptionMessage) Device(com.microsoft.azure.sdk.iot.service.Device) InetSocketAddress(java.net.InetSocketAddress) ServiceClient(com.microsoft.azure.sdk.iot.service.ServiceClient) RegistryManager(com.microsoft.azure.sdk.iot.service.RegistryManager) SSLContext(javax.net.ssl.SSLContext) IotHubSSLContext(com.microsoft.azure.sdk.iot.deps.auth.IotHubSSLContext) ServiceClientOptions(com.microsoft.azure.sdk.iot.service.ServiceClientOptions) TestDeviceIdentity(tests.integration.com.microsoft.azure.sdk.iot.helpers.TestDeviceIdentity)

Example 4 with IotHubSSLContext

use of com.microsoft.azure.sdk.iot.deps.auth.IotHubSSLContext in project azure-iot-sdk-java by Azure.

the class IotHubSSLContextTest method constructorWithDefaultCertAndPublicCertAndPrivateKey.

// Tests_SRS_IOTHUBSSLCONTEXT_34_041: [If the provided cert is not a path, this function shall set the default cert to the provided cert.]
// Tests_SRS_IOTHUBSSLCONTEXT_34_042: [This constructor shall generate a temporary password to protect the created keystore holding the private key.]
// Tests_SRS_IOTHUBSSLCONTEXT_34_043: [The constructor shall create default SSL context for TLSv1.2.]
// Tests_SRS_IOTHUBSSLCONTEXT_34_044: [The constructor shall create a keystore containing the public key certificate and the private key.]
// Tests_SRS_IOTHUBSSLCONTEXT_34_045: [The constructor shall initialize a default trust manager factory that accepts communications from Iot Hub.]
// Tests_SRS_IOTHUBSSLCONTEXT_34_046: [The constructor shall initialize SSL context with its initialized keystore, its initialized TrustManagerFactory and a new secure random.]
@Test
public void constructorWithDefaultCertAndPublicCertAndPrivateKey() throws NoSuchAlgorithmException, KeyStoreException, KeyManagementException, IOException, CertificateException, UnrecoverableKeyException {
    // arrange
    final String publicKeyCert = "someCert";
    final String privateKey = "someKey";
    final String iotHubTrustedCert = "some trusted cert";
    final Collection<X509Certificate> testCertChain = new ArrayList<>();
    testCertChain.add(mockedX509Certificate);
    new MockUp<IotHubSSLContext>() {

        @Mock
        Key parsePrivateKey(String privateKeyString) throws CertificateException {
            return mockedPrivateKey;
        }

        @Mock
        Collection<X509Certificate> parsePublicKeyCertificate(String publicKeyCertificateString) throws CertificateException {
            return testCertChain;
        }
    };
    new Expectations() {

        {
            new SecureRandom();
            result = mockedSecureRandom;
            mockedSecureRandom.nextInt(anyInt);
            result = 'a';
            Deencapsulation.newInstance(IotHubCertificateManager.class);
            result = mockedCertificateManager;
            Deencapsulation.invoke(IotHubSSLContext.class, "parsePrivateKey", privateKey);
            returns(mockedPrivateKey);
            Deencapsulation.invoke(IotHubSSLContext.class, "parsePublicKeyCertificate", publicKeyCert);
            returns(testCertChain);
            Deencapsulation.newInstance(IotHubCertificateManager.class);
            result = mockedCertificateManager;
            mockKeyManagerFactory.getKeyManagers();
            result = mockKeyManagers;
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            result = mockedTrustManagerFactory;
            mockedTrustManagerFactory.getTrustManagers();
            result = mockedTrustManager;
        }
    };
    final IotHubSSLContext iotHubSSLContext = Deencapsulation.newInstance(IotHubSSLContext.class, new Class[] { String.class, String.class, String.class, boolean.class }, publicKeyCert, privateKey, iotHubTrustedCert, false);
}
Also used : IotHubSSLContext(com.microsoft.azure.sdk.iot.deps.auth.IotHubSSLContext) ArrayList(java.util.ArrayList) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.Test)

Example 5 with IotHubSSLContext

use of com.microsoft.azure.sdk.iot.deps.auth.IotHubSSLContext in project azure-iot-sdk-java by Azure.

the class IotHubSSLContextTest method constructorWithDefaultCertPathAndPublicCertAndPrivateKey.

// Tests_SRS_IOTHUBSSLCONTEXT_34_040: [If the provided cert is a path, this function shall set the path of the default cert to the provided cert path.]
@Test
public void constructorWithDefaultCertPathAndPublicCertAndPrivateKey() throws IOException, KeyStoreException, NoSuchAlgorithmException, KeyManagementException, CertificateException {
    // arrange
    final String publicKeyCert = "someCert";
    final String privateKey = "someKey";
    final String iotHubTrustedCertPath = "some trusted cert path";
    final Collection<X509Certificate> testCertChain = new ArrayList<>();
    testCertChain.add(mockedX509Certificate);
    new MockUp<IotHubSSLContext>() {

        @Mock
        Key parsePrivateKey(String privateKeyString) throws CertificateException {
            return mockedPrivateKey;
        }

        @Mock
        Collection<X509Certificate> parsePublicKeyCertificate(String publicKeyCertificateString) throws CertificateException {
            return testCertChain;
        }
    };
    new Expectations() {

        {
            new SecureRandom();
            result = mockedSecureRandom;
            mockedSecureRandom.nextInt(anyInt);
            result = 'a';
            Deencapsulation.newInstance(IotHubCertificateManager.class);
            result = mockedCertificateManager;
            mockKeyManagerFactory.getKeyManagers();
            result = mockKeyManagers;
            TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
            result = mockedTrustManagerFactory;
            mockedTrustManagerFactory.getTrustManagers();
            result = mockedTrustManager;
        }
    };
    final IotHubSSLContext iotHubSSLContext = Deencapsulation.newInstance(IotHubSSLContext.class, new Class[] { String.class, String.class, String.class, boolean.class }, publicKeyCert, privateKey, iotHubTrustedCertPath, true);
}
Also used : IotHubSSLContext(com.microsoft.azure.sdk.iot.deps.auth.IotHubSSLContext) ArrayList(java.util.ArrayList) X509Certificate(java.security.cert.X509Certificate) Test(org.junit.Test)

Aggregations

IotHubSSLContext (com.microsoft.azure.sdk.iot.deps.auth.IotHubSSLContext)18 Test (org.junit.Test)14 SSLContext (javax.net.ssl.SSLContext)7 IotHubAuthenticationProvider (com.microsoft.azure.sdk.iot.device.auth.IotHubAuthenticationProvider)3 X509Certificate (java.security.cert.X509Certificate)3 ArrayList (java.util.ArrayList)3 Device (com.microsoft.azure.sdk.iot.service.Device)2 IOException (java.io.IOException)2 WebSocketImpl (com.microsoft.azure.proton.transport.ws.impl.WebSocketImpl)1 DeviceClient (com.microsoft.azure.sdk.iot.device.DeviceClient)1 IotHubX509HardwareAuthenticationProvider (com.microsoft.azure.sdk.iot.device.auth.IotHubX509HardwareAuthenticationProvider)1 TransportException (com.microsoft.azure.sdk.iot.device.exceptions.TransportException)1 IotHubConnectionString (com.microsoft.azure.sdk.iot.service.IotHubConnectionString)1 IotHubServiceClientProtocol (com.microsoft.azure.sdk.iot.service.IotHubServiceClientProtocol)1 Message (com.microsoft.azure.sdk.iot.service.Message)1 ProxyOptions (com.microsoft.azure.sdk.iot.service.ProxyOptions)1 RegistryManager (com.microsoft.azure.sdk.iot.service.RegistryManager)1 ServiceClient (com.microsoft.azure.sdk.iot.service.ServiceClient)1 ServiceClientOptions (com.microsoft.azure.sdk.iot.service.ServiceClientOptions)1 DeviceTwinDevice (com.microsoft.azure.sdk.iot.service.devicetwin.DeviceTwinDevice)1