Search in sources :

Example 1 with LocalizableValidationException

use of com.vmware.xenon.common.LocalizableValidationException in project photon-model by vmware.

the class AWSEndpointAdapterService method validateCredentials.

private DeferredResult<Void> validateCredentials(AmazonEC2AsyncClient client) {
    AWSDeferredResultAsyncHandler<DescribeAvailabilityZonesRequest, DescribeAvailabilityZonesResult> asyncHandler = new AWSDeferredResultAsyncHandler<>(this, "Validate Credentials");
    client.describeAvailabilityZonesAsync(asyncHandler);
    return asyncHandler.toDeferredResult().handle((describeAvailabilityZonesResult, e) -> {
        if (e instanceof AmazonServiceException) {
            AmazonServiceException ase = (AmazonServiceException) e;
            if (ase.getStatusCode() == STATUS_CODE_UNAUTHORIZED) {
                throw new LocalizableValidationException(e, PHOTON_MODEL_ADAPTER_UNAUTHORIZED_MESSAGE, PHOTON_MODEL_ADAPTER_UNAUTHORIZED_MESSAGE_CODE);
            }
        }
        return null;
    });
}
Also used : LocalizableValidationException(com.vmware.xenon.common.LocalizableValidationException) DescribeAvailabilityZonesRequest(com.amazonaws.services.ec2.model.DescribeAvailabilityZonesRequest) AWSDeferredResultAsyncHandler(com.vmware.photon.controller.model.adapters.awsadapter.util.AWSDeferredResultAsyncHandler) AmazonServiceException(com.amazonaws.AmazonServiceException) DescribeAvailabilityZonesResult(com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult)

Example 2 with LocalizableValidationException

use of com.vmware.xenon.common.LocalizableValidationException in project photon-model by vmware.

the class CertificateUtil method resolveCertificate.

