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

Side by Side Diff: net/websockets/websocket_basic_handshake_stream.cc

Issue 105833003: Fail WebSocket channel when handshake fails. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 7 years 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 2013 The Chromium Authors. All rights reserved. 1 // Copyright 2013 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 #include "net/websockets/websocket_basic_handshake_stream.h" 5 #include "net/websockets/websocket_basic_handshake_stream.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <iterator> 8 #include <iterator>
szym 2013/12/09 18:49:58 include <string>
yhirano 2013/12/10 03:30:09 Done.
9 9
10 #include "base/base64.h" 10 #include "base/base64.h"
11 #include "base/basictypes.h" 11 #include "base/basictypes.h"
12 #include "base/bind.h" 12 #include "base/bind.h"
13 #include "base/containers/hash_tables.h" 13 #include "base/containers/hash_tables.h"
14 #include "base/stl_util.h" 14 #include "base/stl_util.h"
15 #include "base/strings/string_util.h" 15 #include "base/strings/string_util.h"
16 #include "base/strings/stringprintf.h"
16 #include "crypto/random.h" 17 #include "crypto/random.h"
17 #include "net/http/http_request_headers.h" 18 #include "net/http/http_request_headers.h"
18 #include "net/http/http_request_info.h" 19 #include "net/http/http_request_info.h"
19 #include "net/http/http_response_body_drainer.h" 20 #include "net/http/http_response_body_drainer.h"
20 #include "net/http/http_response_headers.h" 21 #include "net/http/http_response_headers.h"
21 #include "net/http/http_status_code.h" 22 #include "net/http/http_status_code.h"
22 #include "net/http/http_stream_parser.h" 23 #include "net/http/http_stream_parser.h"
23 #include "net/socket/client_socket_handle.h" 24 #include "net/socket/client_socket_handle.h"
24 #include "net/websockets/websocket_basic_stream.h" 25 #include "net/websockets/websocket_basic_stream.h"
26 #include "net/websockets/websocket_extension_parser.h"
25 #include "net/websockets/websocket_handshake_constants.h" 27 #include "net/websockets/websocket_handshake_constants.h"
26 #include "net/websockets/websocket_handshake_handler.h" 28 #include "net/websockets/websocket_handshake_handler.h"
27 #include "net/websockets/websocket_stream.h" 29 #include "net/websockets/websocket_stream.h"
28 30
29 namespace net { 31 namespace net {
30 namespace { 32 namespace {
31 33
34 enum GetHeaderResult {
35 GET_HEADER_OK,
36 GET_HEADER_MISSING,
37 GET_HEADER_MULTIPLE,
38 };
39
40 std::string MissingHeader(const std::string& header_name) {
szym 2013/12/09 18:49:58 MissingHeaderMessage or ...Msg
yhirano 2013/12/10 03:30:09 Done.
41 return std::string("'") + header_name + "' header is missing";
42 }
43
44 std::string MultipleHeaderValues(const std::string& header_name) {
45 return
46 std::string("'") +
47 header_name +
48 "' header must not appear more than once in a response";
49 }
50
32 std::string GenerateHandshakeChallenge() { 51 std::string GenerateHandshakeChallenge() {
33 std::string raw_challenge(websockets::kRawChallengeLength, '\0'); 52 std::string raw_challenge(websockets::kRawChallengeLength, '\0');
34 crypto::RandBytes(string_as_array(&raw_challenge), raw_challenge.length()); 53 crypto::RandBytes(string_as_array(&raw_challenge), raw_challenge.length());
35 std::string encoded_challenge; 54 std::string encoded_challenge;
36 bool encode_success = base::Base64Encode(raw_challenge, &encoded_challenge); 55 bool encode_success = base::Base64Encode(raw_challenge, &encoded_challenge);
37 DCHECK(encode_success); 56 DCHECK(encode_success);
38 return encoded_challenge; 57 return encoded_challenge;
39 } 58 }
40 59
41 void AddVectorHeaderIfNonEmpty(const char* name, 60 void AddVectorHeaderIfNonEmpty(const char* name,
42 const std::vector<std::string>& value, 61 const std::vector<std::string>& value,
43 HttpRequestHeaders* headers) { 62 HttpRequestHeaders* headers) {
44 if (value.empty()) 63 if (value.empty())
45 return; 64 return;
46 headers->SetHeader(name, JoinString(value, ", ")); 65 headers->SetHeader(name, JoinString(value, ", "));
47 } 66 }
48 67
49 // If |case_sensitive| is false, then |value| must be in lower-case. 68 GetHeaderResult GetSingleHeaderValue(const HttpResponseHeaders* headers,
50 bool ValidateSingleTokenHeader( 69 const base::StringPiece& name,
51 const scoped_refptr<HttpResponseHeaders>& headers, 70 std::string* value) {
52 const base::StringPiece& name,
53 const std::string& value,
54 bool case_sensitive) {
55 void* state = NULL; 71 void* state = NULL;
72 int tokens = 0;
56 std::string token; 73 std::string token;
57 int tokens = 0;
58 bool has_value = false;
59 while (headers->EnumerateHeader(&state, name, &token)) { 74 while (headers->EnumerateHeader(&state, name, &token)) {
60 if (++tokens > 1) 75 if (++tokens > 1)
61 return false; 76 return GET_HEADER_MULTIPLE;
62 has_value = case_sensitive ? value == token 77 *value = token;
63 : LowerCaseEqualsASCII(token, value.c_str());
64 } 78 }
65 return has_value; 79 return tokens > 0 ? GET_HEADER_OK : GET_HEADER_MISSING;
80 }
81
82 bool ValidateHeaderHasSingleValue(GetHeaderResult result,
83 const std::string& header_name,
84 std::string* failure_message) {
85 if (result == GET_HEADER_MISSING) {
86 *failure_message = MissingHeader(header_name);
87 return false;
88 }
89 if (result == GET_HEADER_MULTIPLE) {
90 *failure_message = MultipleHeaderValues(header_name);
91 return false;
92 }
93 DCHECK_EQ(result, GET_HEADER_OK);
94 return true;
95 }
96
97 bool ValidateUpgrade(const HttpResponseHeaders* headers,
98 std::string* failure_message) {
99 std::string value;
100 GetHeaderResult result =
101 GetSingleHeaderValue(headers, websockets::kUpgrade, &value);
102 if (!ValidateHeaderHasSingleValue(result,
103 websockets::kUpgrade,
104 failure_message)) {
105 return false;
106 }
107
108 if (!LowerCaseEqualsASCII(value, websockets::kWebSocketLowercase)) {
109 *failure_message =
110 "'Upgrade' header value is not 'WebSocket': " + value;
111 return false;
112 }
113 return true;
114 }
115
116 bool ValidateSecWebSocketAccept(const HttpResponseHeaders* headers,
117 const std::string& expected,
118 std::string* failure_message) {
119 std::string actual;
120 GetHeaderResult result =
121 GetSingleHeaderValue(headers, websockets::kSecWebSocketAccept, &actual);
122 if (!ValidateHeaderHasSingleValue(result,
123 websockets::kSecWebSocketAccept,
124 failure_message)) {
125 return false;
126 }
127
128 if (expected != actual) {
129 *failure_message = "Incorrect 'Sec-WebSocket-Accept' header value";
130 return false;
131 }
132 return true;
133 }
134
135 bool ValidateConnection(const HttpResponseHeaders* headers,
136 std::string* failure_message) {
137 // Connection header is permitted to contain other tokens.
138 if (!headers->HasHeader(HttpRequestHeaders::kConnection)) {
139 *failure_message = MissingHeader(HttpRequestHeaders::kConnection);
140 return false;
141 }
142 if (!headers->HasHeaderValue(HttpRequestHeaders::kConnection,
143 websockets::kUpgrade)) {
144 *failure_message = "'Connection' header value must contain 'Upgrade'";
145 return false;
146 }
147 return true;
66 } 148 }
67 149
68 bool ValidateSubProtocol( 150 bool ValidateSubProtocol(
69 const scoped_refptr<HttpResponseHeaders>& headers, 151 const HttpResponseHeaders* headers,
70 const std::vector<std::string>& requested_sub_protocols, 152 const std::vector<std::string>& requested_sub_protocols,
71 std::string* sub_protocol) { 153 std::string* sub_protocol,
154 std::string* failure_message) {
72 void* state = NULL; 155 void* state = NULL;
73 std::string token; 156 std::string token;
157 std::string last_token;
74 base::hash_set<std::string> requested_set(requested_sub_protocols.begin(), 158 base::hash_set<std::string> requested_set(requested_sub_protocols.begin(),
75 requested_sub_protocols.end()); 159 requested_sub_protocols.end());
76 int accepted = 0; 160 int count = 0;
161 bool has_multiple_protocols = false;
162 bool has_invalid_protocol = false;
163
77 while (headers->EnumerateHeader( 164 while (headers->EnumerateHeader(
78 &state, websockets::kSecWebSocketProtocol, &token)) { 165 &state, websockets::kSecWebSocketProtocol, &token) &&
166 !(has_multiple_protocols && has_invalid_protocol)) {
79 if (requested_set.count(token) == 0) 167 if (requested_set.count(token) == 0)
80 return false; 168 has_invalid_protocol = true;
169 if (++count > 1)
170 has_multiple_protocols = true;
171 last_token = token;
172 }
81 173
82 *sub_protocol = token; 174 if (has_multiple_protocols) {
83 // The server is only allowed to accept one protocol. 175 *failure_message = MultipleHeaderValues(websockets::kSecWebSocketProtocol);
84 if (++accepted > 1) 176 return false;
85 return false; 177 } else if (count > 0 && requested_sub_protocols.size() == 0) {
178 *failure_message =
179 std::string("Response must not include 'Sec-WebSocket-Protocol' "
180 "header if not present in request: ")
181 + last_token;
182 return false;
183 } else if (has_invalid_protocol) {
184 *failure_message =
185 "'Sec-WebSocket-Protocol' header value '" +
186 last_token +
187 "' in response does not match any of sent values";
188 return false;
189 } else if (requested_sub_protocols.size() > 0 && count == 0) {
190 *failure_message =
191 "Sent non-empty 'Sec-WebSocket-Protocol' header "
192 "but no response was received";
193 return false;
86 } 194 }
87 // If the browser requested > 0 protocols, the server is required to accept 195 *sub_protocol = last_token;
88 // one. 196 return true;
89 return requested_set.empty() || accepted == 1;
90 } 197 }
91 198
92 bool ValidateExtensions(const scoped_refptr<HttpResponseHeaders>& headers, 199 bool ValidateExtensions(const HttpResponseHeaders* headers,
93 const std::vector<std::string>& requested_extensions, 200 const std::vector<std::string>& requested_extensions,
94 std::string* extensions) { 201 std::string* extensions,
202 std::string* failure_message) {
95 void* state = NULL; 203 void* state = NULL;
96 std::string token; 204 std::string token;
97 while (headers->EnumerateHeader( 205 while (headers->EnumerateHeader(
98 &state, websockets::kSecWebSocketExtensions, &token)) { 206 &state, websockets::kSecWebSocketExtensions, &token)) {
207 WebSocketExtensionParser parser;
208 parser.Parse(token);
209 if (parser.has_error()) {
210 // TODO(yhirano) Set appropriate failure message.
211 *failure_message =
212 "'WebSocket-Extensions' header value is rejected by the parser: " +
213 token;
214 return false;
215 }
99 // TODO(ricea): Accept permessage-deflate with valid parameters. 216 // TODO(ricea): Accept permessage-deflate with valid parameters.
217 *failure_message =
218 "Found an unsupported extension '" +
219 parser.extension().name() +
220 "' in 'Sec-WebSocket-Extensions' header";
100 return false; 221 return false;
101 } 222 }
102 return true; 223 return true;
103 } 224 }
104 225
105 } // namespace 226 } // namespace
106 227
107 WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream( 228 WebSocketBasicHandshakeStream::WebSocketBasicHandshakeStream(
108 scoped_ptr<ClientSocketHandle> connection, 229 scoped_ptr<ClientSocketHandle> connection,
109 bool using_proxy, 230 bool using_proxy,
(...skipping 147 matching lines...) Expand 10 before | Expand all | Expand 10 after
257 state_.read_buf(), 378 state_.read_buf(),
258 sub_protocol_, 379 sub_protocol_,
259 extensions_)); 380 extensions_));
260 } 381 }
261 382
262 void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting( 383 void WebSocketBasicHandshakeStream::SetWebSocketKeyForTesting(
263 const std::string& key) { 384 const std::string& key) {
264 handshake_challenge_for_testing_.reset(new std::string(key)); 385 handshake_challenge_for_testing_.reset(new std::string(key));
265 } 386 }
266 387
388 std::string WebSocketBasicHandshakeStream::FailureMessage() const {
389 return failure_message_;
390 }
391
267 void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback( 392 void WebSocketBasicHandshakeStream::ReadResponseHeadersCallback(
268 const CompletionCallback& callback, 393 const CompletionCallback& callback,
269 int result) { 394 int result) {
270 if (result == OK) 395 if (result == OK)
271 result = ValidateResponse(); 396 result = ValidateResponse();
272 callback.Run(result); 397 callback.Run(result);
273 } 398 }
274 399
275 int WebSocketBasicHandshakeStream::ValidateResponse() { 400 int WebSocketBasicHandshakeStream::ValidateResponse() {
276 DCHECK(http_response_info_); 401 DCHECK(http_response_info_);
277 const scoped_refptr<HttpResponseHeaders>& headers = 402 const scoped_refptr<HttpResponseHeaders>& headers =
278 http_response_info_->headers; 403 http_response_info_->headers;
279 404
280 switch (headers->response_code()) { 405 switch (headers->response_code()) {
281 case HTTP_SWITCHING_PROTOCOLS: 406 case HTTP_SWITCHING_PROTOCOLS:
282 return ValidateUpgradeResponse(headers); 407 return ValidateUpgradeResponse(headers);
283 408
284 // We need to pass these through for authentication to work. 409 // We need to pass these through for authentication to work.
285 case HTTP_UNAUTHORIZED: 410 case HTTP_UNAUTHORIZED:
286 case HTTP_PROXY_AUTHENTICATION_REQUIRED: 411 case HTTP_PROXY_AUTHENTICATION_REQUIRED:
287 return OK; 412 return OK;
288 413
289 // Other status codes are potentially risky (see the warnings in the 414 // Other status codes are potentially risky (see the warnings in the
290 // WHATWG WebSocket API spec) and so are dropped by default. 415 // WHATWG WebSocket API spec) and so are dropped by default.
291 default: 416 default:
417 failure_message_ = base::StringPrintf("Unexpected status code: %d",
418 headers->response_code());
292 return ERR_INVALID_RESPONSE; 419 return ERR_INVALID_RESPONSE;
293 } 420 }
294 } 421 }
295 422
296 int WebSocketBasicHandshakeStream::ValidateUpgradeResponse( 423 int WebSocketBasicHandshakeStream::ValidateUpgradeResponse(
297 const scoped_refptr<HttpResponseHeaders>& headers) { 424 const scoped_refptr<HttpResponseHeaders>& headers) {
298 if (ValidateSingleTokenHeader(headers, 425 if (ValidateUpgrade(headers.get(), &failure_message_) &&
299 websockets::kUpgrade, 426 ValidateSecWebSocketAccept(headers.get(),
300 websockets::kWebSocketLowercase, 427 handshake_challenge_response_,
301 false) && 428 &failure_message_) &&
302 ValidateSingleTokenHeader(headers, 429 ValidateConnection(headers.get(), &failure_message_) &&
303 websockets::kSecWebSocketAccept, 430 ValidateSubProtocol(headers.get(),
304 handshake_challenge_response_, 431 requested_sub_protocols_,
305 true) && 432 &sub_protocol_,
306 headers->HasHeaderValue(HttpRequestHeaders::kConnection, 433 &failure_message_) &&
307 websockets::kUpgrade) && 434 ValidateExtensions(headers.get(),
308 ValidateSubProtocol(headers, requested_sub_protocols_, &sub_protocol_) && 435 requested_extensions_,
309 ValidateExtensions(headers, requested_extensions_, &extensions_)) { 436 &extensions_,
437 &failure_message_)) {
310 return OK; 438 return OK;
311 } 439 }
440 failure_message_ = "Error during WebSocket handshake: " + failure_message_;
312 return ERR_INVALID_RESPONSE; 441 return ERR_INVALID_RESPONSE;
313 } 442 }
314 443
315 } // namespace net 444 } // namespace net
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698