Search in sources :

Example 6 with TlsContext

use of software.amazon.awssdk.crt.io.TlsContext in project aws-crt-java by awslabs.

the class TlsContextOptionsTest method testMtlsPkcs11.

@Test
public void testMtlsPkcs11() {
    Assume.assumeTrue(System.getProperty("NETWORK_TESTS_DISABLED") == null);
    Pkcs11LibTest.assumeEnvironmentSetUpForPkcs11Tests();
    try (Pkcs11Lib pkcs11Lib = new Pkcs11Lib(Pkcs11LibTest.TEST_PKCS11_LIB);
        TlsContextPkcs11Options pkcs11Options = new TlsContextPkcs11Options(pkcs11Lib).withUserPin(Pkcs11LibTest.TEST_PKCS11_PIN).withTokenLabel(Pkcs11LibTest.TEST_PKCS11_TOKEN_LABEL).withPrivateKeyObjectLabel(Pkcs11LibTest.TEST_PKCS11_PKEY_LABEL).withCertificateFilePath(Pkcs11LibTest.TEST_PKCS11_CERT_FILE);
        TlsContextOptions tlsOptions = TlsContextOptions.createWithMtlsPkcs11(pkcs11Options);
        TlsContext tls = new TlsContext(tlsOptions)) {
    } catch (CrtRuntimeException ex) {
        // This is expected to fail on platforms where we don't yet support mTLS with PKCS#11
        assertEquals("AWS_ERROR_UNIMPLEMENTED", ex.errorName);
    }
}
Also used : TlsContextOptions(software.amazon.awssdk.crt.io.TlsContextOptions) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) Pkcs11Lib(software.amazon.awssdk.crt.io.Pkcs11Lib) TlsContext(software.amazon.awssdk.crt.io.TlsContext) TlsContextPkcs11Options(software.amazon.awssdk.crt.io.TlsContextPkcs11Options) Test(org.junit.Test)

Example 7 with TlsContext

use of software.amazon.awssdk.crt.io.TlsContext in project aws-crt-java by awslabs.

the class MqttClientConnection method connect.

/**
 * Connect to the service endpoint and start a session
 *
 * @return Future result is true if resuming a session, false if clean session
 * @throws MqttException If the port is out of range
 */
public CompletableFuture<Boolean> connect() throws MqttException {
    TlsContext tls = config.getMqttClient().getTlsContext();
    // Just clamp the pingTimeout, no point in throwing
    short pingTimeout = (short) Math.max(0, Math.min(config.getPingTimeoutMs(), Short.MAX_VALUE));
    short port = (short) config.getPort();
    if (port > Short.MAX_VALUE || port <= 0) {
        throw new MqttException("Port must be betweeen 0 and " + Short.MAX_VALUE);
    }
    CompletableFuture<Boolean> future = new CompletableFuture<>();
    connectAck = AsyncCallback.wrapFuture(future, null);
    SocketOptions socketOptions = config.getSocketOptions();
    try {
        mqttClientConnectionConnect(getNativeHandle(), config.getEndpoint(), port, socketOptions != null ? socketOptions.getNativeHandle() : 0, tls != null ? tls.getNativeHandle() : 0, config.getClientId(), config.getCleanSession(), config.getKeepAliveSecs(), pingTimeout, config.getProtocolOperationTimeoutMs());
    } catch (CrtRuntimeException ex) {
        future.completeExceptionally(ex);
    }
    return future;
}
Also used : CompletableFuture(java.util.concurrent.CompletableFuture) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) TlsContext(software.amazon.awssdk.crt.io.TlsContext)

Example 8 with TlsContext

use of software.amazon.awssdk.crt.io.TlsContext in project aws-iot-device-sdk-java-v2 by aws.

the class RawConnect method main.

