mobile/android/base/sync/net/HawkAuthHeaderProvider.java

Wed, 31 Dec 2014 06:09:35 +0100

author
Michael Schloh von Bennewitz <michael@schloh.com>
date
Wed, 31 Dec 2014 06:09:35 +0100
changeset 0
6474c204b198
permissions
-rw-r--r--

Cloned upstream origin tor-browser at tor-browser-31.3.0esr-4.5-1-build1
revision ID fc1c9ff7c1b2defdbc039f12214767608f46423f for hacking purpose.

michael@0 1 /* This Source Code Form is subject to the terms of the Mozilla Public
michael@0 2 * License, v. 2.0. If a copy of the MPL was not distributed with this
michael@0 3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
michael@0 4
michael@0 5 package org.mozilla.gecko.sync.net;
michael@0 6
michael@0 7 import java.io.IOException;
michael@0 8 import java.io.InputStream;
michael@0 9 import java.io.UnsupportedEncodingException;
michael@0 10 import java.net.URI;
michael@0 11 import java.security.GeneralSecurityException;
michael@0 12 import java.security.InvalidKeyException;
michael@0 13 import java.security.MessageDigest;
michael@0 14 import java.security.NoSuchAlgorithmException;
michael@0 15 import java.util.Locale;
michael@0 16
michael@0 17 import javax.crypto.Mac;
michael@0 18 import javax.crypto.spec.SecretKeySpec;
michael@0 19
michael@0 20 import org.mozilla.apache.commons.codec.binary.Base64;
michael@0 21 import org.mozilla.gecko.background.common.log.Logger;
michael@0 22 import org.mozilla.gecko.sync.Utils;
michael@0 23
michael@0 24 import ch.boye.httpclientandroidlib.Header;
michael@0 25 import ch.boye.httpclientandroidlib.HttpEntity;
michael@0 26 import ch.boye.httpclientandroidlib.HttpEntityEnclosingRequest;
michael@0 27 import ch.boye.httpclientandroidlib.client.methods.HttpRequestBase;
michael@0 28 import ch.boye.httpclientandroidlib.client.methods.HttpUriRequest;
michael@0 29 import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient;
michael@0 30 import ch.boye.httpclientandroidlib.message.BasicHeader;
michael@0 31 import ch.boye.httpclientandroidlib.protocol.BasicHttpContext;
michael@0 32
michael@0 33 /**
michael@0 34 * An <code>AuthHeaderProvider</code> that returns an Authorization header for
michael@0 35 * Hawk: <a href="https://github.com/hueniverse/hawk">https://github.com/hueniverse/hawk</a>.
michael@0 36 *
michael@0 37 * Hawk is an HTTP authentication scheme using a message authentication code
michael@0 38 * (MAC) algorithm to provide partial HTTP request cryptographic verification.
michael@0 39 * Hawk is the successor to the HMAC authentication scheme.
michael@0 40 */
michael@0 41 public class HawkAuthHeaderProvider implements AuthHeaderProvider {
michael@0 42 public static final String LOG_TAG = HawkAuthHeaderProvider.class.getSimpleName();
michael@0 43
michael@0 44 public static final int HAWK_HEADER_VERSION = 1;
michael@0 45
michael@0 46 protected static final int NONCE_LENGTH_IN_BYTES = 8;
michael@0 47 protected static final String HMAC_SHA256_ALGORITHM = "hmacSHA256";
michael@0 48
michael@0 49 protected final String id;
michael@0 50 protected final byte[] key;
michael@0 51 protected final boolean includePayloadHash;
michael@0 52 protected final long skewSeconds;
michael@0 53
michael@0 54 /**
michael@0 55 * Create a Hawk Authorization header provider.
michael@0 56 * <p>
michael@0 57 * Hawk specifies no mechanism by which a client receives an
michael@0 58 * identifier-and-key pair from the server.
michael@0 59 * <p>
michael@0 60 * Hawk requests can include a payload verification hash with requests that
michael@0 61 * enclose an entity (PATCH, POST, and PUT requests). <b>You should default
michael@0 62 * to including the payload verification hash<b> unless you have a good reason
michael@0 63 * not to -- the server can always ignore payload verification hashes provided
michael@0 64 * by the client.
michael@0 65 *
michael@0 66 * @param id
michael@0 67 * to name requests with.
michael@0 68 * @param key
michael@0 69 * to sign request with.
michael@0 70 *
michael@0 71 * @param includePayloadHash
michael@0 72 * true if payload verification hash should be included in signed
michael@0 73 * request header. See <a href="https://github.com/hueniverse/hawk#payload-validation">https://github.com/hueniverse/hawk#payload-validation</a>.
michael@0 74 *
michael@0 75 * @param skewSeconds
michael@0 76 * a number of seconds by which to skew the current time when
michael@0 77 * computing a header.
michael@0 78 */
michael@0 79 public HawkAuthHeaderProvider(String id, byte[] key, boolean includePayloadHash, long skewSeconds) {
michael@0 80 if (id == null) {
michael@0 81 throw new IllegalArgumentException("id must not be null");
michael@0 82 }
michael@0 83 if (key == null) {
michael@0 84 throw new IllegalArgumentException("key must not be null");
michael@0 85 }
michael@0 86 this.id = id;
michael@0 87 this.key = key;
michael@0 88 this.includePayloadHash = includePayloadHash;
michael@0 89 this.skewSeconds = skewSeconds;
michael@0 90 }
michael@0 91
michael@0 92 /**
michael@0 93 * @return the current time in milliseconds.
michael@0 94 */
michael@0 95 @SuppressWarnings("static-method")
michael@0 96 protected long now() {
michael@0 97 return System.currentTimeMillis();
michael@0 98 }
michael@0 99
michael@0 100 /**
michael@0 101 * @return the current time in seconds, adjusted for skew. This should
michael@0 102 * approximate the server's timestamp.
michael@0 103 */
michael@0 104 protected long getTimestampSeconds() {
michael@0 105 return (now() / 1000) + skewSeconds;
michael@0 106 }
michael@0 107
michael@0 108 @Override
michael@0 109 public Header getAuthHeader(HttpRequestBase request, BasicHttpContext context, DefaultHttpClient client) throws GeneralSecurityException {
michael@0 110 long timestamp = getTimestampSeconds();
michael@0 111 String nonce = Base64.encodeBase64String(Utils.generateRandomBytes(NONCE_LENGTH_IN_BYTES));
michael@0 112 String extra = "";
michael@0 113
michael@0 114 try {
michael@0 115 return getAuthHeader(request, context, client, timestamp, nonce, extra, this.includePayloadHash);
michael@0 116 } catch (Exception e) {
michael@0 117 // We lie a little and make every exception a GeneralSecurityException.
michael@0 118 throw new GeneralSecurityException(e);
michael@0 119 }
michael@0 120 }
michael@0 121
michael@0 122 /**
michael@0 123 * Helper function that generates an HTTP Authorization: Hawk header given
michael@0 124 * additional Hawk specific data.
michael@0 125 *
michael@0 126 * @throws NoSuchAlgorithmException
michael@0 127 * @throws InvalidKeyException
michael@0 128 * @throws IOException
michael@0 129 */
michael@0 130 protected Header getAuthHeader(HttpRequestBase request, BasicHttpContext context, DefaultHttpClient client,
michael@0 131 long timestamp, String nonce, String extra, boolean includePayloadHash)
michael@0 132 throws InvalidKeyException, NoSuchAlgorithmException, IOException {
michael@0 133 if (timestamp < 0) {
michael@0 134 throw new IllegalArgumentException("timestamp must contain only [0-9].");
michael@0 135 }
michael@0 136
michael@0 137 if (nonce == null) {
michael@0 138 throw new IllegalArgumentException("nonce must not be null.");
michael@0 139 }
michael@0 140 if (nonce.length() == 0) {
michael@0 141 throw new IllegalArgumentException("nonce must not be empty.");
michael@0 142 }
michael@0 143
michael@0 144 String payloadHash = null;
michael@0 145 if (includePayloadHash) {
michael@0 146 payloadHash = getPayloadHashString(request);
michael@0 147 } else {
michael@0 148 Logger.debug(LOG_TAG, "Configured to not include payload hash for this request.");
michael@0 149 }
michael@0 150
michael@0 151 String app = null;
michael@0 152 String dlg = null;
michael@0 153 String requestString = getRequestString(request, "header", timestamp, nonce, payloadHash, extra, app, dlg);
michael@0 154 String macString = getSignature(requestString.getBytes("UTF-8"), this.key);
michael@0 155
michael@0 156 StringBuilder sb = new StringBuilder();
michael@0 157 sb.append("Hawk id=\"");
michael@0 158 sb.append(this.id);
michael@0 159 sb.append("\", ");
michael@0 160 sb.append("ts=\"");
michael@0 161 sb.append(timestamp);
michael@0 162 sb.append("\", ");
michael@0 163 sb.append("nonce=\"");
michael@0 164 sb.append(nonce);
michael@0 165 sb.append("\", ");
michael@0 166 if (payloadHash != null) {
michael@0 167 sb.append("hash=\"");
michael@0 168 sb.append(payloadHash);
michael@0 169 sb.append("\", ");
michael@0 170 }
michael@0 171 if (extra != null && extra.length() > 0) {
michael@0 172 sb.append("ext=\"");
michael@0 173 sb.append(escapeExtraHeaderAttribute(extra));
michael@0 174 sb.append("\", ");
michael@0 175 }
michael@0 176 sb.append("mac=\"");
michael@0 177 sb.append(macString);
michael@0 178 sb.append("\"");
michael@0 179
michael@0 180 return new BasicHeader("Authorization", sb.toString());
michael@0 181 }
michael@0 182
michael@0 183 /**
michael@0 184 * Get the payload verification hash for the given request, if possible.
michael@0 185 * <p>
michael@0 186 * Returns null if the request does not enclose an entity (is not an HTTP
michael@0 187 * PATCH, POST, or PUT). Throws if the payload verification hash cannot be
michael@0 188 * computed.
michael@0 189 *
michael@0 190 * @param request
michael@0 191 * to compute hash for.
michael@0 192 * @return verification hash, or null if the request does not enclose an entity.
michael@0 193 * @throws IllegalArgumentException if the request does not enclose a valid non-null entity.
michael@0 194 * @throws UnsupportedEncodingException
michael@0 195 * @throws NoSuchAlgorithmException
michael@0 196 * @throws IOException
michael@0 197 */
michael@0 198 protected static String getPayloadHashString(HttpRequestBase request)
michael@0 199 throws UnsupportedEncodingException, NoSuchAlgorithmException, IOException, IllegalArgumentException {
michael@0 200 final boolean shouldComputePayloadHash = request instanceof HttpEntityEnclosingRequest;
michael@0 201 if (!shouldComputePayloadHash) {
michael@0 202 Logger.debug(LOG_TAG, "Not computing payload verification hash for non-enclosing request.");
michael@0 203 return null;
michael@0 204 }
michael@0 205 if (!(request instanceof HttpEntityEnclosingRequest)) {
michael@0 206 throw new IllegalArgumentException("Cannot compute payload verification hash for enclosing request without an entity");
michael@0 207 }
michael@0 208 final HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
michael@0 209 if (entity == null) {
michael@0 210 throw new IllegalArgumentException("Cannot compute payload verification hash for enclosing request with a null entity");
michael@0 211 }
michael@0 212 return Base64.encodeBase64String(getPayloadHash(entity));
michael@0 213 }
michael@0 214
michael@0 215 /**
michael@0 216 * Escape the user-provided extra string for the ext="" header attribute.
michael@0 217 * <p>
michael@0 218 * Hawk escapes the header ext="" attribute differently than it does the extra
michael@0 219 * line in the normalized request string.
michael@0 220 * <p>
michael@0 221 * See <a href="https://github.com/hueniverse/hawk/blob/871cc597973110900467bd3dfb84a3c892f678fb/lib/browser.js#L385">https://github.com/hueniverse/hawk/blob/871cc597973110900467bd3dfb84a3c892f678fb/lib/browser.js#L385</a>.
michael@0 222 *
michael@0 223 * @param extra to escape.
michael@0 224 * @return extra escaped for the ext="" header attribute.
michael@0 225 */
michael@0 226 protected static String escapeExtraHeaderAttribute(String extra) {
michael@0 227 return extra.replaceAll("\\\\", "\\\\").replaceAll("\"", "\\\"");
michael@0 228 }
michael@0 229
michael@0 230 /**
michael@0 231 * Escape the user-provided extra string for inserting into the normalized
michael@0 232 * request string.
michael@0 233 * <p>
michael@0 234 * Hawk escapes the header ext="" attribute differently than it does the extra
michael@0 235 * line in the normalized request string.
michael@0 236 * <p>
michael@0 237 * See <a href="https://github.com/hueniverse/hawk/blob/871cc597973110900467bd3dfb84a3c892f678fb/lib/crypto.js#L67">https://github.com/hueniverse/hawk/blob/871cc597973110900467bd3dfb84a3c892f678fb/lib/crypto.js#L67</a>.
michael@0 238 *
michael@0 239 * @param extra to escape.
michael@0 240 * @return extra escaped for the normalized request string.
michael@0 241 */
michael@0 242 protected static String escapeExtraString(String extra) {
michael@0 243 return extra.replaceAll("\\\\", "\\\\").replaceAll("\n", "\\n");
michael@0 244 }
michael@0 245
michael@0 246 /**
michael@0 247 * Return the content type with no parameters (pieces following ;).
michael@0 248 *
michael@0 249 * @param contentTypeHeader to interrogate.
michael@0 250 * @return base content type.
michael@0 251 */
michael@0 252 protected static String getBaseContentType(Header contentTypeHeader) {
michael@0 253 if (contentTypeHeader == null) {
michael@0 254 throw new IllegalArgumentException("contentTypeHeader must not be null.");
michael@0 255 }
michael@0 256 String contentType = contentTypeHeader.getValue();
michael@0 257 if (contentType == null) {
michael@0 258 throw new IllegalArgumentException("contentTypeHeader value must not be null.");
michael@0 259 }
michael@0 260 int index = contentType.indexOf(";");
michael@0 261 if (index < 0) {
michael@0 262 return contentType.trim();
michael@0 263 }
michael@0 264 return contentType.substring(0, index).trim();
michael@0 265 }
michael@0 266
michael@0 267 /**
michael@0 268 * Generate the SHA-256 hash of a normalized Hawk payload generated from an
michael@0 269 * HTTP entity.
michael@0 270 * <p>
michael@0 271 * <b>Warning:</b> the entity <b>must</b> be repeatable. If it is not, this
michael@0 272 * code throws an <code>IllegalArgumentException</code>.
michael@0 273 * <p>
michael@0 274 * This is under-specified; the code here was reverse engineered from the code
michael@0 275 * at
michael@0 276 * <a href="https://github.com/hueniverse/hawk/blob/871cc597973110900467bd3dfb84a3c892f678fb/lib/crypto.js#L81">https://github.com/hueniverse/hawk/blob/871cc597973110900467bd3dfb84a3c892f678fb/lib/crypto.js#L81</a>.
michael@0 277 * @param entity to normalize and hash.
michael@0 278 * @return hash.
michael@0 279 * @throws IllegalArgumentException if entity is not repeatable.
michael@0 280 */
michael@0 281 protected static byte[] getPayloadHash(HttpEntity entity) throws UnsupportedEncodingException, IOException, NoSuchAlgorithmException {
michael@0 282 if (!entity.isRepeatable()) {
michael@0 283 throw new IllegalArgumentException("entity must be repeatable");
michael@0 284 }
michael@0 285 final MessageDigest digest = MessageDigest.getInstance("SHA-256");
michael@0 286 digest.update(("hawk." + HAWK_HEADER_VERSION + ".payload\n").getBytes("UTF-8"));
michael@0 287 digest.update(getBaseContentType(entity.getContentType()).getBytes("UTF-8"));
michael@0 288 digest.update("\n".getBytes("UTF-8"));
michael@0 289 InputStream stream = entity.getContent();
michael@0 290 try {
michael@0 291 int numRead;
michael@0 292 byte[] buffer = new byte[4096];
michael@0 293 while (-1 != (numRead = stream.read(buffer))) {
michael@0 294 if (numRead > 0) {
michael@0 295 digest.update(buffer, 0, numRead);
michael@0 296 }
michael@0 297 }
michael@0 298 digest.update("\n".getBytes("UTF-8")); // Trailing newline is specified by Hawk.
michael@0 299 return digest.digest();
michael@0 300 } finally {
michael@0 301 stream.close();
michael@0 302 }
michael@0 303 }
michael@0 304
michael@0 305 /**
michael@0 306 * Generate a normalized Hawk request string. This is under-specified; the
michael@0 307 * code here was reverse engineered from the code at
michael@0 308 * <a href="https://github.com/hueniverse/hawk/blob/871cc597973110900467bd3dfb84a3c892f678fb/lib/crypto.js#L55">https://github.com/hueniverse/hawk/blob/871cc597973110900467bd3dfb84a3c892f678fb/lib/crypto.js#L55</a>.
michael@0 309 * <p>
michael@0 310 * This method trusts its inputs to be valid.
michael@0 311 */
michael@0 312 protected static String getRequestString(HttpUriRequest request, String type, long timestamp, String nonce, String hash, String extra, String app, String dlg) {
michael@0 313 String method = request.getMethod().toUpperCase(Locale.US);
michael@0 314
michael@0 315 URI uri = request.getURI();
michael@0 316 String host = uri.getHost();
michael@0 317
michael@0 318 String path = uri.getRawPath();
michael@0 319 if (uri.getRawQuery() != null) {
michael@0 320 path += "?";
michael@0 321 path += uri.getRawQuery();
michael@0 322 }
michael@0 323 if (uri.getRawFragment() != null) {
michael@0 324 path += "#";
michael@0 325 path += uri.getRawFragment();
michael@0 326 }
michael@0 327
michael@0 328 int port = uri.getPort();
michael@0 329 String scheme = uri.getScheme();
michael@0 330 if (port != -1) {
michael@0 331 } else if ("http".equalsIgnoreCase(scheme)) {
michael@0 332 port = 80;
michael@0 333 } else if ("https".equalsIgnoreCase(scheme)) {
michael@0 334 port = 443;
michael@0 335 } else {
michael@0 336 throw new IllegalArgumentException("Unsupported URI scheme: " + scheme + ".");
michael@0 337 }
michael@0 338
michael@0 339 StringBuilder sb = new StringBuilder();
michael@0 340 sb.append("hawk.");
michael@0 341 sb.append(HAWK_HEADER_VERSION);
michael@0 342 sb.append('.');
michael@0 343 sb.append(type);
michael@0 344 sb.append('\n');
michael@0 345 sb.append(timestamp);
michael@0 346 sb.append('\n');
michael@0 347 sb.append(nonce);
michael@0 348 sb.append('\n');
michael@0 349 sb.append(method);
michael@0 350 sb.append('\n');
michael@0 351 sb.append(path);
michael@0 352 sb.append('\n');
michael@0 353 sb.append(host);
michael@0 354 sb.append('\n');
michael@0 355 sb.append(port);
michael@0 356 sb.append('\n');
michael@0 357 if (hash != null) {
michael@0 358 sb.append(hash);
michael@0 359 }
michael@0 360 sb.append("\n");
michael@0 361 if (extra != null && extra.length() > 0) {
michael@0 362 sb.append(escapeExtraString(extra));
michael@0 363 }
michael@0 364 sb.append("\n");
michael@0 365 if (app != null) {
michael@0 366 sb.append(app);
michael@0 367 sb.append("\n");
michael@0 368 if (dlg != null) {
michael@0 369 sb.append(dlg);
michael@0 370 }
michael@0 371 sb.append("\n");
michael@0 372 }
michael@0 373
michael@0 374 return sb.toString();
michael@0 375 }
michael@0 376
michael@0 377 protected static byte[] hmacSha256(byte[] message, byte[] key)
michael@0 378 throws NoSuchAlgorithmException, InvalidKeyException {
michael@0 379
michael@0 380 SecretKeySpec keySpec = new SecretKeySpec(key, HMAC_SHA256_ALGORITHM);
michael@0 381
michael@0 382 Mac hasher = Mac.getInstance(HMAC_SHA256_ALGORITHM);
michael@0 383 hasher.init(keySpec);
michael@0 384 hasher.update(message);
michael@0 385
michael@0 386 return hasher.doFinal();
michael@0 387 }
michael@0 388
michael@0 389 /**
michael@0 390 * Sign a Hawk request string.
michael@0 391 *
michael@0 392 * @param requestString to sign.
michael@0 393 * @param key as <code>String</code>.
michael@0 394 * @return signature as base-64 encoded string.
michael@0 395 * @throws InvalidKeyException
michael@0 396 * @throws NoSuchAlgorithmException
michael@0 397 * @throws UnsupportedEncodingException
michael@0 398 */
michael@0 399 protected static String getSignature(byte[] requestString, byte[] key)
michael@0 400 throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
michael@0 401 return Base64.encodeBase64String(hmacSha256(requestString, key));
michael@0 402 }
michael@0 403 }

mercurial