Chain validation failed как исправить ошибку

У меня есть проект Android Studio, который вызывает веб-службу API. Когда сервисный код находится в dev, qa, prod и т.д. Никаких проблем с сертификатами нет, но при попытке открыть окно разработчиков веб-API для тестирования новой функции/исправления ошибки/и т.д. я получаю:

Нет ответа из-за ошибки:

javax.net.ssl.SSLHandshakeException: проверка цепочки не удалась

на com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:361)

У меня был самозаверяющий сертификат, экспортированный с машины разработчиков сервисов БЕЗ закодированного DER ключа. Я упал на эмулятор, и он «установлен», но это не сработало.

Я взял тот же сертификат выше и скопировал на эмулируемую SD-карту. Затем устанавливается из настроек безопасности в эмуляторе. Тот же результат. Проверка цепочки не удалась.

Теперь мои знания по безопасности/сертификатам очень просты. Я думаю, что ошибка на самом деле описывает проблему. В самозаверяющем сертификате нет цепочки… но я могу ошибаться.

Независимо от того, как мне обойти это?

Я хочу иметь возможность запускать свой код Android и устанавливать флажки для разработчиков для тестирования/отладки и т.д.

Я прочитал этот пост только для того, чтобы иметь корпоративную среду, в которой я блокирую сайты для открытого SSL и т.д.

https://android.stackexchange.com/info/61540/self-signed-certificate-install-claims-success-but-android-acts-as-if-cert-isn

Я получаю доступ к сервису через WebView.

4b9b3361

Ответ 1

Причиной этой проблемы может быть неправильная дата и время устройства

Ответ 2

Я получал

javax.net.ssl.SSLHandshakeException: Chain validation failed

и

java.security.cert.CertPathValidatorException: Response is unreliable: its validity interval is out-of-date

решение, которое работало для меня, заключалось в том, чтобы заставить холодную загрузку эмулятора через Диспетчер виртуальных устройств → Выпадающее меню Actions → Cold Boot Now

Ответ 3

Просто перезагрузка эмулятора решила эту ошибку.
Длительно нажмите кнопку выключения питания в меню эмулятора и выберите «Перезагрузка».

Ответ 4

холодная загрузка работала нормально для меня. Большое спасибо !!

Ответ 5

Я стер все данные с эмулятора и снова загрузил его, установил приложение и все работало. Но видел другое решение, я думаю, что теперь это может быть излишним.

Ответ 6

Я знаю, что это старый вопрос, но у меня была похожая проблема с совершенно другим решением.

Убедитесь, что ваш SSL не истек. После того, как я исправил эту проблему, я больше не получал ошибки «javax.net.ssl.SSLHandshakeException: Chain validation fail». У меня были другие проблемы, но это другая тема.

Это звучит как такое очевидное решение, но это то, на что нужно обратить внимание, и это не обязательно первое, что приходит на ум людям.

in my application I am trying to do a HTTPS POST request to my server.
However, I keep getting SSLHandshakeException — Chain chain validation failed, all the time. I tried to send a request using POSTMAN and I got a response from the server. What can be causing this error when I try to send the request from the application?