public static void main(String[] args) {
    cmdUtils = new CommandLineUtils();
    cmdUtils.registerProgramName("RawConnect");
    cmdUtils.addCommonMQTTCommands();
    cmdUtils.registerCommand("key", "<path>", "Path to your key in PEM format.");
    cmdUtils.registerCommand("cert", "<path>", "Path to your client certificate in PEM format.");
    cmdUtils.addCommonProxyCommands();
    cmdUtils.registerCommand("client_id", "<int>", "Client id to use (optional, default='test-*').");
    cmdUtils.registerCommand("username", "<str>", "Username to use as part of the connection/authentication process.");
    cmdUtils.registerCommand("password", "<str>", "Password to use as part of the connection/authentication process.");
    cmdUtils.registerCommand("protocol", "<str>", "ALPN protocol to use (optional, default='x-amzn-mqtt-ca').");
    cmdUtils.registerCommand("auth_params", "<comma delimited list>", "Comma delimited list of auth parameters. For websockets these will be set as headers. " + "For raw mqtt these will be appended to user_name. (optional)");
    cmdUtils.sendArguments(args);
    String endpoint = cmdUtils.getCommandRequired("endpoint", "");
    String clientId = cmdUtils.getCommandOrDefault("client_id", "test-" + UUID.randomUUID().toString());
    String caPath = cmdUtils.getCommandOrDefault("ca_file", "");
    String certPath = cmdUtils.getCommandRequired("cert", "");
    String keyPath = cmdUtils.getCommandRequired("key", "");
    String proxyHost = cmdUtils.getCommandOrDefault("proxy_host", "");
    int proxyPort = Integer.parseInt(cmdUtils.getCommandOrDefault("proxy_port", "8080"));
    String userName = cmdUtils.getCommandRequired("username", "");
    String password = cmdUtils.getCommandRequired("password", "");
    String protocolName = cmdUtils.getCommandOrDefault("protocol", "x-amzn-mqtt-ca");
    List<String> authParams = null;
    if (cmdUtils.hasCommand("auth_params")) {
        authParams = Arrays.asList(cmdUtils.getCommand("auth_params").split("\\s*,\\s*"));
    }
    MqttClientConnectionEvents callbacks = new MqttClientConnectionEvents() {

        @Override
        public void onConnectionInterrupted(int errorCode) {
            if (errorCode != 0) {
                System.out.println("Connection interrupted: " + errorCode + ": " + CRT.awsErrorString(errorCode));
            }
        }

        @Override
        public void onConnectionResumed(boolean sessionPresent) {
            System.out.println("Connection resumed: " + (sessionPresent ? "existing session" : "clean session"));
        }
    };
    if (authParams != null && authParams.size() > 0) {
        if (userName.length() > 0) {
            StringBuilder usernameBuilder = new StringBuilder();
            usernameBuilder.append(userName);
            usernameBuilder.append("?");
            for (int i = 0; i < authParams.size(); ++i) {
                usernameBuilder.append(authParams.get(i));
                if (i + 1 < authParams.size()) {
                    usernameBuilder.append("&");
                }
            }
            userName = usernameBuilder.toString();
        }
    }
    try (TlsContextOptions tlsContextOptions = TlsContextOptions.createWithMtlsFromPath(certPath, keyPath)) {
        if (caPath != null) {
            tlsContextOptions.overrideDefaultTrustStoreFromPath(null, caPath);
        }
        int port = 8883;
        if (TlsContextOptions.isAlpnSupported()) {
            port = 443;
            tlsContextOptions.withAlpnList(protocolName);
        }
        try (TlsContext tlsContext = new TlsContext(tlsContextOptions);
            MqttClient client = new MqttClient(tlsContext);
            MqttConnectionConfig config = new MqttConnectionConfig()) {
            config.setMqttClient(client);
            config.setClientId(clientId);
            config.setConnectionCallbacks(callbacks);
            config.setCleanSession(true);
            config.setEndpoint(endpoint);
            config.setPort(port);
            if (userName != null && userName.length() > 0) {
                config.setLogin(userName, password);
            }
            try (MqttClientConnection connection = new MqttClientConnection(config)) {
                // Connect and disconnect using the connection we created
                // (see sampleConnectAndDisconnect for implementation)
                cmdUtils.sampleConnectAndDisconnect(connection);
            }
        }
    } catch (CrtRuntimeException | InterruptedException | ExecutionException ex) {
        System.out.println("Exception encountered: " + ex.toString());
    }
    CrtResource.waitForNoResources();
    System.out.println("Complete!");
}
Also used : CommandLineUtils(utils.commandlineutils.CommandLineUtils) TlsContextOptions(software.amazon.awssdk.crt.io.TlsContextOptions) CrtRuntimeException(software.amazon.awssdk.crt.CrtRuntimeException) TlsContext(software.amazon.awssdk.crt.io.TlsContext) ExecutionException(java.util.concurrent.ExecutionException)

Example 9 with TlsContext

use of software.amazon.awssdk.crt.io.TlsContext in project aws-crt-java by awslabs.

the class HttpClientConnectionTest method testStaticDefaults.

@Test
public void testStaticDefaults() throws Exception {
    skipIfNetworkUnavailable();
    URI uri = new URI("https://aws-crt-test-stuff.s3.amazonaws.com");
    try (ClientBootstrap bootstrap = new ClientBootstrap(null, null);
        SocketOptions socketOptions = new SocketOptions();
        TlsContextOptions tlsOpts = TlsContextOptions.createDefaultClient();
        TlsContext tlsCtx = new TlsContext(tlsOpts)) {
        HttpClientConnectionManagerOptions options = new HttpClientConnectionManagerOptions();
        options.withClientBootstrap(bootstrap).withSocketOptions(socketOptions).withTlsContext(tlsCtx).withUri(uri);
        try (HttpClientConnectionManager connectionPool = HttpClientConnectionManager.create(options)) {
            try (HttpClientConnection conn = connectionPool.acquireConnection().get(60, TimeUnit.SECONDS)) {
                ;
            }
        }
    }
}
Also used : ClientBootstrap(software.amazon.awssdk.crt.io.ClientBootstrap) HttpClientConnectionManagerOptions(software.amazon.awssdk.crt.http.HttpClientConnectionManagerOptions) HttpClientConnection(software.amazon.awssdk.crt.http.HttpClientConnection) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) TlsContextOptions(software.amazon.awssdk.crt.io.TlsContextOptions) TlsContext(software.amazon.awssdk.crt.io.TlsContext) HttpClientConnectionManager(software.amazon.awssdk.crt.http.HttpClientConnectionManager) URI(java.net.URI) Test(org.junit.Test)