public static X509TrustManagerResolver resolveCertificate(URI uri, Proxy proxy, String proxyUsername, String proxyPassword, long timeoutMillis) {
    logger.entering(logger.getName(), "resolveCertificate");
    X509TrustManagerResolver trustManagerResolver = new X509TrustManagerResolver();
    SSLContext sslContext;
    try {
        sslContext = SSLContext.getInstance("TLS");
        sslContext.init(null, new TrustManager[] { trustManagerResolver }, null);
    } catch (KeyManagementException | NoSuchAlgorithmException e) {
        logger.throwing(logger.getName(), "connect", e);
        throw new LocalizableValidationException(e, "Failed to initialize SSL context.", "security.certificate.context.init.error");
    }
    String hostAddress = uri.getHost();
    int port = uri.getPort() == -1 ? DEFAULT_SECURE_CONNECTION_PORT : uri.getPort();
    String uriScheme = uri.getScheme();
    String host = String.format("%s://%s:%d", uriScheme, hostAddress, port);
    try {
        SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
        if (proxy != null && proxy.type() == Type.HTTP && proxyUsername != null && UriUtils.HTTPS_SCHEME.equalsIgnoreCase(uriScheme)) {
            URL url = uri.toURL();
            handleCertForHttpsThroughHttpProxyWithAuth(url, proxy, proxyUsername, proxyPassword, timeoutMillis, sslSocketFactory);
        } else {
            SSLSocket sslSocket;
            if (proxy != null) {
                if (proxyUsername != null) {
                    throw new LocalizableValidationException("Proxy authentication supported " + "for HTTPS URI through HTTP Proxy only." + " URI: " + uri.toASCIIString() + ", Proxy: " + proxy.toString(), "security.certificate.proxy.authentication.not.supported.error", uri.toASCIIString(), proxy.toString());
                }
                Socket tunnel = new Socket(proxy);
                tunnel.connect(new InetSocketAddress(hostAddress, port), (int) timeoutMillis);
                sslSocket = (SSLSocket) sslSocketFactory.createSocket(tunnel, hostAddress, port, true);
            } else {
                sslSocket = (SSLSocket) sslSocketFactory.createSocket();
                if (SSL_CONNECT_USE_SNI) {
                    SNIHostName serverName = new SNIHostName(hostAddress);
                    List<SNIServerName> serverNames = new ArrayList<>(1);
                    serverNames.add(serverName);
                    SSLParameters params = sslSocket.getSSLParameters();
                    params.setServerNames(serverNames);
                    sslSocket.setSSLParameters(params);
                }
                sslSocket.connect(new InetSocketAddress(hostAddress, port), (int) timeoutMillis);
            }
            SSLSession session = sslSocket.getSession();
            session.invalidate();
        }
    } catch (IOException e) {
        try {
            if (trustManagerResolver.isCertsTrusted() || trustManagerResolver.getCertificateChain().length == 0) {
                Utils.logWarning("Exception while resolving certificate for host: [%s]. Error: %s ", host, e.getMessage());
            } else {
                logger.throwing(logger.getName(), "connect", e);
                throw new IllegalArgumentException(e.getMessage(), e);
            }
        } catch (IllegalStateException ise) {
            throw new LocalizableValidationException(e, String.format("Cannot connect to host: [%s]. Error: %s", host, e.getMessage()), "security.certificate.connection.error", host, e.getMessage());
        }
    }
    if (trustManagerResolver.getCertificateChain().length == 0) {
        LocalizableValidationException e = new LocalizableValidationException("Check ssl certificate failed for server: " + host, "security.certificate.check.error", host);
        logger.throwing(logger.getName(), "connect", e);
        throw e;
    }
    logger.exiting(logger.getName(), "resolveCertificate");
    return trustManagerResolver;
}
Also used : LocalizableValidationException(com.vmware.xenon.common.LocalizableValidationException) InetSocketAddress(java.net.InetSocketAddress) SSLSocket(javax.net.ssl.SSLSocket) ArrayList(java.util.ArrayList) SSLSession(javax.net.ssl.SSLSession) SSLContext(javax.net.ssl.SSLContext) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DEROctetString(org.bouncycastle.asn1.DEROctetString) IOException(java.io.IOException) CertIOException(org.bouncycastle.cert.CertIOException) KeyManagementException(java.security.KeyManagementException) URL(java.net.URL) SNIServerName(javax.net.ssl.SNIServerName) SSLParameters(javax.net.ssl.SSLParameters) SNIHostName(javax.net.ssl.SNIHostName) X509TrustManagerResolver(com.vmware.photon.controller.model.security.ssl.X509TrustManagerResolver) SSLSocketFactory(javax.net.ssl.SSLSocketFactory) SSLSocket(javax.net.ssl.SSLSocket) Socket(java.net.Socket)

Example 3 with LocalizableValidationException

use of com.vmware.xenon.common.LocalizableValidationException in project photon-model by vmware.

the class EncryptorService method decrypt.

/**
 * Decrypts the provided byte array.
 * @param input
 *         Byte array (in base 64) to be decrypted
 * @return The decrypted version of the input byte array.
 */
