Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(728)

Side by Side Diff: components/cronet/android/api/src/org/chromium/net/CronetEngine.java

Issue 1407263010: [Cronet] Public key pinning for Java API (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Hostname conversion to ASCII and IPv4-like hostname validation Created 5 years, 1 month ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2015 The Chromium Authors. All rights reserved. 1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 package org.chromium.net; 5 package org.chromium.net;
6 6
7 import android.content.Context; 7 import android.content.Context;
8 import android.support.annotation.IntDef; 8 import android.support.annotation.IntDef;
9 import android.util.Base64;
9 import android.util.Log; 10 import android.util.Log;
10 11
11 import org.json.JSONArray; 12 import org.json.JSONArray;
12 import org.json.JSONException; 13 import org.json.JSONException;
13 import org.json.JSONObject; 14 import org.json.JSONObject;
14 15
15 import java.io.File; 16 import java.io.File;
16 import java.lang.annotation.Retention; 17 import java.lang.annotation.Retention;
17 import java.lang.annotation.RetentionPolicy; 18 import java.lang.annotation.RetentionPolicy;
18 import java.lang.reflect.Constructor; 19 import java.lang.reflect.Constructor;
20 import java.net.IDN;
19 import java.net.Proxy; 21 import java.net.Proxy;
20 import java.net.URL; 22 import java.net.URL;
21 import java.net.URLConnection; 23 import java.net.URLConnection;
22 import java.net.URLStreamHandlerFactory; 24 import java.net.URLStreamHandlerFactory;
25 import java.util.Collection;
26 import java.util.Date;
27 import java.util.HashSet;
23 import java.util.List; 28 import java.util.List;
24 import java.util.Map; 29 import java.util.Map;
30 import java.util.Set;
25 import java.util.concurrent.Executor; 31 import java.util.concurrent.Executor;
32 import java.util.regex.Pattern;
26 33
27 /** 34 /**
28 * An engine to process {@link UrlRequest}s, which uses the best HTTP stack 35 * An engine to process {@link UrlRequest}s, which uses the best HTTP stack
29 * available on the current platform. 36 * available on the current platform.
30 */ 37 */
31 public abstract class CronetEngine { 38 public abstract class CronetEngine {
32 /** 39 /**
33 * A builder for {@link CronetEngine}s, which allows runtime configuration o f 40 * A builder for {@link CronetEngine}s, which allows runtime configuration o f
34 * {@code CronetEngine}. Configuration options are set on the builder and 41 * {@code CronetEngine}. Configuration options are set on the builder and
35 * then {@link #build} is called to create the {@code CronetEngine}. 42 * then {@link #build} is called to create the {@code CronetEngine}.
36 */ 43 */
37 public static class Builder { 44 public static class Builder {
45 private static final Pattern INVALID_PKP_HOST_NAME = Pattern.compile("^[ 0-9\\.]*$");
46
38 private final JSONObject mConfig; 47 private final JSONObject mConfig;
39 private final Context mContext; 48 private final Context mContext;
40 49
41 /** 50 /**
42 * Default config enables SPDY, disables QUIC, SDCH and HTTP cache. 51 * Default config enables SPDY, disables QUIC, SDCH and HTTP cache.
43 * @param context Android {@link Context} for engine to use. 52 * @param context Android {@link Context} for engine to use.
44 */ 53 */
45 public Builder(Context context) { 54 public Builder(Context context) {
46 mConfig = new JSONObject(); 55 mConfig = new JSONObject();
47 mContext = context; 56 mContext = context;
(...skipping 248 matching lines...) Expand 10 before | Expand all | Expand 10 after
296 hint.put(CronetEngineBuilderList.QUIC_HINT_PORT, port); 305 hint.put(CronetEngineBuilderList.QUIC_HINT_PORT, port);
297 hint.put(CronetEngineBuilderList.QUIC_HINT_ALT_PORT, alternatePo rt); 306 hint.put(CronetEngineBuilderList.QUIC_HINT_ALT_PORT, alternatePo rt);
298 quicHints.put(hint); 307 quicHints.put(hint);
299 } catch (JSONException e) { 308 } catch (JSONException e) {
300 // Intentionally do nothing. 309 // Intentionally do nothing.
301 } 310 }
302 return this; 311 return this;
303 } 312 }
304 313
305 /** 314 /**
315 * Adds public key pins for a given host.
316 *
317 * @param hostName name of the host to which the public keys should be p inned. A host that
318 * consists of digits and the dot character only is trea ted as invalid.
319 * @param pinsSha256 a collection of pins. Each pin is the SHA-256 crypt ographic
320 * hash of DER-encoded ASN.1 representation of Subject Public
321 * Key Info (SPKI) of the host X.509 certificate. Use
322 * {@link java.security.cert.Certificate#getPublicKey( )
323 * Certificate.getPublicKey} and
324 * {@link java.security.Key#getEncoded() Key.getEncode d}
325 * to obtain DER-encoded ASN.1 representation of SPKI.
326 * @param includeSubdomains indicates whether the pinning policy should be applied to
327 * subdomains of {@code hostName}.
328 * @param expirationDate specifies the expiration date for the pins.
329 * @return the builder to facilitate chaining.
330 * @throws NullPointerException if one of the input parameters is null.
331 * @throws IllegalArgumentException if the given host name is invalid or the
332 * {@code pinsSha256} collection contai ns a byte array
333 * that does not represent a valid SHA- 256 hash.
334 */
335 public Builder addPublicKeyPins(String hostName, Collection<byte[]> pins Sha256,
336 boolean includeSubdomains, Date expirationDate) {
337 if (hostName == null) {
338 throw new NullPointerException("The hostname cannot be null");
339 }
340 if (pinsSha256 == null) {
341 throw new NullPointerException("The collection of SHA256 pins ca nnot be null");
342 }
343 String idnHostName = validateHostNameForPinningAndConvert(hostName);
344 try {
345 // Add PKP_LIST JSON array element if it is not present.
346 JSONArray pkpList = mConfig.optJSONArray(CronetEngineBuilderList .PKP_LIST);
347 if (pkpList == null) {
348 pkpList = new JSONArray();
349 mConfig.put(CronetEngineBuilderList.PKP_LIST, pkpList);
350 }
351
352 // Convert the pin to BASE64 encoding.
353 Set<String> hashes = new HashSet<>(pinsSha256.size());
354 for (byte[] pinSha256 : pinsSha256) {
355 hashes.add(convertSha256ToBase64WithPrefix(pinSha256));
356 }
357
358 // Add new element to PKP_LIST JSON array.
359 JSONObject pkp = new JSONObject();
360 pkp.put(CronetEngineBuilderList.PKP_HOST, idnHostName);
361 pkp.put(CronetEngineBuilderList.PKP_PIN_HASHES, new JSONArray(ha shes));
362 pkp.put(CronetEngineBuilderList.PKP_INCLUDE_SUBDOMAINS, includeS ubdomains);
363 // The expiration time is passed as a double, in seconds since J anuary 1, 1970.
364 pkp.put(CronetEngineBuilderList.PKP_EXPIRATION_DATE,
365 (double) expirationDate.getTime() / 1000);
366 pkpList.put(pkp);
367 } catch (JSONException e) {
368 // This exception should never happen.
369 throw new RuntimeException(
370 "Failed to add pubic key pins with the given arguments", e);
371 }
372 return this;
373 }
374
375 /**
376 * Converts a given SHA256 array of bytes to BASE64 encoded string and p repends
377 * {@code sha256/} prefix to it. The format corresponds to the format th at is expected by
378 * {@code net::HashValue} class.
379 *
380 * @param sha256 SHA256 bytes to convert to BASE64.
381 * @return the BASE64 encoded SHA256 with the prefix.
382 * @throws IllegalArgumentException if the provided pin is invalid.
383 */
384 private static String convertSha256ToBase64WithPrefix(byte[] sha256) {
385 if (sha256 == null || sha256.length != 32) {
386 throw new IllegalArgumentException("Public key pin is invalid");
387 }
388 return "sha256/" + Base64.encodeToString(sha256, Base64.NO_WRAP);
389 }
390
391 /**
392 * Checks whether a given string represents a valid host name for PKP an d converts it
393 * to ASCII Compatible Encoding representation according to RFC 1122, RF C 1123 and
394 * RFC 3490. This method is more restrictive than required by RFC 7469. Thus, a host
395 * that contains digits and the dot character only is considered invalid .
396 *
397 * Note: Currently Cronet doesn't have native implementation of host nam e validation that
398 * can be used. There is code that parses a provided URL but doesn 't ensure its
399 * correctness. The implementation relies on {@code getaddrinfo} f unction.
400 *
401 * @see <a href="https://tools.ietf.org/html/rfc7469#section-2.3.3>RFC 7 469</a>
402 * @param hostName host name to check and convert.
403 * @return true if the string is a valid host name.
404 * @throws IllegalArgumentException if the the given string does not rep resent a valid
405 * hostname.
406 */
407 private static String validateHostNameForPinningAndConvert(String hostNa me)
408 throws IllegalArgumentException {
409 if (INVALID_PKP_HOST_NAME.matcher(hostName).matches()) {
mef 2015/11/23 19:45:37 Is this enough to cover testHostNameArgumentValida
kapishnikov 2015/11/23 21:13:35 INVALID_PKP_HOST_NAME matcher discards host names
mef 2015/11/30 18:02:49 Cool!
410 throw new IllegalArgumentException("Hostname " + hostName + " is illegal."
411 + " A hostname should not consist of digits and/or dots only.");
412 }
413 try {
414 return IDN.toASCII(hostName, IDN.USE_STD3_ASCII_RULES);
415 } catch (IllegalArgumentException ex) {
416 throw new IllegalArgumentException("Hostname " + hostName + " is illegal."
417 + " The name of the host does not comply with RFC 1122 a nd RFC 1123.");
418 }
419 }
420
421 /**
306 * Sets experimental options to be used in Cronet. 422 * Sets experimental options to be used in Cronet.
307 * 423 *
308 * @param options JSON formatted experimental options. 424 * @param options JSON formatted experimental options.
309 * @return the builder to facilitate chaining. 425 * @return the builder to facilitate chaining.
310 */ 426 */
311 public Builder setExperimentalOptions(String options) { 427 public Builder setExperimentalOptions(String options) {
312 return putString(CronetEngineBuilderList.EXPERIMENTAL_OPTIONS, optio ns); 428 return putString(CronetEngineBuilderList.EXPERIMENTAL_OPTIONS, optio ns);
313 } 429 }
314 430
315 /** 431 /**
(...skipping 370 matching lines...) Expand 10 before | Expand all | Expand 10 after
686 cronetEngine = possibleEngine; 802 cronetEngine = possibleEngine;
687 } 803 }
688 } catch (ClassNotFoundException e) { 804 } catch (ClassNotFoundException e) {
689 // Leave as null. 805 // Leave as null.
690 } catch (Exception e) { 806 } catch (Exception e) {
691 throw new IllegalStateException("Cannot instantiate: " + CRONET_URL_ REQUEST_CONTEXT, e); 807 throw new IllegalStateException("Cannot instantiate: " + CRONET_URL_ REQUEST_CONTEXT, e);
692 } 808 }
693 return cronetEngine; 809 return cronetEngine;
694 } 810 }
695 } 811 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698