1// Copyright (c) 2013 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "chrome/browser/ui/android/ssl_client_certificate_request.h"
6
7#include "base/android/jni_array.h"
8#include "base/android/jni_string.h"
9#include "base/android/scoped_java_ref.h"
10#include "base/basictypes.h"
11#include "base/bind.h"
12#include "base/callback_helpers.h"
13#include "base/compiler_specific.h"
14#include "base/logging.h"
15#include "chrome/browser/ssl/ssl_client_certificate_selector.h"
16#include "chrome/browser/ui/android/window_android_helper.h"
17#include "content/public/browser/browser_thread.h"
18#include "crypto/scoped_openssl_types.h"
19#include "jni/SSLClientCertificateRequest_jni.h"
20#include "net/android/keystore_openssl.h"
21#include "net/base/host_port_pair.h"
22#include "net/cert/cert_database.h"
23#include "net/cert/x509_certificate.h"
24#include "net/ssl/openssl_client_key_store.h"
25#include "net/ssl/ssl_cert_request_info.h"
26#include "net/ssl/ssl_client_cert_type.h"
27#include "ui/base/android/window_android.h"
28
29
30namespace chrome {
31
32namespace {
33
34// Must be called on the I/O thread to record a client certificate
35// and its private key in the OpenSSLClientKeyStore.
36void RecordClientCertificateKey(
37    const scoped_refptr<net::X509Certificate>& client_cert,
38    crypto::ScopedEVP_PKEY private_key) {
39  DCHECK_CURRENTLY_ON(content::BrowserThread::IO);
40  net::OpenSSLClientKeyStore::GetInstance()->RecordClientCertPrivateKey(
41      client_cert.get(), private_key.get());
42}
43
44void StartClientCertificateRequest(
45    const net::SSLCertRequestInfo* cert_request_info,
46    ui::WindowAndroid* window,
47    const chrome::SelectCertificateCallback& callback) {
48  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
49
50  // Ensure that callback(NULL) is posted as a task on the UI thread
51  // in case of an error.
52  base::Closure post_task_closure = base::Bind(
53      base::IgnoreResult(&content::BrowserThread::PostTask),
54      content::BrowserThread::UI,
55      FROM_HERE,
56      base::Bind(callback, scoped_refptr<net::X509Certificate>()));
57
58  base::ScopedClosureRunner guard(post_task_closure);
59
60  // Build the |key_types| JNI parameter, as a String[]
61  std::vector<std::string> key_types;
62  for (size_t n = 0; n < cert_request_info->cert_key_types.size(); ++n) {
63    switch (cert_request_info->cert_key_types[n]) {
64      case net::CLIENT_CERT_RSA_SIGN:
65        key_types.push_back("RSA");
66        break;
67      case net::CLIENT_CERT_DSS_SIGN:
68        key_types.push_back("DSA");
69        break;
70      case net::CLIENT_CERT_ECDSA_SIGN:
71        key_types.push_back("ECDSA");
72        break;
73      default:
74        // Ignore unknown types.
75        break;
76    }
77  }
78
79  JNIEnv* env = base::android::AttachCurrentThread();
80  ScopedJavaLocalRef<jobjectArray> key_types_ref =
81      base::android::ToJavaArrayOfStrings(env, key_types);
82  if (key_types_ref.is_null()) {
83    LOG(ERROR) << "Could not create key types array (String[])";
84    return;
85  }
86
87  // Build the |encoded_principals| JNI parameter, as a byte[][]
88  ScopedJavaLocalRef<jobjectArray> principals_ref =
89      base::android::ToJavaArrayOfByteArray(
90          env, cert_request_info->cert_authorities);
91  if (principals_ref.is_null()) {
92    LOG(ERROR) << "Could not create principals array (byte[][])";
93    return;
94  }
95
96  // Build the |host_name| and |port| JNI parameters, as a String and
97  // a jint.
98  ScopedJavaLocalRef<jstring> host_name_ref =
99      base::android::ConvertUTF8ToJavaString(
100          env, cert_request_info->host_and_port.host());
101
102  // Create a copy of the callback on the heap so that its address
103  // and ownership can be passed through and returned from Java via JNI.
104  scoped_ptr<chrome::SelectCertificateCallback> request(
105      new chrome::SelectCertificateCallback(callback));
106
107  jlong request_id = reinterpret_cast<intptr_t>(request.get());
108
109  if (!chrome::android::
110      Java_SSLClientCertificateRequest_selectClientCertificate(
111          env,
112          request_id,
113          window->GetJavaObject().obj(),
114          key_types_ref.obj(),
115          principals_ref.obj(),
116          host_name_ref.obj(),
117          cert_request_info->host_and_port.port())) {
118    return;
119  }
120
121  ignore_result(guard.Release());
122
123  // Ownership was transferred to Java.
124  chrome::SelectCertificateCallback* ALLOW_UNUSED dummy =
125      request.release();
126}
127
128}  // namespace
129
130namespace android {
131
132// Called from JNI on request completion/result.
133// |env| is the current thread's JNIEnv.
134// |clazz| is the SSLClientCertificateRequest JNI class reference.
135// |request_id| is the id passed to
136// Java_SSLClientCertificateRequest_selectClientCertificate() in Start().
137// |encoded_chain_ref| is a JNI reference to a Java array of byte arrays,
138// each item holding a DER-encoded X.509 certificate.
139// |private_key_ref| is the platform PrivateKey object JNI reference for
140// the client certificate.
141// Note: both |encoded_chain_ref| and |private_key_ref| will be NULL if
142// the user didn't select a certificate.
143static void OnSystemRequestCompletion(
144    JNIEnv* env,
145    jclass clazz,
146    jlong request_id,
147    jobjectArray encoded_chain_ref,
148    jobject private_key_ref) {
149  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
150
151  // Take back ownership of the request object.
152  scoped_ptr<chrome::SelectCertificateCallback> callback(
153      reinterpret_cast<chrome::SelectCertificateCallback*>(request_id));
154
155  // Ensure that callback(NULL) is called in case of an error.
156  base::Closure null_closure =
157      base::Bind(*callback, scoped_refptr<net::X509Certificate>());
158
159  base::ScopedClosureRunner guard(null_closure);
160
161  if (encoded_chain_ref == NULL || private_key_ref == NULL) {
162    LOG(ERROR) << "Client certificate request cancelled";
163    return;
164  }
165
166  // Convert the encoded chain to a vector of strings.
167  std::vector<std::string> encoded_chain_strings;
168  if (encoded_chain_ref) {
169    base::android::JavaArrayOfByteArrayToStringVector(
170        env, encoded_chain_ref, &encoded_chain_strings);
171  }
172
173  std::vector<base::StringPiece> encoded_chain;
174  for (size_t n = 0; n < encoded_chain_strings.size(); ++n)
175    encoded_chain.push_back(encoded_chain_strings[n]);
176
177  // Create the X509Certificate object from the encoded chain.
178  scoped_refptr<net::X509Certificate> client_cert(
179      net::X509Certificate::CreateFromDERCertChain(encoded_chain));
180  if (!client_cert.get()) {
181    LOG(ERROR) << "Could not decode client certificate chain";
182    return;
183  }
184
185  // Create an EVP_PKEY wrapper for the private key JNI reference.
186  crypto::ScopedEVP_PKEY private_key(
187      net::android::GetOpenSSLPrivateKeyWrapper(private_key_ref));
188  if (!private_key.get()) {
189    LOG(ERROR) << "Could not create OpenSSL wrapper for private key";
190    return;
191  }
192
193  ignore_result(guard.Release());
194
195  // RecordClientCertificateKey() must be called on the I/O thread,
196  // before the callback is called with the selected certificate on
197  // the UI thread.
198  content::BrowserThread::PostTaskAndReply(
199      content::BrowserThread::IO,
200      FROM_HERE,
201      base::Bind(&RecordClientCertificateKey,
202                 client_cert,
203                 base::Passed(&private_key)),
204      base::Bind(*callback, client_cert));
205}
206
207static void NotifyClientCertificatesChanged() {
208  net::CertDatabase::GetInstance()->OnAndroidKeyStoreChanged();
209}
210
211static void NotifyClientCertificatesChangedOnIOThread(JNIEnv* env, jclass) {
212  if (content::BrowserThread::CurrentlyOn(content::BrowserThread::IO)) {
213    NotifyClientCertificatesChanged();
214  } else {
215    content::BrowserThread::PostTask(
216         content::BrowserThread::IO,
217         FROM_HERE,
218         base::Bind(&NotifyClientCertificatesChanged));
219  }
220}
221
222bool RegisterSSLClientCertificateRequestAndroid(JNIEnv* env) {
223  return RegisterNativesImpl(env);
224}
225
226}  // namespace android
227
228void ShowSSLClientCertificateSelector(
229    content::WebContents* contents,
230    const net::HttpNetworkSession* network_session,
231    net::SSLCertRequestInfo* cert_request_info,
232    const chrome::SelectCertificateCallback& callback) {
233  ui::WindowAndroid* window =
234      WindowAndroidHelper::FromWebContents(contents)->GetWindowAndroid();
235  DCHECK(window);
236  DCHECK_CURRENTLY_ON(content::BrowserThread::UI);
237  StartClientCertificateRequest(cert_request_info, window, callback);
238}
239
240}  // namespace chrome
241