Example 10 with TlsContext

use of software.amazon.awssdk.crt.io.TlsContext in project aws-crt-java by awslabs.

the class HttpClientConnectionTest method testConnectionWithAllCiphers.

private void testConnectionWithAllCiphers(URI uri, boolean expectConnected, String exceptionMsg) throws Exception {
    for (TlsCipherPreference pref : TlsCipherPreference.values()) {
        if (!TlsContextOptions.isCipherPreferenceSupported(pref)) {
            continue;
        }
        HttpConnectionTestResponse resp = null;
        try (TlsContextOptions tlsOpts = TlsContextOptions.createDefaultClient().withCipherPreference(pref)) {
            if (getContext().trustStore != null) {
                tlsOpts.withCertificateAuthority(new String(getContext().trustStore));
            }
            try (EventLoopGroup eventLoopGroup = new EventLoopGroup(1);
                HostResolver resolver = new HostResolver(eventLoopGroup);
                ClientBootstrap bootstrap = new ClientBootstrap(eventLoopGroup, resolver);
                SocketOptions socketOptions = new SocketOptions();
                TlsContext tlsCtx = new TlsContext(tlsOpts)) {
                socketOptions.connectTimeoutMs = 10000;
                resp = testConnection(uri, bootstrap, socketOptions, tlsCtx);
            }
        }
        String assertMsg = uri.toString() + " " + pref;
        // If an unexpected exception occurred, rethrow so we get details in the logs
        if (resp.exceptionThrown && (expectConnected || !resp.exception.getMessage().contains(exceptionMsg))) {
            System.out.println(assertMsg);
            throw resp.exception;
        }
        Assert.assertEquals(assertMsg + " connection success.", expectConnected, resp.actuallyConnected);
        Assert.assertEquals(assertMsg + " exception thrown.", !expectConnected, resp.exceptionThrown);
        resp.shutdownComplete.get();
    }
}
Also used : EventLoopGroup(software.amazon.awssdk.crt.io.EventLoopGroup) ClientBootstrap(software.amazon.awssdk.crt.io.ClientBootstrap) TlsContextOptions(software.amazon.awssdk.crt.io.TlsContextOptions) SocketOptions(software.amazon.awssdk.crt.io.SocketOptions) TlsContext(software.amazon.awssdk.crt.io.TlsContext) TlsCipherPreference(software.amazon.awssdk.crt.io.TlsCipherPreference) HostResolver(software.amazon.awssdk.crt.io.HostResolver)

Aggregations

TlsContext (software.amazon.awssdk.crt.io.TlsContext)12 ClientBootstrap (software.amazon.awssdk.crt.io.ClientBootstrap)7 TlsContextOptions (software.amazon.awssdk.crt.io.TlsContextOptions)7 EventLoopGroup (software.amazon.awssdk.crt.io.EventLoopGroup)6 HostResolver (software.amazon.awssdk.crt.io.HostResolver)6 CrtRuntimeException (software.amazon.awssdk.crt.CrtRuntimeException)5 SocketOptions (software.amazon.awssdk.crt.io.SocketOptions)5 Test (org.junit.Test)4 HttpClientConnectionManagerOptions (software.amazon.awssdk.crt.http.HttpClientConnectionManagerOptions)3 HttpProxyOptions (software.amazon.awssdk.crt.http.HttpProxyOptions)3 ClientTlsContext (software.amazon.awssdk.crt.io.ClientTlsContext)3 IOException (java.io.IOException)1 URI (java.net.URI)1 InvalidPathException (java.nio.file.InvalidPathException)1 CompletableFuture (java.util.concurrent.CompletableFuture)1 ExecutionException (java.util.concurrent.ExecutionException)1 X509CredentialsProvider (software.amazon.awssdk.crt.auth.credentials.X509CredentialsProvider)1 HttpClientConnection (software.amazon.awssdk.crt.http.HttpClientConnection)1 HttpClientConnectionManager (software.amazon.awssdk.crt.http.HttpClientConnectionManager)1 Pkcs11Lib (software.amazon.awssdk.crt.io.Pkcs11Lib)1