Here a code snippet where I try to send the post request:

   public static JSONObject getDataLibConfiguration(Context context) throws HttpRequestException {

    int statusCode = 0;

    JSONObject commonInformation;
    HttpsURLConnection connection = null;

    try {

        commonInformation = ConfigurationProcessor.getCommonInformation(context);
        if (commonInformation == null) {
            return null;
        }

        URL url = new URL(BuildConfig.SERVER_CONFIG_URL);
        if (BuildConfig.DEBUG) {
            LogUtils.d(TAG, "url = " + url.getPath());
        }

        connection = getHttpsConnection(url);
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        connection.setRequestProperty("Content-Encoding", "gzip");

        byte[] gzipped = HttpUtils.gzip(commonInformation.toString());
        cos = new CountingOutputStream(connection.getOutputStream()); //<-- This is where I get the exception
        cos.write(gzipped);
        cos.flush();

        statusCode = connection.getResponseCode();
        // More code her
 }

private static HttpsURLConnection getHttpsConnection(URL url) throws IOException, GeneralSecurityException {

        HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();

        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            MatchDomainTrustManager myTrustManager = new MatchDomainTrustManager(url.getHost());
            TrustManager[] tms = new TrustManager[]{myTrustManager};
            sslContext.init(null, tms, null);
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            connection.setSSLSocketFactory(sslSocketFactory);
        } catch (AssertionError ex) {
            if (BuildConfig.DEBUG) {
                LogFileUtils.e(TAG, "Exception in getHttpsConnection: " + ex.getMessage());
            }
            LogUtils.e(TAG, "Exception: " + ex.toString());
        }
        return connection;
    }

asked Nov 12, 2018 at 15:25

Keselme's user avatar

2

In my case it was wrong date on the phone.

Fixing the date resolved an issue

answered Aug 1, 2019 at 8:05

Vadim's user avatar

VadimVadim

3,8652 gold badges17 silver badges22 bronze badges

6

If you’re using an emulated device it may solve the problem if you just ‘Cold Boot’ it.

Sometimes the date on those things can get stuck if you let them run for some time, which results in this expired-certificate-problem.

answered Aug 28, 2020 at 7:45

Sebastian Müller's user avatar

0

The problem was that the certificate was expired.

answered Nov 14, 2018 at 10:11

Keselme's user avatar

KeselmeKeselme

3,7997 gold badges36 silver badges68 bronze badges

6

In my case, I fetch this issue on Android Emulator.
When I clear emulator cache has resolved the issue.

enter image description here

answered Nov 10, 2021 at 9:48

Md Imran Choudhury's user avatar

1

In my case, the issue was with the phone date. So please check it, set to automatic.

answered May 21, 2022 at 9:53

Hayk Mkrtchyan's user avatar

Hayk MkrtchyanHayk Mkrtchyan

2,8453 gold badges19 silver badges62 bronze badges

My date and time were correct, but I didn’t have «Use Network Provided Time checked» in my system settings.

I fixed this issue by going to Settings > Date and Time > Check «Use network-provided time» and also check «Use network-provided time zone».

Then this error went away.

answered Feb 15, 2021 at 21:03

zetatlas's user avatar

zetatlaszetatlas

3202 silver badges9 bronze badges

2

public static void trustEveryone() {
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }});
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new X509TrustManager[]{new X509TrustManager(){
                public void checkClientTrusted(X509Certificate[] chain,
                                               String authType) throws CertificateException {}
                public void checkServerTrusted(X509Certificate[] chain,
                                               String authType) throws CertificateException {}
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }}}, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(
                    context.getSocketFactory());
        } catch (Exception e) { // should never happen
            e.printStackTrace();
        }
    }

or check system date of your device — I had this Exception when I tried to connect with wrong date!..

answered May 24, 2019 at 12:30

Pavlo Synytsia's user avatar

1

If anyone come across this issue pertaining to specific device, then the reason should be because of incorrect date set in the device.

answered Aug 17, 2020 at 13:41

harishanth raveendren's user avatar

0

I fixed this error by resetting my emulator date and time. My server is working fine just I changed the date and time of my emulator as current server time zone.

answered Nov 3, 2021 at 6:59

Sachidanand Pandit's user avatar

If you use android emulator, you can wipe data and run again, it works

answered Jul 17, 2022 at 13:32

Muhammed Murat Göktaş's user avatar

1

@Yash Bhardwaj in the comment on @Vadim answer said that the problem was in Glide framework. I faced the same problem: Https requests to server using Ktor framework were all successful, but when Glide tried to load image from the same server, it faced the SSLHandshakeException.
To solve this issue you should look here: Solve Glide SSLHandshakeException.

To make a deal with @GlideModule annotation you should import kapt plugin and add these dependencies into your app build.gradle:

implementation 'com.github.bumptech.glide:okhttp3-integration:4.11.0'
kapt 'com.github.bumptech.glide:compiler:4.12.0'

answered Oct 17, 2021 at 10:08

Emir Vildanov's user avatar

In my case the date/ time was ok and I was still getting the exception. I restarted my device and the problem went away. Hope it helps someone if all the above fails.

answered Jul 19 at 9:36

android enthusiast's user avatar

Checks

  • I have read the FAQ section, searched the open issues, and still think this is a new bug.

Describe the bug you encountered:

So recently kee2pass started to deny me opening DB from my pcloud storage with chain validation failed error.
I tried to wipe the app, reinstall, authenticate myself against pcloud (I use 2FA there) everything is ok — I see the folder and DB file, but it doesn’t allow me to open it for some reason… From PC obviously everything is fine. From logs I see it says certificate is expired, but I can’t understand what certificate it is referring to? On the phone’s storage (I use Samsung S22 Ultra, it’s on the latest official android 13 FW) I don’t see any users certificates in the internal storage… Not sure what is happening and how to mitigate that… Do we possibly have an option to accept certificates anyways? Could you please clarify that? Phone’s time date is synced with NTP obviously — doublechecked.

System.Exception: Chain validation failed ---> Java.IO.IOException: Chain validation failed ---> Java.Security.Cert.CertificateException: Chain validation failed ---> Java.Security.GeneralSecurityException: timestamp check failed ---> Java.Security.Cert.CertificateException: **Certificate expired at Thu Mar 09 19:23:00 GMT+04:00 2023** (compared to Sat Apr 15 12:36:51 GMT+04:00 2023) --- End of inner exception stack trace --- --- End of inner exception stack trace --- --- End of inner exception stack trace --- at Java.Interop.JniEnvironment+InstanceMethods.CallObjectMethod (Java.Interop.JniObjectReference instance, Java.Interop.JniMethodInfo method, Java.Interop.JniArgumentValue* args) [0x0006e] in <6fb1725a77344b3e81b15cb69a959b5c>:0 at Java.Interop.JniPeerMembers+JniInstanceMethods.InvokeVirtualObjectMethod (System.String encodedMember, Java.Interop.IJavaPeerable self, Java.Interop.JniArgumentValue* parameters) [0x0003c] in <6fb1725a77344b3e81b15cb69a959b5c>:0 at Keepass2android.Javafilestorage.PCloudFileStorage.OpenFileForRead (System.String path) [0x00029] in <ef4fc53bed604ca380e5f749cd276ee6>:0 at keepass2android.Io.JavaFileStorage.OpenFileForRead (KeePassLib.Serialization.IOConnectionInfo ioc) [0x0000d] in <483bd1ecfe364ef6a0dfb2f58ee9f0f5>:0 --- End of inner exception stack trace --- at keepass2android.Io.JavaFileStorage.OpenFileForRead (KeePassLib.Serialization.IOConnectionInfo ioc) [0x0002b] in <483bd1ecfe364ef6a0dfb2f58ee9f0f5>:0 at keepass2android.Io.OfflineSwitchableFileStorage.OpenFileForRead (KeePassLib.Serialization.IOConnectionInfo ioc) [0x00006] in <483bd1ecfe364ef6a0dfb2f58ee9f0f5>:0 at keepass2android.Io.CachingFileStorage.UpdateCacheFromRemote (KeePassLib.Serialization.IOConnectionInfo ioc, System.String cachedFilePath) [0x00000] in <483bd1ecfe364ef6a0dfb2f58ee9f0f5>:0 at keepass2android.Io.CachingFileStorage.OpenFileForReadWhenNoLocalChanges (KeePassLib.Serialization.IOConnectionInfo ioc, System.String cachedFilePath) [0x00023] in <483bd1ecfe364ef6a0dfb2f58ee9f0f5>:0 at keepass2android.Io.CachingFileStorage.OpenFileForRead (KeePassLib.Serialization.IOConnectionInfo ioc) [0x0005a] in <483bd1ecfe364ef6a0dfb2f58ee9f0f5>:0 at keepass2android.LoadDb.Run () [0x000c2] in <483bd1ecfe364ef6a0dfb2f58ee9f0f5>:0

2023-04-15_13-46-08

Describe what you expected to happen:

No response

What version of Keepass2Android are you using?

1.09e-r7

Which version of Android are you on?

13

Problem Description:

I’m having the below Okhttp code:

val client = OkHttpClient()

val mediaType = MediaType.parse("application/x-www-form-urlencoded")
val body = RequestBody.create(mediaType, "tenant_id=xxxx&client_id=xxxx&client_secret=xxxx&resource=xxxx&grant_type=client_credentials")
val request = Request.Builder()
  .url("https://sxxx.com/axxx/oauth2/token")
  .post(body)
  .addHeader("Content-Type", "application/x-www-form-urlencoded")
  .build()

val response = client.newCall(request).execute()

And want to convert it usint ktor, so I wrote the below:

class Greeting {
        private val httpClient = HttpClient {
        }

        @Throws(Exception::class)
        suspend fun greeting(): String {
        val response = httpClient.request {
            method = HttpMethod.Post
            url {
                protocol = URLProtocol.HTTPS
                host = "sxxx.com"
                path("axxx/oauth2/token")
             //   encodedParameters
                trailingQuery = true
                parameters.append("tenant_id", "xxxx")
                parameters.append("client_id", "xxxx")
                parameters.append("client_secret", "xxxx")
                parameters.append("resource", "xxxx")
                parameters.append("grant_type", "client_credentials")
            }
            headers {
                append(HttpHeaders.ContentType, "application/x-www-form-urlencoded")
            }
        }
        return response.bodyAsText()
     }
}

And calling my new code as:

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyApplicationTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colors.background
                ) {
                    val scope = rememberCoroutineScope()
                    var text by remember {
                        mutableStateOf("Loading")
                    }
                    LaunchedEffect(true){
                        scope.launch {
                            text = try {
                                Greeting().greeting()
                            } catch (e: Exception) {
                                e.localizedMessage ?: "error"
                            }
                        }
                    }
                    Greeting(text)
                }
            }
        }
    }
}

@Composable
fun Greeting(text: String) {
    Text(text = text)
}

But instead of getting the required token, I’m getting the response: Chain validation failed

enter image description here

Solution – 1

Make sure that:

  • Your server certificate is valid.
  • Your android system datetime is correct.

Источник возникновения симптома (ошибка в EventViewer/JAS/логи A2FA/ошибки мобильного приложения/визуальные ошибки в мобильном приложении): 

Ошибки мобильного приложения Aladdin 2FA

Версия ПО:

Aladdin 2FA: версия 1.2.0 и выше;

Версия ОС: Android

Проблема: 

При нажатии на красный индикатор ранее добавленного PUSH-аутентификатора появляется ошибка: «Chain validation failed» (см. рисунки ниже):

Причина:

Ссылка, по которой пытается обращаться мобильное приложение Aladdin 2FA в момент регистрации аутентификатора, небезопасна.

Решение:

Обратитесь к администратору, выдавшему аутентификатор. В обращении сообщите об ошибке «Chain validation failed» и прикрепите необходимые скриншоты (см. рисунки в описание выше).

Понравилась статья? Поделить с друзьями:

Интересное по теме:

  • Chaffoteaux ошибка 105
  • Chevrolet aveo ошибка 0420
  • Chery tiggo знаки ошибок на панели
  • Chaffoteaux котел ошибка 6p1
  • Chevrolet aveo ошибка p0016

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии