1 /*
   2  * Copyright (c) 2015, 2020, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 
  26 package jdk.internal.net.http.websocket;
  27 
  28 import java.net.http.HttpClient;
  29 import java.net.http.HttpClient.Version;
  30 import java.net.http.HttpHeaders;
  31 import java.net.http.HttpRequest;
  32 import java.net.http.HttpResponse;
  33 import java.net.http.HttpResponse.BodyHandlers;
  34 import java.net.http.WebSocketHandshakeException;
  35 
  36 import jdk.internal.net.http.HttpRequestBuilderImpl;
  37 import jdk.internal.net.http.HttpRequestImpl;
  38 import jdk.internal.net.http.common.MinimalFuture;
  39 import jdk.internal.net.http.common.Pair;
  40 import jdk.internal.net.http.common.Utils;
  41 
  42 import java.io.IOException;
  43 import java.net.InetSocketAddress;
  44 import java.net.Proxy;
  45 import java.net.ProxySelector;
  46 import java.net.URI;
  47 import java.net.URISyntaxException;
  48 import java.net.URLPermission;
  49 import java.nio.charset.StandardCharsets;
  50 import java.security.AccessController;
  51 import java.security.MessageDigest;
  52 import java.security.NoSuchAlgorithmException;
  53 import java.security.PrivilegedAction;
  54 import java.security.SecureRandom;
  55 import java.time.Duration;
  56 import java.util.Base64;
  57 import java.util.Collection;
  58 import java.util.Collections;
  59 import java.util.LinkedHashSet;
  60 import java.util.List;
  61 import java.util.Optional;
  62 import java.util.Set;
  63 import java.util.TreeSet;
  64 import java.util.concurrent.CompletableFuture;
  65 import java.util.stream.Collectors;
  66 import java.util.stream.Stream;
  67 
  68 import static java.lang.String.format;
  69 import static jdk.internal.net.http.common.Utils.isValidName;
  70 import static jdk.internal.net.http.common.Utils.permissionForProxy;
  71 import static jdk.internal.net.http.common.Utils.stringOf;
  72 
  73 public class OpeningHandshake {
  74 
  75     private static final String HEADER_CONNECTION = "Connection";
  76     private static final String HEADER_UPGRADE    = "Upgrade";
  77     private static final String HEADER_ACCEPT     = "Sec-WebSocket-Accept";
  78     private static final String HEADER_EXTENSIONS = "Sec-WebSocket-Extensions";
  79     private static final String HEADER_KEY        = "Sec-WebSocket-Key";
  80     private static final String HEADER_PROTOCOL   = "Sec-WebSocket-Protocol";
  81     private static final String HEADER_VERSION    = "Sec-WebSocket-Version";
  82     private static final String VERSION           = "13";  // WebSocket's lucky number
  83 
  84     private static final Set<String> ILLEGAL_HEADERS;
  85 
  86     static {
  87         ILLEGAL_HEADERS = new TreeSet<>(String.CASE_INSENSITIVE_ORDER);
  88         ILLEGAL_HEADERS.addAll(List.of(HEADER_ACCEPT,
  89                                        HEADER_EXTENSIONS,
  90                                        HEADER_KEY,
  91                                        HEADER_PROTOCOL,
  92                                        HEADER_VERSION));
  93     }
  94 
  95     private static final SecureRandom random = new SecureRandom();
  96 
  97     private final MessageDigest sha1;
  98     private final HttpClient client;
  99 
 100     {
 101         try {
 102             sha1 = MessageDigest.getInstance("SHA-1");
 103         } catch (NoSuchAlgorithmException e) {
 104             // Shouldn't happen: SHA-1 must be available in every Java platform
 105             // implementation
 106             throw new InternalError("Minimum requirements", e);
 107         }
 108     }
 109 
 110     private final HttpRequestImpl request;
 111     private final Collection<String> subprotocols;
 112     private final String nonce;
 113 
 114     public OpeningHandshake(BuilderImpl b) {
 115         checkURI(b.getUri());
 116         Proxy proxy = proxyFor(b.getProxySelector(), b.getUri());
 117         checkPermissions(b, proxy);
 118         this.client = b.getClient();
 119         URI httpURI = createRequestURI(b.getUri());
 120         HttpRequestBuilderImpl requestBuilder = new HttpRequestBuilderImpl(httpURI);
 121         Duration connectTimeout = b.getConnectTimeout();
 122         if (connectTimeout != null) {
 123             requestBuilder.timeout(connectTimeout);
 124         }
 125         for (Pair<String, String> p : b.getHeaders()) {
 126             if (ILLEGAL_HEADERS.contains(p.first)) {
 127                 throw illegal("Illegal header: " + p.first);
 128             }
 129             requestBuilder.header(p.first, p.second);
 130         }
 131         this.subprotocols = createRequestSubprotocols(b.getSubprotocols());
 132         if (!this.subprotocols.isEmpty()) {
 133             String p = String.join(", ", this.subprotocols);
 134             requestBuilder.header(HEADER_PROTOCOL, p);
 135         }
 136         requestBuilder.header(HEADER_VERSION, VERSION);
 137         this.nonce = createNonce();
 138         requestBuilder.header(HEADER_KEY, this.nonce);
 139         // Setting request version to HTTP/1.1 forcibly, since it's not possible
 140         // to upgrade from HTTP/2 to WebSocket (as of August 2016):
 141         //
 142         //     https://tools.ietf.org/html/draft-hirano-httpbis-websocket-over-http2-00
 143         requestBuilder.version(Version.HTTP_1_1).GET();
 144         request = requestBuilder.buildForWebSocket();
 145         request.isWebSocket(true);
 146         Utils.setWebSocketUpgradeHeaders(request);
 147         request.setProxy(proxy);
 148     }
 149 
 150     private static Collection<String> createRequestSubprotocols(
 151             Collection<String> subprotocols)
 152     {
 153         LinkedHashSet<String> sp = new LinkedHashSet<>(subprotocols.size(), 1);
 154         for (String s : subprotocols) {
 155             if (s.trim().isEmpty() || !isValidName(s)) {
 156                 throw illegal("Bad subprotocol syntax: " + s);
 157             }
 158             if (!sp.add(s)) {
 159                 throw illegal("Duplicating subprotocol: " + s);
 160             }
 161         }
 162         return Collections.unmodifiableCollection(sp);
 163     }
 164 
 165     /*
 166      * Checks the given URI for being a WebSocket URI and translates it into a
 167      * target HTTP URI for the Opening Handshake.
 168      *
 169      * https://tools.ietf.org/html/rfc6455#section-3
 170      */
 171     static URI createRequestURI(URI uri) {
 172         String s = uri.getScheme();
 173         assert "ws".equalsIgnoreCase(s) || "wss".equalsIgnoreCase(s);
 174         String scheme = "ws".equalsIgnoreCase(s) ? "http" : "https";
 175         try {
 176             return new URI(scheme,
 177                            uri.getUserInfo(),
 178                            uri.getHost(),
 179                            uri.getPort(),
 180                            uri.getPath(),
 181                            uri.getQuery(),
 182                            null); // No fragment
 183         } catch (URISyntaxException e) {
 184             // Shouldn't happen: URI invariant
 185             throw new InternalError(e);
 186         }
 187     }
 188 
 189     public CompletableFuture<Result> send() {
 190         PrivilegedAction<CompletableFuture<Result>> pa = () ->
 191                 client.sendAsync(this.request, BodyHandlers.discarding())
 192                       .thenCompose(this::resultFrom);
 193         return AccessController.doPrivileged(pa);
 194     }
 195 
 196     /*
 197      * The result of the opening handshake.
 198      */
 199     static final class Result {
 200 
 201         final String subprotocol;
 202         final TransportFactory transport;
 203 
 204         private Result(String subprotocol, TransportFactory transport) {
 205             this.subprotocol = subprotocol;
 206             this.transport = transport;
 207         }
 208     }
 209 
 210     private CompletableFuture<Result> resultFrom(HttpResponse<?> response) {
 211         // Do we need a special treatment for SSLHandshakeException?
 212         // Namely, invoking
 213         //
 214         //     Listener.onClose(StatusCodes.TLS_HANDSHAKE_FAILURE, "")
 215         //
 216         // See https://tools.ietf.org/html/rfc6455#section-7.4.1
 217         Result result = null;
 218         Throwable exception = null;
 219         try {
 220             result = handleResponse(response);
 221         } catch (IOException e) {
 222             exception = e;
 223         } catch (Exception e) {
 224             exception = new WebSocketHandshakeException(response).initCause(e);
 225         } catch (Error e) {
 226             // We should attempt to close the connection and relay
 227             // the error through the completable future even in this
 228             // case.
 229             exception = e;
 230         }
 231         if (exception == null) {
 232             return MinimalFuture.completedFuture(result);
 233         }
 234         try {
 235             // calling this method will close the rawChannel, if created,
 236             // or the connection, if not.
 237             ((RawChannel.Provider) response).closeRawChannel();
 238         } catch (IOException e) {
 239             exception.addSuppressed(e);
 240         }
 241         return MinimalFuture.failedFuture(exception);
 242     }
 243 
 244     private Result handleResponse(HttpResponse<?> response) throws IOException {
 245         // By this point all redirects, authentications, etc. (if any) MUST have
 246         // been done by the HttpClient used by the WebSocket; so only 101 is
 247         // expected
 248         int c = response.statusCode();
 249         if (c != 101) {
 250             throw checkFailed("Unexpected HTTP response status code " + c);
 251         }
 252         HttpHeaders headers = response.headers();
 253         String upgrade = requireSingle(headers, HEADER_UPGRADE);
 254         if (!upgrade.equalsIgnoreCase("websocket")) {
 255             throw checkFailed("Bad response field: " + HEADER_UPGRADE);
 256         }
 257         String connection = requireSingle(headers, HEADER_CONNECTION);
 258         if (!connection.equalsIgnoreCase("Upgrade")) {
 259             throw checkFailed("Bad response field: " + HEADER_CONNECTION);
 260         }
 261         Optional<String> version = requireAtMostOne(headers, HEADER_VERSION);
 262         if (version.isPresent() && !version.get().equals(VERSION)) {
 263             throw checkFailed("Bad response field: " + HEADER_VERSION);
 264         }
 265         requireAbsent(headers, HEADER_EXTENSIONS);
 266         String x = this.nonce + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
 267         this.sha1.update(x.getBytes(StandardCharsets.ISO_8859_1));
 268         String expected = Base64.getEncoder().encodeToString(this.sha1.digest());
 269         String actual = requireSingle(headers, HEADER_ACCEPT);
 270         if (!actual.trim().equals(expected)) {
 271             throw checkFailed("Bad " + HEADER_ACCEPT);
 272         }
 273         String subprotocol = checkAndReturnSubprotocol(headers);
 274         RawChannel channel = ((RawChannel.Provider) response).rawChannel();
 275         return new Result(subprotocol, new TransportFactoryImpl(channel));
 276     }
 277 
 278     private String checkAndReturnSubprotocol(HttpHeaders responseHeaders)
 279             throws CheckFailedException
 280     {
 281         Optional<String> opt = responseHeaders.firstValue(HEADER_PROTOCOL);
 282         if (!opt.isPresent()) {
 283             // If there is no such header in the response, then the server
 284             // doesn't want to use any subprotocol
 285             return "";
 286         }
 287         String s = requireSingle(responseHeaders, HEADER_PROTOCOL);
 288         // An empty string as a subprotocol's name is not allowed by the spec
 289         // and the check below will detect such responses too
 290         if (this.subprotocols.contains(s)) {
 291             return s;
 292         } else {
 293             throw checkFailed("Unexpected subprotocol: " + s);
 294         }
 295     }
 296 
 297     private static void requireAbsent(HttpHeaders responseHeaders,
 298                                       String headerName)
 299     {
 300         List<String> values = responseHeaders.allValues(headerName);
 301         if (!values.isEmpty()) {
 302             throw checkFailed(format("Response field '%s' present: %s",
 303                                      headerName,
 304                                      stringOf(values)));
 305         }
 306     }
 307 
 308     private static Optional<String> requireAtMostOne(HttpHeaders responseHeaders,
 309                                                      String headerName)
 310     {
 311         List<String> values = responseHeaders.allValues(headerName);
 312         if (values.size() > 1) {
 313             throw checkFailed(format("Response field '%s' multivalued: %s",
 314                                      headerName,
 315                                      stringOf(values)));
 316         }
 317         return values.stream().findFirst();
 318     }
 319 
 320     private static String requireSingle(HttpHeaders responseHeaders,
 321                                         String headerName)
 322     {
 323         List<String> values = responseHeaders.allValues(headerName);
 324         if (values.isEmpty()) {
 325             throw checkFailed("Response field missing: " + headerName);
 326         } else if (values.size() > 1) {
 327             throw checkFailed(format("Response field '%s' multivalued: %s",
 328                                      headerName,
 329                                      stringOf(values)));
 330         }
 331         return values.get(0);
 332     }
 333 
 334     private static String createNonce() {
 335         byte[] bytes = new byte[16];
 336         OpeningHandshake.random.nextBytes(bytes);
 337         return Base64.getEncoder().encodeToString(bytes);
 338     }
 339 
 340     private static CheckFailedException checkFailed(String message) {
 341         throw new CheckFailedException(message);
 342     }
 343 
 344     private static URI checkURI(URI uri) {
 345         String scheme = uri.getScheme();
 346         if (!("ws".equalsIgnoreCase(scheme) || "wss".equalsIgnoreCase(scheme)))
 347             throw illegal("invalid URI scheme: " + scheme);
 348         if (uri.getHost() == null)
 349             throw illegal("URI must contain a host: " + uri);
 350         if (uri.getFragment() != null)
 351             throw illegal("URI must not contain a fragment: " + uri);
 352         return uri;
 353     }
 354 
 355     private static IllegalArgumentException illegal(String message) {
 356         return new IllegalArgumentException(message);
 357     }
 358 
 359     /**
 360      * Returns the proxy for the given URI when sent through the given client,
 361      * or {@code null} if none is required or applicable.
 362      */
 363     private static Proxy proxyFor(Optional<ProxySelector> selector, URI uri) {
 364         if (!selector.isPresent()) {
 365             return null;
 366         }
 367         URI requestURI = createRequestURI(uri); // Based on the HTTP scheme
 368         List<Proxy> pl = selector.get().select(requestURI);
 369         if (pl.isEmpty()) {
 370             return null;
 371         }
 372         Proxy proxy = pl.get(0);
 373         if (proxy.type() != Proxy.Type.HTTP) {
 374             return null;
 375         }
 376         return proxy;
 377     }
 378 
 379     /**
 380      * Performs the necessary security permissions checks to connect ( possibly
 381      * through a proxy ) to the builders WebSocket URI.
 382      *
 383      * @throws SecurityException if the security manager denies access
 384      */
 385     static void checkPermissions(BuilderImpl b, Proxy proxy) {
 386         SecurityManager sm = System.getSecurityManager();
 387         if (sm == null) {
 388             return;
 389         }
 390         Stream<String> headers = b.getHeaders().stream().map(p -> p.first).distinct();
 391         URLPermission perm1 = Utils.permissionForServer(b.getUri(), "", headers);
 392         sm.checkPermission(perm1);
 393         if (proxy == null) {
 394             return;
 395         }
 396         URLPermission perm2 = permissionForProxy((InetSocketAddress) proxy.address());
 397         if (perm2 != null) {
 398             sm.checkPermission(perm2);
 399         }
 400     }
 401 }