• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2013 The Chromium Authors
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 "net/websockets/websocket_basic_handshake_stream.h"
6 
7 #include <stddef.h>
8 
9 #include <array>
10 #include <set>
11 #include <string_view>
12 #include <type_traits>
13 #include <utility>
14 
15 #include "base/base64.h"
16 #include "base/check.h"
17 #include "base/check_op.h"
18 #include "base/functional/bind.h"
19 #include "base/functional/callback.h"
20 #include "base/memory/scoped_refptr.h"
21 #include "base/metrics/histogram_functions.h"
22 #include "base/strings/strcat.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/time/time.h"
26 #include "base/values.h"
27 #include "crypto/random.h"
28 #include "net/base/net_errors.h"
29 #include "net/http/http_network_session.h"
30 #include "net/http/http_request_headers.h"
31 #include "net/http/http_request_info.h"
32 #include "net/http/http_response_body_drainer.h"
33 #include "net/http/http_response_headers.h"
34 #include "net/http/http_response_info.h"
35 #include "net/http/http_status_code.h"
36 #include "net/http/http_stream_parser.h"
37 #include "net/http/http_version.h"
38 #include "net/log/net_log_event_type.h"
39 #include "net/socket/client_socket_handle.h"
40 #include "net/socket/stream_socket.h"
41 #include "net/socket/websocket_transport_client_socket_pool.h"
42 #include "net/ssl/ssl_cert_request_info.h"
43 #include "net/ssl/ssl_info.h"
44 #include "net/traffic_annotation/network_traffic_annotation.h"
45 #include "net/websockets/websocket_basic_stream.h"
46 #include "net/websockets/websocket_basic_stream_adapters.h"
47 #include "net/websockets/websocket_deflate_predictor_impl.h"
48 #include "net/websockets/websocket_deflate_stream.h"
49 #include "net/websockets/websocket_handshake_challenge.h"
50 #include "net/websockets/websocket_handshake_constants.h"
51 #include "net/websockets/websocket_handshake_request_info.h"
52 #include "net/websockets/websocket_stream.h"
53 
54 namespace net {
55 class HttpStream;
56 class IOBuffer;
57 class IPEndPoint;
58 struct AlternativeService;
59 struct LoadTimingInfo;
60 struct NetErrorDetails;
61 
62 namespace {
63 
64 constexpr char kConnectionErrorStatusLine[] = "HTTP/1.1 503 Connection Error";
65 
66 }  // namespace
67 
68 namespace {
69 
70 enum GetHeaderResult {
71   GET_HEADER_OK,
72   GET_HEADER_MISSING,
73   GET_HEADER_MULTIPLE,
74 };
75 
MissingHeaderMessage(const std::string & header_name)76 std::string MissingHeaderMessage(const std::string& header_name) {
77   return base::StrCat({"'", header_name, "' header is missing"});
78 }
79 
GenerateHandshakeChallenge()80 std::string GenerateHandshakeChallenge() {
81   std::array<uint8_t, websockets::kRawChallengeLength> raw_challenge = {};
82   crypto::RandBytes(raw_challenge);
83   return base::Base64Encode(raw_challenge);
84 }
85 
GetSingleHeaderValue(const HttpResponseHeaders * headers,std::string_view name,std::string * value)86 GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
87                                      std::string_view name,
88                                      std::string* value) {
89   size_t iter = 0;
90   bool found_value = false;
91   while (std::optional<std::string_view> maybe_value =
92              headers->EnumerateHeader(&iter, name)) {
93     if (found_value) {
94       return GET_HEADER_MULTIPLE;
95     }
96     found_value = true;
97     *value = *maybe_value;
98   }
99   return found_value ? GET_HEADER_OK : GET_HEADER_MISSING;
100 }
101 
ValidateHeaderHasSingleValue(GetHeaderResult result,const std::string & header_name,std::string * failure_message)102 bool ValidateHeaderHasSingleValue(GetHeaderResult result,
103                                   const std::string& header_name,
104                                   std::string* failure_message) {
105   if (result == GET_HEADER_MISSING) {
106     *failure_message = MissingHeaderMessage(header_name);
107     return false;
108   }
109   if (result == GET_HEADER_MULTIPLE) {
110     *failure_message =
111         WebSocketHandshakeStreamBase::MultipleHeaderValuesMessage(header_name);
112     return false;
113   }
114   DCHECK_EQ(result, GET_HEADER_OK);
115   return true;
116 }
117 
ValidateUpgrade(const HttpResponseHeaders * headers,std::string * failure_message)118 bool ValidateUpgrade(const HttpResponseHeaders* headers,
119                      std::string* failure_message) {
120   std::string value;
121   GetHeaderResult result =
122       GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
123   if (!ValidateHeaderHasSingleValue(result,
124                                     websockets::kUpgrade,
125                                     failure_message)) {
126     return false;
127   }
128 
129   if (!base::EqualsCaseInsensitiveASCII(value,
130                                         websockets::kWebSocketLowercase)) {
131     *failure_message =
132         "'Upgrade' header value is not 'WebSocket': " + value;
133     return false;
134   }
135   return true;
136 }
137 
ValidateSecWebSocketAccept(const HttpResponseHeaders * headers,const std::string & expected,std::string * failure_message)138 bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
139                                 const std::string& expected,
140                                 std::string* failure_message) {
141   std::string actual;
142   GetHeaderResult result =
143       GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
144   if (!ValidateHeaderHasSingleValue(result,
145                                     websockets::kSecWebSocketAccept,
146                                     failure_message)) {
147     return false;
148   }
149 
150   if (expected != actual) {
151     *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
152     return false;
153   }
154   return true;
155 }
156 
ValidateConnection(const HttpResponseHeaders * headers,std::string * failure_message)157 bool ValidateConnection(const HttpResponseHeaders* headers,
158                         std::string* failure_message) {
159   // Connection header is permitted to contain other tokens.
160   if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
161     *failure_message = MissingHeaderMessage(HttpRequestHeaders::kConnection);
162     return false;
163   }
164   if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
165                                websockets::kUpgrade)) {
166     *failure_message = "'Connection' header value must contain 'Upgrade'";
167     return false;
168   }
169   return true;
170 }
171 
NetLogFailureParam(int net_error,const std::string & message)172 base::Value::Dict NetLogFailureParam(int net_error,
173                                      const std::string& message) {
174   base::Value::Dict dict;
175   dict.Set("net_error", net_error);
176   dict.Set("message", message);
177   return dict;
178 }
179 
180 }  // namespace
181 
WebSocketBasicHandshakeStream(std::unique_ptr<StreamSocketHandle> connection,WebSocketStream::ConnectDelegate * connect_delegate,bool is_for_get_to_http_proxy,std::vector<std::string> requested_sub_protocols,std::vector<std::string> requested_extensions,WebSocketStreamRequestAPI * request,WebSocketEndpointLockManager * websocket_endpoint_lock_manager)182 WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
183     std::unique_ptr<StreamSocketHandle> connection,
184     WebSocketStream::ConnectDelegate* connect_delegate,
185     bool is_for_get_to_http_proxy,
186     std::vector<std::string> requested_sub_protocols,
187     std::vector<std::string> requested_extensions,
188     WebSocketStreamRequestAPI* request,
189     WebSocketEndpointLockManager* websocket_endpoint_lock_manager)
190     : state_(std::move(connection), is_for_get_to_http_proxy),
191       connect_delegate_(connect_delegate),
192       requested_sub_protocols_(std::move(requested_sub_protocols)),
193       requested_extensions_(std::move(requested_extensions)),
194       stream_request_(request),
195       websocket_endpoint_lock_manager_(websocket_endpoint_lock_manager) {
196   DCHECK(connect_delegate);
197   DCHECK(request);
198 }
199 
~WebSocketBasicHandshakeStream()200 WebSocketBasicHandshakeStream::~WebSocketBasicHandshakeStream() {
201   // Some members are "stolen" by RenewStreamForAuth() and should not be touched
202   // here. Particularly |connect_delegate_|, |stream_request_|, and
203   // |websocket_endpoint_lock_manager_|.
204 
205   // TODO(ricea): What's the right thing to do here if we renewed the stream for
206   // auth? Currently we record it as INCOMPLETE.
207   RecordHandshakeResult(result_);
208 }
209 
RegisterRequest(const HttpRequestInfo * request_info)210 void WebSocketBasicHandshakeStream::RegisterRequest(
211     const HttpRequestInfo* request_info) {
212   DCHECK(request_info);
213   DCHECK(request_info->traffic_annotation.is_valid());
214   request_info_ = request_info;
215 }
216 
InitializeStream(bool can_send_early,RequestPriority priority,const NetLogWithSource & net_log,CompletionOnceCallback callback)217 int WebSocketBasicHandshakeStream::InitializeStream(
218     bool can_send_early,
219     RequestPriority priority,
220     const NetLogWithSource& net_log,
221     CompletionOnceCallback callback) {
222   url_ = request_info_->url;
223   net_log_ = net_log;
224   // The WebSocket may receive a socket in the early data state from
225   // HttpNetworkTransaction, which means it must call ConfirmHandshake() for
226   // requests that need replay protection. However, the first request on any
227   // WebSocket stream is a GET with an idempotent request
228   // (https://tools.ietf.org/html/rfc6455#section-1.3), so there is no need to
229   // call ConfirmHandshake().
230   //
231   // Data after the WebSockets handshake may not be replayable, but the
232   // handshake is guaranteed to be confirmed once the HTTP response is received.
233   DCHECK(can_send_early);
234   state_.Initialize(request_info_, priority, net_log);
235   // RequestInfo is no longer needed after this point.
236   request_info_ = nullptr;
237   return OK;
238 }
239 
SendRequest(const HttpRequestHeaders & headers,HttpResponseInfo * response,CompletionOnceCallback callback)240 int WebSocketBasicHandshakeStream::SendRequest(
241     const HttpRequestHeaders& headers,
242     HttpResponseInfo* response,
243     CompletionOnceCallback callback) {
244   DCHECK(!headers.HasHeader(websockets::kSecWebSocketKey));
245   DCHECK(!headers.HasHeader(websockets::kSecWebSocketProtocol));
246   DCHECK(!headers.HasHeader(websockets::kSecWebSocketExtensions));
247   DCHECK(headers.HasHeader(HttpRequestHeaders::kOrigin));
248   DCHECK(headers.HasHeader(websockets::kUpgrade));
249   DCHECK(headers.HasHeader(HttpRequestHeaders::kConnection));
250   DCHECK(headers.HasHeader(websockets::kSecWebSocketVersion));
251   DCHECK(parser());
252 
253   http_response_info_ = response;
254 
255   // Create a copy of the headers object, so that we can add the
256   // Sec-WebSocket-Key header.
257   HttpRequestHeaders enriched_headers = headers;
258   std::string handshake_challenge;
259   if (handshake_challenge_for_testing_.has_value()) {
260     handshake_challenge = handshake_challenge_for_testing_.value();
261     handshake_challenge_for_testing_.reset();
262   } else {
263     handshake_challenge = GenerateHandshakeChallenge();
264   }
265   enriched_headers.SetHeader(websockets::kSecWebSocketKey, handshake_challenge);
266 
267   AddVectorHeaders(requested_extensions_, requested_sub_protocols_,
268                    &enriched_headers);
269 
270   handshake_challenge_response_ =
271       ComputeSecWebSocketAccept(handshake_challenge);
272 
273   DCHECK(connect_delegate_);
274   auto request =
275       std::make_unique<WebSocketHandshakeRequestInfo>(url_, base::Time::Now());
276   request->headers = enriched_headers;
277   connect_delegate_->OnStartOpeningHandshake(std::move(request));
278 
279   return parser()->SendRequest(
280       state_.GenerateRequestLine(), enriched_headers,
281       NetworkTrafficAnnotationTag(state_.traffic_annotation()), response,
282       std::move(callback));
283 }
284 
ReadResponseHeaders(CompletionOnceCallback callback)285 int WebSocketBasicHandshakeStream::ReadResponseHeaders(
286     CompletionOnceCallback callback) {
287   // HttpStreamParser uses a weak pointer when reading from the
288   // socket, so it won't be called back after being destroyed. The
289   // HttpStreamParser is owned by HttpBasicState which is owned by this object,
290   // so this use of base::Unretained() is safe.
291   int rv = parser()->ReadResponseHeaders(base::BindOnce(
292       &WebSocketBasicHandshakeStream::ReadResponseHeadersCallback,
293       base::Unretained(this), std::move(callback)));
294   if (rv == ERR_IO_PENDING)
295     return rv;
296   return ValidateResponse(rv);
297 }
298 
ReadResponseBody(IOBuffer * buf,int buf_len,CompletionOnceCallback callback)299 int WebSocketBasicHandshakeStream::ReadResponseBody(
300     IOBuffer* buf,
301     int buf_len,
302     CompletionOnceCallback callback) {
303   return parser()->ReadResponseBody(buf, buf_len, std::move(callback));
304 }
305 
Close(bool not_reusable)306 void WebSocketBasicHandshakeStream::Close(bool not_reusable) {
307   // This class ignores the value of `not_reusable` and never lets the socket be
308   // re-used.
309   state_.Close(/*not_reusable=*/true);
310 }
311 
IsResponseBodyComplete() const312 bool WebSocketBasicHandshakeStream::IsResponseBodyComplete() const {
313   return parser()->IsResponseBodyComplete();
314 }
315 
IsConnectionReused() const316 bool WebSocketBasicHandshakeStream::IsConnectionReused() const {
317   return state_.IsConnectionReused();
318 }
319 
SetConnectionReused()320 void WebSocketBasicHandshakeStream::SetConnectionReused() {
321   state_.SetConnectionReused();
322 }
323 
CanReuseConnection() const324 bool WebSocketBasicHandshakeStream::CanReuseConnection() const {
325   return state_.CanReuseConnection();
326 }
327 
GetTotalReceivedBytes() const328 int64_t WebSocketBasicHandshakeStream::GetTotalReceivedBytes() const {
329   return 0;
330 }
331 
GetTotalSentBytes() const332 int64_t WebSocketBasicHandshakeStream::GetTotalSentBytes() const {
333   return 0;
334 }
335 
GetAlternativeService(AlternativeService * alternative_service) const336 bool WebSocketBasicHandshakeStream::GetAlternativeService(
337     AlternativeService* alternative_service) const {
338   return false;
339 }
340 
GetLoadTimingInfo(LoadTimingInfo * load_timing_info) const341 bool WebSocketBasicHandshakeStream::GetLoadTimingInfo(
342     LoadTimingInfo* load_timing_info) const {
343   return state_.GetLoadTimingInfo(load_timing_info);
344 }
345 
GetSSLInfo(SSLInfo * ssl_info)346 void WebSocketBasicHandshakeStream::GetSSLInfo(SSLInfo* ssl_info) {
347   state_.GetSSLInfo(ssl_info);
348 }
349 
GetRemoteEndpoint(IPEndPoint * endpoint)350 int WebSocketBasicHandshakeStream::GetRemoteEndpoint(IPEndPoint* endpoint) {
351   return state_.GetRemoteEndpoint(endpoint);
352 }
353 
PopulateNetErrorDetails(NetErrorDetails *)354 void WebSocketBasicHandshakeStream::PopulateNetErrorDetails(
355     NetErrorDetails* /*details*/) {
356   return;
357 }
358 
Drain(HttpNetworkSession * session)359 void WebSocketBasicHandshakeStream::Drain(HttpNetworkSession* session) {
360   session->StartResponseDrainer(
361       std::make_unique<HttpResponseBodyDrainer>(this));
362   // |drainer| will delete itself.
363 }
364 
SetPriority(RequestPriority priority)365 void WebSocketBasicHandshakeStream::SetPriority(RequestPriority priority) {
366   // TODO(ricea): See TODO comment in HttpBasicStream::SetPriority(). If it is
367   // gone, then copy whatever has happened there over here.
368 }
369 
370 std::unique_ptr<HttpStream>
RenewStreamForAuth()371 WebSocketBasicHandshakeStream::RenewStreamForAuth() {
372   DCHECK(IsResponseBodyComplete());
373   DCHECK(!parser()->IsMoreDataBuffered());
374 
375   auto handshake_stream = std::make_unique<WebSocketBasicHandshakeStream>(
376       state_.ReleaseConnection(), connect_delegate_,
377       state_.is_for_get_to_http_proxy(), std::move(requested_sub_protocols_),
378       std::move(requested_extensions_), stream_request_,
379       websocket_endpoint_lock_manager_);
380 
381   stream_request_->OnBasicHandshakeStreamCreated(handshake_stream.get());
382 
383   return handshake_stream;
384 }
385 
GetDnsAliases() const386 const std::set<std::string>& WebSocketBasicHandshakeStream::GetDnsAliases()
387     const {
388   return state_.GetDnsAliases();
389 }
390 
GetAcceptChViaAlps() const391 std::string_view WebSocketBasicHandshakeStream::GetAcceptChViaAlps() const {
392   return {};
393 }
394 
Upgrade()395 std::unique_ptr<WebSocketStream> WebSocketBasicHandshakeStream::Upgrade() {
396   WebSocketTransportClientSocketPool::UnlockEndpoint(
397       state_.connection(), websocket_endpoint_lock_manager_);
398   std::unique_ptr<WebSocketStream> basic_stream =
399       std::make_unique<WebSocketBasicStream>(
400           std::make_unique<WebSocketClientSocketHandleAdapter>(
401               state_.ReleaseConnection()),
402           state_.read_buf(), sub_protocol_, extensions_, net_log_);
403   DCHECK(extension_params_.get());
404   if (extension_params_->deflate_enabled) {
405     return std::make_unique<WebSocketDeflateStream>(
406         std::move(basic_stream), extension_params_->deflate_parameters,
407         std::make_unique<WebSocketDeflatePredictorImpl>());
408   }
409 
410   return basic_stream;
411 }
412 
CanReadFromStream() const413 bool WebSocketBasicHandshakeStream::CanReadFromStream() const {
414   auto* connection = state_.connection();
415   if (!connection) {
416     return false;
417   }
418   return connection->socket();
419 }
420 
421 base::WeakPtr<WebSocketHandshakeStreamBase>
GetWeakPtr()422 WebSocketBasicHandshakeStream::GetWeakPtr() {
423   return weak_ptr_factory_.GetWeakPtr();
424 }
425 
SetWebSocketKeyForTesting(const std::string & key)426 void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
427     const std::string& key) {
428   handshake_challenge_for_testing_ = key;
429 }
430 
ReadResponseHeadersCallback(CompletionOnceCallback callback,int result)431 void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
432     CompletionOnceCallback callback,
433     int result) {
434   std::move(callback).Run(ValidateResponse(result));
435 }
436 
ValidateResponse(int rv)437 int WebSocketBasicHandshakeStream::ValidateResponse(int rv) {
438   DCHECK(http_response_info_);
439   // Most net errors happen during connection, so they are not seen by this
440   // method. The histogram for error codes is created in
441   // Delegate::OnResponseStarted in websocket_stream.cc instead.
442   if (rv >= 0) {
443     const HttpResponseHeaders* headers = http_response_info_->headers.get();
444     const int response_code = headers->response_code();
445     base::UmaHistogramSparse("Net.WebSocket.ResponseCode", response_code);
446     switch (response_code) {
447       case HTTP_SWITCHING_PROTOCOLS:
448         return ValidateUpgradeResponse(headers);
449 
450       // We need to pass these through for authentication to work.
451       case HTTP_UNAUTHORIZED:
452       case HTTP_PROXY_AUTHENTICATION_REQUIRED:
453         return OK;
454 
455       // Other status codes are potentially risky (see the warnings in the
456       // WHATWG WebSocket API spec) and so are dropped by default.
457       default:
458         // A WebSocket server cannot be using HTTP/0.9, so if we see version
459         // 0.9, it means the response was garbage.
460         // Reporting "Unexpected response code: 200" in this case is not
461         // helpful, so use a different error message.
462         if (headers->GetHttpVersion() == HttpVersion(0, 9)) {
463           OnFailure("Error during WebSocket handshake: Invalid status line",
464                     ERR_FAILED, std::nullopt);
465         } else {
466           OnFailure(base::StringPrintf("Error during WebSocket handshake: "
467                                        "Unexpected response code: %d",
468                                        headers->response_code()),
469                     ERR_FAILED, headers->response_code());
470         }
471         result_ = HandshakeResult::INVALID_STATUS;
472         return ERR_INVALID_RESPONSE;
473     }
474   } else {
475     if (rv == ERR_EMPTY_RESPONSE) {
476       OnFailure("Connection closed before receiving a handshake response", rv,
477                 std::nullopt);
478       result_ = HandshakeResult::EMPTY_RESPONSE;
479       return rv;
480     }
481     OnFailure(
482         base::StrCat({"Error during WebSocket handshake: ", ErrorToString(rv)}),
483         rv, std::nullopt);
484     // Some error codes (for example ERR_CONNECTION_CLOSED) get changed to OK at
485     // higher levels. To prevent an unvalidated connection getting erroneously
486     // upgraded, don't pass through the status code unchanged if it is
487     // HTTP_SWITCHING_PROTOCOLS.
488     if (http_response_info_->headers &&
489         http_response_info_->headers->response_code() ==
490             HTTP_SWITCHING_PROTOCOLS) {
491       http_response_info_->headers->ReplaceStatusLine(
492           kConnectionErrorStatusLine);
493       result_ = HandshakeResult::FAILED_SWITCHING_PROTOCOLS;
494       return rv;
495     }
496     result_ = HandshakeResult::FAILED;
497     return rv;
498   }
499 }
500 
ValidateUpgradeResponse(const HttpResponseHeaders * headers)501 int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
502     const HttpResponseHeaders* headers) {
503   extension_params_ = std::make_unique<WebSocketExtensionParams>();
504   std::string failure_message;
505   if (!ValidateUpgrade(headers, &failure_message)) {
506     result_ = HandshakeResult::FAILED_UPGRADE;
507   } else if (!ValidateSecWebSocketAccept(headers, handshake_challenge_response_,
508                                          &failure_message)) {
509     result_ = HandshakeResult::FAILED_ACCEPT;
510   } else if (!ValidateConnection(headers, &failure_message)) {
511     result_ = HandshakeResult::FAILED_CONNECTION;
512   } else if (!ValidateSubProtocol(headers, requested_sub_protocols_,
513                                   &sub_protocol_, &failure_message)) {
514     result_ = HandshakeResult::FAILED_SUBPROTO;
515   } else if (!ValidateExtensions(headers, &extensions_, &failure_message,
516                                  extension_params_.get())) {
517     result_ = HandshakeResult::FAILED_EXTENSIONS;
518   } else {
519     result_ = HandshakeResult::CONNECTED;
520     return OK;
521   }
522   OnFailure("Error during WebSocket handshake: " + failure_message, ERR_FAILED,
523             std::nullopt);
524   return ERR_INVALID_RESPONSE;
525 }
526 
OnFailure(const std::string & message,int net_error,std::optional<int> response_code)527 void WebSocketBasicHandshakeStream::OnFailure(
528     const std::string& message,
529     int net_error,
530     std::optional<int> response_code) {
531   net_log_.AddEvent(net::NetLogEventType::WEBSOCKET_UPGRADE_FAILURE,
532                     [&] { return NetLogFailureParam(net_error, message); });
533   // Avoid connection reuse if auth did not happen.
534   state_.connection()->socket()->Disconnect();
535   stream_request_->OnFailure(message, net_error, response_code);
536 }
537 
538 }  // namespace net
539