use of javax.net.ssl.SSLPeerUnverifiedException in project aware-client by denzilferreira.
the class SSLManager method retrieveRemoteCertificate.
/**
* Downloads the certificate directly from the URL, instead of a public folder. This only happens once when joining the study.
* We are trusting the certificate that is sent to us by the URL only once to avoid man-in-the-middle attacks
* @param url
* @return
*/
public static X509Certificate retrieveRemoteCertificate(URL url) {
try {
SSLContext ctx = SSLContext.getInstance("TLS");
ctx.init(null, new TrustManager[] { new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
} }, null);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ctx.getSocketFactory());
// 5 seconds to connect
conn.setConnectTimeout(5000);
// 10 seconds to acknowledge the response
conn.setReadTimeout(10000);
conn.setHostnameVerifier(new HostnameVerifier() {
@Override
public boolean verify(String hostname, SSLSession session) {
return true;
}
});
conn.connect();
// retrieve the N-length signing chain for the server certificates
// certs[0] is the server's certificate
Certificate[] certs = conn.getServerCertificates();
if (certs.length > 0 && certs[0] instanceof X509Certificate) {
return ((X509Certificate) certs[0]);
}
Log.d(Aware.TAG, "Not an X509Certificate! " + certs[0].getType() + " : " + certs[0].toString());
// connection is not HTTPS or server is not signed with an X.509 certificate, return null
return null;
} catch (SSLPeerUnverifiedException | NoSuchAlgorithmException | KeyManagementException spue) {
// connection to server is not verified, unable to get certificates
Log.d(Aware.TAG, "Certificates: " + spue.getMessage());
return null;
} catch (IllegalStateException ise) {
// shouldn't get here -- indicates attempt to get certificates before
// connection is established
Log.d(Aware.TAG, "Certificates: " + ise.getMessage());
return null;
} catch (IOException ioe) {
// error connecting to URL -- this must be caught last since
// other exceptions are subclasses of IOException
Log.d(Aware.TAG, "Certificates: " + ioe.getMessage());
return null;
}
}
use of javax.net.ssl.SSLPeerUnverifiedException in project hono by eclipse.
the class HonoSaslAuthenticator method init.
@Override
public void init(final NetSocket socket, final ProtonConnection protonConnection, final Transport transport) {
LOG.debug("initializing SASL authenticator");
this.protonConnection = protonConnection;
this.sasl = transport.sasl();
sasl.server();
sasl.allowSkip(false);
sasl.setMechanisms(authenticationService.getSupportedSaslMechanisms());
if (socket.isSsl() && Arrays.asList(authenticationService.getSupportedSaslMechanisms()).contains(AuthenticationConstants.MECHANISM_EXTERNAL)) {
LOG.debug("client connected using TLS, extracting client certificate chain");
try {
final Certificate cert = socket.sslSession().getPeerCertificates()[0];
if (cert instanceof X509Certificate) {
clientCertificate = (X509Certificate) cert;
}
} catch (final SSLPeerUnverifiedException e) {
LOG.debug("could not extract client certificate chain, maybe client uses other mechanism than SASL EXTERNAL");
}
}
}
use of javax.net.ssl.SSLPeerUnverifiedException in project hono by eclipse.
the class X509AuthHandlerTest method testHandleFailsWithStatusCodeFromAuthProvider.
/**
* Verifies that the handler returns the status code conveyed in a
* failed Tenant service invocation in the response.
*
* @param ctx The vert.x test context.
* @throws SSLPeerUnverifiedException if the client certificate cannot be determined.
*/
@SuppressWarnings("unchecked")
@Test
public void testHandleFailsWithStatusCodeFromAuthProvider(final VertxTestContext ctx) throws SSLPeerUnverifiedException {
// GIVEN an auth handler configured with an auth provider that
// fails with a 503 error code during authentication
final ServiceInvocationException error = new ServerErrorException(HttpURLConnection.HTTP_UNAVAILABLE);
when(clientAuth.validateClientCertificate(any(Certificate[].class), any(List.class), (SpanContext) any())).thenReturn(Future.failedFuture(error));
// WHEN trying to authenticate a request that contains a client certificate
final X509Certificate clientCert = getClientCertificate("CN=device", "CN=tenant");
final SSLSession sslSession = mock(SSLSession.class);
when(sslSession.getPeerCertificates()).thenReturn(new X509Certificate[] { clientCert });
final MqttEndpoint endpoint = mock(MqttEndpoint.class);
when(endpoint.isSsl()).thenReturn(true);
when(endpoint.sslSession()).thenReturn(sslSession);
final MqttConnectContext context = MqttConnectContext.fromConnectPacket(endpoint, span);
authHandler.authenticateDevice(context).onComplete(ctx.failing(t -> {
ctx.verify(() -> {
assertThat(t).isEqualTo(error);
});
ctx.completeNow();
}));
}
use of javax.net.ssl.SSLPeerUnverifiedException in project bitcoin-wallet by bitcoin-wallet.
the class RequestWalletBalanceTask method requestWalletBalance.
public void requestWalletBalance(final AssetManager assets, final ECKey key) {
backgroundHandler.post(new Runnable() {
@Override
public void run() {
org.bitcoinj.core.Context.propagate(Constants.CONTEXT);
final Address legacyAddress = LegacyAddress.fromKey(Constants.NETWORK_PARAMETERS, key);
final Script[] outputScripts;
final String addressesStr;
if (key.isCompressed()) {
final Address segwitAddress = SegwitAddress.fromKey(Constants.NETWORK_PARAMETERS, key);
outputScripts = new Script[] { ScriptBuilder.createP2PKHOutputScript(legacyAddress.getHash()), ScriptBuilder.createP2WPKHOutputScript(segwitAddress.getHash()) };
addressesStr = legacyAddress.toString() + "," + segwitAddress.toString();
} else {
outputScripts = new Script[] { ScriptBuilder.createP2PKHOutputScript(legacyAddress.getHash()) };
addressesStr = legacyAddress.toString();
}
final List<ElectrumServer> servers = loadElectrumServers(Assets.open(assets, Constants.Files.ELECTRUM_SERVERS_ASSET));
final List<Callable<Set<UTXO>>> tasks = new ArrayList<>(servers.size());
for (final ElectrumServer server : servers) {
tasks.add(() -> {
log.info("{} - trying to request wallet balance for {}", server.socketAddress, addressesStr);
try (final Socket socket = connect(server)) {
final BufferedSink sink = Okio.buffer(Okio.sink(socket));
sink.timeout().timeout(5000, TimeUnit.MILLISECONDS);
final BufferedSource source = Okio.buffer(Okio.source(socket));
source.timeout().timeout(5000, TimeUnit.MILLISECONDS);
final Moshi moshi = new Moshi.Builder().build();
final JsonAdapter<ElectrumRequest> requestAdapter = moshi.adapter(ElectrumRequest.class);
final JsonAdapter<ListunspentResponse> listunspentResponseAdapter = moshi.adapter(ListunspentResponse.class);
final JsonAdapter<TransactionResponse> transactionResponseAdapter = moshi.adapter(TransactionResponse.class);
final Set<UTXO> utxos = new HashSet<>();
for (final Script outputScript : outputScripts) {
requestAdapter.toJson(sink, new ElectrumRequest(outputScript.getScriptType().ordinal(), "blockchain.scripthash.listunspent", new String[] { Constants.HEX.encode(Sha256Hash.of(outputScript.getProgram()).getReversedBytes()) }));
sink.writeUtf8("\n").flush();
final ListunspentResponse listunspentResponse = listunspentResponseAdapter.fromJson(source);
final int expectedResponseId = outputScript.getScriptType().ordinal();
if (listunspentResponse.id != expectedResponseId) {
log.warn("{} - id mismatch listunspentResponse:{} vs request:{}", server.socketAddress, listunspentResponse.id, expectedResponseId);
return null;
}
if (listunspentResponse.error != null) {
log.info("{} - server error {}: {}", server.socketAddress, listunspentResponse.error.code, listunspentResponse.error.message);
return null;
}
if (listunspentResponse.result == null) {
log.info("{} - missing result", server.socketAddress);
return null;
}
for (final ListunspentResponse.Utxo responseUtxo : listunspentResponse.result) {
final Sha256Hash utxoHash = Sha256Hash.wrap(responseUtxo.tx_hash);
final int utxoIndex = responseUtxo.tx_pos;
// the value cannot be trusted; will be validated below
final Coin utxoValue = Coin.valueOf(responseUtxo.value);
final UTXO utxo = new UTXO(utxoHash, utxoIndex, utxoValue, responseUtxo.height, false, outputScript);
// validation of value and some sanity checks
requestAdapter.toJson(sink, new ElectrumRequest("blockchain.transaction.get", new String[] { Constants.HEX.encode(utxo.getHash().getBytes()) }));
sink.writeUtf8("\n").flush();
final TransactionResponse transactionResponse = transactionResponseAdapter.fromJson(source);
if (transactionResponse.error != null) {
log.info("{} - server error {}: {}", server.socketAddress, transactionResponse.error.code, transactionResponse.error.message);
return null;
}
if (transactionResponse.result == null) {
log.info("{} - missing result", server.socketAddress);
return null;
}
final Transaction tx = new Transaction(Constants.NETWORK_PARAMETERS, Constants.HEX.decode(transactionResponse.result));
if (!tx.getTxId().equals(utxo.getHash()))
log.warn("{} - lied about txid", server.socketAddress);
else if (!tx.getOutput(utxo.getIndex()).getValue().equals(utxo.getValue()))
log.warn("{} - lied about amount", server.socketAddress);
else if (!tx.getOutput(utxo.getIndex()).getScriptPubKey().equals(outputScript))
log.warn("{} - lied about output script", server.socketAddress);
else
// use valid UTXO
utxos.add(utxo);
}
}
log.info("{} - got {} UTXOs {}", server.socketAddress, utxos.size(), utxos);
return utxos;
} catch (final ConnectException | SSLPeerUnverifiedException | JsonDataException x) {
log.warn("{} - {}", server.socketAddress, x.getMessage());
return null;
} catch (final IOException x) {
log.info(server.socketAddress.toString(), x);
return null;
} catch (final RuntimeException x) {
log.error(server.socketAddress.toString(), x);
throw x;
}
});
}
final ExecutorService threadPool = Executors.newFixedThreadPool(servers.size(), new ContextPropagatingThreadFactory("request"));
final List<Future<Set<UTXO>>> futures;
try {
futures = threadPool.invokeAll(tasks, 10, TimeUnit.SECONDS);
} catch (final InterruptedException x) {
throw new RuntimeException(x);
} finally {
threadPool.shutdown();
}
final Multiset<UTXO> countedUtxos = HashMultiset.create();
int numSuccess = 0, numFail = 0, numTimeOuts = 0;
for (Future<Set<UTXO>> future : futures) {
if (!future.isCancelled()) {
try {
final Set<UTXO> utxos = future.get();
if (utxos != null) {
countedUtxos.addAll(utxos);
numSuccess++;
} else {
numFail++;
}
} catch (InterruptedException | ExecutionException x) {
throw new RuntimeException(x);
}
} else {
numTimeOuts++;
}
}
final int trustThreshold = servers.size() / 2;
for (final Iterator<Multiset.Entry<UTXO>> i = countedUtxos.entrySet().iterator(); i.hasNext(); ) {
final Multiset.Entry<UTXO> entry = i.next();
if (entry.getCount() < trustThreshold)
i.remove();
}
final Set<UTXO> utxos = countedUtxos.elementSet();
log.info("{} successes, {} fails, {} time-outs, {} UTXOs {}", numSuccess, numFail, numTimeOuts, utxos.size(), utxos);
if (numSuccess < trustThreshold)
onFail(R.string.sweep_wallet_fragment_request_wallet_balance_failed_connection);
else if (utxos.isEmpty())
onFail(R.string.sweep_wallet_fragment_request_wallet_balance_empty);
else
onResult(utxos);
}
private Socket connect(final ElectrumServer server) throws IOException {
final Socket socket;
if (server.type == ElectrumServer.Type.TLS) {
final SocketFactory sf = sslTrustAllCertificates();
socket = sf.createSocket(server.socketAddress.getHostName(), server.socketAddress.getPort());
final SSLSession sslSession = ((SSLSocket) socket).getSession();
final Certificate certificate = sslSession.getPeerCertificates()[0];
final String certificateFingerprint = sslCertificateFingerprint(certificate);
if (server.certificateFingerprint == null) {
// signed by CA
if (!HttpsURLConnection.getDefaultHostnameVerifier().verify(server.socketAddress.getHostName(), sslSession))
throw new SSLPeerUnverifiedException("Expected " + server.socketAddress.getHostName() + ", got " + sslSession.getPeerPrincipal());
} else {
// self-signed
if (!certificateFingerprint.equals(server.certificateFingerprint))
throw new SSLPeerUnverifiedException("Expected " + server.certificateFingerprint + " for " + server.socketAddress.getHostName() + ", got " + certificateFingerprint);
}
} else if (server.type == ElectrumServer.Type.TCP) {
socket = new Socket();
socket.connect(server.socketAddress, 5000);
} else {
throw new IllegalStateException("Cannot handle: " + server.type);
}
return socket;
}
});
}
use of javax.net.ssl.SSLPeerUnverifiedException in project grpc-java by grpc.
the class GrpcAuthorizationEngineTest method authenticatedMatcher.
@Test
public void authenticatedMatcher() throws Exception {
AuthenticatedMatcher authMatcher = AuthenticatedMatcher.create(StringMatcher.forExact("*.test.google.fr", false));
PathMatcher pathMatcher = PathMatcher.create(STRING_MATCHER);
OrMatcher permission = OrMatcher.create(authMatcher);
OrMatcher principal = OrMatcher.create(pathMatcher);
PolicyMatcher policyMatcher = PolicyMatcher.create(POLICY_NAME, permission, principal);
GrpcAuthorizationEngine engine = new GrpcAuthorizationEngine(AuthConfig.create(Collections.singletonList(policyMatcher), Action.ALLOW));
AuthDecision decision = engine.evaluate(HEADER, serverCall);
assertThat(decision.decision()).isEqualTo(Action.ALLOW);
assertThat(decision.matchingPolicyName()).isEqualTo(POLICY_NAME);
X509Certificate[] certs = { TestUtils.loadX509Cert("badserver.pem") };
when(sslSession.getPeerCertificates()).thenReturn(certs);
decision = engine.evaluate(HEADER, serverCall);
assertThat(decision.decision()).isEqualTo(Action.DENY);
assertThat(decision.matchingPolicyName()).isEqualTo(null);
X509Certificate mockCert = mock(X509Certificate.class);
when(sslSession.getPeerCertificates()).thenReturn(new X509Certificate[] { mockCert });
assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.DENY);
when(mockCert.getSubjectDN()).thenReturn(mock(Principal.class));
assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.DENY);
when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList(Arrays.asList(2, "*.test.google.fr")));
assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.ALLOW);
when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList(Arrays.asList(6, "*.test.google.fr")));
assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.ALLOW);
when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList(Arrays.asList(10, "*.test.google.fr")));
assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.DENY);
when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList(Arrays.asList(2, "google.com"), Arrays.asList(6, "*.test.google.fr")));
assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.ALLOW);
when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList(Arrays.asList(6, "*.test.google.fr"), Arrays.asList(2, "google.com")));
assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.ALLOW);
when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList(Arrays.asList(2, "*.test.google.fr"), Arrays.asList(6, "google.com")));
assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.DENY);
when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList(Arrays.asList(2, "*.test.google.fr"), Arrays.asList(6, "google.com"), Arrays.asList(6, "*.test.google.fr")));
assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.ALLOW);
// match any authenticated connection if StringMatcher not set in AuthenticatedMatcher
permission = OrMatcher.create(AuthenticatedMatcher.create(null));
policyMatcher = PolicyMatcher.create(POLICY_NAME, permission, principal);
when(mockCert.getSubjectAlternativeNames()).thenReturn(Arrays.<List<?>>asList(Arrays.asList(6, "random")));
engine = new GrpcAuthorizationEngine(AuthConfig.create(Collections.singletonList(policyMatcher), Action.ALLOW));
assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.ALLOW);
// not match any unauthenticated connection
Attributes attributes = Attributes.newBuilder().set(Grpc.TRANSPORT_ATTR_REMOTE_ADDR, new InetSocketAddress(IP_ADDR2, PORT)).set(Grpc.TRANSPORT_ATTR_LOCAL_ADDR, new InetSocketAddress(IP_ADDR1, PORT)).build();
when(serverCall.getAttributes()).thenReturn(attributes);
assertThat(engine.evaluate(HEADER, serverCall).decision()).isEqualTo(Action.DENY);
doThrow(new SSLPeerUnverifiedException("bad")).when(sslSession).getPeerCertificates();
decision = engine.evaluate(HEADER, serverCall);
assertThat(decision.decision()).isEqualTo(Action.DENY);
assertThat(decision.matchingPolicyName()).isEqualTo(null);
}
Aggregations