OLD | NEW |
| (Empty) |
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. | |
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/socket/ssl_server_socket_openssl.h" | |
6 | |
7 #include <openssl/err.h> | |
8 #include <openssl/ssl.h> | |
9 #include <utility> | |
10 | |
11 #include "base/callback_helpers.h" | |
12 #include "base/logging.h" | |
13 #include "base/strings/string_util.h" | |
14 #include "crypto/openssl_util.h" | |
15 #include "crypto/rsa_private_key.h" | |
16 #include "crypto/scoped_openssl_types.h" | |
17 #include "net/base/net_errors.h" | |
18 #include "net/cert/cert_verify_result.h" | |
19 #include "net/cert/client_cert_verifier.h" | |
20 #include "net/cert/x509_util_openssl.h" | |
21 #include "net/ssl/openssl_ssl_util.h" | |
22 #include "net/ssl/ssl_connection_status_flags.h" | |
23 #include "net/ssl/ssl_info.h" | |
24 | |
25 #define GotoState(s) next_handshake_state_ = s | |
26 | |
27 namespace net { | |
28 | |
29 namespace { | |
30 | |
31 // Creates an X509Certificate out of the concatenation of |cert|, if non-null, | |
32 // with |chain|. | |
33 scoped_refptr<X509Certificate> CreateX509Certificate(X509* cert, | |
34 STACK_OF(X509) * chain) { | |
35 std::vector<base::StringPiece> der_chain; | |
36 base::StringPiece der_cert; | |
37 scoped_refptr<X509Certificate> client_cert; | |
38 if (cert) { | |
39 if (!x509_util::GetDER(cert, &der_cert)) | |
40 return nullptr; | |
41 der_chain.push_back(der_cert); | |
42 } | |
43 | |
44 for (size_t i = 0; i < sk_X509_num(chain); ++i) { | |
45 X509* x = sk_X509_value(chain, i); | |
46 if (!x509_util::GetDER(x, &der_cert)) | |
47 return nullptr; | |
48 der_chain.push_back(der_cert); | |
49 } | |
50 | |
51 return X509Certificate::CreateFromDERCertChain(der_chain); | |
52 } | |
53 | |
54 class SSLServerSocketOpenSSL : public SSLServerSocket { | |
55 public: | |
56 // See comments on CreateSSLServerSocket for details of how these | |
57 // parameters are used. | |
58 SSLServerSocketOpenSSL(std::unique_ptr<StreamSocket> socket, SSL* ssl); | |
59 ~SSLServerSocketOpenSSL() override; | |
60 | |
61 // SSLServerSocket interface. | |
62 int Handshake(const CompletionCallback& callback) override; | |
63 | |
64 // SSLSocket interface. | |
65 int ExportKeyingMaterial(const base::StringPiece& label, | |
66 bool has_context, | |
67 const base::StringPiece& context, | |
68 unsigned char* out, | |
69 unsigned int outlen) override; | |
70 | |
71 // Socket interface (via StreamSocket). | |
72 int Read(IOBuffer* buf, | |
73 int buf_len, | |
74 const CompletionCallback& callback) override; | |
75 int Write(IOBuffer* buf, | |
76 int buf_len, | |
77 const CompletionCallback& callback) override; | |
78 int SetReceiveBufferSize(int32_t size) override; | |
79 int SetSendBufferSize(int32_t size) override; | |
80 | |
81 // StreamSocket implementation. | |
82 int Connect(const CompletionCallback& callback) override; | |
83 void Disconnect() override; | |
84 bool IsConnected() const override; | |
85 bool IsConnectedAndIdle() const override; | |
86 int GetPeerAddress(IPEndPoint* address) const override; | |
87 int GetLocalAddress(IPEndPoint* address) const override; | |
88 const BoundNetLog& NetLog() const override; | |
89 void SetSubresourceSpeculation() override; | |
90 void SetOmniboxSpeculation() override; | |
91 bool WasEverUsed() const override; | |
92 bool WasNpnNegotiated() const override; | |
93 NextProto GetNegotiatedProtocol() const override; | |
94 bool GetSSLInfo(SSLInfo* ssl_info) override; | |
95 void GetConnectionAttempts(ConnectionAttempts* out) const override; | |
96 void ClearConnectionAttempts() override {} | |
97 void AddConnectionAttempts(const ConnectionAttempts& attempts) override {} | |
98 int64_t GetTotalReceivedBytes() const override; | |
99 static int CertVerifyCallback(X509_STORE_CTX* store_ctx, void* arg); | |
100 | |
101 private: | |
102 enum State { | |
103 STATE_NONE, | |
104 STATE_HANDSHAKE, | |
105 }; | |
106 | |
107 void OnSendComplete(int result); | |
108 void OnRecvComplete(int result); | |
109 void OnHandshakeIOComplete(int result); | |
110 | |
111 int BufferSend(); | |
112 void BufferSendComplete(int result); | |
113 void TransportWriteComplete(int result); | |
114 int BufferRecv(); | |
115 void BufferRecvComplete(int result); | |
116 int TransportReadComplete(int result); | |
117 bool DoTransportIO(); | |
118 int DoPayloadRead(); | |
119 int DoPayloadWrite(); | |
120 | |
121 int DoHandshakeLoop(int last_io_result); | |
122 int DoReadLoop(int result); | |
123 int DoWriteLoop(int result); | |
124 int DoHandshake(); | |
125 void DoHandshakeCallback(int result); | |
126 void DoReadCallback(int result); | |
127 void DoWriteCallback(int result); | |
128 | |
129 int Init(); | |
130 void ExtractClientCert(); | |
131 | |
132 // Members used to send and receive buffer. | |
133 bool transport_send_busy_; | |
134 bool transport_recv_busy_; | |
135 bool transport_recv_eof_; | |
136 | |
137 scoped_refptr<DrainableIOBuffer> send_buffer_; | |
138 scoped_refptr<IOBuffer> recv_buffer_; | |
139 | |
140 BoundNetLog net_log_; | |
141 | |
142 CompletionCallback user_handshake_callback_; | |
143 CompletionCallback user_read_callback_; | |
144 CompletionCallback user_write_callback_; | |
145 | |
146 // Used by Read function. | |
147 scoped_refptr<IOBuffer> user_read_buf_; | |
148 int user_read_buf_len_; | |
149 | |
150 // Used by Write function. | |
151 scoped_refptr<IOBuffer> user_write_buf_; | |
152 int user_write_buf_len_; | |
153 | |
154 // Used by TransportWriteComplete() and TransportReadComplete() to signify an | |
155 // error writing to the transport socket. A value of OK indicates no error. | |
156 int transport_write_error_; | |
157 | |
158 // OpenSSL stuff | |
159 SSL* ssl_; | |
160 BIO* transport_bio_; | |
161 | |
162 // StreamSocket for sending and receiving data. | |
163 std::unique_ptr<StreamSocket> transport_socket_; | |
164 | |
165 // Certificate for the client. | |
166 scoped_refptr<X509Certificate> client_cert_; | |
167 | |
168 State next_handshake_state_; | |
169 bool completed_handshake_; | |
170 | |
171 DISALLOW_COPY_AND_ASSIGN(SSLServerSocketOpenSSL); | |
172 }; | |
173 | |
174 SSLServerSocketOpenSSL::SSLServerSocketOpenSSL( | |
175 std::unique_ptr<StreamSocket> transport_socket, | |
176 SSL* ssl) | |
177 : transport_send_busy_(false), | |
178 transport_recv_busy_(false), | |
179 transport_recv_eof_(false), | |
180 user_read_buf_len_(0), | |
181 user_write_buf_len_(0), | |
182 transport_write_error_(OK), | |
183 ssl_(ssl), | |
184 transport_bio_(NULL), | |
185 transport_socket_(std::move(transport_socket)), | |
186 next_handshake_state_(STATE_NONE), | |
187 completed_handshake_(false) {} | |
188 | |
189 SSLServerSocketOpenSSL::~SSLServerSocketOpenSSL() { | |
190 if (ssl_) { | |
191 // Calling SSL_shutdown prevents the session from being marked as | |
192 // unresumable. | |
193 SSL_shutdown(ssl_); | |
194 SSL_free(ssl_); | |
195 ssl_ = NULL; | |
196 } | |
197 if (transport_bio_) { | |
198 BIO_free_all(transport_bio_); | |
199 transport_bio_ = NULL; | |
200 } | |
201 } | |
202 | |
203 int SSLServerSocketOpenSSL::Handshake(const CompletionCallback& callback) { | |
204 net_log_.BeginEvent(NetLog::TYPE_SSL_SERVER_HANDSHAKE); | |
205 | |
206 // Set up new ssl object. | |
207 int rv = Init(); | |
208 if (rv != OK) { | |
209 LOG(ERROR) << "Failed to initialize OpenSSL: rv=" << rv; | |
210 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_SERVER_HANDSHAKE, rv); | |
211 return rv; | |
212 } | |
213 | |
214 // Set SSL to server mode. Handshake happens in the loop below. | |
215 SSL_set_accept_state(ssl_); | |
216 | |
217 GotoState(STATE_HANDSHAKE); | |
218 rv = DoHandshakeLoop(OK); | |
219 if (rv == ERR_IO_PENDING) { | |
220 user_handshake_callback_ = callback; | |
221 } else { | |
222 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_SERVER_HANDSHAKE, rv); | |
223 } | |
224 | |
225 return rv > OK ? OK : rv; | |
226 } | |
227 | |
228 int SSLServerSocketOpenSSL::ExportKeyingMaterial( | |
229 const base::StringPiece& label, | |
230 bool has_context, | |
231 const base::StringPiece& context, | |
232 unsigned char* out, | |
233 unsigned int outlen) { | |
234 if (!IsConnected()) | |
235 return ERR_SOCKET_NOT_CONNECTED; | |
236 | |
237 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); | |
238 | |
239 int rv = SSL_export_keying_material( | |
240 ssl_, out, outlen, label.data(), label.size(), | |
241 reinterpret_cast<const unsigned char*>(context.data()), | |
242 context.length(), context.length() > 0); | |
243 | |
244 if (rv != 1) { | |
245 int ssl_error = SSL_get_error(ssl_, rv); | |
246 LOG(ERROR) << "Failed to export keying material;" | |
247 << " returned " << rv | |
248 << ", SSL error code " << ssl_error; | |
249 return MapOpenSSLError(ssl_error, err_tracer); | |
250 } | |
251 return OK; | |
252 } | |
253 | |
254 int SSLServerSocketOpenSSL::Read(IOBuffer* buf, | |
255 int buf_len, | |
256 const CompletionCallback& callback) { | |
257 DCHECK(user_read_callback_.is_null()); | |
258 DCHECK(user_handshake_callback_.is_null()); | |
259 DCHECK(!user_read_buf_); | |
260 DCHECK(!callback.is_null()); | |
261 | |
262 user_read_buf_ = buf; | |
263 user_read_buf_len_ = buf_len; | |
264 | |
265 DCHECK(completed_handshake_); | |
266 | |
267 int rv = DoReadLoop(OK); | |
268 | |
269 if (rv == ERR_IO_PENDING) { | |
270 user_read_callback_ = callback; | |
271 } else { | |
272 user_read_buf_ = NULL; | |
273 user_read_buf_len_ = 0; | |
274 } | |
275 | |
276 return rv; | |
277 } | |
278 | |
279 int SSLServerSocketOpenSSL::Write(IOBuffer* buf, | |
280 int buf_len, | |
281 const CompletionCallback& callback) { | |
282 DCHECK(user_write_callback_.is_null()); | |
283 DCHECK(!user_write_buf_); | |
284 DCHECK(!callback.is_null()); | |
285 | |
286 user_write_buf_ = buf; | |
287 user_write_buf_len_ = buf_len; | |
288 | |
289 int rv = DoWriteLoop(OK); | |
290 | |
291 if (rv == ERR_IO_PENDING) { | |
292 user_write_callback_ = callback; | |
293 } else { | |
294 user_write_buf_ = NULL; | |
295 user_write_buf_len_ = 0; | |
296 } | |
297 return rv; | |
298 } | |
299 | |
300 int SSLServerSocketOpenSSL::SetReceiveBufferSize(int32_t size) { | |
301 return transport_socket_->SetReceiveBufferSize(size); | |
302 } | |
303 | |
304 int SSLServerSocketOpenSSL::SetSendBufferSize(int32_t size) { | |
305 return transport_socket_->SetSendBufferSize(size); | |
306 } | |
307 | |
308 int SSLServerSocketOpenSSL::Connect(const CompletionCallback& callback) { | |
309 NOTIMPLEMENTED(); | |
310 return ERR_NOT_IMPLEMENTED; | |
311 } | |
312 | |
313 void SSLServerSocketOpenSSL::Disconnect() { | |
314 transport_socket_->Disconnect(); | |
315 } | |
316 | |
317 bool SSLServerSocketOpenSSL::IsConnected() const { | |
318 // TODO(wtc): Find out if we should check transport_socket_->IsConnected() | |
319 // as well. | |
320 return completed_handshake_; | |
321 } | |
322 | |
323 bool SSLServerSocketOpenSSL::IsConnectedAndIdle() const { | |
324 return completed_handshake_ && transport_socket_->IsConnectedAndIdle(); | |
325 } | |
326 | |
327 int SSLServerSocketOpenSSL::GetPeerAddress(IPEndPoint* address) const { | |
328 if (!IsConnected()) | |
329 return ERR_SOCKET_NOT_CONNECTED; | |
330 return transport_socket_->GetPeerAddress(address); | |
331 } | |
332 | |
333 int SSLServerSocketOpenSSL::GetLocalAddress(IPEndPoint* address) const { | |
334 if (!IsConnected()) | |
335 return ERR_SOCKET_NOT_CONNECTED; | |
336 return transport_socket_->GetLocalAddress(address); | |
337 } | |
338 | |
339 const BoundNetLog& SSLServerSocketOpenSSL::NetLog() const { | |
340 return net_log_; | |
341 } | |
342 | |
343 void SSLServerSocketOpenSSL::SetSubresourceSpeculation() { | |
344 transport_socket_->SetSubresourceSpeculation(); | |
345 } | |
346 | |
347 void SSLServerSocketOpenSSL::SetOmniboxSpeculation() { | |
348 transport_socket_->SetOmniboxSpeculation(); | |
349 } | |
350 | |
351 bool SSLServerSocketOpenSSL::WasEverUsed() const { | |
352 return transport_socket_->WasEverUsed(); | |
353 } | |
354 | |
355 bool SSLServerSocketOpenSSL::WasNpnNegotiated() const { | |
356 NOTIMPLEMENTED(); | |
357 return false; | |
358 } | |
359 | |
360 NextProto SSLServerSocketOpenSSL::GetNegotiatedProtocol() const { | |
361 // NPN is not supported by this class. | |
362 return kProtoUnknown; | |
363 } | |
364 | |
365 bool SSLServerSocketOpenSSL::GetSSLInfo(SSLInfo* ssl_info) { | |
366 ssl_info->Reset(); | |
367 if (!completed_handshake_) | |
368 return false; | |
369 | |
370 ssl_info->cert = client_cert_; | |
371 | |
372 const SSL_CIPHER* cipher = SSL_get_current_cipher(ssl_); | |
373 CHECK(cipher); | |
374 ssl_info->security_bits = SSL_CIPHER_get_bits(cipher, NULL); | |
375 | |
376 SSLConnectionStatusSetCipherSuite( | |
377 static_cast<uint16_t>(SSL_CIPHER_get_id(cipher)), | |
378 &ssl_info->connection_status); | |
379 SSLConnectionStatusSetVersion(GetNetSSLVersion(ssl_), | |
380 &ssl_info->connection_status); | |
381 | |
382 if (!SSL_get_secure_renegotiation_support(ssl_)) | |
383 ssl_info->connection_status |= SSL_CONNECTION_NO_RENEGOTIATION_EXTENSION; | |
384 | |
385 ssl_info->handshake_type = SSL_session_reused(ssl_) | |
386 ? SSLInfo::HANDSHAKE_RESUME | |
387 : SSLInfo::HANDSHAKE_FULL; | |
388 | |
389 return true; | |
390 } | |
391 | |
392 void SSLServerSocketOpenSSL::GetConnectionAttempts( | |
393 ConnectionAttempts* out) const { | |
394 out->clear(); | |
395 } | |
396 | |
397 int64_t SSLServerSocketOpenSSL::GetTotalReceivedBytes() const { | |
398 return transport_socket_->GetTotalReceivedBytes(); | |
399 } | |
400 | |
401 void SSLServerSocketOpenSSL::OnSendComplete(int result) { | |
402 if (next_handshake_state_ == STATE_HANDSHAKE) { | |
403 // In handshake phase. | |
404 OnHandshakeIOComplete(result); | |
405 return; | |
406 } | |
407 | |
408 // TODO(byungchul): This state machine is not correct. Copy the state machine | |
409 // of SSLClientSocketOpenSSL::OnSendComplete() which handles it better. | |
410 if (!completed_handshake_) | |
411 return; | |
412 | |
413 if (user_write_buf_) { | |
414 int rv = DoWriteLoop(result); | |
415 if (rv != ERR_IO_PENDING) | |
416 DoWriteCallback(rv); | |
417 } else { | |
418 // Ensure that any queued ciphertext is flushed. | |
419 DoTransportIO(); | |
420 } | |
421 } | |
422 | |
423 void SSLServerSocketOpenSSL::OnRecvComplete(int result) { | |
424 if (next_handshake_state_ == STATE_HANDSHAKE) { | |
425 // In handshake phase. | |
426 OnHandshakeIOComplete(result); | |
427 return; | |
428 } | |
429 | |
430 // Network layer received some data, check if client requested to read | |
431 // decrypted data. | |
432 if (!user_read_buf_ || !completed_handshake_) | |
433 return; | |
434 | |
435 int rv = DoReadLoop(result); | |
436 if (rv != ERR_IO_PENDING) | |
437 DoReadCallback(rv); | |
438 } | |
439 | |
440 void SSLServerSocketOpenSSL::OnHandshakeIOComplete(int result) { | |
441 int rv = DoHandshakeLoop(result); | |
442 if (rv == ERR_IO_PENDING) | |
443 return; | |
444 | |
445 net_log_.EndEventWithNetErrorCode(NetLog::TYPE_SSL_SERVER_HANDSHAKE, rv); | |
446 if (!user_handshake_callback_.is_null()) | |
447 DoHandshakeCallback(rv); | |
448 } | |
449 | |
450 // Return 0 for EOF, | |
451 // > 0 for bytes transferred immediately, | |
452 // < 0 for error (or the non-error ERR_IO_PENDING). | |
453 int SSLServerSocketOpenSSL::BufferSend() { | |
454 if (transport_send_busy_) | |
455 return ERR_IO_PENDING; | |
456 | |
457 if (!send_buffer_) { | |
458 // Get a fresh send buffer out of the send BIO. | |
459 size_t max_read = BIO_pending(transport_bio_); | |
460 if (!max_read) | |
461 return 0; // Nothing pending in the OpenSSL write BIO. | |
462 send_buffer_ = new DrainableIOBuffer(new IOBuffer(max_read), max_read); | |
463 int read_bytes = BIO_read(transport_bio_, send_buffer_->data(), max_read); | |
464 DCHECK_GT(read_bytes, 0); | |
465 CHECK_EQ(static_cast<int>(max_read), read_bytes); | |
466 } | |
467 | |
468 int rv = transport_socket_->Write( | |
469 send_buffer_.get(), send_buffer_->BytesRemaining(), | |
470 base::Bind(&SSLServerSocketOpenSSL::BufferSendComplete, | |
471 base::Unretained(this))); | |
472 if (rv == ERR_IO_PENDING) { | |
473 transport_send_busy_ = true; | |
474 } else { | |
475 TransportWriteComplete(rv); | |
476 } | |
477 return rv; | |
478 } | |
479 | |
480 void SSLServerSocketOpenSSL::BufferSendComplete(int result) { | |
481 transport_send_busy_ = false; | |
482 TransportWriteComplete(result); | |
483 OnSendComplete(result); | |
484 } | |
485 | |
486 void SSLServerSocketOpenSSL::TransportWriteComplete(int result) { | |
487 DCHECK(ERR_IO_PENDING != result); | |
488 if (result < 0) { | |
489 // Got a socket write error; close the BIO to indicate this upward. | |
490 // | |
491 // TODO(davidben): The value of |result| gets lost. Feed the error back into | |
492 // the BIO so it gets (re-)detected in OnSendComplete. Perhaps with | |
493 // BIO_set_callback. | |
494 DVLOG(1) << "TransportWriteComplete error " << result; | |
495 (void)BIO_shutdown_wr(SSL_get_wbio(ssl_)); | |
496 | |
497 // Match the fix for http://crbug.com/249848 in NSS by erroring future reads | |
498 // from the socket after a write error. | |
499 // | |
500 // TODO(davidben): Avoid having read and write ends interact this way. | |
501 transport_write_error_ = result; | |
502 (void)BIO_shutdown_wr(transport_bio_); | |
503 send_buffer_ = NULL; | |
504 } else { | |
505 DCHECK(send_buffer_); | |
506 send_buffer_->DidConsume(result); | |
507 DCHECK_GE(send_buffer_->BytesRemaining(), 0); | |
508 if (send_buffer_->BytesRemaining() <= 0) | |
509 send_buffer_ = NULL; | |
510 } | |
511 } | |
512 | |
513 int SSLServerSocketOpenSSL::BufferRecv() { | |
514 if (transport_recv_busy_) | |
515 return ERR_IO_PENDING; | |
516 | |
517 // Determine how much was requested from |transport_bio_| that was not | |
518 // actually available. | |
519 size_t requested = BIO_ctrl_get_read_request(transport_bio_); | |
520 if (requested == 0) { | |
521 // This is not a perfect match of error codes, as no operation is | |
522 // actually pending. However, returning 0 would be interpreted as | |
523 // a possible sign of EOF, which is also an inappropriate match. | |
524 return ERR_IO_PENDING; | |
525 } | |
526 | |
527 // Known Issue: While only reading |requested| data is the more correct | |
528 // implementation, it has the downside of resulting in frequent reads: | |
529 // One read for the SSL record header (~5 bytes) and one read for the SSL | |
530 // record body. Rather than issuing these reads to the underlying socket | |
531 // (and constantly allocating new IOBuffers), a single Read() request to | |
532 // fill |transport_bio_| is issued. As long as an SSL client socket cannot | |
533 // be gracefully shutdown (via SSL close alerts) and re-used for non-SSL | |
534 // traffic, this over-subscribed Read()ing will not cause issues. | |
535 size_t max_write = BIO_ctrl_get_write_guarantee(transport_bio_); | |
536 if (!max_write) | |
537 return ERR_IO_PENDING; | |
538 | |
539 recv_buffer_ = new IOBuffer(max_write); | |
540 int rv = transport_socket_->Read( | |
541 recv_buffer_.get(), max_write, | |
542 base::Bind(&SSLServerSocketOpenSSL::BufferRecvComplete, | |
543 base::Unretained(this))); | |
544 if (rv == ERR_IO_PENDING) { | |
545 transport_recv_busy_ = true; | |
546 } else { | |
547 rv = TransportReadComplete(rv); | |
548 } | |
549 return rv; | |
550 } | |
551 | |
552 void SSLServerSocketOpenSSL::BufferRecvComplete(int result) { | |
553 result = TransportReadComplete(result); | |
554 OnRecvComplete(result); | |
555 } | |
556 | |
557 int SSLServerSocketOpenSSL::TransportReadComplete(int result) { | |
558 DCHECK(ERR_IO_PENDING != result); | |
559 if (result <= 0) { | |
560 DVLOG(1) << "TransportReadComplete result " << result; | |
561 // Received 0 (end of file) or an error. Either way, bubble it up to the | |
562 // SSL layer via the BIO. TODO(joth): consider stashing the error code, to | |
563 // relay up to the SSL socket client (i.e. via DoReadCallback). | |
564 if (result == 0) | |
565 transport_recv_eof_ = true; | |
566 (void)BIO_shutdown_wr(transport_bio_); | |
567 } else if (transport_write_error_ < 0) { | |
568 // Mirror transport write errors as read failures; transport_bio_ has been | |
569 // shut down by TransportWriteComplete, so the BIO_write will fail, failing | |
570 // the CHECK. http://crbug.com/335557. | |
571 result = transport_write_error_; | |
572 } else { | |
573 DCHECK(recv_buffer_); | |
574 int ret = BIO_write(transport_bio_, recv_buffer_->data(), result); | |
575 // A write into a memory BIO should always succeed. | |
576 DCHECK_EQ(result, ret); | |
577 } | |
578 recv_buffer_ = NULL; | |
579 transport_recv_busy_ = false; | |
580 return result; | |
581 } | |
582 | |
583 // Do as much network I/O as possible between the buffer and the | |
584 // transport socket. Return true if some I/O performed, false | |
585 // otherwise (error or ERR_IO_PENDING). | |
586 bool SSLServerSocketOpenSSL::DoTransportIO() { | |
587 bool network_moved = false; | |
588 int rv; | |
589 // Read and write as much data as possible. The loop is necessary because | |
590 // Write() may return synchronously. | |
591 do { | |
592 rv = BufferSend(); | |
593 if (rv != ERR_IO_PENDING && rv != 0) | |
594 network_moved = true; | |
595 } while (rv > 0); | |
596 if (!transport_recv_eof_ && BufferRecv() != ERR_IO_PENDING) | |
597 network_moved = true; | |
598 return network_moved; | |
599 } | |
600 | |
601 int SSLServerSocketOpenSSL::DoPayloadRead() { | |
602 DCHECK(user_read_buf_); | |
603 DCHECK_GT(user_read_buf_len_, 0); | |
604 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); | |
605 int rv = SSL_read(ssl_, user_read_buf_->data(), user_read_buf_len_); | |
606 if (rv >= 0) | |
607 return rv; | |
608 int ssl_error = SSL_get_error(ssl_, rv); | |
609 OpenSSLErrorInfo error_info; | |
610 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, | |
611 &error_info); | |
612 if (net_error != ERR_IO_PENDING) { | |
613 net_log_.AddEvent( | |
614 NetLog::TYPE_SSL_READ_ERROR, | |
615 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info)); | |
616 } | |
617 return net_error; | |
618 } | |
619 | |
620 int SSLServerSocketOpenSSL::DoPayloadWrite() { | |
621 DCHECK(user_write_buf_); | |
622 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); | |
623 int rv = SSL_write(ssl_, user_write_buf_->data(), user_write_buf_len_); | |
624 if (rv >= 0) | |
625 return rv; | |
626 int ssl_error = SSL_get_error(ssl_, rv); | |
627 OpenSSLErrorInfo error_info; | |
628 int net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, | |
629 &error_info); | |
630 if (net_error != ERR_IO_PENDING) { | |
631 net_log_.AddEvent( | |
632 NetLog::TYPE_SSL_WRITE_ERROR, | |
633 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info)); | |
634 } | |
635 return net_error; | |
636 } | |
637 | |
638 int SSLServerSocketOpenSSL::DoHandshakeLoop(int last_io_result) { | |
639 int rv = last_io_result; | |
640 do { | |
641 // Default to STATE_NONE for next state. | |
642 // (This is a quirk carried over from the windows | |
643 // implementation. It makes reading the logs a bit harder.) | |
644 // State handlers can and often do call GotoState just | |
645 // to stay in the current state. | |
646 State state = next_handshake_state_; | |
647 GotoState(STATE_NONE); | |
648 switch (state) { | |
649 case STATE_HANDSHAKE: | |
650 rv = DoHandshake(); | |
651 break; | |
652 case STATE_NONE: | |
653 default: | |
654 rv = ERR_UNEXPECTED; | |
655 LOG(DFATAL) << "unexpected state " << state; | |
656 break; | |
657 } | |
658 | |
659 // Do the actual network I/O | |
660 bool network_moved = DoTransportIO(); | |
661 if (network_moved && next_handshake_state_ == STATE_HANDSHAKE) { | |
662 // In general we exit the loop if rv is ERR_IO_PENDING. In this | |
663 // special case we keep looping even if rv is ERR_IO_PENDING because | |
664 // the transport IO may allow DoHandshake to make progress. | |
665 rv = OK; // This causes us to stay in the loop. | |
666 } | |
667 } while (rv != ERR_IO_PENDING && next_handshake_state_ != STATE_NONE); | |
668 return rv; | |
669 } | |
670 | |
671 int SSLServerSocketOpenSSL::DoReadLoop(int result) { | |
672 DCHECK(completed_handshake_); | |
673 DCHECK(next_handshake_state_ == STATE_NONE); | |
674 | |
675 if (result < 0) | |
676 return result; | |
677 | |
678 bool network_moved; | |
679 int rv; | |
680 do { | |
681 rv = DoPayloadRead(); | |
682 network_moved = DoTransportIO(); | |
683 } while (rv == ERR_IO_PENDING && network_moved); | |
684 return rv; | |
685 } | |
686 | |
687 int SSLServerSocketOpenSSL::DoWriteLoop(int result) { | |
688 DCHECK(completed_handshake_); | |
689 DCHECK_EQ(next_handshake_state_, STATE_NONE); | |
690 | |
691 if (result < 0) | |
692 return result; | |
693 | |
694 bool network_moved; | |
695 int rv; | |
696 do { | |
697 rv = DoPayloadWrite(); | |
698 network_moved = DoTransportIO(); | |
699 } while (rv == ERR_IO_PENDING && network_moved); | |
700 return rv; | |
701 } | |
702 | |
703 int SSLServerSocketOpenSSL::DoHandshake() { | |
704 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); | |
705 int net_error = OK; | |
706 int rv = SSL_do_handshake(ssl_); | |
707 | |
708 if (rv == 1) { | |
709 completed_handshake_ = true; | |
710 // The results of SSL_get_peer_certificate() must be explicitly freed. | |
711 ScopedX509 cert(SSL_get_peer_certificate(ssl_)); | |
712 if (cert) { | |
713 // The caller does not take ownership of SSL_get_peer_cert_chain's | |
714 // results. | |
715 STACK_OF(X509)* chain = SSL_get_peer_cert_chain(ssl_); | |
716 client_cert_ = CreateX509Certificate(cert.get(), chain); | |
717 if (!client_cert_.get()) | |
718 return ERR_SSL_CLIENT_AUTH_CERT_BAD_FORMAT; | |
719 } | |
720 } else { | |
721 int ssl_error = SSL_get_error(ssl_, rv); | |
722 OpenSSLErrorInfo error_info; | |
723 net_error = MapOpenSSLErrorWithDetails(ssl_error, err_tracer, &error_info); | |
724 | |
725 // This hack is necessary because the mapping of SSL error codes to | |
726 // net_errors assumes (correctly for client sockets, but erroneously for | |
727 // server sockets) that peer cert verification failure can only occur if | |
728 // the cert changed during a renego. crbug.com/570351 | |
729 if (net_error == ERR_SSL_SERVER_CERT_CHANGED) | |
730 net_error = ERR_BAD_SSL_CLIENT_AUTH_CERT; | |
731 | |
732 // If not done, stay in this state | |
733 if (net_error == ERR_IO_PENDING) { | |
734 GotoState(STATE_HANDSHAKE); | |
735 } else { | |
736 LOG(ERROR) << "handshake failed; returned " << rv | |
737 << ", SSL error code " << ssl_error | |
738 << ", net_error " << net_error; | |
739 net_log_.AddEvent( | |
740 NetLog::TYPE_SSL_HANDSHAKE_ERROR, | |
741 CreateNetLogOpenSSLErrorCallback(net_error, ssl_error, error_info)); | |
742 } | |
743 } | |
744 return net_error; | |
745 } | |
746 | |
747 void SSLServerSocketOpenSSL::DoHandshakeCallback(int rv) { | |
748 DCHECK_NE(rv, ERR_IO_PENDING); | |
749 base::ResetAndReturn(&user_handshake_callback_).Run(rv > OK ? OK : rv); | |
750 } | |
751 | |
752 void SSLServerSocketOpenSSL::DoReadCallback(int rv) { | |
753 DCHECK(rv != ERR_IO_PENDING); | |
754 DCHECK(!user_read_callback_.is_null()); | |
755 | |
756 user_read_buf_ = NULL; | |
757 user_read_buf_len_ = 0; | |
758 base::ResetAndReturn(&user_read_callback_).Run(rv); | |
759 } | |
760 | |
761 void SSLServerSocketOpenSSL::DoWriteCallback(int rv) { | |
762 DCHECK(rv != ERR_IO_PENDING); | |
763 DCHECK(!user_write_callback_.is_null()); | |
764 | |
765 user_write_buf_ = NULL; | |
766 user_write_buf_len_ = 0; | |
767 base::ResetAndReturn(&user_write_callback_).Run(rv); | |
768 } | |
769 | |
770 int SSLServerSocketOpenSSL::Init() { | |
771 DCHECK(!transport_bio_); | |
772 | |
773 crypto::OpenSSLErrStackTracer err_tracer(FROM_HERE); | |
774 | |
775 if (!ssl_) | |
776 return ERR_UNEXPECTED; | |
777 | |
778 BIO* ssl_bio = NULL; | |
779 // 0 => use default buffer sizes. | |
780 if (!BIO_new_bio_pair(&ssl_bio, 0, &transport_bio_, 0)) | |
781 return ERR_UNEXPECTED; | |
782 DCHECK(ssl_bio); | |
783 DCHECK(transport_bio_); | |
784 | |
785 SSL_set_bio(ssl_, ssl_bio, ssl_bio); | |
786 | |
787 return OK; | |
788 } | |
789 | |
790 // static | |
791 int SSLServerSocketOpenSSL::CertVerifyCallback(X509_STORE_CTX* store_ctx, | |
792 void* arg) { | |
793 ClientCertVerifier* verifier = reinterpret_cast<ClientCertVerifier*>(arg); | |
794 // If a verifier was not supplied, all certificates are accepted. | |
795 if (!verifier) | |
796 return 1; | |
797 STACK_OF(X509)* chain = store_ctx->untrusted; | |
798 scoped_refptr<X509Certificate> client_cert( | |
799 CreateX509Certificate(nullptr, chain)); | |
800 if (!client_cert.get()) { | |
801 X509_STORE_CTX_set_error(store_ctx, X509_V_ERR_CERT_REJECTED); | |
802 return 0; | |
803 } | |
804 // Asynchronous completion of Verify is currently not supported. | |
805 // http://crbug.com/347402 | |
806 // The API for Verify supports the parts needed for async completion | |
807 // but is currently expected to complete synchronously. | |
808 std::unique_ptr<ClientCertVerifier::Request> ignore_async; | |
809 int res = | |
810 verifier->Verify(client_cert.get(), CompletionCallback(), &ignore_async); | |
811 DCHECK_NE(res, ERR_IO_PENDING); | |
812 | |
813 if (res != OK) { | |
814 X509_STORE_CTX_set_error(store_ctx, X509_V_ERR_CERT_REJECTED); | |
815 return 0; | |
816 } | |
817 return 1; | |
818 } | |
819 | |
820 } // namespace | |
821 | |
822 std::unique_ptr<SSLServerContext> CreateSSLServerContext( | |
823 X509Certificate* certificate, | |
824 const crypto::RSAPrivateKey& key, | |
825 const SSLServerConfig& ssl_server_config) { | |
826 return std::unique_ptr<SSLServerContext>( | |
827 new SSLServerContextOpenSSL(certificate, key, ssl_server_config)); | |
828 } | |
829 | |
830 SSLServerContextOpenSSL::SSLServerContextOpenSSL( | |
831 X509Certificate* certificate, | |
832 const crypto::RSAPrivateKey& key, | |
833 const SSLServerConfig& ssl_server_config) | |
834 : ssl_server_config_(ssl_server_config), | |
835 cert_(certificate), | |
836 key_(key.Copy()) { | |
837 CHECK(key_); | |
838 crypto::EnsureOpenSSLInit(); | |
839 ssl_ctx_.reset(SSL_CTX_new(TLS_method())); | |
840 SSL_CTX_set_session_cache_mode(ssl_ctx_.get(), SSL_SESS_CACHE_SERVER); | |
841 uint8_t session_ctx_id = 0; | |
842 SSL_CTX_set_session_id_context(ssl_ctx_.get(), &session_ctx_id, | |
843 sizeof(session_ctx_id)); | |
844 | |
845 int verify_mode = 0; | |
846 switch (ssl_server_config_.client_cert_type) { | |
847 case SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT: | |
848 verify_mode |= SSL_VERIFY_FAIL_IF_NO_PEER_CERT; | |
849 // Fall-through | |
850 case SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT: | |
851 verify_mode |= SSL_VERIFY_PEER; | |
852 SSL_CTX_set_verify(ssl_ctx_.get(), verify_mode, nullptr); | |
853 SSL_CTX_set_cert_verify_callback( | |
854 ssl_ctx_.get(), SSLServerSocketOpenSSL::CertVerifyCallback, | |
855 ssl_server_config_.client_cert_verifier); | |
856 break; | |
857 case SSLServerConfig::ClientCertType::NO_CLIENT_CERT: | |
858 break; | |
859 } | |
860 | |
861 // Set certificate and private key. | |
862 DCHECK(cert_->os_cert_handle()); | |
863 #if defined(USE_OPENSSL_CERTS) | |
864 CHECK(SSL_CTX_use_certificate(ssl_ctx_.get(), cert_->os_cert_handle())); | |
865 #else | |
866 // Convert OSCertHandle to X509 structure. | |
867 std::string der_string; | |
868 CHECK(X509Certificate::GetDEREncoded(cert_->os_cert_handle(), &der_string)); | |
869 | |
870 const unsigned char* der_string_array = | |
871 reinterpret_cast<const unsigned char*>(der_string.data()); | |
872 | |
873 ScopedX509 x509(d2i_X509(NULL, &der_string_array, der_string.length())); | |
874 CHECK(x509); | |
875 | |
876 // On success, SSL_CTX_use_certificate acquires a reference to |x509|. | |
877 CHECK(SSL_CTX_use_certificate(ssl_ctx_.get(), x509.get())); | |
878 #endif // USE_OPENSSL_CERTS | |
879 | |
880 DCHECK(key_->key()); | |
881 CHECK(SSL_CTX_use_PrivateKey(ssl_ctx_.get(), key_->key())); | |
882 | |
883 DCHECK_LT(SSL3_VERSION, ssl_server_config_.version_min); | |
884 DCHECK_LT(SSL3_VERSION, ssl_server_config_.version_max); | |
885 SSL_CTX_set_min_version(ssl_ctx_.get(), ssl_server_config_.version_min); | |
886 SSL_CTX_set_max_version(ssl_ctx_.get(), ssl_server_config_.version_max); | |
887 | |
888 // OpenSSL defaults some options to on, others to off. To avoid ambiguity, | |
889 // set everything we care about to an absolute value. | |
890 SslSetClearMask options; | |
891 options.ConfigureFlag(SSL_OP_NO_COMPRESSION, true); | |
892 | |
893 SSL_CTX_set_options(ssl_ctx_.get(), options.set_mask); | |
894 SSL_CTX_clear_options(ssl_ctx_.get(), options.clear_mask); | |
895 | |
896 // Same as above, this time for the SSL mode. | |
897 SslSetClearMask mode; | |
898 | |
899 mode.ConfigureFlag(SSL_MODE_RELEASE_BUFFERS, true); | |
900 | |
901 SSL_CTX_set_mode(ssl_ctx_.get(), mode.set_mask); | |
902 SSL_CTX_clear_mode(ssl_ctx_.get(), mode.clear_mask); | |
903 | |
904 // See SSLServerConfig::disabled_cipher_suites for description of the suites | |
905 // disabled by default. Note that !SHA256 and !SHA384 only remove HMAC-SHA256 | |
906 // and HMAC-SHA384 cipher suites, not GCM cipher suites with SHA256 or SHA384 | |
907 // as the handshake hash. | |
908 std::string command("DEFAULT:!SHA256:!SHA384:!AESGCM+AES256:!aPSK"); | |
909 | |
910 if (ssl_server_config_.require_ecdhe) | |
911 command.append(":!kRSA:!kDHE"); | |
912 | |
913 // Remove any disabled ciphers. | |
914 for (uint16_t id : ssl_server_config_.disabled_cipher_suites) { | |
915 const SSL_CIPHER* cipher = SSL_get_cipher_by_value(id); | |
916 if (cipher) { | |
917 command.append(":!"); | |
918 command.append(SSL_CIPHER_get_name(cipher)); | |
919 } | |
920 } | |
921 | |
922 int rv = SSL_CTX_set_cipher_list(ssl_ctx_.get(), command.c_str()); | |
923 // If this fails (rv = 0) it means there are no ciphers enabled on this SSL. | |
924 // This will almost certainly result in the socket failing to complete the | |
925 // handshake at which point the appropriate error is bubbled up to the client. | |
926 LOG_IF(WARNING, rv != 1) << "SSL_set_cipher_list('" << command | |
927 << "') returned " << rv; | |
928 | |
929 if (ssl_server_config_.client_cert_type != | |
930 SSLServerConfig::ClientCertType::NO_CLIENT_CERT && | |
931 !ssl_server_config_.cert_authorities_.empty()) { | |
932 ScopedX509NameStack stack(sk_X509_NAME_new_null()); | |
933 for (const auto& authority : ssl_server_config_.cert_authorities_) { | |
934 const uint8_t* name = reinterpret_cast<const uint8_t*>(authority.c_str()); | |
935 const uint8_t* name_start = name; | |
936 ScopedX509_NAME subj(d2i_X509_NAME(nullptr, &name, authority.length())); | |
937 CHECK(subj && name == name_start + authority.length()); | |
938 sk_X509_NAME_push(stack.get(), subj.release()); | |
939 } | |
940 SSL_CTX_set_client_CA_list(ssl_ctx_.get(), stack.release()); | |
941 } | |
942 } | |
943 | |
944 SSLServerContextOpenSSL::~SSLServerContextOpenSSL() {} | |
945 | |
946 std::unique_ptr<SSLServerSocket> SSLServerContextOpenSSL::CreateSSLServerSocket( | |
947 std::unique_ptr<StreamSocket> socket) { | |
948 SSL* ssl = SSL_new(ssl_ctx_.get()); | |
949 return std::unique_ptr<SSLServerSocket>( | |
950 new SSLServerSocketOpenSSL(std::move(socket), ssl)); | |
951 } | |
952 | |
953 void EnableSSLServerSockets() { | |
954 // No-op because CreateSSLServerSocket() calls crypto::EnsureOpenSSLInit(). | |
955 } | |
956 | |
957 } // namespace net | |
OLD | NEW |