I have issues in connecting to my server using gRPC. The server uses certificate files(rpc.cert and rpc.key) to authenticate but i do not know how to include those files. Currently this is the code i use to connect
ManagedChannel channel = OkHttpChannelBuilder.forAddress("127.0.0.1", 9111)
.usePlaintext(true)
.build();
Using the above code throws this error
io.grpc.StatusRuntimeException: UNAVAILABLE: End of stream or IOExceptio
at io.grpc.stub.ClientCalls.toStatusRuntimeException(ClientCalls.jav
at io.grpc.stub.ClientCalls.getUnchecked(ClientCalls.java:202)
at io.grpc.stub.ClientCalls.blockingUnaryCall(ClientCalls.java:131)
at com.dcrwallet.grpc.WalletLoaderServiceGrpc$WalletLoaderServiceBlo
at com.decrediton.MainActivity$2.onClick(MainActivity.java:86)
at android.view.View.performClick(View.java:5675)
at android.view.View$PerformClick.run(View.java:22641)
at android.os.Handler.handleCallback(Handler.java:836)
at android.os.Handler.dispatchMessage(Handler.java:103)
at android.os.Looper.loop(Looper.java:203)
at android.app.ActivityThread.main(ActivityThread.java:6285)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(Zygote
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:924)
Caused by: javax.net.ssl.SSLHandshakeException: Handshake failed
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:444)
at io.grpc.okhttp.OkHttpProtocolNegotiator.negotiate(OkHttpProtocolNegotiator.java:93)
at io.grpc.okhttp.OkHttpProtocolNegotiator$AndroidNegotiator.negotiate(OkHttpProtocolNegotiator.java:159)
at io.grpc.okhttp.OkHttpTlsUpgrader.upgrade(OkHttpTlsUpgrader.java:63)
at io.grpc.okhttp.OkHttpClientTransport$1.run(OkHttpClientTransport.java:429)
at io.grpc.internal.SerializingExecutor.run(SerializingExecutor.java:123)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb036ce80: Failure in SSL library, usually a protocol error error:1000006b:SSL routines:OPENSSL_internal:BAD_ECC_CERT (external/boringssl/src/ssl/s3_clnt.c:957 0xa74a5d15:0x00000000)
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:362)
I cannot find any documentation on using grpc okhttp in android. The gRPC documentation by google does not include that so i pretty much don't know what to do about the error.Thanks
Since the server expects TLS, you can't use plaintext. Normally, you don't need to do anything; grpc-java Channels default to using TLS:
ManagedChannel channel = OkHttpChannelBuilder.forAddress("127.0.0.1", 9111)
.sslSocketFactory(yourSslSocketFactory)
.build();
The client doesn't need any files to identify the server because the server's certificate should be signed by a trusted Certificate Authority (CA).
It's unclear by your question if this is the case though. If you are using a self-signed certificate or a custom CA to sign the certificate then SSLSocketFactory.getDefault(), which grpc-okhttp uses by default, likely will not accept the server's certificate.
In that rarer case, you will need to specify an SSLSocketFactory for gRPC to use:
ManagedChannel channel = OkHttpChannelBuilder.forAddress("127.0.0.1", 9111)
.sslSocketFactory(yourSslSocketFactory)
.build();
You would need to include a certificate in the client binary and the yourSslSocketFactory would need to reference that certificate for it's TrustManager. As an example (taken from some grpc tests):
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(theRawCert);
ks.setCertificateEntry("customca", cert);
TrustManagerFactory trustManagerFactory =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(ks);
SSLContext context = SSLContext.getInstance("TLS", provider);
context.init(null, trustManagerFactory.getTrustManagers(), null);
return context.getSocketFactory();
Related
My Server is using Self-Signed certificate. I am using Okhttp + Retrofit for api calls. I have got crt file and public key [SHA-256] from the server. Following this and this links from Google docs, I have created a network_security_config file in xml folder and added my crt file in raw folder and added it in manifest file as
android:networkSecurityConfig="#xml/network_security_config"
Here is my network config file as per Google docs:
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
<domain-config>
<domain includeSubdomains="true">2.48.3.66:</domain>
<pin-set>
<pin digest="SHA-256">ofJqMSD8j9q3w5myKalxjJO5OklHyBqgkwgHjqcOhds=</pin>
</pin-set>
<trust-anchors>
<certificates src="#raw/ssl_certificate"/>
</trust-anchors>
</domain-config>
</network-security-config>
I get following exception when calling an api
ResponseĀ Failure: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
W/System.err: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
W/System.err: at com.android.org.conscrypt.ConscryptFileDescriptorSocket.startHandshake(ConscryptFileDescriptorSocket.java:231)
W/System.err: at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.kt:367)
W/System.err: at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.kt:325)
W/System.err: at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:197)
W/System.err: at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:249)
W/System.err: at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:108)
W/System.err: at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:76)
W/System.err: at okhttp3.internal.connection.RealCall.initExchange$okhttp(RealCall.kt:245)
W/System.err: at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:32)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
W/System.err: at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:96)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
W/System.err: at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:83)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
W/System.err: at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:76)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
W/System.err: at okhttp3.logging.HttpLoggingInterceptor.intercept(HttpLoggingInterceptor.kt:219)
W/System.err: at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:100)
W/System.err: at okhttp3.internal.connection.RealCall.getResponseWithInterceptorChain$okhttp(RealCall.kt:197)
W/System.err: at okhttp3.internal.connection.RealCall$AsyncCall.run(RealCall.kt:502)
W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
W/System.err: at java.lang.Thread.run(Thread.java:919)
So following are my queries:
Is this the right way to implement Self-Signed certificate pinning?
Because google clearly mentions in their docs that "Fortunately, you can teach your application to trust custom CAs by configuring your application's Network Security Config, without needing to modify the code inside your application."
If network_security_config is correct then how to check if there is any issue with server configurations (crt file + public key)
Do i manually need to load crt file and then use keystore + sslfactory to configure ssl pinning as mentioned in this link
Note: For now just to run the apis, I am using a trust manager that does not validate certificate chains as follow:
try {
val trustAllCerts: Array<TrustManager> = arrayOf(object : X509TrustManager {
override fun checkClientTrusted(chain: Array<out java.security.cert.X509Certificate>?, authType: String?) {
}
override fun checkServerTrusted(chain: Array<out java.security.cert.X509Certificate>?, authType: String?) {
}
override fun getAcceptedIssuers(): Array<out java.security.cert.X509Certificate>? = arrayOf()
})
// Install the all-trusting trust manager
val sslContext = SSLContext.getInstance("SSL")
sslContext.init(null, trustAllCerts, SecureRandom())
// Create an ssl socket factory with our all-trusting manager
val sslSocketFactory = sslContext.socketFactory
if (trustAllCerts.isNotEmpty() && trustAllCerts.first() is X509TrustManager) {
builder.sslSocketFactory(sslSocketFactory, trustAllCerts.first() as X509TrustManager)
builder.hostnameVerifier { hostname, session -> true }
}
} catch (e: Exception) {
}
Below is my code:
database = Utils.inializeDb(HomeActivity.this, "company-3");
URL url = null;
try {
url = new URL("https://*********/db_name");
} catch (IOException e) {
e.printStackTrace();
}
Replication push = database.createPushReplication(url);
Replication pull = database.createPullReplication(url);
Authenticator auth = AuthenticatorFactory.createBasicAuthenticator("admin", "1m2p3k4n");
pull.setAuthenticator(auth);
push.setContinuous(true);
pull.setContinuous(true);
pull.start();
I want to add ssl Certificate in this code..
Below is error code;
javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:366)
at okhttp3.internal.connection.RealConnection.connectTls(RealConnection.kt:351)
at okhttp3.internal.connection.RealConnection.establishProtocol(RealConnection.kt:310)
at okhttp3.internal.connection.RealConnection.connect(RealConnection.kt:178)
at okhttp3.internal.connection.ExchangeFinder.findConnection(ExchangeFinder.kt:236)
at okhttp3.internal.connection.ExchangeFinder.findHealthyConnection(ExchangeFinder.kt:109)
at okhttp3.internal.connection.ExchangeFinder.find(ExchangeFinder.kt:77)
at okhttp3.internal.connection.Transmitter.newExchange$okhttp(Transmitter.kt:162)
at okhttp3.internal.connection.ConnectInterceptor.intercept(ConnectInterceptor.kt:35)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:87)
at okhttp3.internal.cache.CacheInterceptor.intercept(CacheInterceptor.kt:82)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:87)
at okhttp3.internal.http.BridgeInterceptor.intercept(BridgeInterceptor.kt:84)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112)
at okhttp3.internal.http.RetryAndFollowUpInterceptor.intercept(RetryAndFollowUpInterceptor.kt:71)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:112)
at okhttp3.internal.http.RealInterceptorChain.proceed(RealInterceptorChain.kt:87)
at okhttp3.RealCall.getResponseWithInterceptorChain(RealCall.kt:184)
at okhttp3.RealCall.execute(RealCall.kt:66)
at com.couchbase.lite.replicator.RemoteRequest.executeRequest(RemoteRequest.java:262)
at com.couchbase.lite.replicator.RemoteRequest.execute(RemoteRequest.java:166)
at com.couchbase.lite.replicator.RemoteRequest.run(RemoteRequest.java:106)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
at com.android.org.conscrypt.TrustManagerImpl.checkTrustedRecursive(TrustManagerImpl.java:549)
at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:401)
at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:375)
at com.android.org.conscrypt.TrustManagerImpl.getTrustedChainForServer(TrustManagerImpl.java:304)
at android.security.net.config.NetworkSecurityTrustManager.checkServerTrusted(NetworkSecurityTrustManager.java:94)
at android.security.net.config.RootTrustManager.checkServerTrusted(RootTrustManager.java:88)
at com.android.org.conscrypt.Platform.checkServerTrusted(Platform.java:178)
at com.android.org.conscrypt.OpenSSLSocketImpl.verifyCertificateChain(OpenSSLSocketImpl.java:611)
at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:362)
From errors, it looks like the Sync Gateway cert from a well-known trusted CA or it was perhaps self-signed. How was the cert issued? Follow the steps here to configure your system to accept the cert.
Any reason you are starting with 1.x version of Couchbase Lite? Version 1.x is EoL for almost a year. You should switch to 2.x.
I'm new to reactive programming and currently learning kotlin. I'm trying to make an API request using okhttp client but instead of using asynctask, I want to try rxjava.
fun network():Observable<String>{
val exe = Observable.create<String> { emitter->
emitter.onNext("https://pokeapi.co/api/v2/pokemon/500")
}
return exe.onErrorReturn{
it.toString()
}.subscribeOn(Schedulers.io()).flatMap {
val c = OkHttpClient();
val req = Request.Builder()
.url(it)
.build();
val resp = c.newCall(req).execute()
Observable.just(resp.toString())
}
I created a method with return type of observable string which will contain a string url from pokemon API and then I added a subscribeOn method which will force it to do the okhttpClient request be executed in the io thread (do in background equivalent of asynctask) then finally subscribe to it via simply calling the method in the onCreate of my activity:
network().subscribe {
Log.e("response",it);
}
Unfortunately im having the following error:
FATAL EXCEPTION: RxCachedThreadScheduler-1
io.reactivex.exceptions.OnErrorNotImplementedException: The exception was not handled due to missing onError handler in the subscribe() method call. Further reading: https://github.com/ReactiveX/RxJava/wiki/Error-Handling | javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb955faf8: Failure in SSL library, usually a protocol error
error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x9da8e8c1:0x00000000)
at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:704)
at io.reactivex.internal.functions.Functions$OnErrorMissingConsumer.accept(Functions.java:701)
at io.reactivex.internal.observers.LambdaObserver.onError(LambdaObserver.java:77)
at io.reactivex.internal.observers.BasicFuseableObserver.onError(BasicFuseableObserver.java:100)
at io.reactivex.internal.observers.BasicFuseableObserver.fail(BasicFuseableObserver.java:110)
at io.reactivex.internal.operators.observable.ObservableMap$MapObserver.onNext(ObservableMap.java:59)
at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeOnObserver.onNext(ObservableSubscribeOn.java:58)
at io.reactivex.internal.operators.observable.ObservableOnErrorReturn$OnErrorReturnObserver.onNext(ObservableOnErrorReturn.java:65)
at io.reactivex.internal.operators.observable.ObservableCreate$CreateEmitter.onNext(ObservableCreate.java:66)
at ui.activities.ObjectManipulation$network$exe$1.subscribe(ObjectManipulation.kt:37)
at io.reactivex.internal.operators.observable.ObservableCreate.subscribeActual(ObservableCreate.java:40)
at io.reactivex.Observable.subscribe(Observable.java:12267)
at io.reactivex.internal.operators.observable.ObservableOnErrorReturn.subscribeActual(ObservableOnErrorReturn.java:31)
at io.reactivex.Observable.subscribe(Observable.java:12267)
at io.reactivex.internal.operators.observable.ObservableSubscribeOn$SubscribeTask.run(ObservableSubscribeOn.java:96)
at io.reactivex.Scheduler$DisposeTask.run(Scheduler.java:578)
at io.reactivex.internal.schedulers.ScheduledRunnable.run(ScheduledRunnable.java:66)
at io.reactivex.internal.schedulers.ScheduledRunnable.call(ScheduledRunnable.java:57)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:153)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:267)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: javax.net.ssl.SSLHandshakeException: javax.net.ssl.SSLProtocolException: SSL handshake aborted: ssl=0xb955faf8: Failure in SSL library, usually a protocol error
error:14077410:SSL routines:SSL23_GET_SERVER_HELLO:sslv3 alert handshake failure (external/openssl/ssl/s23_clnt.c:741 0x9da8e8c1:0x00000000)
Line 37 in the error is the onNext(url).
Any useful hint or reply would be greatly appreciated!
At first it seems that the problem comes from the OkHTTP client configuration, you can check this to see how to fix it.
If you want that the app doesnĀ“t crash you should handle the error by implementing onError when you are subscribing, you can find more information here.
Finally I would recommend you to use Retrofit instead of using raw OkHTTP. You can find an example here.
I am trying to upload a file to Dropbox using Sync API, but while uploading getting Error
W/libDropboxSync.so(status): REQUEST: api_core.cpp:264: HTTP request error 400: v1_retired [dc166c5befd76df2]
W/com.dropbox.sync.android.DbxAccount: Failed to update account info.
com.dropbox.sync.android.DbxException$Request: _jobject* dropboxsync::Java_com_dropbox_sync_android_NativeApp_nativeGetAccountInfo(JNIEnv*, jobject, jlong, jobject) - Invalid server request: HTTP request error 400: v1_retired [dc166c5befd76df2]
at com.dropbox.sync.android.DbxError.exceptionFrom(DbxError.java:296)
at com.dropbox.sync.android.NativeLib.exceptionFrom(NativeLib.java:254)
at com.dropbox.sync.android.NativeLib.throwFrom(NativeLib.java:242)
at com.dropbox.sync.android.NativeApp.nativeGetAccountInfo(Native Method)
at com.dropbox.sync.android.NativeApp.getAccountInfo(NativeApp.java:175)
at com.dropbox.sync.android.DbxAccount.fetchAccountInfo(DbxAccount.java:559)
at com.dropbox.sync.android.DbxAccount.backgroundUpdateAccountInfo(DbxAccount.java:540)
at com.dropbox.sync.android.CoreBackgroundProcessor$RunAccountInfoUpdate.attemptRun(CoreBackgroundProcessor.java:209)
at com.dropbox.sync.android.CoreBackgroundProcessor$BackgroundRunner.run(CoreBackgroundProcessor.java:239)
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:761)
Below Code, I am using for file uploading. Stuck in this from 2 days.
DbxFileSystem dbxFs = DbxFileSystem.forAccount(HomeActivity.mDbxAcctMgr.getLinkedAccount());
DbxPath path = new DbxPath(recordingData.filePath);
DbxFile mFile;
try {
mFile = dbxFs.open(path);
} catch (DbxException.NotFound e) {
mFile = dbxFs.create(path);
}
mFile.addListener(mChangeListener);
The SDK you're trying to use is built on Dropbox API v1, which is retired: https://blogs.dropbox.com/developers/2016/06/api-v1-deprecated/
You should instead switch to API v2: https://www.dropbox.com/developers
To use API v2 from Java/Android, we recommend using the official Dropbox API v2 Java SDK: https://github.com/dropbox/dropbox-sdk-java
I am using Firebase UI Auth to login into the application. The debug build is working fine but when I try to login with the release build the application crashes with an error.
2018-10-02 14:05:23.072 4827-4866/io.palette E/c.b.a.J: Creating atomic field updaters failed
java.lang.RuntimeException: java.security.PrivilegedActionException: java.lang.NoSuchFieldException: No field streamClosed in class Lc/b/a/J$c; (declaration of 'c.b.a.J$c' appears in /data/app/io.palette-1/base.apk)
at java.util.concurrent.atomic.AtomicIntegerFieldUpdater$AtomicIntegerFieldUpdaterImpl.<init>(AtomicIntegerFieldUpdater.java:380)
at java.util.concurrent.atomic.AtomicIntegerFieldUpdater.newUpdater(AtomicIntegerFieldUpdater.java:58)
at c.b.a.J.<clinit>(:77)
at c.b.a.c.c(:420)
at c.b.a.c.a(:395)
at com.google.firebase.firestore.f.zzd.<init>(:102)
at com.google.firebase.firestore.b.zzg.zza(:1217)
at com.google.firebase.firestore.b.zzi.run()
at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:428)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:272)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at com.google.firebase.firestore.g.zza$zza.run(:190)
at java.lang.Thread.run(Thread.java:761)
What could be the possible reason for this?