public byte[] decrypt(final byte[] input) {
    if (input == null || input.length == 0) {
        return input;
    }
    try {
        BufferedBlockCipher cipher = getCipher(false);
        byte[] bytes = Base64.getDecoder().decode(input);
        byte[] output = new byte[cipher.getOutputSize(bytes.length)];
        int length = cipher.processBytes(bytes, 0, bytes.length, output, 0);
        length += cipher.doFinal(output, length);
        return Arrays.copyOfRange(output, 0, length);
    } catch (Exception e) {
        throw new LocalizableValidationException(e, "Decryption error!", "common.dercyption.error");
    }
}
Also used : LocalizableValidationException(com.vmware.xenon.common.LocalizableValidationException) BufferedBlockCipher(org.bouncycastle.crypto.BufferedBlockCipher) PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) IOException(java.io.IOException) LocalizableValidationException(com.vmware.xenon.common.LocalizableValidationException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 4 with LocalizableValidationException

use of com.vmware.xenon.common.LocalizableValidationException in project photon-model by vmware.

the class EncryptorService method encrypt.

/**
 * Encrypts the provided byte array.
 * @param input
 *         Byte array to be encrypted
 * @return The encrypted version of the input byte array (in base 64).
 */
public byte[] encrypt(final byte[] input) {
    if (input == null || input.length == 0) {
        return input;
    }
    try {
        BufferedBlockCipher cipher = getCipher(true);
        byte[] output = new byte[cipher.getOutputSize(input.length)];
        int length = cipher.processBytes(input, 0, input.length, output, 0);
        length += cipher.doFinal(output, length);
        return Base64.getEncoder().encode(Arrays.copyOfRange(output, 0, length));
    } catch (Exception e) {
        throw new LocalizableValidationException(e, "Encryption error!", "common.ecryption.error");
    }
}
Also used : LocalizableValidationException(com.vmware.xenon.common.LocalizableValidationException) BufferedBlockCipher(org.bouncycastle.crypto.BufferedBlockCipher) PaddedBufferedBlockCipher(org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher) IOException(java.io.IOException) LocalizableValidationException(com.vmware.xenon.common.LocalizableValidationException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 5 with LocalizableValidationException

use of com.vmware.xenon.common.LocalizableValidationException in project photon-model by vmware.

the class EncryptorServiceTest method testBadFile.

@Test
public void testBadFile() throws IOException {
    // it's an empty file!
    File keyFile = File.createTempFile("encription.key", null);
    EncryptorService serviceBad = new EncryptorService(keyFile);
    String plainText = generatePlainText();
    try {
        serviceBad.encrypt(plainText);
        fail("It shouldn't get here");
    } catch (LocalizableValidationException e) {
        assertTrue(e.getMessage().equalsIgnoreCase("Encryption error!"));
    }
    EncryptorService service = new EncryptorService(KEY_FILE);
    String encryptedString = service.encrypt(plainText);
    try {
        serviceBad.decrypt(encryptedString);
        fail("It shouldn't get here");
    } catch (LocalizableValidationException e) {
        assertTrue(e.getMessage().equalsIgnoreCase("Decryption error!"));
    }
}
Also used : LocalizableValidationException(com.vmware.xenon.common.LocalizableValidationException) File(java.io.File) Test(org.junit.Test)

Aggregations

LocalizableValidationException (com.vmware.xenon.common.LocalizableValidationException)11 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)5 IOException (java.io.IOException)3 File (java.io.File)2 BufferedBlockCipher (org.bouncycastle.crypto.BufferedBlockCipher)2 PaddedBufferedBlockCipher (org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher)2 Test (org.junit.Test)2 AmazonServiceException (com.amazonaws.AmazonServiceException)1 DescribeAvailabilityZonesRequest (com.amazonaws.services.ec2.model.DescribeAvailabilityZonesRequest)1 DescribeAvailabilityZonesResult (com.amazonaws.services.ec2.model.DescribeAvailabilityZonesResult)1 SubscriptionState (com.microsoft.azure.management.resources.SubscriptionState)1 SubscriptionClientImpl (com.microsoft.azure.management.resources.implementation.SubscriptionClientImpl)1 SubscriptionInner (com.microsoft.azure.management.resources.implementation.SubscriptionInner)1 EndpointConfigRequest (com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest)1 PRIVATE_KEYID_KEY (com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest.PRIVATE_KEYID_KEY)1 PRIVATE_KEY_KEY (com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest.PRIVATE_KEY_KEY)1 REGION_KEY (com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest.REGION_KEY)1 RequestType (com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest.RequestType)1 SUPPORT_DATASTORES (com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest.SUPPORT_DATASTORES)1 SUPPORT_PUBLIC_IMAGES (com.vmware.photon.controller.model.adapterapi.EndpointConfigRequest.SUPPORT_PUBLIC_IMAGES)1