Android上SSL双向认证失败,客户端接受服务器证书但服务器未收到客户端证书。

6
我正在尝试在Linux服务器和Android APP之间建立双向认证SSL。到目前为止,我已经成功让应用程序通过SSL与服务器证书通信,但一旦我将服务器设置为仅接受客户端证书,它就无法正常工作。服务器配置似乎没问题,但我有些困惑。我最好的猜测是客户端证书没有正确地呈现给服务器,但不知道该如何进行下一步测试。我尝试在我的OS X钥匙链中使用客户端的.pem文件,但浏览器似乎无法使用该证书。然而,服务器证书完美地工作,因为我可以实现https连接并且应用程序接受我的未签名服务器证书。

我正在使用各种教程和答案的组合代码,这是我收藏的主要内容:

这是我使用的两个主要类用于连接: 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;

    }
}

这个第二个类处理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 [command]

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

为了获取 Android BKS 密钥,我使用了位于 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

最后,在Fedora 19中,我添加到/etc/httpd/conf.d/ssl.conf的行用于要求客户端证书并检查证书的有效性(与我创建的客户端证书匹配):

...
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: No peer certificate"异常。我注释掉了服务器的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

这应该返回受信任的客户端证书列表(如果您看到添加的证书,则有效)

现在问题的第二部分是我的authclientcerts.BKS没有包含私钥,因此我提供的密码从未被使用,服务器无法验证证书。因此,我将我的密钥和证书导出为pkcs12,并相应地更新了JAVA代码。

导出命令:

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

然后我更改了SecureHttpClient.java类的部分内容,使用PKCS12来创建客户端证书,而不是BKS。

要将密钥库类型从BKS更改为PKCS12, 我替换了:

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

1个回答

4
当服务器要求客户端提供证书时,它会提供一个可接受的CA证书列表。如果客户端没有受任何一个CA签名的证书,那么就不会回复证书。如果服务器被配置为需要客户端证书而非只是想要一个,那么它将关闭连接。
因此,确保客户端拥有一个对服务器信任库可接受的证书。

1
谢谢你的回答,解决了我的问题。我成功地使用双向认证将Android应用程序与服务器连接起来。非常感谢你抽出时间来回答我的问题。我稍后会添加一个更新,包含完整的解决方案以及我需要进行的修正和补充。 - jmarrero

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接