AndroidクライアントでのSSL相互認証の失敗はサーバー証明書を受け入れますが、サーバーはクライアント証明書を取得しません

jmarrero:

LinuxサーバーとAndroidアプリの間に相互認証されたSSLをセットアップしようとしています。これまでのところ、アプリがサーバー証明書と連携してSSL経由で通信できるようにしましたが、クライアント証明書のみを受け入れるようにサーバーを設定すると、機能しなくなります。サーバーの設定は問題ないようですが、私は一種の行き詰まりです。私の推測では、クライアント証明書はサーバーに正しく提示されていませんが、次にそれをテストする方法がわかりません。OS Xキーチェーンでクライアントに.pemを使用してみましたが、ブラウザーがその証明書で動作しないようです。次に、サーバー接続証明書が完全に機能します。これは、https接続を確立でき、APPが未署名のサーバー証明書を受け入れるためです。

私が使用しているコードはさまざまなチュートリアルの組み合わせであり、これが私がブックマークした主なものです:

これは、接続に使用している2つの主要なクラスです。1)このクラスは、JSON解析を処理し、要求を行います

package edu.hci.additional;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import android.content.Context;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URLEncodedUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class JSONParser {

    static InputStream is = null;
    static JSONObject jObj = null;
    static String json = "";

    // constructor
    public JSONParser() {

    }

    // function get json from url
    // by making HTTP POST or GET mehtod
    public JSONObject makeHttpRequest(String url, String method,
            List<NameValuePair> params, Context context) {

        // Making HTTP request
        try {

            // check for request method
            if(method == "POST"){
                // request method is POST
                // defaultHttpClient
                SecureHttpClient httpClient = new SecureHttpClient(context);
                HttpPost httpPost = new HttpPost(url);
                httpPost.setEntity(new UrlEncodedFormEntity(params));

                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();

            }else if(method == "GET"){
                // request method is GET
                SecureHttpClient httpClient = new SecureHttpClient(context);
                String paramString = URLEncodedUtils.format(params, "utf-8");
                url += "?" + paramString;
                HttpGet httpGet = new HttpGet(url);

                HttpResponse httpResponse = httpClient.execute(httpGet);
                HttpEntity httpEntity = httpResponse.getEntity();
                is = httpEntity.getContent();
            }           


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "iso-8859-1"), 8);
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
            is.close();
            json = sb.toString();
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            jObj = new JSONObject(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

この2番目のクラスはSSL認証を処理します。

package edu.hci.additional;

import android.content.Context;
import android.util.Log;
import edu.hci.R;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.HttpParams;

import java.io.IOException;
import java.io.InputStream;
import java.security.*;


public class SecureHttpClient extends DefaultHttpClient {

    private static Context appContext = null;
    private static HttpParams params = null;
    private static SchemeRegistry schmReg = null;
    private static Scheme httpsScheme = null;
    private static Scheme httpScheme = null;
    private static String TAG = "MyHttpClient";

    public SecureHttpClient(Context myContext) {

        appContext = myContext;

        if (httpScheme == null || httpsScheme == null) {
            httpScheme = new Scheme("http", PlainSocketFactory.getSocketFactory(), 80);
            httpsScheme = new Scheme("https", mySSLSocketFactory(), 443);
        }

        getConnectionManager().getSchemeRegistry().register(httpScheme);
        getConnectionManager().getSchemeRegistry().register(httpsScheme);

    }

    private SSLSocketFactory mySSLSocketFactory() {
        SSLSocketFactory ret = null;
        try {

            final KeyStore clientCert = KeyStore.getInstance("BKS");
            final KeyStore serverCert = KeyStore.getInstance("BKS");

            final InputStream client_inputStream = appContext.getResources().openRawResource(R.raw.authclientcerts);
            final InputStream server_inputStream = appContext.getResources().openRawResource(R.raw.certs);

            clientCert.load(client_inputStream, appContext.getString(R.string.client_store_pass).toCharArray());
            serverCert.load(server_inputStream, appContext.getString(R.string.server_store_pass).toCharArray());

            String client_password = appContext.getString(R.string.client_store_pass);

            server_inputStream.close();
            client_inputStream.close();

            ret = new SSLSocketFactory(clientCert,client_password,serverCert);
        } catch (UnrecoverableKeyException ex) {
            Log.d(TAG, ex.getMessage());
        } catch (KeyStoreException ex) {
            Log.d(TAG, ex.getMessage());
        } catch (KeyManagementException ex) {
            Log.d(TAG, ex.getMessage());
        } catch (NoSuchAlgorithmException ex) {
            Log.d(TAG, ex.getMessage());
        } catch (IOException ex) {
            Log.d(TAG, ex.getMessage());
        } catch (Exception ex) {
            Log.d(TAG, ex.getMessage());
        } finally {
            return ret;
        }
    }

}

このコマンドでopensslを使用してキーを作成するには:

openssl req -nodes -x509 -newkey rsa:2048 -keyout key.pem -out cert.pem -days 500

BKS for Androidのキーを取得するには、http://www.bouncycastle.org/latest_releases.htmlにある弾力のある城bcprov-jdk15on-150.jarを使用しました

そして、コマンドを使用しました:

keytool -import -v -trustcacerts -alias 0 -file ~/cert.pem -keystore ~/Downloads/authclientcerts.bks -storetype BKS -provider org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath ~/Downloads/bcprov-jdk15on-150.jar -storepass passWORD

最後に、/ etc / httpd / conf.d / ssl.confに追加してクライアント証明書を要求し、Fedora 19で(作成したクライアント証明書と一致する)証明書の有効性を確認する行は次のとおりです。

...
SSLVerifyClient require
SSLVerifyDepth  5
...
<Location />
SSLRequire (    %{SSL_CLIENT_S_DN_O} eq "Develop" \
            and %{SSL_CLIENT_S_DN_OU} in {"Staff", "Operations", "Dev"} )
</Location>
...
SSLOptions +FakeBasicAuth +StrictRequire

この構成ファイルで多くの組み合わせを試したところ、「SSLPeerUnverifiedException:ピア証明書がありません」という例外が発生し、すべて同じ結果に終わりました。私はサーバーのSSL構成ファイルでこの行をコメント化し、すべてがうまく機能しますが、サーバーはすべてのクライアントを受け入れますが、これは私が必要としているものではありません。

前もって感謝します :)

更新

@EJPの答えがトリックをしました

最初に、証明書を正しい(/ etc / pki / tls / certs /)パスに追加し、次を使用してロードする必要がありました:証明書の名前を変更します:mv ca-andr.pem ca-andr.crtそして、証明書をロードします:

 ln -s ca-andr.crt $( openssl x509 -hash -noout -in ca-andr.crt )".0"

これにより、「f3f24175.0」のような名前のopenSSLで読み取り可能なシンボリックリンクが作成されます

次に、新しい証明書ファイルを/etc/httpd/conf.d/ssl.conf構成ファイルに設定します。

…
SSLCACertificateFile /etc/pki/tls/certs/f2f62175.0
…

次にhttpサービスを再起動し、証明書がロードされているかどうかをテストします。

openssl verify -CApath /etc/pki/tls/certs/ f2f62175.0

すべて問題なければ、次のように表示されます。

f3f24175.0:OK

そして、あなたはテストを終了することができます:

openssl s_client -connect example.com:443 -CApath /etc/pki/tls/certs

これにより、信頼できるクライアント証明書のリストが返されます(追加した証明書が表示されている場合は、機能しています)

問題の2番目の部分は、authclientcerts.BKSに秘密鍵が含まれていないため、指定したパスワードが使用されず、サーバーが証明書を認証しないことでした。そこで、キーと証明書をpkcs12にエクスポートし、それに応じてJAVAコードを更新しました。

エクスポートコマンド:

openssl pkcs12 -export -in ~/cert.pem -inkey ~/key.pem > android_client_p12.p12

次に、SecureHttpClient.javaクラスの部分を変更して、BKSではなくPKCS12でクライアント証明書を作成しました。

鍵ストアのタイプをBKSからPKCS12 I Replacedに変更するには:

final KeyStore clientCert = KeyStore.getInstance("BKS”);

このため:

final KeyStore clientCert = KeyStore.getInstance("PKCS12");

次に、res / raw /にある実際のキーストアファイルへの参照を更新しました。

final InputStream client_inputStream = appContext.getResources().openRawResource(R.raw.authclientcerts);

このため:

final InputStream client_inputStream = appContext.getResources().openRawResource(R.raw.android_client_p12);

そしてそれはトリックをしました:D

ローン侯爵:

サーバーがクライアント証明書を要求すると、署名された証明書を受け入れるCAのリストが提供されます。クライアントのいずれかに署名された証明書がない場合、クライアントは応答として証明書を送信しません。サーバーがクライアント証明書を要求するように構成されている場合は、クライアント証明書を要求するだけではなく、接続を閉じます。

したがって、サーバーのトラストストアに受け入れられる証明書がクライアントにあることを確認してください。

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

TOP 一覧

  1. 1

    Python / SciPyのピーク検出アルゴリズム

  2. 2

    セレンのモデルダイアログからテキストを抽出するにはどうすればよいですか?

  3. 3

    tkinterウィンドウを閉じてもPythonプログラムが終了しない

  4. 4

    androidsoongビルドシステムによるネイティブコードカバレッジ

  5. 5

    ZScalerと証明書の問題により、Dockerを使用できません

  6. 6

    Reactでclsxを使用する方法

  7. 7

    VisualStudioコードの特異点/ドッカー画像でPythonインタープリターを使用するにはどうすればよいですか?

  8. 8

    二次導関数を数値計算するときの大きな誤差

  9. 9

    Ansibleで複数行のシェルスクリプトを実行する方法

  10. 10

    STSでループプロセス「クラスパス通知の送信」のループを停止する方法

  11. 11

    ビュー用にサイズ変更した後の画像の高さと幅を取得する方法

  12. 12

    Three.js indexed BufferGeometry vs. InstancedBufferGeometry

  13. 13

    __init__。pyファイルの整理中に循環インポートエラーが発生しました

  14. 14

    三項演算子良い練習の代わりとしてOptional.ofNullableを使用していますか?

  15. 15

    エンティティIDを含む@RequestBody属性をSpringの対応するエンティティに変換します

  16. 16

    Spring Boot Filter is not getting invoked if remove @component in fitler class

  17. 17

    値間の一致を見つける最も簡単な方法は何ですか

  18. 18

    reCAPTCHA-エラーコード:ユーザーの応答を検証するときの「missing-input-response」、「missing-input-secret」(POSTの詳細がない)

  19. 19

    Rパッケージ「AppliedPredictiveModeling」のインストール中にエラーが発生しました

  20. 20

    画像変更コードを実行してもボタンの画像が変更されない

  21. 21

    好き/愛の関係のためのデータベース設計

ホットタグ

アーカイブ