Java Code Examples for org.apache.http.conn.ssl.SSLSocketFactory#ALLOW_ALL_HOSTNAME_VERIFIER

The following examples show how to use org.apache.http.conn.ssl.SSLSocketFactory#ALLOW_ALL_HOSTNAME_VERIFIER . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BrooklynWebServerTest.java    From brooklyn-server with Apache License 2.0 6 votes vote down vote up
private void verifyHttpsFromConfig(BrooklynProperties brooklynProperties) throws Exception {
    webServer = new BrooklynWebServer(MutableMap.of(), newManagementContext(brooklynProperties));
    webServer.skipSecurity();
    webServer.start();
    
    try {
        KeyStore keyStore = load("client.ks", "password");
        KeyStore trustStore = load("client.ts", "password");
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, "password", trustStore, (SecureRandom)null, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpToolResponse response = HttpTool.execAndConsume(
                HttpTool.httpClientBuilder()
                        .port(webServer.getActualPort())
                        .https(true)
                        .socketFactory(socketFactory)
                        .build(),
                new HttpGet(webServer.getRootUrl()));
        assertEquals(response.getResponseCode(), 200);
    } finally {
        webServer.stop();
    }
}
 
Example 2
Source File: SocketFactoryHttpClientFactory.java    From olingo-odata4 with Apache License 2.0 6 votes vote down vote up
@Override
public DefaultHttpClient create(final HttpMethod method, final URI uri) {
  final TrustStrategy acceptTrustStrategy = new TrustStrategy() {
    @Override
    public boolean isTrusted(final X509Certificate[] certificate, final String authType) {
      return true;
    }
  };

  final SchemeRegistry registry = new SchemeRegistry();
  try {
    final SSLSocketFactory ssf =
            new SSLSocketFactory(acceptTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    registry.register(new Scheme(uri.getScheme(), uri.getPort(), ssf));
  } catch (Exception e) {
    throw new ODataRuntimeException(e);
  }

  final DefaultHttpClient httpClient = new DefaultHttpClient(new BasicClientConnectionManager(registry));
  httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);

  return httpClient;
}
 
Example 3
Source File: RestClient.java    From s2g-zuul with MIT License 5 votes vote down vote up
public void resetSSLSocketFactory(AbstractSslContextFactory abstractContextFactory){

    	try {

    		KeyStoreAwareSocketFactory awareSocketFactory = isHostnameValidationRequired ? new KeyStoreAwareSocketFactory(abstractContextFactory) :
                new KeyStoreAwareSocketFactory(abstractContextFactory, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    		httpClient4.getConnectionManager().getSchemeRegistry().register(new Scheme(
                    "https",443, awareSocketFactory));

    	} catch (Exception e) {
    		throw new IllegalArgumentException("Unable to configure custom secure socket factory", e);
    	}
    }
 
Example 4
Source File: BrooklynWebServerTest.java    From brooklyn-server with Apache License 2.0 5 votes vote down vote up
@Test(dataProvider="keystorePaths")
public void verifyHttps(String keystoreUrl) throws Exception {
    Map<String,?> flags = ImmutableMap.<String,Object>builder()
            .put("httpsEnabled", true)
            .put("keystoreUrl", keystoreUrl)
            .put("keystorePassword", "password")
            .build();
    webServer = new BrooklynWebServer(flags, newManagementContext(brooklynProperties));
    webServer.skipSecurity().start();
    
    try {
        KeyStore keyStore = load("client.ks", "password");
        KeyStore trustStore = load("client.ts", "password");
        SSLSocketFactory socketFactory = new SSLSocketFactory(SSLSocketFactory.TLS, keyStore, "password", trustStore, (SecureRandom)null, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

        HttpToolResponse response = HttpTool.execAndConsume(
                HttpTool.httpClientBuilder()
                        .port(webServer.getActualPort())
                        .https(true)
                        .socketFactory(socketFactory)
                        .build(),
                new HttpGet(webServer.getRootUrl()));
        assertEquals(response.getResponseCode(), 200);
    } finally {
        webServer.stop();
    }
}
 
Example 5
Source File: RestClient.java    From ribbon with Apache License 2.0 5 votes vote down vote up
public void resetSSLSocketFactory(AbstractSslContextFactory abstractContextFactory){

    	try {

    		KeyStoreAwareSocketFactory awareSocketFactory = isHostnameValidationRequired ? new KeyStoreAwareSocketFactory(abstractContextFactory) :
                new KeyStoreAwareSocketFactory(abstractContextFactory, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    		httpClient4.getConnectionManager().getSchemeRegistry().register(new Scheme(
                    "https",443, awareSocketFactory));

    	} catch (Exception e) {
    		throw new IllegalArgumentException("Unable to configure custom secure socket factory", e);
    	}
    }
 
Example 6
Source File: AcceptAllSocketFactory.java    From ribbon with Apache License 2.0 5 votes vote down vote up
public AcceptAllSocketFactory() throws KeyManagementException, UnrecoverableKeyException, NoSuchAlgorithmException, KeyStoreException {
    super(new TrustStrategy() {

        @Override
        public boolean isTrusted(final X509Certificate[] chain, String authType) throws CertificateException {
            return true;
        }

    }, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
}
 
Example 7
Source File: HookSSLImpl.java    From Introspy-Android with GNU General Public License v2.0 5 votes vote down vote up
public void execute(Object... args) {
	
	// this only display data when there is a potential issue
	if ((org.apache.http.conn.ssl.X509HostnameVerifier)args[0] == 
			SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) {
		_logBasicInfo();
		_logParameter("SSLSocketFactory", "ALLOW_ALL_HOSTNAME_VERIFIER");
		_logFlush_W("HostNameVerifier set to accept ANY hostname");
	}
}
 
Example 8
Source File: MTSLClientAuthenticationTest.java    From oxAuth with MIT License 4 votes vote down vote up
public static void main(String[] args) throws Exception {

        File jdkJks = new File("u:\\tmp\\ce-ob\\clientkeystore");
        if (!jdkJks.exists()) {
            throw new RuntimeException("Failed to find jks trust store");
        }

        File certificate = new File("u:\\tmp\\ce-ob\\fullchain.p12");
        if (!certificate.exists()) {
            throw new RuntimeException("Failed to find certificate");
        }

        HttpClient httpclient = new DefaultHttpClient();
// truststore
        KeyStore ts = KeyStore.getInstance("JKS", "SUN");
        ts.load(new FileInputStream(jdkJks), "secret".toCharArray());
// if you remove me, you've got 'javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated' on missing truststore
        if(0 == ts.size()) throw new IOException("Error loading truststore");
// tmf
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
        tmf.init(ts);
// keystore
        KeyStore ks = KeyStore.getInstance("PKCS12", "SunJSSE");
        ks.load(new FileInputStream(certificate), "".toCharArray());
// if you remove me, you've got 'javax.net.ssl.SSLPeerUnverifiedException: peer not authenticated' on missing keystore
        if(0 == ks.size()) throw new IOException("Error loading keystore");
// kmf
        KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        kmf.init(ks, "".toCharArray());
// SSL
        SSLContext ctx = SSLContext.getInstance("TLS");
        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
// socket
        SSLSocketFactory socketFactory = new SSLSocketFactory(ctx, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        Scheme sch = new Scheme("https", 443, socketFactory);
        httpclient.getConnectionManager().getSchemeRegistry().register(sch);

        String clientId = "@!D445.22BF.5EF1.0D87!0001!03F2.297D!0008!F599.E2C7";
        String clientSecret = "testClientSecret";

        TokenRequest tokenRequest = new TokenRequest(GrantType.AUTHORIZATION_CODE);
        tokenRequest.setCode("testCode");
        tokenRequest.setRedirectUri("https://ce-ob.gluu.org/cas/login");
        tokenRequest.setAuthUsername(clientId);
        tokenRequest.setAuthPassword(clientSecret);
        tokenRequest.setAuthenticationMethod(AuthenticationMethod.TLS_CLIENT_AUTH);

        TokenClient tokenClient = new TokenClient("https://ce-ob.gluu.org/oxauth/restv1/token");
        tokenClient.setExecutor(new ApacheHttpClient4Executor(httpclient));
        tokenClient.setRequest(tokenRequest);
        TokenResponse tokenResponse = tokenClient.exec();

        System.out.println(tokenResponse);
        showClient(tokenClient);
    }
 
Example 9
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void login() throws EndpointNotFoundException, UnauthorizedException, UnexpectedStatusCodeException,
        IOException, NoSuchAlgorithmException, KeyStoreException, KeyManagementException, UnrecoverableKeyException {

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);

    try {
        HttpPost request = new HttpPost(authUrl);

        String body = String
                .format("{\"auth\": {\"passwordCredentials\": {\"username\": \"%s\", \"password\": \"%s\"}, \"tenantName\":\"%s\"}}",
                user, password, tenant);
        StringEntity entity = new StringEntity(body);
        entity.setContentType("application/json");
        request.setEntity(entity);
        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("404 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

        String responseBody = swiftResponse.getResponseBodyAsString();

        Gson gson = new Gson();
        LoginResponseObject loginResponse = gson.fromJson(responseBody, LoginResponseObject.class);

        this.authToken = loginResponse.getAccess().getToken().getId();

        Boolean endpointFound = false;

        for (ServiceObject service : loginResponse.getAccess().getServiceCatalog()) {

            if (service.getType().equals("object-store")) {
                this.storageUrl = service.getEndpoints().get(0).getPublicURL();
                endpointFound = true;
                break;
            }
        }

        // get the token issue swift date
        DateTimeZone.setDefault(DateTimeZone.UTC);
        DateTimeFormatter dateStringFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSSSS");
        DateTime issuedAt = dateStringFormat.parseDateTime(loginResponse.getAccess().getToken().getIssuedAt());

        // get the token expiration swift date
        dateStringFormat = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ssZ");
        DateTime expiresAt = dateStringFormat.parseDateTime(loginResponse.getAccess().getToken().getExpires());

        // calculate the period between these two dates and add it to our
        // current time because datetime can differ from Swift and this
        // device
        Period period = new Period(issuedAt, expiresAt);
        expirationDate = DateTime.now().plus(period);

        if (!endpointFound) {
            throw new EndpointNotFoundException();
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 10
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void createNewWorkspace(Workspace workspace) throws Exception {

    if (!isTokenActive()) {
        login();
    }



    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);

    String url = this.storageUrl + "/" + workspace.getSwiftContainer();

    try {

        HttpPut request = new HttpPut(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("401 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 11
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void removeUserToWorkspace(User owner, User user, Workspace workspace) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    String permissions = getWorkspacePermissions(owner, workspace);

    String tenantUser = Config.getSwiftTenant() + ":" + user.getSwiftUser();

    if (permissions.contains("," + tenantUser)) {
        permissions.replace("," + tenantUser, "");
    } else if (permissions.contains(tenantUser)) {
        permissions.replace(tenantUser, "");
    } else {
        return;
    }

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);
    String url = this.storageUrl + "/" + workspace.getSwiftContainer();

    try {

        HttpPut request = new HttpPut(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);
        request.setHeader(SwiftResponse.X_CONTAINER_READ, permissions);
        request.setHeader(SwiftResponse.X_CONTAINER_WRITE, permissions);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("404 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 12
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void grantUserToWorkspace(User owner, User user, Workspace workspace) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    String permissions = getWorkspacePermissions(owner, workspace);

    String tenantUser = Config.getSwiftTenant() + ":" + user.getSwiftUser();

    if (permissions.contains(tenantUser)) {
        return;
    }

    permissions += "," + tenantUser;

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);
    String url = this.storageUrl + "/" + workspace.getSwiftContainer();

    try {

        HttpPut request = new HttpPut(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);
        request.setHeader(SwiftResponse.X_CONTAINER_READ, permissions);
        request.setHeader(SwiftResponse.X_CONTAINER_WRITE, permissions);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("404 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 13
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void copyChunk(Workspace sourceWorkspace, Workspace destinationWorkspace, String chunkName) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    chunkName = "chk-" + chunkName;

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);

    String url = this.storageUrl + "/" + destinationWorkspace.getSwiftContainer() + "/"
            + chunkName;

    String copyFrom = "/" + sourceWorkspace.getSwiftContainer() + "/" + chunkName;

    try {

        HttpPut request = new HttpPut(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);
        request.setHeader(SwiftResponse.X_COPY_FROM, copyFrom);
        //request.setHeader("Content-Length", "0");                        

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("401 User unauthorized");
        }

        if (swiftResponse.getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            throw new ObjectNotFoundException("404 Not Found");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 14
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
@Override
public void deleteWorkspace(Workspace workspace) throws Exception {

    if (!isTokenActive()) {
        login();
    }

    TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
        @Override
        public boolean isTrusted(X509Certificate[] certificate, String authType) {
            return true;
        }
    };

    SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
    SchemeRegistry registry = new SchemeRegistry();
    registry.register(new Scheme("https", 5000, sf));
    ClientConnectionManager ccm = new SingleClientConnManager(registry);

    HttpClient httpClient = new DefaultHttpClient(ccm);

    String url = this.storageUrl + "/" + workspace.getSwiftContainer();

    try {

        HttpDelete request = new HttpDelete(url);
        request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);

        HttpResponse response = httpClient.execute(request);

        SwiftResponse swiftResponse = new SwiftResponse(response);

        if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
            throw new UnauthorizedException("401 User unauthorized");
        }

        if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
            throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
        }

    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}
 
Example 15
Source File: SwiftManagerHTTPS.java    From sync-service with Apache License 2.0 4 votes vote down vote up
private String getWorkspacePermissions(User user, Workspace workspace) throws Exception {

        if (!isTokenActive()) {
            login();
        }

        TrustStrategy acceptingTrustStrategy = new TrustStrategy() {
            @Override
            public boolean isTrusted(X509Certificate[] certificate, String authType) {
                return true;
            }
        };

        SSLSocketFactory sf = new SSLSocketFactory(acceptingTrustStrategy, SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
        SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("https", 5000, sf));
        ClientConnectionManager ccm = new SingleClientConnManager(registry);

        HttpClient httpClient = new DefaultHttpClient(ccm);

        String url = this.storageUrl + "/" + workspace.getSwiftContainer();

        try {

            HttpHead request = new HttpHead(url);
            request.setHeader(SwiftResponse.X_AUTH_TOKEN, authToken);

            HttpResponse response = httpClient.execute(request);

            SwiftResponse swiftResponse = new SwiftResponse(response);

            if (swiftResponse.getStatusCode() == HttpStatus.SC_UNAUTHORIZED) {
                throw new UnauthorizedException("404 User unauthorized");
            }

            if (swiftResponse.getStatusCode() < 200 || swiftResponse.getStatusCode() >= 300) {
                throw new UnexpectedStatusCodeException("Unexpected status code: " + swiftResponse.getStatusCode());
            }

            // We suppose there are the same permissions for read and write
            Header containerWriteHeader = swiftResponse.getResponseHeader(SwiftResponse.X_CONTAINER_WRITE);

            if (containerWriteHeader == null) {
                return "";
            }

            return containerWriteHeader.getValue();

        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }